问:
Why does this sed command to match number not work?
My command is like this:

```<code>echo "12 cats" | sed 's/[0-9]+/Number/g'
</code>```

(I'm using the sed in vanilla Mac)

I expect the result to be:

```<code>Number cats
</code>```

However, the real result is:

```<code>12 cats
</code>```

Does anyone have ideas about this? Thanks!

答:
In a very mystic way that is not explained (at least in resources I have so far..),
You should check up the next terms:

globbing (in the context of bash),
regex,
extended regex

For your question it seems that the expr' you gave to sed is a regex or extended regex....so by a tutorial I read you should insert also the -r before your actual command in sed...

echo "12 cats" | sed -r 's/[0-9]+/Number/g'

Works for me in an Ubuntu 16.04 , bash.

Body:
My command is like this:

echo "12 cats" | sed 's/[0-9]+/Number/g'

(I'm using the sed in vanilla Mac)

I expect the result to be:

Number cats

However, the real result is:

12 cats

Does anyone have ideas about this? Thanks!


来源: stackexchange

问:
Plotting with pandas and matplotlib
I'm trying to create a scatter plot in Python. I have a dataframe 'df' with a specified category and x and y are column numbers:

```<code>groups = df.groupby(category)
fig, ax = plt.subplots()
for name, group in groups:
    ax.plot(x=group.iloc[:,x], y=group.iloc[:,y], marker='o', linestyle='',label=name)
fig = ax.get_figure()
fig.savefig(path)
</code>```

For some reason, I am getting an empty scatterplot -- Am I doing something wrong?

答:
ax.plot does not have x and y arguments.

The signature is Axes.plot(*args, **kwargs), meaning that x and y are simply positional arguments. If you specify x= and y= they will be treated as keyword arguments and ignored.

So remove x= and y= from the code,

```<code>ax.plot(group.iloc[:,x], group.iloc[:,y], marker='o', linestyle='',label=name)
</code>```

Complete example:

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"x":np.random.rand(40),
                   "y":np.random.rand(40),
                   "category": np.random.choice(list("ABCD"), size=40)})
category = "category"
x=1; y=2
groups = df.groupby(category)
fig, ax = plt.subplots()
for name, group in groups:
    ax.plot(group.iloc[:,x], group.iloc[:,y], marker='o', linestyle='',label=name)
fig = ax.get_figure()
#fig.savefig(path)
plt.show()
</code>```

ContentLicense: CC BY-SA 3.0

Title: Plotting with pandas and matplotlib

Body:
I'm trying to create a scatter plot in Python. I have a dataframe 'df' with a specified category and x and y are column numbers:

groups = df.groupby(category)
fig, ax = plt.subplots()
for name, group in groups:
    ax.plot(x=group.iloc[:,x], y=group.iloc[:,y], marker='o', linestyle='',label=name)
fig = ax.get_figure()
fig.savefig(path)

For some reason, I am getting an empty scatterplot -- Am I doing something wrong?

Body:
ax.plot does not have x and y arguments.

The signature is Axes.plot(*args, **kwargs), meaning that x and y are simply positional arguments. If you specify x= and y= they will be treated as keyword arguments and ignored.

So remove x= and y= from the code,

ax.plot(group.iloc[:,x], group.iloc[:,y], marker='o', linestyle='',label=name)

Complete example:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"x":np.random.rand(40),
                   "y":np.random.rand(40),
                   "category": np.random.choice(list("ABCD"), size=40)})
category = "category"
x=1; y=2
groups = df.groupby(category)
fig, ax = plt.subplots()
for name, group in groups:
    ax.plot(group.iloc[:,x], group.iloc[:,y], marker='o', linestyle='',label=name)
fig = ax.get_figure()
#fig.savefig(path)
plt.show()


问:
How to add an Extra button on Extjs grid header menu
has anybody had the need to add an extra button to the grid panel header menu(sorting\columns)?
potentially I would like to add another button to the menu that resets to the default columns model. I can accomplish this using Jquery but I was wondering if there is an EXTjs way to do it.

Thanks

答:
You need to dig through the source to see it's there, but a GridPanel has a view property which is its GridView which in turn has a hmenu property which is the menu it shows when you click on one of those column headers.

So, with a GridPanel called gridpanel (once it's rendered) you can do the following:

```<code>gridpanel.view.hmenu.add({
  text: 'reset',
  handler: function() {
    // reset magicks
  }
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You need to dig through the source to see it's there, but a GridPanel has a view property which is its GridView which in turn has a hmenu property which is the menu it shows when you click on one of those column headers.

So, with a GridPanel called gridpanel (once it's rendered) you can do the following:

gridpanel.view.hmenu.add({
  text: 'reset',
  handler: function() {
    // reset magicks
  }
});


问:
Why can foldr take a function with three arguments?
I was having a look at some list operations and came across !!:

```<code>(!!)                    :: [a] -> Int -> a
xs !! n
  | n < 0     = negIndex
  | otherwise = foldr (\x r k -> case k of
                                   0 -> x
                                   _ -> r (k-1)) tooLarge xs n
</code>```

The function (\x r k -> ...) has type a -> (Int -> a) -> Int -> a, but foldr takes a function that should only accept two arguments:

```<code>foldr            :: (a -> b -> b) -> b -> [a] -> b
foldr k z = go
          where
            go []     = z
            go (y:ys) = y `k` go ys
</code>```

Can someone explain to me why foldr accepts a function that takes 3 arguments with the following type a -> (Int -> a) -> Int -> a? Especially since the result should have the same type as the second argument?

答:
-> is right-associative. So a -> b -> c is a -> (b -> c). Therefore, your type

```<code>a -> (Int -> a) ->  Int -> a
</code>```

is the same as

```<code>a -> (Int -> a) -> (Int -> a)
</code>```

and  we can see that it fits foldr's type quite well.

Body:
I was having a look at some list operations and came across !!:

(!!)                    :: [a] -> Int -> a
xs !! n
  | n < 0     = negIndex
  | otherwise = foldr (\x r k -> case k of
                                   0 -> x
                                   _ -> r (k-1)) tooLarge xs n

The function (\x r k -> ...) has type a -> (Int -> a) -> Int -> a, but foldr takes a function that should only accept two arguments:

foldr            :: (a -> b -> b) -> b -> [a] -> b
foldr k z = go
          where
            go []     = z
            go (y:ys) = y `k` go ys

Can someone explain to me why foldr accepts a function that takes 3 arguments with the following type a -> (Int -> a) -> Int -> a? Especially since the result should have the same type as the second argument?

Body:
-> is right-associative. So a -> b -> c is a -> (b -> c). Therefore, your type

a -> (Int -> a) ->  Int -> a

is the same as

a -> (Int -> a) -> (Int -> a)

and  we can see that it fits foldr's type quite well.


问:
Autotools: using -D with variable works for all but one compile (C programming)
I am in the process of converting old autotools setup with a handwritten Makefile.in (and of-course a configure.in) to the latest (Makefile.am and configure.ac). Up to now things were looking fine, but I ran into something I cannot find the answer for in other questions.

I added a define in Makefile.am that is included in the compile of all c-modules I indicated in _SOURCES but one. I see absolutely no difference between the c-sources, except that the one where the define is not included in the compile is the main of the program.

Below the code for Makefile.am (relevant part):

```<code>bin_PROGRAMS = wpe we
lib_LTLIBRARIES = libxwpe-x11.la libxwpe-term.la
libxwpe_x11_la_SOURCES = we_xterm.c WeXterm.c
libxwpe_x11_la_CPPFLAGS = -DLIBRARY_DIR=\"@libdir@/xwpe\"
libxwpe_term_la_SOURCES = we_term.c
libxwpe_term_la_CPPFLAGS = -DLIBRARY_DIR=\"@libdir@/xwpe\"
wpe_SOURCES =   we_main.c we_block.c we_unix.c we_e_aus.c \
        we_edit.c we_fl_fkt.c we_fl_unix.c we_hfkt.c \
        we_menue.c we_mouse.c we_opt.c we_wind.c \
        we_prog.c we_progn.c we_debug.c WeString.c \
        WeSyntax.c WeExpArr.c WeLinux.c we_gpm.c
wpe_LDADD = libxwpe-x11.la libxwpe-term.la
wpe_CPPFLAGS = -DLIBRARY_DIR=\"@libdir@/xwpe\"
we_SOURCES =    we_main.c we_block.c we_unix.c we_e_aus.c \
        we_edit.c we_fl_fkt.c we_fl_unix.c we_hfkt.c \
        we_menue.c we_mouse.c we_opt.c we_wind.c \
        we_prog.c we_progn.c we_debug.c WeString.c \
        WeSyntax.c WeExpArr.c WeLinux.c we_gpm.c
</code>```

The result of the compile is that all c sources are compiled with the define of LIBRARY_DIR, except for we_main.c which is compiled without this define.

Does anyone have any idea what could cause this difference? What am I doing wrong? Should I not have defined wpe_CPPFLAGS but some other flag?

EDIT 1: Looking at the Makefile, I noticed that it compiles we_main multiple times! It create we-we_main.o, wpe-we_main.o and xwe-we_main.o. These files are all compiled correctly, but the only one I don't understand is the compilation of we_main.o which is compiled without the define. It looks like I am missing a flag that I should have defined. Probably I misunderstand the automake input in Makefile.am. Should I define an extra flag? If so, which one?

EDIT 2: Multiple compiles seems a bit wasteful. I am new to autotools, so there might be a better solution. If necessary I will pose a different query about this subject.

答:
I found the answer due to the observation in EDIT 1. First I used CPPFLAGS = -DLIBRARY_DIR=\"@libdir@/xwpe\".autoreconfwarned me to better useAM_CPPFLAGS`, so I did, and that solved the issue.

Additionally, I found I do not need all the program specific we_CPPFLAGS, wpe_CPPFLAGS and xwe_CPPFLAGS, because AM_CPPFLAGS adds to all.

So apparantly you only need specific xxx_CPPFLAGS if xxx is different from the other programs.

Sorry all to have bothered you. I hope this helps someone else who has the same query.

Edit 1: This change also removed the multiple compilations of the same sources. With hindsight, it makes sense: if the xxx_CPPFLAGS are specific to one program, then the program xxx needs to be separately compiled. If they all have the same flags, this is no longer necessary.

Body:
I am in the process of converting old autotools setup with a handwritten Makefile.in (and of-course a configure.in) to the latest (Makefile.am and configure.ac). Up to now things were looking fine, but I ran into something I cannot find the answer for in other questions.

I added a define in Makefile.am that is included in the compile of all c-modules I indicated in _SOURCES but one. I see absolutely no difference between the c-sources, except that the one where the define is not included in the compile is the main of the program.

Below the code for Makefile.am (relevant part):

bin_PROGRAMS = wpe we
lib_LTLIBRARIES = libxwpe-x11.la libxwpe-term.la
libxwpe_x11_la_SOURCES = we_xterm.c WeXterm.c
libxwpe_x11_la_CPPFLAGS = -DLIBRARY_DIR=\"@libdir@/xwpe\"
libxwpe_term_la_SOURCES = we_term.c
libxwpe_term_la_CPPFLAGS = -DLIBRARY_DIR=\"@libdir@/xwpe\"
wpe_SOURCES =   we_main.c we_block.c we_unix.c we_e_aus.c \
        we_edit.c we_fl_fkt.c we_fl_unix.c we_hfkt.c \
        we_menue.c we_mouse.c we_opt.c we_wind.c \
        we_prog.c we_progn.c we_debug.c WeString.c \
        WeSyntax.c WeExpArr.c WeLinux.c we_gpm.c
wpe_LDADD = libxwpe-x11.la libxwpe-term.la
wpe_CPPFLAGS = -DLIBRARY_DIR=\"@libdir@/xwpe\"
we_SOURCES =    we_main.c we_block.c we_unix.c we_e_aus.c \
        we_edit.c we_fl_fkt.c we_fl_unix.c we_hfkt.c \
        we_menue.c we_mouse.c we_opt.c we_wind.c \
        we_prog.c we_progn.c we_debug.c WeString.c \
        WeSyntax.c WeExpArr.c WeLinux.c we_gpm.c

The result of the compile is that all c sources are compiled with the define of LIBRARY_DIR, except for we_main.c which is compiled without this define.

Does anyone have any idea what could cause this difference? What am I doing wrong? Should I not have defined wpe_CPPFLAGS but some other flag?

EDIT 1: Looking at the Makefile, I noticed that it compiles we_main multiple times! It create we-we_main.o, wpe-we_main.o and xwe-we_main.o. These files are all compiled correctly, but the only one I don't understand is the compilation of we_main.o which is compiled without the define. It looks like I am missing a flag that I should have defined. Probably I misunderstand the automake input in Makefile.am. Should I define an extra flag? If so, which one?

EDIT 2: Multiple compiles seems a bit wasteful. I am new to autotools, so there might be a better solution. If necessary I will pose a different query about this subject.


问:
Virtual functions and performance - C++
In my class design, I use abstract classes and virtual functions extensively. I had a  feeling that virtual functions affects the performance. Is this true? But I think this performance difference is not noticeable and looks like I am doing premature optimization. Right?</p>

答: Yes, you're right and if you curious about the cost of virtual function call you might find this post interesting.</p>

OwnerDisplayName: Appu

Title: Virtual functions and performance - C++

LastEditorDisplayName: Serge

OwnerDisplayName: Serge


问:
Correct way to use DynamoDB Optimistic Locking
I'm trying to understand if DynamoDB Optimistic Locking is the correct thing for my use case or should I be doing something else.

I'm trying to do the following in my Java method.

```<code>function updateItem(String key) {
    Item item = mapper.load(Item.class, key);
    if (some condition) {
        item.setValue(item.getValue() + 1);
        mapper.save(item);
    }
 }
</code>```

I want to update the same item based on some condition succeeding. I've created a version attribute, so that Optimistic locking works and when I have multiple requests coming in, only one request gets and updates the data.

I'm trying to understand the following:

What happens when some other thread tries to update the value but the version id has changed, I couldn't find any documentation on what exception will be thrown?

Should I be using a synchronized function for this? Considering multiple requests will be coming in? But, to me this seems like it defeats the purpose of optimistic locking, since I don't care which request gets access first.

Is there an alternate solution to this problem?

I've been through the following documentation:
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptimisticLocking.html

答:
If you need to guarantee that all multiple requests (from different threads / servers) were applied, you could use the following implementation of optimistic locking:

```<code>public void updateItem(String key) {
    while (true) {
        try {
            Item item = dynamoDBMapper.load(Item.class, key);
            if (some condition) {
                item.setValue(item.getValue() + 1);
                dynamoDBMapper.save(item);
            }
            break;
        } catch (ConditionalCheckFailedException e) {
            System.out.println("ConditionalCheckFailedException. Retrying again...");
        }
    }
}
</code>```

Here if item has already been updated by another request, we will receive ConditionalCheckFailedException and trying one more time until changes will be applied.

ConditionalCheckFailedException - this exception is thrown when an expected value does not match what was found in the system (database). This exception will be thrown:

if you use optimistic locking with @DynamoDBVersionAttribute, and version value on the server is different from value on the client side;

if you specify your own conditional constraints while saving / deleting data using dynamoDBMapper with DynamoDBSaveExpression / DynamoDBDeleteExpression and these constraints are failed.

Regarding @Nawaz question, if you haven’t specified your own conditional constraints (using DynamoDBSaveExpression and DynamoDBDeleteExpression), this exception is due to changed version.  If you catch ConditionalCheckFailedException, you will have the following information:

```<code>requestId = …
errorCode = ConditionalCheckFailedException
errorType = {AmazonServiceException$ErrorType} "Client"
errorMessage = The conditional request failed
statusCode = 400
serviceName = AmazonDynamoDBv2
</code>```

Body:
I'm trying to understand if DynamoDB Optimistic Locking is the correct thing for my use case or should I be doing something else.

I'm trying to do the following in my Java method.

function updateItem(String key) {
    Item item = mapper.load(Item.class, key);
    if (some condition) {
        item.setValue(item.getValue() + 1);
        mapper.save(item);
    }
 }

I want to update the same item based on some condition succeeding. I've created a version attribute, so that Optimistic locking works and when I have multiple requests coming in, only one request gets and updates the data.

I'm trying to understand the following:

What happens when some other thread tries to update the value but the version id has changed, I couldn't find any documentation on what exception will be thrown?

Should I be using a synchronized function for this? Considering multiple requests will be coming in? But, to me this seems like it defeats the purpose of optimistic locking, since I don't care which request gets access first.

Is there an alternate solution to this problem?

I've been through the following documentation:
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptimisticLocking.html

Body:
If you need to guarantee that all multiple requests (from different threads / servers) were applied, you could use the following implementation of optimistic locking:

public void updateItem(String key) {
    while (true) {
        try {
            Item item = dynamoDBMapper.load(Item.class, key);
            if (some condition) {
                item.setValue(item.getValue() + 1);
                dynamoDBMapper.save(item);
            }
            break;
        } catch (ConditionalCheckFailedException e) {
            System.out.println("ConditionalCheckFailedException. Retrying again...");
        }
    }
}

Here if item has already been updated by another request, we will receive ConditionalCheckFailedException and trying one more time until changes will be applied.

ConditionalCheckFailedException - this exception is thrown when an expected value does not match what was found in the system (database). This exception will be thrown:

if you use optimistic locking with @DynamoDBVersionAttribute, and version value on the server is different from value on the client side;

if you specify your own conditional constraints while saving / deleting data using dynamoDBMapper with DynamoDBSaveExpression / DynamoDBDeleteExpression and these constraints are failed.

Regarding @Nawaz question, if you haven’t specified your own conditional constraints (using DynamoDBSaveExpression and DynamoDBDeleteExpression), this exception is due to changed version.  If you catch ConditionalCheckFailedException, you will have the following information:

requestId = …
errorCode = ConditionalCheckFailedException
errorType = {AmazonServiceException$ErrorType} "Client"
errorMessage = The conditional request failed
statusCode = 400
serviceName = AmazonDynamoDBv2


问:
Strange problems with ConstraintLayout and Toolbar
I've got some problems. with Costraint Layout and Toolbar. I upload some images to explain better what happens. I can't do nothing. If I add a new button It doesn't show it. I don't know if it is a normal situation, but if you have a solution, please, help me.
Thanks in advance

enter image description here

答:
Change your ConstraintLayout to RelativeLayout and then add below code and see what happens:

```<code>android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
</code>```

Body:
Change your ConstraintLayout to RelativeLayout and then add below code and see what happens:

android:layout_centerHorizontal="true"
android:layout_centerVertical="true"


问:
Swift 3 - Limit number of characters in uitextview
I am giving a text view to tweet some string .

I am applying the following method to restrict the number of characters to 140 in length.

code in a viewController

```<code>import UIKit
import SVProgressHUD
import Toaster

class ViewController: UIViewController , UITextViewDelegate ,
UITextFieldDelegate {

var checktoaster = false
@IBOutlet weak var txtDescription: UITextView!

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if txtDescription == textView
    {
        guard let tex = textView.text else { return true }
        let newLength = tex.characters.count + text.characters.count - range.length
        if !(newLength <= 140)
        {
            if checktoaster == false
            {
                checktoaster = true
                let toast = Toast(text: "You have write only 140 character.", duration: Delay.long)
                toast.show()
            }
        }
        else
        {
            checktoaster = false
        }
        return newLength <= 140 //Bool
     }
    return true

     }

}
</code>```

here is The textView class

```<code>import UIKit
public class LetsTextView : UITextView , UITextViewDelegate{

required public init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    NotificationCenter.default.addObserver(self, selector: #selector(LetsTextView.refreshPlaceholder), name: NSNotification.Name.UITextViewTextDidChange, object: self)
}

override init(frame: CGRect, textContainer: NSTextContainer?) {
    super.init(frame: frame, textContainer: textContainer)
    NotificationCenter.default.addObserver(self, selector: #selector(LetsTextView.refreshPlaceholder), name: NSNotification.Name.UITextViewTextDidChange, object: self)
}

override public func awakeFromNib() {
    super.awakeFromNib()
    NotificationCenter.default.addObserver(self, selector: #selector(LetsTextView.refreshPlaceholder), name: NSNotification.Name.UITextViewTextDidChange, object: self)
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

@IBInspectable  public var placeholder : String? {

    get {

        return placeholderLabel?.text
    }

    set {

        if placeholderLabel == nil {
            var frm = self.bounds.insetBy(dx: 5, dy: 6)
            frm.size.height = 20
            placeholderLabel = UILabel(frame:frm)

            if let unwrappedPlaceholderLabel = placeholderLabel {

                unwrappedPlaceholderLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight]
                unwrappedPlaceholderLabel.lineBreakMode = .byWordWrapping
                unwrappedPlaceholderLabel.numberOfLines = 0
                unwrappedPlaceholderLabel.font = self.font
                unwrappedPlaceholderLabel.backgroundColor = UIColor.clear
                unwrappedPlaceholderLabel.textColor = UIColor.gray//UIColor(red: 255/255, green: 190/255, blue: 70/255, alpha: 1.0)
                unwrappedPlaceholderLabel.alpha = 0
                addSubview(unwrappedPlaceholderLabel)
            }
        }

        placeholderLabel?.text = newValue
        refreshPlaceholder()
    }
}

func refreshPlaceholder() {

    if text.characters.count != 0 {
        placeholderLabel?.alpha = 0
    } else {
        placeholderLabel?.alpha = 1
    }
}

override public var text: String! {

    didSet {

        refreshPlaceholder()

    }
}

override public var font : UIFont? {

    didSet {

        if let unwrappedFont = font {
            placeholderLabel?.font = unwrappedFont
        } else {
            placeholderLabel?.font = UIFont.systemFont(ofSize: 12)
        }
    }
}

override public var delegate : UITextViewDelegate? {

    get {
        refreshPlaceholder()
        return super.delegate
    }

    set {

    }
  }

}
</code>```

//
Any solution please

答:
```<code> func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if txtTwitt.text.characters.count <= 140
        {
            // Code here
        }
        else
        {
            //Code Here
        }
        return true
    }
</code>```

Body:
I am giving a text view to tweet some string .

I am applying the following method to restrict the number of characters to 140 in length.

code in a viewController

import UIKit
import SVProgressHUD
import Toaster

class ViewController: UIViewController , UITextViewDelegate ,
UITextFieldDelegate {

var checktoaster = false
@IBOutlet weak var txtDescription: UITextView!

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if txtDescription == textView
    {
        guard let tex = textView.text else { return true }
        let newLength = tex.characters.count + text.characters.count - range.length
        if !(newLength <= 140)
        {
            if checktoaster == false
            {
                checktoaster = true
                let toast = Toast(text: "You have write only 140 character.", duration: Delay.long)
                toast.show()
            }
        }
        else
        {
            checktoaster = false
        }
        return newLength <= 140 //Bool
     }
    return true

     }

}

here is The textView class

import UIKit
public class LetsTextView : UITextView , UITextViewDelegate{

required public init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    NotificationCenter.default.addObserver(self, selector: #selector(LetsTextView.refreshPlaceholder), name: NSNotification.Name.UITextViewTextDidChange, object: self)
}

override init(frame: CGRect, textContainer: NSTextContainer?) {
    super.init(frame: frame, textContainer: textContainer)
    NotificationCenter.default.addObserver(self, selector: #selector(LetsTextView.refreshPlaceholder), name: NSNotification.Name.UITextViewTextDidChange, object: self)
}

override public func awakeFromNib() {
    super.awakeFromNib()
    NotificationCenter.default.addObserver(self, selector: #selector(LetsTextView.refreshPlaceholder), name: NSNotification.Name.UITextViewTextDidChange, object: self)
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

@IBInspectable  public var placeholder : String? {

    get {

        return placeholderLabel?.text
    }

    set {

        if placeholderLabel == nil {
            var frm = self.bounds.insetBy(dx: 5, dy: 6)
            frm.size.height = 20
            placeholderLabel = UILabel(frame:frm)

            if let unwrappedPlaceholderLabel = placeholderLabel {

                unwrappedPlaceholderLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight]
                unwrappedPlaceholderLabel.lineBreakMode = .byWordWrapping
                unwrappedPlaceholderLabel.numberOfLines = 0
                unwrappedPlaceholderLabel.font = self.font
                unwrappedPlaceholderLabel.backgroundColor = UIColor.clear
                unwrappedPlaceholderLabel.textColor = UIColor.gray//UIColor(red: 255/255, green: 190/255, blue: 70/255, alpha: 1.0)
                unwrappedPlaceholderLabel.alpha = 0
                addSubview(unwrappedPlaceholderLabel)
            }
        }

        placeholderLabel?.text = newValue
        refreshPlaceholder()
    }
}

func refreshPlaceholder() {

    if text.characters.count != 0 {
        placeholderLabel?.alpha = 0
    } else {
        placeholderLabel?.alpha = 1
    }
}

override public var text: String! {

    didSet {

        refreshPlaceholder()

    }
}

override public var font : UIFont? {

    didSet {

        if let unwrappedFont = font {
            placeholderLabel?.font = unwrappedFont
        } else {
            placeholderLabel?.font = UIFont.systemFont(ofSize: 12)
        }
    }
}

override public var delegate : UITextViewDelegate? {

    get {
        refreshPlaceholder()
        return super.delegate
    }

    set {

    }
  }

}

//
Any solution please


问:
Swift 3 - store the User Location and call it from different View Controllers
I'm pretty new in programming and this is my first app, so sorry if the approach is very shabby.

I created a helper method to get the user location, because I need to call it from different view controllers so I thought this was a cleaner way to do it. But I don't know why is not working now (no errors, it just show the general view of Europe). But when it was inside the view controller it worked perfectly fine.

I got this new approach from the course I'm doing and I've been researching in many sources. I've also checked this question but I didn't find any solution yet.

Here is the method I created in the GMSClient file. It will get the user location, but if the user disables this option, it will show the default position (centred in Berlin):

```<code>    extension GMSClient: CLLocationManagerDelegate {

    //MARK: Initial Location: Berlin

    func setDefaultInitialLocation(_ map: GMSMapView) {
        let camera = GMSCameraPosition.camera(withLatitude: 52.520736, longitude: 13.409423, zoom: 8)
        map.camera = camera

        let initialLocation = CLLocationCoordinate2DMake(52.520736, 13.409423)
        let marker = GMSMarker(position: initialLocation)
        marker.title = "Berlin"
        marker.map = map

    }

    //MARK: Get user location

    func getUserLocation(_ map: GMSMapView,_ locationManager: CLLocationManager) {

        var userLocation: String?

        locationManager.requestWhenInUseAuthorization()

        func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

            if status == .authorizedWhenInUse {
                locationManager.startUpdatingLocation()

                map.isMyLocationEnabled = true
                map.settings.myLocationButton = true

            } else {
                setDefaultInitialLocation(map)
            }
        }

        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

            if let location = locations.first {

                map.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)

                locationManager.stopUpdatingLocation()

                //Store User Location
                userLocation = "\(location.coordinate.latitude), \(location.coordinate.longitude)"
                print("userLocation is: \((userLocation) ?? "No user Location")")

            }
        }
    }
}
</code>```

This file has also this singelton:

```<code>// MARK: Shared Instance

    class func sharedInstance() -> GMSClient {
        struct Singleton {
            static var sharedInstance = GMSClient()
        }
        return Singleton.sharedInstance
    }
</code>```

And then I call it in my view controller like this:

```<code>class MapViewController: UIViewController, CLLocationManagerDelegate {

    // MARK: Outlets

    @IBOutlet weak var mapView: GMSMapView!

    // MARK: Properties

    let locationManager = CLLocationManager()
    var userLocation: String?
    let locationManagerDelegate = GMSClient()

    // MARK: Life Cycle

    override func viewDidLoad() {

        super.viewDidLoad()

        self.locationManager.delegate = locationManagerDelegate

        GMSClient.sharedInstance().getUserLocation(mapView, locationManager)

    }
</code>```

Anyone has an idea of what can be wrong?

Thanks!

答:
I guess the problem is here,

```<code>self.locationManager.delegate = locationManagerDelegate
</code>```

You have created a new instance of GMSClient, and saved it in the stored property and that instance is set as the delegate property of CLLocationManager.

You need to do this instead,

```<code>self.locationManager.delegate = GMSClient.sharedInstance()
</code>```

You need to do this because you would want singleton instance of GMSClient to be the delegate for CLLocationManager and not a new instance. That way your singleton class would recieve the callbacks from
CLLocationManager class.

To understand more about why your code was not working, I would suggest you read more about Objects, Instances, Instance variables, Singletons, Delegate design pattern.

Body:
I'm pretty new in programming and this is my first app, so sorry if the approach is very shabby.

I created a helper method to get the user location, because I need to call it from different view controllers so I thought this was a cleaner way to do it. But I don't know why is not working now (no errors, it just show the general view of Europe). But when it was inside the view controller it worked perfectly fine.

I got this new approach from the course I'm doing and I've been researching in many sources. I've also checked this question but I didn't find any solution yet.

Here is the method I created in the GMSClient file. It will get the user location, but if the user disables this option, it will show the default position (centred in Berlin):

    extension GMSClient: CLLocationManagerDelegate {

    //MARK: Initial Location: Berlin

    func setDefaultInitialLocation(_ map: GMSMapView) {
        let camera = GMSCameraPosition.camera(withLatitude: 52.520736, longitude: 13.409423, zoom: 8)
        map.camera = camera

        let initialLocation = CLLocationCoordinate2DMake(52.520736, 13.409423)
        let marker = GMSMarker(position: initialLocation)
        marker.title = "Berlin"
        marker.map = map

    }

    //MARK: Get user location

    func getUserLocation(_ map: GMSMapView,_ locationManager: CLLocationManager) {

        var userLocation: String?

        locationManager.requestWhenInUseAuthorization()

        func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

            if status == .authorizedWhenInUse {
                locationManager.startUpdatingLocation()

                map.isMyLocationEnabled = true
                map.settings.myLocationButton = true

            } else {
                setDefaultInitialLocation(map)
            }
        }

        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

            if let location = locations.first {

                map.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)

                locationManager.stopUpdatingLocation()

                //Store User Location
                userLocation = "\(location.coordinate.latitude), \(location.coordinate.longitude)"
                print("userLocation is: \((userLocation) ?? "No user Location")")

            }
        }
    }
}

This file has also this singelton:

// MARK: Shared Instance

    class func sharedInstance() -> GMSClient {
        struct Singleton {
            static var sharedInstance = GMSClient()
        }
        return Singleton.sharedInstance
    }

And then I call it in my view controller like this:

class MapViewController: UIViewController, CLLocationManagerDelegate {

    // MARK: Outlets

    @IBOutlet weak var mapView: GMSMapView!

    // MARK: Properties

    let locationManager = CLLocationManager()
    var userLocation: String?
    let locationManagerDelegate = GMSClient()

    // MARK: Life Cycle

    override func viewDidLoad() {

        super.viewDidLoad()

        self.locationManager.delegate = locationManagerDelegate

        GMSClient.sharedInstance().getUserLocation(mapView, locationManager)

    }

Anyone has an idea of what can be wrong?

Thanks!

Body:
I guess the problem is here,

self.locationManager.delegate = locationManagerDelegate

You have created a new instance of GMSClient, and saved it in the stored property and that instance is set as the delegate property of CLLocationManager.

You need to do this instead,

self.locationManager.delegate = GMSClient.sharedInstance()

You need to do this because you would want singleton instance of GMSClient to be the delegate for CLLocationManager and not a new instance. That way your singleton class would recieve the callbacks from
CLLocationManager class.

To understand more about why your code was not working, I would suggest you read more about Objects, Instances, Instance variables, Singletons, Delegate design pattern.


问:
Restart Delphi Application Programmatically
It should not be possible to run multiple instances of my application. Therefore the project source contains:

```<code>CreateMutex (nil, False, PChar (ID));
if (GetLastError = ERROR_ALREADY_EXISTS) then
  Halt;
</code>```

Now I want to restart my application programmatically. The usual way would be:

```<code>AppName := PChar(Application.ExeName) ;
ShellExecute(Handle,'open', AppName, nil, nil, SW_SHOWNORMAL) ;
Application.Terminate;
</code>```

But this won't work in my case because of the mutex. Even if I release the mutex before starting the second instace it won't work because shutdown takes some time and two instance cannot run in parallel (because of common resources and other effects).

Is there a way to restart an application with such characteristics? (If possible without an additional executable)

Thanks in advance.

答:
hi take a look a the following article by Zarko Gajic - there you will get some ideas, sample code and even a whole component to use.

hth,
reinhard

Body:
It should not be possible to run multiple instances of my application. Therefore the project source contains:

CreateMutex (nil, False, PChar (ID));
if (GetLastError = ERROR_ALREADY_EXISTS) then
  Halt;

Now I want to restart my application programmatically. The usual way would be:

AppName := PChar(Application.ExeName) ;
ShellExecute(Handle,'open', AppName, nil, nil, SW_SHOWNORMAL) ;
Application.Terminate;

But this won't work in my case because of the mutex. Even if I release the mutex before starting the second instace it won't work because shutdown takes some time and two instance cannot run in parallel (because of common resources and other effects).

Is there a way to restart an application with such characteristics? (If possible without an additional executable)

Thanks in advance.


问:
How to calculate form fields values to update hidden field value?
I want to know how to calculate the input values of the following fields

```<code><input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
</code>```

And update the span text and the hidden field value

```<code>TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
</code>```

Thanks in advance

答:
I post this as an answer because the comment areas are to small

At first i think it´s an good idea to write

```<code><input type  = "number">
</code>```

when you don´t want to display the small arrows look at this solution:

https://css-tricks.com/snippets/css/turn-off-number-input-spinners/

the keyup event ist the best way to "live" display the total sum

At last take a look at vue.js

This is the best solution for this scenario.

Body:
I want to know how to calculate the input values of the following fields

<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">

And update the span text and the hidden field value

TOTAL 0
<input id="total" type="hidden" name="total" value="">

Thanks in advance

Body:
I post this as an answer because the comment areas are to small

At first i think it´s an good idea to write

<input type  = "number">

when you don´t want to display the small arrows look at this solution:

https://css-tricks.com/snippets/css/turn-off-number-input-spinners/

the keyup event ist the best way to "live" display the total sum

At last take a look at vue.js

This is the best solution for this scenario.


问:
Struggling with a UnhandledPromiseRejectionWarning
I'm struggling to see where the promise rejection is emerging in the following:

```<code>MongoClient.connect(mongourl)
    .then(db => {
        console.log("making promises:", typeof lib.getAllData)
        // let promises = packages.map(repo => lib.getAllData(db, repo));
        let promises = [];
        console.log("making promises2")
        // return getAllData(db, packages[0])
        return Promise.all(promises)
            .then(results => {
                console.log("RAW RES", results);
                let missing = results.filter(r => r.error).map(r => r.error)
                return (db, missing);
            })
            // Should never fail as getAllData always resolves
            .catch(err => {
                console.log("err1", err);
                return Promise.reject({db, err})
            });
    }).then(({db, results}) => {
        console.log("RES: ", results);
        db.close();
    }).catch(({db, err}) => {
        console.log("Final Err:", err);
        db.close();
    });
</code>```

What I see in the console is

```<code>making promises: function
making promises2
RAW RES []
RES:  undefined
Final Err: undefined
(node:7026) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'close' of undefined
(node:7026) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

I have two questions:

why is RES undefined - I would expect it to be []

why am I ending up at "Final Err" as there should be no rejections occuring in this script

答:
I didn't go through the entire code but from a glance I think you got your deconstructing broken:

```<code>const test = () => {
    return ('one','two');
}

console.log( test() )
</code>```

Will return two, not {'one', 'two'} as you suggest here.

So change your code like this:

```<code>MongoClient.connect(mongourl)
    .then(db => {
        console.log("making promises:", typeof lib.getAllData)
        // let promises = packages.map(repo => lib.getAllData(db, repo));
        let promises = [];
        console.log("making promises2")
        // return getAllData(db, packages[0])
        return Promise.all(promises)
            .then(results => {
                console.log("RAW RES", results);
                let missing = results.filter(r => r.error).map(r => r.error)

                return {db, missing};
                //      ^------- THE CHANGE

            })
            // Should never fail as getAllData always resolves
            .catch(err => {
                console.log("err1", err);
                return Promise.reject({db, err})
            });
    }).then(({db, results}) => {
        console.log("RES: ", results);
        db.close();
    }).catch(({db, err}) => {
        console.log("Final Err:", err);
        db.close();
    });
</code>```

I also suggest to abstract these functions so that you get to a nice promise chain.

Your questions

why is RES undefined - I would expect it to be []

Well you return a single variable rather than an object so db and results is both undefined

why am I ending up at "Final Err" as there should be no rejections occuring in this script

Famous last words ;)
Always assume things will break.

Body:
I'm struggling to see where the promise rejection is emerging in the following:

MongoClient.connect(mongourl)
    .then(db => {
        console.log("making promises:", typeof lib.getAllData)
        // let promises = packages.map(repo => lib.getAllData(db, repo));
        let promises = [];
        console.log("making promises2")
        // return getAllData(db, packages[0])
        return Promise.all(promises)
            .then(results => {
                console.log("RAW RES", results);
                let missing = results.filter(r => r.error).map(r => r.error)
                return (db, missing);
            })
            // Should never fail as getAllData always resolves
            .catch(err => {
                console.log("err1", err);
                return Promise.reject({db, err})
            });
    }).then(({db, results}) => {
        console.log("RES: ", results);
        db.close();
    }).catch(({db, err}) => {
        console.log("Final Err:", err);
        db.close();
    });

What I see in the console is

making promises: function
making promises2
RAW RES []
RES:  undefined
Final Err: undefined
(node:7026) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'close' of undefined
(node:7026) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I have two questions:

why is RES undefined - I would expect it to be []

why am I ending up at "Final Err" as there should be no rejections occuring in this script

Body:
I didn't go through the entire code but from a glance I think you got your deconstructing broken:

const test = () => {
    return ('one','two');
}

console.log( test() )

Will return two, not {'one', 'two'} as you suggest here.

So change your code like this:

MongoClient.connect(mongourl)
    .then(db => {
        console.log("making promises:", typeof lib.getAllData)
        // let promises = packages.map(repo => lib.getAllData(db, repo));
        let promises = [];
        console.log("making promises2")
        // return getAllData(db, packages[0])
        return Promise.all(promises)
            .then(results => {
                console.log("RAW RES", results);
                let missing = results.filter(r => r.error).map(r => r.error)

                return {db, missing};
                //      ^------- THE CHANGE

            })
            // Should never fail as getAllData always resolves
            .catch(err => {
                console.log("err1", err);
                return Promise.reject({db, err})
            });
    }).then(({db, results}) => {
        console.log("RES: ", results);
        db.close();
    }).catch(({db, err}) => {
        console.log("Final Err:", err);
        db.close();
    });

I also suggest to abstract these functions so that you get to a nice promise chain.

Your questions

why is RES undefined - I would expect it to be []

Well you return a single variable rather than an object so db and results is both undefined

why am I ending up at "Final Err" as there should be no rejections occuring in this script

Famous last words ;)
Always assume things will break.


问:
How to modify the source of Buildroot packages for package development?
I've been using buildroot in order to build a toolchain using uclibc. Now, buildroot downloads all the packages, extract them and build them all..

I want to change the toolchain's uclibc source and then recompile the toolchain with the new source and i just can't understand how it can be done in the pretty way..

After it finishes building, all of the extracted sources are found in the "<buildroot-src>/output/build". But changing them won't give me a thing because buildroot only uses this directory as an intermediate during build time.

So my thought was, maybe changing the .mk file in the uclibc package and make it use my modified source instead of downloading and extracting it (not yet sure if it can be done there) but that seems a bit ugly solution..

So my question is this: Is there any better way of telling buildroot to build a package using existing source?

答:
Minimal git submodule + *_OVERRIDE_SRCDIR example

Docs explain it, but here is a faster to parse version.

Directory structure:

buildroot/: git submodule with buildroot 2017.02

linux/: git submodule with Linux kernel pointing to your fork at https://github.com/you/linux

buildroot_override: contains:

```<code>LINUX_OVERRIDE_SRCDIR = ../linux
</code>```

Build and run:

```<code>cd buildroot
make qemu_x86_64_defconfig
echo 'BR2_PACKAGE_OVERRIDE_FILE=../buildroot_override' >> .config
make
qemu-system-x86_64 -M pc -kernel output/images/bzImage -drive file=output/images/rootfs.ext2,if=virtio,format=raw -append root=/dev/vda -net nic,model=virtio -net user
</code>```

Here is an example project using it.

Body:
Minimal git submodule + *_OVERRIDE_SRCDIR example

Docs explain it, but here is a faster to parse version.

Directory structure:

buildroot/: git submodule with buildroot 2017.02

linux/: git submodule with Linux kernel pointing to your fork at https://github.com/you/linux

buildroot_override: contains:

LINUX_OVERRIDE_SRCDIR = ../linux

Build and run:

cd buildroot
make qemu_x86_64_defconfig
echo 'BR2_PACKAGE_OVERRIDE_FILE=../buildroot_override' >> .config
make
qemu-system-x86_64 -M pc -kernel output/images/bzImage -drive file=output/images/rootfs.ext2,if=virtio,format=raw -append root=/dev/vda -net nic,model=virtio -net user

Here is an example project using it.

ContentLicense: CC BY-SA 4.0


问:
How to display json data into the android layout?
MY JSON looks like this. I just need to set these values in the layout of the fragment. So that the details about this product will be displayed. </p>

<p>```<code></p>

```<code>{
  "adid": 5,
  "uid": 1130,
  "userName": "Maëly",
  "cid": 5,
  "brand": null,
  "model": null,
  "title": "Nummular dermatitis",
  "description": "Nam sa dea ss "
  "address": "9795 Debra Center",
  "price": 1544,
  "photo1": "../../../img/mobile/oneplus/3t/3t-1.jpg",
  "photo2": null,
  "photo3": null,
  "photo4": null,
  "ip_add": null,
  "created": 1493921700000,
  "expiryDate": null,
  "published": true,
  "sold": null,
  "featured": true,
  "cond": true,
  "price_neg": true,
  "used_for": "8",
  "views": 1575,
  "city": "Kathmandu",
  "landmark": null,
  "quality": null,
  "alert": null,
  "features": [

  ]
}
</code>```

<p>```</code></p>

答:
do step that SpaceBison Suggest
Then do this,
if for e.g. JSONSCHEMATOPOJO create class POJO for you then do this.</p>

```<code>try{
JSONObject object = new JSONObject(string);
Gson gson= new Gson();
POJO p = gson.fromJson(object,POJO.class)'
}catch(JSONException){
e.printStackStra();
}
</code>```

Body:
MY JSON looks like this. I just need to set these values in the layout of the fragment. So that the details about this product will be displayed.

{
  "adid": 5,
  "uid": 1130,
  "userName": "Maëly",
  "cid": 5,
  "brand": null,
  "model": null,
  "title": "Nummular dermatitis",
  "description": "Nam sa dea ss "
  "address": "9795 Debra Center",
  "price": 1544,
  "photo1": "../../../img/mobile/oneplus/3t/3t-1.jpg",
  "photo2": null,
  "photo3": null,
  "photo4": null,
  "ip_add": null,
  "created": 1493921700000,
  "expiryDate": null,
  "published": true,
  "sold": null,
  "featured": true,
  "cond": true,
  "price_neg": true,
  "used_for": "8",
  "views": 1575,
  "city": "Kathmandu",
  "landmark": null,
  "quality": null,
  "alert": null,
  "features": [

  ]
}

Body:
do step that SpaceBison Suggest
Then do this,
if for e.g. JSONSCHEMATOPOJO create class POJO for you then do this.

try{
JSONObject object = new JSONObject(string);
Gson gson= new Gson();
POJO p = gson.fromJson(object,POJO.class)'
}catch(JSONException){
e.printStackStra();
}


问:
Coroutine not starting
I'm using a lightning GameObject prefab to have a visual effect when i'm firing my weapon. When I fire, I enable that lightning object and I have a generic component that deactivates it after a certain delay.

The problem is that the "should wait" log is never reached, and instead of waiting the set delay, it waits much longer and doesn't actually deactivate the GameObject.

Here's the code for the DeactivateAfter component

public class DestroyAfter : MonoBehaviour {

    [SerializeField]
    private float delay;
    private bool firstRun = true;

    void OnEnable () {
        if (firstRun == false) {
            StartCoroutine(DestroyMethod());
        }
        firstRun = false;
    }

    public IEnumerator DestroyMethod() {
        Debug.LogFormat("Should wait; Time: {0}", Time.time);
        yield return new WaitForSeconds(delay);
        Debug.LogFormat("Should deactivate; Time: {0}", Time.time);
        gameObject.SetActive(false);
    }
}
```

答:
Hmm. Your code works fine in my project.

What i'm doing, some object have your script and I deactivate and then activate the gameObject when scene is playing.

Your Destroy Method is public.
Check your project, maybe somewhere calls StopAllCoroutines() or StopCoroutine(DestroyMethod());

Title: Coroutine not starting


问:
C# Elegant way to handle checking for an item in a collection
I've posted a code sample below. Firstly let me explain

termStore.Groups in the code below is a collection of Group Objects (The exact class is irrelevant).

Checking for null : if (termStore.Groups[groupName] == null) seems like a logical (clean) approach, but if the Groups collection is empty then an exception is produced.

using the termStore.Groups.Contains is not an option either because this expects a strong type i.e: .Contains(Group)... not .Contains(GroupName as string)

Can someone recommend a clean / generic way I can check for if an item exists in collection .

Thank you....

```<code>TermStore termStore = session.TermStores.Where(ts => ts.Name == termStoreName).FirstOrDefault();
                if (termStore.Groups[groupName] == null)
                {
                    termStore.CreateGroup(groupName);
                    termStore.CommitAll();
                }
</code>```

Update: The exact class Sharepoint Taxonomy Classes. http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.group.aspx

Update 2, the exact collection : http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.groupcollection.aspx

答:
Ok, 2nd attempt.  If Groups doesn't contain the required ContainsKey method then you can write it yourself.  Then you can just use ContainsKey in place of Contains.</p>

```<code>static class GroupExtensions
{
   public static bool ContainsKey(this Groups groups, string key)
   {
      try
      {
         if(groups[key] == null)
         {
            return false;
         }
      }
      catch
      {
         return false;
      }
      return true;
   }

}
</code>```

Body:
I've posted a code sample below. Firstly let me explain

termStore.Groups in the code below is a collection of Group Objects (The exact class is irrelevant).

Checking for null : if (termStore.Groups[groupName] == null) seems like a logical (clean) approach, but if the Groups collection is empty then an exception is produced.

using the termStore.Groups.Contains is not an option either because this expects a strong type i.e: .Contains(Group)... not .Contains(GroupName as string)

Can someone recommend a clean / generic way I can check for if an item exists in collection .

Thank you....

TermStore termStore = session.TermStores.Where(ts => ts.Name == termStoreName).FirstOrDefault();
                if (termStore.Groups[groupName] == null)
                {
                    termStore.CreateGroup(groupName);
                    termStore.CommitAll();
                }

Update: The exact class Sharepoint Taxonomy Classes. http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.group.aspx

Update 2, the exact collection : http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.groupcollection.aspx

Body:
Ok, 2nd attempt.  If Groups doesn't contain the required ContainsKey method then you can write it yourself.  Then you can just use ContainsKey in place of Contains.

static class GroupExtensions
{
   public static bool ContainsKey(this Groups groups, string key)
   {
      try
      {
         if(groups[key] == null)
         {
            return false;
         }
      }
      catch
      {
         return false;
      }
      return true;
   }

}


问:
bind Knockoutjs arrays to Bootstrap slider
I'm trying to implement a bootstrap slider in a webapplication and use knockoutjs for the data handling.

Javascript

```<code>$(document).ready(() => {
    function ViewModel() {
        singleValue  = ko.observable(20)
        arrayValues  = ko.observableArray([20, 50])
    }
    ko.applyBindings(ViewModel)
})
</code>```

HTML

```<code><input
  type                ='text'
  data-slider-min     = 0
  data-slider-max     = 100
  data-slider-step    = 1
  data-slider-tooltip ='hide'
  data-provide        ='slider'
  data-slider-value   = 20
  data-bind           = 'value: singleValue'
/>

<p data-bind='text: singleValue'></p>
</code>```

That works perfectly fine. If I change the value of the slider, the value in p is changing accordingly.

```<code><input
  type                ='text'
  data-slider-min     = 0
  data-slider-max     = 100
  data-slider-step    = 1
  data-slider-tooltip ='hide'
  data-provide        ='slider'
  data-slider-value   = [20, 40]
  data-bind           = 'value: arrayValues'
/>

<p data-bind='text: arrayValues()'></p>
// output is 20,50, so knockout is taking precedence,
// because I set the initial value to [20, 40] in html
</code>```

If I change the value of the slider, it seems the values are changing accordingly. But it's not an array anymore, its a string value. But the minimum and maximun values are changing correctly with the slider.

```<code><p data-bind='text: arrayValues()[0]'></p>
</code>```

Here the output is 20 when site is rendered. Which is what I expected.
But as soon as I start to move the slider, the array is becoming a string and the output changes to 2, which is the first char of 20,40.

Does anyone knows what I'm doing wrong?

答:
I believe the value binding for <input>, <textarea> etc. really just understands string values. This is not true for <select>, which accepts arbitrary data types, even objects.

My suggestion would be to work-around the problem. In the example below, I use a writable computed to parse '20,40' into an array of the form you described. You might just provide such a computed using data-bind = 'value: val'.

let _val = ko.observable([20, 50]);
let val = ko.computed({
  read: () => _val(),
  write: v => {
    _val(v.split(',').map(n => parseInt(n)));
  },
});

console.log(val());
val('20,40');
console.log(val());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script></code>```

Body:
I'm trying to implement a bootstrap slider in a webapplication and use knockoutjs for the data handling.

Javascript

$(document).ready(() => {
    function ViewModel() {
        singleValue  = ko.observable(20)
        arrayValues  = ko.observableArray([20, 50])
    }
    ko.applyBindings(ViewModel)
})

HTML

<input
  type                ='text'
  data-slider-min     = 0
  data-slider-max     = 100
  data-slider-step    = 1
  data-slider-tooltip ='hide'
  data-provide        ='slider'
  data-slider-value   = 20
  data-bind           = 'value: singleValue'
/>

That works perfectly fine. If I change the value of the slider, the value in p is changing accordingly.

<input
  type                ='text'
  data-slider-min     = 0
  data-slider-max     = 100
  data-slider-step    = 1
  data-slider-tooltip ='hide'
  data-provide        ='slider'
  data-slider-value   = [20, 40]
  data-bind           = 'value: arrayValues'
/>

// output is 20,50, so knockout is taking precedence,
// because I set the initial value to [20, 40] in html

If I change the value of the slider, it seems the values are changing accordingly. But it's not an array anymore, its a string value. But the minimum and maximun values are changing correctly with the slider.

Here the output is 20 when site is rendered. Which is what I expected.
But as soon as I start to move the slider, the array is becoming a string and the output changes to 2, which is the first char of 20,40.

Does anyone knows what I'm doing wrong?

Body:
I believe the value binding for <input>, <textarea> etc. really just understands string values. This is not true for <select>, which accepts arbitrary data types, even objects.

My suggestion would be to work-around the problem. In the example below, I use a writable computed to parse '20,40' into an array of the form you described. You might just provide such a computed using data-bind = 'value: val'.

let _val = ko.observable([20, 50]);
let val = ko.computed({
  read: () => _val(),
  write: v => {
    _val(v.split(',').map(n => parseInt(n)));
  },
});

console.log(val());
val('20,40');
console.log(val());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>


问:
Passing JS to PHP
I am trying to pass a string stored in a variable to a mysql table via php.

Currently I am using an <input> with type hidden, I assign the variable that I want as its value and post it through a form submit.
it is working but it's ugly.

I know there is $.post and $.ajax but I don't seem to figure out how to use them in the js side and php side. I have looked for them online and there are a lot of questions of this sort but none of them work for me (probably because I am missing knowledge)

How can I do it?

答:
Here is a very basic example. We start out with a form on an HTML page. When this button is clicked, we are going to activate a javascript function.

```<code><html>
  <form>
    <input type="email" id="email-field" />
    <input id="submitButton" type="submit" value="Submit" />
  </form>
</html>
</code>```

Now, here is the javascript function being activated due to the button click. Inside, we extract any information that might have been filled out in the input field with id of "email-field", then send that off via ajax to a php file that sits on the server.

```<code>$('#submitButton').click(function() {
  var email = $('#email-field').val();

  $.ajax({
    type: 'POST',
    url: './yourphpfilename.php',
    data: {
      email: email
    }
  }).done(function(data) {
    console.log(data) // Will send you the result that is echoed in the PHP file
  })
})
</code>```

As long as you put the correct url in your ajax request to your PHP file, you can easily receive the data being sent like so,

```<code><?php

 if($_SERVER['REQUEST_METHOD'] == 'POST') {

   $email = $_POST['email'];
   echo 'I have received your request.';

 }
</code>```

To send the data back, I use the echo command to do so here.

Try to read some documentation on the $_POST variable in PHP. Notice how I call for ['email']. The identifier inside the brackets directly correlates to the key inside the data object in the js file. For example, say we decided to name our email key something different in the js file.

```<code>data: {
   useremail: email
}
</code>```

You would then just change the PHP code like so,

```<code>$email = $_POST['useremail'];
</code>```

This was very confusing for me starting out, and sometimes it's hard to even pose a quality question on it if you have no idea how it works. In the future though, I would atleast try to post some code showing that you attempted the problem.

Title: Passing JS to PHP

Body:
Here is a very basic example. We start out with a form on an HTML page. When this button is clicked, we are going to activate a javascript function.

<html>
  <form>
    <input type="email" id="email-field" />
    <input id="submitButton" type="submit" value="Submit" />
  </form>
</html>

Now, here is the javascript function being activated due to the button click. Inside, we extract any information that might have been filled out in the input field with id of "email-field", then send that off via ajax to a php file that sits on the server.

$('#submitButton').click(function() {
  var email = $('#email-field').val();

  $.ajax({
    type: 'POST',
    url: './yourphpfilename.php',
    data: {
      email: email
    }
  }).done(function(data) {
    console.log(data) // Will send you the result that is echoed in the PHP file
  })
})

As long as you put the correct url in your ajax request to your PHP file, you can easily receive the data being sent like so,

<?php

 if($_SERVER['REQUEST_METHOD'] == 'POST') {

   $email = $_POST['email'];
   echo 'I have received your request.';

 }

To send the data back, I use the echo command to do so here.

Try to read some documentation on the $_POST variable in PHP. Notice how I call for ['email']. The identifier inside the brackets directly correlates to the key inside the data object in the js file. For example, say we decided to name our email key something different in the js file.

data: {
   useremail: email
}

You would then just change the PHP code like so,

$email = $_POST['useremail'];

This was very confusing for me starting out, and sometimes it's hard to even pose a quality question on it if you have no idea how it works. In the future though, I would atleast try to post some code showing that you attempted the problem.


问:
Using Python module pyautogui, to take a screenshot and auto name the .png file by date&time
I am creating a program that will eventually read the screen through shots and I need it to save the filename with a date and time stamp, the program runs fine but does not create the filename correctly and is therefore replacing the existing screenshot. How do I change it to where the file name becomes the date and time defined in the code below?</p>

```<code>def getTime():

    #GET THE CURRENT DATE AND TIME
    now = datetime.datetime.now()
    now_str = now.strftime("%Y-%m-%d-%H-%M-%S")
    outFile = pyautogui.screenshot('ImageFile.PNG'.format(now_str))
</code>```

答:
You are missing the brackets.
https://docs.python.org/2/library/string.html#format-examples</p>

```<code>outFile = pyautogui.screenshot('ImageFile{}.PNG'.format(now_str))
</code>```

Body:
I am creating a program that will eventually read the screen through shots and I need it to save the filename with a date and time stamp, the program runs fine but does not create the filename correctly and is therefore replacing the existing screenshot. How do I change it to where the file name becomes the date and time defined in the code below?

def getTime():

    #GET THE CURRENT DATE AND TIME
    now = datetime.datetime.now()
    now_str = now.strftime("%Y-%m-%d-%H-%M-%S")
    outFile = pyautogui.screenshot('ImageFile.PNG'.format(now_str))

Body:
You are missing the brackets.
https://docs.python.org/2/library/string.html#format-examples

outFile = pyautogui.screenshot('ImageFile{}.PNG'.format(now_str))


问:
Can't compile image with `gforthmi`
The application shown below

```<code>." Hello, world!"
bye
</code>```

creates the following error when compiling via gforthmi stdout.4th:

```<code>/usr/bin/gforthmi: 47: /usr/bin/gforthmi: /usr/lib/gforth/0.7.3/gforth-ditc: not found
/usr/bin/gforthmi: 48: /usr/bin/gforthmi: /usr/lib/gforth/0.7.3/gforth-ditc: not found
redefined th
*OS command line*:-1: No such file or directory
comp-image >>>./temp-image.fi1<<< ./temp-image.fi2 stdout.4th bye
Backtrace:
$7F416215C970 throw
$7F41621924F8 slurp-file
rm: cannot remove './temp-image.fi1': No such file or directory
rm: cannot remove './temp-image.fi2': No such file or directory
</code>```

I am running gforth 0.7.3 installed on an Ubuntu system via the official Ubuntu PPA.

Have I made a mistake in the way I compile the image? Am I missing any options?

答:
There's couple of issues involved.

For some reason gforth-ditc on ubuntu is located in different path. Not under /usr/bin, but under /use/lib/$MACHTYPE/gforth/$version. I.e. for 64-bit ubuntu and gforth version 0.7.2 I have it located at /usr/lib/x86_64-linux-gnu/gforth/0.7.2/gforth-ditc. Find it in your system and specify with GFORTHD environment variable.

Second problem is with your test sample. It shouldn't end with bye, as that will terminate gforth-ditc (used by gforthmi) without possibly saving anything, as  savesystem word passed as arguments to gforth-ditc will never be reached.

Another hint - your test sample will be interpreted during compilation, but won't contribute any code to generated image. At least define some words to be called after your image is loaded :)

Title: Can't compile image with `gforthmi`

Body:
The application shown below

." Hello, world!"
bye

creates the following error when compiling via gforthmi stdout.4th:

/usr/bin/gforthmi: 47: /usr/bin/gforthmi: /usr/lib/gforth/0.7.3/gforth-ditc: not found
/usr/bin/gforthmi: 48: /usr/bin/gforthmi: /usr/lib/gforth/0.7.3/gforth-ditc: not found
redefined th
*OS command line*:-1: No such file or directory
comp-image >>>./temp-image.fi1<<< ./temp-image.fi2 stdout.4th bye
Backtrace:
$7F416215C970 throw
$7F41621924F8 slurp-file
rm: cannot remove './temp-image.fi1': No such file or directory
rm: cannot remove './temp-image.fi2': No such file or directory

I am running gforth 0.7.3 installed on an Ubuntu system via the official Ubuntu PPA.

Have I made a mistake in the way I compile the image? Am I missing any options?


问:
Parent Child Relationships with Fluent NHibernate?
I would like to create a cascading tree/list of N number of children for a given parent, where a child can also become a parent.

Given the following data structure:

CountryType=1; ColorType=3; StateType=5

6,7,8 = {Can, US, Mex}

10, 11, 12 = {Red, White, Blue}

20,21,22= {California, Florida, Alberta}

```<code>TreeID  ListTypeID  ParentTreeID           ListItemID
1            1       Null                   6   (Canada is a Country)
2            1       Null                   7   (US is a Country)
3            1       Null                   8   (Mexico is a Country)
4            3       3                      10  (Mexico has Red)
5            3       3                      11  (Mexico has White)
6            5       1                      22  (Alberta is in Canada)
7            5       7                      20  (California is in US)
8            5       7                      21  (Florida is in US)
9            3       6                     10  (Alberta is Red)
10           3       6                    12  (Alberta is Blue)
11          3       2                      10  (US is Red)
12          3       2                      11  (Us is Blue)
</code>```

How would this be represented in Fluent NHibernate classes?

Some direction would be appreciated.

Thanks.

答:
If this model doesn't get any complicated than this I would go for a simple TreeNode entity with a NodeType enum property, a Name property and a ParentNode property of type TreeNode.

If you plan do add some more complexity to the different node types I would go for a TreeNode entity subclassed to different node types by a NodeType discriminator.

Body:
I would like to create a cascading tree/list of N number of children for a given parent, where a child can also become a parent.

Given the following data structure:

CountryType=1; ColorType=3; StateType=5

6,7,8 = {Can, US, Mex}

10, 11, 12 = {Red, White, Blue}

20,21,22= {California, Florida, Alberta}

TreeID  ListTypeID  ParentTreeID           ListItemID
1            1       Null                   6   (Canada is a Country)
2            1       Null                   7   (US is a Country)
3            1       Null                   8   (Mexico is a Country)
4            3       3                      10  (Mexico has Red)
5            3       3                      11  (Mexico has White)
6            5       1                      22  (Alberta is in Canada)
7            5       7                      20  (California is in US)
8            5       7                      21  (Florida is in US)
9            3       6                     10  (Alberta is Red)
10           3       6                    12  (Alberta is Blue)
11          3       2                      10  (US is Red)
12          3       2                      11  (Us is Blue)

How would this be represented in Fluent NHibernate classes?

Some direction would be appreciated.

Thanks.


问:
Removing the first lines of multiple records in an RTF Long Text field in access
Is it possible to remove the first few lines of multiple records in a Rich Text Long Text field in access? Thanks.</p>

答:
Obviously, you can, as you can do many string manipulations in Access.
Try to show some research and attempts next time.

You can use the following function to remove lines from strings:

```<code>Public Function RemoveLines(str As String, LineCount As Integer) As String
    Dim searchPosition As Integer
    searchPosition = 1
    Dim linesPassed As Integer
    linesPassed = 0
    Dim Found As Integer
    Found = 1
    Do While linesPassed < LineCount
        Found = InStr(searchPosition, str, vbCrLf)
        If Found <> 0 Then
            searchPosition = Found + 2
        Else
            RemoveLines = ""
            Exit Function
        End If
        linesPassed = linesPassed + 1
    Loop
    RemoveLines = Mid(str, searchPosition)
End Function
</code>```

This removes LineCount lines from your string. You can either use it in VBA or in action queries, though rich text memo fields in action queries tend to start with a single linebreak, and have all line breaks repeated. If you just enter twice the amount you actually want to remove, it will work in action queries.

Body:
Obviously, you can, as you can do many string manipulations in Access.
Try to show some research and attempts next time.

You can use the following function to remove lines from strings:

Public Function RemoveLines(str As String, LineCount As Integer) As String
    Dim searchPosition As Integer
    searchPosition = 1
    Dim linesPassed As Integer
    linesPassed = 0
    Dim Found As Integer
    Found = 1
    Do While linesPassed < LineCount
        Found = InStr(searchPosition, str, vbCrLf)
        If Found <> 0 Then
            searchPosition = Found + 2
        Else
            RemoveLines = ""
            Exit Function
        End If
        linesPassed = linesPassed + 1
    Loop
    RemoveLines = Mid(str, searchPosition)
End Function

This removes LineCount lines from your string. You can either use it in VBA or in action queries, though rich text memo fields in action queries tend to start with a single linebreak, and have all line breaks repeated. If you just enter twice the amount you actually want to remove, it will work in action queries.


问:
What does "poll" in django mean?
In Django doc it is said

Creation of a basic poll application will consist of two parts:

A public site that lets people view polls and vote in them.
An admin site that lets you add, change, and delete polls.

I couldn't find any clear description of a poll. So what does it mean?

答:
don't be confused with the word poll. Poll here is used only in reference with vote, and nothing related to django as such. What it means to say is to have a site for voting, on which people can view previous votes (polls) and can cast their own vote. And an admin site to change and delete these votes casted by the people.

It is like many sites on which you may like some post or article, and can also see the current likes for that post. And site admin has a right to delete or change your votes.

Title: What does "poll" in django mean?


问:
How to parse the next xml using XPath in java?I want to extract the cue and the xscope from a sentence?
This is my java code:

```<code>class SentenceNode {
    Node xscope;
    Node cue;
}

List<SentenceNode> getSentenceNodes(InputSource is) {
    List<SentenceNode> sentenceNodes = new ArrayList<SentenceNode>();
    try {

        Object xscopes = XPathFactory
                .newInstance()
                .newXPath()
                .evaluate("//xscope/cue", is,
                        XPathConstants.NODESET);
        if (xscopes != null) {
            NodeList cuesNodes = (NodeList) xscopes;
            for (int i = 0; i < cuesNodes.getLength(); i++) {
                SentenceNode sentenceNode = new SentenceNode();
                Node cue = cuesNodes.item(i);
                sentenceNode.cue = cue;
                NodeList xscope = cue.getParentNode().getParentNode()
                        .getChildNodes();
                for (int j = 0; j < xscope.getLength(); j++) {
                    Node n = xscope.item(j);
                    if (n.getNodeName().equals("xscope")) {
                        sentenceNode.xscope = n;
                        break;
                    }
                }
                sentenceNodes.add(sentenceNode);

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sentenceNodes;
}

public void displaySentenceNodes() throws ClassNotFoundException, ClassCastException,
        IOException {
    InputSource is = new InputSource(new StringReader("TestBIO.xml"));
    List<SentenceNode> nodes = getSentenceNodes(is);
    for (SentenceNode node : nodes) {

        System.out.println("Xscope: " + node.xscope.getTextContent());
        System.out
                .println("Cue: " + node.cue.getTextContent());

    }
</code>```

I want to extract from this xml the sentence with its cue and xscope.For each sentence I want to obtain the xscope and cue.If the sentence has more xscopes and more cues I want to obtain all.
 Here is my xml:

```<code>   <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Annotation created="22/2/2010" creator="BioscopeWriterCasConsumer">
<DocumentSet>
        <Document type="Biological_abstract">
            <DocID type="PMID">1984449</DocID>
                <DocumentPart type="AbstractText">
                <sentence>When cells were infected with HIV, no induction of NF-KB factor was detected, <xscope>whereas high level of progeny virions was produced, <cue>suggesting</cue> that</xscope>.</sentence>
                <sentence> HIV <xscope><cue>could</cue> mimic some differentiation/activation stimuli allowing nuclear NF-KB expression</xscope>.</sentence>
                </DocumentPart>
        </Document>
</DocumentSet>
</Annotation>
</code>```

An error occured when I am trying to parse the xml file.

```<code>[Fatal Error] :1:1: Content is not allowed in prolog.
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(Unknown Source)
</code>```

答:
I found the equivalent.Is like XPath but parse the xml with DOM parser bottom-up
Here is the code:

```<code>  class SentenceNode {
            Node xscope;
            Node cue;
        }

List<SentenceNode> extractElem(String file) throws ParserConfigurationException,
            SAXException, IOException {
        List<SentenceNode> sentenceNodes = new ArrayList<SentenceNode>();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse("Test1.xml");
        document.getDocumentElement().normalize();
        NodeList nList = document.getElementsByTagName("cue");
        for (int temp = 0; temp < nList.getLength(); temp++) {
            SentenceNode sentNode = new SentenceNode();
            Node nodeCue = nList.item(temp);
            sentNode.cue = nodeCue;
            NodeList xscope = null;
            if(nodeCue.getParentNode().getParentNode().getNodeName().equals("sentence")){
                 xscope = nodeCue.getParentNode().getParentNode()
                        .getChildNodes();
            }
            else if(nodeCue.getParentNode().getParentNode().getNodeName().equals("xscope")){
                 xscope = nodeCue.getParentNode().getParentNode().getParentNode()
                        .getChildNodes();
            }
            for (int j = 0; j < xscope.getLength(); j++) {
                Node n = xscope.item(j);
                if (n.getNodeName().equals("xscope")) {
                    sentNode.xscope = n;
                    break;
                }
            }

            sentenceNodes.add(sentNode);
        }
        return sentenceNodes;
    }
</code>```

And it worked

Body:
This is my java code:

class SentenceNode {
    Node xscope;
    Node cue;
}

List<SentenceNode> getSentenceNodes(InputSource is) {
    List<SentenceNode> sentenceNodes = new ArrayList<SentenceNode>();
    try {

        Object xscopes = XPathFactory
                .newInstance()
                .newXPath()
                .evaluate("//xscope/cue", is,
                        XPathConstants.NODESET);
        if (xscopes != null) {
            NodeList cuesNodes = (NodeList) xscopes;
            for (int i = 0; i < cuesNodes.getLength(); i++) {
                SentenceNode sentenceNode = new SentenceNode();
                Node cue = cuesNodes.item(i);
                sentenceNode.cue = cue;
                NodeList xscope = cue.getParentNode().getParentNode()
                        .getChildNodes();
                for (int j = 0; j < xscope.getLength(); j++) {
                    Node n = xscope.item(j);
                    if (n.getNodeName().equals("xscope")) {
                        sentenceNode.xscope = n;
                        break;
                    }
                }
                sentenceNodes.add(sentenceNode);

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sentenceNodes;
}

public void displaySentenceNodes() throws ClassNotFoundException, ClassCastException,
        IOException {
    InputSource is = new InputSource(new StringReader("TestBIO.xml"));
    List<SentenceNode> nodes = getSentenceNodes(is);
    for (SentenceNode node : nodes) {

        System.out.println("Xscope: " + node.xscope.getTextContent());
        System.out
                .println("Cue: " + node.cue.getTextContent());

    }

I want to extract from this xml the sentence with its cue and xscope.For each sentence I want to obtain the xscope and cue.If the sentence has more xscopes and more cues I want to obtain all.
 Here is my xml:

   <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Annotation created="22/2/2010" creator="BioscopeWriterCasConsumer">
<DocumentSet>
        <Document type="Biological_abstract">
            <DocID type="PMID">1984449</DocID>
                <DocumentPart type="AbstractText">
                <sentence>When cells were infected with HIV, no induction of NF-KB factor was detected, <xscope>whereas high level of progeny virions was produced, <cue>suggesting</cue> that</xscope>.</sentence>
                <sentence> HIV <xscope><cue>could</cue> mimic some differentiation/activation stimuli allowing nuclear NF-KB expression</xscope>.</sentence>
                </DocumentPart>
        </Document>
</DocumentSet>
</Annotation>

An error occured when I am trying to parse the xml file.

[Fatal Error] :1:1: Content is not allowed in prolog.
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(Unknown Source)

Body:
I found the equivalent.Is like XPath but parse the xml with DOM parser bottom-up
Here is the code:

  class SentenceNode {
            Node xscope;
            Node cue;
        }

List<SentenceNode> extractElem(String file) throws ParserConfigurationException,
            SAXException, IOException {
        List<SentenceNode> sentenceNodes = new ArrayList<SentenceNode>();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse("Test1.xml");
        document.getDocumentElement().normalize();
        NodeList nList = document.getElementsByTagName("cue");
        for (int temp = 0; temp < nList.getLength(); temp++) {
            SentenceNode sentNode = new SentenceNode();
            Node nodeCue = nList.item(temp);
            sentNode.cue = nodeCue;
            NodeList xscope = null;
            if(nodeCue.getParentNode().getParentNode().getNodeName().equals("sentence")){
                 xscope = nodeCue.getParentNode().getParentNode()
                        .getChildNodes();
            }
            else if(nodeCue.getParentNode().getParentNode().getNodeName().equals("xscope")){
                 xscope = nodeCue.getParentNode().getParentNode().getParentNode()
                        .getChildNodes();
            }
            for (int j = 0; j < xscope.getLength(); j++) {
                Node n = xscope.item(j);
                if (n.getNodeName().equals("xscope")) {
                    sentNode.xscope = n;
                    break;
                }
            }

            sentenceNodes.add(sentNode);
        }
        return sentenceNodes;
    }

And it worked


答: Why can't you just release the mutex before attempting to restart? If by some chance another instance gets going before the one you explicitly invoke with the restart that doesn't matter, you'll still have your app up and running again with whatever changes effected that required the restart.  I don't think you need any of the complexity of the other solutions.</p>

Title: Restart Delphi Application Programmatically

Body:
It should not be possible to run multiple instances of my application. Therefore the project source contains:

CreateMutex (nil, False, PChar (ID));
if (GetLastError = ERROR_ALREADY_EXISTS) then
  Halt;

Now I want to restart my application programmatically. The usual way would be:

AppName := PChar(Application.ExeName) ;
ShellExecute(Handle,'open', AppName, nil, nil, SW_SHOWNORMAL) ;
Application.Terminate;

But this won't work in my case because of the mutex. Even if I release the mutex before starting the second instace it won't work because shutdown takes some time and two instance cannot run in parallel (because of common resources and other effects).

Is there a way to restart an application with such characteristics? (If possible without an additional executable)

Thanks in advance.


问:
Java Selenium looping through website sendKeys combine strings together
I have a for loop that constantly loops back a website to fill out and submit a search box with the next string from a list.

For example, if the list contains [abcd, efgh, ijkl....], the first loop would send abcd, the second loop would send efgh and etc.

Currently the loop sends the first string correctly, but on every loop afterwards, the string sent is added to the previous string. So instead of efgh on the second loop, it is abcdefgh.

How do I clear the keys so that I can just send the individual string? Here's what I have right now:

```<code>    for(String value : List){
        driver.get(Link);
        Actions actions = new Actions(driver);
        WebElement input_field = driver.findElement(By.id("txtBoxSearch"));

        actions.moveToElement(input_field);
        actions.click();
        actions.sendKeys(value);
        actions.build().perform();

        WebElement submit_key = driver.findElement(By.xpath("//button[contains(@title, 'Search')]"));
        actions.moveToElement(submit_key);

        actions.click();
        actions.build().perform();
    }
</code>```

答:
Here is the Answer to your Question:

Once you call click() method on the on the desired element through action class instance, next use the action  class instance to clickAndHold, send CONTROL A and then send the new text DebanjanB to the form control to overwrite the previous text as follows:

```<code>for(String value : List){
    driver.get(Link);
    Actions actions = new Actions(driver);
    WebElement input_field = driver.findElement(By.id("txtBoxSearch"));
    actions.moveToElement(input_field);
    actions.click();
    actions.clickAndHold(input_field).sendKeys(Keys.chord(Keys.CONTROL, "a"), "DebanjanB").build().perform();
    WebElement submit_key = driver.findElement(By.xpath("//button[contains(@title, 'Search')]"));
    actions.moveToElement(submit_key);
    actions.click();
    actions.build().perform();
}
</code>```

Let me know if this Answers your Question.

Body:
I have a for loop that constantly loops back a website to fill out and submit a search box with the next string from a list.

For example, if the list contains [abcd, efgh, ijkl....], the first loop would send abcd, the second loop would send efgh and etc.

Currently the loop sends the first string correctly, but on every loop afterwards, the string sent is added to the previous string. So instead of efgh on the second loop, it is abcdefgh.

How do I clear the keys so that I can just send the individual string? Here's what I have right now:

    for(String value : List){
        driver.get(Link);
        Actions actions = new Actions(driver);
        WebElement input_field = driver.findElement(By.id("txtBoxSearch"));

        actions.moveToElement(input_field);
        actions.click();
        actions.sendKeys(value);
        actions.build().perform();

        WebElement submit_key = driver.findElement(By.xpath("//button[contains(@title, 'Search')]"));
        actions.moveToElement(submit_key);

        actions.click();
        actions.build().perform();
    }

Body:
Here is the Answer to your Question:

Once you call click() method on the on the desired element through action class instance, next use the action  class instance to clickAndHold, send CONTROL A and then send the new text DebanjanB to the form control to overwrite the previous text as follows:

for(String value : List){
    driver.get(Link);
    Actions actions = new Actions(driver);
    WebElement input_field = driver.findElement(By.id("txtBoxSearch"));
    actions.moveToElement(input_field);
    actions.click();
    actions.clickAndHold(input_field).sendKeys(Keys.chord(Keys.CONTROL, "a"), "DebanjanB").build().perform();
    WebElement submit_key = driver.findElement(By.xpath("//button[contains(@title, 'Search')]"));
    actions.moveToElement(submit_key);
    actions.click();
    actions.build().perform();
}

Let me know if this Answers your Question.


问:
img src doesnt show in cordova app although it works in browser
Hello I have an image url, when I try to open in browser it works but when I try to open from mobile app it doesn't work.

```<code><img src="http://83.66.137.45/hys/e-ticaret/cms/File/Get?fileNameWithExtension=p2.jpg&extendedPath=Product"  />
</code>```

I couldnt understand anything from problem. Because there is no error but img doesnt work . How can I solve problem

Thanks

答:
I just added your image to one of my recent projects and it does work (for me):

https://i.stack.imgur.com/1HvDB.png

Body:
Hello I have an image url, when I try to open in browser it works but when I try to open from mobile app it doesn't work.

I couldnt understand anything from problem. Because there is no error but img doesnt work . How can I solve problem

Thanks


问:
Validating/Allowing YouTube Embed Code
hopefully this is a simple question. I have a simple custom forum on my site written in PHP. For security reasons I don't allow any HTML in the forum posts. I only allow certain BBCode tags. I would however like to allow embedded YouTube videos.

So my question is this: What's the best (most secure) way to validate the YouTube embed code? YouTube is currently using iframes to embed videos, but obviously I can't just allow the iframe tag. I also need to ensure the src of the iframe is a YouTube URL, and ensure there's no other malicious bits of code in the iframe code.

答:
The safest way is to create a [youtube] tag. http://www.youtube.com/watch?v=PVHzXnS5Gms could become [youtube v='PVHzXnS5Gms'][/youtube] (or your syntax of choice).

To convert this into a YouTube embed code, take <object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/VIDEO_ID?fs=1&hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/VIDEO_ID?fs=1&hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object> and replace VIDEO_ID with the identifier.

Title: Validating/Allowing YouTube Embed Code

Body:
The safest way is to create a [youtube] tag. http://www.youtube.com/watch?v=PVHzXnS5Gms could become [youtube v='PVHzXnS5Gms'][/youtube] (or your syntax of choice).

To convert this into a YouTube embed code, take <object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/VIDEO_ID?fs=1&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/VIDEO_ID?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object> and replace VIDEO_ID with the identifier.


问:
Disable hover on specific ceils
I would like to avoid the hover on the 4 middle ceils in my table when the user make the hover on the entire line.

Initial state:

Hover state:

Expected result: Keep the 4 middle ceils in the initial state when hover.

HTML :

```<code><tr class="gradeX odd" role="row">
   <td class="" tabindex="0"> CD-5-CZ-TOS-110.21 </td>
   <td class=""> OS6450-P24 </td>
   <td class="supportedClass"> Supported </td>
   <td class="supportedClass"> Supported </td>
   <td class="notSupportedClass"> Not supported </td>
   <td class="mediumClass"> Within 90 days of end of support </td>
   <td class=""> 2c:fa:a2:2e:15:c4 </td>
   <td class=""> T5184190 </td>
   <td class=""> 6.7.2.49.R01 </td>
</tr>
</code>```

CSS (bootstrap)

```<code>.table-hover>tbody>tr:hover, .table-hover>tbody>tr:hover>td {
    background: #f3f4f6!important;
}

.table-hover>tbody>tr:hover, .table>tbody>tr.active>td, .table>tbody>tr.active>th, .table>tbody>tr>td.active, .table>tbody>tr>th.active, .table>tfoot>tr.active>td, .table>tfoot>tr.active>th, .table>tfoot>tr>td.active, .table>tfoot>tr>th.active, .table>thead>tr.active>td, .table>thead>tr.active>th, .table>thead>tr>td.active, .table>thead>tr>th.active {
    background-color: #eef1f5;
}
</code>```

答: Define a new class for the middle td's maybe with the name "holdInitial" and in the css you can use the ::not(.holdInitial) preprocessor on the querys where you define hover efects.

Title: Disable hover on specific ceils

Body:
I would like to avoid the hover on the 4 middle ceils in my table when the user make the hover on the entire line.

Initial state:

Hover state:

Expected result: Keep the 4 middle ceils in the initial state when hover.

HTML :

    CD-5-CZ-TOS-110.21
    OS6450-P24
    Supported
    Supported
    Not supported
    Within 90 days of end of support
    2c:fa:a2:2e:15:c4
    T5184190
    6.7.2.49.R01

CSS (bootstrap)

.table-hover>tbody>tr:hover, .table-hover>tbody>tr:hover>td {
    background: #f3f4f6!important;
}

.table-hover>tbody>tr:hover, .table>tbody>tr.active>td, .table>tbody>tr.active>th, .table>tbody>tr>td.active, .table>tbody>tr>th.active, .table>tfoot>tr.active>td, .table>tfoot>tr.active>th, .table>tfoot>tr>td.active, .table>tfoot>tr>th.active, .table>thead>tr.active>td, .table>thead>tr.active>th, .table>thead>tr>td.active, .table>thead>tr>th.active {
    background-color: #eef1f5;
}


问:
Code for iterative function
I'd like to write the Matlab code for the following equation:

```<code>z(k)=lamda*x(k)+(1-lamda)*z(k-1)
</code>```

lamda can be of any value. x is a 1000x22 matrix. Z(0)=0.

Can anyone help me please?

答:
Does that vectorized solution work for you?

```<code>% parameters
x = rand(10,1);
lambda = 2;

% init z, normalize with (1-lambda)
z(2:numel(x)) = lambda/(1-lambda)*x(2:end);

% cumsum, denormalize with (1-lambda)
z = cumsum(z)*(1-lambda)
</code>```

However I don't get why your x is a matrix and not a vector. What is z supposed to be, in what dimension works k? So in case xrepresents a couple of vectors you want to calculate in parallel, that could work:

```<code>% parameters
x = rand(1000,22);
lambda = 2;

% init z, normalize with (1-lambda)
z(2:size(x,1),:) = lambda/(1-lambda)*x(2:end,:);

% cumsum, denormalize with (1-lambda)
z = cumsum(z,1)*(1-lambda)
</code>```

Title: Code for iterative function

Body:
I'd like to write the Matlab code for the following equation:

z(k)=lamda*x(k)+(1-lamda)*z(k-1)

lamda can be of any value. x is a 1000x22 matrix. Z(0)=0.

Can anyone help me please?

Body:
Does that vectorized solution work for you?

% parameters
x = rand(10,1);
lambda = 2;

% init z, normalize with (1-lambda)
z(2:numel(x)) = lambda/(1-lambda)*x(2:end);

% cumsum, denormalize with (1-lambda)
z = cumsum(z)*(1-lambda)

However I don't get why your x is a matrix and not a vector. What is z supposed to be, in what dimension works k? So in case xrepresents a couple of vectors you want to calculate in parallel, that could work:

% parameters
x = rand(1000,22);
lambda = 2;

% init z, normalize with (1-lambda)
z(2:size(x,1),:) = lambda/(1-lambda)*x(2:end,:);

% cumsum, denormalize with (1-lambda)
z = cumsum(z,1)*(1-lambda)