答:
```<code>UPDATE a
SET a.boolean='True'
FROM tableA AS a
INNER JOIN  (
     SELECT b.id, max(b.date) AS 'LatestDate'
     FROM tableA AS b
     GROUP BY b.id
 ) as c
 ON a.id=c.id AND a.date=c.LatestDate;
</code>```

Here is the SQL Fiddle link: http://sqlfiddle.com/#!6/bfb3e8/2

Title: Update 1 record according to 2 sorts criteria

Body:
Do you know how can I update 1 record according to 2 sorts criteria?

I have in my table A :

id    |     date    | boolean  | data
-------------------------------------------
001    | 11.13.2017  |    0     | value 1
001    | 09.13.2017  |    1     | value 2
001    | 01.01.2017  |    0     | value 0
002    | 06.15.2017  |    1     | value 3
003    | 04.23.2017  |    1     | value 4
003    | 12.13.2017  |    0     | value 5

I would like by id, change the boolean value according with the most recent date.

for example:

id     |     date    | boolean  | data
-------------------------------------------
001    | 11.13.2017  |    1     | value 1
001    | 09.13.2017  |    0     | value 2
001    | 01.01.2017  |    0     | value 0

Thank you

Body:
UPDATE a
SET a.boolean='True'
FROM tableA AS a
INNER JOIN  (
     SELECT b.id, max(b.date) AS 'LatestDate'
     FROM tableA AS b
     GROUP BY b.id
 ) as c
 ON a.id=c.id AND a.date=c.LatestDate;

Here is the SQL Fiddle link: http://sqlfiddle.com/#!6/bfb3e8/2


来源: stackexchange

问:
What is the best software to host a ruby on rails application on production?
Is webrick the only good option?
I know there is a way of using apache, but is it better than webrick?</p>

答: We use heroku and <del> despite it runs with ruby 1.8.7, </del> I never had problems with it</p>

ContentLicense: CC BY-SA 2.5

Body: We use heroku and  despite it runs with ruby 1.8.7,  I never had problems with it


问:
Lottery Generator
Okay guys I need your help. I'm creating a lottery number generator and it's supposed to ask the user how many numbers s/he wants to pick. After that it's supposed to create an array to hold that many (whatever the user enters) numbers, and then create that many random numbers (between 1 and 99) and fill the array with the random numbers. I have gotten it to create a random number between 1-99 and store it in a single array and display it. My problem is when the user picks how many numbers they want, I can't get it to create an array with that many random numbers in it. Do you guys have any solutions?</p>

```<code>[1]: https://codepen.io/nfinsand/pen/KyqvyV
</code>```

答:
Try changing this line:

```<code>document.getElementById("display").innerHTML = lottoNums[i];
</code>```

To this:

```<code>document.getElementById("display").innerHTML = document.getElementById("display").innerHTML + ' - ' + lottoNums[i];
</code>```

ContentLicense: CC BY-SA 3.0

Title: Lottery Generator

Body:
Okay guys I need your help. I'm creating a lottery number generator and it's supposed to ask the user how many numbers s/he wants to pick. After that it's supposed to create an array to hold that many (whatever the user enters) numbers, and then create that many random numbers (between 1 and 99) and fill the array with the random numbers. I have gotten it to create a random number between 1-99 and store it in a single array and display it. My problem is when the user picks how many numbers they want, I can't get it to create an array with that many random numbers in it. Do you guys have any solutions?

[1]: https://codepen.io/nfinsand/pen/KyqvyV

Body:
Try changing this line:

document.getElementById("display").innerHTML = lottoNums[i];

To this:

document.getElementById("display").innerHTML = document.getElementById("display").innerHTML + ' - ' + lottoNums[i];


问:
Angular 2 how to iterate through multi-dimensional arrays?
EDIT#2

Unfortunately, I haven't had any success incorporating either one of these suggestions. It's late, so I'm heading off to bed, but I'll try to update tomorrow.

Thanks to Pradeep Jain for the help. I'll also try out the Pipe that evil mind suggested.

I've learned how to use the *ngFor command, but it looks like it only works with simple arrays. Here's the code I'm trying to iterate through.

```<code>import {Lesson} from './lesson';

export var LESSONS: Lesson[] = [
{
    "idL": 1,
    "subject": 'Chapter One',
    "points": [
                'picture story', 'spelling test', 'words'
            ]
},
{
    "idL": 2,
    "subject": 'Words',
    "points": [
            'words', 'bacon', 'proliferation'
    ]
}
]
</code>```

So I am trying to access that second array called "points". I don't think it's improperly formatted, but I haven't been able to figure out how to access it.

I did read about angularJs's foreach command, but Angular2's documentation does not show such a command is available.

Any advice?

答:
This worked for me in Angular 4, using Pardeep Jain's answer as a basis. Almost the same as StepUps answer, but with ng-containers:

```<code> constructor() {

        this.data = {
            displayArray:[
                ["Top Row 1st col", "Top Row 2nd col", "Top Row 3rd col"],
                ["Middle Row 1st col", "Middle Row 2nd col", "Middle Row 3rd col"],
                ["Bottom Row 1st col", "Bottom Row 2nd col", "Bottom Row 3rd col"]
            ]
        }

    };
</code>```

in the template:

```<code><table >
    <ng-container *ngFor="let row of data.displayArray; let i = index">
        <tr>
            <ng-container *ngFor="let col of row; let j = index">
                <td>{{col}}</td>
            </ng-container>
        </tr>
    </ng-container>
</table>
</code>```

I didn't need the indexes, but I left them in in case they are needed by others.

Body:
EDIT#2

Unfortunately, I haven't had any success incorporating either one of these suggestions. It's late, so I'm heading off to bed, but I'll try to update tomorrow.

Thanks to Pradeep Jain for the help. I'll also try out the Pipe that evil mind suggested.

I've learned how to use the *ngFor command, but it looks like it only works with simple arrays. Here's the code I'm trying to iterate through.

import {Lesson} from './lesson';

export var LESSONS: Lesson[] = [
{
    "idL": 1,
    "subject": 'Chapter One',
    "points": [
                'picture story', 'spelling test', 'words'
            ]
},
{
    "idL": 2,
    "subject": 'Words',
    "points": [
            'words', 'bacon', 'proliferation'
    ]
}
]

So I am trying to access that second array called "points". I don't think it's improperly formatted, but I haven't been able to figure out how to access it.

I did read about angularJs's foreach command, but Angular2's documentation does not show such a command is available.

Any advice?

Body:
This worked for me in Angular 4, using Pardeep Jain's answer as a basis. Almost the same as StepUps answer, but with ng-containers:

 constructor() {

        this.data = {
            displayArray:[
                ["Top Row 1st col", "Top Row 2nd col", "Top Row 3rd col"],
                ["Middle Row 1st col", "Middle Row 2nd col", "Middle Row 3rd col"],
                ["Bottom Row 1st col", "Bottom Row 2nd col", "Bottom Row 3rd col"]
            ]
        }

    };

in the template:

<table >
    <ng-container *ngFor="let row of data.displayArray; let i = index">
        <tr>
            <ng-container *ngFor="let col of row; let j = index">
                <td>{{col}}</td>
            </ng-container>
        </tr>
    </ng-container>
</table>

I didn't need the indexes, but I left them in in case they are needed by others.


问:
Image control not being populated by binary data from database
I have an image for every student recorded in the database. However when ever l want to show details of a student. All the other stuff is shown besides the image. My code shows no run-time errors or debugging errors. The Id input for the method is the student number entered so as to show information show that student.</p>

```<code>private void Image(string id)
{
    byte[] bytes = (byte[])GetData("SELECT Image FROM SI WHERE  Username=" + id).Rows[0]["Image"];
    string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
    imgPic.ImageUrl = "data:image/jpg;base64," + base64String;
}

private DataTable GetData(string query)
{
    DataTable dt = new DataTable();
    string constr = ConfigurationManager.ConnectionStrings["tlcString"].ConnectionString;

    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                sda.Fill(dt);
            }
        }

        return dt;
    }
}
</code>```

答:
You want to create a completely separate ashx handler or aspx page for this that expects an ID in the URL and does something like the following on page load:

```<code>void Page_Load(object sender, EventArgs e)
{
    string ID = Request.QueryString["ID"];
    byte[] bytes = (byte[])GetData("SELECT Image FROM SI WHERE  Username=" + ID;
    Response.BinaryWrite(bytes);
}
</code>```

Then the ASP:Image in your current page can have a conventional URL more like this:

```<code>private void Image(string id)
{
    imgPic.ImageUrl = "mynewpage.ashx?ID=" + id;
}
</code>```

But don't do exactly this!

This is crazy-vulernable to Sql Injection attacks. It's practically begging to get you hacked. The problem is in the GetData() method, which lacks any mechanism to parameterize your queries. The method as is effectively forces you to write bad code. You need to change the method to something more like this:

```<code>private DataTable GetData(string query, params SqlParameter[] parameters)
{
    DataTable dt = new DataTable();
    string constr = ConfigurationManager.ConnectionStrings["tlcString"].ConnectionString;

    //You can stack these up
    using (SqlConnection con = new SqlConnection(constr))
    using (SqlCommand cmd = new SqlCommand(query, con))
    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
    {
        foreach(var p in parameters)
            cmd.Parameters.Add(p);

         sda.Fill(dt);
    }
    return dt;
}
</code>```

And now you can change the Page_Load() to do this:

```<code>void Page_Load(object sender, EventArgs e)
{
    var userID = new SqlParameter("@Username", SqlDbType.Int);
    userID.Value = Request.QueryString["ID"];

    byte[] bytes = (byte[])GetData("SELECT Image FROM SI WHERE  Username= @Username", userID).Rows[0]["Image"];
    Response.BinaryWrite(bytes);
}
</code>```

When that is done — AND THIS IS IMPORTANT! — go back and check everywhere else that uses the GetData() method to make sure you fix any other places that use string concatenation to put data into a query. This is so important, you might even want to skip the params option on the method, to force a compile error for any query that's not explicitly creating a parameter array, but be sure you get them all.

Body:
I have an image for every student recorded in the database. However when ever l want to show details of a student. All the other stuff is shown besides the image. My code shows no run-time errors or debugging errors. The Id input for the method is the student number entered so as to show information show that student.

private void Image(string id)
{
    byte[] bytes = (byte[])GetData("SELECT Image FROM SI WHERE  Username=" + id).Rows[0]["Image"];
    string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
    imgPic.ImageUrl = "data:image/jpg;base64," + base64String;
}

private DataTable GetData(string query)
{
    DataTable dt = new DataTable();
    string constr = ConfigurationManager.ConnectionStrings["tlcString"].ConnectionString;

    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                sda.Fill(dt);
            }
        }

        return dt;
    }
}

Body:
You want to create a completely separate ashx handler or aspx page for this that expects an ID in the URL and does something like the following on page load:

void Page_Load(object sender, EventArgs e)
{
    string ID = Request.QueryString["ID"];
    byte[] bytes = (byte[])GetData("SELECT Image FROM SI WHERE  Username=" + ID;
    Response.BinaryWrite(bytes);
}

Then the ASP:Image in your current page can have a conventional URL more like this:

private void Image(string id)
{
    imgPic.ImageUrl = "mynewpage.ashx?ID=" + id;
}

But don't do exactly this!

This is crazy-vulernable to Sql Injection attacks. It's practically begging to get you hacked. The problem is in the GetData() method, which lacks any mechanism to parameterize your queries. The method as is effectively forces you to write bad code. You need to change the method to something more like this:

private DataTable GetData(string query, params SqlParameter[] parameters)
{
    DataTable dt = new DataTable();
    string constr = ConfigurationManager.ConnectionStrings["tlcString"].ConnectionString;

    //You can stack these up
    using (SqlConnection con = new SqlConnection(constr))
    using (SqlCommand cmd = new SqlCommand(query, con))
    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
    {
        foreach(var p in parameters)
            cmd.Parameters.Add(p);

         sda.Fill(dt);
    }
    return dt;
}

And now you can change the Page_Load() to do this:

void Page_Load(object sender, EventArgs e)
{
    var userID = new SqlParameter("@Username", SqlDbType.Int);
    userID.Value = Request.QueryString["ID"];

    byte[] bytes = (byte[])GetData("SELECT Image FROM SI WHERE  Username= @Username", userID).Rows[0]["Image"];
    Response.BinaryWrite(bytes);
}

When that is done — AND THIS IS IMPORTANT! — go back and check everywhere else that uses the GetData() method to make sure you fix any other places that use string concatenation to put data into a query. This is so important, you might even want to skip the params option on the method, to force a compile error for any query that's not explicitly creating a parameter array, but be sure you get them all.


问:
how to use JQuery "toggle" with parameters?
I have a table like this:

```<code><table>
  <tr>
    <td><input type="button" title="Toggle" value="Show" id="btn534534" class="toggle" />    </td>
    <td>some data about ID 534534</td>
  </tr>
  <tr id="row534534" class="hiddenRow">
    <td colspan="2">some hidden data about ID 534534 that must show/hide with toggle</td>
  </tr>
  <tr>
    <td><input type="button" title="Toggle" value="Show" id="btn2423434" class="toggle" /></td>
    <td>some data about ID 2423434</td>
  </tr>
  <tr id="row2423434" class="hiddenRow">
    <td colspan="2">some hidden data about ID 2423434that must show/hide with toggle</td>
  </tr>
  <!-- many more rows here -->
</table>
</code>```

There are MANY "sets" of rows like the above.  One row of the table is visible for each "set" of rows.  The second row with class "hiddenRow" is hidden on page load by JQuery like this:

```<code>$("tr.hiddenRow").hide();
</code>```

Now I want each button to toggle visibility of the row immediately after it.  Note that the INPUT in the visible row, and the TR of the hidden row share a unique ID.  I want to have the button onclick call a JQuery function and pass the ID so that JQuery knows which row to toggle.

Any ideas?  I can't find any examples of this online.

答:
My first suggestion when you say:

"MANY ... hidden on page load" is that you're using Javascript to do CSS's job, and it's either already causing or going to cause you a performance problem. Define:

```<code>tr.hiddenRow {
    display: none;
}
</code>```

in your stylesheet, and get rid of the on page load code.

I'd use the following to implement your button code:

```<code>$('input.toggle').live('click', function(ev) {
    var id = this.id.substr(3);
    var row = $('#row' + id);
    if (row.hasClass('hiddenRow'))
        row.removeClass('hiddenRow');
    else
        row.addClass('hiddenRow');
});
</code>```

If row IDs aren't necessary for other functions, you could reduce the size of your HTML by getting rid of the ID on both the input and the tr, then implement toggle with DOM-walking:

```<code>$('input.toggle').live('click', function(ev) {
    var row = $(this).parents('tr').next('tr');
    if (row.hasClass('hiddenRow'))
        row.removeClass('hiddenRow');
    else
        row.addClass('hiddenRow');
});
</code>```

Edit: Hadn't come across jsfiddle before - that's sort of fun. Here you go: http://jsfiddle.net/z6rAe/

Updating again to include my corrections to Šime's answer - why doesn't StackOverflow do code in comments?

```<code>$('#tableID').click(function(ev) {
    if (!$(ev.target).hasClass('toggle')) { return; }
    $(ev.target.id.replace('btn', '#row')).toggle();
});
</code>```

http://jsfiddle.net/7Dy5s/3/

Body:
I have a table like this:

    <input type="button" title="Toggle" value="Show" id="btn534534" class="toggle" />
    some data about ID 534534

    some hidden data about ID 534534 that must show/hide with toggle

    <input type="button" title="Toggle" value="Show" id="btn2423434" class="toggle" />
    some data about ID 2423434

    some hidden data about ID 2423434that must show/hide with toggle

There are MANY "sets" of rows like the above.  One row of the table is visible for each "set" of rows.  The second row with class "hiddenRow" is hidden on page load by JQuery like this:

$("tr.hiddenRow").hide();

Now I want each button to toggle visibility of the row immediately after it.  Note that the INPUT in the visible row, and the TR of the hidden row share a unique ID.  I want to have the button onclick call a JQuery function and pass the ID so that JQuery knows which row to toggle.

Any ideas?  I can't find any examples of this online.

Body:
My first suggestion when you say:

"MANY ... hidden on page load" is that you're using Javascript to do CSS's job, and it's either already causing or going to cause you a performance problem. Define:

tr.hiddenRow {
    display: none;
}

in your stylesheet, and get rid of the on page load code.

I'd use the following to implement your button code:

$('input.toggle').live('click', function(ev) {
    var id = this.id.substr(3);
    var row = $('#row' + id);
    if (row.hasClass('hiddenRow'))
        row.removeClass('hiddenRow');
    else
        row.addClass('hiddenRow');
});

If row IDs aren't necessary for other functions, you could reduce the size of your HTML by getting rid of the ID on both the input and the tr, then implement toggle with DOM-walking:

$('input.toggle').live('click', function(ev) {
    var row = $(this).parents('tr').next('tr');
    if (row.hasClass('hiddenRow'))
        row.removeClass('hiddenRow');
    else
        row.addClass('hiddenRow');
});

Edit: Hadn't come across jsfiddle before - that's sort of fun. Here you go: http://jsfiddle.net/z6rAe/

Updating again to include my corrections to Šime's answer - why doesn't StackOverflow do code in comments?

$('#tableID').click(function(ev) {
    if (!$(ev.target).hasClass('toggle')) { return; }
    $(ev.target.id.replace('btn', '#row')).toggle();
});

http://jsfiddle.net/7Dy5s/3/


问:
How to implement monaco-editor on a webpage without nodejs and electron
i am trying to make a simple web editor i found this thing called Monaco-editor and I've seen someone use it with electron but I want to just use it in plain javascript like on their webpage (link) but how do I do this? I was searching google but I can't find any info on how to implement it</p>

答:
I built a simple project for creating a Knockout binding handler for the Monaco editor and it creates editor instances in browser purely client side. It simply loads the required Monaco resources from the Monaco GitHub repo. So the project index.html contains all the link and script tags required and the most important require configuration that points root to the repo script block is also present. Monaco uses a custom AMD based loader and so upon loading the loader.js script the custom loader is stored in the global require variable.

https://github.com/simpert/MonacoEditorKnockoutBindingHandler

Hope this helps.


问:
Create/Access a ClearCase view (Snapshot or Dynamic) without local admin privileges
In our current environment all the users who would like to access ClearCase will require local administrative rights and i'm looking into the options to remove the local admin privs constraint so that all the users should be able to access if they are part of clearcase domain groups like CCUsers.</p>

答:
Local admin privilege should only be required for installing ClearCase, especially when it comes to the MVFS (MultiView FileSystem) part.

But it is also used for launching ClearCase services. Without a privilege elevation, you would see:

```<code>C:\>net start albd
System error 5 has occurred.
Access is denied.

From Windows Services
Unable to open service Albd for writing on Local Computer
Error 5: Access is denied.
</code>```

First, check if you can set those services as "Automatic": they should be started during Windows Startup, even if the user is not an administrator.

This thread recommends:

Click on Atria Location Broker service and select Properties.

  On the General tab, "Startup type" should be "Automatic".

  On the Log On tab, select the radio button to Log on as "This account" and enter the ALBD user account and password that you should have already setup (e.g. your-domain\clearcase_albd). If you do this properly, the Atria Location Broker service should start automatically for any user.

See also "Troubleshooting ALBD startup failures on Microsoft Windows".

Body:
Local admin privilege should only be required for installing ClearCase, especially when it comes to the MVFS (MultiView FileSystem) part.

But it is also used for launching ClearCase services. Without a privilege elevation, you would see:

C:\>net start albd
System error 5 has occurred.
Access is denied.

From Windows Services
Unable to open service Albd for writing on Local Computer
Error 5: Access is denied.

First, check if you can set those services as "Automatic": they should be started during Windows Startup, even if the user is not an administrator.

This thread recommends:

Click on Atria Location Broker service and select Properties.

  On the General tab, "Startup type" should be "Automatic".

  On the Log On tab, select the radio button to Log on as "This account" and enter the ALBD user account and password that you should have already setup (e.g. your-domain\clearcase_albd). If you do this properly, the Atria Location Broker service should start automatically for any user.

See also "Troubleshooting ALBD startup failures on Microsoft Windows".


问:
UIImageView animated doesn't work properly inside UICollectionViewCell
I would like to add a UIImageView animated inside an UICollectionViewCell so I came up with this code:

```<code>    import UIKit

class MainViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    var items:[String] = ["one", "two", "three", "four"]

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(red: 220/255, green: 220/255, blue: 220/255, alpha: 1.0)
        self.view.addSubview(self.collectionView)
    }

    lazy var collectionView:UICollectionView = {
        var cv = UICollectionView(frame: self.view.bounds, collectionViewLayout: self.flowLayout)
        cv.delegate = self
        cv.dataSource = self
        cv.bounces = true
        cv.alwaysBounceVertical = true
        cv.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
        cv.registerClass(CustomCell.self, forCellWithReuseIdentifier: "cell")
        cv.backgroundColor = UIColor(red: 220/255, green: 220/255, blue: 220/255, alpha: 1.0)
        return cv
    }()

    lazy var flowLayout:UICollectionViewFlowLayout = {
        var flow = UICollectionViewFlowLayout()
        flow.sectionInset = UIEdgeInsetsMake(2.0, 2.0, 2.0, 2.0)
        return flow
    }()

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{

        let width:CGFloat = self.view.bounds.size.width*0.98;
        let height:CGFloat = 150.0;
        return CGSizeMake(width, height)
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return self.items.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CustomCell
        cell.layer.cornerRadius = 4
        cell.backgroundColor = UIColor.whiteColor()
        cell.imgView.animationImages = ["1","2","3","4","5", "6","7","8"].map{UIImage(named: $0)!}
        cell.imgView.animationDuration = NSTimeInterval(0.8)
        cell.imgView.startAnimating()
        return cell
    }

    func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
         return true
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        var alert = UIAlertController(title: "Alert!", message: "Cell tapped", preferredStyle: UIAlertControllerStyle.Alert)
        var action = UIAlertAction(title: "ok", style: UIAlertActionStyle.Cancel) { (dd) -> Void in }
        alert.addAction(action)
        self.presentViewController(alert, animated: true, completion: nil)
    }

}
</code>```

This is my MainViewController with a CollectionView added programmatically.

```<code>    import UIKit

class CustomCell: UICollectionViewCell {

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(self.imgView)
    }

    lazy var imgView:UIImageView = {
        var iv = UIImageView()
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        return iv
    }()

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.imgView.frame = CGRectMake(6,15,self.frame.width*0.2, self.frame.height*0.8)
    }
}
</code>```

And this is my custom UICollectionViewCell with an UIImageView

My problem is when you tap a cell the UIImageView disappears. Trying to solve the problem I started to look another UICoolectionView delegate methods. Then I tried to use shouldHighlightItemAtIndexPath, But If I use this method returning false the animation works fine but the collection view stops responding to didSelectItemAtIndexPath.

This is a github repository with a code that shows the issue: https://github.com/gazolla/ImageAnimation (updated with solution)

SOLUTION:

With matt's help, I made the following changes in my code:

1) add images array to highlightedAnimationImages property

```<code>let animationArray = ["1","2","3","4","5", "6","7","8"].map{UIImage(named: $0)!}
cell.imgView.highlightedAnimationImages = animationArray
</code>```

2) Restart animation when cells are deselected

```<code> func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CustomCell{
        cell.imgView.startAnimating()
    }
 }
</code>```

3) Restart animation when cells are selected

```<code>func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

    let cell = collectionView.cellForItemAtIndexPath(indexPath) as! CustomCell
    cell.imgView.startAnimating()

    //...

}
</code>```

SOLUTION 2:

After some tests, I found out that when you tap and hold a cell UIImageView disappears again, So we have to restart animation in another two methods:

1) didHighlightItemAtIndexPath

```<code>func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) {
        if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CustomCell{
            cell.imgView.startAnimating()
        }

  }
</code>```

2) didUnhighlightItemAtIndexPath

```<code>func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) {
    if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CustomCell{
        cell.imgView.startAnimating()
    }
}
</code>```

答: In case anyone else encounters this nasty bug and the above solutions don't help – try calling imageView.stopAnimating() in your cell's prepareForReuse() function.

Body:
I would like to add a UIImageView animated inside an UICollectionViewCell so I came up with this code:

    import UIKit

class MainViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    var items:[String] = ["one", "two", "three", "four"]

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(red: 220/255, green: 220/255, blue: 220/255, alpha: 1.0)
        self.view.addSubview(self.collectionView)
    }

    lazy var collectionView:UICollectionView = {
        var cv = UICollectionView(frame: self.view.bounds, collectionViewLayout: self.flowLayout)
        cv.delegate = self
        cv.dataSource = self
        cv.bounces = true
        cv.alwaysBounceVertical = true
        cv.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
        cv.registerClass(CustomCell.self, forCellWithReuseIdentifier: "cell")
        cv.backgroundColor = UIColor(red: 220/255, green: 220/255, blue: 220/255, alpha: 1.0)
        return cv
    }()

    lazy var flowLayout:UICollectionViewFlowLayout = {
        var flow = UICollectionViewFlowLayout()
        flow.sectionInset = UIEdgeInsetsMake(2.0, 2.0, 2.0, 2.0)
        return flow
    }()

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{

        let width:CGFloat = self.view.bounds.size.width*0.98;
        let height:CGFloat = 150.0;
        return CGSizeMake(width, height)
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return self.items.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CustomCell
        cell.layer.cornerRadius = 4
        cell.backgroundColor = UIColor.whiteColor()
        cell.imgView.animationImages = ["1","2","3","4","5", "6","7","8"].map{UIImage(named: $0)!}
        cell.imgView.animationDuration = NSTimeInterval(0.8)
        cell.imgView.startAnimating()
        return cell
    }

    func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
         return true
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        var alert = UIAlertController(title: "Alert!", message: "Cell tapped", preferredStyle: UIAlertControllerStyle.Alert)
        var action = UIAlertAction(title: "ok", style: UIAlertActionStyle.Cancel) { (dd) -> Void in }
        alert.addAction(action)
        self.presentViewController(alert, animated: true, completion: nil)
    }

}

This is my MainViewController with a CollectionView added programmatically.

    import UIKit

class CustomCell: UICollectionViewCell {

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(self.imgView)
    }

    lazy var imgView:UIImageView = {
        var iv = UIImageView()
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        return iv
    }()

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.imgView.frame = CGRectMake(6,15,self.frame.width*0.2, self.frame.height*0.8)
    }
}

And this is my custom UICollectionViewCell with an UIImageView

My problem is when you tap a cell the UIImageView disappears. Trying to solve the problem I started to look another UICoolectionView delegate methods. Then I tried to use shouldHighlightItemAtIndexPath, But If I use this method returning false the animation works fine but the collection view stops responding to didSelectItemAtIndexPath.

This is a github repository with a code that shows the issue: https://github.com/gazolla/ImageAnimation (updated with solution)

SOLUTION:

With matt's help, I made the following changes in my code:

1) add images array to highlightedAnimationImages property

let animationArray = ["1","2","3","4","5", "6","7","8"].map{UIImage(named: $0)!}
cell.imgView.highlightedAnimationImages = animationArray

2) Restart animation when cells are deselected

 func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CustomCell{
        cell.imgView.startAnimating()
    }
 }

3) Restart animation when cells are selected

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

    let cell = collectionView.cellForItemAtIndexPath(indexPath) as! CustomCell
    cell.imgView.startAnimating()

    //...

}

SOLUTION 2:

After some tests, I found out that when you tap and hold a cell UIImageView disappears again, So we have to restart animation in another two methods:

1) didHighlightItemAtIndexPath

func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) {
        if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CustomCell{
            cell.imgView.startAnimating()
        }

  }

2) didUnhighlightItemAtIndexPath

func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) {
    if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CustomCell{
        cell.imgView.startAnimating()
    }
}


问:
python distinguish between '300' and '300.0' for a dataframe column
Recently I have been developing some code to read a csv file and store key data columns in a dataframe. Afterwards I plan to have some mathematical functions performed on certain columns in the dataframe.

I've been fairly successful in storing the correct columns in the dataframe. I have been able to have it do whatever maths is necessary such as summations, additions of dataframe columns, averaging etc.

My problem lies in accessing specific columns once they are stored in the dataframe. I was working with a test file to get everything working and managed this no problem. The problems arise when I open a different csv file, it will store the data in the dataframe, but the accessing the column I want no longer works and it stops at the calculation part.

From what I can tell the problem lies with how it reads the column name. The column names are all numbers. For example, df['300'], df['301'] etc. When accessing the column df['300'] works fine in the testfile, while the next file requires df['300.0']. If I switch to a different file it may require df['300'] again. All the data was obtained in the same way so I am not certain why some are read as 300 and the others 300.0.

Short of constantly changing the column labels each time I open a different file, is there anyway to have it automatically distinguish between '300' and '300.0' when opening the file, or force '300.0' = '300'?

Thanks

答:
This answer assumes you want only the integer part to remain in the column name. It takes the column names and does a float->int->string conversion to strip the decimal places.

Be careful, if you have numbers like '300.5' as a column name, this will turn them into '300'.

```<code>cols = df.columns.tolist()
new_columns = dict([(c,str(int(float(c)))) for c in cols])
df = df.rename(columns = new_columns)
</code>```

For clarity, most of the 'magic' is happening on the middle line. I iterate over the currently existing columns, and turn them into tuples of the form (old_name, new_name). df.rename takes that dictionary and then does the renaming for you.

My thanks to user Nipun Batra for this answer that explained df.rename.

Body:
This answer assumes you want only the integer part to remain in the column name. It takes the column names and does a float->int->string conversion to strip the decimal places.

Be careful, if you have numbers like '300.5' as a column name, this will turn them into '300'.

cols = df.columns.tolist()
new_columns = dict([(c,str(int(float(c)))) for c in cols])
df = df.rename(columns = new_columns)

For clarity, most of the 'magic' is happening on the middle line. I iterate over the currently existing columns, and turn them into tuples of the form (old_name, new_name). df.rename takes that dictionary and then does the renaming for you.

My thanks to user Nipun Batra for this answer that explained df.rename.


问:
Make bash awk write in single line with separators
I'm a newbie to bash and i need to extract data from a file. I wrote it like this

```<code>    awk '/Iteration/''{print $3$4}''/TOTEN/''{print $5}''/energy without entropy/'
'{print $5 }''/energy without entropy/''{print $8 }' "OUTCAR.txt" > test.txt
</code>```

the output is like this

```<code>1(1)
-298.23864042
-298.23333028
-298.23731288
1(2)
-1924.01607328
-1924.02845253
-1924.01916810
</code>```

but i want every 4 results in a different column but single row. I tried awk -F '""' but it removes every result, leaving only empty lines
 edit: I want something like this

```<code>title1  title2  title3  title4
 1(1)  -298.23864042  -298.23333028  -298.23731288
 1(2)  -1924.01607328  -1924.02845253  -1924.01916810
</code>```

答:
```<code> awk '/Iteration/{printf "%s%s\t", $3, $4}
      /TOTEN/{printf "%s\t", $5}
      /energy without entropy/{printf "%s\t%s\n", $5, $8 }' OUTCAR.txt
</code>```

Body:
I'm a newbie to bash and i need to extract data from a file. I wrote it like this

    awk '/Iteration/''{print $3$4}''/TOTEN/''{print $5}''/energy without entropy/'
'{print $5 }''/energy without entropy/''{print $8 }' "OUTCAR.txt" > test.txt

the output is like this

1(1)
-298.23864042
-298.23333028
-298.23731288
1(2)
-1924.01607328
-1924.02845253
-1924.01916810

but i want every 4 results in a different column but single row. I tried awk -F '""' but it removes every result, leaving only empty lines
 edit: I want something like this

title1  title2  title3  title4
 1(1)  -298.23864042  -298.23333028  -298.23731288
 1(2)  -1924.01607328  -1924.02845253  -1924.01916810


问:
Jupyter notebook can not been started because of output cells
I kinda shot my leg:

By accident, collected so much output in jupyter cell, that it crashed. When i tried to restart it - found out that browser just can't load it. No errors - just can not load( doesn't show cells, can't start the kernel )

So, how can i access the code? :D

答:
From terminal or CommandLine you can convert .ipynb to .py

```<code>ipython nbconvert --to python <YourNotebookName>.ipynb
</code>```

Body:
From terminal or CommandLine you can convert .ipynb to .py

ipython nbconvert --to python <YourNotebookName>.ipynb


问:
IE structural problems
I have just made a very simple static side via wordpress. However, I made the theme from scratch with html and css. It looks perfect and exactly how I want in FFox,Chrome,Safari etc...but upon inspection in IE 6,7,8 is is not right.

Click {here} to see the site and if you don't have IE... Here is a screen shot of how it is rendering in there.

Any idea on what this may be or an idea on how to fix it would be greatly appreciated. I can't find any syntax errors in my css and the html seems right

Thanks

答:
There is usually a way to have a website render in all browsers correctly without using an IE template, but it takes a bit of work.

Try adding margin-left: auto; and margin-right: auto; and/or width:100% to your body.

Also it is good practice to wrap things that need to exist on the same y-axis, such as your tab and content in a div so that they can move together.

Title: IE structural problems


问:
How to get all users that the logged in user is not friends with in MySQL?
I am fully able to get all of the logged in users current friends, which I do with this query here -

```<code>SELECT users.*
FROM users
LEFT JOIN friends
ON users.id = friends.friend_id
WHERE friends.user_id = $user_logged_in_id
</code>```

But I want to do the opposite, and I can't figure it out.

I am trying to do friends logic.

I need to get all the users who the currently logged in user is not already friends with

I have a users table and a friends table to act as a many to many relationship between users and their friends. The keys in the friends table are user_id friend_id.

To illustrate that someone is friends with another user I put (say the logged in user id is 3, and friends user id is 6) user_id = 3 and friend_id = 6 as one row, and then put another row with the id's flipped to illustrate the friendship the other way, user_id = 6 and friend_id = 3.

users table

```<code>|---------------------|------------------|
|          id         |     username     |
|---------------------|------------------|
|          1          |     sonja12      |
|---------------------|------------------|
|          2          |     dorris32     |
|---------------------|------------------|
|          3          |     billy32      |
|---------------------|------------------|
|          4          |     micha97      |
|---------------------|------------------|
|          5          |     travis841    |
|---------------------|------------------|
|          6          |     johnny28     |
|---------------------|------------------|
</code>```

friends table

```<code>|---------------------|------------------|------------------|
|          id         |     user_id      |     friend_id    |
|---------------------|------------------|------------------|
|          1          |        3         |         6        |
|---------------------|------------------|------------------|
|          2          |        6         |         3        |
|---------------------|------------------|------------------|
</code>```

EDIT:

I think I have narrowed down my question a bit to be more concise.

I want to get all users from the users table where their id does not appear as a friend id beside the user_id of the current logged in user in the friends table.

答:
You're thinking of the problem in a strange way. It might help to think of it as an intersection of sets you need to create as opposed to a set that exists in the absence of an id.

SELECT id from users WHERE id != $logged_in_user AND id NOT IN ( SELECT friend_id from friends where user_id=$logged_in_user)

Body:
I am fully able to get all of the logged in users current friends, which I do with this query here -

SELECT users.*
FROM users
LEFT JOIN friends
ON users.id = friends.friend_id
WHERE friends.user_id = $user_logged_in_id

But I want to do the opposite, and I can't figure it out.

I am trying to do friends logic.

I need to get all the users who the currently logged in user is not already friends with

I have a users table and a friends table to act as a many to many relationship between users and their friends. The keys in the friends table are user_id friend_id.

To illustrate that someone is friends with another user I put (say the logged in user id is 3, and friends user id is 6) user_id = 3 and friend_id = 6 as one row, and then put another row with the id's flipped to illustrate the friendship the other way, user_id = 6 and friend_id = 3.

users table

|---------------------|------------------|
|          id         |     username     |
|---------------------|------------------|
|          1          |     sonja12      |
|---------------------|------------------|
|          2          |     dorris32     |
|---------------------|------------------|
|          3          |     billy32      |
|---------------------|------------------|
|          4          |     micha97      |
|---------------------|------------------|
|          5          |     travis841    |
|---------------------|------------------|
|          6          |     johnny28     |
|---------------------|------------------|

friends table

|---------------------|------------------|------------------|
|          id         |     user_id      |     friend_id    |
|---------------------|------------------|------------------|
|          1          |        3         |         6        |
|---------------------|------------------|------------------|
|          2          |        6         |         3        |
|---------------------|------------------|------------------|

EDIT:

I think I have narrowed down my question a bit to be more concise.

I want to get all users from the users table where their id does not appear as a friend id beside the user_id of the current logged in user in the friends table.


问:
WPF ListView/GridView Binding
I am attempting to make a simple VS 2017 Extension that is taking a object and displaying it. I have the data coming back and displaying the json in a text box, so I know the data is coming back correctly. But for some reason the gv is just showing the word "id" twice, as their are two records in the dataset. I have tried so many things I'm loosing track. Plus the documentation seems to be all over the place.

I believe there could be at least 2 issues here...

1) XAML the "Bindings"

2) Binding or adding the data to the LV?

Any help with this would be greatly appreciated!

XAML

```<code><UserControl x:Class="DoWork.AllWorkVSControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             Background="{DynamicResource VsBrush.Window}"
             Foreground="{DynamicResource VsBrush.WindowText}"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300"
             Name="MyToolWindow">
    <Grid>
        <StackPanel Orientation="Vertical">
            <TextBlock Margin="10" HorizontalAlignment="Center">AllWorkVS</TextBlock>
            <Button Content="Click me!" Click="button1_Click" Width="120" Height="80" Name="button1"/>
            <TextBox Height="200" TextWrapping="Wrap" Name="txtJson"/>
            <ListView x:Name="LvIssues">
                <ListView.View>
                    <GridView>
                        <GridView.Columns>
                            <GridViewColumn Width="Auto" Header="Id"  DisplayMemberBinding="{Binding Source='Id'}"></GridViewColumn>
                        </GridView.Columns>
                    </GridView>
                </ListView.View>
            </ListView>
        </StackPanel>
    </Grid>
</UserControl>
</code>```

C#

```<code>public class People
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public partial class AllWorkVSControl : UserControl
{

    public AllWorkVSControl()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        var t = Issues.GetPeopleById("2");
        PopulateListView();
        MessageBox.Show(t);
    }

    private void PopulateListView()
    {
        var l = GetPeople();
        txtJson.Text = JsonConvert.SerializeObject(l);

        foreach (var p in l)
        {
            LvIssues.Items.Add(p);
        }
    }
}
</code>```

答:
you need to set the ListView.ItemsSource.</p>

```<code>private void PopulateListView()
{
    var l = GetPeople();
    txtJson.Text = JsonConvert.SerializeObject(l);

    LvIssues.ItemsSource= l;
}

<ListView x:Name="LvIssues">
            <ListView.View>
                <GridView>
                    <GridView.Columns>
                        <GridViewColumn Width="Auto" Header="Id"  DisplayMemberBinding="{Binding Id}"></GridViewColumn>
                    </GridView.Columns>
                </GridView>
            </ListView.View>
        </ListView>
</code>```

Title: WPF ListView/GridView Binding

Body:
I am attempting to make a simple VS 2017 Extension that is taking a object and displaying it. I have the data coming back and displaying the json in a text box, so I know the data is coming back correctly. But for some reason the gv is just showing the word "id" twice, as their are two records in the dataset. I have tried so many things I'm loosing track. Plus the documentation seems to be all over the place.

I believe there could be at least 2 issues here...

1) XAML the "Bindings"

2) Binding or adding the data to the LV?

Any help with this would be greatly appreciated!

XAML

<UserControl x:Class="DoWork.AllWorkVSControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             Background="{DynamicResource VsBrush.Window}"
             Foreground="{DynamicResource VsBrush.WindowText}"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300"
             Name="MyToolWindow">
    <Grid>
        <StackPanel Orientation="Vertical">
            <TextBlock Margin="10" HorizontalAlignment="Center">AllWorkVS</TextBlock>
            <Button Content="Click me!" Click="button1_Click" Width="120" Height="80" Name="button1"/>
            <TextBox Height="200" TextWrapping="Wrap" Name="txtJson"/>
            <ListView x:Name="LvIssues">
                <ListView.View>
                    <GridView>
                        <GridView.Columns>
                            <GridViewColumn Width="Auto" Header="Id"  DisplayMemberBinding="{Binding Source='Id'}"></GridViewColumn>
                        </GridView.Columns>
                    </GridView>
                </ListView.View>
            </ListView>
        </StackPanel>
    </Grid>
</UserControl>

C#

public class People
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public partial class AllWorkVSControl : UserControl
{

    public AllWorkVSControl()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        var t = Issues.GetPeopleById("2");
        PopulateListView();
        MessageBox.Show(t);
    }

    private void PopulateListView()
    {
        var l = GetPeople();
        txtJson.Text = JsonConvert.SerializeObject(l);

        foreach (var p in l)
        {
            LvIssues.Items.Add(p);
        }
    }
}

Body:
you need to set the ListView.ItemsSource.

private void PopulateListView()
{
    var l = GetPeople();
    txtJson.Text = JsonConvert.SerializeObject(l);

    LvIssues.ItemsSource= l;
}

<ListView x:Name="LvIssues">
            <ListView.View>
                <GridView>
                    <GridView.Columns>
                        <GridViewColumn Width="Auto" Header="Id"  DisplayMemberBinding="{Binding Id}"></GridViewColumn>
                    </GridView.Columns>
                </GridView>
            </ListView.View>
        </ListView>


问:
how to exclude escaped characters in split() javascript
I am looking to ignore the characters inside the square brackets because it matches with my split parameters.

The string that i want to split is

```<code>var str = "K1.1.[Other] + K1.2A.[tcc + K*-=>]";
var split = str.split(/[+|,|*|/||>|<|=|-]+/);
</code>```

I want the output as K1.1.[Other], K1.2A.[tcc + K*-=>].

But this above code is including the characters inside square brackets which i don't want to consider. Any suggestion on how to solve this?

答:
split by both plus and braces as well. then go through chunks and join everything between  braces pairs.

But better not to use regexp at all for that.

Body:
I am looking to ignore the characters inside the square brackets because it matches with my split parameters.

The string that i want to split is

var str = "K1.1.[Other] + K1.2A.[tcc + K*-=>]";
var split = str.split(/[+|,|*|/||>|<|=|-]+/);

I want the output as K1.1.[Other], K1.2A.[tcc + K*-=>].

But this above code is including the characters inside square brackets which i don't want to consider. Any suggestion on how to solve this?


问:
How to create mp3 from text with Google TTS?
How to create mp3 from any text with Google TTS?

1) I try to find google.translate API, but finded only "audio to text", except "text to audio"!

2) I try to find SpeechSynthesis convert to mp3, but again find nothing!

3) I find only site "beta.soundoftext.com", they generate mp3 audio file without API interface.

So, can anyone help me, please.
I searching for any ways to convert text to SPEECH for my web-site (Dedicated Server). Thank you!

答:
I'm the creator of Sound of Text.

My site does have an API! (As of last week)

You can find the documentation for the API here: https://soundoftext.com/docs.

However, behind the scenes, I'm just using an npm library that automatically generates the Google Translate TTS link for me. Specifically, I'm using this library: https://www.npmjs.com/package/google-tts-api

I'm pretty sure every popular language has a library that does a similar thing, and I can help you find it if you tell me what language you prefer to use.

Or you can just use my API =)


答:
Split on the following pattern: /\+(?![^\[]*\])/

https://regex101.com/r/NZKaKD/1

Explanation:

\+ - A literal plus sign

(?! ... ) - Negative lookahead (don't match the previous character/group if it is followed by the contents of this block)

[^\[]* - Any number of non-left-square-brackets

\] - A literal right square bracket

Title: how to exclude escaped characters in split() javascript


问:
react native how to get return from a promise
my problem is i want to get a json from this function but all i get is a only a promise and why i choose this way because in app that i'm working on it works dynamicly but the only place that i see i can put this promise is render()

this is my code :

```<code>var userInfo = (async()=>{
    var value = await AsyncStorage.getItem("@user_info");
    value = JSON.parse(value);
    return value ;
  })();
</code>```

and this is my result :

```<code>Promise {
 "_40": 0,
 "_55": null,
 "_65": 0,
 "_72": null,
}
</code>```

but what i want to get is a json what sould i have to do ?

答:
I think it is because your function is self-executing.

You should be able to access the value if you remove the self-execution

```<code>var userInfo = async () => {
    var value = await AsyncStorage.getItem("@user_info");
    value = JSON.parse(value);
    return value ;
  });
</code>```

As AsyncStore.getItem is a Promise you could also use .then method

```<code>const userInfo = () => {
  AsyncStorage.getItem("@user_info").then((response) => {
     console.log(response);
  });
}
</code>```

Body:
my problem is i want to get a json from this function but all i get is a only a promise and why i choose this way because in app that i'm working on it works dynamicly but the only place that i see i can put this promise is render()

this is my code :

var userInfo = (async()=>{
    var value = await AsyncStorage.getItem("@user_info");
    value = JSON.parse(value);
    return value ;
  })();

and this is my result :

Promise {
 "_40": 0,
 "_55": null,
 "_65": 0,
 "_72": null,
}

but what i want to get is a json what sould i have to do ?

Body:
I think it is because your function is self-executing.

You should be able to access the value if you remove the self-execution

var userInfo = async () => {
    var value = await AsyncStorage.getItem("@user_info");
    value = JSON.parse(value);
    return value ;
  });

As AsyncStore.getItem is a Promise you could also use .then method

const userInfo = () => {
  AsyncStorage.getItem("@user_info").then((response) => {
     console.log(response);
  });
}


问:
Access value inside params hash
```<code>Rails 5
</code>```

I am trying to access one of the params

```<code>Parameters: {
  "utf8"=>"✓", "authenticity_token"=>".......",
  "temp_file_path"=>"{:value=>\"/home/utils/rails/fw_export/tmp/1510608598.csv\"}",
  "button"=>""
}
</code>```

specifically, temp_file_path. I tried:

```<code>temp_file_path = params[:temp_file_path][:value]
</code>```

But I am getting an error:

```<code>TypeError (no implicit conversion of Symbol into Integer):
</code>```

How do I access the value?

I also tried params["temp_file_path"][:value]

Solution:

I was passing the temp_file_file path as part of the params, as follows (from a View):

```<code>= hidden_field_tag :temp_file_path, :value => temp_file_path
</code>```

I changed it to:

```<code> = hidden_field_tag :temp_file_path, temp_file_path
</code>```

and  now the value is accessible as:

```<code>params[:temp_file_path]
</code>```

答:
Your hash is not valid:

```<code>{
    "utf8" => "✓",
    "authenticity_token" => ".......",
    "temp_file_path" => { "value" => "/home/utils/rails/fw_export/tmp/1510608598.csv\" },
    "button" => ""
 }
</code>```

The above would be a valid hash.

You can access it as: params["temp_file_path"]["value"]

Also, symbolizing the keys will let you access the hash using symbols.
Seep symbolizing symbolizes nested hashes:
https://apidock.com/rails/Hash/deep_symbolize_keys

```<code>params.deep_symbolize_keys
</code>```

Now you can access it as: params[:temp_file_path][:value]

Title: Access value inside params hash

Body:
Rails 5

I am trying to access one of the params

Parameters: {
  "utf8"=>"✓", "authenticity_token"=>".......",
  "temp_file_path"=>"{:value=>\"/home/utils/rails/fw_export/tmp/1510608598.csv\"}",
  "button"=>""
}

specifically, temp_file_path. I tried:

temp_file_path = params[:temp_file_path][:value]

But I am getting an error:

TypeError (no implicit conversion of Symbol into Integer):

How do I access the value?

I also tried params["temp_file_path"][:value]

Solution:

I was passing the temp_file_file path as part of the params, as follows (from a View):

= hidden_field_tag :temp_file_path, :value => temp_file_path

I changed it to:

 = hidden_field_tag :temp_file_path, temp_file_path

and  now the value is accessible as:

params[:temp_file_path]

Body:
Your hash is not valid:

{
    "utf8" => "✓",
    "authenticity_token" => ".......",
    "temp_file_path" => { "value" => "/home/utils/rails/fw_export/tmp/1510608598.csv\" },
    "button" => ""
 }

The above would be a valid hash.

You can access it as: params["temp_file_path"]["value"]

Also, symbolizing the keys will let you access the hash using symbols.
Seep symbolizing symbolizes nested hashes:
https://apidock.com/rails/Hash/deep_symbolize_keys

params.deep_symbolize_keys

Now you can access it as: params[:temp_file_path][:value]


问:
How to save a DataFrame as compressed (gzipped) CSV?
I use Spark 1.6.0 and Scala.

I want to save a DataFrame as compressed CSV format.

Here is what I have so far (assume I already have df and sc as SparkContext):

```<code>//set the conf to the codec I want
sc.getConf.set("spark.hadoop.mapred.output.compress", "true")
sc.getConf.set("spark.hadoop.mapred.output.compression.codec", "true")
sc.getConf.set("spark.hadoop.mapred.output.compression.codec", "org.apache.hadoop.io.compress.GzipCodec")
sc.getConf.set("spark.hadoop.mapred.output.compression.type", "BLOCK")

df.write
  .format("com.databricks.spark.csv")
  .save(my_directory)
</code>```

The output is not in gz format.

答:
With Spark 2.0+, this has become a bit simpler:

```<code>df.write.csv("path", compression="gzip")  # Python-only
df.write.option("compression", "gzip").csv("path") // Scala or Python
</code>```

You don't need the external Databricks CSV package anymore.

The csv() writer supports a number of handy options. For example:

sep: To set the separator character.

quote: Whether and how to quote values.

header: Whether to include a header line.

There are also a number of other compression codecs you can use, in addition to gzip:

bzip2

lz4

snappy

deflate

The full Spark docs for the csv() writer are here: Python / Scala

Body:
I use Spark 1.6.0 and Scala.

I want to save a DataFrame as compressed CSV format.

Here is what I have so far (assume I already have df and sc as SparkContext):

//set the conf to the codec I want
sc.getConf.set("spark.hadoop.mapred.output.compress", "true")
sc.getConf.set("spark.hadoop.mapred.output.compression.codec", "true")
sc.getConf.set("spark.hadoop.mapred.output.compression.codec", "org.apache.hadoop.io.compress.GzipCodec")
sc.getConf.set("spark.hadoop.mapred.output.compression.type", "BLOCK")

df.write
  .format("com.databricks.spark.csv")
  .save(my_directory)

The output is not in gz format.

Body:
With Spark 2.0+, this has become a bit simpler:

df.write.csv("path", compression="gzip")  # Python-only
df.write.option("compression", "gzip").csv("path") // Scala or Python

You don't need the external Databricks CSV package anymore.

The csv() writer supports a number of handy options. For example:

sep: To set the separator character.

quote: Whether and how to quote values.

header: Whether to include a header line.

There are also a number of other compression codecs you can use, in addition to gzip:

bzip2

lz4

snappy

deflate

The full Spark docs for the csv() writer are here: Python / Scala

ContentLicense: CC BY-SA 4.0


问:
Create a key value pair for both the current key and value
I currently have an array of simple objects:

```<code>data = [{ "alternative hip hop": 3 }, { "escape room": 4 }, ...]
</code>```

...to which I'd like to transform into

```<code>newData = [
    { "name": "alternative hip hop", "count": 3 },
    { "name": "escape room", "count" 4 }
]
</code>```

Is this doable with a map? I've failed at figuring out how to do so with one.

lodash responses are welcome as well

答:
Assuming each item in the data has a single key/value pair, you'd want:</p>

```<code>data.map(obj => {
    const key = Object.keys(obj)[0]; //Just get the first key we find
    return {
        name: key,
        count: obj[key]
    };
})
</code>```

Body:
I currently have an array of simple objects:

data = [{ "alternative hip hop": 3 }, { "escape room": 4 }, ...]

...to which I'd like to transform into

newData = [
    { "name": "alternative hip hop", "count": 3 },
    { "name": "escape room", "count" 4 }
]

Is this doable with a map? I've failed at figuring out how to do so with one.

lodash responses are welcome as well

Body:
Assuming each item in the data has a single key/value pair, you'd want:

data.map(obj => {
    const key = Object.keys(obj)[0]; //Just get the first key we find
    return {
        name: key,
        count: obj[key]
    };
})


问:
How to apply a Zero-Phase filter using MathDotNet library?
Is there a specific function or class in the Math.NET library to obtain a Zero-Phase (non causal) IIR filter?

If not, how can this be achieved using current functions? I believe this can be obtained by filtering the signal and then filtering the reverse, but I'm not sure the result is correct.

答:
The following sample shows how to obtain a Zero-Phase filter by using the reverse-filtering technique and it also compares the result with that of a conventional lowpass filter. The signal being filtered is a 5Hz sine wave + white gaussian noise.

```<code>//signal + noise
double fs = 1000; //sampling rate
double fw = 5; //signal frequency
double n = 5; //number of periods to show
double A = 10; //signal amplitude
double N = 2; //noise amplitude
int size = (int)(n * fs / fw); //sample size

var t = Enumerable.Range(1, size).Select(p => p * 1 / fs).ToArray();
var noise = new WhiteGaussianNoiseSource();
var y = t.Select(p => (A * Math.Sin(2 * pi * fw * p)) + (N * noise.ReadNextSample())).ToArray();

//filter
double fc = 10; //cutoff frequency
var filter = OnlineFirFilter.CreateLowpass(ImpulseResponse.Finite, fs, fc);

double[] yf1 = filter.ProcessSamples(y); //Lowpass
double[] yf2 = filter.ProcessSamples(yf1.Reverse().ToArray()); //Lowpass reversed
double[] yf2r = yf2.Reverse().ToArray(); //Zero-Phase
</code>```

Body:
The following sample shows how to obtain a Zero-Phase filter by using the reverse-filtering technique and it also compares the result with that of a conventional lowpass filter. The signal being filtered is a 5Hz sine wave + white gaussian noise.

//signal + noise
double fs = 1000; //sampling rate
double fw = 5; //signal frequency
double n = 5; //number of periods to show
double A = 10; //signal amplitude
double N = 2; //noise amplitude
int size = (int)(n * fs / fw); //sample size

var t = Enumerable.Range(1, size).Select(p => p * 1 / fs).ToArray();
var noise = new WhiteGaussianNoiseSource();
var y = t.Select(p => (A * Math.Sin(2 * pi * fw * p)) + (N * noise.ReadNextSample())).ToArray();

//filter
double fc = 10; //cutoff frequency
var filter = OnlineFirFilter.CreateLowpass(ImpulseResponse.Finite, fs, fc);

double[] yf1 = filter.ProcessSamples(y); //Lowpass
double[] yf2 = filter.ProcessSamples(yf1.Reverse().ToArray()); //Lowpass reversed
double[] yf2r = yf2.Reverse().ToArray(); //Zero-Phase


问:
Configure a SQL Server Instance as (local)
Each member of our development team has a copy of our application's database running on a local version of SQL Server 2008 Enterprise with SP1. Everyone is able to access the database by specifying their server and instance name in their web.config file, but to best share the developer version of our web.config file, we have standardized on making connections strings generic by using integrated security and setting server property to (local). This strategy is working fine for the majority of our 64-bit Windows 7 machines but in few cases (local) isn't recognized. We have compared settings via the SQL Server Configuration Manager (namely ensuring that the named pipes protocol was enabled) and we've tried setting the "(local)" alias via SQL Server Client Network Utility, but we haven't any luck. What needs to be done in order to use (local) in our connections strings? </p>

答:
Those machines where the database connection as (local) doesn't work is probably that way because during the database installation, the instance name was set to something specific, rather than the default of "default instance". You can change these instance names, which may resolve this issue: http://coderjournal.com/2008/02/how-to-change-instance-name-of-sql-server/.

I think this occurs when you have SQL Server Express already installed and running, and then install SQL Server Developer Edition / Standard / etc....not 100% sure though, but from what I recall, that may be the case.


问:
Access 2013 Module in Windows Task Scheduler
I have tried using Windows Task Scheduler to run my Access Database module although I can't figure out how to create the macro for this as I believe this is the only way to do this.
The details I have are Program/script:"C:\Program Files\Microsoft Office\Office15\MSACCESS.EXE"Add Arguments(optional):"C:\deskop\Reports.accdb" /x AutoExec I have created a macro on my access database called AutoExec but I don't know how to call my module which is called Main.

My Module contains 5 different public functions and a Sub which I changed to Function. I have now added all 5 functions as RunCode and function name to the macro is this correct? it seems to be running the macro now.

答:
you can do this in below steps

Step 1 : Create a macro (AutoExec in your case )  in database and call the function (main in your case).

Step 2:  Create a batch file, now in batch file you will write a code to open your database and call the macro that you want to execute (AutoExec)

e.g.

```<code>if exist "C:\Program Files (x86)\Microsoft Office\Office14\MSACCESS.EXE" ("C:\Program Files (x86)\Microsoft Office\Office14\MSACCESS.EXE" C:\AccessDatabase\MyDatabase.accdb /x:AutoExec)
</code>```

When this batch file is exacuted, access database will be opened and AutoExec Macro from that database will run which inturn call your function and then complete the task that you want to do.

Step 3: in this step, create a scheduled task in Windows task scheduler. Create a new action as start a program and provide the above Step 2 created batch file path in Program/Script.

As per schedule you setup this will run the batch fle and hence the later access and macro and your function....

hope this helps.

Body:
you can do this in below steps

Step 1 : Create a macro (AutoExec in your case )  in database and call the function (main in your case).

Step 2:  Create a batch file, now in batch file you will write a code to open your database and call the macro that you want to execute (AutoExec)

e.g.

if exist "C:\Program Files (x86)\Microsoft Office\Office14\MSACCESS.EXE" ("C:\Program Files (x86)\Microsoft Office\Office14\MSACCESS.EXE" C:\AccessDatabase\MyDatabase.accdb /x:AutoExec)

When this batch file is exacuted, access database will be opened and AutoExec Macro from that database will run which inturn call your function and then complete the task that you want to do.

Step 3: in this step, create a scheduled task in Windows task scheduler. Create a new action as start a program and provide the above Step 2 created batch file path in Program/Script.

As per schedule you setup this will run the batch fle and hence the later access and macro and your function....

hope this helps.


问:
Cannot return an HTML view in Spring MVC
It's my first attempt at using Spring and I ran into a problem. I cannot seem to return a simple HTML file as a view inside a controller. I'm trying to return the index.html file (it just has some text and a button), because it is displayed correctly when going to localhost:8080/.

The project was generated using IntelliJ, I figure I'd mention this since it handled most of the configuration.

Here's the file structure:

```<code>app:
 | src
    | main
       | java
          | com.my.testapp
              | Main.java
              | controllers
                  | TestController.java
       | resources
          | static
              | index.html
</code>```

Here are my files:

Main.java

```<code>@SpringBootApplication
public class Main
{
    public static void main(String[] args)
    {
        SpringApplication.run(Main.class, args);
    }
}
</code>```

TestController.java (the first controller actually works)

```<code>@RequestMapping("/test")
@Controller
public class TestController
{
    @RequestMapping(method = RequestMethod.GET, value = "/testget")
    public @ResponseBody ArrayList<Test> foo()
    {
        ArrayList<Test> tests = new ArrayList<>();

        tests.add(new Test("id1", "pass1"));
        tests.add(new Test("id2", "pass2"));

        return tests;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/someview")
    public String showView()
    {
        return "index";
    }
}
</code>```

And finally, the pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.my</groupId>
    <artifactId>testapp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springtest</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

I was previously using @RestController annotation and the controller would simply return the string index, but now I get a 404 page (Whitelabel Error Page). I know this is a common issue, but I haven't been able to solve it using other people's solution.

EDIT: Ok, I managed to fix part of it by removing the line @RequestMapping("/test"), but I now need to pass the view as "index.html" instead of simply "index". Is there a way to skip the .html? Currently it doesn't work without it.

EDIT #2: I finally figured out how to make the views work properly, check my answer below.

答:
After a lot of useless Google searches, two kind Indian dudes explaining stuff on YouTube and a few white hairs I finally got the app running properly. Here's everything I found out:

File structure

The structure I posted in my question is correct, no need to change anything. The HTML views can reside under src/main/resources/static.

Returning HTML views using controllers

I removed the annotation from the Controller class and now my simplified controller looks like this:

```<code>@Controller
public class TestController
{
    @RequestMapping(value = "/someview")
    public String showView()
    {
        return "index";
    }
}
</code>```

You can add/map more URLs to this controller by changing the annotation to

@RequestMapping(value = {"/someview", "/someotherview", "/onelastview"}).

Now I can navigate to localhost:8080/someview and get the index.html view (without actually specifying the file extension in the controller).

Extra configuration

By default, my controller function needed to return "index.html" instead of "index". The solution for this is to add a line to application.properties. This file resides (in my case) under the resources folder.

The line is spring.mvc.view.suffix=.html. This specifies the type of the views. You can also set spring.mvc.view.prefix=/path/to/views, but I didn't know how to set it and it worked anyway (I guess that it defaults to resources/static).

This basically tells the framework to grab the views using the following path:

prefix + viewName + suffix, where viewName in my case is index (whatever String I return in my method).

Main.java required no extra configuration, just the SpringApplication.run() line.

Body:
It's my first attempt at using Spring and I ran into a problem. I cannot seem to return a simple HTML file as a view inside a controller. I'm trying to return the index.html file (it just has some text and a button), because it is displayed correctly when going to localhost:8080/.

The project was generated using IntelliJ, I figure I'd mention this since it handled most of the configuration.

Here's the file structure:

app:
 | src
    | main
       | java
          | com.my.testapp
              | Main.java
              | controllers
                  | TestController.java
       | resources
          | static
              | index.html

Here are my files:

Main.java

@SpringBootApplication
public class Main
{
    public static void main(String[] args)
    {
        SpringApplication.run(Main.class, args);
    }
}

TestController.java (the first controller actually works)

@RequestMapping("/test")
@Controller
public class TestController
{
    @RequestMapping(method = RequestMethod.GET, value = "/testget")
    public @ResponseBody ArrayList<Test> foo()
    {
        ArrayList<Test> tests = new ArrayList<>();

        tests.add(new Test("id1", "pass1"));
        tests.add(new Test("id2", "pass2"));

        return tests;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/someview")
    public String showView()
    {
        return "index";
    }
}

And finally, the pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.my</groupId>
    <artifactId>testapp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springtest</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

I was previously using @RestController annotation and the controller would simply return the string index, but now I get a 404 page (Whitelabel Error Page). I know this is a common issue, but I haven't been able to solve it using other people's solution.

EDIT: Ok, I managed to fix part of it by removing the line @RequestMapping("/test"), but I now need to pass the view as "index.html" instead of simply "index". Is there a way to skip the .html? Currently it doesn't work without it.

EDIT #2: I finally figured out how to make the views work properly, check my answer below.

Body:
After a lot of useless Google searches, two kind Indian dudes explaining stuff on YouTube and a few white hairs I finally got the app running properly. Here's everything I found out:

File structure

The structure I posted in my question is correct, no need to change anything. The HTML views can reside under src/main/resources/static.

Returning HTML views using controllers

I removed the annotation from the Controller class and now my simplified controller looks like this:

@Controller
public class TestController
{
    @RequestMapping(value = "/someview")
    public String showView()
    {
        return "index";
    }
}

You can add/map more URLs to this controller by changing the annotation to

@RequestMapping(value = {"/someview", "/someotherview", "/onelastview"}).

Now I can navigate to localhost:8080/someview and get the index.html view (without actually specifying the file extension in the controller).

Extra configuration

By default, my controller function needed to return "index.html" instead of "index". The solution for this is to add a line to application.properties. This file resides (in my case) under the resources folder.

The line is spring.mvc.view.suffix=.html. This specifies the type of the views. You can also set spring.mvc.view.prefix=/path/to/views, but I didn't know how to set it and it worked anyway (I guess that it defaults to resources/static).

This basically tells the framework to grab the views using the following path:

prefix + viewName + suffix, where viewName in my case is index (whatever String I return in my method).

Main.java required no extra configuration, just the SpringApplication.run() line.


问:
Webpack 2: Watch external files
I have a project that uses source files external to the project. Effectively, there is the actual project source code (an Typescript/Angular 2 application, lets call it the 'core' stuff), and this is a generic web application that is meant to be the base code that consumes these external source files.

The external files include additional stuff-- that could be SCSS files, images, evn additional JS. The way I want this to work is that webpack copies these external files from any source directory (this is critical, it is not part of the core project) to a local .tmp directory. The files in the .tmp directory are worked on along with the core src files to generate the prod output.

I can't figure out how to add these additional external source files to the watch list. Effectively what I'm looking to do is watch that directory and as things change, it re-copies the affected files to the local .tmp directory and triggers a recompile.

Presently I have to restart webpack and have a very very ugly solution using Grunt to watch the additional files. It's nasty but these kinds of workarounds have historically been what I've had to do with webpack.

Does anyone have a better solution? Ideally I'd like to not have to mix grunt with webpack. Webpack should be able to do this, but its hard to know whether there's an existing plugin for this or what the best approach would be.

Also, please spare the "look for it on google" or "read the docs" comments. I've combed through it all, hard, and have not found anything.

Thanks in advance.

答:
As of now Webpack doesn't watch external files out-of-the-box . You need a plugin for that.

Basically idea is to have a file watcher module chokidar / watch , listening to the file change , and when there is a change, restart the webpack compilation phase . Webpack plugins can access the compilation object and we you need to hook it to a compiler phase i.e. 'emit' , 'after-emit' etc.

This Webpack plugin exactly solves your problem - https://www.npmjs.com/package/filewatcher-webpack-plugin .

Title: Webpack 2: Watch external files


问:
Is it possible to draw an information flow between two states
In sparx Architect, it is possible to model between two states in a state machine diagram, as shown in the diagram.

Is the schema legal ? What is its meaning ?

答:
Information flow is defined on p. 667:

InformationFlows describe circulation of information through a system in a general manner. They do not specify the
  nature of the information, mechanisms by which it is conveyed, sequences of exchange, or any control conditions.

Information flow is a way to model data/information flow but without details or "implementation constraints".

The source and the target are NameElement, see p. 670:

```<code>informationSource : NamedElement [1..*]
informationTarget : NamedElement [1..*]
</code>```

NamedElement is one of the root classes of the meta-model.

It means that an information flow may be modeled between almost all UML classes.

After what could the schema mean?

An InformationFlow is not a transition. State3 is never reached and has no transition: it is not involved in the state machine. If State3 will be removed the state machine stays the same.

Even if the schema is correct, the meaning of information flows in a such context is not defined by the norm. States must be reached by Transitions.

If data have to be transferred from one state to another, a solution could be to create a subclass of Event, add properties to this subclass, and model that as instance of this subclass to trigger the transition.

Body:
Information flow is defined on p. 667:

InformationFlows describe circulation of information through a system in a general manner. They do not specify the
  nature of the information, mechanisms by which it is conveyed, sequences of exchange, or any control conditions.

Information flow is a way to model data/information flow but without details or "implementation constraints".

The source and the target are NameElement, see p. 670:

informationSource : NamedElement [1..*]
informationTarget : NamedElement [1..*]

NamedElement is one of the root classes of the meta-model.

It means that an information flow may be modeled between almost all UML classes.

After what could the schema mean?

An InformationFlow is not a transition. State3 is never reached and has no transition: it is not involved in the state machine. If State3 will be removed the state machine stays the same.

Even if the schema is correct, the meaning of information flows in a such context is not defined by the norm. States must be reached by Transitions.

If data have to be transferred from one state to another, a solution could be to create a subclass of Event, add properties to this subclass, and model that as instance of this subclass to trigger the transition.


问:
Late binding for non version specific Excel VBA code
I have an Excel spreadsheet that my VBA code pulls from to create appointments on a shared Outlook calendar. It will be manipulated by multiple project managers (not at the same time of course).

I found a couple of users have and older version of Office and as such I have learned I should be using "late binding" to make this compatible with older versions.

How do I convert what I have to late binding. All of the examples that I had to create this code was early binding.

Option Explicit

Sub SCHMTG() 'Schedule Meeting

    Dim wb As Workbook
    Set wb = ThisWorkbook

    Dim ws As Worksheet
    Set ws = wb.Sheets("Projects")

    ws.Unprotect ""

    Dim check As Boolean
    check = False

    Dim o As Outlook.Application
    Set o = New Outlook.Application

    Dim oNS As Outlook.Namespace
    Set oNS = o.GetNamespace("MAPI")

    Dim FOL As Outlook.MAPIFolder
    Set FOL = oNS.GetFolderFromID("00000000F4EFC638C1F878469E872F63F51D794A0100F96BCFC3DAF87B4F8C66193C3EA6F4F40000029DA2430000")

    Dim oAPT As Outlook.AppointmentItem
    Dim oAPT_DATE As Date
    Dim oAPT_TIME As Date
    Dim oOBJECT As Object
    Dim b As CheckBox
    Dim r As Integer
    Dim c As Integer

    Set b = ws.CheckBoxes(Application.Caller)
    With b.TopLeftCell
        r = .Row
        c = .Column
    End With

    For Each oAPT In FOL.Items 'Search for existing meeting

        oAPT_DATE = Format(oAPT.Start, "MM-DD-YYYY")
        oAPT_TIME = TimeValue(oAPT.Start)

        If oAPT_DATE = ws.Cells(r, c - 3).Value And oAPT.Subject = ws.Cells(r, 1).Value And oAPT_TIME = ws.Cells(r, c - 2).Value Then
            check = True
        Else
        End If

    Next oAPT

    If check = False Then 'If no meeting already exist Then create new meeting
        Set oAPT = FOL.Items.Add(olAppointmentItem)
        With oAPT
            .Start = ws.Cells(r, c - 3).Value + ws.Cells(r, c - 2).Value
            .Duration = ws.Cells(r, c - 1).Value * 60
            .Subject = ws.Cells(r, 1).Value & " " & ws.Cells(1, c).Value
            .Body = "Project: " & ws.Cells(r, 1).Value & vbCrLf & "Location: " & ws.Cells(r, 2) & vbCrLf & "OASIS#: " & ws.Cells(r, 3) & vbCrLf & "Project Manager: " & ws.Cells(r, 5) & vbCrLf & "Distributor: " & ws.Cells(r, 8) & vbCrLf & "Assigned Technitian: " & ws.Cells(r, c - 5) & vbCrLf & "Date: " & ws.Cells(r, c - 3) & vbCrLf & "Start Time: " & Format(ws.Cells(r, c - 2), "h:mm am/pm") & vbCrLf & "Duration: " & ws.Cells(r, c - 1) & " Hour(s)"
            .Location = ws.Cells(r, 2).Value
            .Recipients.Add Cells(r, c - 4).Value
            .MeetingStatus = olMeeting
            .ReminderMinutesBeforeStart = 1440
            .Save
            .Send
        End With
        ws.Cells(r, c - 1).Locked = True
        ws.Cells(r, c - 2).Locked = True
        ws.Cells(r, c - 3).Locked = True
        ws.Cells(r, c - 5).Locked = True
    Else
    End If

    ws.Cells(r, 1).Locked = True
    ws.Cells(r, 2).Locked = True
    ws.Cells(r, 3).Locked = True

    ws.Protect "", True, True

End Sub
```

答:
Remove any VBA project references to the Outlook library.

Declare any Outlook objects As Object instead of using the Outlook library typename. Use CreateObject() in place of New

eg:

```<code>Dim oAPT As Outlook.AppointmentItem
Dim o As Outlook.Application
Set o = New Outlook.Application
</code>```

would be

```<code>Dim oAPT As Object
Dim o As Object
Set o = CreateObject("Outlook.Application")
</code>```

Any Outlook-derived constants such as olAppointmentItem should either be declared as Constants in your code, or replaced by their numeric values (which you can find using the Object Browser)

Body:
Remove any VBA project references to the Outlook library.

Declare any Outlook objects As Object instead of using the Outlook library typename. Use CreateObject() in place of New

eg:

Dim oAPT As Outlook.AppointmentItem
Dim o As Outlook.Application
Set o = New Outlook.Application

would be

Dim oAPT As Object
Dim o As Object
Set o = CreateObject("Outlook.Application")

Any Outlook-derived constants such as olAppointmentItem should either be declared as Constants in your code, or replaced by their numeric values (which you can find using the Object Browser)


问:
How can I set the minSdk just for androidTest?
I'd like to increase the minSdk to 21 just for androidTest. Is this possible without introducing a product flavor?

Note: Using Android Gradle Plugin 3.0, and my app's minSdk needs to be 16.

答:
You can add the minSdk in either the projects gradle file or manifest. When adding the minSdk it means that you are specifying the minimum sdk level that you have designed and tested your app. You also would want to add the targetSdk. A google support link which may interest you https://developer.android.com/training/basics/supporting-devices/platforms.html

In the manifest it would look like

<manifest xmlns:android="http://schemas.android.com/apk/res/android" ... >
    <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" />
    ...
</manifest>

In your gradle file

```<code>defaultConfig {
    applicationId "com.project.projectName"
    minSdkVersion 14
    targetSdkVersion 21
}
</code>```

Body:
You can add the minSdk in either the projects gradle file or manifest. When adding the minSdk it means that you are specifying the minimum sdk level that you have designed and tested your app. You also would want to add the targetSdk. A google support link which may interest you https://developer.android.com/training/basics/supporting-devices/platforms.html

In the manifest it would look like

<manifest xmlns:android="http://schemas.android.com/apk/res/android" ... >
    <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" />
    ...
</manifest>

In your gradle file

defaultConfig {
    applicationId "com.project.projectName"
    minSdkVersion 14
    targetSdkVersion 21
}


问:
pandas Date get numeric Time intervall
i have the following dataframe example with the Date and Interval:

```<code>       Date     Interval
0   2013-08-01  14:00:00
1   2013-08-01  14:15:00
2   2013-08-01  14:30:00
3   2013-08-01  14:45:00
4   2013-08-01  15:00:00
        ...
</code>```

What i want is a new Column where the Interval is mapped like:

```<code>00:00:00 = 1
00:15:00 = 2
00:30:00 = 3
00:45:00 = 4
    ...
23:45:00 = 96
</code>```

So every 15Minutes is 1 Intervall.
The rows in the dataframe are mixed, so i cant start a counter and increase the value. i need to use the time value in the Interval Column to get the mapped value in the new Column

i tried:

```<code>dates = pandas.to_datetime(df['Interval'])
df['IntervalMapped']= dates.dt.hour * 2 + dates.dt.minute//15 + 1
</code>```

but thats wrong

答:
I thought you might want to treat the "hms" form as text and write your own counting function? Hope this helps.</p>

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

def converter(hms):
    """Takes a time in hms returns number of 15 second intervals after 00:00:00.
    """
    h,m,s = hms.split(':')
    return int(h)*4+int(m)//15

converter('02:15:00')  # 9

path = 'YOUR path'
new_df = pd.read_csv(path+'stack.txt')

new_df['Interval Mapped'] = new_df['Interval'].apply(lambda x: converter(x))
new_df
</code>```

Title: pandas Date get numeric Time intervall

Body:
i have the following dataframe example with the Date and Interval:

       Date     Interval
0   2013-08-01  14:00:00
1   2013-08-01  14:15:00
2   2013-08-01  14:30:00
3   2013-08-01  14:45:00
4   2013-08-01  15:00:00
        ...

What i want is a new Column where the Interval is mapped like:

00:00:00 = 1
00:15:00 = 2
00:30:00 = 3
00:45:00 = 4
    ...
23:45:00 = 96

So every 15Minutes is 1 Intervall.
The rows in the dataframe are mixed, so i cant start a counter and increase the value. i need to use the time value in the Interval Column to get the mapped value in the new Column

i tried:

dates = pandas.to_datetime(df['Interval'])
df['IntervalMapped']= dates.dt.hour * 2 + dates.dt.minute//15 + 1

but thats wrong

Body:
I thought you might want to treat the "hms" form as text and write your own counting function? Hope this helps.

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

def converter(hms):
    """Takes a time in hms returns number of 15 second intervals after 00:00:00.
    """
    h,m,s = hms.split(':')
    return int(h)*4+int(m)//15

converter('02:15:00')  # 9

path = 'YOUR path'
new_df = pd.read_csv(path+'stack.txt')

new_df['Interval Mapped'] = new_df['Interval'].apply(lambda x: converter(x))
new_df


问:
Mongoose Query to Match Object ID with User ID, then display in DOM
I'm pretty new to this, so apologies if I'm not using the right jargon. I am using Node, Express, MongoDB, and Mongoose.

I have a mongo model for Recipe:

```<code>var recipeSchema = new mongoose.Schema({
    name: String,
    url: String,
    notes: String,
    image: String,
    ingredients: [String],
    author: {
       id: {
         type: mongoose.Schema.Types.ObjectId,
         ref: 'User'
       },
       username: String
    }
});
</code>```

and a model for User:

```<code>var userSchema = new mongoose.Schema({
  username: String,
  password: String,
  recipes: [
  {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Recipe'
  }
]
});
</code>```

When I display recipes, I want one button to show up if the current user has added a specific recipe to their recipes object, and a different button to appear if they have not. My client-side code has access to a currentUser_id which I could use to query that user's recipes and see if the current recipe is a match, but I'm a bit lost on how to do that (client side or server side?), and then pass that information to the DOM to update a button.

答:
The approach to this type of problems is to have a server that responds to a certain API. For example:

calling: http://yourserver.com/recipes/<user_id> - will return a json with all the recipes for that user.

Another idea: http://yourserver.com/u/<user_id>/recipe/<recipe_id> - will return true or false whether that user_id has that recipe_id.

All access to the DB will be performed on the express method that handles it.

Body:
I'm pretty new to this, so apologies if I'm not using the right jargon. I am using Node, Express, MongoDB, and Mongoose.

I have a mongo model for Recipe:

var recipeSchema = new mongoose.Schema({
    name: String,
    url: String,
    notes: String,
    image: String,
    ingredients: [String],
    author: {
       id: {
         type: mongoose.Schema.Types.ObjectId,
         ref: 'User'
       },
       username: String
    }
});

and a model for User:

var userSchema = new mongoose.Schema({
  username: String,
  password: String,
  recipes: [
  {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Recipe'
  }
]
});

When I display recipes, I want one button to show up if the current user has added a specific recipe to their recipes object, and a different button to appear if they have not. My client-side code has access to a currentUser_id which I could use to query that user's recipes and see if the current recipe is a match, but I'm a bit lost on how to do that (client side or server side?), and then pass that information to the DOM to update a button.


问:
securing passwords in code
Even with https enabled, you can write a password to the event log in code-behind.  Any way to keep that password encrypted in code while you're checking it against a data store?

(using Login control)

(couldn't add comment to Andrew's answer, so I'm putting it here)

NTLM uses the username/password of the machine the user is logged into right?  For this, I was thinking using ActiveDirectory on the server as the data store.  It would have a diferrent un/pw than what the user is currently signed in to their machine as.

答: If you are concerned about the plaintext password being in memory simply encrypt it as soon as possible in your workflow.  Also make sure that you never log the plaintext password to any event logs either.</p>

Title: securing passwords in code