问:
MySQL - How can I do a conditional WHERE and OR clause Query?

Problem 1:

I need to add a field in a WHERE clause with a condition in my stored procedure, so what is the right syntax for the below query in CASE condition?

Problem 2:

OR condition is giving me all records with values 0,1,2,3,4 for below condition (I need tqm.is_imp = 1 if not found then tqm.is_imp IN (0,2,3,4)). What should I do? Please help.

```<code>tqm.is_imp = 1 OR tqm.is_imp IN (0,2,3,4)
</code>```

My Query:

```<code> SELECT tqm.id INTO selectedQuestionNumber
    FROM tc_question_master tqm
    INNER JOIN tc_question_mapping tqmap ON tqmap.tc_question_id = tqm.id
    WHERE tqmap.syllabus_chapter_details_id IN (SELECT cms_id from topic where chapter_id IN (SELECT id from MyChapters))
    AND tqm.marks = CurMark
CASE WHEN CurQuestionType > 0 THEN
    AND tqm.question_type = CurQuestionType
END
    AND (tqm.level_of_question = 'Easy' OR tqm.level_of_question
    IN ('Moderate','Difficult','Very difficult'))
    AND (tqm.is_imp = 1 OR tqm.is_imp IN (0,2,3,4))
    AND tqm.id NOT IN (SELECT q.question_id FROM QBDetails q)
    ORDER BY RAND() LIMIT 1;
</code>```

答:
The upper part is just a reformat, but lower as you approach the logic that was a case expression, most of that is pure guess.</p>

```<code>SELECT
      tqm.id INTO selectedQuestionNumber
FROM tc_question_master tqm
INNER JOIN tc_question_mapping tqmap ON tqmap.tc_question_id = tqm.id
WHERE tqmap.syllabus_chapter_details_id IN (
      SELECT
            cms_id
      FROM topic
      WHERE chapter_id IN (
            SELECT
                  id
            FROM MyChapters
      )
)
AND (
     tqm.level_of_question = 'Easy'
  OR tqm.level_of_question IN ('Moderate', 'Difficult', 'Very difficult')
    )
AND (
    tqm.is_imp = 1
 OR tqm.is_imp IN (0, 2, 3, 4)
    )
AND tqm.id NOT IN (
      SELECT
            q.question_id
      FROM QBDetails q
)

    ## now it is really vague
    AND (
         tqm.marks = CurMark
      OR
        (CurQuestionType > 0 AND tqm.question_type = CurQuestionType)
        )
    ## end of guesswork

ORDER BY
      RAND()
LIMIT 1;
</code>```

Body:
Problem 1:

I need to add a field in a WHERE clause with a condition in my stored procedure, so what is the right syntax for the below query in CASE condition?

Problem 2:

OR condition is giving me all records with values 0,1,2,3,4 for below condition (I need tqm.is_imp = 1 if not found then tqm.is_imp IN (0,2,3,4)). What should I do? Please help.

tqm.is_imp = 1 OR tqm.is_imp IN (0,2,3,4)

My Query:

 SELECT tqm.id INTO selectedQuestionNumber
    FROM tc_question_master tqm
    INNER JOIN tc_question_mapping tqmap ON tqmap.tc_question_id = tqm.id
    WHERE tqmap.syllabus_chapter_details_id IN (SELECT cms_id from topic where chapter_id IN (SELECT id from MyChapters))
    AND tqm.marks = CurMark
CASE WHEN CurQuestionType > 0 THEN
    AND tqm.question_type = CurQuestionType
END
    AND (tqm.level_of_question = 'Easy' OR tqm.level_of_question
    IN ('Moderate','Difficult','Very difficult'))
    AND (tqm.is_imp = 1 OR tqm.is_imp IN (0,2,3,4))
    AND tqm.id NOT IN (SELECT q.question_id FROM QBDetails q)
    ORDER BY RAND() LIMIT 1;

Body:
The upper part is just a reformat, but lower as you approach the logic that was a case expression, most of that is pure guess.

SELECT
      tqm.id INTO selectedQuestionNumber
FROM tc_question_master tqm
INNER JOIN tc_question_mapping tqmap ON tqmap.tc_question_id = tqm.id
WHERE tqmap.syllabus_chapter_details_id IN (
      SELECT
            cms_id
      FROM topic
      WHERE chapter_id IN (
            SELECT
                  id
            FROM MyChapters
      )
)
AND (
     tqm.level_of_question = 'Easy'
  OR tqm.level_of_question IN ('Moderate', 'Difficult', 'Very difficult')
    )
AND (
    tqm.is_imp = 1
 OR tqm.is_imp IN (0, 2, 3, 4)
    )
AND tqm.id NOT IN (
      SELECT
            q.question_id
      FROM QBDetails q
)

    ## now it is really vague
    AND (
         tqm.marks = CurMark
      OR
        (CurQuestionType > 0 AND tqm.question_type = CurQuestionType)
        )
    ## end of guesswork

ORDER BY
      RAND()
LIMIT 1;


来源: stackexchange

问:
How do I atomically increment a variable in Swift?
I want to be able to increment a counter atomically and I can't find any reference on how to do it.

Adding more information based on comments:

Are you using GCD? No. I am not using GCD. Having to use a queue system to increment a number seems overkill.

Do You understand basic thread safety? Yes I do otherwise I would not be asking about atomic increments.

Is this variable local? No.

Is it instance level? Yes it should be part of a single instance.

I want to do  something like this:

```<code> class Counter {
      private var mux: Mutex
      private (set) value: Int
      func increment() {
          mux.lock()
          value += 1
          mux.unlock()
      }
 }
</code>```

答:
Details

Xcode 10.1 (10B61)

Swift 4.2

Solution

```<code>import Foundation

struct AtomicInteger<Type>: BinaryInteger where Type: BinaryInteger {

    typealias Magnitude = Type.Magnitude
    typealias IntegerLiteralType = Type.IntegerLiteralType
    typealias Words = Type.Words
    fileprivate var value: Type

    private var semaphore = DispatchSemaphore(value: 1)
    fileprivate func _wait() { semaphore.wait() }
    fileprivate func _signal() { semaphore.signal() }

    init() { value = Type() }

    init(integerLiteral value: AtomicInteger.IntegerLiteralType) {
        self.value = Type(integerLiteral: value)
    }

    init<T>(_ source: T) where T : BinaryInteger {
        value = Type(source)
    }

    init(_ source: Int) {
        value = Type(source)
    }

    init<T>(clamping source: T) where T : BinaryInteger {
        value = Type(clamping: source)
    }

    init?<T>(exactly source: T) where T : BinaryInteger {
        guard let value = Type(exactly: source) else { return nil }
        self.value = value
    }

    init<T>(truncatingIfNeeded source: T) where T : BinaryInteger {
        value = Type(truncatingIfNeeded: source)
    }

    init?<T>(exactly source: T) where T : BinaryFloatingPoint {
        guard let value = Type(exactly: source) else { return nil }
        self.value = value
    }

    init<T>(_ source: T) where T : BinaryFloatingPoint {
        value = Type(source)
    }
}

// Instance Properties

extension AtomicInteger {
    var words: Type.Words {
        _wait(); defer { _signal() }
        return value.words
    }
    var bitWidth: Int {
        _wait(); defer { _signal() }
        return value.bitWidth
    }
    var trailingZeroBitCount: Int {
        _wait(); defer { _signal() }
        return value.trailingZeroBitCount
    }
    var magnitude: Type.Magnitude {
        _wait(); defer { _signal() }
        return value.magnitude
    }
}

// Type Properties

extension AtomicInteger {
    static var isSigned: Bool { return Type.isSigned }
}

// Instance Methods

extension AtomicInteger {

    func quotientAndRemainder(dividingBy rhs: AtomicInteger<Type>) -> (quotient: AtomicInteger<Type>, remainder: AtomicInteger<Type>) {
        _wait(); defer { _signal() }
        rhs._wait(); defer { rhs._signal() }
        let result = value.quotientAndRemainder(dividingBy: rhs.value)
        return (AtomicInteger(result.quotient), AtomicInteger(result.remainder))
    }

    func signum() -> AtomicInteger<Type> {
        _wait(); defer { _signal() }
        return AtomicInteger(value.signum())
    }
}

extension AtomicInteger {

    fileprivate static func atomicAction<Result, Other>(lhs: AtomicInteger<Type>,
                                                        rhs: Other, closure: (Type, Type) -> (Result)) -> Result where Other : BinaryInteger {
        lhs._wait(); defer { lhs._signal() }
        var rhsValue = Type(rhs)
        if let rhs = rhs as? AtomicInteger {
            rhs._wait(); defer { rhs._signal() }
            rhsValue = rhs.value
        }
        let result = closure(lhs.value, rhsValue)
        return result
    }

    fileprivate static func atomicActionAndResultSaving<Other>(lhs: inout AtomicInteger<Type>,
                                                               rhs: Other, closure: (Type, Type) -> (Type)) where Other : BinaryInteger {
        lhs._wait(); defer { lhs._signal() }
        var rhsValue = Type(rhs)
        if let rhs = rhs as? AtomicInteger {
            rhs._wait(); defer { rhs._signal() }
            rhsValue = rhs.value
        }
        let result = closure(lhs.value, rhsValue)
        lhs.value = result
    }
}

// Math Operator Functions

extension AtomicInteger {

    static func != <Other>(lhs: AtomicInteger, rhs: Other) -> Bool where Other : BinaryInteger {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 != $1 }
    }

    static func != (lhs: AtomicInteger, rhs: AtomicInteger) -> Bool {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 != $1 }
    }

    static func % (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 % $1 }
        return self.init(value)
    }

    static func %= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 % $1 }
    }

    static func & (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 & $1 }
        return self.init(value)
    }

    static func &= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 & $1 }
    }

    static func * (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 * $1 }
        return self.init(value)
    }

    static func *= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 * $1 }
    }

    static func + (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 + $1 }
        return self.init(value)
    }
    static func += (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 + $1 }
    }

    static func - (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 - $1 }
        return self.init(value)
    }

    static func -= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 - $1 }
    }

    static func / (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 / $1 }
        return self.init(value)
    }

    static func /= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 / $1 }
    }
}

// Shifting Operator Functions

extension AtomicInteger {
    static func << <RHS>(lhs:  AtomicInteger<Type>, rhs: RHS) -> AtomicInteger where RHS : BinaryInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 << $1 }
        return self.init(value)
    }

    static func <<= <RHS>(lhs: inout AtomicInteger, rhs: RHS) where RHS : BinaryInteger {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 << $1 }
    }

    static func >> <RHS>(lhs: AtomicInteger, rhs: RHS) -> AtomicInteger where RHS : BinaryInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 >> $1 }
        return self.init(value)
    }

    static func >>= <RHS>(lhs: inout AtomicInteger, rhs: RHS) where RHS : BinaryInteger {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 >> $1 }
    }
}

// Comparing Operator Functions

extension AtomicInteger {

    static func < <Other>(lhs: AtomicInteger<Type>, rhs: Other) -> Bool where Other : BinaryInteger {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 < $1 }
    }

    static func <= (lhs: AtomicInteger, rhs: AtomicInteger) -> Bool {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 <= $1 }
    }

    static func == <Other>(lhs: AtomicInteger, rhs: Other) -> Bool where Other : BinaryInteger {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 == $1 }
    }

    static func > <Other>(lhs: AtomicInteger, rhs: Other) -> Bool where Other : BinaryInteger {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 > $1 }
    }

    static func > (lhs: AtomicInteger, rhs: AtomicInteger) -> Bool {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 > $1 }
    }

    static func >= (lhs: AtomicInteger, rhs: AtomicInteger) -> Bool {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 >= $1 }
    }

    static func >= <Other>(lhs: AtomicInteger, rhs: Other) -> Bool where Other : BinaryInteger {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 >= $1 }
    }
}

// Binary Math Operator Functions

extension AtomicInteger {

    static func ^ (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 ^ $1 }
        return self.init(value)
    }

    static func ^= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 ^ $1 }
    }

    static func | (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 | $1 }
        return self.init(value)
    }

    static func |= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 | $1 }
    }

    static prefix func ~ (x: AtomicInteger) -> AtomicInteger {
        x._wait(); defer { x._signal() }
        return self.init(x.value)
    }
}

// Hashable

extension AtomicInteger {

    var hashValue: Int {
        _wait(); defer { _signal() }
        return value.hashValue
    }

    func hash(into hasher: inout Hasher) {
        _wait(); defer { _signal() }
        value.hash(into: &hasher)
    }
}

// Get/Set

extension AtomicInteger {

    // Single  actions

    func get() -> Type {
        _wait(); defer { _signal() }
        return value
    }

    mutating func set(value: Type) {
        _wait(); defer { _signal() }
        self.value = value
    }

    // Multi-actions

    func get(closure: (Type)->()) {
        _wait(); defer { _signal() }
        closure(value)
    }

    mutating func set(closure: (Type)->(Type)) {
        _wait(); defer { _signal() }
        self.value = closure(value)
    }
}
</code>```

Usage

```<code>// Usage Samples
let numA = AtomicInteger<Int8>(0)
let numB = AtomicInteger<Int16>(0)
let numC = AtomicInteger<Int32>(0)
let numD = AtomicInteger<Int64>(0)

var num1 = AtomicInteger<Int>(0)
num1 += 1
num1 -= 1
num1 = 10
num1 = num1/2

var num2 = 0
num2 = num1.get()
num1.set(value: num2*5)

// lock num1 to do several actions
num1.get { value in
    //...
}

num1.set { value in
    //...
    return value
}
</code>```

Full Sample

```<code>import Foundation

var x = AtomicInteger<Int>(0)
let dispatchGroup = DispatchGroup()
private func async(dispatch: DispatchQueue, closure: @escaping (DispatchQueue)->()) {
    for _ in 0 ..< 100 {
        dispatchGroup.enter()
        dispatch.async {
            print("Queue: \(dispatch.qos.qosClass)")
            closure(dispatch)
            dispatchGroup.leave()
        }
    }
}

func sample() {
    let closure1: (DispatchQueue)->() = { _ in x += 1 }
    let closure2: (DispatchQueue)->() = { _ in x -= 1 }
    async(dispatch: .global(qos: .userInitiated), closure: closure1) // result: x += 100
    async(dispatch: .global(qos: .utility), closure: closure1) // result: x += 100
    async(dispatch: .global(qos: .background), closure: closure2) // result: x -= 100
    async(dispatch: .global(qos: .default), closure: closure2) // result: x -= 100
}

sample()
dispatchGroup.wait()
print(x) // expected result x = 0
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to be able to increment a counter atomically and I can't find any reference on how to do it.

Adding more information based on comments:

Are you using GCD? No. I am not using GCD. Having to use a queue system to increment a number seems overkill.

Do You understand basic thread safety? Yes I do otherwise I would not be asking about atomic increments.

Is this variable local? No.

Is it instance level? Yes it should be part of a single instance.

I want to do  something like this:

 class Counter {
      private var mux: Mutex
      private (set) value: Int
      func increment() {
          mux.lock()
          value += 1
          mux.unlock()
      }
 }

Body:
Details

Xcode 10.1 (10B61)

Swift 4.2

Solution

import Foundation

struct AtomicInteger<Type>: BinaryInteger where Type: BinaryInteger {

    typealias Magnitude = Type.Magnitude
    typealias IntegerLiteralType = Type.IntegerLiteralType
    typealias Words = Type.Words
    fileprivate var value: Type

    private var semaphore = DispatchSemaphore(value: 1)
    fileprivate func _wait() { semaphore.wait() }
    fileprivate func _signal() { semaphore.signal() }

    init() { value = Type() }

    init(integerLiteral value: AtomicInteger.IntegerLiteralType) {
        self.value = Type(integerLiteral: value)
    }

    init<T>(_ source: T) where T : BinaryInteger {
        value = Type(source)
    }

    init(_ source: Int) {
        value = Type(source)
    }

    init<T>(clamping source: T) where T : BinaryInteger {
        value = Type(clamping: source)
    }

    init?<T>(exactly source: T) where T : BinaryInteger {
        guard let value = Type(exactly: source) else { return nil }
        self.value = value
    }

    init<T>(truncatingIfNeeded source: T) where T : BinaryInteger {
        value = Type(truncatingIfNeeded: source)
    }

    init?<T>(exactly source: T) where T : BinaryFloatingPoint {
        guard let value = Type(exactly: source) else { return nil }
        self.value = value
    }

    init<T>(_ source: T) where T : BinaryFloatingPoint {
        value = Type(source)
    }
}

// Instance Properties

extension AtomicInteger {
    var words: Type.Words {
        _wait(); defer { _signal() }
        return value.words
    }
    var bitWidth: Int {
        _wait(); defer { _signal() }
        return value.bitWidth
    }
    var trailingZeroBitCount: Int {
        _wait(); defer { _signal() }
        return value.trailingZeroBitCount
    }
    var magnitude: Type.Magnitude {
        _wait(); defer { _signal() }
        return value.magnitude
    }
}

// Type Properties

extension AtomicInteger {
    static var isSigned: Bool { return Type.isSigned }
}

// Instance Methods

extension AtomicInteger {

    func quotientAndRemainder(dividingBy rhs: AtomicInteger<Type>) -> (quotient: AtomicInteger<Type>, remainder: AtomicInteger<Type>) {
        _wait(); defer { _signal() }
        rhs._wait(); defer { rhs._signal() }
        let result = value.quotientAndRemainder(dividingBy: rhs.value)
        return (AtomicInteger(result.quotient), AtomicInteger(result.remainder))
    }

    func signum() -> AtomicInteger<Type> {
        _wait(); defer { _signal() }
        return AtomicInteger(value.signum())
    }
}

extension AtomicInteger {

    fileprivate static func atomicAction<Result, Other>(lhs: AtomicInteger<Type>,
                                                        rhs: Other, closure: (Type, Type) -> (Result)) -> Result where Other : BinaryInteger {
        lhs._wait(); defer { lhs._signal() }
        var rhsValue = Type(rhs)
        if let rhs = rhs as? AtomicInteger {
            rhs._wait(); defer { rhs._signal() }
            rhsValue = rhs.value
        }
        let result = closure(lhs.value, rhsValue)
        return result
    }

    fileprivate static func atomicActionAndResultSaving<Other>(lhs: inout AtomicInteger<Type>,
                                                               rhs: Other, closure: (Type, Type) -> (Type)) where Other : BinaryInteger {
        lhs._wait(); defer { lhs._signal() }
        var rhsValue = Type(rhs)
        if let rhs = rhs as? AtomicInteger {
            rhs._wait(); defer { rhs._signal() }
            rhsValue = rhs.value
        }
        let result = closure(lhs.value, rhsValue)
        lhs.value = result
    }
}

// Math Operator Functions

extension AtomicInteger {

    static func != <Other>(lhs: AtomicInteger, rhs: Other) -> Bool where Other : BinaryInteger {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 != $1 }
    }

    static func != (lhs: AtomicInteger, rhs: AtomicInteger) -> Bool {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 != $1 }
    }

    static func % (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 % $1 }
        return self.init(value)
    }

    static func %= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 % $1 }
    }

    static func & (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 & $1 }
        return self.init(value)
    }

    static func &= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 & $1 }
    }

    static func * (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 * $1 }
        return self.init(value)
    }

    static func *= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 * $1 }
    }

    static func + (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 + $1 }
        return self.init(value)
    }
    static func += (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 + $1 }
    }

    static func - (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 - $1 }
        return self.init(value)
    }

    static func -= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 - $1 }
    }

    static func / (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 / $1 }
        return self.init(value)
    }

    static func /= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 / $1 }
    }
}

// Shifting Operator Functions

extension AtomicInteger {
    static func << <RHS>(lhs:  AtomicInteger<Type>, rhs: RHS) -> AtomicInteger where RHS : BinaryInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 << $1 }
        return self.init(value)
    }

    static func <<= <RHS>(lhs: inout AtomicInteger, rhs: RHS) where RHS : BinaryInteger {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 << $1 }
    }

    static func >> <RHS>(lhs: AtomicInteger, rhs: RHS) -> AtomicInteger where RHS : BinaryInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 >> $1 }
        return self.init(value)
    }

    static func >>= <RHS>(lhs: inout AtomicInteger, rhs: RHS) where RHS : BinaryInteger {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 >> $1 }
    }
}

// Comparing Operator Functions

extension AtomicInteger {

    static func < <Other>(lhs: AtomicInteger<Type>, rhs: Other) -> Bool where Other : BinaryInteger {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 < $1 }
    }

    static func <= (lhs: AtomicInteger, rhs: AtomicInteger) -> Bool {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 <= $1 }
    }

    static func == <Other>(lhs: AtomicInteger, rhs: Other) -> Bool where Other : BinaryInteger {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 == $1 }
    }

    static func > <Other>(lhs: AtomicInteger, rhs: Other) -> Bool where Other : BinaryInteger {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 > $1 }
    }

    static func > (lhs: AtomicInteger, rhs: AtomicInteger) -> Bool {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 > $1 }
    }

    static func >= (lhs: AtomicInteger, rhs: AtomicInteger) -> Bool {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 >= $1 }
    }

    static func >= <Other>(lhs: AtomicInteger, rhs: Other) -> Bool where Other : BinaryInteger {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 >= $1 }
    }
}

// Binary Math Operator Functions

extension AtomicInteger {

    static func ^ (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 ^ $1 }
        return self.init(value)
    }

    static func ^= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 ^ $1 }
    }

    static func | (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 | $1 }
        return self.init(value)
    }

    static func |= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 | $1 }
    }

    static prefix func ~ (x: AtomicInteger) -> AtomicInteger {
        x._wait(); defer { x._signal() }
        return self.init(x.value)
    }
}

// Hashable

extension AtomicInteger {

    var hashValue: Int {
        _wait(); defer { _signal() }
        return value.hashValue
    }

    func hash(into hasher: inout Hasher) {
        _wait(); defer { _signal() }
        value.hash(into: &hasher)
    }
}

// Get/Set

extension AtomicInteger {

    // Single  actions

    func get() -> Type {
        _wait(); defer { _signal() }
        return value
    }

    mutating func set(value: Type) {
        _wait(); defer { _signal() }
        self.value = value
    }

    // Multi-actions

    func get(closure: (Type)->()) {
        _wait(); defer { _signal() }
        closure(value)
    }

    mutating func set(closure: (Type)->(Type)) {
        _wait(); defer { _signal() }
        self.value = closure(value)
    }
}

Usage

// Usage Samples
let numA = AtomicInteger<Int8>(0)
let numB = AtomicInteger<Int16>(0)
let numC = AtomicInteger<Int32>(0)
let numD = AtomicInteger<Int64>(0)

var num1 = AtomicInteger<Int>(0)
num1 += 1
num1 -= 1
num1 = 10
num1 = num1/2

var num2 = 0
num2 = num1.get()
num1.set(value: num2*5)

// lock num1 to do several actions
num1.get { value in
    //...
}

num1.set { value in
    //...
    return value
}

Full Sample

import Foundation

var x = AtomicInteger<Int>(0)
let dispatchGroup = DispatchGroup()
private func async(dispatch: DispatchQueue, closure: @escaping (DispatchQueue)->()) {
    for _ in 0 ..< 100 {
        dispatchGroup.enter()
        dispatch.async {
            print("Queue: \(dispatch.qos.qosClass)")
            closure(dispatch)
            dispatchGroup.leave()
        }
    }
}

func sample() {
    let closure1: (DispatchQueue)->() = { _ in x += 1 }
    let closure2: (DispatchQueue)->() = { _ in x -= 1 }
    async(dispatch: .global(qos: .userInitiated), closure: closure1) // result: x += 100
    async(dispatch: .global(qos: .utility), closure: closure1) // result: x += 100
    async(dispatch: .global(qos: .background), closure: closure2) // result: x -= 100
    async(dispatch: .global(qos: .default), closure: closure2) // result: x -= 100
}

sample()
dispatchGroup.wait()
print(x) // expected result x = 0


问:
How to pass parameter to vue.js router in a method function?
I'm trying to send 'joke.id' as parameter to the router:

```<code>edit: function(joke) {
    this.$router.push({ '/edit/' + joke.id });
}
</code>```

The relevant route is:

```<code>{path: '/edit/:id', component: editJoke, name: 'editJoke'},
</code>```

However I get this in the console:

Module build failed: SyntaxError: Unexpected token

```<code>this.$router.push({ '/edit/' + joke.id });
  |                          ^
</code>```

How can I fix this?

答:
You can pass parameters to the router by using this syntax:

```<code>edit: function(joke) {
    this.$router.push('/edit/' + joke.id)
}
</code>```

If you have named your route you can use this syntax instead:

```<code>edit: function(joke) {
    this.$router.push({ name: 'edit', params: { id: joke.id }})
}
</code>```

Read more about programmatic navigation with Vue Router here.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to send 'joke.id' as parameter to the router:

edit: function(joke) {
    this.$router.push({ '/edit/' + joke.id });
}

The relevant route is:

{path: '/edit/:id', component: editJoke, name: 'editJoke'},

However I get this in the console:

Module build failed: SyntaxError: Unexpected token

this.$router.push({ '/edit/' + joke.id });
  |                          ^

How can I fix this?

Body:
You can pass parameters to the router by using this syntax:

edit: function(joke) {
    this.$router.push('/edit/' + joke.id)
}

If you have named your route you can use this syntax instead:

edit: function(joke) {
    this.$router.push({ name: 'edit', params: { id: joke.id }})
}

Read more about programmatic navigation with Vue Router here.


问:
ld can not find symbol _start error after assemble and link .asm file to 64 bit executables
I have a shellcode file.
Then use ndisasm to build the assembly code.

```<code> ndisasm -b 64 shellcode > shellcode.asm
 cat shellcode.asm | cut -c29->key.asm
</code>```

I add 2 lines to the key.asm file

global_start:

       _start:

```<code>$vi key.asm
global_start:
_start:
xor eax,eax
push rax
push qword 0x79237771
push qword 0x76772427
push qword 0x25747320
.    .     .
.    .     .
.    .     .
push qword 0x20757577
push rsp
pop rsi
mov edi,esi
mov edx,edi
cld
mov ecx,0x80
mov ebx,0x41
xor eax,eax
push rax
lodsb
xor eax,ebx
</code>```

An then I assemble and link it to 64 bit executables

```<code>$nasm -f elf64 -g -F stabs key.asm
$ld -o key key.o
</code>```

It gives me a warning

```<code>ld: warning: cannot find entry symbol _start; defaulting to 0000000000400080
</code>```

I tested it out with gcc

```<code>gcc -o key key.o
</code>```

I still get an error almost the same as the first one

```<code>/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: In
function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
</code>```

And when I run ./key with gdb after I use $ld NOT $gcc

```<code>$gdb -q ./key
$run
</code>```

I get a seg fault

```<code>Starting program: /mnt/c/Users/owner/Documents/U
M/Computer_Security/ExtraCredit/key
Program received signal SIGSEGV, Segmentation fault.
0x000000000040013a in global_start ()
</code>```

If I debug after run with gcc then the file will not be found because of exit status

Can you explain why does it happen? And how can I fix this problem? Thanks

答:
It gives me a warning

```<code>ld: warning: cannot find entry symbol _start; defaulting to 0000000000400080
</code>```

This isn't actually a problem, as long as you're fine with the entry point being the start of the text segment (i.e. the first instruction in your shellcode).

You got the error because you left out the space between the global keyword and the _start symbol name.  i.e. use global _start, or don't bother.  What you did defined a label called global_start, as you can see from your later error message.

You segfault on lodsb because you truncated a stack address with mov edi,esi instead of mov rdi, rsi. And if you fix that then you fall off the end of your code into garbage instructions because you don't make an exit system call. You're already running this inside gdb, use it!

I tested it out with gcc:  gcc -o key key.o

I still get an error almost the same as the first one

```<code> /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:
In function `_start':
(.text+0x20): undefined reference to `main'
</code>```

No, that's a totally different error.  If you had exported _start correctly, you would have gotten an error for conflicting definitions of _start (between your code and the CRT start files).

This error is that the _start definition in crt1.o (provided by gcc) has a reference to main, but your code doesn't provide a main.  This is what happens when you try to compile a C or C++ program that doesn't define main.

To link with gcc, use -nostdlib to omit the CRT start files and all other libraries.  (i.e. link pretty much exactly like you were doing manually with ld.)

```<code>gcc -nostdlib -static key.o -o key   # static executable: just your code
</code>```

Or dynamically linked without the CRT start files, using your _start.

```<code>gcc -nostdinc -no-pie key.o -o key
</code>```

You can call libc functions from code linked that way, but only on Linux or other platforms where dynamic linking takes care of running libc initialization functions.

If you statically link libc, you can only call functions like printf if you first call all the libc init functions that the normal CRT startup code does.  (Not going into detail here because this code doesn't use libc)

Body:
I have a shellcode file.
Then use ndisasm to build the assembly code.

 ndisasm -b 64 shellcode > shellcode.asm
 cat shellcode.asm | cut -c29->key.asm

I add 2 lines to the key.asm file

global_start:

       _start:

$vi key.asm
global_start:
_start:
xor eax,eax
push rax
push qword 0x79237771
push qword 0x76772427
push qword 0x25747320
.    .     .
.    .     .
.    .     .
push qword 0x20757577
push rsp
pop rsi
mov edi,esi
mov edx,edi
cld
mov ecx,0x80
mov ebx,0x41
xor eax,eax
push rax
lodsb
xor eax,ebx

An then I assemble and link it to 64 bit executables

$nasm -f elf64 -g -F stabs key.asm
$ld -o key key.o

It gives me a warning

ld: warning: cannot find entry symbol _start; defaulting to 0000000000400080

I tested it out with gcc

gcc -o key key.o

I still get an error almost the same as the first one

/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: In
function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status

And when I run ./key with gdb after I use $ld NOT $gcc

$gdb -q ./key
$run

I get a seg fault

Starting program: /mnt/c/Users/owner/Documents/U
M/Computer_Security/ExtraCredit/key
Program received signal SIGSEGV, Segmentation fault.
0x000000000040013a in global_start ()

If I debug after run with gcc then the file will not be found because of exit status

Can you explain why does it happen? And how can I fix this problem? Thanks

Body:
It gives me a warning

ld: warning: cannot find entry symbol _start; defaulting to 0000000000400080

This isn't actually a problem, as long as you're fine with the entry point being the start of the text segment (i.e. the first instruction in your shellcode).

You got the error because you left out the space between the global keyword and the _start symbol name.  i.e. use global _start, or don't bother.  What you did defined a label called global_start, as you can see from your later error message.

You segfault on lodsb because you truncated a stack address with mov edi,esi instead of mov rdi, rsi. And if you fix that then you fall off the end of your code into garbage instructions because you don't make an exit system call. You're already running this inside gdb, use it!

I tested it out with gcc:  gcc -o key key.o

I still get an error almost the same as the first one

 /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:
In function `_start':
(.text+0x20): undefined reference to `main'

No, that's a totally different error.  If you had exported _start correctly, you would have gotten an error for conflicting definitions of _start (between your code and the CRT start files).

This error is that the _start definition in crt1.o (provided by gcc) has a reference to main, but your code doesn't provide a main.  This is what happens when you try to compile a C or C++ program that doesn't define main.

To link with gcc, use -nostdlib to omit the CRT start files and all other libraries.  (i.e. link pretty much exactly like you were doing manually with ld.)

gcc -nostdlib -static key.o -o key   # static executable: just your code

Or dynamically linked without the CRT start files, using your _start.

gcc -nostdinc -no-pie key.o -o key

You can call libc functions from code linked that way, but only on Linux or other platforms where dynamic linking takes care of running libc initialization functions.

If you statically link libc, you can only call functions like printf if you first call all the libc init functions that the normal CRT startup code does.  (Not going into detail here because this code doesn't use libc)


问:
Can't get the array inside hashtable obj
I have an array of type Guid inside an HashTable
I get the values like the following but I can't get the array inside

```<code>    IDictionaryEnumerator enumObj = moreTable.GetEnumerator();

                while (enumObj.MoveNext())
                {
 foreach (var obj in enumObj.Value)
                    {
                        _guidList.Add(new Guid(obj.ToString()));
                    }
}
</code>```

but this doesn't working with me any one know how to extract an array stored inside Hash table

答: I guess you should cast enumObj.Value to array, that should allow you to use it.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have an array of type Guid inside an HashTable
I get the values like the following but I can't get the array inside

    IDictionaryEnumerator enumObj = moreTable.GetEnumerator();

                while (enumObj.MoveNext())
                {
 foreach (var obj in enumObj.Value)
                    {
                        _guidList.Add(new Guid(obj.ToString()));
                    }
}

but this doesn't working with me any one know how to extract an array stored inside Hash table


问:
Excel VBA save as text file without delimiter
I am trying to convert the output sheet from excel into text file using macro, but is it possible to convert a file without a delimiter? my existing code can only save as tab delimited but the system that I am uploading the text file detects the tab spaces as excess character.

here is my existing VBA code:

```<code>Sub SaveAsTXT()
Dim parts As Variant

parts = Split(ActiveWorkbook.Name, ".")
parts(UBound(parts)) = ".txt"

ActiveWorkbook.SaveAs Filename:=ActiveWorkbook.Path & "\" & _
    Join(parts, "."), FileFormat:=xlTextWindows, CreateBackup:=False
End Sub
</code>```

答:
You need delimiter or a separator for distinct differentiate fields.

In approach below there is a code that you can choose you value separator optionally as you want.

Now , character as delimiter for default.

Notes about below code:

rngRange argument: is the source range that you want to export as your report in *.txt file.

strSeparator: is a your suitable delimiter can define here.

...

```<code>sub Report
    CsvExportRange rngRange:=ThisWorkbook.Worksheets("Sheet1").Range("tblTaxRep"), _
        strFileName:="C:\" & ".txt", _
        strCharset:="UTF-8", strSeparator:=",", strRowEnd:=vbCrLf, NVC:=False
End Sub
</code>```

```<code>Sub CsvExportRange(rngRange As Object, strFileName As String, strCharset, strSeparator As String, strRowEnd As String, NVC As Boolean) 'NVC: _
    Null Value Control (If cell contain Null value, suppose reached end of range), d: delimiter

    Dim rngRow As Range
    Dim objStream As Object
    Dim i, lngFR, lngLR As Long 'lngFR: First Row, lngLR: Last Row

    lngFR = rngRange.SpecialCells(xlCellTypeVisible).Rows(1).row - rngRange.Rows(1).row + 1
    lngLR = rngRange.End(xlDown).row - rngRange.Rows(1).row + 1

    Set objStream = CreateObject("ADODB.Stream")
    objStream.Type = 2
    objStream.Charset = strCharset
    objStream.Open

    For i = lngFR To lngLR
        If Not (rngRange.Rows(i).EntireRow.Hidden) Then
            If IIf(NVC, (Cells(i + rngRange.Rows(1).row - 1, _
                rngRange.SpecialCells(xlCellTypeVisible).Columns(1).column).Value = vbNullString), False) Then Exit For
            objStream.WriteText CsvFormatRow(rngRange.Rows(i), strSeparator, strRowEnd)
        End If
    Next i

    objStream.SaveToFile strFileName, 2
    objStream.Close
End Sub 'CsvExportRange

Function CsvFormatRow(rngRow As Variant, strSeparator As String, strRowEnd As String) As String

    Dim arrCsvRow() As String

    ReDim arrCsvRow(rngRow.SpecialCells(xlCellTypeVisible).Cells.Count - 1)
    Dim rngCell As Range
    Dim lngIndex As Long

    lngIndex = 0

    For Each rngCell In rngRow.SpecialCells(xlCellTypeVisible).Cells
        arrCsvRow(lngIndex) = CsvFormatString(rngCell.Value, strSeparator)
        lngIndex = lngIndex + 1
    Next rngCell

    CsvFormatRow = Join(arrCsvRow, strSeparator) & strRowEnd

End Function 'CsvFormatRow

Function CsvFormatString(strRaw, strSeparator As String) As String

    Dim boolNeedsDelimiting As Boolean

    Dim strDelimiter, strDelimiterEscaped As String

    strDelimiter = """"
    strDelimiterEscaped = strDelimiter & strDelimiter

    boolNeedsDelimiting = InStr(1, strRaw, strDelimiter) > 0 _
        Or InStr(1, strRaw, chr(10)) > 0 _
        Or InStr(1, strRaw, strSeparator) > 0

    CsvFormatString = strRaw

    If boolNeedsDelimiting Then
        CsvFormatString = strDelimiter & _
            Replace(strRaw, strDelimiter, strDelimiterEscaped) & _
            strDelimiter
    End If

End Function 'CsvFormatString
</code>```

Body:
I am trying to convert the output sheet from excel into text file using macro, but is it possible to convert a file without a delimiter? my existing code can only save as tab delimited but the system that I am uploading the text file detects the tab spaces as excess character.

here is my existing VBA code:

Sub SaveAsTXT()
Dim parts As Variant

parts = Split(ActiveWorkbook.Name, ".")
parts(UBound(parts)) = ".txt"

ActiveWorkbook.SaveAs Filename:=ActiveWorkbook.Path & "\" & _
    Join(parts, "."), FileFormat:=xlTextWindows, CreateBackup:=False
End Sub

Body:
You need delimiter or a separator for distinct differentiate fields.

In approach below there is a code that you can choose you value separator optionally as you want.

Now , character as delimiter for default.

Notes about below code:

rngRange argument: is the source range that you want to export as your report in *.txt file.

strSeparator: is a your suitable delimiter can define here.

...

sub Report
    CsvExportRange rngRange:=ThisWorkbook.Worksheets("Sheet1").Range("tblTaxRep"), _
        strFileName:="C:\" & ".txt", _
        strCharset:="UTF-8", strSeparator:=",", strRowEnd:=vbCrLf, NVC:=False
End Sub

Sub CsvExportRange(rngRange As Object, strFileName As String, strCharset, strSeparator As String, strRowEnd As String, NVC As Boolean) 'NVC: _
    Null Value Control (If cell contain Null value, suppose reached end of range), d: delimiter

    Dim rngRow As Range
    Dim objStream As Object
    Dim i, lngFR, lngLR As Long 'lngFR: First Row, lngLR: Last Row

    lngFR = rngRange.SpecialCells(xlCellTypeVisible).Rows(1).row - rngRange.Rows(1).row + 1
    lngLR = rngRange.End(xlDown).row - rngRange.Rows(1).row + 1

    Set objStream = CreateObject("ADODB.Stream")
    objStream.Type = 2
    objStream.Charset = strCharset
    objStream.Open

    For i = lngFR To lngLR
        If Not (rngRange.Rows(i).EntireRow.Hidden) Then
            If IIf(NVC, (Cells(i + rngRange.Rows(1).row - 1, _
                rngRange.SpecialCells(xlCellTypeVisible).Columns(1).column).Value = vbNullString), False) Then Exit For
            objStream.WriteText CsvFormatRow(rngRange.Rows(i), strSeparator, strRowEnd)
        End If
    Next i

    objStream.SaveToFile strFileName, 2
    objStream.Close
End Sub 'CsvExportRange

Function CsvFormatRow(rngRow As Variant, strSeparator As String, strRowEnd As String) As String

    Dim arrCsvRow() As String

    ReDim arrCsvRow(rngRow.SpecialCells(xlCellTypeVisible).Cells.Count - 1)
    Dim rngCell As Range
    Dim lngIndex As Long

    lngIndex = 0

    For Each rngCell In rngRow.SpecialCells(xlCellTypeVisible).Cells
        arrCsvRow(lngIndex) = CsvFormatString(rngCell.Value, strSeparator)
        lngIndex = lngIndex + 1
    Next rngCell

    CsvFormatRow = Join(arrCsvRow, strSeparator) & strRowEnd

End Function 'CsvFormatRow

Function CsvFormatString(strRaw, strSeparator As String) As String

    Dim boolNeedsDelimiting As Boolean

    Dim strDelimiter, strDelimiterEscaped As String

    strDelimiter = """"
    strDelimiterEscaped = strDelimiter & strDelimiter

    boolNeedsDelimiting = InStr(1, strRaw, strDelimiter) > 0 _
        Or InStr(1, strRaw, chr(10)) > 0 _
        Or InStr(1, strRaw, strSeparator) > 0

    CsvFormatString = strRaw

    If boolNeedsDelimiting Then
        CsvFormatString = strDelimiter & _
            Replace(strRaw, strDelimiter, strDelimiterEscaped) & _
            strDelimiter
    End If

End Function 'CsvFormatString


问:
How to disable @Scheduled method via properties file?
I have a Spring scheduled method that is periodically run:

@Scheduled(cron = "${spring.cron.expression}")
public void demonJob() { ... }
```
<p>The cron expression is successfully read from the <code>application.properties</code>:</p>
<pre class="lang-none prettyprint-override"><code>spring.cron.expression=0 0 * * * *
</code>```

Now, I want to deploy my application to a special environment on which this particular scheduled method is not supposed to run. If I leave the cron property empty like this...

spring.cron.expression=
```
<p>... I get the following exception:</p>
<pre class="lang-none prettyprint-override"><code>Encountered invalid @Scheduled method 'demonJob': Cron expression must consist of 6 fields (found 0 in "")
</code>```

How can I disable the Scheduled method elegantly, ideally only by providing a different setting in application.properties?

答:
I could give another approach. Just redefine applicatino cron expression in any way to set unreachable time period. E.g. spring.cron.expression=1 1 1 1 1 ? (this is I use in my code and it is enough for me).

Profit of this approach is that you do not have to do any additional changes in the code.

Body:
I have a Spring scheduled method that is periodically run:

@Scheduled(cron = "${spring.cron.expression}")
public void demonJob() { ... }

The cron expression is successfully read from the application.properties:

spring.cron.expression=0 0 * * * *

Now, I want to deploy my application to a special environment on which this particular scheduled method is not supposed to run. If I leave the cron property empty like this...

spring.cron.expression=

... I get the following exception:

Encountered invalid @Scheduled method 'demonJob': Cron expression must consist of 6 fields (found 0 in "")

How can I disable the Scheduled method elegantly, ideally only by providing a different setting in application.properties?


问:
AJAX & jQuery - Form Data is being sent correctly, but not being inserted. Why?
i am try to insert data from $.ajax post

```<code><form action="" class="form-horizontal form-groups validate" enctype="multipart/from-data" id="validated_form" method="post" accept-charset="utf-8">

<div class="row">

    <div class="col-md-12">
        <div class="panel panel-default" data-collapsed="0">
            <div class="panel-heading">
                <div class="panel-title">
                    <i class="entypo-user"></i>  Customer Information              </div>
            </div>
            <div class="panel-body">

                <div class="col-sm-5">

                    <div class="form-group">
                        <label class="col-sm-3 control-label">SKU_No</label>
                        <div class="col-sm-8">
                            <div class="input-group">
                                <span class="input-group-addon"><i class="entypo-code"></i></span>
                                <input type="text" id="SKU_No" class="form-control" name="SKU_No"
                                    value="" required>
                            </div>
                        </div>
                    </div>
....................

    </form>
</code>```

My Parameters are going fine from form

this is My ajax call which is sending data

```<code>  $.ajax({
         data: data,
         type: "post",
         url: "Product_DB.php",
         success: function(data){
              alert(data);
         }
});
</code>```

this is my php file

```<code><?php
         if(isset($_POST["submit"])){
            $servername = "localhost";
            $username = "root";
            $password = "";
            $dbname = "pharmacy";

            // Create connection
            $conn = new mysqli($servername, $username, $password, $dbname);

            // Check connection
            if ($conn->connect_error) {
               die("Connection failed: " . $conn->connect_error);
            }

            $sql = "insert into `pharmacy`.`tblproduct` ( SKU_No, Batch_No, Strip_No, SAP_Code, Item_Name, Item_Qty, Purchase_Price, Deal%, Created_Date, Modified_Date, IsDeleted)
            values ('".$_POST["SKU_No"]."','".$_POST["Batch_No"]."' ,'".$_POST["Strip_No"]."' , '".$_POST["SAP_Code"]."','".$_POST["Item_Name"]."' ,'".$_POST["Qty"]."' ,'".$_POST["Purchase_Price"]."' , '".$_POST["Discount"]."','".date("Y-m-d")."' ,'".date("Y-m-d")."' ,'0' )";

            if (mysqli_query($conn, $sql)) {
               echo "New record created successfully";
            } else {
               echo "Error: " . $sql . "" . mysqli_error($conn);
            }
            $conn->close();
         }
      ?>
</code>```

in response I am not getting any msg or error .. the php file is not hitting .
I also try to
How can i track the issue ? Any Idea

答:
I think the issue is you're posting data to your php file and checking isset($_POST['submit']) which is surely not set. Try this

```<code>$.ajax({
         data: {'submit': data}, //Align your submit with the data your're posting
         type: "post",
         url: "Product_DB.php",
         success: function(data){
              alert(data);
         }
});
</code>```

Body:
i am try to insert data from $.ajax post

<form action="" class="form-horizontal form-groups validate" enctype="multipart/from-data" id="validated_form" method="post" accept-charset="utf-8">

                      Customer Information

                        SKU_No

                                <input type="text" id="SKU_No" class="form-control" name="SKU_No"
                                    value="" required>

....................

    </form>

My Parameters are going fine from form

this is My ajax call which is sending data

  $.ajax({
         data: data,
         type: "post",
         url: "Product_DB.php",
         success: function(data){
              alert(data);
         }
});

this is my php file

<?php
         if(isset($_POST["submit"])){
            $servername = "localhost";
            $username = "root";
            $password = "";
            $dbname = "pharmacy";

            // Create connection
            $conn = new mysqli($servername, $username, $password, $dbname);

            // Check connection
            if ($conn->connect_error) {
               die("Connection failed: " . $conn->connect_error);
            }

            $sql = "insert into `pharmacy`.`tblproduct` ( SKU_No, Batch_No, Strip_No, SAP_Code, Item_Name, Item_Qty, Purchase_Price, Deal%, Created_Date, Modified_Date, IsDeleted)
            values ('".$_POST["SKU_No"]."','".$_POST["Batch_No"]."' ,'".$_POST["Strip_No"]."' , '".$_POST["SAP_Code"]."','".$_POST["Item_Name"]."' ,'".$_POST["Qty"]."' ,'".$_POST["Purchase_Price"]."' , '".$_POST["Discount"]."','".date("Y-m-d")."' ,'".date("Y-m-d")."' ,'0' )";

            if (mysqli_query($conn, $sql)) {
               echo "New record created successfully";
            } else {
               echo "Error: " . $sql . "" . mysqli_error($conn);
            }
            $conn->close();
         }
      ?>

in response I am not getting any msg or error .. the php file is not hitting .
I also try to
How can i track the issue ? Any Idea

Body:
I think the issue is you're posting data to your php file and checking isset($_POST['submit']) which is surely not set. Try this

$.ajax({
         data: {'submit': data}, //Align your submit with the data your're posting
         type: "post",
         url: "Product_DB.php",
         success: function(data){
              alert(data);
         }
});


问:
Does TeeChart in javascript support multiple y-axes at the same time?
I am looking at TeeChart to create a time series line chart that can display multiple series with each series having its own y-axis. I would like all the axes on the same side and be visible at the same time. I have seen examples where the multiple vertical y-axes are stacked one above the other but I would like them to be standing side by side. I have provided an example.
Thanks in advance.

答:
You can see some examples about Axes at the online demo here.

And here an example trying to achieve what you are requiring:

var Chart, series, axis, nSeries;

function draw() {
  Chart = new Tee.Chart("canvas1");

  nSeries=4;
  Chart.panel.margins.left = 25;

  for (var i=0; i<nSeries; i++) {
    series = Chart.addSeries(new Tee.Line());
    series.addRandom();

    if (i==0)
      axis = Chart.axes.left;
    else {
      axis = Chart.axes.add(false,false);
      axis.position = -i*15;
      axis.grid.visible=false;
    }

    series.vertAxis=axis;

    axis.format.stroke.fill = series.format.fill;

  }

  Chart.draw();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <script src="http://www.steema.com/files/public/teechart/html5/latest/src/teechart.js" type="text/javascript"></script>
</head>

<body onload="draw()">
  <canvas id="canvas1" width="700" height="300">
    This browser does not seem to support HTML5 Canvas.
</canvas>
</body>

</html></code>```

Body:
You can see some examples about Axes at the online demo here.

And here an example trying to achieve what you are requiring:

var Chart, series, axis, nSeries;

function draw() {
  Chart = new Tee.Chart("canvas1");

  nSeries=4;
  Chart.panel.margins.left = 25;

  for (var i=0; i<nSeries; i++) {
    series = Chart.addSeries(new Tee.Line());
    series.addRandom();

    if (i==0)
      axis = Chart.axes.left;
    else {
      axis = Chart.axes.add(false,false);
      axis.position = -i*15;
      axis.grid.visible=false;
    }

    series.vertAxis=axis;

    axis.format.stroke.fill = series.format.fill;

  }

  Chart.draw();
}

<!DOCTYPE html>
<html lang="en">

<head>
  <script src="http://www.steema.com/files/public/teechart/html5/latest/src/teechart.js" type="text/javascript"></script>
</head>

<body onload="draw()">
  <canvas id="canvas1" width="700" height="300">
    This browser does not seem to support HTML5 Canvas.
</canvas>
</body>

</html>


问:
Webpack AngularJS Sourcemaps issue
I've been struggling with getting my source-maps working in my app for quite a while. I have set

```<code>devtool:  'source-map',
</code>```

in the webpack configuration, but they are still not available in the Chrome devtools.

I pushed a really simple app using my FE Stack hoping someone could identify the issue, whether it is with webpack, angular, or some other library. https://github.com/coreysnyder/Angular-Webpack3-Seed

Here are the versions I'm running:

```<code>{
  CoreyApp: '1.0.0',
  npm: '4.4.4',
  ares: '1.10.1-DEV',
  http_parser: '2.7.0',
  icu: '57.1',
  modules: '48',
  node: '6.9.0',
  openssl: '1.0.2j',
  uv: '1.9.1',
  v8: '5.1.281.84',
  zlib: '1.2.8'
}
OSX 10.12.6
</code>```

答:
I could fix your source maps for JS files, by adding the babel-loader. To do this, you need to install babel-loader:

```<code>npm i -D babel-loader@8.0.0-beta.0 @babel/core @babel/preset-env
</code>```

and then extend your rule for .js

```<code> rules: [
       {
         test: /\.js$/,
         exclude: /node_modules/,
         use: [
           {
             loader: 'ng-annotate-loader',
             options: { add: true, single_quotes: true }
           },
          {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env']
            }
          }
         ]
       }, [...]
 ]
</code>```

Ready further details on babel-loader github repo

Title: Webpack AngularJS Sourcemaps issue

Body:
I've been struggling with getting my source-maps working in my app for quite a while. I have set

devtool:  'source-map',

in the webpack configuration, but they are still not available in the Chrome devtools.

I pushed a really simple app using my FE Stack hoping someone could identify the issue, whether it is with webpack, angular, or some other library. https://github.com/coreysnyder/Angular-Webpack3-Seed

Here are the versions I'm running:

{
  CoreyApp: '1.0.0',
  npm: '4.4.4',
  ares: '1.10.1-DEV',
  http_parser: '2.7.0',
  icu: '57.1',
  modules: '48',
  node: '6.9.0',
  openssl: '1.0.2j',
  uv: '1.9.1',
  v8: '5.1.281.84',
  zlib: '1.2.8'
}
OSX 10.12.6

Body:
I could fix your source maps for JS files, by adding the babel-loader. To do this, you need to install babel-loader:

npm i -D babel-loader@8.0.0-beta.0 @babel/core @babel/preset-env

and then extend your rule for .js

 rules: [
       {
         test: /\.js$/,
         exclude: /node_modules/,
         use: [
           {
             loader: 'ng-annotate-loader',
             options: { add: true, single_quotes: true }
           },
          {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env']
            }
          }
         ]
       }, [...]
 ]

Ready further details on babel-loader github repo


问:
How can I make a function treat a whole sentence like one parameter?
How should I pass a sentence to function and make it behave like one parameter.

Example:

```<code>function Test ()
{
  echo $1
}
body="This the test"
Test $body
</code>```

I want output like this=> "This the test"  because of spaces it will print me Test only. What specific characters should i put to make whole sentence like one parameter. Thanks in advance.

答:
Thanks guys !!! work perfectly</p>

```<code>logmsg=" This is log message "
logger "$logmsg" 0
logger ()
{
      # mode=$(echo ${@:${#@}} ) #last from parameters
     mode=${@: -1}
     [ $mode -eq 2 ]  && return
     B=`[ $mode -eq 0 ] && echo $1 `
     F=`echo $1 > $LOG_FILE_DIRECTORY_PATH$LOG_FILE_NAME `
     echo ${B:-$F}
}
</code>```

Body:
How should I pass a sentence to function and make it behave like one parameter.

Example:

function Test ()
{
  echo $1
}
body="This the test"
Test $body

I want output like this=> "This the test"  because of spaces it will print me Test only. What specific characters should i put to make whole sentence like one parameter. Thanks in advance.

Body:
Thanks guys !!! work perfectly

logmsg=" This is log message "
logger "$logmsg" 0
logger ()
{
      # mode=$(echo ${@:${#@}} ) #last from parameters
     mode=${@: -1}
     [ $mode -eq 2 ]  && return
     B=`[ $mode -eq 0 ] && echo $1 `
     F=`echo $1 > $LOG_FILE_DIRECTORY_PATH$LOG_FILE_NAME `
     echo ${B:-$F}
}


问:
Customize Prompt Color for Pure Theme?
I'm currently using the Pure theme for zsh, but the default blue is really dark. Is it possible to change only the blue (i.e. I don't want to install zsh-syntax-highlighting)?

答:
As the color is set via %F{blue} inside the theme the exact color used for blue is set in your terminal (most probably).

So to change this color you need to check how to configure those colors for your terminal.

Just as an example here is a superuser answer for "How to set color terminal for iTerm2?"

Title: Customize Prompt Color for Pure Theme?


问:
Get the response of one controller in another controller in nodejs
I am facing an issue to get the response from one controller inside another controller.

How do I get the response from getUserAppointmentDetails.js to respondAppointment.js file

```<code>   getUserAppointmentDetails.js

   const con = require('./../database_connection');

   exports.getUserAppointmentDetails = function (req, res, next) {
       // const details = req.body;
       con.query('SELECT * from user_appointment_details WHERE id = 1', (err,
   respond) => {
           if (err) throw err;

           res.send({result: respond});
    });
   }

   Another file
   respondAppointment.js

   const con = require('./../database_connection');
   const userDetails = require('./getUserAppointmentDetails');

   exports.respondAppointment = function (req, res, next) {
       const details = req.body;
       con.query('update user_appointment_details SET status = "' + details.status
           + '" WHERE id = ' + details.id,
           (err, respond) => {
           if (err) throw err;

           res.send({result: respond});
    });

    var userData = userDetails.getUserAppointmentDetails(req, res, next);
    }
</code>```

Please respond if anyone has any idea.

答:
The problem here is that you are sending the response in both and not actually returning the result in callback from another function.

Assuming that you want the result of getUserAppointmentDetails.js in respondAppointment.js. Make the change in getUserAppointmentDetails.js and getUserAppointmentDetails.js to return the value to the calling function.

getUserAppointmentDetails.js

```<code> const con = require('./../database_connection');

   exports.getUserAppointmentDetails = function (idToGet) {
       // const details = req.body;
       con.query('SELECT * from user_appointment_details WHERE id = '+idToGet, (err,
   respond) => {
           if (err) throw err;

           return respond;
    });
   }
</code>```

Another file:
   respondAppointment.js

```<code>const con = require('./../database_connection');
   const userDetails = require('./getUserAppointmentDetails');

   exports.respondAppointment = function (req, res, next) {

   const details = req.body;

   var userData = userDetails.getUserAppointmentDetails(details.id);
    console.log(userData);

       con.query('update user_appointment_details SET status = "' + details.status
           + '" WHERE id = ' + details.id,
           (err, respond) => {
           if (err) throw err;

           res.send({result: respond});
    });

    }
</code>```

Body:
I am facing an issue to get the response from one controller inside another controller.

How do I get the response from getUserAppointmentDetails.js to respondAppointment.js file

   getUserAppointmentDetails.js

   const con = require('./../database_connection');

   exports.getUserAppointmentDetails = function (req, res, next) {
       // const details = req.body;
       con.query('SELECT * from user_appointment_details WHERE id = 1', (err,
   respond) => {
           if (err) throw err;

           res.send({result: respond});
    });
   }

   Another file
   respondAppointment.js

   const con = require('./../database_connection');
   const userDetails = require('./getUserAppointmentDetails');

   exports.respondAppointment = function (req, res, next) {
       const details = req.body;
       con.query('update user_appointment_details SET status = "' + details.status
           + '" WHERE id = ' + details.id,
           (err, respond) => {
           if (err) throw err;

           res.send({result: respond});
    });

    var userData = userDetails.getUserAppointmentDetails(req, res, next);
    }

Please respond if anyone has any idea.

Body:
The problem here is that you are sending the response in both and not actually returning the result in callback from another function.

Assuming that you want the result of getUserAppointmentDetails.js in respondAppointment.js. Make the change in getUserAppointmentDetails.js and getUserAppointmentDetails.js to return the value to the calling function.

getUserAppointmentDetails.js

 const con = require('./../database_connection');

   exports.getUserAppointmentDetails = function (idToGet) {
       // const details = req.body;
       con.query('SELECT * from user_appointment_details WHERE id = '+idToGet, (err,
   respond) => {
           if (err) throw err;

           return respond;
    });
   }

Another file:
   respondAppointment.js

const con = require('./../database_connection');
   const userDetails = require('./getUserAppointmentDetails');

   exports.respondAppointment = function (req, res, next) {

   const details = req.body;

   var userData = userDetails.getUserAppointmentDetails(details.id);
    console.log(userData);

       con.query('update user_appointment_details SET status = "' + details.status
           + '" WHERE id = ' + details.id,
           (err, respond) => {
           if (err) throw err;

           res.send({result: respond});
    });

    }


问:
How do i write in my txt file and append text below
I cant seem to have output appears in my .txt file.
I would like to append below the text file in future.

```<code>using namespace std;

int main()
{
    string month;
    int year;
    stringstream filename;

    cin >> month;
    cin >> year;

    filename << "Expenses_" << month << "_" << year << ".txt";
    ofstream myfile(filename.str());

    myfile.open(filename.str());
    myfile << "Hello World!";
    myfile.close();

    return 0;
}
</code>```

答:
Open your file as:

```<code>std::ofstream myfile(filename.str(), std::ofstream::out | std::ofstream::app);
</code>```

And passing the filename while creating the object of ofstream will open that file too, you don't need to call .open again.

Body:
I cant seem to have output appears in my .txt file.
I would like to append below the text file in future.

using namespace std;

int main()
{
    string month;
    int year;
    stringstream filename;

    cin >> month;
    cin >> year;

    filename << "Expenses_" << month << "_" << year << ".txt";
    ofstream myfile(filename.str());

    myfile.open(filename.str());
    myfile << "Hello World!";
    myfile.close();

    return 0;
}

Body:
Open your file as:

std::ofstream myfile(filename.str(), std::ofstream::out | std::ofstream::app);

And passing the filename while creating the object of ofstream will open that file too, you don't need to call .open again.


问:
GroupBy performs slowly
I have the following query and is super slow for 3000 records and produces 370 entries. How can I improve performance on it?</p>

```<code>dealerResults = _results.GroupBy(x => new { x.DealerName, x.DealerId })
                                      .Select(x => new MarketingReportResults()
                                      {
                                          DealerId = x.Key.DealerId,
                                          DealerName = x.Key.DealerName,
                                          LinkedTotal = linkedLeadCores.Count(y => y.DealerId == x.Key.DealerId),
                                          LeadsTotal = x.Count(),
                                          SalesTotal = x.Count(y => y.IsSold),
                                          Percent = (decimal)(x.Count() * 100) / count,
                                          ActiveTotal = x.Count(y => y.IsActive),
                                      }).ToList();
</code>```

答:
Doing a Group Join to linkedLeadCores will use an internal hash table for lookup and should solve your problem.

```<code>var dealerResults =
               (from r in _results.GroupBy(x => new { x.DealerName, x.DealerId })
               join llc in linkedLeadCores on r.Key.DealerId equals llc.DealerId into g
               select new MarketingReportResults()
               {
                  DealerId = r.Key.DealerId,
                  DealerName = r.Key.DealerName,
                  LinkedTotal = g.Count(),
                  LeadsTotal = r.Count(),
                  SalesTotal = r.Count(y => y.IsSold),
                  Percent = (decimal)(r.Count() * 100) / count,
                  ActiveTotal = r.Count(y => y.IsActive),
              }).ToList();
</code>```

Title: GroupBy performs slowly

Body:
I have the following query and is super slow for 3000 records and produces 370 entries. How can I improve performance on it?

dealerResults = _results.GroupBy(x => new { x.DealerName, x.DealerId })
                                      .Select(x => new MarketingReportResults()
                                      {
                                          DealerId = x.Key.DealerId,
                                          DealerName = x.Key.DealerName,
                                          LinkedTotal = linkedLeadCores.Count(y => y.DealerId == x.Key.DealerId),
                                          LeadsTotal = x.Count(),
                                          SalesTotal = x.Count(y => y.IsSold),
                                          Percent = (decimal)(x.Count() * 100) / count,
                                          ActiveTotal = x.Count(y => y.IsActive),
                                      }).ToList();

Body:
Doing a Group Join to linkedLeadCores will use an internal hash table for lookup and should solve your problem.

var dealerResults =
               (from r in _results.GroupBy(x => new { x.DealerName, x.DealerId })
               join llc in linkedLeadCores on r.Key.DealerId equals llc.DealerId into g
               select new MarketingReportResults()
               {
                  DealerId = r.Key.DealerId,
                  DealerName = r.Key.DealerName,
                  LinkedTotal = g.Count(),
                  LeadsTotal = r.Count(),
                  SalesTotal = r.Count(y => y.IsSold),
                  Percent = (decimal)(r.Count() * 100) / count,
                  ActiveTotal = r.Count(y => y.IsActive),
              }).ToList();


问:
SAPUI5: Binding Attributes of XMLModels
How is this done in OpenUI 5 / SAPUI5?

given the following

```<code><MainNavigation>
    <Link>
      <property name="Name">Clinical Overview</property>
      <property name="command">showTeachingPoints</property>
      <property name="autoSelect">true</property>
    </Link>
    <Link>
      <property name="command">showDevices</property>
      <property name="Name">Equipment</property>
    </Link>
</MainNavigation>
</code>```

And trying to fill out the text property for the following:

```<code><tnt:SideNavigation expanded="true" itemSelect="onItemSelect">
  <tnt:NavigationList id="sideMenu" items="{/MainNavigation/Link}">
    <tnt:NavigationListItem text="{property/[@name='Name']/text()}" />
  </tnt:NavigationList>
</tnt:SideNavigation>
</code>```

The goal should be to display the Name of each property (so Clinical Overview, Equipment, etc...) but the query is not working.

Also I've tried:

```<code>{property/[@name='Name']/text()}
{property/[name='Name']/text()}
{property/['@name='Name'']/text()}
{property[@name='Name']/text()}
</code>```

The only way that's worked has been

{property}

However that will only display whatever is first in the collection of property nodes. I want to know how to get at a specific node since I want to use the other nodes for different purposes (default selection, function callback names, etc...)

edited to clarify:

The list should contain:

```<code>Clinical Overview
Equipment
</code>```

Using {property/@name} the list would be:

```<code>Name
command
</code>```

Granted this is not what I'm looking for but it shares the same problem as {property} in that it returns only the first item under <Link> when I may want the second or third.

This xpath query works in other places /UI/MainNavigation/Link/property[@name='Name']/text() and I would just like to how to translate that into OpenUI.

答:
This should do the trick:

```<code><tnt:SideNavigation expanded="true" itemSelect="onItemSelect">
  <tnt:NavigationList id="sideMenu" items="{/MainNavigation/Link}">
    <tnt:NavigationListItem text="{property/@name}" />
  </tnt:NavigationList>
</tnt:SideNavigation>
</code>```

More info in the docs about Binding Path Syntax for XML Models.

For attributes, a special selector using the "@" character exists and "text()" can be used to reference the content text of an element. Lists are referenced by using the path to the multiple element.

BR Chris

Title: SAPUI5: Binding Attributes of XMLModels

Body:
How is this done in OpenUI 5 / SAPUI5?

given the following

<MainNavigation>
    <Link>
      <property name="Name">Clinical Overview</property>
      <property name="command">showTeachingPoints</property>
      <property name="autoSelect">true</property>
    </Link>
    <Link>
      <property name="command">showDevices</property>
      <property name="Name">Equipment</property>
    </Link>
</MainNavigation>

And trying to fill out the text property for the following:

<tnt:SideNavigation expanded="true" itemSelect="onItemSelect">
  <tnt:NavigationList id="sideMenu" items="{/MainNavigation/Link}">
    <tnt:NavigationListItem text="{property/[@name='Name']/text()}" />
  </tnt:NavigationList>
</tnt:SideNavigation>

The goal should be to display the Name of each property (so Clinical Overview, Equipment, etc...) but the query is not working.

Also I've tried:

{property/[@name='Name']/text()}
{property/[name='Name']/text()}
{property/['@name='Name'']/text()}
{property[@name='Name']/text()}

The only way that's worked has been

{property}

However that will only display whatever is first in the collection of property nodes. I want to know how to get at a specific node since I want to use the other nodes for different purposes (default selection, function callback names, etc...)

edited to clarify:

The list should contain:

Clinical Overview
Equipment

Using {property/@name} the list would be:

Name
command

Granted this is not what I'm looking for but it shares the same problem as {property} in that it returns only the first item under <Link> when I may want the second or third.

This xpath query works in other places /UI/MainNavigation/Link/property[@name='Name']/text() and I would just like to how to translate that into OpenUI.

Body:
This should do the trick:

<tnt:SideNavigation expanded="true" itemSelect="onItemSelect">
  <tnt:NavigationList id="sideMenu" items="{/MainNavigation/Link}">
    <tnt:NavigationListItem text="{property/@name}" />
  </tnt:NavigationList>
</tnt:SideNavigation>

More info in the docs about Binding Path Syntax for XML Models.

For attributes, a special selector using the "@" character exists and "text()" can be used to reference the content text of an element. Lists are referenced by using the path to the multiple element.

BR Chris


问:
Set spark.serializer to kryo with kryo.KryoException org.hibernate.LazyInitializationException
I get some entity from db with hibernate3 using Dao method(after the entity return, session is closed), and wrap it into a broadcast for all the executors. After setting spark.serializer to org.apache.spark.serializer.KryoSerializer, exception throw: KryoException org.hibernate.LazyInitializationException... no session or session was closed.
How should I get entity serialized without eager get all the value from db? Thanks a lot! </p>

答: I register the hibernate entity with javaSerilizer, and bypass the problem;</p>


问:
Buildroot plugin for eclipse-mars and up
I have followed the instructions in https://github.com/mbats/eclipse-buildroot-bundle/wiki/Tutorial-:-How-to-activate-and-install-the-Buildroot-Eclipse-plugin-%3F for installing the plugin.

Buildroot's server for eclipse plugins (https://buildroot.org/downloads/eclipse/) does'nt contain plugin for eclipse MARS version (v4.5).
I tried to install the 'Luna' version (v4.4) plugin but I got my toolchain list corrupted.

I tried starting-up eclipse with the -clean flag in the 'eclipse.ini' file but it didnt help either.

How can I make eclipse "register" buildroot plugin for eclipse versions higher than 4.4 ?

答: The plugin supports at most Eclipse Luna at the moment. Work is on-going to support higher versions.</p>


问:
I need to create a random number generator in php using mt_rand which should only generate random numbers
I need to create a random number generator in php using mt_rand which should only generate random numbers. I know I need to use an infinite loop. How can I achieve this?

This is what I've already tried:

```<code>$query = "SELECT * FROM random";
$result = mysqli_query($link,$query);
$rows = mysqli_num_rows($result);
for($j = 0; $j < $rows; ++$j) {
    $row=mysqli_fetch_assoc($result);
    if($row["randomcol"]==$a) {
    do {
        echo "\n fetched";
        echo $row["randomcol"];
        echo "\n generated";
        echo $a;
        echo "\n repetition";
        $a=mt_rand(1,10);
        echo "\n Just after regeneration";
        echo $a;
    } while ($row["randomcol"]==$a);
 }
}
</code>```

答:
Use rand() function.</p>

```<code>$random_number = rand(1000,99999); //random number between 1000 and 99999
</code>```

Body:
I need to create a random number generator in php using mt_rand which should only generate random numbers. I know I need to use an infinite loop. How can I achieve this?

This is what I've already tried:

$query = "SELECT * FROM random";
$result = mysqli_query($link,$query);
$rows = mysqli_num_rows($result);
for($j = 0; $j < $rows; ++$j) {
    $row=mysqli_fetch_assoc($result);
    if($row["randomcol"]==$a) {
    do {
        echo "\n fetched";
        echo $row["randomcol"];
        echo "\n generated";
        echo $a;
        echo "\n repetition";
        $a=mt_rand(1,10);
        echo "\n Just after regeneration";
        echo $a;
    } while ($row["randomcol"]==$a);
 }
}

Body:
Use rand() function.

$random_number = rand(1000,99999); //random number between 1000 and 99999


答:
Try it

```<code>DECLARE
  @MinDate date='20140601',
  @MaxDate date='20170531'

;WITH yearCTE AS(
  SELECT @MinDate StartDate,DATEADD(YEAR,1,@MinDate) EndDate

  UNION ALL

  SELECT EndDate,IIF(DATEADD(YEAR,1,EndDate)<@MaxDate,DATEADD(YEAR,1,EndDate),@MaxDate)
  -- if your version of SQLServer don't support IIF then use CASE
  --SELECT EndDate,CASE WHEN DATEADD(YEAR,1,EndDate)<@MaxDate THEN DATEADD(YEAR,1,EndDate) ELSE @MaxDate END
  FROM yearCTE
  WHERE EndDate<@MaxDate
)
SELECT StartDate,EndDate
--SELECT StartDate,DATEADD(DAY,-1,EndDate) EndDate
FROM yearCTE
OPTION(MAXRECURSION 0);
</code>```

Variant with DATEADD(DAY,365,...)

```<code>DECLARE
  @MinDate date='20140601',
  @MaxDate date='20170531'

;WITH yearCTE AS(
  SELECT @MinDate StartDate,DATEADD(DAY,365,@MinDate) EndDate

  UNION ALL

  SELECT EndDate,IIF(DATEADD(DAY,365,EndDate)<@MaxDate,DATEADD(DAY,365,EndDate),@MaxDate)
  -- if your version of SQLServer don't support IIF then use CASE
  --SELECT EndDate,CASE WHEN DATEADD(DAY,365,EndDate)<@MaxDate THEN DATEADD(DAY,365,EndDate) ELSE @MaxDate END
  FROM yearCTE
  WHERE EndDate<@MaxDate
)
SELECT StartDate,EndDate
--SELECT StartDate,DATEADD(DAY,-1,EndDate) EndDate
FROM yearCTE
OPTION(MAXRECURSION 0);
</code>```

Title: list date period between two date

Body:
I was wondering if there is way to use sql output list the date start date end by year + 1 interval(have leap year) like following:

Date_start      2014-06-01 00:00:00                   Date_End 2017-05-31 00:00:00

select '2014-06-01 00:00:00',dateadd(DAY, 365, '2014-06-01 00:00:00')

2014-06-01 00:00:00   2015-06-01 00:00:00

2015-06-01 00:00:00     2016-05-31 00:00:00

2016-05-31 00:00:00     2017-05-31 00:00:00

Body:
Try it

DECLARE
  @MinDate date='20140601',
  @MaxDate date='20170531'

;WITH yearCTE AS(
  SELECT @MinDate StartDate,DATEADD(YEAR,1,@MinDate) EndDate

  UNION ALL

  SELECT EndDate,IIF(DATEADD(YEAR,1,EndDate)<@MaxDate,DATEADD(YEAR,1,EndDate),@MaxDate)
  -- if your version of SQLServer don't support IIF then use CASE
  --SELECT EndDate,CASE WHEN DATEADD(YEAR,1,EndDate)<@MaxDate THEN DATEADD(YEAR,1,EndDate) ELSE @MaxDate END
  FROM yearCTE
  WHERE EndDate<@MaxDate
)
SELECT StartDate,EndDate
--SELECT StartDate,DATEADD(DAY,-1,EndDate) EndDate
FROM yearCTE
OPTION(MAXRECURSION 0);

Variant with DATEADD(DAY,365,...)

DECLARE
  @MinDate date='20140601',
  @MaxDate date='20170531'

;WITH yearCTE AS(
  SELECT @MinDate StartDate,DATEADD(DAY,365,@MinDate) EndDate

  UNION ALL

  SELECT EndDate,IIF(DATEADD(DAY,365,EndDate)<@MaxDate,DATEADD(DAY,365,EndDate),@MaxDate)
  -- if your version of SQLServer don't support IIF then use CASE
  --SELECT EndDate,CASE WHEN DATEADD(DAY,365,EndDate)<@MaxDate THEN DATEADD(DAY,365,EndDate) ELSE @MaxDate END
  FROM yearCTE
  WHERE EndDate<@MaxDate
)
SELECT StartDate,EndDate
--SELECT StartDate,DATEADD(DAY,-1,EndDate) EndDate
FROM yearCTE
OPTION(MAXRECURSION 0);


问:
Is there a quick way to remove using statements in C#?
Is there a quick way to determine whether you are using certain namespaces in your application. I want to remove all the unneccessary using statements like using System.Reflection and so on, but I need a way to determine if I am using those libraries or not. I know that the tool Resharper does this for you, but is there a quick and dirty and Free way to do this?</p>

答: Visual Studio 2008 + PowerCommmands = Remove and Sort usings across a whole solution.</p>

OwnerDisplayName: Jason

LastEditorDisplayName: Jorge

OwnerDisplayName: ajmastrean


问:
ajax success function not working kindly help me
just trying to pass some values from ajax to php file, but i am getting error function working ... kindly suggest me. my codes follows

```<code><script>
    function test(){
    //alert("hello");
    var myData ={
         name : $("#name").val(),
         email : $("#email").val(),
    };

    $.ajax({
    url: "test1.php",
    type: "POST",
    dataType:'json',
    data: {a: 155},
    success: function(data){
      console.log(data);
     },
    error : function(et){
      console.log("failed");
      alert(et);
 });
return false;}
</script>
</code>```

in console i can see vales are passing, i cant find the real solution for this help

答:
```<code>$( document ).ready( function test(){
  //alert("hello");
  var myData ={
    name : $("#name").val(),
    email : $("#email").val(),
  };

  $.ajax({
    url: "test1.php",
    type: "POST",
    dataType:'json',
    data: {a: 155}})

    .success (function(data){
      console.log(data);
    })

    .error ( function(et){
      console.log("failed");
      alert(et);
    })
});
</code>```

You had some wrong syntax + you need to tell your jquery when to execute. I set it on  $( document ).ready you can modify it for onClick or whatever you want. Ajax call is working tested it in my environment.

Body:
just trying to pass some values from ajax to php file, but i am getting error function working ... kindly suggest me. my codes follows

in console i can see vales are passing, i cant find the real solution for this help

Body:
$( document ).ready( function test(){
  //alert("hello");
  var myData ={
    name : $("#name").val(),
    email : $("#email").val(),
  };

  $.ajax({
    url: "test1.php",
    type: "POST",
    dataType:'json',
    data: {a: 155}})

    .success (function(data){
      console.log(data);
    })

    .error ( function(et){
      console.log("failed");
      alert(et);
    })
});

You had some wrong syntax + you need to tell your jquery when to execute. I set it on  $( document ).ready you can modify it for onClick or whatever you want. Ajax call is working tested it in my environment.


问:
Build NuGet package for .Net Standard 2.0 lib with Cake
I have created a class library based on .Net Standard 2.0 and I build the project/solution with Cake, but I cannot find how to build NuGet package for that library. NuGetPack doesn't work.</p>

答:
You really have two options.  NuGetPack will continue to work, I use this approach on a couple of Cake Addins that I maintain.  Could you explain more details about the issue that you are seeing?

The other option would be to use the DotNetCorePack alias.  You can see this in action in this file (which is part of the Cake.Recipe set of scripts):

https://github.com/cake-contrib/Cake.Recipe/blob/develop/Cake.Recipe/Content/nuget.cake

And it is also documented here:

https://cakebuild.net/api/Cake.Common.Tools.DotNetCore/DotNetCoreAliases/0F7A518E

```<code>var projects = GetFiles(BuildParameters.SourceDirectoryPath + "/**/*.csproj")
    - GetFiles(BuildParameters.SourceDirectoryPath + "/**/*.Tests.csproj");

var settings = new DotNetCorePackSettings {
    NoBuild = true,
    Configuration = BuildParameters.Configuration,
    OutputDirectory = BuildParameters.Paths.Directories.NuGetPackages,
    ArgumentCustomization = (args) => {
        if (BuildParameters.ShouldBuildNugetSourcePackage)
        {
            args.Append("--include-source");
        }
        return args
            .Append("/p:Version={0}", BuildParameters.Version.SemVersion)
            .Append("/p:AssemblyVersion={0}", BuildParameters.Version.Version)
            .Append("/p:FileVersion={0}", BuildParameters.Version.Version)
            .Append("/p:AssemblyInformationalVersion={0}", BuildParameters.Version.InformationalVersion);
    }
};

foreach (var project in projects)
{
    DotNetCorePack(project.ToString(), settings);
}
</code>```

Body:
You really have two options.  NuGetPack will continue to work, I use this approach on a couple of Cake Addins that I maintain.  Could you explain more details about the issue that you are seeing?

The other option would be to use the DotNetCorePack alias.  You can see this in action in this file (which is part of the Cake.Recipe set of scripts):

https://github.com/cake-contrib/Cake.Recipe/blob/develop/Cake.Recipe/Content/nuget.cake

And it is also documented here:

https://cakebuild.net/api/Cake.Common.Tools.DotNetCore/DotNetCoreAliases/0F7A518E

var projects = GetFiles(BuildParameters.SourceDirectoryPath + "/**/*.csproj")
    - GetFiles(BuildParameters.SourceDirectoryPath + "/**/*.Tests.csproj");

var settings = new DotNetCorePackSettings {
    NoBuild = true,
    Configuration = BuildParameters.Configuration,
    OutputDirectory = BuildParameters.Paths.Directories.NuGetPackages,
    ArgumentCustomization = (args) => {
        if (BuildParameters.ShouldBuildNugetSourcePackage)
        {
            args.Append("--include-source");
        }
        return args
            .Append("/p:Version={0}", BuildParameters.Version.SemVersion)
            .Append("/p:AssemblyVersion={0}", BuildParameters.Version.Version)
            .Append("/p:FileVersion={0}", BuildParameters.Version.Version)
            .Append("/p:AssemblyInformationalVersion={0}", BuildParameters.Version.InformationalVersion);
    }
};

foreach (var project in projects)
{
    DotNetCorePack(project.ToString(), settings);
}


问:
How to pass arguments to redux-saga
I am familiar with redux-thunk, and today I come to redux-saga, I know that when we want to handle asynchronous, with redux-saga, we need to call an actions as signal first and then sagas will handle and return success/fail actions, so, if I want to pass argument from react component ( pass search-value to search) but my first actions is just the signal, so, how to pass value to the action in charge, thank you</p>

答:
first actions is just the signal, so, how to pass value to the action in charge, thank you

In general case, redux action is custom-form object with mandatory field type, so it can carry enough information. Common use-case with redux-saga is emitting from React component action like MY_ACTION_REQUEST, which is intercepts with some saga process, performs asynchronous reaction and emit action like MY_ACTION_SUCCESS or MY_ACTION_FAIL, depending on successful state of operation.

If you are using some action creators, like bindActionCreators, just pass subsequent arguments into target action-creator function. You can see details in that answer: https://stackoverflow.com/a/44066279/7878274

Title: How to pass arguments to redux-saga


问:
Automate SAS program for different sites using %include
The problem I have is, I use the same program for reports on multiple sites. I have to run the code for each of them individually. I'm looking to automate my process to call the code and run for all sites in a go. This is the code I tried using but it is not working.

```<code>data _null_;
array sites {2} _temporary_ (SiteA SiteB);

do k = 1 to dim(sites);
    %let site = sites(k);

    %include '...path\SitesWait.sas';

end; run;
</code>```

The code in SiteWait works perfectly on its own. I defined a macro variable called site, which sets the site for the code to run.

The error I keep getting is 'ERROR 117-185: There was 1 unclosed DO block.'

Thanks

答:
So you wish to include different files based on prior dataset. I suggest you create the file instead of reading it from array, but keeping with the spirit of your initial request:

```<code>%let basePath= c:\foo;

data _NULL_;
    array sites {2} $5. ('SiteA' , 'SiteB');

    do k = 1 to dim(sites);
        site = sites(k);
        call execute('%nrstr(%put &basePath.\'||site||';)');
    end;
run;
</code>```

This produces

c:\foo\SiteA

c:\foo\SiteB

You can easily replace the %put command with %include to accomplish what you wish.

Edit: What I suggest you try to do instead is something like this:

```<code>data includes;
    format path $30. file $10.;
    input path $ file $;
    cards;
    c:\foo\ file1.sas
    c:\foo\ file2.sas
    c:\Bar\ file1.sas
    c:\Bar\ file2.sas
; run;

data _null_;
    set includes;
        call execute('%nrstr(%put '||strip(path)||''||strip(file)||';)');
run;
</code>```

Body:
The problem I have is, I use the same program for reports on multiple sites. I have to run the code for each of them individually. I'm looking to automate my process to call the code and run for all sites in a go. This is the code I tried using but it is not working.

data _null_;
array sites {2} _temporary_ (SiteA SiteB);

do k = 1 to dim(sites);
    %let site = sites(k);

    %include '...path\SitesWait.sas';

end; run;

The code in SiteWait works perfectly on its own. I defined a macro variable called site, which sets the site for the code to run.

The error I keep getting is 'ERROR 117-185: There was 1 unclosed DO block.'

Thanks

Body:
So you wish to include different files based on prior dataset. I suggest you create the file instead of reading it from array, but keeping with the spirit of your initial request:

%let basePath= c:\foo;

data _NULL_;
    array sites {2} $5. ('SiteA' , 'SiteB');

    do k = 1 to dim(sites);
        site = sites(k);
        call execute('%nrstr(%put &basePath.\'||site||';)');
    end;
run;

This produces

c:\foo\SiteA

c:\foo\SiteB

You can easily replace the %put command with %include to accomplish what you wish.

Edit: What I suggest you try to do instead is something like this:

data includes;
    format path $30. file $10.;
    input path $ file $;
    cards;
    c:\foo\ file1.sas
    c:\foo\ file2.sas
    c:\Bar\ file1.sas
    c:\Bar\ file2.sas
; run;

data _null_;
    set includes;
        call execute('%nrstr(%put '||strip(path)||''||strip(file)||';)');
run;


问:
f# Insert on MongoDB using Records
I've been trying for a while to insert on MongoDB using only records with no success.

My problem is that I want to create a simple insert function which I send a generic type and it is inserted into the database.

Like so.

```<code>let insert (value: 'a) =
    let collection = MongoClient().GetDatabase("db").GetCollection<'a> "col"
    collection.InsertOne value
</code>```

From this function, I tried inserting the following records.

```<code>// Error that it can't set the Id
type t1 = {
    Id: ObjectId
    Text: string
}
// Creates the record perfectly but doesn't generate a new Id
type t2 = {
    Id: string
    Text: string
}
// Creates the record and autogenerates the Id but doesn't insert the Text, and there are two Ids (_id, Id@)
type t3 = {
    mutable Id: ObjectId
    Text: string
}
// Creates the record and autogenerates the Id but for every property it generates two on MongoDB (_id, Id@, Text, Text@)
type t4 = {
    mutable Id: ObjectId
    mutable Text: string
}
</code>```

So does anyone can think of a solution for this or am I stuck having to use a class.

```<code>// Works!!!
type t5() =
    member val Id = ObjectId.Empty with get, set
    member val Name = ""  with get, set
</code>```

Also, does anyone has any Idea of why when the C# MongoDB library translates the mutable he gets the property with the @ at the end?
I would be fine with having all my properties set as mutable, although this wouldn't be my first choice, having he create multiple properties on the DB is quite bad.

答:
You could try annotating your records with CLIMutable (and no mutable fields).

The @s end up in the DB because MongoDB using reflection and F# implementing mutable with backing fields fieldName@

Title: f# Insert on MongoDB using Records

Body:
I've been trying for a while to insert on MongoDB using only records with no success.

My problem is that I want to create a simple insert function which I send a generic type and it is inserted into the database.

Like so.

let insert (value: 'a) =
    let collection = MongoClient().GetDatabase("db").GetCollection<'a> "col"
    collection.InsertOne value

From this function, I tried inserting the following records.

// Error that it can't set the Id
type t1 = {
    Id: ObjectId
    Text: string
}
// Creates the record perfectly but doesn't generate a new Id
type t2 = {
    Id: string
    Text: string
}
// Creates the record and autogenerates the Id but doesn't insert the Text, and there are two Ids (_id, Id@)
type t3 = {
    mutable Id: ObjectId
    Text: string
}
// Creates the record and autogenerates the Id but for every property it generates two on MongoDB (_id, Id@, Text, Text@)
type t4 = {
    mutable Id: ObjectId
    mutable Text: string
}

So does anyone can think of a solution for this or am I stuck having to use a class.

// Works!!!
type t5() =
    member val Id = ObjectId.Empty with get, set
    member val Name = ""  with get, set

Also, does anyone has any Idea of why when the C# MongoDB library translates the mutable he gets the property with the @ at the end?
I would be fine with having all my properties set as mutable, although this wouldn't be my first choice, having he create multiple properties on the DB is quite bad.


问:
using ggmap to plot points randomly distributed within boundaries of shape file
Is it possible to use ggplot2 / ggmap to plot geom_points randomly within a given spatial area defined by a shapefile?

I considered geom_jitter, however I need the plots to be randomly distributed and not cross spatial borders.

Sample data shamelessly borrowed from @matthiash here.

```<code>library(rgdal)
library(ggmap)

# Get shapefile with Drammen municipality borders
tmpzip<-tempfile()
tmpdir<-tempfile()
dir.create(tmpdir)
download.file("http://www.kartverket.no/Documents/Kart/N50-N5000%20Kartdata/33_N5000_shape.zip",tmpzip)
unzip(tmpzip, exdir=tmpdir)
kommune <- readOGR(dsn=tmpdir, layer="NO_AdminOmrader_pol")
kommune<-kommune[kommune$NAVN=="Drammen",]
kommune<-spTransform(kommune, CRS("+init=epsg:4326"))
dat<-fortify(kommune)

#get the base map
map <- get_map(location = "Drammen",
           maptype = "watercolor", source = "stamen", zoom = 11)
</code>```

Below code plots the base map with region id 154 from the shapefile plotted on top.

```<code>ggmap(map, extent = "normal", maprange = TRUE)+
 geom_polygon(data = dat,
           aes(long, lat, group = group),
           fill = "orange", colour = "red", alpha = 0.2)
</code>```

What I'd like to do is plot 10 points randomly within the shapefile region defined by dat$id==154

答:
Ok, I sorted it out. The solution is in spsample() in package "raster".

```<code>d<-data.frame(id=NA,x=NA,y=NA)
l<-data.frame(id=154,n=10)

for (i in unique(l$id)){
 temp<-spsample(kommune[which(kommune$OBJECTID==i),],n=l[l$id==i,"n"],type="random")
 temp<-as.data.frame(temp)
 temp$id<-i
 d<-rbind(d,temp[,c("id","x","y")])
}
d<-d[-1,] #drop the first empty row

ggmap(map, extent = "normal", maprange = T)+
  geom_polygon(data = dat,
           aes(long, lat, group = group),
           fill = "blue", colour = "yellow", alpha = 0.1)+
  geom_point(aes(x = x, y = y), data = d[which(d$id==154),], alpha = .9,show.legend = T)
</code>```

Body:
Is it possible to use ggplot2 / ggmap to plot geom_points randomly within a given spatial area defined by a shapefile?

I considered geom_jitter, however I need the plots to be randomly distributed and not cross spatial borders.

Sample data shamelessly borrowed from @matthiash here.

library(rgdal)
library(ggmap)

# Get shapefile with Drammen municipality borders
tmpzip<-tempfile()
tmpdir<-tempfile()
dir.create(tmpdir)
download.file("http://www.kartverket.no/Documents/Kart/N50-N5000%20Kartdata/33_N5000_shape.zip",tmpzip)
unzip(tmpzip, exdir=tmpdir)
kommune <- readOGR(dsn=tmpdir, layer="NO_AdminOmrader_pol")
kommune<-kommune[kommune$NAVN=="Drammen",]
kommune<-spTransform(kommune, CRS("+init=epsg:4326"))
dat<-fortify(kommune)

#get the base map
map <- get_map(location = "Drammen",
           maptype = "watercolor", source = "stamen", zoom = 11)

Below code plots the base map with region id 154 from the shapefile plotted on top.

ggmap(map, extent = "normal", maprange = TRUE)+
 geom_polygon(data = dat,
           aes(long, lat, group = group),
           fill = "orange", colour = "red", alpha = 0.2)

What I'd like to do is plot 10 points randomly within the shapefile region defined by dat$id==154

Body:
Ok, I sorted it out. The solution is in spsample() in package "raster".

d<-data.frame(id=NA,x=NA,y=NA)
l<-data.frame(id=154,n=10)

for (i in unique(l$id)){
 temp<-spsample(kommune[which(kommune$OBJECTID==i),],n=l[l$id==i,"n"],type="random")
 temp<-as.data.frame(temp)
 temp$id<-i
 d<-rbind(d,temp[,c("id","x","y")])
}
d<-d[-1,] #drop the first empty row

ggmap(map, extent = "normal", maprange = T)+
  geom_polygon(data = dat,
           aes(long, lat, group = group),
           fill = "blue", colour = "yellow", alpha = 0.1)+
  geom_point(aes(x = x, y = y), data = d[which(d$id==154),], alpha = .9,show.legend = T)