问:
Syntax error in formula
Could you please help me to identify and fix the error I am facing in the following program. It's saying syntax error and I tried all the possible ways to enter the formula but I couldn't.</p>

```<code>Dim T As Integer
T = 12
Range("AJ3").Value = "Target ETY"
Range("AJ4").Formula = "=SUM(((Range("A4").Value) * aa), (Range("C4").Value * b), (Range("E4").Value * c), (Range("G4").Value * d), (Range("I4").Value * e), (Range("K4").Value * f), (Range("M4").Value * g), (Range("O4").Value * h), (Range("Q4").Value * i), (Range("S4").Value * j), (Range("U4").Value * k), (Range("W4").Value * l), (Range("Y4").Value * m), (Range("AA4").Value * n), (Range("AC4").Value * o), (Range("AE4").Value * p))"
Range("AJ4").Select
Range("AK3").Value = "Actual ETY"
Range("AK4").FormulaR1C1 = Sum((Range("B4").Value * aa), (Range("D4").Value * b), (Range("F4").Value * c), (Range("H4").Value * d), (Range("J4").Value * e), (Range("L4").Value * f), (Range("N4").Value * g), (Range("P4").Value * h), (Range("R4").Value * i), (Range("T4").Value * j), (Range("V4").Value * k), (Range("X4").Value * l), (Range("Z4").Value * m), (Range("AB4").Value * n), (Range("AD4").Value * o), (Range("AF4").Value * p))
Range("AK4").Select
Range("AL4").Value = Range("AK4").Value / T
Range("AL4").Select
Selection.NumberFormat = "0.0%"
Range("AL3").Value = "Total ETY"
MsgBox "Total ETY for Day" & vbNewLine & Range("AL4").Value
If Range("AL4").Value >= 0 Then
UserForm2.Show
End If
End Sub
</code>```

答:
Try the changes bellow

```<code>    Dim T As Integer, frm As String
    T = 12

    Range("AJ3").Value = "Target ETY"

    frm = "=Sum(A4 * " & aa & ", C4 * " & b & ", E4 * " & c & ", G4 * " & d & ", "
    frm = frm & "I4 * " & e & ", K4 * " & f & ", M4 * " & g & ", O4 * " & h & ", "
    frm = frm & "Q4 * " & i & ", S4 * " & j & ", U4 * " & k & ", W4 * " & l & ", "
    frm = frm & "Y4 * " & m & ", AA4 * " & n & ", AC4 * " & o & ", AE4 * " & p & ")"
    Range("AJ4").Formula = frm

    Range("AK3").Value = "Actual ETY"

    frm = "=Sum(B4 * " & aa & ", D4 * " & b & ", F4 * " & c & ", H4 * " & d & ", "
    frm = frm & "J4 * " & e & ", L4 * " & f & ", N4 * " & g & ", P4 * " & h & ", "
    frm = frm & "R4 * " & i & ", T4 * " & j & ", V4 * " & k & ", X4 * " & l & ", "
    frm = frm & "Z4 * " & m & ", AB4 * " & n & ", AD4 * " & o & ", AF4 * " & p & ")"
    Range("AK4").Formula = frm

    Range("AL4").Value = Range("AK4").Value / T
    Range("AJ4, AK4, AL4").NumberFormat = "0.0%"
    Range("AL3").Value = "Total ETY"

    MsgBox "Total ETY for Day" & vbNewLine & Range("AL4").Value

    If Range("AL4").Value >= 0 Then UserForm2.Show
End Sub
</code>```

(I'm not sure what aa, b, c, ... are because your code is incomplete, but I think they're variables that you want to use in your formula?)

Title: Syntax error in formula

Body:
Could you please help me to identify and fix the error I am facing in the following program. It's saying syntax error and I tried all the possible ways to enter the formula but I couldn't.

Dim T As Integer
T = 12
Range("AJ3").Value = "Target ETY"
Range("AJ4").Formula = "=SUM(((Range("A4").Value) * aa), (Range("C4").Value * b), (Range("E4").Value * c), (Range("G4").Value * d), (Range("I4").Value * e), (Range("K4").Value * f), (Range("M4").Value * g), (Range("O4").Value * h), (Range("Q4").Value * i), (Range("S4").Value * j), (Range("U4").Value * k), (Range("W4").Value * l), (Range("Y4").Value * m), (Range("AA4").Value * n), (Range("AC4").Value * o), (Range("AE4").Value * p))"
Range("AJ4").Select
Range("AK3").Value = "Actual ETY"
Range("AK4").FormulaR1C1 = Sum((Range("B4").Value * aa), (Range("D4").Value * b), (Range("F4").Value * c), (Range("H4").Value * d), (Range("J4").Value * e), (Range("L4").Value * f), (Range("N4").Value * g), (Range("P4").Value * h), (Range("R4").Value * i), (Range("T4").Value * j), (Range("V4").Value * k), (Range("X4").Value * l), (Range("Z4").Value * m), (Range("AB4").Value * n), (Range("AD4").Value * o), (Range("AF4").Value * p))
Range("AK4").Select
Range("AL4").Value = Range("AK4").Value / T
Range("AL4").Select
Selection.NumberFormat = "0.0%"
Range("AL3").Value = "Total ETY"
MsgBox "Total ETY for Day" & vbNewLine & Range("AL4").Value
If Range("AL4").Value >= 0 Then
UserForm2.Show
End If
End Sub

Body:
Try the changes bellow

    Dim T As Integer, frm As String
    T = 12

    Range("AJ3").Value = "Target ETY"

    frm = "=Sum(A4 * " & aa & ", C4 * " & b & ", E4 * " & c & ", G4 * " & d & ", "
    frm = frm & "I4 * " & e & ", K4 * " & f & ", M4 * " & g & ", O4 * " & h & ", "
    frm = frm & "Q4 * " & i & ", S4 * " & j & ", U4 * " & k & ", W4 * " & l & ", "
    frm = frm & "Y4 * " & m & ", AA4 * " & n & ", AC4 * " & o & ", AE4 * " & p & ")"
    Range("AJ4").Formula = frm

    Range("AK3").Value = "Actual ETY"

    frm = "=Sum(B4 * " & aa & ", D4 * " & b & ", F4 * " & c & ", H4 * " & d & ", "
    frm = frm & "J4 * " & e & ", L4 * " & f & ", N4 * " & g & ", P4 * " & h & ", "
    frm = frm & "R4 * " & i & ", T4 * " & j & ", V4 * " & k & ", X4 * " & l & ", "
    frm = frm & "Z4 * " & m & ", AB4 * " & n & ", AD4 * " & o & ", AF4 * " & p & ")"
    Range("AK4").Formula = frm

    Range("AL4").Value = Range("AK4").Value / T
    Range("AJ4, AK4, AL4").NumberFormat = "0.0%"
    Range("AL3").Value = "Total ETY"

    MsgBox "Total ETY for Day" & vbNewLine & Range("AL4").Value

    If Range("AL4").Value >= 0 Then UserForm2.Show
End Sub

(I'm not sure what aa, b, c, ... are because your code is incomplete, but I think they're variables that you want to use in your formula?)


来源: stackexchange

问:
How to ignore values when using numpy.sum and numpy.mean in matrices
Is there a way to avoid using specific values when applying sum and mean in numpy?

I'd like to avoid, for instance, the -999 value when calculating the result.

```<code>In [14]: c = np.matrix([[4., 2.],[4., 1.]])

In [15]: d = np.matrix([[3., 2.],[4., -999.]])

In [16]: np.sum([c, d], axis=0)
Out[16]:
array([[   7.,    4.],
       [   8., -998.]])

In [17]: np.mean([c, d], axis=0)
Out[17]:
array([[   3.5,    2. ],
       [   4. , -499. ]])
</code>```

答:
Use a masked array:</p>

```<code>>>> c = np.ma.array([[4., 2.], [4., 1.]])
>>> d = np.ma.masked_values([[3., 2.], [4., -999]], -999)

>>> np.ma.array([c, d]).sum(axis=0)
masked_array(data =
 [[7.0 4.0]
 [8.0 1.0]],
             mask =
 [[False False]
 [False False]],
       fill_value = 1e+20)

>>> np.ma.array([c, d]).mean(axis=0)
masked_array(data =
 [[3.5 2.0]
 [4.0 1.0]],
             mask =
 [[False False]
 [False False]],
       fill_value = 1e+20)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to avoid using specific values when applying sum and mean in numpy?

I'd like to avoid, for instance, the -999 value when calculating the result.

In [14]: c = np.matrix([[4., 2.],[4., 1.]])

In [15]: d = np.matrix([[3., 2.],[4., -999.]])

In [16]: np.sum([c, d], axis=0)
Out[16]:
array([[   7.,    4.],
       [   8., -998.]])

In [17]: np.mean([c, d], axis=0)
Out[17]:
array([[   3.5,    2. ],
       [   4. , -499. ]])

Body:
Use a masked array:

>>> c = np.ma.array([[4., 2.], [4., 1.]])
>>> d = np.ma.masked_values([[3., 2.], [4., -999]], -999)

>>> np.ma.array([c, d]).sum(axis=0)
masked_array(data =
 [[7.0 4.0]
 [8.0 1.0]],
             mask =
 [[False False]
 [False False]],
       fill_value = 1e+20)

>>> np.ma.array([c, d]).mean(axis=0)
masked_array(data =
 [[3.5 2.0]
 [4.0 1.0]],
             mask =
 [[False False]
 [False False]],
       fill_value = 1e+20)


问:
Open, type safe and easy to extend component structure in Haskell?
I im trying to implement a small and simple open type component structure in Haskell.

The goal is to easily allow function and type extension by creating new components in other modules while preserving type safety at compile time.

I managed to implement a recursive search function by component type (find, in CompFinder), and it works well in the simple tests i tried. However i need to write trivial instances for CompFinder for non-composite components and multiple instances with the only difference being the component type for the CompFinder CompMix instance.

I am aware of Derive for automatic code generation for instance deriving but I would like a simpler solution if there is one, the compiler doing the code generation in the worst case, if possible.

So the questions are: How can I modify this system to simplify the writing of new Components?

or: How can I tell GHC to automatically generate CompFinder instances since only the type change in the different definitions?

Perhaps by doing something like this:

```<code>instance (Component a, CompFinder a T, Component b, CompFinder b T) => CompFinder (CompMix a b) T where
    find (CompMix x y ) = (find x :: [T]) ++ (find y :: [T])
</code>```

where T would by a type parameter

Or maybe by writing CompFinder so it automatically works for all Components.

This is the full code:

```<code>--ghc 7.10
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}

-- Defined in the library module
class Component a

class ComponentMix a where -- Allow recursive component aggregation
    add :: b -> c -> a b c

class (Component a, Component b) => CompFinder a b where -- class that need a new instance for each new component type
    find :: a -> [b]
    find _ = []

-- Defined in the user module
data CompMix a b = CompMix a b deriving (Show, Eq)

instance ComponentMix CompMix where
    add x y = ( CompMix x y )

instance (Component a, Component b) => Component (CompMix a b)

-- Two simple component types that can be defined in another module
data Position = Pos Int Int deriving (Show, Eq, Ord)
data Name = Name String deriving (Show, Eq)

instance Component Position
instance CompFinder Position Position where -- Trivial instance
    find x = [x]
instance CompFinder Position Name           -- Trivial instance

instance Component Name
instance CompFinder Name Name where -- Trivial instance
    find x = [x]
instance CompFinder Name Position   -- Trivial instance

instance (Component a, CompFinder a Name, Component b, CompFinder b Name) => CompFinder (CompMix a b) Name where
    find (CompMix x y ) = (find x :: [Name]) ++ (find y :: [Name])

instance (Component a, CompFinder a Position, Component b, CompFinder b Position) => CompFinder (CompMix a b) Position where
    find (CompMix x y ) = (find x :: [Position]) ++ (find y :: [Position])

main = print $ (find (CompMix (Name "Henri") (CompMix (Pos 1 2) (Name "Julie") ) ) :: [Position] ) -- Correctly outputs [Pos 1 2]
</code>```

答:
After looking at some Generic Haskell, I finally found an easier way than automatic derivation to avoid writing each instance for Finder (formerly CompFinder).
By doing this way, we only need to define instances of Finder for the structural types defined by the user.

Start with some pragmas

```<code>{-# LANGUAGE MultiParamTypeClasses #-} -- allows functions at the type level
{-# LANGUAGE FlexibleContexts #-} -- allows using data types in typeclass declarations
</code>```

Then define a simple Component wrapper. This way we will write the instance for the Finder only once for all the simple components.

```<code>data Component a = Comp a
</code>```

Then define the Finder class, we will use MultiParamTypeClasses without Functional dependencies because we want to specify the return type to get the desired components:

```<code>class Finder s c where -- s is the structure and c the component
    find :: s -> [c]
    find _ = [] -- provides empty list on search fail
</code>```

We can implement this for our wrapper, first with actual component and searched component matching.

```<code>instance {-# OVERLAPABLE #-} Finder (Component a) (Component a) where
    find (Comp o) = [Comp o]
</code>```

We take advantage of the OVERLAPPABLE pragma to provide an empty list if components differs:

```<code>instance Finder (Component a) (Component b) where
    find (Comp o) = []
</code>```

We can structure our components with a simple Mix (2-Tuple) for instance:

```<code>data Mix a b = Mix a b deriving (Show,Eq,Ord)
instance (Finder a (Component c), Finder b (Component c) ) => Finder (Mix a b) (Component c) where
    find (Mix x y) = find x ++ (find y)
</code>```

Now let's define some components:

```<code>data Velocity = Vel Int Int deriving (Show,Eq,Ord)
data Name = Name String deriving (Show,Eq,Ord)
</code>```

And finally:

```<code>myStruct = Mix (Comp $ Name "Julien") (Comp $ Vel 5 2)

-- we can use the return type to ask for a list of components of that type
Prelude> find myStruct :: [Component Name]
  [Comp (Name "Julien")]

Prelude> find myStruct :: [Component Velocity]
  [Comp (Vel 5 2)]

Prelude> find (Comp $ Name "Marie") :: [Component Velocity]
  []
</code>```

This works with nested Mix too!
The only downside is the use of the Component wrapper but it's fine.

Body:
I im trying to implement a small and simple open type component structure in Haskell.

The goal is to easily allow function and type extension by creating new components in other modules while preserving type safety at compile time.

I managed to implement a recursive search function by component type (find, in CompFinder), and it works well in the simple tests i tried. However i need to write trivial instances for CompFinder for non-composite components and multiple instances with the only difference being the component type for the CompFinder CompMix instance.

I am aware of Derive for automatic code generation for instance deriving but I would like a simpler solution if there is one, the compiler doing the code generation in the worst case, if possible.

So the questions are: How can I modify this system to simplify the writing of new Components?

or: How can I tell GHC to automatically generate CompFinder instances since only the type change in the different definitions?

Perhaps by doing something like this:

instance (Component a, CompFinder a T, Component b, CompFinder b T) => CompFinder (CompMix a b) T where
    find (CompMix x y ) = (find x :: [T]) ++ (find y :: [T])

where T would by a type parameter

Or maybe by writing CompFinder so it automatically works for all Components.

This is the full code:

--ghc 7.10
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}

-- Defined in the library module
class Component a

class ComponentMix a where -- Allow recursive component aggregation
    add :: b -> c -> a b c

class (Component a, Component b) => CompFinder a b where -- class that need a new instance for each new component type
    find :: a -> [b]
    find _ = []

-- Defined in the user module
data CompMix a b = CompMix a b deriving (Show, Eq)

instance ComponentMix CompMix where
    add x y = ( CompMix x y )

instance (Component a, Component b) => Component (CompMix a b)

-- Two simple component types that can be defined in another module
data Position = Pos Int Int deriving (Show, Eq, Ord)
data Name = Name String deriving (Show, Eq)

instance Component Position
instance CompFinder Position Position where -- Trivial instance
    find x = [x]
instance CompFinder Position Name           -- Trivial instance

instance Component Name
instance CompFinder Name Name where -- Trivial instance
    find x = [x]
instance CompFinder Name Position   -- Trivial instance

instance (Component a, CompFinder a Name, Component b, CompFinder b Name) => CompFinder (CompMix a b) Name where
    find (CompMix x y ) = (find x :: [Name]) ++ (find y :: [Name])

instance (Component a, CompFinder a Position, Component b, CompFinder b Position) => CompFinder (CompMix a b) Position where
    find (CompMix x y ) = (find x :: [Position]) ++ (find y :: [Position])

main = print $ (find (CompMix (Name "Henri") (CompMix (Pos 1 2) (Name "Julie") ) ) :: [Position] ) -- Correctly outputs [Pos 1 2]

Body:
After looking at some Generic Haskell, I finally found an easier way than automatic derivation to avoid writing each instance for Finder (formerly CompFinder).
By doing this way, we only need to define instances of Finder for the structural types defined by the user.

Start with some pragmas

{-# LANGUAGE MultiParamTypeClasses #-} -- allows functions at the type level
{-# LANGUAGE FlexibleContexts #-} -- allows using data types in typeclass declarations

Then define a simple Component wrapper. This way we will write the instance for the Finder only once for all the simple components.

data Component a = Comp a

Then define the Finder class, we will use MultiParamTypeClasses without Functional dependencies because we want to specify the return type to get the desired components:

class Finder s c where -- s is the structure and c the component
    find :: s -> [c]
    find _ = [] -- provides empty list on search fail

We can implement this for our wrapper, first with actual component and searched component matching.

instance {-# OVERLAPABLE #-} Finder (Component a) (Component a) where
    find (Comp o) = [Comp o]

We take advantage of the OVERLAPPABLE pragma to provide an empty list if components differs:

instance Finder (Component a) (Component b) where
    find (Comp o) = []

We can structure our components with a simple Mix (2-Tuple) for instance:

data Mix a b = Mix a b deriving (Show,Eq,Ord)
instance (Finder a (Component c), Finder b (Component c) ) => Finder (Mix a b) (Component c) where
    find (Mix x y) = find x ++ (find y)

Now let's define some components:

data Velocity = Vel Int Int deriving (Show,Eq,Ord)
data Name = Name String deriving (Show,Eq,Ord)

And finally:

myStruct = Mix (Comp $ Name "Julien") (Comp $ Vel 5 2)

-- we can use the return type to ask for a list of components of that type
Prelude> find myStruct :: [Component Name]
  [Comp (Name "Julien")]

Prelude> find myStruct :: [Component Velocity]
  [Comp (Vel 5 2)]

Prelude> find (Comp $ Name "Marie") :: [Component Velocity]
  []

This works with nested Mix too!
The only downside is the use of the Component wrapper but it's fine.


问:
Swift 3 submit form - UITextField changes only after focusing field again
I am working on a login view and trying to change the border color of a UITextField in Xcode/swift3 when validation of the textfield fails. The UITextField should get a red border color.

The problem is that if enter an email, then a password and then press the submit button, i have to focus email text field again before it gets a red border.

This is my LoginViewController.swift so far:

```<code>import Foundation
import UIKit

class LoginViewController : UIViewController, UITextFieldDelegate  {

@IBOutlet weak var userEmailTextField: UITextField!
@IBOutlet weak var userPasswordTextField: UITextField!
override func viewDidLoad() {

    super.viewDidLoad()

}

// login button action
@IBAction func loginButtonTabbed(_ sender: Any) {

    // getting values from text fields
    let userEmail = userEmailTextField.text;
    let userPassword = userPasswordTextField.text;

    // set enpoind data
    let requestURL = NSURL(string: Constants.apiUrl)

    //creating a task to send the post request
    var request = URLRequest(url: requestURL as! URL)

    request.httpMethod = "POST"

    let postString = "cmd=addUser&email="+userEmail!+"&password="+userPassword!

    request.httpBody = postString.data(using: .utf8)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in

        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        do {

            let json = try? JSONSerialization.jsonObject(with: data, options: [])

            // store json response to dictionary
            if let dictionary = json as? [String: Any] {

                // check if we got validation errors
                if let nestedDictionary = dictionary["validation"] as? [String: Any] {

                    // display validation messages on device
                    if let emailMsg = nestedDictionary["Email"] as? String {                            // change color of textfield
                        self.userEmailTextField.errorField()

                    }

                }

            }

        } catch let error as NSError {
            print(error)
        }

    }
    //executing the task
    task.resume()

}

}
</code>```

and the UITextField extension UITextField.swift:

```<code>import Foundation
import UIKit

extension UITextField {

    func errorField(){
        self.layer.borderColor = UIColor(red: 255/255.0, green: 59/255.0, blue: 48/255.0, alpha: 1.0).cgColor
        self.layer.borderWidth = 1.0;
    }

}
</code>```

答:
When you're doing a network call, it always happens in the background...so in order to do any kind of UI updates you need to be on the main queue. Just put the self.userEmailTextField.errorField() inside DispatchQueue.main.async {...} so it would be done immediately.

Also haven't really tested your code very well. Why?

Even in your current code the border would still turn red, but it turns red after almost like 6-7 seconds (it could take less or more for you)...because it's being ran from background thread.

What I don't understand is why clicking on the textField again brings the red border right away!? Here's what I'm guessing happens:

From the background thread you update the model ie change the textField color which queues the UI/view to be updated...but since we're on a background queue, that UI updated could take a few seconds to happen

But then you tapped on the textField right away and forced a super quick read of the textField and all its properties which includes the border—from main thread (actual user touches are always handled through main thread)...which even though are not yet red on the screen, but since it's red on the model it will read from it and change color to red immediately.

Body:
I am working on a login view and trying to change the border color of a UITextField in Xcode/swift3 when validation of the textfield fails. The UITextField should get a red border color.

The problem is that if enter an email, then a password and then press the submit button, i have to focus email text field again before it gets a red border.

This is my LoginViewController.swift so far:

import Foundation
import UIKit

class LoginViewController : UIViewController, UITextFieldDelegate  {

@IBOutlet weak var userEmailTextField: UITextField!
@IBOutlet weak var userPasswordTextField: UITextField!
override func viewDidLoad() {

    super.viewDidLoad()

}

// login button action
@IBAction func loginButtonTabbed(_ sender: Any) {

    // getting values from text fields
    let userEmail = userEmailTextField.text;
    let userPassword = userPasswordTextField.text;

    // set enpoind data
    let requestURL = NSURL(string: Constants.apiUrl)

    //creating a task to send the post request
    var request = URLRequest(url: requestURL as! URL)

    request.httpMethod = "POST"

    let postString = "cmd=addUser&email="+userEmail!+"&password="+userPassword!

    request.httpBody = postString.data(using: .utf8)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in

        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        do {

            let json = try? JSONSerialization.jsonObject(with: data, options: [])

            // store json response to dictionary
            if let dictionary = json as? [String: Any] {

                // check if we got validation errors
                if let nestedDictionary = dictionary["validation"] as? [String: Any] {

                    // display validation messages on device
                    if let emailMsg = nestedDictionary["Email"] as? String {                            // change color of textfield
                        self.userEmailTextField.errorField()

                    }

                }

            }

        } catch let error as NSError {
            print(error)
        }

    }
    //executing the task
    task.resume()

}

}

and the UITextField extension UITextField.swift:

import Foundation
import UIKit

extension UITextField {

    func errorField(){
        self.layer.borderColor = UIColor(red: 255/255.0, green: 59/255.0, blue: 48/255.0, alpha: 1.0).cgColor
        self.layer.borderWidth = 1.0;
    }

}


问:
Local database vs Server database in Android Development
What are the differences between a local database and a server database?</p>

答:
The local database is Local (offline) & the server database is online

This is the biggest difference, It all depends on your app style

If you want a dynamic application you should use online database

else

you can use both of them for static data


问:
Removing certain biomes when generating world in Bukkit/Spigot
Is there a way of removing certain biomes (like Jungles) from the WorldCreator when generating a new world on the server? I'm trying to disable the biomes in only one world instead of all of them (which most of the examples online seem to be doing). Is there any way of achieving this?</p>

答:
You can use your own ChunkGenerator and override the methods generateExtBlockSections, generateBlockSections and generateChunkData. Now loop through all x and z in the chunk and get the supposed Biome from the BiomeGrid. If the Biome is the one you would like to remove, replace it by a different Biome via #setBiome. With the manipulated BiomeGrid you can now call the super method.

I did not test this, but with this method I set the Biomes to ocean for the whole world in my SkyBlock plugin. So it should work.


问:
Grid Layout Add Evenly Spaced Images
I am trying to fit a specified amount of images in a Grid Layout programmatically and I want them all to be evenly sized and spread out. Whenever I try to add multiple images the grid layout only shows one. What am I doing wrong?

XML:

```<code><GridLayout
        android:id="@+id/gridlayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="6"
        android:gravity="center"/>
</code>```

Java:

```<code>//reset data and grid
    data.clear();
    gridLayout.removeAllViews();

    Random random = new Random();
    for(int i = 0; i < num; i++){
        data.add(String.format("%." + 0 + "f", random.nextDouble() * (6 - 1) + 1));
        ImageView imageView = new ImageView(getContext());
        switch (data.get(i)) {
            case "1":
                imageView.setImageResource(R.drawable.dice1);
                break;
            case "2":
                imageView.setImageResource(R.drawable.dice2);
                break;
            case "3":
                imageView.setImageResource(R.drawable.dice3);
                break;
            case "4":
                imageView.setImageResource(R.drawable.dice4);
                break;
            case "5":
                imageView.setImageResource(R.drawable.dice5);
                break;
            default:
                imageView.setImageResource(R.drawable.dice6);
                break;
        }
        gridLayout.addView(imageView, i);
    }
</code>```

What shows up:

What I want:

答:
Look at these properties

android:columnCount="2"
    android:rowCount="2"

Before adding the image to the gridview try to play the properties listed above.

If layout contains 1 image set both to 1
If layout contains 2 images set row to 1 and column to 2.
If layout contains 3 images set row to 1 and column to 3

If layout contains 4 set both to 2.

Etc...

Title: Grid Layout Add Evenly Spaced Images

Body:
I am trying to fit a specified amount of images in a Grid Layout programmatically and I want them all to be evenly sized and spread out. Whenever I try to add multiple images the grid layout only shows one. What am I doing wrong?

XML:

<GridLayout
        android:id="@+id/gridlayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="6"
        android:gravity="center"/>

Java:

//reset data and grid
    data.clear();
    gridLayout.removeAllViews();

    Random random = new Random();
    for(int i = 0; i < num; i++){
        data.add(String.format("%." + 0 + "f", random.nextDouble() * (6 - 1) + 1));
        ImageView imageView = new ImageView(getContext());
        switch (data.get(i)) {
            case "1":
                imageView.setImageResource(R.drawable.dice1);
                break;
            case "2":
                imageView.setImageResource(R.drawable.dice2);
                break;
            case "3":
                imageView.setImageResource(R.drawable.dice3);
                break;
            case "4":
                imageView.setImageResource(R.drawable.dice4);
                break;
            case "5":
                imageView.setImageResource(R.drawable.dice5);
                break;
            default:
                imageView.setImageResource(R.drawable.dice6);
                break;
        }
        gridLayout.addView(imageView, i);
    }

What shows up:

What I want:


问:
GET Requests vs JavaScript
Alright, I have a JavaScript doing HTTP Requests to a PHP file onto the same directory. Then it's returning it's output.

Let's say there are over 50+ people doing this request simultaneously ... will it slow down anything? Yes, this may seem like a dumb question - but sorry. :|

Thank you.

答:
Potentially yes. There are some basic questions to answer:

How long does riddle.php take to execute?

How many simultaneous requests can your server handle?

Note that the first answer may vary if riddle.php accesses any shared resources (files, database tables) that may require locking for updates.

ContentLicense: CC BY-SA 2.5

Title: GET Requests vs JavaScript


问:
C# Check if result from method is null
```<code> string sql = string.Format("SELECT * FROM userdata WHERE name = " + name);
 Database.Insert(sql);
</code>```

How I check if Database.Insert method return null or not

答:
not the best, but the code below will help you check for nulls   </p>

```<code>bool found;

using (SqlCommand cmd = new SqlCommand("SELECT * FROM userdata WHERE name = @name", connection))
{
    connection.Open();

    cmd.Parameters.AddWithValue("@name", name);

    SqlDataReader reader = cmd.ExecuteReader();

    if(reader.read())
        found = true
    else
        found = false;

    connection.Close();
}
</code>```

Title: C# Check if result from method is null

Body:
 string sql = string.Format("SELECT * FROM userdata WHERE name = " + name);
 Database.Insert(sql);

How I check if Database.Insert method return null or not

Body:
not the best, but the code below will help you check for nulls

bool found;

using (SqlCommand cmd = new SqlCommand("SELECT * FROM userdata WHERE name = @name", connection))
{
    connection.Open();

    cmd.Parameters.AddWithValue("@name", name);

    SqlDataReader reader = cmd.ExecuteReader();

    if(reader.read())
        found = true
    else
        found = false;

    connection.Close();
}


问:
How to call constructor of given instance?
My first object is TGoodFairy (TObject) and it has own children FChildren (TList).
There is Assign procedure, which makes copy of any TGoodFairy and its children.

The second object is TBadFairy which is descendant of TGoodFairy.

I am struggling how to use Assign method of the TBadFairy to create TBadFairy children. I would like to use ClassType in connection with Create, in order to create right children for TBadFairy (for now only TGoodFairy children are created)

```<code>  TGoodFairy = class (TObject)
  private
    FChildren:TList;
    FName:string;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Assign(Source:TGoodFairy);
  published
    property Name:string read FName write FName;
  end;

  TBadFairy = class (TGoodFairy)
    procedure Assign(Source:TBadFairy);
  end;

------------------------

constructor TGoodFairy.Create;
begin
inherited;
FChildren:=TList.Create;
end;

destructor TGoodFairy.Destroy;
var i:integer;
begin
for i:=0 to FChildren.Count-1 do TGoodFairy(FChildren[i]).Free;
FChildren.Clear;
FChildren.Free;
inherited;
end;

procedure TGoodFairy.Assign(Source:TGoodFairy);
var i:integer;
    f:TGoodFairy;
    C:TClass;
begin
    FName:=Source.Name;
    for i:=0 to Source.FChildren.Count-1 do
    begin
    //C := Source.ClassType;
    //f := C.Create;
    f := TGoodFairy.Create;  //<-- this should be parametrized somehow
    f.Assign(Source.FChildren[i]);
    FChildren.Add(f);
    end;
end;

procedure TBadFairy.Assign(Source:TBadFairy);
begin
inherited Assign(Source);
end;
</code>```

答:
Try something more like this:</p>

```<code>type
  TFairy = class(TObject)
  private
    FChildren: TObjectList;
    FName: string;
  public
    constructor Create; virtual;
    destructor Destroy; override;
    procedure Assign(Source: TFairy); virtual;
  published
    property Name: string read FName write FName;
  end;

  TFairyClass = class of TFairy;

  TGoodFairy = class(TFairy)
  end;

  TBadFairy = class(TFairy)
  end;

constructor TFairy.Create;
begin
  inherited;
  FChildren := TObjectList.Create(True);
end;

destructor TFairy.Destroy;
begin
  FChildren.Free;
  inherited;
end;

procedure TFairy.Assign(Source: TFairy);
var
  i: integer;
  f, child: TFairy;
begin
  FName := Source.Name;
  FChildren.Clear;
  for i := 0 to Source.FChildren.Count-1 do
  begin
    child := TFairy(Source.FChildren[i]);
    f := TFairyClass(child.ClassType).Create;
    try
      f.Assign(child);
      FChildren.Add(f);
    except
      f.Free;
      raise;
    end;
  end;
end;
</code>```

Body:
My first object is TGoodFairy (TObject) and it has own children FChildren (TList).
There is Assign procedure, which makes copy of any TGoodFairy and its children.

The second object is TBadFairy which is descendant of TGoodFairy.

I am struggling how to use Assign method of the TBadFairy to create TBadFairy children. I would like to use ClassType in connection with Create, in order to create right children for TBadFairy (for now only TGoodFairy children are created)

  TGoodFairy = class (TObject)
  private
    FChildren:TList;
    FName:string;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Assign(Source:TGoodFairy);
  published
    property Name:string read FName write FName;
  end;

  TBadFairy = class (TGoodFairy)
    procedure Assign(Source:TBadFairy);
  end;

------------------------

constructor TGoodFairy.Create;
begin
inherited;
FChildren:=TList.Create;
end;

destructor TGoodFairy.Destroy;
var i:integer;
begin
for i:=0 to FChildren.Count-1 do TGoodFairy(FChildren[i]).Free;
FChildren.Clear;
FChildren.Free;
inherited;
end;

procedure TGoodFairy.Assign(Source:TGoodFairy);
var i:integer;
    f:TGoodFairy;
    C:TClass;
begin
    FName:=Source.Name;
    for i:=0 to Source.FChildren.Count-1 do
    begin
    //C := Source.ClassType;
    //f := C.Create;
    f := TGoodFairy.Create;  //<-- this should be parametrized somehow
    f.Assign(Source.FChildren[i]);
    FChildren.Add(f);
    end;
end;

procedure TBadFairy.Assign(Source:TBadFairy);
begin
inherited Assign(Source);
end;

Body:
Try something more like this:

type
  TFairy = class(TObject)
  private
    FChildren: TObjectList;
    FName: string;
  public
    constructor Create; virtual;
    destructor Destroy; override;
    procedure Assign(Source: TFairy); virtual;
  published
    property Name: string read FName write FName;
  end;

  TFairyClass = class of TFairy;

  TGoodFairy = class(TFairy)
  end;

  TBadFairy = class(TFairy)
  end;

constructor TFairy.Create;
begin
  inherited;
  FChildren := TObjectList.Create(True);
end;

destructor TFairy.Destroy;
begin
  FChildren.Free;
  inherited;
end;

procedure TFairy.Assign(Source: TFairy);
var
  i: integer;
  f, child: TFairy;
begin
  FName := Source.Name;
  FChildren.Clear;
  for i := 0 to Source.FChildren.Count-1 do
  begin
    child := TFairy(Source.FChildren[i]);
    f := TFairyClass(child.ClassType).Create;
    try
      f.Assign(child);
      FChildren.Add(f);
    except
      f.Free;
      raise;
    end;
  end;
end;


问:
Direct Cache Access in Apollo Angular
I have the following service class:

const DeleteUserMutation = gql `
 mutation($user_id: ID!) {
  deleteUser(id: $user_id) {
   id
  }
 }
`;

@Injectable()
export class UserService {
  constructor(private apollo: Apollo) {}

  deleteUser(userId: string) {
    return this.apollo.mutate({
      mutation: DeleteUserMutation,
      variables: {
        user_id: userId
      },
      update: (proxy, mutationResult) => {
        proxy.writeQuery({
          query: DeleteUserMutation,
          data: {
            deleteUser: {
              id: userId,
              __typename: 'User'
            }
          },
          variables: {
            user_id: userId
          }
        });
      },
    })
  }
}```

whereby I'm trying to delete a user from my server. The mutation actually works and executes on the server successfully, but the cache never gets updated. I'm not sure where I'm going wrong with my update part above.

答:
You're trying to update a Mutation instead of a Query when this user lives.

Let's say you have this query:

```<code>query allUsers {
  users: [User]
}
</code>```

To update the cache you would like to do something like this:

```<code>const DeleteUserMutation = gql `
    mutation($user_id: ID!) {
        deleteUser(id: $user_id) {
            id
        }
    }
`;

@Injectable()
export class UserService {
  constructor(private apollo: Apollo) {}

  deleteUser(userId: string) {
    return this.apollo.mutate({
      mutation: DeleteUserMutation,
      variables: {
        user_id: userId
      },
      update: (proxy, { data: { deleteUser } }) => {
        // Get data from `allUsers` query
        const data = proxy.readQuery({
          query: AllUsersQuery
        });

        // Logic to remove an item from an array
        const users = removeUserFromArray(deleteUser.id, data.users);

        // write new array with users to the store
        proxy.writeQuery({
          query: AllUsersQuery,
          data: {
            users
          }
        });
      },
    })
  }
}
</code>```

Take a look at the "Updating the Store" chapter, the part with update() function in react-angular docs. Those rules apply for Angular too.

Title: Direct Cache Access in Apollo Angular

Body:
I have the following service class:

const DeleteUserMutation = gql `
 mutation($user_id: ID!) {
  deleteUser(id: $user_id) {
   id
  }
 }
`;

@Injectable()
export class UserService {
  constructor(private apollo: Apollo) {}

  deleteUser(userId: string) {
    return this.apollo.mutate({
      mutation: DeleteUserMutation,
      variables: {
        user_id: userId
      },
      update: (proxy, mutationResult) => {
        proxy.writeQuery({
          query: DeleteUserMutation,
          data: {
            deleteUser: {
              id: userId,
              __typename: 'User'
            }
          },
          variables: {
            user_id: userId
          }
        });
      },
    })
  }
}

whereby I'm trying to delete a user from my server. The mutation actually works and executes on the server successfully, but the cache never gets updated. I'm not sure where I'm going wrong with my update part above.

Body:
You're trying to update a Mutation instead of a Query when this user lives.

Let's say you have this query:

query allUsers {
  users: [User]
}

To update the cache you would like to do something like this:

const DeleteUserMutation = gql `
    mutation($user_id: ID!) {
        deleteUser(id: $user_id) {
            id
        }
    }
`;

@Injectable()
export class UserService {
  constructor(private apollo: Apollo) {}

  deleteUser(userId: string) {
    return this.apollo.mutate({
      mutation: DeleteUserMutation,
      variables: {
        user_id: userId
      },
      update: (proxy, { data: { deleteUser } }) => {
        // Get data from `allUsers` query
        const data = proxy.readQuery({
          query: AllUsersQuery
        });

        // Logic to remove an item from an array
        const users = removeUserFromArray(deleteUser.id, data.users);

        // write new array with users to the store
        proxy.writeQuery({
          query: AllUsersQuery,
          data: {
            users
          }
        });
      },
    })
  }
}

Take a look at the "Updating the Store" chapter, the part with update() function in react-angular docs. Those rules apply for Angular too.


问:
What is the difference between both of these class statements?
I am sorry if the title of my question is too vague, but I do not know how to easily describe what I am trying to figure out. Essentially I have a class that has a property of type std::vector, which is supposed to contain pointers to itself. I tried building and running both of the supplied codes, and I got no errors, so now I am wondering what is the difference between both of these codes?
code 1:

```<code>class MyClass {
public:
    std::vector<MyClass *> Container;
};
</code>```

code 2:

```<code>class MyClass {
public:
    std::vector<MyClass> * Container;
};
</code>```

I would appreciate any help.
Thanks

答:
In the first case, you are defining an array of MyClass pointers.

Case 1:

```<code>class MyClass {
public:
    std::vector<MyClass *> Container;
};
</code>```

In this case, the sizeof(Container) will be sizeof(MyClass*) (size of pointer) X length of vector. Same as the vector itself.
You would access the variable like this...

```<code>// ChildContainer is a vector
ChildContainer = myInstance->Container[i]->Container;
</code>```

In the second case, you are defining a pointer to an array of class instances (which are themselves also pointers already, anyway). Here, the sizeof(Container) will be the size of a pointer. The vector itself will be sizeof(MyClass) (the instance pointer!) X length of vector.

Case 2:

```<code>class MyClass {
public:
    std::vector<MyClass> * Container;
};
</code>```

You would access the variable like this...

```<code>// ChildContainer is a pointer to a vector
ChildContainer = myInstance->(*Container)[i]->Container;
</code>```

If MyClass were actually a struct, accessing could be a little different because structs are not pointers by default.

Case 1:

```<code>struct MyClass {
public:
    std::vector<MyClass*> Container;
};
</code>```

Use:

```<code>// ChildContainer is a vector
ChildContainer = myInstance.Container[i]->Container;
</code>```

Case 2:

```<code>struct MyClass {
public:
    std::vector<MyClass> * Container;
};
</code>```

Use:

```<code>// ChildContainer is a pointer to a vector
ChildContainer = myInstance.(*Container)[i].Container;
</code>```

Body:
I am sorry if the title of my question is too vague, but I do not know how to easily describe what I am trying to figure out. Essentially I have a class that has a property of type std::vector, which is supposed to contain pointers to itself. I tried building and running both of the supplied codes, and I got no errors, so now I am wondering what is the difference between both of these codes?
code 1:

class MyClass {
public:
    std::vector<MyClass *> Container;
};

code 2:

class MyClass {
public:
    std::vector<MyClass> * Container;
};

I would appreciate any help.
Thanks

Body:
In the first case, you are defining an array of MyClass pointers.

Case 1:

class MyClass {
public:
    std::vector<MyClass *> Container;
};

In this case, the sizeof(Container) will be sizeof(MyClass*) (size of pointer) X length of vector. Same as the vector itself.
You would access the variable like this...

// ChildContainer is a vector
ChildContainer = myInstance->Container[i]->Container;

In the second case, you are defining a pointer to an array of class instances (which are themselves also pointers already, anyway). Here, the sizeof(Container) will be the size of a pointer. The vector itself will be sizeof(MyClass) (the instance pointer!) X length of vector.

Case 2:

class MyClass {
public:
    std::vector<MyClass> * Container;
};

You would access the variable like this...

// ChildContainer is a pointer to a vector
ChildContainer = myInstance->(*Container)[i]->Container;

If MyClass were actually a struct, accessing could be a little different because structs are not pointers by default.

Case 1:

struct MyClass {
public:
    std::vector<MyClass*> Container;
};

Use:

// ChildContainer is a vector
ChildContainer = myInstance.Container[i]->Container;

Case 2:

struct MyClass {
public:
    std::vector<MyClass> * Container;
};

Use:

// ChildContainer is a pointer to a vector
ChildContainer = myInstance.(*Container)[i].Container;


问:
Move a node to a certain position withou dragging
I use D3.js and i want that a node move to a certain position ( 1; 1000) after i clicked a button.

The onclick function looks like this:

```<code>var node = svg.append("g")
          .attr("class", "nodes")
          .selectAll("circle")
          .data(nodes)
          .enter().append("circle")
           .attr("r", 8)
         .attr("fill", (d, i) => colours[i % 2])
            .style("stroke", "#000")

     button.on("click", function(d) {
            nodes[1].x = 1;
            nodes[1].y = 1000;
            nodes[1].px = 1;
            nodes[1].py = 1000;
            nodes[1].fixed = true; };
</code>```

My problem is that this does not work right. Can someone help me maybe?

Thanks a lot!

答: Looks like you are only setting the 'data' for that node. That data then needs to applied to the relevant DOM element's attributes. I don't know the answer without seeing more of your code, but for example to move a "g" element using "translate", or circle using its "cx" and "cy" attributes.</p>

Body:
I use D3.js and i want that a node move to a certain position ( 1; 1000) after i clicked a button.

The onclick function looks like this:

var node = svg.append("g")
          .attr("class", "nodes")
          .selectAll("circle")
          .data(nodes)
          .enter().append("circle")
           .attr("r", 8)
         .attr("fill", (d, i) => colours[i % 2])
            .style("stroke", "#000")

     button.on("click", function(d) {
            nodes[1].x = 1;
            nodes[1].y = 1000;
            nodes[1].px = 1;
            nodes[1].py = 1000;
            nodes[1].fixed = true; };

My problem is that this does not work right. Can someone help me maybe?

Thanks a lot!


问:
SQL Server failover cluster - determine active node
Is there a way to programmatically determine which node in a SQL Server failover cluster is the active node? Or at least determine whether the current machine is the active node?

I have a Windows program which runs on both physical nodes in a failover cluster, but that should operate differently depending on whether it is running on the active node. Part of the reason is that this program should not run simultaneously on the inactive and the active node.

(I've read a bit about making the program cluster aware, but that seems heavily overkill for this simple scenario.)

答:
From SQL Server:

```<code>Select ServerProperty('ComputerNamePhysicalNetBIOS')
</code>```

You can also access it through the Microsoft.SqlServer.Management.Smo Namespace as shown here.

Body:
From SQL Server:

Select ServerProperty('ComputerNamePhysicalNetBIOS')

You can also access it through the Microsoft.SqlServer.Management.Smo Namespace as shown here.


问:
RxJava - "Only one emission is allowed to travel up the Observable chain at a time..."
I'm reading a blog post here: http://tomstechnicalblog.blogspot.com/2016/02/rxjava-understanding-observeon-and.html

where it is said that

No matter what Scheduler you are subscribed on, only one emission is
  allowed to travel up the Observable chain of operators at a time.
  Below, you can observe that the emission must be pushed all the way
  from the source to the Subscriber before the next emission can start.

Right above that quoted text is an example written as:

```<code> public static void main(String[] args) {

    Observable<Integer> source = Observable.range(1,10);

    source.map(i -> i * 100)
            .doOnNext(i -> System.out.println("Emitting " + i
                    + " on thread " + Thread.currentThread().getName()))
            .observeOn(Schedulers.computation())
            .map(i -> i * 10)
            .subscribe(i -> System.out.println("Received " + i + " on thread "
                    + Thread.currentThread().getName()));

    sleep(3000);
}
</code>```

with the output as: (ref output1)

```<code>Emitting 100 on thread main
Emitting 200 on thread main
Emitting 300 on thread main
Emitting 400 on thread main
Emitting 500 on thread main
Emitting 600 on thread main
Emitting 700 on thread main
Emitting 800 on thread main
Emitting 900 on thread main
Emitting 1000 on thread main
Received 1000 on thread RxComputationThreadPool-3
Received 2000 on thread RxComputationThreadPool-3
Received 3000 on thread RxComputationThreadPool-3
Received 4000 on thread RxComputationThreadPool-3
Received 5000 on thread RxComputationThreadPool-3
Received 6000 on thread RxComputationThreadPool-3
Received 7000 on thread RxComputationThreadPool-3
Received 8000 on thread RxComputationThreadPool-3
Received 9000 on thread RxComputationThreadPool-3
Received 10000 on thread RxComputationThreadPool-3
</code>```

Initially, I thought the end result would look like: (ref output2)

```<code>Emitting 100 on thread main
Received 1000 on thread RxComputationThreadPool-3
Emitting 200 on thread main
Received 2000 on thread RxComputationThreadPool-3
Emitting 300 on thread main
Received 3000 on thread RxComputationThreadPool-3
Emitting 400 on thread main
Received 4000 on thread RxComputationThreadPool-3
Emitting 500 on thread main
Received 5000 on thread RxComputationThreadPool-3
Emitting 600 on thread main
Received 6000 on thread RxComputationThreadPool-3
Emitting 700 on thread main
Received 7000 on thread RxComputationThreadPool-3
Emitting 800 on thread main
Received 8000 on thread RxComputationThreadPool-3
Emitting 900 on thread main
Received 9000 on thread RxComputationThreadPool-3
Emitting 1000 on thread main
Received 10000 on thread RxComputationThreadPool-3
</code>```

but I can see that calling observeOn allows one stream to handoff to another so that it can keep going. So in the example, it seems like the intial map and doOnNext all complete before the second map and subscribe.

Question:

Is it correct to say that theoretically, the output could look like "ref output2" or would it always look identical to "ref output1"?

Again, my reasoning for this is that it seems that one operator has to process all of the observables completely before it gets handed off to the next operator with the example above.

答:
In theory, both ref output1 and ref output2 are possible but in practice, it will be closer to ref output1. Depending on how hot Schedulers.computation() becomes, you may see some interleaving but it is unlikely you get a perfect ping-pong pattern.

What happens is that observeOn has a prefetch of 128 elements and the first element received will trigger an asynchronous re-emission of elements in an internal queue. Since Threads in executors often don't start/resume quickly enough, the time the re-emission starts the main thread has already emitted all of its values.

You can get the ping-pong effect by configuring observeOn to have a prefetch value of 1 via an overload. However, in this case the original emission may get dragged to the re-emission thread instead of staying on the original thread and you also have to introduce subscribeOn after range to make sure the first doOnNext stays on its own thread. (Also note that you can't pin execution with standard schedulers to the main thread, you need a blocking scheduler for that.)

Body:
I'm reading a blog post here: http://tomstechnicalblog.blogspot.com/2016/02/rxjava-understanding-observeon-and.html

where it is said that

No matter what Scheduler you are subscribed on, only one emission is
  allowed to travel up the Observable chain of operators at a time.
  Below, you can observe that the emission must be pushed all the way
  from the source to the Subscriber before the next emission can start.

Right above that quoted text is an example written as:

 public static void main(String[] args) {

    Observable<Integer> source = Observable.range(1,10);

    source.map(i -> i * 100)
            .doOnNext(i -> System.out.println("Emitting " + i
                    + " on thread " + Thread.currentThread().getName()))
            .observeOn(Schedulers.computation())
            .map(i -> i * 10)
            .subscribe(i -> System.out.println("Received " + i + " on thread "
                    + Thread.currentThread().getName()));

    sleep(3000);
}

with the output as: (ref output1)

Emitting 100 on thread main
Emitting 200 on thread main
Emitting 300 on thread main
Emitting 400 on thread main
Emitting 500 on thread main
Emitting 600 on thread main
Emitting 700 on thread main
Emitting 800 on thread main
Emitting 900 on thread main
Emitting 1000 on thread main
Received 1000 on thread RxComputationThreadPool-3
Received 2000 on thread RxComputationThreadPool-3
Received 3000 on thread RxComputationThreadPool-3
Received 4000 on thread RxComputationThreadPool-3
Received 5000 on thread RxComputationThreadPool-3
Received 6000 on thread RxComputationThreadPool-3
Received 7000 on thread RxComputationThreadPool-3
Received 8000 on thread RxComputationThreadPool-3
Received 9000 on thread RxComputationThreadPool-3
Received 10000 on thread RxComputationThreadPool-3

Initially, I thought the end result would look like: (ref output2)

Emitting 100 on thread main
Received 1000 on thread RxComputationThreadPool-3
Emitting 200 on thread main
Received 2000 on thread RxComputationThreadPool-3
Emitting 300 on thread main
Received 3000 on thread RxComputationThreadPool-3
Emitting 400 on thread main
Received 4000 on thread RxComputationThreadPool-3
Emitting 500 on thread main
Received 5000 on thread RxComputationThreadPool-3
Emitting 600 on thread main
Received 6000 on thread RxComputationThreadPool-3
Emitting 700 on thread main
Received 7000 on thread RxComputationThreadPool-3
Emitting 800 on thread main
Received 8000 on thread RxComputationThreadPool-3
Emitting 900 on thread main
Received 9000 on thread RxComputationThreadPool-3
Emitting 1000 on thread main
Received 10000 on thread RxComputationThreadPool-3

but I can see that calling observeOn allows one stream to handoff to another so that it can keep going. So in the example, it seems like the intial map and doOnNext all complete before the second map and subscribe.

Question:

Is it correct to say that theoretically, the output could look like "ref output2" or would it always look identical to "ref output1"?

Again, my reasoning for this is that it seems that one operator has to process all of the observables completely before it gets handed off to the next operator with the example above.


问:
How to add a custom button on an item that does not have Stock?
I'm working with Wordpress and WooCommerce, I need to add a contact button if in my store some product runs out of stock, ie:

If Stock is 0, show me a contact button.

The following image looks more specific about where I want to insert it:

I have found out how to add the button, but it is added to all the products, and I just want the button to appear when I have no stock on any of my products.
Here is the code used:

```<code>add_action('woocommerce_after_add_to_cart_button', 'boton_subasta');
function boton_subasta(){
     global $product;
    if ( ! $product->is_in_stock()){

        echo '<button type="submit" class="button alt" onclick="window.location.href=http://http://138.197.9.71/prov-individuales/">contacto</button>';
    }
}
</code>```

答:
You are missing a ')' on your if statement, that's why condition its not working.

```<code>if ( ! $product->is_in_stock()){
  echo '<button type="submit"
class="button alt" onclick="window.location.
href=http://http://138.197.9.71/prov-individuales/">contacto</button>';
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm working with Wordpress and WooCommerce, I need to add a contact button if in my store some product runs out of stock, ie:

If Stock is 0, show me a contact button.

The following image looks more specific about where I want to insert it:

I have found out how to add the button, but it is added to all the products, and I just want the button to appear when I have no stock on any of my products.
Here is the code used:

add_action('woocommerce_after_add_to_cart_button', 'boton_subasta');
function boton_subasta(){
     global $product;
    if ( ! $product->is_in_stock()){

        echo '<button type="submit" class="button alt" onclick="window.location.href=http://http://138.197.9.71/prov-individuales/">contacto</button>';
    }
}

Body:
You are missing a ')' on your if statement, that's why condition its not working.

if ( ! $product->is_in_stock()){
  echo '<button type="submit"
class="button alt" onclick="window.location.
href=http://http://138.197.9.71/prov-individuales/">contacto</button>';
}


问:
How do I delay code execution in Visual Basic (VB6)?
I have a long running process in VB6 that I want to finish before executing the next line of code. How can I do that? Built-in function? Can I control how long to wait?

Trivial example:

```<code>Call ExternalLongRunningProcess
Call DoOtherStuff
</code>```

How do I delay 'DoOtherStuff'?

答:
I wish you could just add the .net framework system.dll or whatever to your project references so that you could just do this:

```<code>Dim ALongTime As Integer = 2000
System.Threading.Thread.Sleep(ALongTime)
</code>```

...every time. I have VB6, and VB.net 2008 on my machine, and its always difficult for me to switch between the very different IDE's.

OwnerDisplayName: Ray Vega

Body:
I have a long running process in VB6 that I want to finish before executing the next line of code. How can I do that? Built-in function? Can I control how long to wait?

Trivial example:

Call ExternalLongRunningProcess
Call DoOtherStuff

How do I delay 'DoOtherStuff'?

LastEditorDisplayName: Ray Vega

Body:
I wish you could just add the .net framework system.dll or whatever to your project references so that you could just do this:

Dim ALongTime As Integer = 2000
System.Threading.Thread.Sleep(ALongTime)

...every time. I have VB6, and VB.net 2008 on my machine, and its always difficult for me to switch between the very different IDE's.


问:
JS/Jquery: Initiate window resize without actually resizing
So I have a very specific problem that presented itself recently (right before our planned launch day tomorrow) and I am not completely sure how to solve it. I have built our website of an HTML-template with my modest front-end skills and we are very pleased with it. However, I can't seem to solve this.

The problem:
I have a filter system that allows a user to filter articles that are presented on a page. A user can even fill in this filter on the home page, direct to the page with the articles and have the filter applied. However, if then the filter is broadened (less strict) and new articles present itself, the pictures do not show up. Found out this is the case because the flexslider behind it has to be initialized again which happens on a window load (e.g. when the window is resized). The function that controls the initialization of the flexslider is in an external js file and I am not sure whether I can call on it from my own custom.js file, so I am thinking of just calling a resize/reload window function to active it.

The question:
Can I run a resize window function (or something that activates the flexslider) without hindering user experience (more specifically, without ACTUALLY resizing/reloading the window)? I will run this on a change in the filter.

I know this is a very specific question but hopefully somebody can help me out.

Take care!

p.s. it would be ideal if I could run the actual function that loads the flexslider but this is located in an external js file.

EDIT:
Briefly some additional info. If I go straight to the article page, it has no filter active and thus shows all articles, if I then start flipping through the filter, all is good. It is however only if I arrive from the homepage with a set filter that the problems arise. You then arrive on the article page which shows only the articles that are within the boundaries, and when the filter is taken away it has problems loading the images of the new articles showing up. As if it had not loaded these because they were not open on window load the first time.

答:
You can trigger a resize event by creating a new event and passing it into the dispatchEvent command on window. There's a nice guide here. You'll want the type of event to be resize, since that's what it's listening for.

```<code>window.dispatchEvent(new Event('resize'))
</code>```

This will work for events that were added via jQuery as well as events added via addEventListener.

Body:
You can trigger a resize event by creating a new event and passing it into the dispatchEvent command on window. There's a nice guide here. You'll want the type of event to be resize, since that's what it's listening for.

window.dispatchEvent(new Event('resize'))

This will work for events that were added via jQuery as well as events added via addEventListener.


问:
How to find if an array is strictly in an increasing order after omitting only one element
I have given the following problem where I am stuck right now. I am not having the perfect logic for this. Here is the problem below :

Given a sequence of integers as an array, determine whether it is
  possible to obtain a strictly increasing sequence by removing no more than one element from the array.

Example 1:

```<code>For sequence = [1, 3, 2, 1], the output should be false.
There is no one element that can be removed to get a strictly an increasing sequence
</code>```

Example 2:

```<code>For sequence = [1, 3, 2], the output should be true.
You can remove 3 or 2 to get the strictly increasing sequence [1, 2] or [1,3] respectively
</code>```

I have tried as follows :

```<code>boolean almostIncreasingSequence(int[] sequence) {
    ArrayList<Integer> list = new ArrayList<>();

    for(int i=0; i<sequence.length;i++) {
        list.add(sequence[i]);
    }

    int omittedCounter = 0;

    boolean status = true;

    for(int i=1; i<list.size();i++) {
        if(list.get(i-1) >= list.get(i)) {
            omittedCounter ++;
            list.remove(i-1);
            break;
        }
    }

    if (omittedCounter > 0) {
        for(int i=1; i<list.size();i++) {
            if(list.get(i-1) >= list.get(i)) {
                omittedCounter ++;
                list.remove(i-1);
                break;
            }
        }
    }

    if (omittedCounter > 1) {
        status = false;
    }

    return status;
}
</code>```

But I am having trouble when I am given this sequence: [1, 2, 3, 4, 3, 6]

```<code>Output:           false
Expected Output:  true
</code>```

答:
I have one answer of it which have time complexity of N*Log(N). We will find out longest almost increasing sequence and check if it is equal to or greater than (N-1) , Then we will return true else false.

Checkout :

```<code>public int FindIndex(int A[], int l, int r, int key) {
    while (r - l > 1) {
        int m = l + (r - l) / 2;
        if (A[m] >= key) r = m;
        else l = m;
    }
    return r;
}

public boolean LongestIncreasingSubsequenceLength(int A[], int size)
{
    int[] Seq = new int[size];
    int len;
    Seq[0] = A[0];
    len = 1;
    for (int i = 1; i < size; i++) {
        if (A[i] < Seq[0]) Seq[0] = A[i];
        else if (A[i] > Seq[len - 1]) Seq[len++] = A[i];
        else Seq[FindIndex(Seq, -1, len - 1, A[i])] = A[i];
    }
    return len >= size - 1;
}
</code>```

Body:
I have given the following problem where I am stuck right now. I am not having the perfect logic for this. Here is the problem below :

Given a sequence of integers as an array, determine whether it is
  possible to obtain a strictly increasing sequence by removing no more than one element from the array.

Example 1:

For sequence = [1, 3, 2, 1], the output should be false.
There is no one element that can be removed to get a strictly an increasing sequence

Example 2:

For sequence = [1, 3, 2], the output should be true.
You can remove 3 or 2 to get the strictly increasing sequence [1, 2] or [1,3] respectively

I have tried as follows :

boolean almostIncreasingSequence(int[] sequence) {
    ArrayList<Integer> list = new ArrayList<>();

    for(int i=0; i<sequence.length;i++) {
        list.add(sequence[i]);
    }

    int omittedCounter = 0;

    boolean status = true;

    for(int i=1; i<list.size();i++) {
        if(list.get(i-1) >= list.get(i)) {
            omittedCounter ++;
            list.remove(i-1);
            break;
        }
    }

    if (omittedCounter > 0) {
        for(int i=1; i<list.size();i++) {
            if(list.get(i-1) >= list.get(i)) {
                omittedCounter ++;
                list.remove(i-1);
                break;
            }
        }
    }

    if (omittedCounter > 1) {
        status = false;
    }

    return status;
}

But I am having trouble when I am given this sequence: [1, 2, 3, 4, 3, 6]

Output:           false
Expected Output:  true

Body:
I have one answer of it which have time complexity of N*Log(N). We will find out longest almost increasing sequence and check if it is equal to or greater than (N-1) , Then we will return true else false.

Checkout :

public int FindIndex(int A[], int l, int r, int key) {
    while (r - l > 1) {
        int m = l + (r - l) / 2;
        if (A[m] >= key) r = m;
        else l = m;
    }
    return r;
}

public boolean LongestIncreasingSubsequenceLength(int A[], int size)
{
    int[] Seq = new int[size];
    int len;
    Seq[0] = A[0];
    len = 1;
    for (int i = 1; i < size; i++) {
        if (A[i] < Seq[0]) Seq[0] = A[i];
        else if (A[i] > Seq[len - 1]) Seq[len++] = A[i];
        else Seq[FindIndex(Seq, -1, len - 1, A[i])] = A[i];
    }
    return len >= size - 1;
}


问:
Pinch to Zoom on ListBox on windows phone 7
I am trying to add pinch to zoom feature to a data bound ListBox. What is the most efficient way to do this? I have placed the ListBox inside a Grid control and made it scrollable.

This is my current code.

```<code>    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="10,0,10,10" Background="Black" >
        <ListBox Name="lstText" FontSize="24"  Foreground="White" SelectionMode="Single" Margin="10,0,10,10"  ScrollViewer.VerticalScrollBarVisibility="Visible"  >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel >
                        <TextBlock Text="{Binding Text}" TextWrapping="Wrap"></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
    <toolkit:GestureService.GestureListener>
        <toolkit:GestureListener
            Tap="GestureListener_Tap"
            PinchCompleted="GestureListener_PinchCompleted"
            Flick="GestureListener_Flick">

        </toolkit:GestureListener>
    </toolkit:GestureService.GestureListener>
</code>```

答:
The Listbox isn't designed to be zoomed (via pinching or any other method).

If you want to implement this you must redraw the content at the different zoom levels.

You'd have a number of issues to overcome though:

How do you inform the user that they can alter the text size this way?

How do you avoid affecting the standard behaviour for scrolling and selecting items in the listbox.

How should scrolling behave with regard to wrapping and the currently shown text?

A list shouldn't be used to show large amounts of text on a phone. If you need to show a large amount of text, have a short "title" in the list and then show the detail in another page. This way the text in the list can always be displayed in a way that is large enough that it never need changing and should always be readable.

Is this a genuine problem you are trying to overcome or just something you think would be nice to have? The phone won't be used for just your app so why do you need this if the user will still have to use lists with a fixed text size in the OS and other apps.

You'd have potential performance issues with performance as the framework redraws everything in the list when you change the size of the text. You could look at use deferred loading to only have to redraw what is shown on the screen while zooming but this will impact how you determine the top (and bottom) of what is shown as the sizes change.

Summary: This is almost certainly unnecessary and will be very complicated and difficult to do well. If you really want to try this have a go and then post code with any problems.

Body:
I am trying to add pinch to zoom feature to a data bound ListBox. What is the most efficient way to do this? I have placed the ListBox inside a Grid control and made it scrollable.

This is my current code.

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="10,0,10,10" Background="Black" >
        <ListBox Name="lstText" FontSize="24"  Foreground="White" SelectionMode="Single" Margin="10,0,10,10"  ScrollViewer.VerticalScrollBarVisibility="Visible"  >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel >
                        <TextBlock Text="{Binding Text}" TextWrapping="Wrap"></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
    <toolkit:GestureService.GestureListener>
        <toolkit:GestureListener
            Tap="GestureListener_Tap"
            PinchCompleted="GestureListener_PinchCompleted"
            Flick="GestureListener_Flick">

        </toolkit:GestureListener>
    </toolkit:GestureService.GestureListener>


问:
Django - change app name in admin
I don't know how can I change name of my external app in my django admin panel. I can change verbose name of Constance app ('my constance settings'):

```<code>class ConstanceConfig(AppConfig):
    name = 'constance'
    verbose_name = 'My constance settings'
</code>```

I don't have any idea how can I change "config" name. Any idea?

My models.py:

```<code>from datetime import datetime
from datetime import timedelta
from urllib.parse import urlparse
from django.db import models
from django.urls import reverse
from mainapp.widgets import MyTextField
from django.template.defaultfilters import slugify
from smart_selects.db_fields import ChainedForeignKey
from django.db.models import Q
from constance import config

class Category(models.Model):
    category_name = models.CharField(max_length=30, unique=True,
                                 verbose_name='Nazwa kategorii')
    slug = models.SlugField()
    image = models.ImageField(upload_to='category_images',
                          verbose_name="Obrazek kategorii",
                          blank=True)
    category_description = models.TextField(default='Opis',
                                        verbose_name="Opis kategorii")

    class Meta:
        verbose_name_plural = " Kategorie"

    def save(self, *args, **kwargs):
        self.slug = slugify(self.category_name)
        super(Category, self).save(*args, **kwargs)

    def admin_image_thumb(self):
        '''
        Miniaturka obrazka kategorii dla panelu admina
        '''
        if self.image:
            return('<img src="/media/%s" height="42" width="42" />') %
(self.image)
        else:
            return('<img src="/media/category_images/default.ico" alt="" />')

    admin_image_thumb.short_description = 'Miniaturka'
    admin_image_thumb.allow_tags = True

    def image_thumb(self):
        '''
        Miniaturka obrazka kategorii
        '''
        if self.image:
            return('/media/%s') % (self.image)
        else:
            return('/media/category_images/default.ico')

    def get_active_sites(self):
        return Site.objects.filter(Q(category=self) | Q(category1=self),
is_active=True)

    image_thumb.short_description = 'Miniaturka'
    image_thumb.allow_tags = True

    def __str__(self):
        return self.category_name

class SubCategory(models.Model):
    category = models.ForeignKey(
        'Category',
        related_name='subcategory',
        on_delete=models.CASCADE,
        blank=True,
        null=True,
        verbose_name='Kategoria nadrzędna'
    )
    name = models.CharField(max_length=30, verbose_name="Nazwa subkategorii")
    slug = models.SlugField()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(SubCategory, self).save(*args, **kwargs)

    def get_active_sites(self):
        return Site.objects.filter(Q(subcategory=self) | Q(subcategory1=self), is_active=True)

    class Meta:
        verbose_name_plural = " Subkategorie"

    def __str__(self):
        return self.name

def get_deadline():
    return datetime.today() + timedelta(days=20)

class Site(models.Model):
    category = models.ForeignKey('Category')
    subcategory = ChainedForeignKey(
        'SubCategory',
         chained_field='category',
        chained_model_field='category',
        show_all=False,
        auto_choose=True,
        default=None)
    name = models.CharField(max_length=config.TITLE_LENGTH_MAX,
verbose_name="Tytuł")
    slug = models.SlugField()
    description = models.TextField(max_length=config.DESCRIPTION_LENGTH_MAX,
verbose_name="Opis")
    # importuje zmienione TextFields widgets.py
    keywords = MyTextField(max_length=config.KEYWORDS_LENGTH_MAX,
verbose_name="Słowa kluczowe")
    date = models.DateTimeField(default=datetime.now)
    date_end = models.DateTimeField(null=True, blank=True, default=None)
    url = models.URLField()
    is_active = models.BooleanField(default=False, verbose_name='Aktywna')

    flagged = models.TextField(max_length=400, verbose_name="Flagowanie",
null=True, blank=True, default='')
    flagged_true = models.BooleanField(default=False, verbose_name='Oflagowana')

    category1 = models.ForeignKey('Category', related_name='category',
blank=True, null=True, default=None)
    subcategory1 = ChainedForeignKey(
         'SubCategory',
        chained_field='category1',
        chained_model_field='category',
        related_name='subcategory',
        show_all=False,
        auto_choose=True, blank=True, null=True)

    group = models.ForeignKey('Group', default='Podstawowy',
                          help_text="<div id='group'><ul><li>Możesz dodać
wpis do 1 kategorii</b></li></ul></div>")

    email = models.EmailField(help_text='Podaj adres email')
    user = models.CharField(max_length=100)
    kod = models.CharField(max_length=20)

    def save(self, *args, **kwargs):
         self.slug = slugify(self.name)
         # if len(self.flagged.splitlines() > 3):
         #     self.flagged_true = True
        super(Site, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('site', args=[str(self.category.slug),
                                 str(self.subcategory.slug), str(self.slug),
str(self.id)])

    def get_thumb(self):
        host = urlparse(self.url).hostname
        if host.startswith('www.'):
            host = host[4:]
        thumb = 'http://free.pagepeeker.com/thumbs.php?size=l&url=http://' + host
        # thumb = 'https://api.thumbalizr.com/?url=http://' + host + '&width=500'
        return thumb

    class Meta:
        verbose_name_plural = "Strony"

    def __str__(self):
        return self.name

class Group(models.Model):
    group_name = models.CharField(max_length=30, verbose_name='Nazwa grupy',
unique=True)
    codes = models.TextField(null=True, blank=True)
    pay = models.CharField(
        max_length=10,
        choices=(('PAID', 'PŁATNY'), ('FREE', 'DARMOWY')),
        default='FREE',
        verbose_name="Czy płatny")
    time = models.CharField(
        max_length=3,
        choices=(('T', 'TAK'), ('N', 'NIE')),
        default='N',
        help_text='Czy wpis ma być wyłączony po jakimś czasie czy
bezterminowy')
    days = models.IntegerField(default=1)
    premium_box = models.CharField(
         max_length=3,
    choices=(('T', 'TAK'), ('N', 'NIE')),
    default='N',
    help_text='Czy wpis ma być wyświetlany w okienku reklamowym')
category = models.CharField(
    max_length=2,
    choices=(('1', '1'), ('2', '2')),
)

is_active = models.BooleanField(default=True, verbose_name='Aktywna')

class Meta:
    verbose_name_plural = "Grupy wpisów"

def __str__(self):
    return self.group_name
</code>```

And part of my admin.py:

```<code>from constance.admin import ConstanceAdmin, ConstanceForm, Config

class CustomConfigForm(ConstanceForm):
    def __init__(self, *args, **kwargs):
        super(CustomConfigForm, self).__init__(*args, **kwargs)

class ConfigAdmin(ConstanceAdmin):
    change_list_form = CustomConfigForm
    change_list_template = 'admin/config/change_list.html'

admin.site.unregister([Config])
admin.site.register([Config], ConfigAdmin)
</code>```

In my venvs files I found admin.py (inside constance directory). There is:

```<code>class Config(object):
    class Meta(object):
        app_label = 'constance'
        object_name = 'Config'
        model_name = module_name = 'config'
        verbose_name_plural = _('config')
        abstract = False
        swapped = False

        def get_ordered_objects(self):
            return False

        def get_change_permission(self):
            return 'change_%s' % self.model_name

        @property
        def app_config(self):
            return apps.get_app_config(self.app_label)

   _meta = Meta()
</code>```

I can change

```<code>verbose_name_plural = _('config')
</code>```

to:

```<code>verbose_name_plural = _('My config label')
</code>```

I still can't change this from my admin.py file...

答:
The name of the app is showing correctly, you are pointing to the name of a model. One way to do what you want is to modify the Model's Meta:</p>

```<code>class Config(models.Model):
    class Meta:
        verbose_name = 'Some other name'
</code>```

Title: Django - change app name in admin

Body:
I don't know how can I change name of my external app in my django admin panel. I can change verbose name of Constance app ('my constance settings'):

class ConstanceConfig(AppConfig):
    name = 'constance'
    verbose_name = 'My constance settings'

I don't have any idea how can I change "config" name. Any idea?

My models.py:

from datetime import datetime
from datetime import timedelta
from urllib.parse import urlparse
from django.db import models
from django.urls import reverse
from mainapp.widgets import MyTextField
from django.template.defaultfilters import slugify
from smart_selects.db_fields import ChainedForeignKey
from django.db.models import Q
from constance import config

class Category(models.Model):
    category_name = models.CharField(max_length=30, unique=True,
                                 verbose_name='Nazwa kategorii')
    slug = models.SlugField()
    image = models.ImageField(upload_to='category_images',
                          verbose_name="Obrazek kategorii",
                          blank=True)
    category_description = models.TextField(default='Opis',
                                        verbose_name="Opis kategorii")

    class Meta:
        verbose_name_plural = " Kategorie"

    def save(self, *args, **kwargs):
        self.slug = slugify(self.category_name)
        super(Category, self).save(*args, **kwargs)

    def admin_image_thumb(self):
        '''
        Miniaturka obrazka kategorii dla panelu admina
        '''
        if self.image:
            return('') %
(self.image)
        else:
            return('')

    admin_image_thumb.short_description = 'Miniaturka'
    admin_image_thumb.allow_tags = True

    def image_thumb(self):
        '''
        Miniaturka obrazka kategorii
        '''
        if self.image:
            return('/media/%s') % (self.image)
        else:
            return('/media/category_images/default.ico')

    def get_active_sites(self):
        return Site.objects.filter(Q(category=self) | Q(category1=self),
is_active=True)

    image_thumb.short_description = 'Miniaturka'
    image_thumb.allow_tags = True

    def __str__(self):
        return self.category_name

class SubCategory(models.Model):
    category = models.ForeignKey(
        'Category',
        related_name='subcategory',
        on_delete=models.CASCADE,
        blank=True,
        null=True,
        verbose_name='Kategoria nadrzędna'
    )
    name = models.CharField(max_length=30, verbose_name="Nazwa subkategorii")
    slug = models.SlugField()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(SubCategory, self).save(*args, **kwargs)

    def get_active_sites(self):
        return Site.objects.filter(Q(subcategory=self) | Q(subcategory1=self), is_active=True)

    class Meta:
        verbose_name_plural = " Subkategorie"

    def __str__(self):
        return self.name

def get_deadline():
    return datetime.today() + timedelta(days=20)

class Site(models.Model):
    category = models.ForeignKey('Category')
    subcategory = ChainedForeignKey(
        'SubCategory',
         chained_field='category',
        chained_model_field='category',
        show_all=False,
        auto_choose=True,
        default=None)
    name = models.CharField(max_length=config.TITLE_LENGTH_MAX,
verbose_name="Tytuł")
    slug = models.SlugField()
    description = models.TextField(max_length=config.DESCRIPTION_LENGTH_MAX,
verbose_name="Opis")
    # importuje zmienione TextFields widgets.py
    keywords = MyTextField(max_length=config.KEYWORDS_LENGTH_MAX,
verbose_name="Słowa kluczowe")
    date = models.DateTimeField(default=datetime.now)
    date_end = models.DateTimeField(null=True, blank=True, default=None)
    url = models.URLField()
    is_active = models.BooleanField(default=False, verbose_name='Aktywna')

    flagged = models.TextField(max_length=400, verbose_name="Flagowanie",
null=True, blank=True, default='')
    flagged_true = models.BooleanField(default=False, verbose_name='Oflagowana')

    category1 = models.ForeignKey('Category', related_name='category',
blank=True, null=True, default=None)
    subcategory1 = ChainedForeignKey(
         'SubCategory',
        chained_field='category1',
        chained_model_field='category',
        related_name='subcategory',
        show_all=False,
        auto_choose=True, blank=True, null=True)

    group = models.ForeignKey('Group', default='Podstawowy',
                          help_text="

Możesz dodać
wpis do 1 kategorii

")

    email = models.EmailField(help_text='Podaj adres email')
    user = models.CharField(max_length=100)
    kod = models.CharField(max_length=20)

    def save(self, *args, **kwargs):
         self.slug = slugify(self.name)
         # if len(self.flagged.splitlines() > 3):
         #     self.flagged_true = True
        super(Site, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('site', args=[str(self.category.slug),
                                 str(self.subcategory.slug), str(self.slug),
str(self.id)])

    def get_thumb(self):
        host = urlparse(self.url).hostname
        if host.startswith('www.'):
            host = host[4:]
        thumb = 'http://free.pagepeeker.com/thumbs.php?size=l&url=http://' + host
        # thumb = 'https://api.thumbalizr.com/?url=http://' + host + '&width=500'
        return thumb

    class Meta:
        verbose_name_plural = "Strony"

    def __str__(self):
        return self.name

class Group(models.Model):
    group_name = models.CharField(max_length=30, verbose_name='Nazwa grupy',
unique=True)
    codes = models.TextField(null=True, blank=True)
    pay = models.CharField(
        max_length=10,
        choices=(('PAID', 'PŁATNY'), ('FREE', 'DARMOWY')),
        default='FREE',
        verbose_name="Czy płatny")
    time = models.CharField(
        max_length=3,
        choices=(('T', 'TAK'), ('N', 'NIE')),
        default='N',
        help_text='Czy wpis ma być wyłączony po jakimś czasie czy
bezterminowy')
    days = models.IntegerField(default=1)
    premium_box = models.CharField(
         max_length=3,
    choices=(('T', 'TAK'), ('N', 'NIE')),
    default='N',
    help_text='Czy wpis ma być wyświetlany w okienku reklamowym')
category = models.CharField(
    max_length=2,
    choices=(('1', '1'), ('2', '2')),
)

is_active = models.BooleanField(default=True, verbose_name='Aktywna')

class Meta:
    verbose_name_plural = "Grupy wpisów"

def __str__(self):
    return self.group_name

And part of my admin.py:

from constance.admin import ConstanceAdmin, ConstanceForm, Config

class CustomConfigForm(ConstanceForm):
    def __init__(self, *args, **kwargs):
        super(CustomConfigForm, self).__init__(*args, **kwargs)

class ConfigAdmin(ConstanceAdmin):
    change_list_form = CustomConfigForm
    change_list_template = 'admin/config/change_list.html'

admin.site.unregister([Config])
admin.site.register([Config], ConfigAdmin)

In my venvs files I found admin.py (inside constance directory). There is:

class Config(object):
    class Meta(object):
        app_label = 'constance'
        object_name = 'Config'
        model_name = module_name = 'config'
        verbose_name_plural = _('config')
        abstract = False
        swapped = False

        def get_ordered_objects(self):
            return False

        def get_change_permission(self):
            return 'change_%s' % self.model_name

        @property
        def app_config(self):
            return apps.get_app_config(self.app_label)

   _meta = Meta()

I can change

verbose_name_plural = _('config')

to:

verbose_name_plural = _('My config label')

I still can't change this from my admin.py file...

Body:
The name of the app is showing correctly, you are pointing to the name of a model. One way to do what you want is to modify the Model's Meta:

class Config(models.Model):
    class Meta:
        verbose_name = 'Some other name'


问:
Embed git commit hash in a .NET dll
I'm building a C# application, using Git as my version control.

Is there a way to automatically embed the last commit hash in the executable when I build my application?

For example, printing the commit hash to console would look something like:

```<code>class PrintCommitHash
{
    private String lastCommitHash = ?? // What do I put here?
    static void Main(string[] args)
    {
        // Display the version number:
        System.Console.WriteLine(lastCommitHash );
    }
}
</code>```

Note that this has to be done at build time, not runtime, as my deployed executable will not have the git repo accessible.

A related question for C++ can be found here.

EDIT

Per @mattanja's request, I'm posting the git hook script I use in my projects. The setup:

The hooks are linux shell scripts, which are placed under: path_to_project\.git\hooks

If you are using msysgit, the hooks folder already contains some sample scripts. In order to make git call them, remove the '.sample' extension from the script name.

The names of the hook scripts match the event that invokes them. In my case, I modified post-commit and post-merge.

My AssemblyInfo.cs file is directly under the project path (same level as the .git folder). It contains 23 lines, and I use git to generate the 24th.

As my linux-shelling a bit rusty, the script simply reads the first 23-lines of AssemblyInfo.cs to a temporary file, echos the git hash to the last line, and renames the file back to AssemblyInfo.cs. I'm sure there are better ways of doing this:

```<code>#!/bin/sh
cmt=$(git rev-list --max-count=1 HEAD)
head -23 AssemblyInfo.cs > AssemblyInfo.cs.tmp
echo [assembly: AssemblyFileVersion\(\"$cmt\"\)] >> AssemblyInfo.cs.tmp
mv AssemblyInfo.cs.tmp AssemblyInfo.cs
</code>```

答:
Referring to the another answer (https://stackoverflow.com/a/44278482/4537127) i also utilised the VersionInfo.tt text template to generate AssemblyInformationalVersion without AutoT4.

(Atleast works in my C# WPF application)

Problem was that the Pre-build events were run after template transformations, so after cloning, the git_version.txt file was not there and build fails.
After creating it manually to allow transformation to pass once, it was updated after transformation, and was always one commit behind.

I had to make two adjustments to the .csproj file (this applies at least for Visual Studio Community 2017)

1) Import the Text Transformation Targets and make template transformations to run on every build: (Ref https://msdn.microsoft.com/en-us/library/ee847423.aspx)

```<code><PropertyGroup>
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
    <TransformOnBuild>true</TransformOnBuild>
    <TransformOutOfDateOnly>false</TransformOutOfDateOnly>
</PropertyGroup>
</code>```

and after <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

```<code><Import Project="$(VSToolsPath)\TextTemplating\Microsoft.TextTemplating.targets" />
</code>```

2) Make the git describe run before template transformations (so that git_version.txt is there when VersionInfo.tt is transformed) :

```<code><Target Name="PreBuild" BeforeTargets="ExecuteTransformations">
  <Exec Command="git -C $(ProjectDir) describe --long --always --dirty > $(ProjectDir)git_version.txt" />
</Target>
</code>```

..And the C# code to get the AssemblyInformationalVersion (Ref https://stackoverflow.com/a/7770189/4537127)

```<code>public string AppGitHash
{
    get
    {
        AssemblyInformationalVersionAttribute attribute = (AssemblyInformationalVersionAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false).FirstOrDefault();

        return attribute.InformationalVersion;
    }
}
</code>```

..And add the generated files to .gitignore

```<code>VersionInfo.cs
git_version.txt
</code>```

Title: Embed git commit hash in a .NET dll

Body:
I'm building a C# application, using Git as my version control.

Is there a way to automatically embed the last commit hash in the executable when I build my application?

For example, printing the commit hash to console would look something like:

class PrintCommitHash
{
    private String lastCommitHash = ?? // What do I put here?
    static void Main(string[] args)
    {
        // Display the version number:
        System.Console.WriteLine(lastCommitHash );
    }
}

Note that this has to be done at build time, not runtime, as my deployed executable will not have the git repo accessible.

A related question for C++ can be found here.

EDIT

Per @mattanja's request, I'm posting the git hook script I use in my projects. The setup:

The hooks are linux shell scripts, which are placed under: path_to_project\.git\hooks

If you are using msysgit, the hooks folder already contains some sample scripts. In order to make git call them, remove the '.sample' extension from the script name.

The names of the hook scripts match the event that invokes them. In my case, I modified post-commit and post-merge.

My AssemblyInfo.cs file is directly under the project path (same level as the .git folder). It contains 23 lines, and I use git to generate the 24th.

As my linux-shelling a bit rusty, the script simply reads the first 23-lines of AssemblyInfo.cs to a temporary file, echos the git hash to the last line, and renames the file back to AssemblyInfo.cs. I'm sure there are better ways of doing this:

#!/bin/sh
cmt=$(git rev-list --max-count=1 HEAD)
head -23 AssemblyInfo.cs > AssemblyInfo.cs.tmp
echo [assembly: AssemblyFileVersion\(\"$cmt\"\)] >> AssemblyInfo.cs.tmp
mv AssemblyInfo.cs.tmp AssemblyInfo.cs

Body:
Referring to the another answer (https://stackoverflow.com/a/44278482/4537127) i also utilised the VersionInfo.tt text template to generate AssemblyInformationalVersion without AutoT4.

(Atleast works in my C# WPF application)

Problem was that the Pre-build events were run after template transformations, so after cloning, the git_version.txt file was not there and build fails.
After creating it manually to allow transformation to pass once, it was updated after transformation, and was always one commit behind.

I had to make two adjustments to the .csproj file (this applies at least for Visual Studio Community 2017)

1) Import the Text Transformation Targets and make template transformations to run on every build: (Ref https://msdn.microsoft.com/en-us/library/ee847423.aspx)

<PropertyGroup>
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
    <TransformOnBuild>true</TransformOnBuild>
    <TransformOutOfDateOnly>false</TransformOutOfDateOnly>
</PropertyGroup>

and after <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

<Import Project="$(VSToolsPath)\TextTemplating\Microsoft.TextTemplating.targets" />

2) Make the git describe run before template transformations (so that git_version.txt is there when VersionInfo.tt is transformed) :

<Target Name="PreBuild" BeforeTargets="ExecuteTransformations">
  <Exec Command="git -C $(ProjectDir) describe --long --always --dirty &gt; $(ProjectDir)git_version.txt" />
</Target>

..And the C# code to get the AssemblyInformationalVersion (Ref https://stackoverflow.com/a/7770189/4537127)

public string AppGitHash
{
    get
    {
        AssemblyInformationalVersionAttribute attribute = (AssemblyInformationalVersionAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false).FirstOrDefault();

        return attribute.InformationalVersion;
    }
}

..And add the generated files to .gitignore

VersionInfo.cs
git_version.txt