问:
I can't read google drive's data(.xlsx) from local PC
I want read google drive's data(.xlsx) from local PC.
However, the following error is returned and it cannot be read properly. Do you know the reason?

error

```<code>HttpError: <HttpError 403 when requesting https://www.googleapis.com/drive/v3/files/<file_id>/export?mimeType=application%2Fvnd.openxmlformats-officedocument.spreadsheetml.sheet&alt=media returned "Export only supports Docs Editors files.". Details: "[{'domain': 'global', 'reason': 'fileNotExportable', 'message': 'Export only supports Docs Editors files.'}]">
</code>```

code

```<code>if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)

service = build('drive', 'v3', credentials=creds)
file_id = '###'

request = service.files().export_media(fileId=file_id, mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
fh = io.FileIO('test.xlsx', mode='wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print("Download %d%%." % int(status.progress() * 100))
</code>```

答:
From the error message Export only supports Docs Editors files, export_media can only be used for Google Workspace files, while you are trying to export an xlsx file. Instead you can try get_media API.

See
https://developers.google.com/drive/api/v3/manage-downloads#python

Body:
I want read google drive's data(.xlsx) from local PC.
However, the following error is returned and it cannot be read properly. Do you know the reason?

error

HttpError: <HttpError 403 when requesting https://www.googleapis.com/drive/v3/files/<file_id>/export?mimeType=application%2Fvnd.openxmlformats-officedocument.spreadsheetml.sheet&alt=media returned "Export only supports Docs Editors files.". Details: "[{'domain': 'global', 'reason': 'fileNotExportable', 'message': 'Export only supports Docs Editors files.'}]">

code

if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)

service = build('drive', 'v3', credentials=creds)
file_id = '###'

request = service.files().export_media(fileId=file_id, mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
fh = io.FileIO('test.xlsx', mode='wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print("Download %d%%." % int(status.progress() * 100))


来源: stackexchange

问:
How do I modify a realm object without getting these error messages?
I have a small Xcode project in Swift 5. It is a simple NotePad type app which has categories of notes so for example you could have a category of Home with an associated list of notes relevant to the home. I am having trouble modifying one of the notes of the associated category using Realm. I have tried placing the modification code inside a realm.write closure but I get the error message;

*** Terminating app due to uncaught exception 'RLMException', reason: 'The Realm is already in a write transaction'

When I remove the realm.write I get a different message;

*** Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.

What's going on and how can I modify a note and update the realm database?

```<code>import RealmSwift

class NotePadListViewController: UITableViewController {

    var noteArray: Results<Note>?
    let realm = try! Realm()

    var selectedCategory: Category? {
        didSet {
            loadItems()
        }
    }

//    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    @IBOutlet weak var searchBar: UISearchBar!

    override func viewDidLoad() {
        super.viewDidLoad()

        searchBar.autocapitalizationType = .none

//        print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))

    }

    // MARK: TableView Datasource Methods

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return noteArray?.count ?? 1
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)

        cell.textLabel?.text = noteArray?[indexPath.row].title ?? "No Notes Added."

        return cell
    }

    // MARK: TableView Delegate Methods

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)

        let createNoteView = CreateNoteView(frame: CGRect(x: (self.view.frame.width - 240.0)/2.0, y: (self.view.frame.height - 300.0)/2.0, width: 240.0, height: 300.0))

        createNoteView.savedNote = noteArray?[indexPath.row]
        view.addSubview(createNoteView)

        createNoteView.delegate = self

    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

        if let note = noteArray?[indexPath.row] {

            if editingStyle == .delete {
                do {
                    try realm.write {
                        realm.delete(note)
                        tableView.deleteRows(at: [indexPath], with: .fade)
                    }
                } catch {
                    print("Error deleting note: \(error)")
                }
            }
        }
    }

    // MARK: - Add new note

    @IBAction func addButtonPressed(_ sender: UIBarButtonItem) {

        let createNoteView = CreateNoteView(frame: CGRect(x: (self.view.frame.width - 240.0)/2.0, y: (self.view.frame.height - 300.0)/2.0, width: 240.0, height: 300.0))

        createNoteView.savedNote = nil

        view.addSubview(createNoteView)

        createNoteView.delegate = self

    }

    func loadItems() {

        noteArray = selectedCategory?.notes.sorted(byKeyPath: "title", ascending: true)

        tableView.reloadData()
    }
}

// MARK: - Create Note View Protocol

extension NotePadListViewController: CreateNoteViewProtocol {

    func send(note: Note) {

        if let currentCategory = selectedCategory {

            if note.row == -1 {

                note.row = noteArray?.count ?? 0
                do {
                    try! realm.write {
                        currentCategory.notes.append(note)
                    }
                }
            } else {
                do {
                    try! realm.write {
                        let row = note.row
                        currentCategory.notes[row] = note
                    }
                }

            }
        }

        tableView.reloadData()
    }
}

// MARK: - SearchBar delegate methods

extension NotePadListViewController: UISearchBarDelegate {

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

        noteArray = noteArray?.filter("title CONTAINS[cd] %@ ", searchBar.text!).sorted(byKeyPath: "dateCreated", ascending: true)

        tableView.reloadData()
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        if searchText == "" {
            loadItems()
            DispatchQueue.main.async {
                searchBar.resignFirstResponder()
            }
        }
    }
}
</code>```
```<code>import UIKit
import RealmSwift

protocol CreateNoteViewProtocol: AnyObject {
    func send(note: Note)
}

class CreateNoteView: UIView, UITextViewDelegate, UITextFieldDelegate {

    var savedNote: Note? {
        didSet {
            if savedNote == nil {
                noteTitle.text = "Note title"
                noteTitle.textColor = UIColor.lightGray
                noteContent.text = "Type something interesting..."
                noteContent.textColor = UIColor.lightGray
            } else {
                noteTitle.text = savedNote!.title
                noteTitle.textColor = UIColor.black
                noteContent.text = savedNote!.content
                noteContent.textColor = UIColor.black
            }
        }
    }

    @IBOutlet weak var noteTitle: UITextField!
    @IBOutlet weak var noteContent: UITextView!

    weak var delegate: CreateNoteViewProtocol!

    let realm = try! Realm()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
        noteTitle.delegate = self
        noteContent.delegate = self
    }

    func commonInit() {

        let viewFromXib = Bundle.main.loadNibNamed("CreateNoteView", owner: self, options: nil)![0] as! UIView
        viewFromXib.frame = self.bounds
        addSubview(viewFromXib)
    }

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

    @IBAction func cancelButtonTapped(_ UIButton: Any) {
        self.removeFromSuperview()
    }

    @IBAction func saveButtonTapped(_ UIButton: Any) {

        if let existingNote = savedNote {

            existingNote.title = noteTitle.text ?? "No Title"
            existingNote.content = noteContent.text
            delegate.send(note: existingNote)

        } else {

            let note = Note()
            note.title = noteTitle.text ?? "No Title"
            note.content = noteContent.text
            note.row = -1
            note.dateCreated = Date()
            delegate.send(note: note)

        }

        self.removeFromSuperview()
    }

    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.textColor == UIColor.lightGray {
            textView.text = nil
            textView.textColor = UIColor.black
        }
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField.textColor == UIColor.lightGray {
            textField.text = nil
            textField.textColor = UIColor.black
        }
    }
}
</code>```
```<code>import Foundation
import RealmSwift

class Note: Object {
    @objc dynamic var title: String = ""
    @objc dynamic var content: String = ""
    @objc dynamic var row: Int = 0
    @objc dynamic var dateCreated: Date = Date()
    var parentCategory = LinkingObjects(fromType: Category.self, property: "notes")
}
</code>```
```<code>import Foundation
import RealmSwift

class Category: Object {
    @objc dynamic var name: String = ""
    let notes = List<Note>()
}```

```

答:
Instead of declaring a realm instance multiple times, you can use it by making it sharedInstance.

Try to make RealmManager class.

```<code>import UIKit
import RealmSwift

class RealmManager {

    private var realm: Realm

    static let sharedInstance = RealmManager()

    private init() {
        realm = try! Realm()
    }

    func add(object: Object, shouldUpdate: Bool = true) {
        try! realm.write {
            if shouldUpdate {
                realm.add(object, update: .all)
            } else {
                realm.add(object)
            }
        }
    }

    func update(action: () -> Void) {
        try! realm.write {
            action()
        }
    }

    func deleteAll() {
        try! realm.write {
            realm.deleteAll()
        }
    }

    func delete(object: Object) {
        try! realm.write {
            realm.delete(object)
        }
    }

}
</code>```

Now to use this in your code:
Take an example of your NotePadListViewController.

Where you have written this block:

```<code>extension NotePadListViewController: CreateNoteViewProtocol {

    func send(note: Note) {
        if let currentCategory = selectedCategory {
            if note.row == -1 {
                note.row = noteArray?.count ?? 0
                do {
                    try! realm.write {
                        currentCategory.notes.append(note)
                    }
                }
            } else {
                do {
                    try! realm.write {
                        let row = note.row
                        currentCategory.notes[row] = note
                    }
                }
            }
        }

        tableView.reloadData()
    }
}
</code>```

Replace this code with the following block:

```<code>extension NotePadListViewController: CreateNoteViewProtocol {

    func send(note: Note) {
        if let currentCategory = selectedCategory {
            if note.row == -1 {
                note.row = noteArray?.count ?? 0
                RealmManager.sharedInstance.add(object: note)
            } else {
                RealmManager.sharedInstance.update {
                    let row = note.row
                    currentCategory.notes[row] = note
                }
            }
        }
        tableView.reloadData()
    }
}
</code>```

After this whenever you want to perform any action in the entire project with the realm database make use of RealmManager.sharedInstance.

ContentLicense: CC BY-SA 4.0

Body:
I have a small Xcode project in Swift 5. It is a simple NotePad type app which has categories of notes so for example you could have a category of Home with an associated list of notes relevant to the home. I am having trouble modifying one of the notes of the associated category using Realm. I have tried placing the modification code inside a realm.write closure but I get the error message;

*** Terminating app due to uncaught exception 'RLMException', reason: 'The Realm is already in a write transaction'

When I remove the realm.write I get a different message;

*** Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.

What's going on and how can I modify a note and update the realm database?

import RealmSwift

class NotePadListViewController: UITableViewController {

    var noteArray: Results<Note>?
    let realm = try! Realm()

    var selectedCategory: Category? {
        didSet {
            loadItems()
        }
    }

//    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    @IBOutlet weak var searchBar: UISearchBar!

    override func viewDidLoad() {
        super.viewDidLoad()

        searchBar.autocapitalizationType = .none

//        print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))

    }

    // MARK: TableView Datasource Methods

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return noteArray?.count ?? 1
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)

        cell.textLabel?.text = noteArray?[indexPath.row].title ?? "No Notes Added."

        return cell
    }

    // MARK: TableView Delegate Methods

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)

        let createNoteView = CreateNoteView(frame: CGRect(x: (self.view.frame.width - 240.0)/2.0, y: (self.view.frame.height - 300.0)/2.0, width: 240.0, height: 300.0))

        createNoteView.savedNote = noteArray?[indexPath.row]
        view.addSubview(createNoteView)

        createNoteView.delegate = self

    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

        if let note = noteArray?[indexPath.row] {

            if editingStyle == .delete {
                do {
                    try realm.write {
                        realm.delete(note)
                        tableView.deleteRows(at: [indexPath], with: .fade)
                    }
                } catch {
                    print("Error deleting note: \(error)")
                }
            }
        }
    }

    // MARK: - Add new note

    @IBAction func addButtonPressed(_ sender: UIBarButtonItem) {

        let createNoteView = CreateNoteView(frame: CGRect(x: (self.view.frame.width - 240.0)/2.0, y: (self.view.frame.height - 300.0)/2.0, width: 240.0, height: 300.0))

        createNoteView.savedNote = nil

        view.addSubview(createNoteView)

        createNoteView.delegate = self

    }

    func loadItems() {

        noteArray = selectedCategory?.notes.sorted(byKeyPath: "title", ascending: true)

        tableView.reloadData()
    }
}

// MARK: - Create Note View Protocol

extension NotePadListViewController: CreateNoteViewProtocol {

    func send(note: Note) {

        if let currentCategory = selectedCategory {

            if note.row == -1 {

                note.row = noteArray?.count ?? 0
                do {
                    try! realm.write {
                        currentCategory.notes.append(note)
                    }
                }
            } else {
                do {
                    try! realm.write {
                        let row = note.row
                        currentCategory.notes[row] = note
                    }
                }

            }
        }

        tableView.reloadData()
    }
}

// MARK: - SearchBar delegate methods

extension NotePadListViewController: UISearchBarDelegate {

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

        noteArray = noteArray?.filter("title CONTAINS[cd] %@ ", searchBar.text!).sorted(byKeyPath: "dateCreated", ascending: true)

        tableView.reloadData()
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        if searchText == "" {
            loadItems()
            DispatchQueue.main.async {
                searchBar.resignFirstResponder()
            }
        }
    }
}

import UIKit
import RealmSwift

protocol CreateNoteViewProtocol: AnyObject {
    func send(note: Note)
}

class CreateNoteView: UIView, UITextViewDelegate, UITextFieldDelegate {

    var savedNote: Note? {
        didSet {
            if savedNote == nil {
                noteTitle.text = "Note title"
                noteTitle.textColor = UIColor.lightGray
                noteContent.text = "Type something interesting..."
                noteContent.textColor = UIColor.lightGray
            } else {
                noteTitle.text = savedNote!.title
                noteTitle.textColor = UIColor.black
                noteContent.text = savedNote!.content
                noteContent.textColor = UIColor.black
            }
        }
    }

    @IBOutlet weak var noteTitle: UITextField!
    @IBOutlet weak var noteContent: UITextView!

    weak var delegate: CreateNoteViewProtocol!

    let realm = try! Realm()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
        noteTitle.delegate = self
        noteContent.delegate = self
    }

    func commonInit() {

        let viewFromXib = Bundle.main.loadNibNamed("CreateNoteView", owner: self, options: nil)![0] as! UIView
        viewFromXib.frame = self.bounds
        addSubview(viewFromXib)
    }

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

    @IBAction func cancelButtonTapped(_ UIButton: Any) {
        self.removeFromSuperview()
    }

    @IBAction func saveButtonTapped(_ UIButton: Any) {

        if let existingNote = savedNote {

            existingNote.title = noteTitle.text ?? "No Title"
            existingNote.content = noteContent.text
            delegate.send(note: existingNote)

        } else {

            let note = Note()
            note.title = noteTitle.text ?? "No Title"
            note.content = noteContent.text
            note.row = -1
            note.dateCreated = Date()
            delegate.send(note: note)

        }

        self.removeFromSuperview()
    }

    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.textColor == UIColor.lightGray {
            textView.text = nil
            textView.textColor = UIColor.black
        }
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField.textColor == UIColor.lightGray {
            textField.text = nil
            textField.textColor = UIColor.black
        }
    }
}

import Foundation
import RealmSwift

class Note: Object {
    @objc dynamic var title: String = ""
    @objc dynamic var content: String = ""
    @objc dynamic var row: Int = 0
    @objc dynamic var dateCreated: Date = Date()
    var parentCategory = LinkingObjects(fromType: Category.self, property: "notes")
}

import Foundation
import RealmSwift

class Category: Object {
    @objc dynamic var name: String = ""
    let notes = List<Note>()
}```

Body:
Instead of declaring a realm instance multiple times, you can use it by making it sharedInstance.

Try to make RealmManager class.

import UIKit
import RealmSwift

class RealmManager {

    private var realm: Realm

    static let sharedInstance = RealmManager()

    private init() {
        realm = try! Realm()
    }

    func add(object: Object, shouldUpdate: Bool = true) {
        try! realm.write {
            if shouldUpdate {
                realm.add(object, update: .all)
            } else {
                realm.add(object)
            }
        }
    }

    func update(action: () -> Void) {
        try! realm.write {
            action()
        }
    }

    func deleteAll() {
        try! realm.write {
            realm.deleteAll()
        }
    }

    func delete(object: Object) {
        try! realm.write {
            realm.delete(object)
        }
    }

}

Now to use this in your code:
Take an example of your NotePadListViewController.

Where you have written this block:

extension NotePadListViewController: CreateNoteViewProtocol {

    func send(note: Note) {
        if let currentCategory = selectedCategory {
            if note.row == -1 {
                note.row = noteArray?.count ?? 0
                do {
                    try! realm.write {
                        currentCategory.notes.append(note)
                    }
                }
            } else {
                do {
                    try! realm.write {
                        let row = note.row
                        currentCategory.notes[row] = note
                    }
                }
            }
        }

        tableView.reloadData()
    }
}

Replace this code with the following block:

extension NotePadListViewController: CreateNoteViewProtocol {

    func send(note: Note) {
        if let currentCategory = selectedCategory {
            if note.row == -1 {
                note.row = noteArray?.count ?? 0
                RealmManager.sharedInstance.add(object: note)
            } else {
                RealmManager.sharedInstance.update {
                    let row = note.row
                    currentCategory.notes[row] = note
                }
            }
        }
        tableView.reloadData()
    }
}

After this whenever you want to perform any action in the entire project with the realm database make use of RealmManager.sharedInstance.


问:
> Could not initialize class com.android.repository.api.RepoManager
I  am new in Android Studio. After setup, When I am trying to import an application I am getting that error So that gradle not able to build.

Error:> Could not initialize class com.android.repository.api.RepoManager

I checked that my classpath setting for Java is fine. I am running Windows OS. Does anyone know the source of the error?

答:
I had this issue while trying to run a 5-year-old android project. Following these steps fixed the issue for me:

1- update gradle version in the project level build.gradle file  from

classpath 'com.android.tools.build:gradle:2.2.2'
to

classpath 'com.android.tools.build:gradle:7.1.1'

2- add google() to the project repositories

```<code>allprojects {
repositories {
    jcenter()
    mavenLocal()
    google()
}}
</code>```

and in buildScript block as well:

```<code>buildscript {
repositories {
    jcenter()
    mavenLocal()
    google()
} dependencies {...}}
</code>```

3- update gradle version in gradle-wrapper.properties file to an up-to-date version, I updated to 7.2

4- In the app level build.gradle file, in the dependencies block, I changed compile to implementation

5- sync the project

Body:
I had this issue while trying to run a 5-year-old android project. Following these steps fixed the issue for me:

1- update gradle version in the project level build.gradle file  from

classpath 'com.android.tools.build:gradle:2.2.2'
to

classpath 'com.android.tools.build:gradle:7.1.1'

2- add google() to the project repositories

allprojects {
repositories {
    jcenter()
    mavenLocal()
    google()
}}

and in buildScript block as well:

buildscript {
repositories {
    jcenter()
    mavenLocal()
    google()
} dependencies {...}}

3- update gradle version in gradle-wrapper.properties file to an up-to-date version, I updated to 7.2

4- In the app level build.gradle file, in the dependencies block, I changed compile to implementation

5- sync the project


问:
heredoc for Windows batch?
Is there a way of specifying multiline strings in batch in a way similar to heredoc in unix shells. Something similar to:

```<code>cat <<EOF > out.txt
bla
bla
..
EOF
</code>```

The idea is to create a customized file from a template file..

答:
```<code>@echo off
 for /f "delims=:" %%a in (
     'findstr -n "^___" %0') do set "Line=%%a"

 (for /f "skip=%Line% tokens=* eol=_" %%a in (
       'type %0') do echo(%%a) > out.html
:: out.html
pause
goto: EOF

___DATA___
<!Doctype html>
<html>
  <head>
   title></title>
  </head>
  <body>
    <svg width="900" height="600">
        <text x="230"
              y="150"
              font-size="100"
              fill="blue"
              stroke="gray"
              stroke-width="1">
                  Hello World
        </text>
    </svg>
  </body>
</html>
</code>```

ContentLicense: CC BY-SA 2.5

Title: heredoc for Windows batch?

Body:
Is there a way of specifying multiline strings in batch in a way similar to heredoc in unix shells. Something similar to:

cat <<EOF > out.txt
bla
bla
..
EOF

The idea is to create a customized file from a template file..

ContentLicense: CC BY-SA 3.0


问:
Exceeded filesize limit with importing revolution slider from other website
Im trying to import an existing revolution slider template from one site to another.
Whenever im importing the .zip file i get the error below

"Exceeded filesize limit"

I have already tried increasing all limits in the .htaccess file:

php_value memory_limit 256M
php_value post_max_size 256M
php_value upload_max_filesize 64M
php_value max_input_vars 1800
php_value max_execution_time 300
php_value max_input_time 300

But it is still not working.
Im stuk at the moment.

All help is appreciated.

Thanks

答:
locate the file PHP.INI
wamp64\bin\apache\apache2.4.51\bin
modify this lines
max_input_vars = 2500
memory_limit = 128M

you can increase the value according to your wish


问:
How do I parse a URL into hostname and path in javascript?
I would like to take a string

```<code>var a = "http://example.com/aa/bb/"
</code>```

and process it into an object such that

```<code>a.hostname == "example.com"
</code>```

and

```<code>a.pathname == "/aa/bb"
</code>```

答:
Of course in >2016 the right answer is using URL API

For page URL window.location

And for  HTMLAnchorElement API

Also for supporting older browser, using polyfill:

```<code><script crossorigin="anonymous" src="https://polyfill.io/v3/polyfill.min.js?features=URL"></script>
</code>```

But just as an other option, it can be handle easy and accurate by RegEx pattern:

function URIinfo(s) {
    s=s.match(/^(([^/]*?:)\/*((?:([^:]+):([^@]+)@)?([^/:]{2,}|\[[\w:]+])(:\d*)?(?=\/|$))?)?((.*?\/)?(([^/]*?)(\.[^/.]+?)?))(\?.*?)?(#.*)?$/);
    return {origin:s[1],protocol:s[2],host:s[3],username:s[4],password:s[5],hostname:s[6],port:s[7],path:s[8],folders:s[9],file:s[10],filename:s[11],fileext:s[12],search:s[13],hash:s[14]};
}

var sample='http://user:password@my.site.com:8080/onefolder/folder.name/file.min.js?query=http://my.site.com:8080/file.exe#hash-root:/file/1.txt';

console.log (URIinfo(sample));
/*
{
  "origin": "http://user:password@my.site.com:8080",
  "protocol": "http:",
  "host": "user:password@my.site.com:8080",
  "username": "user",
  "password": "password",
  "hostname": "my.site.com",
  "port": ":8080",
  "path": "/onefolder/folder.name/file.min.js",
  "folders": "/onefolder/folder.name/",
  "file": "file.min.js",
  "filename": "file.min",
  "fileext": ".js",
  "search": "?query=http://my.site.com:8080/file.exe",
  "hash": "#hash-root:/file/1.txt"
}
*/```

Work with the RegEx

It is fine with any kind of

Absolute / Relative paths

IPv4 / IPv6

Net protocols / Local Files

Query / Hash

And will return all URL options but not searchParams

(+) Also will return file info like href="https://www.php.net/manual/en/function.pathinfo.php" rel="nofollow noreferrer">PHP pathInfo

Body:
I would like to take a string

var a = "http://example.com/aa/bb/"

and process it into an object such that

a.hostname == "example.com"

and

a.pathname == "/aa/bb"

Body:
Of course in >2016 the right answer is using URL API

For page URL window.location

And for <a href="..."> HTMLAnchorElement API

Also for supporting older browser, using polyfill:

<script crossorigin="anonymous" src="https://polyfill.io/v3/polyfill.min.js?features=URL"></script>

But just as an other option, it can be handle easy and accurate by RegEx pattern:

function URIinfo(s) {
    s=s.match(/^(([^/]*?:)\/*((?:([^:]+):([^@]+)@)?([^/:]{2,}|\[[\w:]+])(:\d*)?(?=\/|$))?)?((.*?\/)?(([^/]*?)(\.[^/.]+?)?))(\?.*?)?(#.*)?$/);
    return {origin:s[1],protocol:s[2],host:s[3],username:s[4],password:s[5],hostname:s[6],port:s[7],path:s[8],folders:s[9],file:s[10],filename:s[11],fileext:s[12],search:s[13],hash:s[14]};
}

var sample='http://user:password@my.site.com:8080/onefolder/folder.name/file.min.js?query=http://my.site.com:8080/file.exe#hash-root:/file/1.txt';

console.log (URIinfo(sample));
/*
{
  "origin": "http://user:password@my.site.com:8080",
  "protocol": "http:",
  "host": "user:password@my.site.com:8080",
  "username": "user",
  "password": "password",
  "hostname": "my.site.com",
  "port": ":8080",
  "path": "/onefolder/folder.name/file.min.js",
  "folders": "/onefolder/folder.name/",
  "file": "file.min.js",
  "filename": "file.min",
  "fileext": ".js",
  "search": "?query=http://my.site.com:8080/file.exe",
  "hash": "#hash-root:/file/1.txt"
}
*/

Work with the RegEx

It is fine with any kind of

Absolute / Relative paths

IPv4 / IPv6

Net protocols / Local Files

Query / Hash

And will return all URL options but not searchParams

(+) Also will return file info like PHP pathInfo


问:
get previous and next id using mysql
I am trying to create a function in PHP that returns "next_id" and "prev_id", from an sql table.

However, the id is not simply 1,2,3,etc which means if one record id is 50, the previous id might be 22 while the next id might be 81.

I tried, in this way...

```<code>public function prevNext($id)
    {
        "SELECT
            IFNULL(SELECT min(id)
                from table
                where id > t.id ) as next_id
            , IFNULL(SELECT max(id)
                from table
                where id < t.id) as prev_id
        from table as t
        where id = $id";
    }
</code>```

答:
If LAG and LEAD are supported in your version of MySQL, you could try something like this:</p>
```<code>SELECT id, LAG(id) OVER(ORDER BY id) AS PrevID,
    LEAD(id) OVER(ORDER BY id) AS NextID
FROM table as t
WHERE id = $id
</code>```

Title: get previous and next id using mysql

Body:
I am trying to create a function in PHP that returns "next_id" and "prev_id", from an sql table.

However, the id is not simply 1,2,3,etc which means if one record id is 50, the previous id might be 22 while the next id might be 81.

I tried, in this way...

public function prevNext($id)
    {
        "SELECT
            IFNULL(SELECT min(id)
                from table
                where id > t.id ) as next_id
            , IFNULL(SELECT max(id)
                from table
                where id < t.id) as prev_id
        from table as t
        where id = $id";
    }

Body:
If LAG and LEAD are supported in your version of MySQL, you could try something like this:

SELECT id, LAG(id) OVER(ORDER BY id) AS PrevID,
    LEAD(id) OVER(ORDER BY id) AS NextID
FROM table as t
WHERE id = $id


问:
Return original response from webservice call on scala with play
I have have a scala project (V. 2.12.12) witch use play framework and i try to call webservice and return response.

To do that, i create a client :

```<code>  override def postStatus(body: JsValue): Future[WSResponse] = {
    wsClientHelper.callWS(updateStatusUrl, POST, callerBody = body)
  }
</code>```

My method return Future[WSResponse]. So i call them in a controller :

```<code>  def postKycStatus: Action[AnyContent] = action.async { implicit request =>
    kycRepository
      .postStatus(request.body.asJson.getOrElse(JsObject.empty))
  }
</code>```

But when i do that, i can call the updateStatus api sucessfully with postStatus but i got an compilation error :

play.sbt.PlayExceptions$CompilationException: Compilation error[type mismatch;
found   : scala.concurrent.Future[play.api.libs.ws.WSResponse]
required: scala.concurrent.Future[play.api.mvc.Result]]

How can i return my original webservice response with original status code ?

Thanks to your help !

答:
I found the response. You can do it with:</p>
```<code>def postKycStatus: Action[AnyContent] = action.async { implicit request =>
  kycRepository
  .postStatus(request.body.asJson.getOrElse(JsObject.empty))
  .map(response => Status(response.status)(response.body).as(JSON))
}
</code>```

Body:
I have have a scala project (V. 2.12.12) witch use play framework and i try to call webservice and return response.

To do that, i create a client :

  override def postStatus(body: JsValue): Future[WSResponse] = {
    wsClientHelper.callWS(updateStatusUrl, POST, callerBody = body)
  }

My method return Future[WSResponse]. So i call them in a controller :

  def postKycStatus: Action[AnyContent] = action.async { implicit request =>
    kycRepository
      .postStatus(request.body.asJson.getOrElse(JsObject.empty))
  }

But when i do that, i can call the updateStatus api sucessfully with postStatus but i got an compilation error :

play.sbt.PlayExceptions$CompilationException: Compilation error[type mismatch;
found   : scala.concurrent.Future[play.api.libs.ws.WSResponse]
required: scala.concurrent.Future[play.api.mvc.Result]]

How can i return my original webservice response with original status code ?

Thanks to your help !

Body:
I found the response. You can do it with:

def postKycStatus: Action[AnyContent] = action.async { implicit request =>
  kycRepository
  .postStatus(request.body.asJson.getOrElse(JsObject.empty))
  .map(response => Status(response.status)(response.body).as(JSON))
}


问:
Problem w/Register-ScheduledTask in Powershell v5.1
Ok, I have the following code which retrieves a file from my main machine makes an adjustment and then creates a Scheduled Task on my test machine.
The program is run from the test machine. This works just as it should.

```<code>$SRCXMLPath = "\\Dellxps8920\BEKDocs-DellXPS8920\TaskSchedulerExports\Tasks"
$DestXMLPath = "G:\BEKDocs\TaskSchedulerExports\Standard"
$XMLFile = "Backup Report.xml"

$GCArgs = @{Path =
             $(Join-Path -Path $SRCXMLPath -ChildPath $XMLFile)}

[xml]$xml = Get-Content @GCArgs

$xml.Task.RegistrationInfo.Author #Has no effect on running!

$xml.Task.Principals.Principal.UserId

<#+----------------------------------------------------+
  | Note: You can use either the text description of   |
  |       the account or the Registry designation.     |
  +----------------------------------------------------+
#>

$xml.Task.Principals.Principal.UserId =
  'DellXPS8700\Bruce'

#  "S-1-5-21-1944453205-1635450679-2182824496-1001"

$xml.save()

& schtasks.exe /create /tn "Backup Report" /xml "$(Join-Path -Path $DestXMLPath -ChildPath $XMLFile)"
</code>```

However, I'm trying to convert it to Full PowerShell via Register-ScheduledTask cmdlet to eliminate the call to schtasks.exe.
Using the following test code I consistently get the displayed error.

```<code>[xml]$Task = Get-Content "G:\BEKDocs\TaskSchedulerExports\Standard\Backup Report.xml"
$RTArgs = @{TaskName = "Backup Report"
            TaskPath = "\"
            XML      = $Task
            Force    = $True}

Register-ScheduledTask @RTArgs
</code>```

Error Message:

```<code>Register-ScheduledTask @RTArgs
Register-ScheduledTask : The task XML is malformed.
(1,2)::ERROR: incorrect document syntax
At line:7 char:1
+ Register-ScheduledTask @RTArgs
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (PS_ScheduledTask:Root/Microsoft/.
   ..S_ScheduledTask) [Register-ScheduledTask], CimException
    + FullyQualifiedErrorId : HRESULT 0x8004131a,Register-ScheduledTask
</code>```

Anyone have any Ideas?

Please Note: the .xml file works perfectly with the code at the top of the post or if it is imported manually inside TaskSheceuler.

答:
You're reading the XML file as an XML object, but the cmdlet expects a string object.

```<code>Register-ScheduledTask
        [-Force]
        [[-Password] <String>]
        [[-User] <String>]
        [-TaskName] <String>
        [[-TaskPath] <String>]
        [-Xml] <String>
        [-CimSession <CimSession[]>]
        [-ThrottleLimit <Int32>]
        [-AsJob]
        [<CommonParameters>]
</code>```

Change the line to read the file in as just one string and you should be all set.

```<code>$Task = Get-Content "G:\BEKDocs\TaskSchedulerExports\Standard\Backup Report.xml" -raw
</code>```

Body:
Ok, I have the following code which retrieves a file from my main machine makes an adjustment and then creates a Scheduled Task on my test machine.
The program is run from the test machine. This works just as it should.

$SRCXMLPath = "\\Dellxps8920\BEKDocs-DellXPS8920\TaskSchedulerExports\Tasks"
$DestXMLPath = "G:\BEKDocs\TaskSchedulerExports\Standard"
$XMLFile = "Backup Report.xml"

$GCArgs = @{Path =
             $(Join-Path -Path $SRCXMLPath -ChildPath $XMLFile)}

[xml]$xml = Get-Content @GCArgs

$xml.Task.RegistrationInfo.Author #Has no effect on running!

$xml.Task.Principals.Principal.UserId

<#+----------------------------------------------------+
  | Note: You can use either the text description of   |
  |       the account or the Registry designation.     |
  +----------------------------------------------------+
#>

$xml.Task.Principals.Principal.UserId =
  'DellXPS8700\Bruce'

#  "S-1-5-21-1944453205-1635450679-2182824496-1001"

$xml.save()

& schtasks.exe /create /tn "Backup Report" /xml "$(Join-Path -Path $DestXMLPath -ChildPath $XMLFile)"

However, I'm trying to convert it to Full PowerShell via Register-ScheduledTask cmdlet to eliminate the call to schtasks.exe.
Using the following test code I consistently get the displayed error.

[xml]$Task = Get-Content "G:\BEKDocs\TaskSchedulerExports\Standard\Backup Report.xml"
$RTArgs = @{TaskName = "Backup Report"
            TaskPath = "\"
            XML      = $Task
            Force    = $True}

Register-ScheduledTask @RTArgs

Error Message:

Register-ScheduledTask @RTArgs
Register-ScheduledTask : The task XML is malformed.
(1,2)::ERROR: incorrect document syntax
At line:7 char:1
+ Register-ScheduledTask @RTArgs
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (PS_ScheduledTask:Root/Microsoft/.
   ..S_ScheduledTask) [Register-ScheduledTask], CimException
    + FullyQualifiedErrorId : HRESULT 0x8004131a,Register-ScheduledTask

Anyone have any Ideas?

Please Note: the .xml file works perfectly with the code at the top of the post or if it is imported manually inside TaskSheceuler.

Body:
You're reading the XML file as an XML object, but the cmdlet expects a string object.

Register-ScheduledTask
        [-Force]
        [[-Password] <String>]
        [[-User] <String>]
        [-TaskName] <String>
        [[-TaskPath] <String>]
        [-Xml] <String>
        [-CimSession <CimSession[]>]
        [-ThrottleLimit <Int32>]
        [-AsJob]
        [<CommonParameters>]

Change the line to read the file in as just one string and you should be all set.

$Task = Get-Content "G:\BEKDocs\TaskSchedulerExports\Standard\Backup Report.xml" -raw


问:
Value of useRef is undefined inside the useEffect function
According to the documentation of useEffect, it starts after the HTML elements are rendered so why I am getting the value of useRef hook as undefined inside the useEffect function.
How can I set the value of Input field using useEffect in this code.

```<code>  const territoryName = useRef();
  const [isLoading, setIsLoading] = useState(true);
  const [isDisabled, setIsDisabled] = useState(false);
  const [selectedColor, setSelectedColor] = useState("");
  const history = useHistory();
  const homepageRoute = useRouteLink("");

  const appContext = useContext(APP_CONTEXT);
  const { user, regionData, areaData, editId, displayedMap, existingPolygons } = appContext;

  useEffect(() => {
    if (!user.name || !regionData.length) {
      return history.push(homepageRoute);
    }
    else if (!areaData[editId]) {
      return errorToast("Invalid Region");
    }
    locateRegion(displayedMap, JSON.parse(areaData[editId]?.polygonVertices));
    setSelectedColor(areaData[editId]?.colorCode);
    territoryName?.current?.setValue(areaData[editId]?.mapName);
    console.log(territoryName.current) // Prints undefined
    setIsLoading(false);
  }, []);

return (
    <>
      <ToastContainer autoClose={3000} />
      <Sidebar isLoading={isLoading} isDisabled={isDisabled}>
        <SidebarHeader headerText={"Edit Territory"} showBackIcon />
        <HorizontalLine />
        <div className="modifypage-sidebar">
          <SidebarContent>
            <Input
              name="territory-name"
              ref={territoryName}
              id="territory-name"
              placeholder="Enter Territory Name"
              label="Territory Name"
            />
            <ColorPallet
              // selectedColor={selectedColor} onColorChange={onColorChange}
            />
          </SidebarContent>
          <HorizontalLine />
        </ div>

        <SidebarFooter
          text="Save"
          help="Save Changes"
          // handler={() => { updateArea(oldValues, territoryName.current.getValue(), selectedColor) }}
        />
      </Sidebar>
    </>
  )
</code>```

答:
The useRef might be undefined when the useEffect callback is run first, therefore a solution could be to listen for changes in the ref, check if it's defined, and only then continue with the function.

More info on possible solutions can be found here

Body:
According to the documentation of useEffect, it starts after the HTML elements are rendered so why I am getting the value of useRef hook as undefined inside the useEffect function.
How can I set the value of Input field using useEffect in this code.

  const territoryName = useRef();
  const [isLoading, setIsLoading] = useState(true);
  const [isDisabled, setIsDisabled] = useState(false);
  const [selectedColor, setSelectedColor] = useState("");
  const history = useHistory();
  const homepageRoute = useRouteLink("");

  const appContext = useContext(APP_CONTEXT);
  const { user, regionData, areaData, editId, displayedMap, existingPolygons } = appContext;

  useEffect(() => {
    if (!user.name || !regionData.length) {
      return history.push(homepageRoute);
    }
    else if (!areaData[editId]) {
      return errorToast("Invalid Region");
    }
    locateRegion(displayedMap, JSON.parse(areaData[editId]?.polygonVertices));
    setSelectedColor(areaData[editId]?.colorCode);
    territoryName?.current?.setValue(areaData[editId]?.mapName);
    console.log(territoryName.current) // Prints undefined
    setIsLoading(false);
  }, []);

return (
    <>
      <ToastContainer autoClose={3000} />
      <Sidebar isLoading={isLoading} isDisabled={isDisabled}>
        <SidebarHeader headerText={"Edit Territory"} showBackIcon />
        <HorizontalLine />

          <SidebarContent>
            <Input
              name="territory-name"
              ref={territoryName}
              id="territory-name"
              placeholder="Enter Territory Name"
              label="Territory Name"
            />
            <ColorPallet
              // selectedColor={selectedColor} onColorChange={onColorChange}
            />
          </SidebarContent>
          <HorizontalLine />

        <SidebarFooter
          text="Save"
          help="Save Changes"
          // handler={() => { updateArea(oldValues, territoryName.current.getValue(), selectedColor) }}
        />
      </Sidebar>
    </>
  )


问:
How to fix files with gulp-eslint?
I'm using gulp with eslint.

Without gulp, I just run eslint ./src --fix. I can't figure out how to make this happen with gulp. I tried below, setting fix to be true, but it doesn't fix any files:

```<code>gulp.task('lint', ['./src/**.js'], () => {
return gulp.src()
    .pipe($.eslint({fix:true}))
    .pipe($.eslint.format())
    .pipe($.eslint.failAfterError());
});
</code>```

I want all the files under ./src to be fixed. How do I achieve this?

答:
I use gulp-eslint-new because gulp-eslint is unmaintained.

It has a method gulpESLintNew.fix() to fix files, which is explained in the readme.

Overwrite files with the fixed content provided by ESLint. This should be used in conjunction with the option fix in gulpESLintNew(options). Files without a fix and files that were not processed by ESLint will be left untouched.

And an example:

function lintNFix() {
  return src('demo/**/*.js').pipe(gulpESLintNew({ fix: true }))
                            .pipe(gulpESLintNew.format())
                            // If a file has a fix, overwrite it.
                            .pipe(gulpESLintNew.fix());
}
```

Title: How to fix files with gulp-eslint?

Body:
I'm using gulp with eslint.

Without gulp, I just run eslint ./src --fix. I can't figure out how to make this happen with gulp. I tried below, setting fix to be true, but it doesn't fix any files:

gulp.task('lint', ['./src/**.js'], () => {
return gulp.src()
    .pipe($.eslint({fix:true}))
    .pipe($.eslint.format())
    .pipe($.eslint.failAfterError());
});

I want all the files under ./src to be fixed. How do I achieve this?


问:
Getting Random Nulls on .querySelector() in for Loop
```<code><div id="agg-filter-buttons">

<button class="btn filter-btn"  onclick="filterSelection(event)"><span data-
 value="freespins">Free Spins <div class="num-brands"></div> </span></button>

    <button class="btn filter-btn"  onclick="filterSelection(event)"> <span data-value="bigbonus">Big Bonus <div class="num-brands"></div>  </span></button>  </div>
    enter code here

</div>
</code>```

```<code>    <div class="brand-row the-table-row all row-1 filterDiv bigbonus newPlay show">
      Row 1
     </div>

       <div class="brand-row the-table-row all row-2 filterDiv freespins  newPlay show">
        Row 2
       </div>

 filterSelection();
  function filterSelection(e) {
    var x, i, c;
    x = document.getElementsByClassName("filterDiv");
    var allBtns = document.getElementsByClassName("filter-btn")
    for(i = 0; i<allBtns.length; i++){
      let rowsAffected = allBtns[i].querySelector('.num-brands');
      rowsAffected.innerText = '';
    }
      c = "all";
      if(e && e.target.dataset){
        c = e.target.dataset.value ? e.target.dataset.value : "all";
      }
    const numBrands = [];
    for (i = 0; i < x.length; i++) {
      x[i].classList.remove('show');
      void x[i].offsetWidth;
          if (x[i].classList.contains(c)) {
            x[i].classList.add('show');
            numBrands.push(i);
          }
    }
    if(e && e.target){
      e.srcElement.children[0].innerText =  ` (${numBrands.length})`;
    }
  }
  // Add active class to the current control button (highlight it)
  var btnContainer = document.getElementById("agg-filter-buttons");
  var btns = btnContainer.getElementsByClassName("filter-btn");

  for (var i = 0; i < btns.length; i++) {
    btns[i].addEventListener("click", function($this) {
      var current = document.querySelectorAll(".active-btn");
      current[0].className = current[0].className.replace(" active-btn", "");
      this.className += " active-btn";
    });
  }

  var filter = document.getElementById('agg-filter-buttons');
  filter.addEventListener('click', function(){
    document.getElementsByClassName('section--btable')[0].classList.add('flash');
  });
</code>```

filterSelection();

function filterSelection(e) {
  var x, i, c;
  x = document.getElementsByClassName("filterDiv");
  var allBtns = document.getElementsByClassName("filter-btn")
  for (i = 0; i < allBtns.length; i++) {
    let rowsAffected = allBtns[i].querySelector('.num-brands');
    rowsAffected.innerText = '';
  }
  c = "all";
  if (e && e.target.dataset) {
    c = e.target.dataset.value ? e.target.dataset.value : "all";
  }
  const numBrands = [];
  for (i = 0; i < x.length; i++) {
    x[i].classList.remove('show');
    void x[i].offsetWidth;
    if (x[i].classList.contains(c)) {
      x[i].classList.add('show');
      numBrands.push(i);
    }
  }
  if (e && e.target) {
    e.srcElement.children[0].innerText = ` (${numBrands.length})`;
  }
}
// Add active class to the current control button (highlight it)
var btnContainer = document.getElementById("agg-filter-buttons");
var btns = btnContainer.getElementsByClassName("filter-btn");

for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function($this) {
    var current = document.querySelectorAll(".active-btn");
    current[0].className = current[0].className.replace(" active-btn", "");
    this.className += " active-btn";
  });
}

var filter = document.getElementById('agg-filter-buttons');
filter.addEventListener('click', function() {
  document.getElementsByClassName('section--btable')[0].classList.add('flash');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="agg-filter-buttons">

  <button class="btn filter-btn" onclick="filterSelection(event)"><span data-
     value="freespins">Free Spins <div class="num-brands"></div> </span></button>

  <button class="btn filter-btn" onclick="filterSelection(event)"> <span data-value="bigbonus">Big Bonus <div class="num-brands"></div>  </span></button> </div>
enter code here

</div>

>
<div class="brand-row the-table-row all row-1 filterDiv bigbonus newPlay show">
  Row 1
</div>

<div class="brand-row the-table-row all row-2 filterDiv freespins  newPlay show">
  Row 2
</div></code>```

So I have a table with rows. These are filtered with the filter buttons. When you click a filter button it shows only the rows with the same name in its class. This works and populates the button with how many rows are affected.
However this breaks occasionally and I have no idea why.
the Variable rowsAffected works until it becomes null for some unknown reason.

My guess is that the dom eventually doesnt load fast enough for the querySelector to be able to read it. But im not sure.. Any advice very welcome!

I have also added a fiddle

https://jsfiddle.net/8z56sxby/

答:
Since you only care about the first .active-btn (because there is at most one), you can just use querySelector.

Make sure there is a current before you do anything with its classes.

Use element.classList.add and element.classList.remove to add or remove classes.

```<code>  for (var i = 0; i < btns.length; i++) {
    btns[i].addEventListener("click", function() {
      var current = document.querySelector(".active-btn");
      if (current) current.classList.remove("active-btn");
      this.classList.add("active-btn");
    });
  }
</code>```

Body:
<button class="btn filter-btn"  onclick="filterSelection(event)">Free Spins

 </button>

    <button class="btn filter-btn"  onclick="filterSelection(event)"> Big Bonus

  </button>

    enter code here

      Row 1

        Row 2

 filterSelection();
  function filterSelection(e) {
    var x, i, c;
    x = document.getElementsByClassName("filterDiv");
    var allBtns = document.getElementsByClassName("filter-btn")
    for(i = 0; i<allBtns.length; i++){
      let rowsAffected = allBtns[i].querySelector('.num-brands');
      rowsAffected.innerText = '';
    }
      c = "all";
      if(e && e.target.dataset){
        c = e.target.dataset.value ? e.target.dataset.value : "all";
      }
    const numBrands = [];
    for (i = 0; i < x.length; i++) {
      x[i].classList.remove('show');
      void x[i].offsetWidth;
          if (x[i].classList.contains(c)) {
            x[i].classList.add('show');
            numBrands.push(i);
          }
    }
    if(e && e.target){
      e.srcElement.children[0].innerText =  ` (${numBrands.length})`;
    }
  }
  // Add active class to the current control button (highlight it)
  var btnContainer = document.getElementById("agg-filter-buttons");
  var btns = btnContainer.getElementsByClassName("filter-btn");

  for (var i = 0; i < btns.length; i++) {
    btns[i].addEventListener("click", function($this) {
      var current = document.querySelectorAll(".active-btn");
      current[0].className = current[0].className.replace(" active-btn", "");
      this.className += " active-btn";
    });
  }

  var filter = document.getElementById('agg-filter-buttons');
  filter.addEventListener('click', function(){
    document.getElementsByClassName('section--btable')[0].classList.add('flash');
  });

filterSelection();

function filterSelection(e) {
  var x, i, c;
  x = document.getElementsByClassName("filterDiv");
  var allBtns = document.getElementsByClassName("filter-btn")
  for (i = 0; i < allBtns.length; i++) {
    let rowsAffected = allBtns[i].querySelector('.num-brands');
    rowsAffected.innerText = '';
  }
  c = "all";
  if (e && e.target.dataset) {
    c = e.target.dataset.value ? e.target.dataset.value : "all";
  }
  const numBrands = [];
  for (i = 0; i < x.length; i++) {
    x[i].classList.remove('show');
    void x[i].offsetWidth;
    if (x[i].classList.contains(c)) {
      x[i].classList.add('show');
      numBrands.push(i);
    }
  }
  if (e && e.target) {
    e.srcElement.children[0].innerText = ` (${numBrands.length})`;
  }
}
// Add active class to the current control button (highlight it)
var btnContainer = document.getElementById("agg-filter-buttons");
var btns = btnContainer.getElementsByClassName("filter-btn");

for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function($this) {
    var current = document.querySelectorAll(".active-btn");
    current[0].className = current[0].className.replace(" active-btn", "");
    this.className += " active-btn";
  });
}

var filter = document.getElementById('agg-filter-buttons');
filter.addEventListener('click', function() {
  document.getElementsByClassName('section--btable')[0].classList.add('flash');
});

  <button class="btn filter-btn" onclick="filterSelection(event)">Free Spins

 </button>

  <button class="btn filter-btn" onclick="filterSelection(event)"> Big Bonus

  </button>

enter code here

>

  Row 1

  Row 2

So I have a table with rows. These are filtered with the filter buttons. When you click a filter button it shows only the rows with the same name in its class. This works and populates the button with how many rows are affected.
However this breaks occasionally and I have no idea why.
the Variable rowsAffected works until it becomes null for some unknown reason.

My guess is that the dom eventually doesnt load fast enough for the querySelector to be able to read it. But im not sure.. Any advice very welcome!

I have also added a fiddle

https://jsfiddle.net/8z56sxby/

Body:
Since you only care about the first .active-btn (because there is at most one), you can just use querySelector.

Make sure there is a current before you do anything with its classes.

Use element.classList.add and element.classList.remove to add or remove classes.

  for (var i = 0; i < btns.length; i++) {
    btns[i].addEventListener("click", function() {
      var current = document.querySelector(".active-btn");
      if (current) current.classList.remove("active-btn");
      this.classList.add("active-btn");
    });
  }


问:
Outlook Add-in that just directs to a website
I want to program a simple Outlook add-in that opens a browser and take the user to a specific site.
I've had a look at using Yeoman, but this add-in opens a task pane where I'm just looking to take that single actions.
Is there a simple way to do this?

EDIT:

I managed to get this done, but I not have the following issue: I have a single button (via Yeoman's generator) that when clicked executes the following:

```<code>function action(event) {

const message = {
    type: Office.MailboxEnums.ItemNotificationMessageType.InformationalMessage,
    message: "Window opened.",
    icon: "Icon.80x80",
    persistent: true,
  };

  // Show a notification message
  window.open("https://myurl.com");
  Office.context.mailbox.item.notificationMessages.replaceAsync("action", message);

  // Be sure to indicate when the add-in command function is complete
  event.completed();
}
</code>```

I get the following error in Outlook itself:

We deployed the app using the MS 365 admin center, but I'm not sure if there is something additional that I need to do in this case to run the webserver?

答:
There is an Office.js API that will open a browser window:

```<code>Office.ui.openBrowserWindow( -- URL string here -- );
</code>```

This will cause the computers default browser to open to the specified URL. You could have a button in the task pane whose handlers calls this method. Alternatively, you could have a custom button on the ribbon that calls a FunctionFile that calls this method.

Body:
I want to program a simple Outlook add-in that opens a browser and take the user to a specific site.
I've had a look at using Yeoman, but this add-in opens a task pane where I'm just looking to take that single actions.
Is there a simple way to do this?

EDIT:

I managed to get this done, but I not have the following issue: I have a single button (via Yeoman's generator) that when clicked executes the following:

function action(event) {

const message = {
    type: Office.MailboxEnums.ItemNotificationMessageType.InformationalMessage,
    message: "Window opened.",
    icon: "Icon.80x80",
    persistent: true,
  };

  // Show a notification message
  window.open("https://myurl.com");
  Office.context.mailbox.item.notificationMessages.replaceAsync("action", message);

  // Be sure to indicate when the add-in command function is complete
  event.completed();
}

I get the following error in Outlook itself:

We deployed the app using the MS 365 admin center, but I'm not sure if there is something additional that I need to do in this case to run the webserver?

Body:
There is an Office.js API that will open a browser window:

Office.ui.openBrowserWindow( -- URL string here -- );

This will cause the computers default browser to open to the specified URL. You could have a button in the task pane whose handlers calls this method. Alternatively, you could have a custom button on the ribbon that calls a FunctionFile that calls this method.


问:
Uploading large files with Brettle Neatupload, but found a possible Intelligencia.UrlRewriter conflict?
I have been working on a project which requires large files to be uploaded (high res images, and videos etc). Windows website on IIS6 and dev on IIS7.

I am used to using Intelligencia.UrlRewriter for URL rewriting and this has worked brilliantly for me in on other projects.

I created a small test website to test NeatUpload and this worked really well, and once I'd figured out how to add some jQuery and more interesting formatting worked well.

However, once I copied the new code into the real web site the page failed with a HTTP Error:

HTTP Error 404.13 - Not Found
The request filtering module is configured to deny a request that exceeds the request content length.

I read the manual and tried the suggested fixes to I did not get any joy.

Has anyone come across this conflict before, or found a work around or solution?

Or if it is a non-starter, are there any other (non-flash) based 3rd party solutions I can use for uploading large files? I have wasted 3 days so far and I am starting to lose patience. :-(

Cheers
Toby

答:
This link has the solution to the problem:

http://deepeshsomani.wordpress.com/2011/08/16/how-to-resolve-file-size-error-for-files-whose-size-is-larger-than-specified-in-web-config/

Faced the same issue and resolved it using the same approach after a week spent like hell for a solution.


问:
Get the next seven days of the week in views - Django
How to get seven consecutive days of the week in views using Django. I try this, but it returns an error.

```<code>from datetime import datetime

day = datetime.now()
day_1 = datetime.now() + datetime.timedelta(days=1)
day_2 = datetime.now() + datetime.timedelta(days=2)
day_3 = datetime.now() + datetime.timedelta(days=3)
day_4 = datetime.now() + datetime.timedelta(days=4)
day_5 = datetime.now() + datetime.timedelta(days=5)
day_6 = datetime.now() + datetime.timedelta(days=6)
day_7 = datetime.now() + datetime.timedelta(days=7)
</code>```

It returns:

```<code>type object 'datetime.datetime' has no attribute 'timedelta'
</code>```

答:
import timedelta from datetime and use directly as

```<code>from datetime import datetime, timedelta

day = datetime.now()
day_1 = datetime.now() + timedelta(days=1)
day_2 = datetime.now() + timedelta(days=2)
day_3 = datetime.now() + timedelta(days=3)
day_4 = datetime.now() + timedelta(days=4)
day_5 = datetime.now() + timedelta(days=5)
day_6 = datetime.now() + timedelta(days=6)
day_7 = datetime.now() + timedelta(days=7)
</code>```

Body:
How to get seven consecutive days of the week in views using Django. I try this, but it returns an error.

from datetime import datetime

day = datetime.now()
day_1 = datetime.now() + datetime.timedelta(days=1)
day_2 = datetime.now() + datetime.timedelta(days=2)
day_3 = datetime.now() + datetime.timedelta(days=3)
day_4 = datetime.now() + datetime.timedelta(days=4)
day_5 = datetime.now() + datetime.timedelta(days=5)
day_6 = datetime.now() + datetime.timedelta(days=6)
day_7 = datetime.now() + datetime.timedelta(days=7)

It returns:

type object 'datetime.datetime' has no attribute 'timedelta'

Body:
import timedelta from datetime and use directly as

from datetime import datetime, timedelta

day = datetime.now()
day_1 = datetime.now() + timedelta(days=1)
day_2 = datetime.now() + timedelta(days=2)
day_3 = datetime.now() + timedelta(days=3)
day_4 = datetime.now() + timedelta(days=4)
day_5 = datetime.now() + timedelta(days=5)
day_6 = datetime.now() + timedelta(days=6)
day_7 = datetime.now() + timedelta(days=7)


问:
Is async all the way inevitable for C# rest API?
I saw and read a lot of pages about async-await in C# but something is still unclear.
With a 3-Tier architecture like Controller - Business Layer - Data Layer, if your Data Layer do async method (because its calling Database or RestAPI), your Business Layer and Controller need to be async and await too.
This is a design intent ?

I understand that async-await is usefull for call that are not handled by the server CPU like for database call or http calls, then you can give the current thread to another task and return to this one when the async operation is finished.
But with an architecture like I explained, if you have async method in your lowest layer you endup bubbling up the async-await pattern everywhere and it seems that it's not useful in those cases.

I must be missing something or some explanation.
So you know I read multiple thread on stackoverflow and some Microsoft documentation but still can't explain that.

答:
Let's invert the example. Compare a regular synchronous application, and and application which is internally async but wrapped in a synchronous shell. How would they appear different to the outside observer?

They wouldn't. Sure, you may know that in your application it's a different component that is blocking the thread (e.g. BLL instead of DAL); but the outside observer only cares that there is a thread being blocked, not which object or layer in the application is doing it. The outside observer pretty much by definition does not care nor differentiate between the internal implementations of an application.

The only way for an application to not block the thread, which is the core principle of asynchrony; is for the await logic to bubble up out of your application. Now, the outside observer sees a difference: the thread isn't blocked and the observer is able to go do something else in the meanwhile. Without that being the case, there is no point to having asynchrony in the first place.

At its very core, synchronous code does not communicate. You give your employee a job: heat the sauce. He uses a microwave. It takes him 10 seconds to put it in and 10 seconds to take it out. During the microwaving, he either stands there doing nothing or leaves the kitchen and tells no one. Others are waiting to use the kitchen, and he's not doing anything and is therefore wasting kitchen availability because he never told anyone that they could jump in while he was waiting for the microwave. He's blocking the path in the kitchen for no purpose other than because he chose to idle there. This is a synchronous worker.

Comparatively, an asynchronous worker will realize that he is idling, steps out of the kitchen to make way, and lets the others know that there is now space for them to get their own work done in the kitchen.

But the only way in which this works is if he actually tells the others that he has stepped out of the kitchen so that they can get in. This part of the analogy is the equivalent of having your await logic bubble up out of your application. If you keep it inside, then you've not communicated.

One more thing: if your application starts a task, but has enough other work to do while the task completes; when it finally awaits the (already finished by now) task, it never bubbled up out of your application. An await only bubbles up if the thread has nothing more to do except waiting.


问:
Escaping strings in bash
I have this simple bash script:

```<code>#!/bin/bash
isRunning=$(ps -Af | awk '{if ($11 == "HomeDir") { print $0 }}' | wc -l)
if [ $isRunning == "0" ]; then
    echo "Script is running"
fi
</code>```

The script returns:

```<code>./script.sh: line 3: [ 0: command not found
</code>```

What did i do wrong?

答:
You are using bash so I think "==" is totally ok:
http://www.gnu.org/software/bash/manual/bashref.html#Bash-Conditional-Expressions

```<code>$ [ a == b ]
$ echo $?
1
$ [ a == a ]
$ echo $?
0
</code>```

I run your script on my machine but I didn't get your error. My bash version is 4.1_p9. You could also try [[ foo == bar ]] and it should be working for you.

Title: Escaping strings in bash

Body:
I have this simple bash script:

#!/bin/bash
isRunning=$(ps -Af | awk '{if ($11 == "HomeDir") { print $0 }}' | wc -l)
if [ $isRunning == "0" ]; then
    echo "Script is running"
fi

The script returns:

./script.sh: line 3: [ 0: command not found

What did i do wrong?

Body:
You are using bash so I think "==" is totally ok:
http://www.gnu.org/software/bash/manual/bashref.html#Bash-Conditional-Expressions

$ [ a == b ]
$ echo $?
1
$ [ a == a ]
$ echo $?
0

I run your script on my machine but I didn't get your error. My bash version is 4.1_p9. You could also try [[ foo == bar ]] and it should be working for you.


问:
How to convert an object into an array of objects with named properties?
How do you go from a single object like this:

```<code>{
    item001: '200',
    item002: '350',
    ...
}
</code>```

to an array of objects with named properties like this:

```<code>[
    {
        product: 'item001',
        price: 200
    },
    {
        product: 'item002',
        price: 350
    },
    ...
]
</code>```

答:
Here you go:

const data = {
    item001: '200',
    item002: '350',
}

const arrData = Object.keys(data).map(product => ({
    product: product,
    price: Number(data[product])
}))
```

Body:
How do you go from a single object like this:

{
    item001: '200',
    item002: '350',
    ...
}

to an array of objects with named properties like this:

[
    {
        product: 'item001',
        price: 200
    },
    {
        product: 'item002',
        price: 350
    },
    ...
]


问:
How to sum two times in Java, using LocalTime?
Example:

```<code>LocalTime time1 = LocalTime.of(12, 30);
LocalTime time2 = LocalTime.of(8, 30);
time1 + time2   // Doesn't work.
time1.plus(time2)   // Doesn't work.
</code>```

I want to get the sum of the two times (12:30 + 8:30 = 21:00) in the format of (hours:minutes).

Any other suggestions?

答:
```<code>LocalTime t1 = LocalTime.parse('03:33:24')
LocalTime t2 = LocalTime.parse('03:13:41')

t1.plusHours(t2.hour)
  .plusMinutes(t2.minute)
  .plusSeconds(t2.second)
  .plusNanos(t2.nano)
</code>```

Body:
Example:

LocalTime time1 = LocalTime.of(12, 30);
LocalTime time2 = LocalTime.of(8, 30);
time1 + time2   // Doesn't work.
time1.plus(time2)   // Doesn't work.

I want to get the sum of the two times (12:30 + 8:30 = 21:00) in the format of (hours:minutes).

Any other suggestions?


问:
Regex to match either range or list of numbers
I need a regex to match lists of numbers and another one to match ranges of numbers (expressions shall never fail in both cases). Ranges shall consist of a number, a dash, and another number (N-N), while lists shall consist of numbers separated by a comma (N,N,N). Here below are some examples.

Ranges:

```<code>'1-10' => OK
Whateverelse => NOK (e.g. '1-10 11-20')
</code>```

List:

```<code>'1,2,3' => OK
Whateverelse => NOK
</code>```

And here are my two regular expressions:

[0-9]+[\-][0-9]+

([0-9]+,?)+

... but I have a few problems with them... for example:

When evaluating '1-10', regex 2 matches 1... but it shouldn't match anything because the string does not contain a list.

Then, when evaluating '1-10 11-14', regex 1 matches 1-10... but it shouldn't match anything because the string contains more than just a range.

What am I missing? Thanks.

答:
I needed something to match a list of integers that are comma separated, such as 1,2,3,4 but also specify ranges such as 100-255 and combinations thereof, such as 1011,1100-1300,1111,1919-9999,2111. Basically the OP request and combinations of it.

For this, I use the following regular expression tested over at Regex101.com:

^\d+((\,|-)\d+)*$

You can think of this as:

From the start of the string

Expect 1 or more digits, and either...

A literal comma and 1 or more digits, or...

A hyphen and 1 or more digits

with (3) and (4) repeating zero or more times

Until the string end

This permits all the following to be valid:

```<code>2011,2100-2300
2011,2013
1014-2024
999
1011,1100-1300,1111,1919-9999,2111
</code>```

Note: global and multiline regex options /gm should be included if being used for multiline input

The downside is something like 100-100-100 is still valid, even though other types of change will ensure no match. Not sure of the complexity to resolve it further, but it was good enough for my needs.

Body:
I need a regex to match lists of numbers and another one to match ranges of numbers (expressions shall never fail in both cases). Ranges shall consist of a number, a dash, and another number (N-N), while lists shall consist of numbers separated by a comma (N,N,N). Here below are some examples.

Ranges:

'1-10' => OK
Whateverelse => NOK (e.g. '1-10 11-20')

List:

'1,2,3' => OK
Whateverelse => NOK

And here are my two regular expressions:

[0-9]+[\-][0-9]+

([0-9]+,?)+

... but I have a few problems with them... for example:

When evaluating '1-10', regex 2 matches 1... but it shouldn't match anything because the string does not contain a list.

Then, when evaluating '1-10 11-14', regex 1 matches 1-10... but it shouldn't match anything because the string contains more than just a range.

What am I missing? Thanks.

Body:
I needed something to match a list of integers that are comma separated, such as 1,2,3,4 but also specify ranges such as 100-255 and combinations thereof, such as 1011,1100-1300,1111,1919-9999,2111. Basically the OP request and combinations of it.

For this, I use the following regular expression tested over at Regex101.com:

^\d+((\,|-)\d+)*$

You can think of this as:

From the start of the string

Expect 1 or more digits, and either...

A literal comma and 1 or more digits, or...

A hyphen and 1 or more digits

with (3) and (4) repeating zero or more times

Until the string end

This permits all the following to be valid:

2011,2100-2300
2011,2013
1014-2024
999
1011,1100-1300,1111,1919-9999,2111

Note: global and multiline regex options /gm should be included if being used for multiline input

The downside is something like 100-100-100 is still valid, even though other types of change will ensure no match. Not sure of the complexity to resolve it further, but it was good enough for my needs.