问:
Rails 5 using Ransack, custom scope order for sorting
I'm using Rails 5 with Ransack, and I have a Model with a column in my Mysql db called status. Status is an integer from 0-5. I am trying to create a default ordering on this column where it is ascending, with the exception of status's that are 0 being last (1, 2, 3, 4, 5, 0).

I am able to get the objects in ascending order without the objects where status == 0 with:

```<code>  scope :asc_no_approved, lambda { where.not(status: [0]).order('status ASC') }
</code>```

And the objects where status == 0 with:

```<code>  scope :approved, lambda { where(status: [0]) }
</code>```

Is there a way to append this second scope to the end of the first? I tried:

```<code>scope :asc_approved_last, lambda { where.not(status: [0]).order('status ASC').where(status: [0]) }
</code>```

But that returns no objects with the following Mysql:

```<code>SELECT  `requests`.* FROM `requests` WHERE (`requests`.`status` != 0) AND `requests`.`status` = 0 ORDER BY status ASC LIMIT 10 OFFSET 0
</code>```

UPDATE:

Since the comments below are somewhat confusing, if anyone else is trying to solve this, this is what worked for me. As per the accepted answer, these are my scopes:

```<code>scope :asc_no_approved, lambda { where.not(status: [0]).order('status ASC') }
scope :approved, lambda { where(status: [0]) }
scope :asc_approved_last, lambda { asc_no_approved + approved }
</code>```

And here is my call in the controller:

```<code>@requests = Kaminari.paginate_array(@q.result.includes(:employee, :user, :title).asc_approved_last).limit(10).page(params[:page])
</code>```

答:
You can chain scopes together like that fine, you could even just do asc_no_approved.approved but I think the reason it is returning zero objects is because you are looking for all things where the status is not 0, and then asking for the things of this collection where the status is 0.

```<code>WHERE (`requests`.`status` != 0) AND `requests`.`status` = 0
</code>```

If you want to literally append the results of approved to asc_no_approved then you could just do approved + asc_no_approved

Body:
I'm using Rails 5 with Ransack, and I have a Model with a column in my Mysql db called status. Status is an integer from 0-5. I am trying to create a default ordering on this column where it is ascending, with the exception of status's that are 0 being last (1, 2, 3, 4, 5, 0).

I am able to get the objects in ascending order without the objects where status == 0 with:

  scope :asc_no_approved, lambda { where.not(status: [0]).order('status ASC') }

And the objects where status == 0 with:

  scope :approved, lambda { where(status: [0]) }

Is there a way to append this second scope to the end of the first? I tried:

scope :asc_approved_last, lambda { where.not(status: [0]).order('status ASC').where(status: [0]) }

But that returns no objects with the following Mysql:

SELECT  `requests`.* FROM `requests` WHERE (`requests`.`status` != 0) AND `requests`.`status` = 0 ORDER BY status ASC LIMIT 10 OFFSET 0

UPDATE:

Since the comments below are somewhat confusing, if anyone else is trying to solve this, this is what worked for me. As per the accepted answer, these are my scopes:

scope :asc_no_approved, lambda { where.not(status: [0]).order('status ASC') }
scope :approved, lambda { where(status: [0]) }
scope :asc_approved_last, lambda { asc_no_approved + approved }

And here is my call in the controller:

@requests = Kaminari.paginate_array(@q.result.includes(:employee, :user, :title).asc_approved_last).limit(10).page(params[:page])

Body:
You can chain scopes together like that fine, you could even just do asc_no_approved.approved but I think the reason it is returning zero objects is because you are looking for all things where the status is not 0, and then asking for the things of this collection where the status is 0.

WHERE (`requests`.`status` != 0) AND `requests`.`status` = 0

If you want to literally append the results of approved to asc_no_approved then you could just do approved + asc_no_approved


来源: stackexchange

问:
How to treat a var as both int and string.
```<code>def die():
    first = str(randint(1, 6))
    second = str(randint(1, 6))
    total = first + second
    print "You have rolled a " + first + " and a " + second + ", for a total score of " + total + "."
</code>```

Standard die throwing game, but I'm struggling to print the values for individual die as well as the total. Treating as a string for individual, but then sum leads to concatenation rather than actual sum.

Thanks

答:
print "You have rolled a " + str(first)
This would convert the int to a string, hence concatenating it.

Also, you can do
total = int(first) + int(second) to address the first issue.

ContentLicense: CC BY-SA 3.0

Body:
def die():
    first = str(randint(1, 6))
    second = str(randint(1, 6))
    total = first + second
    print "You have rolled a " + first + " and a " + second + ", for a total score of " + total + "."

Standard die throwing game, but I'm struggling to print the values for individual die as well as the total. Treating as a string for individual, but then sum leads to concatenation rather than actual sum.

Thanks


问:
Ways to cast objects to a generic type
In relation to Casting generic type "as T" whilst enforcing the type of T

And with the following example

```<code>private static T deserialize<T>(string streng) where T : class
{
    XmlSerializer ser = new XmlSerializer(typeof(T));
    StringReader reader = new StringReader(streng);
    return ser.Deserialize(reader) as T;
}
</code>```

and

```<code>private static T deserialize<T>(string streng)
{
    XmlSerializer ser = new XmlSerializer(typeof(T));
    StringReader reader = new StringReader(streng);
    return (T)ser.Deserialize(reader);
}
</code>```

I'm used to doing the object as Type casting, so I was a little confused when I found that I couldn't just do that with T. Then I found the question above and in that a solution to the as T compiler error.

But why is where T : class necessary when using object as T and not when using (T)object?
What is the actual difference between the two ways of casting the object?

答:
(T)obj throws if obj isn't convertible to T. You should use (T)obj if you're certain that the conversion will work.

And use as to replace a test with is followed by a cast. Of course T needs to be nullable(either a reference type or a Nullable<T>) since as returns null on failure. The typical pattern is:

```<code>T x=y as T;
if(x!=null)
  DoSomething(x);
</code>```

Another difference is that as only works for a subset of conversions. Overloaded casts etc will be ignored.

ContentLicense: CC BY-SA 2.5

Title: Ways to cast objects to a generic type

Body:
In relation to Casting generic type "as T" whilst enforcing the type of T

And with the following example

private static T deserialize<T>(string streng) where T : class
{
    XmlSerializer ser = new XmlSerializer(typeof(T));
    StringReader reader = new StringReader(streng);
    return ser.Deserialize(reader) as T;
}

and

private static T deserialize<T>(string streng)
{
    XmlSerializer ser = new XmlSerializer(typeof(T));
    StringReader reader = new StringReader(streng);
    return (T)ser.Deserialize(reader);
}

I'm used to doing the object as Type casting, so I was a little confused when I found that I couldn't just do that with T. Then I found the question above and in that a solution to the as T compiler error.

But why is where T : class necessary when using object as T and not when using (T)object?
What is the actual difference between the two ways of casting the object?

Body:
(T)obj throws if obj isn't convertible to T. You should use (T)obj if you're certain that the conversion will work.

And use as to replace a test with is followed by a cast. Of course T needs to be nullable(either a reference type or a Nullable<T>) since as returns null on failure. The typical pattern is:

T x=y as T;
if(x!=null)
  DoSomething(x);

Another difference is that as only works for a subset of conversions. Overloaded casts etc will be ignored.


问:
Swift OSX - Delegate protocol function returns nil, crashes when unwrapping textfield value
I'm working on an OSX app with Swift which makes use of an NSSplitView which holds two view controllers: "TableViewController" and "EntryViewController". I'm using delegates in order to transmit a custom NSObject ("Entry") on click from TableViewController up to the SplitViewController, then back down to the EntryViewController.

My problem is this: When the Entry object is received in the EntryViewController, any attempt to assign its properties to a text field value result in an unexpectedly found nil type error, never mind that the IBOutlets are properly linked, and that it can both print the Entry.property and the textfield string value (provided it is in a different, unrelated function).

I have tried many arrangements to solve this problem, which is why the current configuration might be a bit over-complicated. A delegate relation straight from Table VC to Entry VC caused the same issues.

Is there some way that the IBOutlets are not connecting, even though the view has loaded before the delegate is called? I've read many many articles on delegation—mostly for iOS—and yet can't seem to find the root of my problems. I'll be the first to admit that my grasp of Swift is a little bit piecemeal, so I am open to the possibility that what I am trying to do is simply bad/hacky coding and that I should try something completely different.

Thanks for your help!

TableViewController:

```<code>protocol SplitViewSelectionDelegate: class {
    func sendSelection(_ entrySelection: NSObject)
}

class TableViewController: NSViewController {

    @IBOutlet weak var searchField: NSSearchField!
    @IBOutlet var tableArrayController: NSArrayController!
    @IBOutlet weak var tableView: NSTableView!

    var sendDelegate: SplitViewSelectionDelegate?

    dynamic var dataArray = [Entry]()

// load array from .plist array of dictionaries

    func getItems(){
        let home = FileManager.default.homeDirectoryForCurrentUser
        let path = "Documents/resources.plist"
        let urlUse = home.appendingPathComponent(path)

        let referenceArray = NSArray(contentsOf: urlUse)
        dataArray = [Entry]()

        for item in referenceArray! {
            let headwordValue = (item as AnyObject).value(forKey: "headword") as! String
            let defValue = (item as AnyObject).value(forKey: "definition") as! String
            let notesValue = (item as AnyObject).value(forKey: "notes") as! String

            dataArray.append(Entry(headword: headwordValue, definition: defValue, notes: notesValue))
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.sendDelegate = SplitViewController()
        getItems()
        print("TVC loaded")
        // Do any additional setup after loading the view.
    }

// send selection forward to entryviewcontroller

    @IBAction func tableViewSelection(_ sender: Any) {

        let index = tableArrayController.selectionIndex
        let array = tableArrayController.arrangedObjects as! Array<Any>
        let obj: Entry
        let arraySize = array.count
        if index <= arraySize {
            obj = array[index] as! Entry
            print(index)
            print(obj)
            sendDelegate?.sendSelection(obj)
        }
        else {
            print("index unassigned")
        }
        }

}
</code>```

SplitViewController:

```<code>protocol EntryViewSelectionDelegate: class {
    func sendSecondSelection(_ entrySelection: NSObject)
}

class SplitViewController: NSSplitViewController, SplitViewSelectionDelegate {

    var delegate: EntryViewSelectionDelegate?
    @IBOutlet weak var mySplitView: NSSplitView!

    var leftPane: NSViewController?
    var contentView: NSViewController?

    var entrySelectionObject: NSObject!

    override func viewDidLoad() {

        super.viewDidLoad()

    // assign tableview and entryview as child view controllers
        let story = self.storyboard

        leftPane = story?.instantiateController(withIdentifier: "TableViewController") as! TableViewController?
        contentView = story?.instantiateController(withIdentifier: "EntryViewController") as! EntryViewController?

        self.addChildViewController(leftPane!)
        self.addChildViewController(contentView!)

        print("SVC loaded")
}

    func sendSelection(_ entrySelection: NSObject) {
        self.delegate = EntryViewController() //if this goes in viewDidLoad, then delegate is never called/assigned
        entrySelectionObject = entrySelection
        print("SVC:", entrySelectionObject!)
        let obj = entrySelectionObject!
        delegate?.sendSecondSelection(obj)
    }

}
</code>```

And Finally, EntryViewController:

```<code>class EntryViewController: NSViewController, EntryViewSelectionDelegate {

    @IBOutlet weak var definitionField: NSTextField!
    @IBOutlet weak var notesField: NSTextField!
    @IBOutlet weak var entryField: NSTextField!

    var entryObject: Entry!

    override func viewDidLoad() {
        super.viewDidLoad()
        print("EVC loaded")
    }

    func sendSecondSelection(_ entrySelection: NSObject) {
        self.entryObject = entrySelection as! Entry
        print("EVC:", entryObject)
        print(entryObject.headword)
// The Error gets thrown here:
        entryField.stringValue = entryObject.headword
    }

}
</code>```

答:
You don't need a delegate / protocol since there is a reference to EntryViewController (contentView) – by the way the instance created with EntryViewController() is not the instantiated instance in viewDidLoad.

Just use the contentView reference:

```<code>func sendSelection(_ entrySelection: NSObject) {
    contentView?.sendSecondSelection(entrySelection)
}
</code>```

Body:
I'm working on an OSX app with Swift which makes use of an NSSplitView which holds two view controllers: "TableViewController" and "EntryViewController". I'm using delegates in order to transmit a custom NSObject ("Entry") on click from TableViewController up to the SplitViewController, then back down to the EntryViewController.

My problem is this: When the Entry object is received in the EntryViewController, any attempt to assign its properties to a text field value result in an unexpectedly found nil type error, never mind that the IBOutlets are properly linked, and that it can both print the Entry.property and the textfield string value (provided it is in a different, unrelated function).

I have tried many arrangements to solve this problem, which is why the current configuration might be a bit over-complicated. A delegate relation straight from Table VC to Entry VC caused the same issues.

Is there some way that the IBOutlets are not connecting, even though the view has loaded before the delegate is called? I've read many many articles on delegation—mostly for iOS—and yet can't seem to find the root of my problems. I'll be the first to admit that my grasp of Swift is a little bit piecemeal, so I am open to the possibility that what I am trying to do is simply bad/hacky coding and that I should try something completely different.

Thanks for your help!

TableViewController:

protocol SplitViewSelectionDelegate: class {
    func sendSelection(_ entrySelection: NSObject)
}

class TableViewController: NSViewController {

    @IBOutlet weak var searchField: NSSearchField!
    @IBOutlet var tableArrayController: NSArrayController!
    @IBOutlet weak var tableView: NSTableView!

    var sendDelegate: SplitViewSelectionDelegate?

    dynamic var dataArray = [Entry]()

// load array from .plist array of dictionaries

    func getItems(){
        let home = FileManager.default.homeDirectoryForCurrentUser
        let path = "Documents/resources.plist"
        let urlUse = home.appendingPathComponent(path)

        let referenceArray = NSArray(contentsOf: urlUse)
        dataArray = [Entry]()

        for item in referenceArray! {
            let headwordValue = (item as AnyObject).value(forKey: "headword") as! String
            let defValue = (item as AnyObject).value(forKey: "definition") as! String
            let notesValue = (item as AnyObject).value(forKey: "notes") as! String

            dataArray.append(Entry(headword: headwordValue, definition: defValue, notes: notesValue))
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.sendDelegate = SplitViewController()
        getItems()
        print("TVC loaded")
        // Do any additional setup after loading the view.
    }

// send selection forward to entryviewcontroller

    @IBAction func tableViewSelection(_ sender: Any) {

        let index = tableArrayController.selectionIndex
        let array = tableArrayController.arrangedObjects as! Array<Any>
        let obj: Entry
        let arraySize = array.count
        if index <= arraySize {
            obj = array[index] as! Entry
            print(index)
            print(obj)
            sendDelegate?.sendSelection(obj)
        }
        else {
            print("index unassigned")
        }
        }

}

SplitViewController:

protocol EntryViewSelectionDelegate: class {
    func sendSecondSelection(_ entrySelection: NSObject)
}

class SplitViewController: NSSplitViewController, SplitViewSelectionDelegate {

    var delegate: EntryViewSelectionDelegate?
    @IBOutlet weak var mySplitView: NSSplitView!

    var leftPane: NSViewController?
    var contentView: NSViewController?

    var entrySelectionObject: NSObject!

    override func viewDidLoad() {

        super.viewDidLoad()

    // assign tableview and entryview as child view controllers
        let story = self.storyboard

        leftPane = story?.instantiateController(withIdentifier: "TableViewController") as! TableViewController?
        contentView = story?.instantiateController(withIdentifier: "EntryViewController") as! EntryViewController?

        self.addChildViewController(leftPane!)
        self.addChildViewController(contentView!)

        print("SVC loaded")
}

    func sendSelection(_ entrySelection: NSObject) {
        self.delegate = EntryViewController() //if this goes in viewDidLoad, then delegate is never called/assigned
        entrySelectionObject = entrySelection
        print("SVC:", entrySelectionObject!)
        let obj = entrySelectionObject!
        delegate?.sendSecondSelection(obj)
    }

}

And Finally, EntryViewController:

class EntryViewController: NSViewController, EntryViewSelectionDelegate {

    @IBOutlet weak var definitionField: NSTextField!
    @IBOutlet weak var notesField: NSTextField!
    @IBOutlet weak var entryField: NSTextField!

    var entryObject: Entry!

    override func viewDidLoad() {
        super.viewDidLoad()
        print("EVC loaded")
    }

    func sendSecondSelection(_ entrySelection: NSObject) {
        self.entryObject = entrySelection as! Entry
        print("EVC:", entryObject)
        print(entryObject.headword)
// The Error gets thrown here:
        entryField.stringValue = entryObject.headword
    }

}

Body:
You don't need a delegate / protocol since there is a reference to EntryViewController (contentView) – by the way the instance created with EntryViewController() is not the instantiated instance in viewDidLoad.

Just use the contentView reference:

func sendSelection(_ entrySelection: NSObject) {
    contentView?.sendSecondSelection(entrySelection)
}


问:
Unknown prop- react
Currently learning react, when i try and run the following code:

var userData = {
 name: 'Evans D',
 occupation: ' Logistics Planner',
 location: 'Birmingham, UK',
 img: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTAlfOT5088Z6Bj8_qSsvp3UTlU3ub9H5wG1k6qJareFXS7uqDvsQ'
};

class userInfo extends React.Component {
  render() {
    return (

Name: {this.props.user.name}

Occupation: {this.props.user.occupation}

Location: {this.props.user.location}

       //

    )
  }
}

ReactDOM.render(
  <userInfo user={userData}/>,
  document.getElementById('userInfo')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
 <title>Github Battle</title>
</head>
<body>
<div id='userInfo'></div>
</body>
</html></code>```

Console throws the following error :

'Unknown prop user on  tag. Remove this prop from the element.'

Any ideas on what I'm doing wrong?

答:
Your component name should be in PascalCase.
when react tries to render <userInfo user={userData}/> it will think that you are using a non-standard DOM attribute user on a native DOM node userInfo (without any doubt it's not) thus throwing the warning.

Title: Unknown prop- react

Body:
Currently learning react, when i try and run the following code:

var userData = {
 name: 'Evans D',
 occupation: ' Logistics Planner',
 location: 'Birmingham, UK',
 img: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTAlfOT5088Z6Bj8_qSsvp3UTlU3ub9H5wG1k6qJareFXS7uqDvsQ'
};

class userInfo extends React.Component {
  render() {
    return (

Name: {this.props.user.name}

Occupation: {this.props.user.occupation}

Location: {this.props.user.location}

       //

    )
  }
}

ReactDOM.render(
  <userInfo user={userData}/>,
  document.getElementById('userInfo')
);

<!DOCTYPE html>

 <title>Github Battle</title>

Console throws the following error :

'Unknown prop user on  tag. Remove this prop from the element.'

Any ideas on what I'm doing wrong?


问:
Make ImageView display black portions of image as different color
How can I replace the black color with transparent color (or some other color) in an ImageView?

I load image from web using Picasso:

```<code>Picasso.with(getContext()).load("www.abc.com/a.png").into(myImageView);
</code>```

Currently it looks like this:

The image itself contains the black background, which I want to remove. I tried using myImageView.setColorFilter(Color.BLACK); but it doesn't seem to work.

答:
Andy Developer's answer helped, but I had to manually convert black pixels to pixels of my liking. It is working, although I am not sure if this is the best way.

```<code>Picasso.with(getContext()).load(IMAGE_URL).into(new Target() {
    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from)
    {
        Bitmap copy = bitmap.copy(bitmap.getConfig(),true);

        int [] allpixels = new int [copy.getHeight()*copy.getWidth()];
        copy.getPixels(allpixels, 0, copy.getWidth(), 0, 0, copy.getWidth(), copy.getHeight());

        int replacementColor = Color.parseColor("#34495E");
        for(int i = 0; i < allpixels.length; i++) {
            if(allpixels[i] == Color.BLACK)
                allpixels[i] = replacementColor;
        }

        copy.setPixels(allpixels, 0, copy.getWidth(), 0, 0, copy.getWidth(), copy.getHeight());

        myImageView.setImageBitmap(copy);
    }

    @Override
    public void onBitmapFailed(Drawable errorDrawable) { }

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) { }
});
</code>```

Body:
How can I replace the black color with transparent color (or some other color) in an ImageView?

I load image from web using Picasso:

Picasso.with(getContext()).load("www.abc.com/a.png").into(myImageView);

Currently it looks like this:

The image itself contains the black background, which I want to remove. I tried using myImageView.setColorFilter(Color.BLACK); but it doesn't seem to work.

Body:
Andy Developer's answer helped, but I had to manually convert black pixels to pixels of my liking. It is working, although I am not sure if this is the best way.

Picasso.with(getContext()).load(IMAGE_URL).into(new Target() {
    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from)
    {
        Bitmap copy = bitmap.copy(bitmap.getConfig(),true);

        int [] allpixels = new int [copy.getHeight()*copy.getWidth()];
        copy.getPixels(allpixels, 0, copy.getWidth(), 0, 0, copy.getWidth(), copy.getHeight());

        int replacementColor = Color.parseColor("#34495E");
        for(int i = 0; i < allpixels.length; i++) {
            if(allpixels[i] == Color.BLACK)
                allpixels[i] = replacementColor;
        }

        copy.setPixels(allpixels, 0, copy.getWidth(), 0, 0, copy.getWidth(), copy.getHeight());

        myImageView.setImageBitmap(copy);
    }

    @Override
    public void onBitmapFailed(Drawable errorDrawable) { }

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) { }
});


问:
Conversion from 'char' to non-scalar type 'Vector<char>' error thrown unknown reason
Error Thrown Unknown Reason

```<code>#include "std_lib_facilities.h"

int main()
{
    vector<char> shape = ('a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a');
    return(0);
}
</code>```

that one line with the vector throws this error that I've never seen before nor can figure out...

:: g++ TicTacToe.cpp -o TTT

TicTacToe.cpp: In function int main()':

TicTacToe.cpp:5: error: conversion fromchar' to non-scalar type `Vector' requested

See in each tic-tac-toe box it will start as _ and then go to either X or O, I'm doing this without a graphics library so its terminal graphics.

答:
If all value are the same you can use the following constructor of the std::vector:

```<code>std::vector<char> shape( 9, 'a' );
</code>```

If part or all values are distinct you can use another constructor as follows:

```<code>static const char ini[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' };
std::vector<char> shape( ini, ini+sizeof(ini) );
</code>```

Or

```<code>static const char ini[] = "abcdefghi";
std::vector<char> shape( ini, ini+sizeof(ini)-1 );
</code>```

Body:
Error Thrown Unknown Reason

#include "std_lib_facilities.h"

int main()
{
    vector<char> shape = ('a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a');
    return(0);
}

that one line with the vector throws this error that I've never seen before nor can figure out...

:: g++ TicTacToe.cpp -o TTT

TicTacToe.cpp: In function int main()':

TicTacToe.cpp:5: error: conversion fromchar' to non-scalar type `Vector' requested

See in each tic-tac-toe box it will start as _ and then go to either X or O, I'm doing this without a graphics library so its terminal graphics.

Body:
If all value are the same you can use the following constructor of the std::vector:

std::vector<char> shape( 9, 'a' );

If part or all values are distinct you can use another constructor as follows:

static const char ini[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' };
std::vector<char> shape( ini, ini+sizeof(ini) );

Or

static const char ini[] = "abcdefghi";
std::vector<char> shape( ini, ini+sizeof(ini)-1 );


问:
Compare two different Excel Files and Copy data from one to another if conditions met
So I have two files. File1 and File2. Both have the same columns but one is filled and one is not.

What I want to do it if there is a match of name (suppose A1) from File2 in A row of File1 copy the rows Q,R and S to File2.

So if A1 (of File2) is found in A row of File1 (Suppose in A34) then I want to copy Q34,R34 and S34 of File1 to File2.

I think VLOOKUP would be required for the first part so I think that will need to be incorporated in the VBA.

Any help,idea or general direction where I should be heading for would be great.

答:
This should do what you are looking for. Place the macro in the workbook that contains all the filled columns, and change the path link to the second workbook file that you want to copy data over to. You may also need to change the sheet name from "Sheet1" if your sheet name is different.</p>

```<code>Sub copyOnMatch()

Dim i As Long
Dim j As Long
Dim wbk1, wbk2 As Workbook

Set wbk1 = ThisWorkbook.Sheets("Sheet1")
WBK1Range = wbk1.Range("A" & Rows.Count).End(xlUp).Row
Set wbk2 = Workbooks.Open("Your File Path Here") 'Your Filepath here
WBK2Range = wbk2.Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row

    For j = 1 To WBK1Range
        For i = 1 To WBK2Range
             If wbk1.Cells(j, 1).Value = wbk2.Worksheets("Sheet1").Cells(i, 1).Value Then
                wbk2.Worksheets("Sheet1").Cells(j, 17).Value = wbk1.Cells(i, 17).Value 'Copies over Column Q
                wbk2.Worksheets("Sheet1").Cells(j, 18).Value = wbk1.Cells(i, 18).Value 'Copies over Column R
                wbk2.Worksheets("Sheet1").Cells(j, 19).Value = wbk1.Cells(i, 19).Value 'Copies over Column S
            Else
            End If
    Next i
Next j

End Sub
</code>```

Body:
This should do what you are looking for. Place the macro in the workbook that contains all the filled columns, and change the path link to the second workbook file that you want to copy data over to. You may also need to change the sheet name from "Sheet1" if your sheet name is different.

Sub copyOnMatch()

Dim i As Long
Dim j As Long
Dim wbk1, wbk2 As Workbook

Set wbk1 = ThisWorkbook.Sheets("Sheet1")
WBK1Range = wbk1.Range("A" & Rows.Count).End(xlUp).Row
Set wbk2 = Workbooks.Open("Your File Path Here") 'Your Filepath here
WBK2Range = wbk2.Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row

    For j = 1 To WBK1Range
        For i = 1 To WBK2Range
             If wbk1.Cells(j, 1).Value = wbk2.Worksheets("Sheet1").Cells(i, 1).Value Then
                wbk2.Worksheets("Sheet1").Cells(j, 17).Value = wbk1.Cells(i, 17).Value 'Copies over Column Q
                wbk2.Worksheets("Sheet1").Cells(j, 18).Value = wbk1.Cells(i, 18).Value 'Copies over Column R
                wbk2.Worksheets("Sheet1").Cells(j, 19).Value = wbk1.Cells(i, 19).Value 'Copies over Column S
            Else
            End If
    Next i
Next j

End Sub


问:
Python ttk.Style: How to find all possible options to configure?
I'm using python2.7 on Linux. I started experimenting with ttk styles.
I wondered where to find the complete Layout of a widget. For example a Treeview.

When I run:

```<code>import ttk
from pprint import pprint
s = ttk.Style()
ttk.Treeview().pack()

layout = s.layout('Treeview')
pprint(layout)
</code>```

I get this output:

```<code>[('Treeview.field',
  {'border': '1',
   'children': [('Treeview.padding',
                 {'children': [('Treeview.treearea', {'sticky': 'nswe'})],
                  'sticky': 'nswe'})],
   'sticky': 'nswe'})]
</code>```

When I run:

```<code>s.configure('Treeview.Heading', background='red')
</code>```

I get the desired red heading:

My question is:

How do I get the whole layout of the widgets?

As I have found out about the existence of Treeview.Heading on the internet. Why does it not appear in the output of s.layout?

答:
This solved it:

import tkinter.ttk as ttk
from pprint import pprint

s = ttk.Style()
data = {}
for e in s.element_names():
    data[e] = s.element_options(e)

pprint(data)
```

Body:
I'm using python2.7 on Linux. I started experimenting with ttk styles.
I wondered where to find the complete Layout of a widget. For example a Treeview.

When I run:

import ttk
from pprint import pprint
s = ttk.Style()
ttk.Treeview().pack()

layout = s.layout('Treeview')
pprint(layout)

I get this output:

[('Treeview.field',
  {'border': '1',
   'children': [('Treeview.padding',
                 {'children': [('Treeview.treearea', {'sticky': 'nswe'})],
                  'sticky': 'nswe'})],
   'sticky': 'nswe'})]

When I run:

s.configure('Treeview.Heading', background='red')

I get the desired red heading:

My question is:

How do I get the whole layout of the widgets?

As I have found out about the existence of Treeview.Heading on the internet. Why does it not appear in the output of s.layout?

ContentLicense: CC BY-SA 4.0


问:
macOs Fonts are web safe?
Pages app in mac has a long list of fonts. Can I use these fonts on my web page by specifying font-family="xyz"?

What I want to know is the fonts used in mac apps like pages,numbers
are proprietary and unique or they are common fonts that will be available and supported on most devices?

答:
The safest approach will always be to use a web font from google fonts or a font that you have directly in your website so browsers can download it always directly from the website.
If you just call for a font that is installed in the pc like Times New Roman (that both windows and mac generally have) the website probably will work on both windows and mac, but on linux clients it probably won't work, you can do that but you need to set a fallback font just in case they client doesn't have that specific font.

And when you add mobile to the list it gets even worst, generally android has sans droid, or some other propriatary fonts that PCs just don't have unless they are directly installed.

And even IF the browser tried to make up for the lack of font, it might apply a font that doesn't work too well with your website and end up making some pretty weird formatting issues, and if the OS itself has a font with the same type family and it just applies that one you could end up with the same problem, but generally it probably will just show up all as squares/rectangles.

Title: macOs Fonts are web safe?


问:
Windows TCP socket connection using VB.net on Linux
The goal is an vb.net connection between windows and linux.

windows-server (vb.net): The server should listen on port 4001/tcp for connections and do something with the packets.

```<code>Dim serverstream As NetworkStream
Dim serverstreamw As StreamWriter
Dim serverstreamr As StreamReader
Dim Server As TcpListener
Dim serverclient As New TcpClient
Dim ipendpoint As IPEndPoint = New IPEndPoint(IPAddress.Any, 4001)
Dim mainthread As Threading.Thread

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    mainthread = New Threading.Thread(AddressOf mainserver)
    mainthread.Start()
End Sub

Sub mainserver()
    Try
        Server = New TcpListener(ipendpoint)
        Server.Start()
        serverclient = Server.AcceptTcpClient
        serverstream = serverclient.GetStream
        serverstreamr = New StreamReader(serverstream)
        serverstreamw = New StreamWriter(serverstream)
        While True
            Select Case serverstreamr.ReadLine
                Case "onl" '........
                Case "logoff" '........
                Case "iamhere" '........
                    MessageBox.Show("WORKS!!!")
            End Select
        End While
    Catch

    End Try
End Sub
</code>```

linux-client: The client should create an connection with the server and send him packets.

```<code>echo "iamhere" > /dev/tcp/client.ip/4001
</code>```

The problem is that it seems like the server does not open port 4001/tcp. The client gets no connection :/

How to fix that?

答:
The reason the connection doesn't work is because you've got to forward port 4001 in the server's router. Currently it is dropped by the router because the port is not mapped in the router's NAT table, so the router does not know to which LAN device it should send the packet.

As for the message box only being shown once, if that Linux code of yours creates a new TCP connection then you gotta change your code to discard old connections after receiving a message:

```<code> Try
    Server = New TcpListener(ipendpoint)
    Server.Start()
    While True 'Moved While up here to wait for new connections after every command.
        serverclient = Server.AcceptTcpClient
        serverstream = serverclient.GetStream
        serverstreamr = New StreamReader(serverstream)
        serverstreamw = New StreamWriter(serverstream)
        Select Case serverstreamr.ReadLine
            Case "onl" '........
            Case "logoff" '........
            Case "iamhere" '........
                MessageBox.Show("WORKS!!!")
        End Select
        serverclient.Close() 'Close old connection.
    End While
Catch
End Try
</code>```

The reason we do this is because if Linux starts a new connection and the server doesn't, then the server will still be waiting for data on the old connection which isn't used anymore by Linux.

Body:
The goal is an vb.net connection between windows and linux.

windows-server (vb.net): The server should listen on port 4001/tcp for connections and do something with the packets.

Dim serverstream As NetworkStream
Dim serverstreamw As StreamWriter
Dim serverstreamr As StreamReader
Dim Server As TcpListener
Dim serverclient As New TcpClient
Dim ipendpoint As IPEndPoint = New IPEndPoint(IPAddress.Any, 4001)
Dim mainthread As Threading.Thread

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    mainthread = New Threading.Thread(AddressOf mainserver)
    mainthread.Start()
End Sub

Sub mainserver()
    Try
        Server = New TcpListener(ipendpoint)
        Server.Start()
        serverclient = Server.AcceptTcpClient
        serverstream = serverclient.GetStream
        serverstreamr = New StreamReader(serverstream)
        serverstreamw = New StreamWriter(serverstream)
        While True
            Select Case serverstreamr.ReadLine
                Case "onl" '........
                Case "logoff" '........
                Case "iamhere" '........
                    MessageBox.Show("WORKS!!!")
            End Select
        End While
    Catch

    End Try
End Sub

linux-client: The client should create an connection with the server and send him packets.

echo "iamhere" > /dev/tcp/client.ip/4001

The problem is that it seems like the server does not open port 4001/tcp. The client gets no connection :/

How to fix that?

Body:
The reason the connection doesn't work is because you've got to forward port 4001 in the server's router. Currently it is dropped by the router because the port is not mapped in the router's NAT table, so the router does not know to which LAN device it should send the packet.

As for the message box only being shown once, if that Linux code of yours creates a new TCP connection then you gotta change your code to discard old connections after receiving a message:

 Try
    Server = New TcpListener(ipendpoint)
    Server.Start()
    While True 'Moved While up here to wait for new connections after every command.
        serverclient = Server.AcceptTcpClient
        serverstream = serverclient.GetStream
        serverstreamr = New StreamReader(serverstream)
        serverstreamw = New StreamWriter(serverstream)
        Select Case serverstreamr.ReadLine
            Case "onl" '........
            Case "logoff" '........
            Case "iamhere" '........
                MessageBox.Show("WORKS!!!")
        End Select
        serverclient.Close() 'Close old connection.
    End While
Catch
End Try

The reason we do this is because if Linux starts a new connection and the server doesn't, then the server will still be waiting for data on the old connection which isn't used anymore by Linux.


问:
How do I store total points after user input in Javascript?
I'm coding my first JavaScript create your own adventure game. I have an input field for the user to enter his actions, a button to submit the action and an output text field for the story. When the button is clicked it starts a function to calculate the effectiveness of the user action.

Each action has a certain amount of points (25, 50, 75). If the user reaches 100 points after a few tries, he wins. If he reaches over 100 he loses. As long as 100 points aren't met, the user may keep on trying different actions.

The problem is that the function needs to store the current total points in a global variable, but it doesn't do that. After every button click the check function checks if the 100 points are met and gives hints to the user. But right now, it just says "You did it!" which is what it says when you meet 100 total points. What am I doing wrong?

I'm a total beginner at JavaScript, so I hope my code isn't a complete mess. Any help and advice is welcome. :)

Here is my HTML code:

```<code><form>
<fieldset>
<label>Enter your answer here:</label>
<input id="userInput" type="text" name="userInput">
<input id="submit" type="button" name="submit" value="Click!" onclick="userAction()">
<textarea id="txtOutput" type="text" readonly="readonly" name="txtOutput">
</textarea>
</fieldset>
</code>```

And my Javascript code:

```<code>var userInput = document.getElementById("userInput");
var txtOutput = document.getElementById("txtOutput");

txtOutput.value = "(\This is just a test and not the actual game.\) \n\nChoose your method to convince the merchant: \n\nA. compliment him on his work \nB. bribe him with money \nC. initmidate him \nD. blackmail him";

var totalPoints = 0;

function add(points) {
  totalPoints += points;
}

window.userAction = function() {
  var input = userInput.value.toUpperCase();
  var compliment = "A";
  var bribe = "B";
  var intimidate = "C";
  var blackmail = "D";

    if (input == compliment) {
        add(25);
    }
    else if (input == bribe) {
        add(25);
    }
    else if (input == intimidate) {
        add(50);
    }
    else if (input == blackmail) {
        add(75);
    }
    else {
        txtOutput = "Method not found. Choose either A, B, C or D.";
    }
    check();
}

    window.check = function() {
    if (totalPoints <= 25) {
        txtOutput.value = "You have his attention. Keep going.";
        userAction();
    }
    else if (totalPoints <= 50) {
        txtOutput.value = "It's working. Keep going. Don't push it too hard, though.";
        userAction();
    }
    else if (totalPoints <= 75) {
        txtOutput.value = "You almost convinced him. Be careful now!";
        userAction();
    }
    else if (totalPoints = 100) {
        txtOutput.value = "You did it!";
    }
    else if (totalPoints > 100) {
        txtOutput.value = "You pushed it too hard. The merchant runs away!";
    }
    else {
        txtOutput.value = "input not found.";
    }
}
</code>```

The JSfiddle

答:
You simply mistyped equals operator, ==.

```<code>...
else if (totalPoints == 100) {
    txtOutput.value = "You did it!";
}
</code>```

Body:
I'm coding my first JavaScript create your own adventure game. I have an input field for the user to enter his actions, a button to submit the action and an output text field for the story. When the button is clicked it starts a function to calculate the effectiveness of the user action.

Each action has a certain amount of points (25, 50, 75). If the user reaches 100 points after a few tries, he wins. If he reaches over 100 he loses. As long as 100 points aren't met, the user may keep on trying different actions.

The problem is that the function needs to store the current total points in a global variable, but it doesn't do that. After every button click the check function checks if the 100 points are met and gives hints to the user. But right now, it just says "You did it!" which is what it says when you meet 100 total points. What am I doing wrong?

I'm a total beginner at JavaScript, so I hope my code isn't a complete mess. Any help and advice is welcome. :)

Here is my HTML code:

<form>
<fieldset>
Enter your answer here:
<input id="userInput" type="text" name="userInput">
<input id="submit" type="button" name="submit" value="Click!" onclick="userAction()">
<textarea id="txtOutput" type="text" readonly="readonly" name="txtOutput">
</textarea>
</fieldset>

And my Javascript code:

var userInput = document.getElementById("userInput");
var txtOutput = document.getElementById("txtOutput");

txtOutput.value = "(\This is just a test and not the actual game.\) \n\nChoose your method to convince the merchant: \n\nA. compliment him on his work \nB. bribe him with money \nC. initmidate him \nD. blackmail him";

var totalPoints = 0;

function add(points) {
  totalPoints += points;
}

window.userAction = function() {
  var input = userInput.value.toUpperCase();
  var compliment = "A";
  var bribe = "B";
  var intimidate = "C";
  var blackmail = "D";

    if (input == compliment) {
        add(25);
    }
    else if (input == bribe) {
        add(25);
    }
    else if (input == intimidate) {
        add(50);
    }
    else if (input == blackmail) {
        add(75);
    }
    else {
        txtOutput = "Method not found. Choose either A, B, C or D.";
    }
    check();
}

    window.check = function() {
    if (totalPoints <= 25) {
        txtOutput.value = "You have his attention. Keep going.";
        userAction();
    }
    else if (totalPoints <= 50) {
        txtOutput.value = "It's working. Keep going. Don't push it too hard, though.";
        userAction();
    }
    else if (totalPoints <= 75) {
        txtOutput.value = "You almost convinced him. Be careful now!";
        userAction();
    }
    else if (totalPoints = 100) {
        txtOutput.value = "You did it!";
    }
    else if (totalPoints > 100) {
        txtOutput.value = "You pushed it too hard. The merchant runs away!";
    }
    else {
        txtOutput.value = "input not found.";
    }
}

The JSfiddle

Body:
You simply mistyped equals operator, ==.

...
else if (totalPoints == 100) {
    txtOutput.value = "You did it!";
}


问:
Requirements for JSON Parser
I'm thinking about implementing JSON parser for Delphi.
What should a good JSON parser do? Any ideas for requirements?
I believe it should at least output and process JSON...
Looking at XML parsers, should it be more DOM or SAX-like?</p>

答:
I have implemented a pull-style parser in Java, which I find very nice to use.  It parses strictly conforming JSON, with some relaxations accepted (primarily for my specific purposes).  It is published and detailed on my website.  Also published is an additional method which illustrates a document load using the parser - so you can use it either stream-oriented or document oriented.

I highly recommend pull style parsng (I have an XML parser which is pull, also).

OwnerDisplayName: pglowack

Title: Requirements for JSON Parser

OwnerDisplayName: Software Monkey


问:
Trace.WriteLine in ASP.NET Azure
when I use

```<code>Diagnostics.Trace.WriteLine("message", "Information");
</code>```

in my azure-asp.net this does not show up in my  azure compute emulator,
but if I do the same from my worker-role it works, any idea why?

Thanks!

答:
This is with SDK 1.3, right?  In 1.3, web roles by default run with full IIS, which means your actual web app code is in a different app domain from your RoleEntryPoint.  I believe the compute emulator only shows messages from RoleEntryPoint (WebRole.cs or WorkerRole.cs).

To double check, try putting a trace message in OnStart in WebRole.cs; I'm guessing it will show up.

Title: Trace.WriteLine in ASP.NET Azure

Body:
when I use

Diagnostics.Trace.WriteLine("message", "Information");

in my azure-asp.net this does not show up in my  azure compute emulator,
but if I do the same from my worker-role it works, any idea why?

Thanks!


答:
So your problem is you are re-invoking userAction() & with your equality setting vs checking:

```<code>// Notice here you check `<=`
 else if (totalPoints <= 75) {
    txtOutput.value = "You almost convinced him. Be careful now!";
}
// Notice here you SET `=`, this should be `===`
// this will ALWAYS be true
else if (totalPoints = 100) {
    txtOutput.value = "You did it!";
}
// Notice here you check `>`
else if (totalPoints > 100) {
    txtOutput.value = "You pushed it too hard. The merchant runs away!";
}
</code>```

See: https://jsfiddle.net/0mo7peoc/7/

Title: How do I store total points after user input in Javascript?

Body:
So your problem is you are re-invoking userAction() & with your equality setting vs checking:

// Notice here you check `<=`
 else if (totalPoints <= 75) {
    txtOutput.value = "You almost convinced him. Be careful now!";
}
// Notice here you SET `=`, this should be `===`
// this will ALWAYS be true
else if (totalPoints = 100) {
    txtOutput.value = "You did it!";
}
// Notice here you check `>`
else if (totalPoints > 100) {
    txtOutput.value = "You pushed it too hard. The merchant runs away!";
}

See: https://jsfiddle.net/0mo7peoc/7/


问:
VS2017 RC Web deploy - ERROR_CERTIFICATE_VALIDATION_FAILED
First, I upgraded my ASP.NET Core project to 1.1.0. That wasn't smooth at all. Now, when it works, I can't deploy it!

I deploy it to IIS (Windows Server 2012 R2) and I get the error saying

can't validate the certificate ... ERROR_CERTIFICATE_VALIDATION_FAILED!

I added this to my publishing profile:

<AllowUntrustedCertificate>True</AllowUntrustedCertificate>

but that doesn't work in VS2017 RC. So, how can I deploy now?
Why you guys do not provide it from a start? This is an essential operation!

答:
The issue also appears when you are using wrong credentials:  and\or stored password. To check this add into the pubxml file the following line:

```<code><UseMsdeployExe>True</UseMsdeployExe>
</code>```

this will switch from VSMSDeploy to MSDeploy - it got you more verbose with errors.
If you store your password just remove the .pubxml.user file stored near .pubxml file and in Publish setting add the password once more.

Body:
The issue also appears when you are using wrong credentials:  and\or stored password. To check this add into the pubxml file the following line:

<UseMsdeployExe>True</UseMsdeployExe>

this will switch from VSMSDeploy to MSDeploy - it got you more verbose with errors.
If you store your password just remove the .pubxml.user file stored near .pubxml file and in Publish setting add the password once more.


问:
Open Outlook using VBA in MS Access
I am trying to open Outlook when a button is clicked in MS Access, I have the following code which I have gathered online and after tinkering with it it is still not working. Here is my code:

```<code>Private Sub Command56_Click()
Dim obj
On Error Resume Next
Set obj = GetObject(, "Outlook.Application")
On Error GoTo 0
If obj Is Nothing Then Set obj = CreateObject("Outlook.Application")
End Sub
</code>```

Does anyone have any suggestions?

答:
No need to call GetObject. If Outlook is loaded, it will create a reference to it and if not, it will be loaded. It will not create a new instance though.

```<code>Private Sub Command56_Click()
    Dim obj As Object
    Set obj = CreateObject("Outlook.Application")
        obj.Visible = True

    'do work

    obj.Quit  '<-- This will close Outlook
    Set obj = Nothing
End Sub
</code>```

Title: Open Outlook using VBA in MS Access

Body:
I am trying to open Outlook when a button is clicked in MS Access, I have the following code which I have gathered online and after tinkering with it it is still not working. Here is my code:

Private Sub Command56_Click()
Dim obj
On Error Resume Next
Set obj = GetObject(, "Outlook.Application")
On Error GoTo 0
If obj Is Nothing Then Set obj = CreateObject("Outlook.Application")
End Sub

Does anyone have any suggestions?

Body:
No need to call GetObject. If Outlook is loaded, it will create a reference to it and if not, it will be loaded. It will not create a new instance though.

Private Sub Command56_Click()
    Dim obj As Object
    Set obj = CreateObject("Outlook.Application")
        obj.Visible = True

    'do work

    obj.Quit  '<-- This will close Outlook
    Set obj = Nothing
End Sub


问:
Difference between static class and singleton pattern?
What real (i.e. practical) difference exists between a static class and a singleton pattern?

Both can be invoked without instantiation, both provide only one "Instance" and neither of them is thread-safe. Is there any other difference?

答:
As I understand the difference between a Static class and non-Static Singleton class, the static is simply a non-instantiated "type" in C#, where the Singleton is a true "object". In other words, all the static members in a static class are assigned to the type but in the Singleton are housed under the object. But keep in mind, a static class still behaves like a reference type as its not a value type like a Struct.

That means when you create a Singleton, because the class itself isnt static but its member is, the advantage is the static member inside the Singleton that refers to itself is connected to an actual "object" rather than a hollow "type" of itself. That sort of clarifies now the difference between a Static and a Non-Static Singleton beyond its other features and memory usage, which is confusing for me.

Both use static members which are single copies of a member, but the Singleton wraps the referenced member around a true instantiated "object" who's address exists in addition to its static member. That object itself has properties wherein in can be passed around and referenced, adding value. The Static class is just a type so it doesn't exist except to point to its static members. That concept sort of cemented the purpose of the Singleton vs Static Class beyond the inheritance and other issues.

OwnerDisplayName: Jorge Córdoba


问:
ActiveRecord: sort of complicated query with nested associations and sorting
Alrigth, so I'm not sure if this isn't too specific... But I really don't have a clue how to construct such a query, neither in AR, nor in SQL. So here's the situation:

I have a User model. User has_many Projects. A Project, in turn, have a following associations:

Project has_one BasicEvent

Project had_many AdditionalEvents

BasicEvent and AdditionalEvent classes are built on inheritance from a AR model class, Event

Now, the goal is this: on my view, I need:

access to all Projects count per User

access to all Events count, where happened_at attribute in nil

have all the Users sorted, by the count of Events, where happened_at attribute in nil

I made a couple of attempts at it so far, but didn't really get too far... I will appreciate any help with this complicated (at least from my perspective) query.

答:
Assuming basic_events and additional_events have essentially the same columns, a great solution to this problem would be to change your database/app to use single table inheritance.

Assuming you're using Rails 5.x your models would look like this:

```<code>class User < ApplicationRecord
  has_many :projects
  has_many :basic_events, through: :projects
  has_many :additional_events, through: :projects
end
</code>```

```<code>class Project < ApplicationRecord
  belongs_to :user
  has_one :basic_event
  has_many :additional_events
end
</code>```

```<code>class Event < ApplicationRecord
  belongs_to :project
end
</code>```

```<code>class BasicEvent < Event
  belongs_to :project
end
</code>```

```<code>class AdditionalEvent < Event
  belongs_to :project
end
</code>```

This way, there are only three tables involved users, projects and events. Your events table will have a :type column where you can specify if it's basic or additional.

For your queries:

access to all Projects count per User

```<code>User
  .select("users.*, count(projects.id) AS projects_count")
  .joins(:projects)
  .group('users.id')
  .order('projects_count DESC')
</code>```

Using select like this give you access to a :projects_count method on each User object returned in this active record relation, so if you assigned this query to a variable called users_with_projects_count you could do users_with_projects_count.first.projects_count and it would return the number of projects associated with that user.

access to all Events count, where happened_at attribute in nil

```<code>User
  .select("users.*, count(events.id) AS events_count")
  .joins(:events)
  .where('events.happened_at IS NULL')
  .group('users.id')
</code>```

You can access :events_count the same way you did :projects_count in the last example.

have all the Users sorted, by the count of Events, where happened_at attribute in nil

```<code>User
  .select("users.*, count(events.id) AS events_count")
  .joins(:events)
  .where('events.happened_at IS NULL')
  .group('users.id')
  .order('events_count DESC')
</code>```

You use the same query as the last example just add an :order.

Body:
Assuming basic_events and additional_events have essentially the same columns, a great solution to this problem would be to change your database/app to use single table inheritance.

Assuming you're using Rails 5.x your models would look like this:

class User < ApplicationRecord
  has_many :projects
  has_many :basic_events, through: :projects
  has_many :additional_events, through: :projects
end

class Project < ApplicationRecord
  belongs_to :user
  has_one :basic_event
  has_many :additional_events
end

class Event < ApplicationRecord
  belongs_to :project
end

class BasicEvent < Event
  belongs_to :project
end

class AdditionalEvent < Event
  belongs_to :project
end

This way, there are only three tables involved users, projects and events. Your events table will have a :type column where you can specify if it's basic or additional.

For your queries:

access to all Projects count per User

User
  .select("users.*, count(projects.id) AS projects_count")
  .joins(:projects)
  .group('users.id')
  .order('projects_count DESC')

Using select like this give you access to a :projects_count method on each User object returned in this active record relation, so if you assigned this query to a variable called users_with_projects_count you could do users_with_projects_count.first.projects_count and it would return the number of projects associated with that user.

access to all Events count, where happened_at attribute in nil

User
  .select("users.*, count(events.id) AS events_count")
  .joins(:events)
  .where('events.happened_at IS NULL')
  .group('users.id')

You can access :events_count the same way you did :projects_count in the last example.

have all the Users sorted, by the count of Events, where happened_at attribute in nil

User
  .select("users.*, count(events.id) AS events_count")
  .joins(:events)
  .where('events.happened_at IS NULL')
  .group('users.id')
  .order('events_count DESC')

You use the same query as the last example just add an :order.


问:
making standalone toplevels with OCaml and Haskell
In Common Lisp, programs are often produced as binaries with a translator bundled inside. StumpWM is a good example.

How would one do the same with Haskell and OCaml?

It is not necessary to provide a debugger as well, as Common Lisp does, the aim is to make extensions while not depending on the whole translator package ( xmonad which requires GHC ).

P.S. I know about ocamlmktop, and it works great, except I don't really get why it requires "pervasives.cmi" and doesn't bundle it with the binary. So, best thing I can do is mycustomtoplevel -I /path/to/dir/with/pervasives.cmi/. Any way to override it?

答:
With GHC, there is GHC-API, which allows you to embed ghci-like interpreters in your program. It's a quite low-level and often changing library, since it simply provides access to GHC internas.

Then, there is Hint, a library which aims to encapsulate ghc-api behind a well designed and more stable interface.

Nevertheless, I've recently switched from using either of these packages to using an external ghci. The external ghci process is controlled via standard input/output pipes. This change made it easy to stay compatible with GHC 6.12.x and 7.0.x, while our ghc-api code broke with GHC 7.x and hint didn't work out of the box either. I don't know whether there is a new version of hint available, which works with GHC 7.


问:
AWS Cognito and API Gateway for a RESTful API
I would like to build a RESTful API that will be used by a mobile app. We have decided to go for AWS.

I would like to implement a micro service for sign-in/sign-up using the API Gateway. Is their a way to use cognito behind the AWS Api Gateway ? I would like to create a lambda to sign-in users using Cognito. I want to do that to build a complete REST Api and by doing that avoid using any Cognito SDK.

Can you explain if it is possible and if so can someone show me how to proceed ?

答: You should be able to write a Lambda function behind API Gateway endpoint, to receive cognito user credentials and authenticate using Cognito SDK. The response tokens from cognito authenticateUser methods needs to be sent back to your mobile client to invoke other API Gateway endpoints.</p>


问:
Embedding react widget into another website
I'm building a widget that's going to be embedded into all sorts of websites.
I want to build it in React, but i'm not sure what precautions should I take. For example with jQuery you just use the "noConflict" function that prevents collision with the other site's scripts.
Do I need to do something similar with React?
Thanks.</p>

答: It is quite possible, and this explains it nicely: https://facebook.github.io/react/docs/integrating-with-other-libraries.html</p>


问:
How to add razor variables to column template in kendo grid for if else logic
I am trying to use a kendo grid with Razor syntax, and using a if:else logic to build a header template. The problem I am having is that the if statement does not check a property of the model for the kendo grid, but a SessionHelper property from c# razor. I can't seem to get it correctly. I am currently using the following, but it is not working.

We are using ClientTemplate like so:

```<code>.ClientTemplate("#= getLinks(data)#")
</code>```

The function code is listed below:

```<code>function getLinks(data) {

        var level2Access = '@SessionHelper.IsUserLevel2Access()';
        var model = "<a href='javascript:GetCertsHistory(" + data.ControlNumber + ")'>Certs</a> | " +
          "<a href='javascript:GetInvoicesHistory(" + data.ControlNumber + ")'>Invoices</a> | ";

        if (level2Access) {
            model += "<a href='javascript:GetItemToEdit(" + data.ControlNumber + ")'>Edit</a>";
        }

        return model;

    }
</code>```

Now, what is strange is that if one object has the control number of all numeric, it works fine. If the control number is numeric then alpha it fails trying to just call the function for viewing certs.

The error is gets in the developer tools is here:

```<code>GetCertHistory(1210000bbbtest123)   "Invalid or unexpected token"
</code>```

I have no idea on this one as to why this occurs only when the parameter is alphanumeric and not just numeric. I even thought maybe there was a special character I was not seeing, so I ran trim against the params, but it still occurs. Any thought's on this one?

答:
I would change the way you are doing this to an external template something like this:

```<code>.ClientTemplate("#=getLinks(data)#")
</code>```

then have a javascript function that gets the links for you like this (Untested but should work) :

```<code> function getLinks(data) {
        console.log(data);
        var level2Access = '@SessionHelper.IsUserLevel2Access()';
        var model = "<a href='javascript:GetCertsHistory(\"" + data.ControlNumber +"\")'>Certs</a> | " +
          "<a href='javascript:GetInvoicesHistory(\"" + data.ControlNumber + "\")'>Invoices</a> | ";

        if (level2Access) {
            model += "<a href='javascript:GetItemToEdit(\"" + data.ControlNumber + "\")'>Edit</a>";
        }

        return model;

    }
</code>```

alternatively you could look to use external templates for these links which may be a more maintainable solution in the future but this should work for you.

Any issues let me know and I will update the answer for you

Body:
I am trying to use a kendo grid with Razor syntax, and using a if:else logic to build a header template. The problem I am having is that the if statement does not check a property of the model for the kendo grid, but a SessionHelper property from c# razor. I can't seem to get it correctly. I am currently using the following, but it is not working.

We are using ClientTemplate like so:

.ClientTemplate("#= getLinks(data)#")

The function code is listed below:

function getLinks(data) {

        var level2Access = '@SessionHelper.IsUserLevel2Access()';
        var model = "Certs | " +
          "Invoices | ";

        if (level2Access) {
            model += "Edit";
        }

        return model;

    }

Now, what is strange is that if one object has the control number of all numeric, it works fine. If the control number is numeric then alpha it fails trying to just call the function for viewing certs.

The error is gets in the developer tools is here:

GetCertHistory(1210000bbbtest123)   "Invalid or unexpected token"

I have no idea on this one as to why this occurs only when the parameter is alphanumeric and not just numeric. I even thought maybe there was a special character I was not seeing, so I ran trim against the params, but it still occurs. Any thought's on this one?

Body:
I would change the way you are doing this to an external template something like this:

.ClientTemplate("#=getLinks(data)#")

then have a javascript function that gets the links for you like this (Untested but should work) :

 function getLinks(data) {
        console.log(data);
        var level2Access = '@SessionHelper.IsUserLevel2Access()';
        var model = "<a href='javascript:GetCertsHistory(\"" + data.ControlNumber +"\")'>Certs</a> | " +
          "<a href='javascript:GetInvoicesHistory(\"" + data.ControlNumber + "\")'>Invoices</a> | ";

        if (level2Access) {
            model += "<a href='javascript:GetItemToEdit(\"" + data.ControlNumber + "\")'>Edit</a>";
        }

        return model;

    }

alternatively you could look to use external templates for these links which may be a more maintainable solution in the future but this should work for you.

Any issues let me know and I will update the answer for you


问:
Asynchronous communication with multiple web servers C#

I have one 'main' server, and several other servers (Extensions) which need to be controlled by the main server.

The Extensions each have a Web Reference to their respective server. Controlling these extensions is done by Init(), Start() and Stop() web calls. Up until now I did this synchronously, the main server for example calls:

```<code>public void InitExtensions()
{
    foreach (Extension extension in GetEnabledExtensionList())
    {
        extension.Init();
    }
}
</code>```

And than:

```<code>public void StartExtensions()
{
    foreach (Extension extension in GetEnabledExtensionList())
    {
        extension.Start();
    }
}
</code>```

Where the extension.Init() and extension.Start() will do the webcalls.

Now I want to do this asynchronously, but the tricky part is that the StartExtensions() method should wait for the extension.Init() to be finished. A different Extension can of course be started before another one is initialized.

What is the best way to do this? I think I will need for example lists

```<code>List<Thread> _InitThreads;
List<Thread> _StartThreads;
List<Thread> _StopThreads;
</code>```

And check if each list contains a thread for the respective Extension, and Join() it to wait execution. This gets however very difficult very fast...

答:
You can use parallel foreach. This executes the iterations in parallel(asynchronously) and waits until all iterations are finished(means next call after foreach will be executed after all iterations have finished working)

```<code>Parallel.ForEach(GetEnabledExtensionList(), (extension) =>
{
     extension.Init();
     extension.Start();
});
</code>```

This is a good way because you will know, when all of your servers have been started and also the parallel Tasks/Threads will be handled efficiently(number, priority, etc.) by the OS.

Body:
I have one 'main' server, and several other servers (Extensions) which need to be controlled by the main server.

The Extensions each have a Web Reference to their respective server. Controlling these extensions is done by Init(), Start() and Stop() web calls. Up until now I did this synchronously, the main server for example calls:

public void InitExtensions()
{
    foreach (Extension extension in GetEnabledExtensionList())
    {
        extension.Init();
    }
}

And than:

public void StartExtensions()
{
    foreach (Extension extension in GetEnabledExtensionList())
    {
        extension.Start();
    }
}

Where the extension.Init() and extension.Start() will do the webcalls.

Now I want to do this asynchronously, but the tricky part is that the StartExtensions() method should wait for the extension.Init() to be finished. A different Extension can of course be started before another one is initialized.

What is the best way to do this? I think I will need for example lists

List<Thread> _InitThreads;
List<Thread> _StartThreads;
List<Thread> _StopThreads;

And check if each list contains a thread for the respective Extension, and Join() it to wait execution. This gets however very difficult very fast...

Body:
You can use parallel foreach. This executes the iterations in parallel(asynchronously) and waits until all iterations are finished(means next call after foreach will be executed after all iterations have finished working)

Parallel.ForEach(GetEnabledExtensionList(), (extension) =>
{
     extension.Init();
     extension.Start();
});

This is a good way because you will know, when all of your servers have been started and also the parallel Tasks/Threads will be handled efficiently(number, priority, etc.) by the OS.


问:
jQuery money input mask not working in rails project
I am using the jquery-inputmask-rails gem.  Ultimately: it is pulling in Robin Herbots' inputmask jQuery plugin.

As instructed in the jquery-inputmask-rails gem, I put this in application.js:

```<code>//= require jquery.inputmask
//= require jquery.inputmask.extensions
//= require jquery.inputmask.numeric.extensions
</code>```

And here are my two masks:

```<code>$(document).on('turbolinks:load', function() {
  $('.mask_phone').inputmask({mask: "(999) 999-9999"});
  $('.mask_money').inputmask({alias: 'currency', rightAlign: true, placeholder: "", prefix: '', autoGroup: false, digitsOptional: true});
});
</code>```

As far as usage goes: you should be able to just add the appropriate masking class to the input:

```<code><%= f.text_field :some_field, class: "mask_money" %>
</code>```

The issue I am having is that the mask_phone mask works, but the mask_money does not work at all.

I do notice in the logs it says this:

TypeError: null is not an object (evaluating 'e.mask.toString')

The odd thing is that in another project: I did not use the jquery-inputmask-rail gem, but instead brought in the jQuery input mask code into the Vendor directory directly, and it worked.

What am I missing?

答:
My gut tells me that the jquery-inputmask-rails gem is not looking at an updated version of Robin Herbots' input mask plugin.

I removed the gem

I put the jQuery.inputmask.bundle.js in the vender folder.

In application.js I put //= require jquery.inputmask.bundle.js and removed the require statements associated to the gem.

And then all my input masks worked.

Body:
I am using the jquery-inputmask-rails gem.  Ultimately: it is pulling in Robin Herbots' inputmask jQuery plugin.

As instructed in the jquery-inputmask-rails gem, I put this in application.js:

//= require jquery.inputmask
//= require jquery.inputmask.extensions
//= require jquery.inputmask.numeric.extensions

And here are my two masks:

$(document).on('turbolinks:load', function() {
  $('.mask_phone').inputmask({mask: "(999) 999-9999"});
  $('.mask_money').inputmask({alias: 'currency', rightAlign: true, placeholder: "", prefix: '', autoGroup: false, digitsOptional: true});
});

As far as usage goes: you should be able to just add the appropriate masking class to the input:

<%= f.text_field :some_field, class: "mask_money" %>

The issue I am having is that the mask_phone mask works, but the mask_money does not work at all.

I do notice in the logs it says this:

TypeError: null is not an object (evaluating 'e.mask.toString')

The odd thing is that in another project: I did not use the jquery-inputmask-rail gem, but instead brought in the jQuery input mask code into the Vendor directory directly, and it worked.

What am I missing?


问:
Promise in promise?
Is there any way I can make the following work:

function A

This function returns a promise that does a task which uses multiple webworkers, once the webworkers have collectively finished this task it will resolve the promise.

function B

This function executes function A, and after that it executes multiple other functions that require A to have been done first.

function C

This function executes function B, and after that it executes multiple other functions that require A. This function may onle be called once, as it is a single process which improves a certain genetic algorithm task by executing function B multiple times sequentially. (so no callback B -> C).

Something like this:

```<code>var someObject = {test: null};

function A () {
    return new Promise((resolve, reject) => {
    // do some task which requires webworkers
    someObject.test = 10;
  });
}

async function B(){
    await A();

  someObject.test *= 4;
  return someObject.test;
}

function C(){
    // set up complicated options here

  // a loop using these options
  var i = 100;
  while(i--){
    var x = B();

    console.log(x);
    // do tasks that require B;
  }
}

C();
</code>```

View it here on JSFiddle, please note that I want to avoid any kind of callbacks because I am already working with a complicated object architecture (i'm doing neuro-evolution).

The best thing I could think of is somehow wrapping function B in a promise as well, but I haven't figured out how to do that.

答:
You could return a promise from B(). Note, you don't need to resolve someObject in B() (i.e. resolve(someObject.test)) because it's a global var, but I did in order to demonstrate how to resolve a value and to follow your example code. Also note I removed the loop for example sake.

EDIT - thanks to @t.niese and others for pointing out the anti-pattern in my original answer. Please see the updated answer, below

https://jsfiddle.net/ey07zy6h/9/

```<code>var someObject = {test: null};

function A () {
    console.log('in a')
    return new Promise((resolve, reject) => {
        // do some task which requires webworkers
        someObject.test = 10;
        resolve()
  });
}

function B() {
    console.log('in b')
    return A()
    .then(() => new Promise((resolve, reject) => {
        someObject.test *= 4;
        resolve(someObject.test);
    }))
    .catch(e => {
        console.log('Err in A: ' + e)
    })
}

function C() {
    // set up complicated options here
    console.log('in c')

    // a loop using these options
    var i = 100;
    // while(i--) {
    B()
    .then(data => {
        let x = data;
        console.log('X is: ' + JSON.stringify(x));
        // do tasks that require B;
    })
    .catch(e => {
        console.log('Err in B', e)
    })
  // }
}

C();
</code>```

Title: Promise in promise?

Body:
Is there any way I can make the following work:

function A

This function returns a promise that does a task which uses multiple webworkers, once the webworkers have collectively finished this task it will resolve the promise.

function B

This function executes function A, and after that it executes multiple other functions that require A to have been done first.

function C

This function executes function B, and after that it executes multiple other functions that require A. This function may onle be called once, as it is a single process which improves a certain genetic algorithm task by executing function B multiple times sequentially. (so no callback B -> C).

Something like this:

var someObject = {test: null};

function A () {
    return new Promise((resolve, reject) => {
    // do some task which requires webworkers
    someObject.test = 10;
  });
}

async function B(){
    await A();

  someObject.test *= 4;
  return someObject.test;
}

function C(){
    // set up complicated options here

  // a loop using these options
  var i = 100;
  while(i--){
    var x = B();

    console.log(x);
    // do tasks that require B;
  }
}

C();

View it here on JSFiddle, please note that I want to avoid any kind of callbacks because I am already working with a complicated object architecture (i'm doing neuro-evolution).

The best thing I could think of is somehow wrapping function B in a promise as well, but I haven't figured out how to do that.

Body:
You could return a promise from B(). Note, you don't need to resolve someObject in B() (i.e. resolve(someObject.test)) because it's a global var, but I did in order to demonstrate how to resolve a value and to follow your example code. Also note I removed the loop for example sake.

EDIT - thanks to @t.niese and others for pointing out the anti-pattern in my original answer. Please see the updated answer, below

https://jsfiddle.net/ey07zy6h/9/

var someObject = {test: null};

function A () {
    console.log('in a')
    return new Promise((resolve, reject) => {
        // do some task which requires webworkers
        someObject.test = 10;
        resolve()
  });
}

function B() {
    console.log('in b')
    return A()
    .then(() => new Promise((resolve, reject) => {
        someObject.test *= 4;
        resolve(someObject.test);
    }))
    .catch(e => {
        console.log('Err in A: ' + e)
    })
}

function C() {
    // set up complicated options here
    console.log('in c')

    // a loop using these options
    var i = 100;
    // while(i--) {
    B()
    .then(data => {
        let x = data;
        console.log('X is: ' + JSON.stringify(x));
        // do tasks that require B;
    })
    .catch(e => {
        console.log('Err in B', e)
    })
  // }
}

C();


问:
List<T> add method in C#
As I know. List Add method works as below.

```<code>List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");
</code>```

If I designed the data structure as this

```<code>List<object> lstObj = new List<object>();
if (true)  // string members
{
    cities.Add("New York");
    cities.Add("Istanbul");
}
else // List obj members here
{
    List<object> AListObject= new List<object>();
    cities.Add(AListObject);  // how to handle this?
}
</code>```

Does the List Add method works or not if I add different types members in the same function.

答: Since you created a list of type object you can add anything to it since every type can be boxed into an object.

Title: List<T> add method in C#

Body:
As I know. List Add method works as below.

List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");

If I designed the data structure as this

List<object> lstObj = new List<object>();
if (true)  // string members
{
    cities.Add("New York");
    cities.Add("Istanbul");
}
else // List obj members here
{
    List<object> AListObject= new List<object>();
    cities.Add(AListObject);  // how to handle this?
}

Does the List Add method works or not if I add different types members in the same function.


问:
Is it necessary to check for non-zero length when read from a Reader and write to a Writer in Golang?
When I try to copy from a Reader to a Writer manually, I notice that this works:

```<code>func fromAToB(a, b net.Conn) {
    buf := make([]byte, 1024*32)
    for {
        n, err := a.Read(buf)
        if n > 0 {
            if err != nil {
                log.Fatal(err)
            }
            b.Write(buf[0:n])
        }
    }
}
</code>```

But this doesn't

```<code>func fromAToB(a, b net.Conn) {
    buf := make([]byte, 1024*32)
    for {
        _, err := a.Read(buf)
        if err != nil {
            log.Fatal(err)
        }
        b.Write(buf)
    }
}
</code>```

So the questions are:

Why is the check if n>0 necessary?

Is this only necessary for net.Conn or for any type that implements the Reader and Writer interfaces?

EDIT: The second snippet runs fine without any runtime error, just that the behavior is not correct. I want to know what is the effect of that n>0 check and what will happen under the surface when I remove it.

答: I figured it out: without n, it will write the whole buffer (32*1024 bytes) to the Writer instead of just n bytes, and that's the source of the weird behavior.

Body:
When I try to copy from a Reader to a Writer manually, I notice that this works:

func fromAToB(a, b net.Conn) {
    buf := make([]byte, 1024*32)
    for {
        n, err := a.Read(buf)
        if n > 0 {
            if err != nil {
                log.Fatal(err)
            }
            b.Write(buf[0:n])
        }
    }
}

But this doesn't

func fromAToB(a, b net.Conn) {
    buf := make([]byte, 1024*32)
    for {
        _, err := a.Read(buf)
        if err != nil {
            log.Fatal(err)
        }
        b.Write(buf)
    }
}

So the questions are:

Why is the check if n>0 necessary?

Is this only necessary for net.Conn or for any type that implements the Reader and Writer interfaces?

EDIT: The second snippet runs fine without any runtime error, just that the behavior is not correct. I want to know what is the effect of that n>0 check and what will happen under the surface when I remove it.


问:
Executable jar closes immediately after launching (Slick2D)
So I made an executable file with Eclipse but when I double-click it nothing happens. It IS NOT because I've got wrong association for running .jar files (I'm running okey my another jar program just by double-clicking it).
I also tried with command prompt and the console doesn't print anything at all and get back to be "normal".

I think it's something with main class so the thread doesn't last but closes after running (however it looks like the code isn't run because console would print lot of Slick stuff).

So here is the main method:

```<code>public static void main(String[] args) {
    Shiftjumper shiftjumper = new Shiftjumper("Shiftjumper - behavior prototype");
    try {
        AppGameContainer gc = new AppGameContainer(shiftjumper);
        gc.setDisplayMode(TILE_SIZE*RIGHT_LEFT_TILES, TILE_SIZE*UP_DOWN_TILES, false);
        //gc.setTargetFrameRate(60);

        gc.start();
    } catch (SlickException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
</code>```

And here the manifest:

```<code>Manifest-Version: 1.0
Rsrc-Class-Path: ./ lwjgl.jar slick.jar
Class-Path: .
Rsrc-Main-Class: engine.Shiftjumper
Main-Class: org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader
</code>```

答: Try running the jar in your terminal or command prompt, if there are any exceptions it will print to the console and you can debug</p>

Body:
So I made an executable file with Eclipse but when I double-click it nothing happens. It IS NOT because I've got wrong association for running .jar files (I'm running okey my another jar program just by double-clicking it).
I also tried with command prompt and the console doesn't print anything at all and get back to be "normal".

I think it's something with main class so the thread doesn't last but closes after running (however it looks like the code isn't run because console would print lot of Slick stuff).

So here is the main method:

public static void main(String[] args) {
    Shiftjumper shiftjumper = new Shiftjumper("Shiftjumper - behavior prototype");
    try {
        AppGameContainer gc = new AppGameContainer(shiftjumper);
        gc.setDisplayMode(TILE_SIZE*RIGHT_LEFT_TILES, TILE_SIZE*UP_DOWN_TILES, false);
        //gc.setTargetFrameRate(60);

        gc.start();
    } catch (SlickException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

And here the manifest:

Manifest-Version: 1.0
Rsrc-Class-Path: ./ lwjgl.jar slick.jar
Class-Path: .
Rsrc-Main-Class: engine.Shiftjumper
Main-Class: org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader


问:
Horizontal slider with pure JS
I have a stupid, easy question, but I am the beginner in JS. I want to create a horizontal slider. For now the JS code looks like this:

```<code>var slideIndex = 0;
slider();

function slider() {
var i;
var x = document.getElementsByClassName("part");
for (i = 0; i < x.length; i++) {
  x[i].style.display = "none";
}

slideIndex++;
if (slideIndex > x.length) {slideIndex = 1}
x[slideIndex-1].style.display = "inline";
setTimeout(slider, 3000);

}
</code>```

I know that i should use marginLeft property to make the images showed from left to right, but I don't know how to use this property in the code. Any help/hint would be really appreciated!

HTML code:

```<code>     <div class="container">
                <section class="content">
                        <div id="img1" class="slide">
                            <h2>...</h2>
                            <p>....</p>
                        </div>
                        <div id="img2" class="slide">
                            <h2>....</h2>
                            <p>....</p>
                        </div>
                </section>
            </div>
</code>```

答:
Maybe you could add a "slideOut" animation class

    var slideIndex = 0;
    slider();
    function slider() {
        var i;
        var x = document.getElementsByClassName("part");
        for (i = 0; i < x.length; i++) {
            x[i].classList.remove("slide");
            x[i].classList.remove("slideOut");
            x[i].className += " slideOut";
        }
        slideIndex++;
        if (slideIndex > x.length) {
            slideIndex = 1
        }
        x[slideIndex - 1].classList.remove("slideOut");
        x[slideIndex - 1].style.display = "inline";
        x[slideIndex - 1].className += " slide";
        setTimeout(slider, 1500);
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  .content {
            position: relative;
            width: 100px;
            height: 100px;
            overflow: auto;
        }

        .row {
            margin: 0 auto;
            width: 50%;
        }

        .slide {
            position: absolute;
            left: -100px;
            width: 100px;
            height: 100px;
            -webkit-animation: slide 0.5s forwards;
            -webkit-animation-delay: 0.5s;
            animation: slide 0.5s forwards;
            animation-delay: 0.5s;
        }

        @-webkit-keyframes slide {
            100% {
                left: 0;
            }
        }

        @keyframes slide {
            100% {
                left: 0;
            }
        }

        .slideOut {
            position: absolute;
            left: 0px;
            width: 100px;
            height: 100px;
            -webkit-animation: slideOut 0.5s forwards;
            -webkit-animation-delay: 0.5s;
            animation: slideOut 0.5s forwards;
            animation-delay: 0.5s;
        }

        @-webkit-keyframes slideOut {
            100% {
                left: 100px;
            }
        }

        @keyframes slideOut {
            100% {
                left: 100px;
            }
        }

        #img1 {
            background: red;
            text-align: center
        }

        #img2 {
            background: blue;
            text-align: center
        }

        #img3 {
            background: greenyellow;
            text-align: center
        }

        #img4 {
            background: orangered;
            text-align: center
        }</code>```

1

2

3

4

```

Title: Horizontal slider with pure JS

Body:
I have a stupid, easy question, but I am the beginner in JS. I want to create a horizontal slider. For now the JS code looks like this:

var slideIndex = 0;
slider();

function slider() {
var i;
var x = document.getElementsByClassName("part");
for (i = 0; i < x.length; i++) {
  x[i].style.display = "none";
}

slideIndex++;
if (slideIndex > x.length) {slideIndex = 1}
x[slideIndex-1].style.display = "inline";
setTimeout(slider, 3000);

}

I know that i should use marginLeft property to make the images showed from left to right, but I don't know how to use this property in the code. Any help/hint would be really appreciated!

HTML code:

...

....

....

....

Body:
Maybe you could add a "slideOut" animation class

    var slideIndex = 0;
    slider();
    function slider() {
        var i;
        var x = document.getElementsByClassName("part");
        for (i = 0; i < x.length; i++) {
            x[i].classList.remove("slide");
            x[i].classList.remove("slideOut");
            x[i].className += " slideOut";
        }
        slideIndex++;
        if (slideIndex > x.length) {
            slideIndex = 1
        }
        x[slideIndex - 1].classList.remove("slideOut");
        x[slideIndex - 1].style.display = "inline";
        x[slideIndex - 1].className += " slide";
        setTimeout(slider, 1500);
    }

  .content {
            position: relative;
            width: 100px;
            height: 100px;
            overflow: auto;
        }

        .row {
            margin: 0 auto;
            width: 50%;
        }

        .slide {
            position: absolute;
            left: -100px;
            width: 100px;
            height: 100px;
            -webkit-animation: slide 0.5s forwards;
            -webkit-animation-delay: 0.5s;
            animation: slide 0.5s forwards;
            animation-delay: 0.5s;
        }

        @-webkit-keyframes slide {
            100% {
                left: 0;
            }
        }

        @keyframes slide {
            100% {
                left: 0;
            }
        }

        .slideOut {
            position: absolute;
            left: 0px;
            width: 100px;
            height: 100px;
            -webkit-animation: slideOut 0.5s forwards;
            -webkit-animation-delay: 0.5s;
            animation: slideOut 0.5s forwards;
            animation-delay: 0.5s;
        }

        @-webkit-keyframes slideOut {
            100% {
                left: 100px;
            }
        }

        @keyframes slideOut {
            100% {
                left: 100px;
            }
        }

        #img1 {
            background: red;
            text-align: center
        }

        #img2 {
            background: blue;
            text-align: center
        }

        #img3 {
            background: greenyellow;
            text-align: center
        }

        #img4 {
            background: orangered;
            text-align: center
        }

<div class="row">
    <section class="content">
        <div id="img1" class="part"><img src="" alt="">
            <h3>1</h3></div>
        <div id="img2" class="part"><img src="" alt="">
            <h3>2</h3></div>
        <div id="img3" class="part"><img src="" alt="">
            <h3>3</h3></div>
        <div id="img4" class="part"><img src="" alt="">
            <h3>4</h3></div>
    </section>
</div>


问:
Why is putting git repositories inside of a Dropbox folder not recommended?
When creating a Git repository inside of a Dropbox folder using the GitHub application for OSX I get the following message:

Putting git repositories inside of a Dropbox folder is not
  recommended. Are you sure you want to create a repository here?

Why isn't that recommended?

答:
DropBox and other similar cloud disk services such as SpiderOak will mess up your git index files because it might try to synchronize in the middle of these files modifications, and so it will upload a partial state and will then download it back, completely corrupting your git state.

Luckily, this is easily fixable by coming back to the last state using git reset --keep.

Then, to avoid this issue, you can:

Bundle your git index in one file using git bundle create my_repo.git --all.

Set a delay for the file monitoring, eg 5 minutes, instead of instantaneous. This will reduce the chances DropBox synchronizes a partial state in the middle of a change. It also helps greatly when modifying files on the cloud disk on-the-fly (such as with instantaneous saving note-taking apps).


问:
How to prevent entry of a disabled date in bootstrap-datepicker
I am running uxsolutions / bootstrap-datepicker (https://github.com/uxsolutions/bootstrap-datepicker).

I have disabled dates in the popup calendar widget just fine (see code below). Yet in the date's textbox, I can enter a disabled date (screen shot below).

How can I get the date box to recognize disabled dates and prevent them from being able to be input?

```<code>  $('#eventDate-container .input-group.date').datepicker({
    weekStart: 1, // calendar starts on Monday
    autoclose: true,
    todayHighlight: true,
    startDate: "4/10/2017", // disables all dates prior to this date
    datesDisabled: ['01/01/1970', '12/31/2099'] // placeholder sample for possible future use
  });
</code>```

答:
I patched the code:</p>

```<code>keydown: function(e){
    case 13: // enter
        if (!this.o.forceParse)
            break;
        **if (this.picker.find('td.focused.day').hasClass('disabled'))
            break;**
        focusDate = this.focusDate || this.dates.get(-1) || this.viewDate;
        if (this.o.keyboardNavigation) {
            this._toggle_multidate(focusDate);
            dateChanged = true;
        }
</code>```

Body:
I am running uxsolutions / bootstrap-datepicker (https://github.com/uxsolutions/bootstrap-datepicker).

I have disabled dates in the popup calendar widget just fine (see code below). Yet in the date's textbox, I can enter a disabled date (screen shot below).

How can I get the date box to recognize disabled dates and prevent them from being able to be input?

  $('#eventDate-container .input-group.date').datepicker({
    weekStart: 1, // calendar starts on Monday
    autoclose: true,
    todayHighlight: true,
    startDate: "4/10/2017", // disables all dates prior to this date
    datesDisabled: ['01/01/1970', '12/31/2099'] // placeholder sample for possible future use
  });

Body:
I patched the code:

keydown: function(e){
    case 13: // enter
        if (!this.o.forceParse)
            break;
        **if (this.picker.find('td.focused.day').hasClass('disabled'))
            break;**
        focusDate = this.focusDate || this.dates.get(-1) || this.viewDate;
        if (this.o.keyboardNavigation) {
            this._toggle_multidate(focusDate);
            dateChanged = true;
        }


问:
#!/usr/bin/env: No such file or directory
The shebang line in my bin/www file is:

```<code>pi:~/ferc$ head -n 1 bin/www
#!/usr/bin/env node
</code>```

However, executing it:

```<code>pi:~/ferc$ bin/www
bin/www: line 1: #!/usr/bin/env: No such file or directory
</code>```

The env file does exist:

```<code>pi:~/ferc$ ls -lL /usr/bin/env
-rwxr-xr-x 1 root root 31408 Feb 18  2016 /usr/bin/env
</code>```

The node file also exists:

```<code>pi:~/ferc$ ls -al /usr/bin/node
lrwxrwxrwx 1 root root 15 Jul  7 18:29 /usr/bin/node -> /usr/bin/nodejs
</code>```

And node runs fine:

```<code>pi:~/ferc$ node -v
v4.2.6
</code>```

What does the error message really mean? Which file is it complaining about?

答:
The cause was a corrupted file, probably due to a mixture of LF and CF/LF line endings in the file.

What happened were:

I copied the file from a Windows PC to the AWS ec2 Ubuntu instance.

First time I ran the www file, that same error message appeared. The cause at this point was probably the node executable did not exist. I hadn't created the symbolic link yet.

While trying to troubleshoot, I edited and saved the www file using nano. I think at this point the file got corrupted.

Later, I added the symbolic link for /usr/bin/node. However, the same error persisted, but probably due to the corrupted line endings.

I dos2unix the www file, and the error went away.

Body:
The shebang line in my bin/www file is:

pi:~/ferc$ head -n 1 bin/www
#!/usr/bin/env node

However, executing it:

pi:~/ferc$ bin/www
bin/www: line 1: #!/usr/bin/env: No such file or directory

The env file does exist:

pi:~/ferc$ ls -lL /usr/bin/env
-rwxr-xr-x 1 root root 31408 Feb 18  2016 /usr/bin/env

The node file also exists:

pi:~/ferc$ ls -al /usr/bin/node
lrwxrwxrwx 1 root root 15 Jul  7 18:29 /usr/bin/node -> /usr/bin/nodejs

And node runs fine:

pi:~/ferc$ node -v
v4.2.6

What does the error message really mean? Which file is it complaining about?


问:
How to create facebook SignIn & google SignIn button as a floating action button in android?
I am working on android project.In my project, There are two SignIn buttons in my application (facebook,Google).It works properly.So i want to make that Signin buttons as a floating buttons.So how we can do that? I tried it and i also searched on google. But i didn't get any proper solution for it.. So Give me a solution..and
Can we customize Normal Signin button as a floatingButton?</p>

答: you can use one FAB when you click on it two other ones shows with animation and you can choose one of them, check this tutorial for full details.</p>


问:
Python OpenWRT crontab
Im trying to run python script on OpenWrt box:

```<code>#!/root/system/usr/bin/python
import subprocess

p = subprocess.Popen([r"snmpget","-v","1","-c","public","-Oqv","-Ln", "192.168.1.1","1.3.6.1.2.1.2.2.1.10.7"], stdout=subprocess.PIPE).communicate()[0]
data = [r"curl","-d","iface_id=1&content="+ str(p).rstrip() ,"http://192.168.1.5:8080/stat/add_istat/"]
a = subprocess.Popen(data, stdout=subprocess.PIPE).communicate()[0]
</code>```

It's geting data over snmp, then post data by curl to local server.
Its working ok from shell:

```<code>root@OpenWrt:~/python# ./w.py
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0    34    0     6    0    28     31    146 --:--:-- --:--:-- --:--:--     0
</code>```

I can see data in DB.
but from cron:

```<code>0-55/5 * * * * /root/python/w.py
</code>```

I see in logread:

```<code>Dec 20 23:30:01 OpenWrt cron.err crond[1039]: USER root pid 16141 cmd /root/python/w.py
</code>```

But no data in DB :( and nothing in httpd access.log :( why?

答:
I replace curl with python urllib request and now its working! :) </p>

```<code>url = 'http://192.168.1.5:8080/stat/add_istat/"' # write ur URL here

values = {'iface_id' : '1', #write ur specific key/value pair
          'content' : str(p).rstrip(),
         }
try:
   data = urllib.urlencode(values)
   req = urllib2.Request(url, data)
   response = urllib2.urlopen(req)
   the_page = response.read()
   print the_page
except Exception, detail:
   print "Err ", detail
</code>```

Title: Python OpenWRT crontab

Body:
Im trying to run python script on OpenWrt box:

#!/root/system/usr/bin/python
import subprocess

p = subprocess.Popen([r"snmpget","-v","1","-c","public","-Oqv","-Ln", "192.168.1.1","1.3.6.1.2.1.2.2.1.10.7"], stdout=subprocess.PIPE).communicate()[0]
data = [r"curl","-d","iface_id=1&content="+ str(p).rstrip() ,"http://192.168.1.5:8080/stat/add_istat/"]
a = subprocess.Popen(data, stdout=subprocess.PIPE).communicate()[0]

It's geting data over snmp, then post data by curl to local server.
Its working ok from shell:

root@OpenWrt:~/python# ./w.py
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0    34    0     6    0    28     31    146 --:--:-- --:--:-- --:--:--     0

I can see data in DB.
but from cron:

0-55/5 * * * * /root/python/w.py

I see in logread:

Dec 20 23:30:01 OpenWrt cron.err crond[1039]: USER root pid 16141 cmd /root/python/w.py

But no data in DB :( and nothing in httpd access.log :( why?

Body:
I replace curl with python urllib request and now its working! :)

url = 'http://192.168.1.5:8080/stat/add_istat/"' # write ur URL here

values = {'iface_id' : '1', #write ur specific key/value pair
          'content' : str(p).rstrip(),
         }
try:
   data = urllib.urlencode(values)
   req = urllib2.Request(url, data)
   response = urllib2.urlopen(req)
   the_page = response.read()
   print the_page
except Exception, detail:
   print "Err ", detail