问:
DbContext per request aspboilerplate
I need to implement multithreading background job for import file.
I have implemented it with background job(Hangfire). But if i use one thread it goes very slow.
The function look like this.

I using non-transaction unit to save changes to db immediately.

```<code>var contactFound = await _contactRepository.FirstOrDefaultAsync(x => x.Email.ToLower() == contact.Email.ToLower());

            if (contactFound != null)
            {
                await _bjInfoManager.AddLog(args.JobId, "Found duplicated email: " + contact.Email);

            }
            else
            {
                contact.ContactListId = args.ContactListId;
                contact.Email = contact.Email.ToLower();

                await _contactRepository.InsertAsync(contact);

                //Save changes in db
                await CurrentUnitOfWork.SaveChangesAsync();
            }
</code>```

The problem occur when I tries to use this with Producer-Consumer Dataflow Pattern. I throws the exception "A second operation started on this context before a previous asynchronous operation completed."

The question is how to create isolated DbContext inside this method.
Please help me.

答:
Transactions should not be multi-threaded. If you create a new task/thread in a UOW, you can create a seperated UOW using IUnitOfWork.Begin(TransactionScopeOption.RequiresNew) in a using block.

See the links

https://github.com/aspnetboilerplate/aspnetboilerplate/issues/619

Does Entity Framework support Multi-Threading?

Entity Framework and Multi threading

If you are using Microsoft SQL Server, then I recommend you to use bulk insert. It's super fast than entity framework.

https://learn.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql

Title: DbContext per request aspboilerplate

Body:
I need to implement multithreading background job for import file.
I have implemented it with background job(Hangfire). But if i use one thread it goes very slow.
The function look like this.

I using non-transaction unit to save changes to db immediately.

var contactFound = await _contactRepository.FirstOrDefaultAsync(x => x.Email.ToLower() == contact.Email.ToLower());

            if (contactFound != null)
            {
                await _bjInfoManager.AddLog(args.JobId, "Found duplicated email: " + contact.Email);

            }
            else
            {
                contact.ContactListId = args.ContactListId;
                contact.Email = contact.Email.ToLower();

                await _contactRepository.InsertAsync(contact);

                //Save changes in db
                await CurrentUnitOfWork.SaveChangesAsync();
            }

The problem occur when I tries to use this with Producer-Consumer Dataflow Pattern. I throws the exception "A second operation started on this context before a previous asynchronous operation completed."

The question is how to create isolated DbContext inside this method.
Please help me.


来源: stackexchange

问:
disable other input[file] untill the first ( file #1 ) one is selected
i have multiple inputs for file upload and i'm trying by jquery to disable the rest until the first ( file #1 ) one is selected then enable the rest

My code :

<input type="file" id="checkupload" name="image" />
<input type="file" id="checkupload" name="image2" />
<input type="file" id="checkupload" name="image3" />
<input type="file" id="checkupload" name="image4" />
<input type="file" id="checkupload" name="image5" />
<input type="file" id="checkupload" name="image6" />
<input type="file" id="checkupload" name="image7" />
<input type="file" id="checkupload" name="image8" />```

答:
You can use .prop("disabled", true) to disable the input and check then on change event in jQuery like below

$('input[type="file"]:not(:first)').prop("disabled", true);
$('input[type="file"]:first').on('change', function() {
  if ($(this).val() == '') {

  } else {
    $('input[type="file"]').prop("disabled", false);
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="checkupload" name="image" />
<input type="file" id="checkupload" name="image2" />
<input type="file" id="checkupload" name="image3" />
<input type="file" id="checkupload" name="image4" />
<input type="file" id="checkupload" name="image5" />
<input type="file" id="checkupload" name="image6" />
<input type="file" id="checkupload" name="image7" />
<input type="file" id="checkupload" name="image8" /></code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use .prop("disabled", true) to disable the input and check then on change event in jQuery like below

$('input[type="file"]:not(:first)').prop("disabled", true);
$('input[type="file"]:first').on('change', function() {
  if ($(this).val() == '') {

  } else {
    $('input[type="file"]').prop("disabled", false);
  }
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="checkupload" name="image" />
<input type="file" id="checkupload" name="image2" />
<input type="file" id="checkupload" name="image3" />
<input type="file" id="checkupload" name="image4" />
<input type="file" id="checkupload" name="image5" />
<input type="file" id="checkupload" name="image6" />
<input type="file" id="checkupload" name="image7" />
<input type="file" id="checkupload" name="image8" />


问:
How to make HTTP request in Swift?
I read The Programming Language Swift by Apple in iBooks, but cannot figure out how to make an HTTP request (something like cURL) in Swift. Do I need to import Obj-C classes or do I just need to import default libraries? Or is it not possible to make an HTTP request based on native Swift code?</p>

答:
Details

Xcode Version 14.2 (14C18), Swift 5.7

Info.plist

NSAppTransportSecurity

Add to the info plist:

```<code><key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
</code>```

NetworkManagerable interface

```<code>import Foundation

// MARK: NetworkManagerable

protocol NetworkManagerable: AnyObject {
    func dictionary(from request: URLRequest,
                    session: URLSession,
                    jsonReadingOptions: JSONSerialization.ReadingOptions,
                    completion: @escaping (Result<[String: Any], NetworkManagerError>) -> Void)
    func dictionary(from request: URLRequest,
                    session: URLSession,
                    jsonReadingOptions: JSONSerialization.ReadingOptions) async -> Result<[String: Any], NetworkManagerError>

    func codable<Value>(_ type: Value.Type,
                        from request: URLRequest,
                        session: URLSession,
                        completion: @escaping (Result<Value, NetworkManagerError>) -> Void) where Value: Codable
    func codable<Value>(_ type: Value.Type,
                        from request: URLRequest,
                        session: URLSession) async -> Result<Value, NetworkManagerError> where Value: Codable
}

extension NetworkManagerable {
    func dictionary(from request: URLRequest,
                    jsonReadingOptions: JSONSerialization.ReadingOptions = .mutableContainers,
                    completion: @escaping (Result<[String: Any], NetworkManagerError>) -> Void) {
        dictionary(from: request,
                   session: .shared,
                   jsonReadingOptions: jsonReadingOptions,
                   completion: completion)
    }

    func dictionary(from request: URLRequest,
                    jsonReadingOptions: JSONSerialization.ReadingOptions = .mutableContainers) async -> Result<[String: Any], NetworkManagerError> {
        await dictionary(from: request, session: .shared, jsonReadingOptions: jsonReadingOptions)
    }

    func codable<Value>(_ type: Value.Type,
                        from request: URLRequest,
                        completion: @escaping (Result<Value, NetworkManagerError>) -> Void) where Value: Codable {
        codable(type, from: request, session: .shared, completion: completion)
    }

    func codable<Value>(_ type: Value.Type,
                        from request: URLRequest) async -> Result<Value, NetworkManagerError> where Value: Codable {
        await codable(type, from: request, session: .shared)
    }
}

// MARK: NetworkManager Errors

enum NetworkManagerError: Error {
    case dataTask(error: Error)
    case emptyData
    case jsonSerialization(error: Error)
    case castingError(value: Any, isNot: Any)
    case networkMangerIsNotExists
    case jsonDecoding(error: Error)
}
</code>```

NetworkManager

```<code>// MARK: NetworkManager

class NetworkManager {
    private func data(from request: URLRequest,
                      session: URLSession,
                      completion: @escaping (Result<Data, NetworkManagerError>) -> Void) {
        let task = session.dataTask(with: request) { data, response, error in
            if let error = error {
                completion(.failure(.dataTask(error: error)))
                return
            }
            guard let data = data else {
                completion(.failure(.emptyData))
                return
            }
            completion(.success(data))
        }
        task.resume()
    }
}

// MARK: NetworkManagerable

extension NetworkManager: NetworkManagerable { }

// MARK: Receive Codable

extension NetworkManager {
    private func codable<Value>(_ type: Value.Type,
                                from data: Data) -> Result<Value, NetworkManagerError>
    where Value : Decodable, Value : Encodable {
        do {
            let codableValue = try JSONDecoder().decode(Value.self, from: data)
            return .success(codableValue)
        } catch let error {
            return .failure(.jsonDecoding(error: error))
        }
    }

    func codable<Value>(_ type: Value.Type,
                        from request: URLRequest,
                        session: URLSession,
                        completion: @escaping (Result<Value, NetworkManagerError>) -> Void)
    where Value : Decodable, Value : Encodable {
        data(from: request, session: session) { [weak self] result in
            guard let self = self else {
                completion(.failure(.networkMangerIsNotExists))
                return
            }
            switch result {
            case let .success(data):
                return completion(self.codable(type, from: data))
            case let .failure(error):
                return completion(.failure(error))
            }
        }
    }

    func codable<Value>(_ type: Value.Type,
                        from request: URLRequest,
                        session: URLSession) async -> Result<Value, NetworkManagerError> where Value : Decodable, Value : Encodable {
        do {
            let (data, _) = try await URLSession.shared.data(for: request)
            return codable(type, from: data)
        } catch let error {
            return .failure(.dataTask(error: error))
        }
    }
}

// MARK: Receive Dictionary

extension NetworkManager {

    private func dictionary(from data: Data,
                            jsonReadingOptions: JSONSerialization.ReadingOptions) -> Result<[String: Any], NetworkManagerError> {
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: jsonReadingOptions)
            guard let dictionary = json as? [String: Any] else {
                return .failure(.castingError(value: json, isNot: [String: Any].self))
            }
            return .success(dictionary)

        } catch let error {
            return .failure(.jsonSerialization(error: error))
        }
    }

    func dictionary(from request: URLRequest,
                    session: URLSession = .shared,
                    jsonReadingOptions: JSONSerialization.ReadingOptions = .mutableContainers,
                    completion: @escaping (Result<[String: Any], NetworkManagerError>) -> Void) {
        data(from: request, session: session) { [weak self] result in
            guard let self = self else {
                completion(.failure(.networkMangerIsNotExists))
                return
            }
            switch result {
            case let .success(data):
                return completion(self.dictionary(from: data, jsonReadingOptions: jsonReadingOptions))
            case let .failure(error):
                return completion(.failure(error))
            }
        }
    }

    func dictionary(from request: URLRequest,
                    session: URLSession,
                    jsonReadingOptions: JSONSerialization.ReadingOptions) async -> Result<[String: Any], NetworkManagerError> {
        do {
            let (data, _) = try await URLSession.shared.data(for: request)
            return self.dictionary(from: data, jsonReadingOptions: jsonReadingOptions)
        } catch let error {
            return .failure(.dataTask(error: error))
        }
    }
}
</code>```

Usage example

```<code>struct ItunesElement: Codable {
    let artistName: String
}

struct ItunesResponse: Codable {
    let resultCount: Int
    let results: [ItunesElement]
}

private var networkManager: NetworkManagerable = NetworkManager()
let searchString = "matrix".replacingOccurrences(of: " ", with: "+")
let urlString = "https://itunes.apple.com/search?term=\(searchString)"
if let url = URL(string: urlString) {
    let request = URLRequest(url: url)

    networkManager.dictionary(from: request) { result in
        print(result)
    }
    networkManager.codable(ItunesResponse.self, from: request) { result in
        print(result)
    }
    Task {
        print(await networkManager.dictionary(from: request))
        print(await networkManager.codable(ItunesResponse.self, from: request))
    }
}
</code>```

Results

ContentLicense: CC BY-SA 4.0

Title: How to make HTTP request in Swift?

Body:
Details

Xcode Version 14.2 (14C18), Swift 5.7

Info.plist

NSAppTransportSecurity

Add to the info plist:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

NetworkManagerable interface

import Foundation

// MARK: NetworkManagerable

protocol NetworkManagerable: AnyObject {
    func dictionary(from request: URLRequest,
                    session: URLSession,
                    jsonReadingOptions: JSONSerialization.ReadingOptions,
                    completion: @escaping (Result<[String: Any], NetworkManagerError>) -> Void)
    func dictionary(from request: URLRequest,
                    session: URLSession,
                    jsonReadingOptions: JSONSerialization.ReadingOptions) async -> Result<[String: Any], NetworkManagerError>

    func codable<Value>(_ type: Value.Type,
                        from request: URLRequest,
                        session: URLSession,
                        completion: @escaping (Result<Value, NetworkManagerError>) -> Void) where Value: Codable
    func codable<Value>(_ type: Value.Type,
                        from request: URLRequest,
                        session: URLSession) async -> Result<Value, NetworkManagerError> where Value: Codable
}

extension NetworkManagerable {
    func dictionary(from request: URLRequest,
                    jsonReadingOptions: JSONSerialization.ReadingOptions = .mutableContainers,
                    completion: @escaping (Result<[String: Any], NetworkManagerError>) -> Void) {
        dictionary(from: request,
                   session: .shared,
                   jsonReadingOptions: jsonReadingOptions,
                   completion: completion)
    }

    func dictionary(from request: URLRequest,
                    jsonReadingOptions: JSONSerialization.ReadingOptions = .mutableContainers) async -> Result<[String: Any], NetworkManagerError> {
        await dictionary(from: request, session: .shared, jsonReadingOptions: jsonReadingOptions)
    }

    func codable<Value>(_ type: Value.Type,
                        from request: URLRequest,
                        completion: @escaping (Result<Value, NetworkManagerError>) -> Void) where Value: Codable {
        codable(type, from: request, session: .shared, completion: completion)
    }

    func codable<Value>(_ type: Value.Type,
                        from request: URLRequest) async -> Result<Value, NetworkManagerError> where Value: Codable {
        await codable(type, from: request, session: .shared)
    }
}

// MARK: NetworkManager Errors

enum NetworkManagerError: Error {
    case dataTask(error: Error)
    case emptyData
    case jsonSerialization(error: Error)
    case castingError(value: Any, isNot: Any)
    case networkMangerIsNotExists
    case jsonDecoding(error: Error)
}

NetworkManager

// MARK: NetworkManager

class NetworkManager {
    private func data(from request: URLRequest,
                      session: URLSession,
                      completion: @escaping (Result<Data, NetworkManagerError>) -> Void) {
        let task = session.dataTask(with: request) { data, response, error in
            if let error = error {
                completion(.failure(.dataTask(error: error)))
                return
            }
            guard let data = data else {
                completion(.failure(.emptyData))
                return
            }
            completion(.success(data))
        }
        task.resume()
    }
}

// MARK: NetworkManagerable

extension NetworkManager: NetworkManagerable { }

// MARK: Receive Codable

extension NetworkManager {
    private func codable<Value>(_ type: Value.Type,
                                from data: Data) -> Result<Value, NetworkManagerError>
    where Value : Decodable, Value : Encodable {
        do {
            let codableValue = try JSONDecoder().decode(Value.self, from: data)
            return .success(codableValue)
        } catch let error {
            return .failure(.jsonDecoding(error: error))
        }
    }

    func codable<Value>(_ type: Value.Type,
                        from request: URLRequest,
                        session: URLSession,
                        completion: @escaping (Result<Value, NetworkManagerError>) -> Void)
    where Value : Decodable, Value : Encodable {
        data(from: request, session: session) { [weak self] result in
            guard let self = self else {
                completion(.failure(.networkMangerIsNotExists))
                return
            }
            switch result {
            case let .success(data):
                return completion(self.codable(type, from: data))
            case let .failure(error):
                return completion(.failure(error))
            }
        }
    }

    func codable<Value>(_ type: Value.Type,
                        from request: URLRequest,
                        session: URLSession) async -> Result<Value, NetworkManagerError> where Value : Decodable, Value : Encodable {
        do {
            let (data, _) = try await URLSession.shared.data(for: request)
            return codable(type, from: data)
        } catch let error {
            return .failure(.dataTask(error: error))
        }
    }
}

// MARK: Receive Dictionary

extension NetworkManager {

    private func dictionary(from data: Data,
                            jsonReadingOptions: JSONSerialization.ReadingOptions) -> Result<[String: Any], NetworkManagerError> {
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: jsonReadingOptions)
            guard let dictionary = json as? [String: Any] else {
                return .failure(.castingError(value: json, isNot: [String: Any].self))
            }
            return .success(dictionary)

        } catch let error {
            return .failure(.jsonSerialization(error: error))
        }
    }

    func dictionary(from request: URLRequest,
                    session: URLSession = .shared,
                    jsonReadingOptions: JSONSerialization.ReadingOptions = .mutableContainers,
                    completion: @escaping (Result<[String: Any], NetworkManagerError>) -> Void) {
        data(from: request, session: session) { [weak self] result in
            guard let self = self else {
                completion(.failure(.networkMangerIsNotExists))
                return
            }
            switch result {
            case let .success(data):
                return completion(self.dictionary(from: data, jsonReadingOptions: jsonReadingOptions))
            case let .failure(error):
                return completion(.failure(error))
            }
        }
    }

    func dictionary(from request: URLRequest,
                    session: URLSession,
                    jsonReadingOptions: JSONSerialization.ReadingOptions) async -> Result<[String: Any], NetworkManagerError> {
        do {
            let (data, _) = try await URLSession.shared.data(for: request)
            return self.dictionary(from: data, jsonReadingOptions: jsonReadingOptions)
        } catch let error {
            return .failure(.dataTask(error: error))
        }
    }
}

Usage example

struct ItunesElement: Codable {
    let artistName: String
}

struct ItunesResponse: Codable {
    let resultCount: Int
    let results: [ItunesElement]
}

private var networkManager: NetworkManagerable = NetworkManager()
let searchString = "matrix".replacingOccurrences(of: " ", with: "+")
let urlString = "https://itunes.apple.com/search?term=\(searchString)"
if let url = URL(string: urlString) {
    let request = URLRequest(url: url)

    networkManager.dictionary(from: request) { result in
        print(result)
    }
    networkManager.codable(ItunesResponse.self, from: request) { result in
        print(result)
    }
    Task {
        print(await networkManager.dictionary(from: request))
        print(await networkManager.codable(ItunesResponse.self, from: request))
    }
}

Results


问:
java - Loop optimization on int array
I would like to know, which is fast way to write/read in an int array.

Here my Java code: I have three int arrays, two in read access and one int array in write access.

```<code>for(int j = h20 ; j < h21 ; j++){
    for(int i = w20 ; i < w21 ; i++){
        if( int_color == arr3[j*h31 + i] )  continue; //condition
        arr1[(j+decY)*w11 + i+decX] = arr2[j*w21 + i];
    }
}
</code>```

My code is a classic 2D array loop, there are just one special condition to check.

Is it other way to write this code to decrease processing time?

Thx.

答:
Removing calculations, especially multiplications might help.

For arr3 this would be:

```<code>final int icolor = int_color;
final int ix3 = h20 + w20;
final int dx3 = h31 + h21 - h20;

for (int j = h20; j < h21; ++j) {
    for (int i = w20 ; i < w21 ; ++i) {
        assert ix3 == j*h31 + i;
        if (icolor != arr3[ix3]) {
            arr1[(j+decY)*w11 + i+decX] = arr2[j*w21 + i];
        }
        ++ix3;
    }
    ix3 += dx3;
}
</code>```

Whether this is really worthwile one needs to test.

Depending on the frequency of the condition, one might think of using System.arraycopy for consecutive ranges of i.

Title: java - Loop optimization on int array

Body:
I would like to know, which is fast way to write/read in an int array.

Here my Java code: I have three int arrays, two in read access and one int array in write access.

for(int j = h20 ; j < h21 ; j++){
    for(int i = w20 ; i < w21 ; i++){
        if( int_color == arr3[j*h31 + i] )  continue; //condition
        arr1[(j+decY)*w11 + i+decX] = arr2[j*w21 + i];
    }
}

My code is a classic 2D array loop, there are just one special condition to check.

Is it other way to write this code to decrease processing time?

Thx.

Body:
Removing calculations, especially multiplications might help.

For arr3 this would be:

final int icolor = int_color;
final int ix3 = h20 + w20;
final int dx3 = h31 + h21 - h20;

for (int j = h20; j < h21; ++j) {
    for (int i = w20 ; i < w21 ; ++i) {
        assert ix3 == j*h31 + i;
        if (icolor != arr3[ix3]) {
            arr1[(j+decY)*w11 + i+decX] = arr2[j*w21 + i];
        }
        ++ix3;
    }
    ix3 += dx3;
}

Whether this is really worthwile one needs to test.

Depending on the frequency of the condition, one might think of using System.arraycopy for consecutive ranges of i.


问:
How to send images without storing them onto a server?
Is it possible to send the image without storing it in server?

Or, if it is not possible, how to send the image to a chat application?

I tried with firebase storage, but it has storage limitation

Please help me. How to do that?

I am new to Android.

答:
You can't easily send file directly from device to device via internet, without using any server or cloud service.

If you have issues with storage limitations you need to purchase more storage, obviosly.

If you want to use free solution, try to search for another storage providers with greater limits or deploy your own server on your own machine (which unfortunately can be quite hard)


问:
how to check, if the input field contains any value in protractor tests
I would like to check if the input field contains any string or not. From the below code snippet, how can I check ? it actually contains Asset Management.

```<code><input _ngcontent-c6="" class="col-md-3 mat-input-element mat-form-field-autofill-control ng-pristine ng-valid ng-touched" id="title" matinput="" placeholder="Object Title" type="text" ng-reflect-model="Asset Management" ng-reflect-id="title" ng-reflect-placeholder="Object Title" ng-reflect-type="text" aria-describedby="mat-hint-2" aria-invalid="false">
</code>```

答:
Set up a way to select your input, one example :

```<code>beforeEach(function() {
    input = element(by.id('title'));
  });
</code>```

then in your test you can do :

```<code>expect(input.getAttribute('value')).toBe('Asset Management')
</code>```

If you just want to see if there is any value :

```<code>expect(input.getAttribute('value')).toBeTruthy()
</code>```

Body:
I would like to check if the input field contains any string or not. From the below code snippet, how can I check ? it actually contains Asset Management.

<input _ngcontent-c6="" class="col-md-3 mat-input-element mat-form-field-autofill-control ng-pristine ng-valid ng-touched" id="title" matinput="" placeholder="Object Title" type="text" ng-reflect-model="Asset Management" ng-reflect-id="title" ng-reflect-placeholder="Object Title" ng-reflect-type="text" aria-describedby="mat-hint-2" aria-invalid="false">

Body:
Set up a way to select your input, one example :

beforeEach(function() {
    input = element(by.id('title'));
  });

then in your test you can do :

expect(input.getAttribute('value')).toBe('Asset Management')

If you just want to see if there is any value :

expect(input.getAttribute('value')).toBeTruthy()


问:
How to connect keyboard to button?
In my application I have EditText and Button and for this editText I set actionDone for imeOption.

My EditText code :

```<code><EditText
    android:id="@+id/infoSerialFrag_rememberSwitchText"
    android:layout_width="@dimen/size30"
    android:layout_height="match_parent"
    android:layout_toRightOf="@+id/infoSerialFrag_rememberSwitch"
    android:fontFamily="sans-serif-light"
    android:gravity="center"
    android:hint="7"
    android:imeOptions="actionDone"
    android:inputType="number"
    android:maxLength="3"
    android:maxLines="1"
    android:textSize="@dimen/font11" />
</code>```

When open keyboard show me Done in keyboard.

For Button I set one method.

I want when click on Done from keyboard, work me such as onClickListener for my Button.

My mean is : when click on Done from keyboard, call method in button.setOnClickLiostener{...}

How can I it? please help me

答:
Use below code

```<code>editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
       @Override
       public boolean onEditorAction(EditText v, int actionId, KeyEvent event) {
       if (actionId == EditorInfo.IME_ACTION_DONE) {
          view.performClick();
          return true;
       }
       return false;
       }
   });
</code>```

View is the button view name. You need to call performClick() method. this will execute the code which is available in onclick() call back method. Hope that answers your question

Title: How to connect keyboard to button?

Body:
In my application I have EditText and Button and for this editText I set actionDone for imeOption.

My EditText code :

<EditText
    android:id="@+id/infoSerialFrag_rememberSwitchText"
    android:layout_width="@dimen/size30"
    android:layout_height="match_parent"
    android:layout_toRightOf="@+id/infoSerialFrag_rememberSwitch"
    android:fontFamily="sans-serif-light"
    android:gravity="center"
    android:hint="7"
    android:imeOptions="actionDone"
    android:inputType="number"
    android:maxLength="3"
    android:maxLines="1"
    android:textSize="@dimen/font11" />

When open keyboard show me Done in keyboard.

For Button I set one method.

I want when click on Done from keyboard, work me such as onClickListener for my Button.

My mean is : when click on Done from keyboard, call method in button.setOnClickLiostener{...}

How can I it? please help me

Body:
Use below code

editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
       @Override
       public boolean onEditorAction(EditText v, int actionId, KeyEvent event) {
       if (actionId == EditorInfo.IME_ACTION_DONE) {
          view.performClick();
          return true;
       }
       return false;
       }
   });

View is the button view name. You need to call performClick() method. this will execute the code which is available in onclick() call back method. Hope that answers your question


问:
How to get column count in SQL before executing the query? i.e. way other than ResultSetMetaData
I have a sql query. Because of too many BO's are involved, it's forming very big query containing more than 1000 columns. So I need some way with which I can find column count before hand and then apply some logic to handle 1000 column error.

May be parsing a query to get column count would help. But not getting how to implement it.

Note: tried below code already, it's giving me result, but i dont want to execute query, that's costly.

```<code>PreparedStatement pstmt;
    try {
        pstmt = getConnection().prepareStatement(sql);
        ResultSetMetaData meta = pstmt.getMetaData();
        System.out.println(meta.getColumnCount());

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

答: I guess your SQL query using lot of wildcards after SELECT statement right? If no wildcard used, you can parse SQL query part between SELECT and FROM to get column numbers.I feel some disturbance in the force if i hear you have such big results of unknown attributes. If we can say that SQL table is data source, we can say that query result is data source too. In case of SQL table we have defined very specifically what columns(attributes) it contain. If u create SQL query without specification of columns you have data source of unknown entity. Are you trying to create some BI system? If yes you should consider to get metadata of table and create specific query based on this informations.</p>

Body:
I have a sql query. Because of too many BO's are involved, it's forming very big query containing more than 1000 columns. So I need some way with which I can find column count before hand and then apply some logic to handle 1000 column error.

May be parsing a query to get column count would help. But not getting how to implement it.

Note: tried below code already, it's giving me result, but i dont want to execute query, that's costly.

PreparedStatement pstmt;
    try {
        pstmt = getConnection().prepareStatement(sql);
        ResultSetMetaData meta = pstmt.getMetaData();
        System.out.println(meta.getColumnCount());

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


问:
How to get data from database which has been publish in Azure through bot application in visual C#
I created a bot application by using bot framework in visual c# and I published it in Azure. My database also in Azure. I give the CompanyId, TenantId, SiteId and Bandid via bot, then should reply as CompanyName and Address from database. It written in TestData.cs class.
I attached my TestAPIController also and I want to get the data from database into bot application. How to code my RootDialog.cs ?</p>

```<code>public class TestAPIController : ApiController
{

    [HttpGet]
    public IHttpActionResult Get(string TenantId, string CompanyId, string SiteId, string BandId)
    {
        TestData TestData = new TestData();
        var TestBusiness = TestData.Select(TenantId, CompanyId, SiteId, BandId);

        return Ok(TestBusiness);
    }

}

public class TestData :DBConnection
{

    public List<TestBusiness> Select(string TenantId, string CompanyId, string SiteId, string BandId)
    {
        List<TestBusiness> list = new List<TestBusiness>();
        this.StoredProcedure = "RESQBOTGetCompanywiseData";
        AddParameter("TenantId", TenantId);
        AddParameter("CompanyId", CompanyId);
        AddParameter("SiteId", SiteId);
        AddParameter("BandId", BandId);
        DataTable dt = this.ExecuteSelect();
        foreach (DataRow dr in dt.Select())
        {
            TestBusiness item = new TestBusiness();
            item.CompanyName = dr["CompanyName"].ToString();
            item.Address = dr["Address"].ToString();
            list.Add(item);
        }
        return list;

    }
}
</code>```

答:
you have to make use of HttpClient that allows you to call webapi and get data below is example code

```<code>using(var client = newHttpClient())
{
    client.BaseAddress = newUri("http://localhost:55587/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add
              (newMediaTypeWithQualityHeaderValue("application/json"));
    //GET Method
    HttpResponseMessage response =
              await client.GetAsync("GetAllRows/1/1/1/1");
    if (response.IsSuccessStatusCode)
    {
    }
}
</code>```

you also need to set route in you web api as below , and pass all parameter when calling this method

```<code>[Route("GetAllRows/{TenantId}/{CompanyId}/{SiteId}/{BandId}")]
 public IHttpActionResult Get(string TenantId, string CompanyId,
                   string SiteId, string BandId)
{
}
</code>```

also configure you webapi for route attribute based routing

```<code>   public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

       }
</code>```

Follow this article : https://dzone.com/articles/web-api-with-httpclient-or-consume-web-api-from-co

Body:
I created a bot application by using bot framework in visual c# and I published it in Azure. My database also in Azure. I give the CompanyId, TenantId, SiteId and Bandid via bot, then should reply as CompanyName and Address from database. It written in TestData.cs class.
I attached my TestAPIController also and I want to get the data from database into bot application. How to code my RootDialog.cs ?

public class TestAPIController : ApiController
{

    [HttpGet]
    public IHttpActionResult Get(string TenantId, string CompanyId, string SiteId, string BandId)
    {
        TestData TestData = new TestData();
        var TestBusiness = TestData.Select(TenantId, CompanyId, SiteId, BandId);

        return Ok(TestBusiness);
    }

}

public class TestData :DBConnection
{

    public List<TestBusiness> Select(string TenantId, string CompanyId, string SiteId, string BandId)
    {
        List<TestBusiness> list = new List<TestBusiness>();
        this.StoredProcedure = "RESQBOTGetCompanywiseData";
        AddParameter("TenantId", TenantId);
        AddParameter("CompanyId", CompanyId);
        AddParameter("SiteId", SiteId);
        AddParameter("BandId", BandId);
        DataTable dt = this.ExecuteSelect();
        foreach (DataRow dr in dt.Select())
        {
            TestBusiness item = new TestBusiness();
            item.CompanyName = dr["CompanyName"].ToString();
            item.Address = dr["Address"].ToString();
            list.Add(item);
        }
        return list;

    }
}

Body:
you have to make use of HttpClient that allows you to call webapi and get data below is example code

using(var client = newHttpClient())
{
    client.BaseAddress = newUri("http://localhost:55587/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add
              (newMediaTypeWithQualityHeaderValue("application/json"));
    //GET Method
    HttpResponseMessage response =
              await client.GetAsync("GetAllRows/1/1/1/1");
    if (response.IsSuccessStatusCode)
    {
    }
}

you also need to set route in you web api as below , and pass all parameter when calling this method

[Route("GetAllRows/{TenantId}/{CompanyId}/{SiteId}/{BandId}")]
 public IHttpActionResult Get(string TenantId, string CompanyId,
                   string SiteId, string BandId)
{
}

also configure you webapi for route attribute based routing

   public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

       }

Follow this article : https://dzone.com/articles/web-api-with-httpclient-or-consume-web-api-from-co


问:
enable.auto.commit value is not configuring to true
As per Kafka documentation, default value of consumer config enable.auto.commit is true. But I am getting as false.

In my Kafka stream application, I try to change this to true as props.put(StreamsConfig.consumerPrefix(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG), true) to commit offset automatically. But I am getting WARN o.a.k.s.StreamsConfig [main] Unexpected user-specified consumer config: enable.auto.commit found. User setting (true) will be ignored and the Streams default setting (false) will be used message in log and reverting back to false.

What would be the reason? Please help me.

答:
Kafka Streams does not allow users to set enable.auto.commit. Streams uses its own mechanism for committing offset instead of relying on the Consumer auto commit feature. This is to ensure commit are only done at certain points when the library is sure no data will be lost.

The only commit setting you can control is commit.interval.ms.


问:
SAPUI5: How to set service url parameters in runtime?
I have an OData service which is made in manifest.json

In some services I need to pass some url parameters like ?$expand=XYZ

SO the question is how can I set serviceUrlParams in the run time and not inside of the manifest.json while the OData model has been created by component class.

答:
There seems to be a misunderstanding that parameters such as $expand belong to the serviceUrlParams. No, we need to distinguish between

Metadata URL parameters: metadataUrlParams in model definition. Those parameters will be only attached to the $metadata request which is at the model instantiation.

Service URL parameters: serviceUrlParams in model definition. Those parameters will be attached to all requests.

Data URL parameters:

parameters in binding definition (usually in the view) as mentioned here, or

urlParameters in model APIs such as read as mentioned here.

For $expand, data request parameter is what you have to define in each binding definition whereever it's needed. Then, the respective data will be loaded on-demand.

API Reference: ui5.sap.com/#/api/sap.ui.model.odata.v2.ODataModel

Documentation: ui5.sap.com/#/topic/6c47b2b39db9404582994070ec3d57a2


问:
why can I run 2 or more http servers (with different ports) in one process
It only has 1 node process in my Windows7 task manager. Surprise. How nodejs achieve this and What the difference if I split servers in difference processes? Thanks.</p>

```<code>http.createServer(function(req, res) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello World');
}).listen(5000, '127.0.0.1');

http.createServer(function(req, res) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello World2');
}).listen(5001, '127.0.0.1');

http.createServer(function(req, res) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello World3');
}).listen(5002, '127.0.0.1');
</code>```

答:
A single process can open as many sockets as the OS allows it to. As long as it does not try to open a socket on a port which is already taken by another socket.

One difference would be that you have one thread running for each server instead of one thread for all three servers, since Node only runs one thread per process. This can be relevant to you if you have issues with performance.

Body:
It only has 1 node process in my Windows7 task manager. Surprise. How nodejs achieve this and What the difference if I split servers in difference processes? Thanks.

http.createServer(function(req, res) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello World');
}).listen(5000, '127.0.0.1');

http.createServer(function(req, res) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello World2');
}).listen(5001, '127.0.0.1');

http.createServer(function(req, res) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello World3');
}).listen(5002, '127.0.0.1');


问:
How to start a new list, continuing the numbering from the previous list?
I'm trying to do something that used to be really easy before the start attribute on ol tags was deprecated. I'd just like to have a pair of ordered lists in my page, but start the numbering of the second list where the first one finished. Something like:

```<code>1. do stuff
2. do stuff

Here's a paragraph

3. do stuff
</code>```

I've seen that the counter-reset and counter-increment CSS properties should be able to achieve this, but I can't get it working. Here's my code so far:

```<code><html>
<head>
  <style type="text/css">
    ol li { counter-increment: mycounter; }
    ol.start { counter-reset: mycounter; }
    ol.continue { counter-reset: mycounter 2; }
  </style>
</head>

<body>
  <ol class="start">
    <li>You can't touch this</li>
    <li>You can't touch this</li>
  </ol>
  <p>STOP! Hammer time.</p>
  <ol class="continue">
    <li>You can't touch this</li>
  </ol>
</body>
</html>
</code>```

To be honest, even if that worked, it wouldn't be ideal. I don't want to have to specify the number reached by the first list in my ol.continue selector.

What am I doing wrong? What's the minimal HTML/CSS combination required to achieve the desired effect?

答:
A much easier solution to the OP's problem is the following:

```<code><ol start="X">
</code>```

Where X is the value of the list you want to continue, so in his sample:

You can't touch this

You can't touch this

STOP! Hammer time.

You can't touch this

```

Body:
I'm trying to do something that used to be really easy before the start attribute on ol tags was deprecated. I'd just like to have a pair of ordered lists in my page, but start the numbering of the second list where the first one finished. Something like:

1. do stuff
2. do stuff

Here's a paragraph

3. do stuff

I've seen that the counter-reset and counter-increment CSS properties should be able to achieve this, but I can't get it working. Here's my code so far:

You can't touch this

You can't touch this

STOP! Hammer time.

You can't touch this

To be honest, even if that worked, it wouldn't be ideal. I don't want to have to specify the number reached by the first list in my ol.continue selector.

What am I doing wrong? What's the minimal HTML/CSS combination required to achieve the desired effect?

Body:
A much easier solution to the OP's problem is the following:

<ol start="X">

Where X is the value of the list you want to continue, so in his sample:

<ol>
  <li>You can't touch this</li>
  <li>You can't touch this</li>
</ol>
<p>STOP! Hammer time.</p>
<ol start="3">
  <li>You can't touch this</li>
</ol>


问:
why there is a difference in output in CSS : li a VS li,a
why there is a difference in output in CSS:

```<code>li a
</code>```

from https://www.w3schools.com/code/tryit.asp?filename=FM0HPU6L0R35

versus

```<code>li,a
</code>```

from https://www.w3schools.com/code/tryit.asp?filename=FM0HQKZG79HR

答:
Well, it's simply because in the first case, the style is applied to all "a" tags found within a li element.

```<code>li a {
       display: block;
    color: white;
    text-align: center;
    padding: 16px;
    text-decoration: none;
}
</code>```

In the second case, the style is applied to all "li" elements as well as to all "a" elements:

```<code>li,a {
       display: block;
    color: white;
    text-align: center;
    padding: 16px;
    text-decoration: none;
}
</code>```

To put it simply, in the second case you get double the padding: 16px from li + 16px from a.

Here are a couple of links on css selectors that you might find useful:

https://www.sitepoint.com/css-selectors/
  https://www.w3schools.com/css/css_attribute_selectors.asp

Hope this helps!

Body:
why there is a difference in output in CSS:

li a

from https://www.w3schools.com/code/tryit.asp?filename=FM0HPU6L0R35

versus

li,a

from https://www.w3schools.com/code/tryit.asp?filename=FM0HQKZG79HR

Body:
Well, it's simply because in the first case, the style is applied to all "a" tags found within a li element.

li a {
       display: block;
    color: white;
    text-align: center;
    padding: 16px;
    text-decoration: none;
}

In the second case, the style is applied to all "li" elements as well as to all "a" elements:

li,a {
       display: block;
    color: white;
    text-align: center;
    padding: 16px;
    text-decoration: none;
}

To put it simply, in the second case you get double the padding: 16px from li + 16px from a.

Here are a couple of links on css selectors that you might find useful:

https://www.sitepoint.com/css-selectors/
  https://www.w3schools.com/css/css_attribute_selectors.asp

Hope this helps!


问:
How to eliminate values from list2 (which are common with another list1) in python
Input:

```<code>list1 = ['name', 'age', 'gender', 'location']
list2 = ['name', 'age']
list3
</code>```

Output:

```<code>list3 = ['gender', 'location']
</code>```

How do I subtract common elements from list?

答:
A simple method for beginers:

```<code>list1 = some_list
list2 = some_other_list
list3 = []
if len(list1) >= len(list2):
    longer_list = list1
    shorter_list = list2
else:
    longer_list = list2
    shorterlist = list1

for element in longer_list:
    if element not in shorter_list:
        list3.append(element)
</code>```

This way, you account capture the entire difference. If the list in the outer loop is shorter than the list in the inner loop, you will miss some elements.

As you advance, you will pick up other methods like set difference: list(set(list1) - set(list2)), list comprehensions: [i for i in list1 if i not in list2], filters with lambdas, etc.

Start with the basics, understand what's going on, befor learning fancy methods

Body:
Input:

list1 = ['name', 'age', 'gender', 'location']
list2 = ['name', 'age']
list3

Output:

list3 = ['gender', 'location']

How do I subtract common elements from list?

Body:
A simple method for beginers:

list1 = some_list
list2 = some_other_list
list3 = []
if len(list1) >= len(list2):
    longer_list = list1
    shorter_list = list2
else:
    longer_list = list2
    shorterlist = list1

for element in longer_list:
    if element not in shorter_list:
        list3.append(element)

This way, you account capture the entire difference. If the list in the outer loop is shorter than the list in the inner loop, you will miss some elements.

As you advance, you will pick up other methods like set difference: list(set(list1) - set(list2)), list comprehensions: [i for i in list1 if i not in list2], filters with lambdas, etc.

Start with the basics, understand what's going on, befor learning fancy methods


问:
Hardware differences for ARKit?
Are there any differences in what's available for ARKit depending on hardware? Is iPhone 8 a more potent AR platform than older models in terms of pure functionality?</p>

答: Yes, ARKit runs on the Apple A9, A10, and A11 processors. In device only it will work on an iPhone 6S or iPhone SE, or newer.</p>

Title: Hardware differences for ARKit?


问:
JS: Sum of span values in For loop
I have the following values within span tags:

```<code><div id="aantallen">
 <span>3</span>
 <span>2</span>
</div>
</code>```

In JS I want to get the sum of these values. So I made the following For Loop:

```<code>var div = document.getElementById("aantallen");
var spans = div.getElementsByTagName("span");
for(i=0;i<spans.length;i++)
{
    var totaalPersonen = totaalPersonen + i;
    alert(totaalPersonen);
}
</code>```

However, the 3 and 2 are text, so I get Nan in the alerts. My question: how can in convert the 3 and 2 into strings so that I can make a sum of these values?

I tried with String(i) but couldn't get it to work.

答:
To convert string to Int in Javascript, Use:

parseInt(totaalPersonen);

Title: JS: Sum of span values in For loop

Body:
I have the following values within span tags:

 3
 2

In JS I want to get the sum of these values. So I made the following For Loop:

var div = document.getElementById("aantallen");
var spans = div.getElementsByTagName("span");
for(i=0;i<spans.length;i++)
{
    var totaalPersonen = totaalPersonen + i;
    alert(totaalPersonen);
}

However, the 3 and 2 are text, so I get Nan in the alerts. My question: how can in convert the 3 and 2 into strings so that I can make a sum of these values?

I tried with String(i) but couldn't get it to work.


问:
How do I shuffle an array in Swift?
.shuffle() and .shuffled() are part of Swift

Original historic question:

How do I randomize or shuffle the elements within an array in Swift? For example, if my array consists of 52 playing cards, I want to shuffle the array in order to shuffle the deck.

答:
works!!. organisms is the array to shuffle.</p>

```<code>extension Array
{
    /** Randomizes the order of an array's elements. */
    mutating func shuffle()
    {
        for _ in 0..<10
        {
            sort { (_,_) in arc4random() < arc4random() }
        }
    }
}

var organisms = [
    "ant",  "bacteria", "cougar",
    "dog",  "elephant", "firefly",
    "goat", "hedgehog", "iguana"]

print("Original: \(organisms)")

organisms.shuffle()

print("Shuffled: \(organisms)")
</code>```

Title: How do I shuffle an array in Swift?

Body:
works!!. organisms is the array to shuffle.

extension Array
{
    /** Randomizes the order of an array's elements. */
    mutating func shuffle()
    {
        for _ in 0..<10
        {
            sort { (_,_) in arc4random() < arc4random() }
        }
    }
}

var organisms = [
    "ant",  "bacteria", "cougar",
    "dog",  "elephant", "firefly",
    "goat", "hedgehog", "iguana"]

print("Original: \(organisms)")

organisms.shuffle()

print("Shuffled: \(organisms)")


问:
Angular5 ParamMap and HttpClient
How can I get ParamMap to work with the HttpClient via a service in Angular5?

Component

```<code>// importing the service, ActivatedRoute, ParamMap, switchMap, etc

public value;
constructor(private myService: MyService, private activatedRouter: ActivatedRoute) { }

ngOnInit() {
    this.value = this.activatedRouter.paramMap
    .switchMap((params: ParamMap) => this.myService.getOne(params.get('id')));
  }
</code>```

Service

```<code>import { HttpClient } from '@angular/common/http';
// ...
constructor(private httpClient: HttpClient) { }
getOne(id) {
    return this.httpClient.get(`http://my.api/${id}`);
  }
</code>```

At the moment if I do console.log(this.value) in my component I get a AnonymousSubject.

The question is, how can I use ParamMap and get the value from the HttpClient? I know I could use a router snapshot - which I have done and it works but I'd like to get this example working as well.

答:
Based on CozyAzure's comment the final solution is</p>

```<code>this.activatedRouter.paramMap
    .switchMap((params: ParamMap) =>
      this.myService.getOne(params.get('id')))
      .subscribe(data => value = data);
  }
</code>```

Title: Angular5 ParamMap and HttpClient

Body:
How can I get ParamMap to work with the HttpClient via a service in Angular5?

Component

// importing the service, ActivatedRoute, ParamMap, switchMap, etc

public value;
constructor(private myService: MyService, private activatedRouter: ActivatedRoute) { }

ngOnInit() {
    this.value = this.activatedRouter.paramMap
    .switchMap((params: ParamMap) => this.myService.getOne(params.get('id')));
  }

Service

import { HttpClient } from '@angular/common/http';
// ...
constructor(private httpClient: HttpClient) { }
getOne(id) {
    return this.httpClient.get(`http://my.api/${id}`);
  }

At the moment if I do console.log(this.value) in my component I get a AnonymousSubject.

The question is, how can I use ParamMap and get the value from the HttpClient? I know I could use a router snapshot - which I have done and it works but I'd like to get this example working as well.

Body:
Based on CozyAzure's comment the final solution is

this.activatedRouter.paramMap
    .switchMap((params: ParamMap) =>
      this.myService.getOne(params.get('id')))
      .subscribe(data => value = data);
  }


问:
rxjs - Is it necessary to kill cold stream?

If subscribe isn't exist, the stream does not work?

Is it necessary to kill subscribe in cold stream? For example: operator .take(1) or .first() or common .unsubscribe, so other.

or may is it necessary to kill himself stream? .complete()
Or does not it affect performance in the future?

A simple example: Create 100 cold stream

```<code>    function test() {
       let obs = Rx.Observable.create(observer => observer.next(Date.now()));
       obs.subscribe(v => console.log("1st subscriber: " + v));
       obs.subscribe(v => console.log("2nd subscriber: " + v));
     }
     for(var i = 0; i < 100; i++){
       test();
     }
</code>```

答: Cold streams are just functions not being executed. So creating them will alloc memory but not incur any further performance issues.</p>

Body:
If subscribe isn't exist, the stream does not work?

Is it necessary to kill subscribe in cold stream? For example: operator .take(1) or .first() or common .unsubscribe, so other.

or may is it necessary to kill himself stream? .complete()
Or does not it affect performance in the future?

A simple example: Create 100 cold stream

    function test() {
       let obs = Rx.Observable.create(observer => observer.next(Date.now()));
       obs.subscribe(v => console.log("1st subscriber: " + v));
       obs.subscribe(v => console.log("2nd subscriber: " + v));
     }
     for(var i = 0; i < 100; i++){
       test();
     }


问:
SQL: How to calculate correctly with any DATE_TIME and CURRENT_TIMESTAMP?
I have created a table where I listed some spare parts of my company.

The Table looks like this:

```<code>ID | Name | install_date | last_changed | order_nr. | WearStatus
----------
1  | "ABC" | **2017-11-08 10:34:40** | NULL | 123456 | **50**<br>
2  | "DEF" | **2017-11-08 10:34:40** | NULL | 654321 | **10**<br>
</code>```

.

.

I want to calculate the Future Date, where the spare Parts should be changed. For example:

I installed a Part on the 01. December and exactly 10 Days later on the 11. December this part has a Wear of 50%, then I know: It has 10 more Days left.

My calculation is according to the rule of three formula: Time = (100 * delta t) / Wear

I use the following SQL command:

```<code>SELECT ( (100*(CURRENT_TIMESTAMP - First_Usage) / Wear) + First_Usage) As 'Change_Date' FROM spare_parts
</code>```

And get the following Results:

If you see there are some crazy DATE_TIMES like 2017-19-41-43-19-31.

So my Question is now: How to format this "Numbers" to a useful DATE_TIME Format like YYYY-MM-DD hh:mm:ss ?

kind regards Toby

答:
Try these 2 approaches:

```<code>SELECT DATE(DATE_ADD(First_Usage, INTERVAL (100*(DATEDIFF(NOW(),First_Usage) / Wear)) day)) As 'Change_Date' FROM spare_parts
</code>```

or

```<code>SELECT FROM_UNIXTIME( (100*(CURRENT_TIMESTAMP - UNIX_TIMESTAMP(First_Usage)) / Wear) + UNIX_TIMESTAMP(First_Usage))) As 'Change_Date' FROM spare_parts
</code>```

Body:
I have created a table where I listed some spare parts of my company.

The Table looks like this:

ID | Name | install_date | last_changed | order_nr. | WearStatus
----------
1  | "ABC" | **2017-11-08 10:34:40** | NULL | 123456 | **50**

2  | "DEF" | **2017-11-08 10:34:40** | NULL | 654321 | **10**

.

.

I want to calculate the Future Date, where the spare Parts should be changed. For example:

I installed a Part on the 01. December and exactly 10 Days later on the 11. December this part has a Wear of 50%, then I know: It has 10 more Days left.

My calculation is according to the rule of three formula: Time = (100 * delta t) / Wear

I use the following SQL command:

SELECT ( (100*(CURRENT_TIMESTAMP - First_Usage) / Wear) + First_Usage) As 'Change_Date' FROM spare_parts

And get the following Results:

If you see there are some crazy DATE_TIMES like 2017-19-41-43-19-31.

So my Question is now: How to format this "Numbers" to a useful DATE_TIME Format like YYYY-MM-DD hh:mm:ss ?

kind regards Toby

Body:
Try these 2 approaches:

SELECT DATE(DATE_ADD(First_Usage, INTERVAL (100*(DATEDIFF(NOW(),First_Usage) / Wear)) day)) As 'Change_Date' FROM spare_parts

or

SELECT FROM_UNIXTIME( (100*(CURRENT_TIMESTAMP - UNIX_TIMESTAMP(First_Usage)) / Wear) + UNIX_TIMESTAMP(First_Usage))) As 'Change_Date' FROM spare_parts


问:
Trigger a "ENTER" in programmatically
It is possible to program a "Enter" after a value is added to a input text box?

If yes, I need help on my code below. It does't trigger the "ENTER" keypress.

My code as below:

```<code>$('#clo_cart').click( function () {

/*Save ENTER in variable*/
var eneterKey = jQuery.Event("keydown");
eneterKey.which = 13;
eneterKey.keycode = 13;

$("#scan_char").focus().val('CLOSECTN').trigger(eneterKey);
}//end of button click
</code>```

Pls Help

答:
You can use this code,</p>

```<code>$('#clo_cart').click( function () {

var e = $.Event( "keypress", { which: 13 } );
$("#scan_char").focus().val('CLOSECTN').trigger(e);

}//end of bu
</code>```

Title: Trigger a "ENTER" in programmatically

Body:
It is possible to program a "Enter" after a value is added to a input text box?

If yes, I need help on my code below. It does't trigger the "ENTER" keypress.

My code as below:

$('#clo_cart').click( function () {

/*Save ENTER in variable*/
var eneterKey = jQuery.Event("keydown");
eneterKey.which = 13;
eneterKey.keycode = 13;

$("#scan_char").focus().val('CLOSECTN').trigger(eneterKey);
}//end of button click

Pls Help

Body:
You can use this code,

$('#clo_cart').click( function () {

var e = $.Event( "keypress", { which: 13 } );
$("#scan_char").focus().val('CLOSECTN').trigger(e);

}//end of bu


问:
Using R shiny with an external javascript file for event handling
I'm trying to create a R Shiny app in which an external javascript is included. As a newbie, this javascript should for now only detect the press of enter and simulate the click of that button.
The Shiny interface looks like this where text is being inputted and when the Send-button is clicked that same text outputted:

```<code>library(shiny)

# Define UI ----
ui <- fluidPage(

  includeScript("sendOnEnter.js"),

  titlePanel("GUI"),

  sidebarLayout(
    sidebarPanel(
      textInput("text",h3("Cmd"),value="Enter question"),
      actionButton("send", "Send"),
      width = 3
    ),

    mainPanel(
      textOutput("query")
    )
  )
)

# Define server logic ----
server <- function(input, output) {

  ntext <- eventReactive(input$send, {
            input$text
              })

  output$query <- renderText({
    ntext()

    })
}

# Run the app ----
shinyApp(ui = ui, server = server)
</code>```

The Javascript file listens for the pressing of the enter button and simulates this as the clicking of the Send button;

```<code>jQuery(document).ready(function(){
  jQuery('#entry').keypress(function(evt){

    if (evt.keyCode == 13){
      // Enter, simulate clicking send
      jQuery('#send').click();
    }
  });
})
</code>```

Thanks in advance

答: Nevermind, there was a typo in script. jQuery('#entry').keypress(...)should be jQuery('#text').keypress(..)

Body:
I'm trying to create a R Shiny app in which an external javascript is included. As a newbie, this javascript should for now only detect the press of enter and simulate the click of that button.
The Shiny interface looks like this where text is being inputted and when the Send-button is clicked that same text outputted:

library(shiny)

# Define UI ----
ui <- fluidPage(

  includeScript("sendOnEnter.js"),

  titlePanel("GUI"),

  sidebarLayout(
    sidebarPanel(
      textInput("text",h3("Cmd"),value="Enter question"),
      actionButton("send", "Send"),
      width = 3
    ),

    mainPanel(
      textOutput("query")
    )
  )
)

# Define server logic ----
server <- function(input, output) {

  ntext <- eventReactive(input$send, {
            input$text
              })

  output$query <- renderText({
    ntext()

    })
}

# Run the app ----
shinyApp(ui = ui, server = server)

The Javascript file listens for the pressing of the enter button and simulates this as the clicking of the Send button;

jQuery(document).ready(function(){
  jQuery('#entry').keypress(function(evt){

    if (evt.keyCode == 13){
      // Enter, simulate clicking send
      jQuery('#send').click();
    }
  });
})

Thanks in advance


问:
Displaytag alternatives
I'm building an application using Struts 2 + Spring 3 + Hibernate 3. I was wondering if any of you knows of any alternative to the "displaytag" library to draw and manage tables.

Not that I dislike it so much, but I read this comment and made me wonder about other options. And I see it has not been updated in a while and I was wondering if there is some reason for that (like a better/more popular alternative available).

答:
Instead of loading all the data into memory and have DisplayTag to perform pagination through javascript magic, you can configure DisplayTag's pagination to load the right chunk of data only when it is requested. This way, you are not going to have performance loss since you are not loading all the data into memory.

I can't remember the code on top of my head (I'm away from my work machine), but here's an example which may be useful to you: http://i-work-i-blog.blogspot.com/2007/06/display-tag-and-external-pagination.html

ContentLicense: CC BY-SA 2.5

Title: Displaytag alternatives


答:
You are reintializing var totaalPersonen = totaalPersonen + i; in every loop.
So you need to initialize totaalPersonen outside the loop like this var totaalPersonen = 0; and inside the loop just count it up like totaalPersonen = totaalPersonen + 1; or just totaalPerseonen++;

Title: JS: Sum of span values in For loop


问:
Importing from MySQL dump to Clickhouse
I want to import from MySQL dump to Clickhouse. I've tried going through the official docs but cannot find anything. I've tried importing using CSV following Stack Overflow answer. Any help appreciated. I've an Ubuntu 16.04 LTS.</p>

答:
You can export data from MySQL into TSV file using MySQL command line:

```<code>mysql -Bse "select * from TABLE_NAME" > table.tsv
</code>```

And then import data to ClickHouse:

```<code>cat table.tsv | clickhouse-client --query="INSERT INTO TABLE_NAME FORMAT TabSeparated"
</code>```

Title: Importing from MySQL dump to Clickhouse

Body:
You can export data from MySQL into TSV file using MySQL command line:

mysql -Bse "select * from TABLE_NAME" > table.tsv

And then import data to ClickHouse:

cat table.tsv | clickhouse-client --query="INSERT INTO TABLE_NAME FORMAT TabSeparated"


问:
Multiplayer Spawning in UE4 blueprint
i want to create a local multiplayer game for 2-4 players.
It seems like i have made a mistake or it is a bug. I tried different tutorials but i dont get my mistake. I posted the same question in the answer hub of unreal, but i didn´t get a response. Here ist my gamemode and the spawning function:
GamemodeSpawning

My Pawn is called Physics Ball BP. The default spawn in the gamemode is disabled. The default value of the variable "Max Player Amount" is 2. "Player Start Array" contains the PlayerStarts. The PlayerStarts have the tag "0" and "1". This is my viewport before the start:
Viewport

This is my viewport if i press Play: ViewportPlaying

I think i just missed something basic, but i cant figure out what i´ve done wrong. I hope you can help me.

best regards chris

答:
Not sure if you did it on purpose but you uploaded the same screenshot of your viewport twice. Maybe edit your post, and upload the right ones.

But maybe the problem your having is because you forgot to plug your Index variable into the Player Int variable in the Spawn Actor node?

Title: Multiplayer Spawning in UE4 blueprint


问:
Trying to use Javascript to populate a hidden input
I have this code:

```<code> while($row = mysql_fetch_array($res)) {
        $name = $row['advertiser'];
        $id = $row['id'];
        if($row['id'] % 4 == 1 || $row['id'] == 1)
        {
            echo "<tr>";
        }
        if($row['availability'] == 0)
        {
            $td = "<td id='green'>";
        }
        if($row['availability'] == 1)
        {
            $td = "<td id='grey'>";
        }
        if($row['price'] == 0)
        {
            mysql_query("UPDATE booklet SET availability = 0 WHERE id = '$id'");
        }
        echo $td . $row['id'] . "<br/><p style='font-size: 6pt;'>" . $name[0] . "<p><img src=" . $row['image'] . "></td>";

        if($row['id'] % 4 == 0)
        {
            echo "</tr>";
        }
}
</code>```

It creates a table. What I want to do is this: if you click on a td, I want to pass the value of that td, for example - the number one (1), if you clicked on the first td - I want to pass this value over to a hidden input so I may later use it elsewhere.

The table looks fine. I know what to do when I have the value in a hidden input. I just need to be able to have the table, when I click on a td, to pass the value over. Or to do anything. onClick doesn't work. Even the absolute simplest isolated JQuery statements don't even come close to parsing. The most complex Javascript that actually has worked on this page is a document.write(). Everything else stumps any known browser.

So, using absolutely any methods, is it a possibility, within the realm of current technology, to have code that does what I want?

Again, I need to have a table cell, when clicked on, pass a variable to a hidden input. I've tried everything.

答:
You'll need to add the click event with JQuery and then use Jquery to set the value... Something like this should work.</p>

```<code>$(function() {
    $("table#mytable td").mouseover(function() {
    //The onmouseover code
    }).click(function() {
        //The onclick code
        $("#hiddenInputID").val(text);
    });
});
</code>```

Body:
I have this code:

 while($row = mysql_fetch_array($res)) {
        $name = $row['advertiser'];
        $id = $row['id'];
        if($row['id'] % 4 == 1 || $row['id'] == 1)
        {
            echo "
";
        }
        if($row['availability'] == 0)
        {
            $td = "";
        }
        if($row['availability'] == 1)
        {
            $td = "";
        }
        if($row['price'] == 0)
        {
            mysql_query("UPDATE booklet SET availability = 0 WHERE id = '$id'");
        }
        echo $td . $row['id'] . "

" . $name[0] . "
	";

        if($row['id'] % 4 == 0)
        {
            echo "
";
        }
}

It creates a table. What I want to do is this: if you click on a td, I want to pass the value of that td, for example - the number one (1), if you clicked on the first td - I want to pass this value over to a hidden input so I may later use it elsewhere.

The table looks fine. I know what to do when I have the value in a hidden input. I just need to be able to have the table, when I click on a td, to pass the value over. Or to do anything. onClick doesn't work. Even the absolute simplest isolated JQuery statements don't even come close to parsing. The most complex Javascript that actually has worked on this page is a document.write(). Everything else stumps any known browser.

So, using absolutely any methods, is it a possibility, within the realm of current technology, to have code that does what I want?

Again, I need to have a table cell, when clicked on, pass a variable to a hidden input. I've tried everything.

Body:
You'll need to add the click event with JQuery and then use Jquery to set the value... Something like this should work.

$(function() {
    $("table#mytable td").mouseover(function() {
    //The onmouseover code
    }).click(function() {
        //The onclick code
        $("#hiddenInputID").val(text);
    });
});


问:
Distribute iOS app for specific region/territory
I am about to release my App, just waiting for my Apple Developer to come in.

Can I decide the countries where my app will be available to download from? Or will I only be able to choose one single country/whole Europe/World?

Say I wanted to make my app available in Europe but not in Portugal - Is that possible?.......

答:
Yes, of course you can enable/disable (make your app available for) specific regions (countries).

As you want to disable you app for Portugal...

Portugal is listed in territory list in iTune account for app. Just uncheck (remove tickmark) for that country.

Look at this snapshot:

Here is more detailed answer (how you can see territories/list) -
 Application approved - pending developer release - Currently unavailable in your Country


问:
Is Celery needed for asynchronous file writing functionality in Django?
I'm planning to add some functionality to my Django app that will write a row of data to a csv file when certain views are called:

```<code>    session_dict = collectUserDataFromRequest(request) #....collect parameters from  request

     if os.path.isfile(filename):

        with open(filename, 'a') as csv_file:
            a = csv.DictWriter(csv_file,session_dict.keys())
            a.writerow(session_dict)
            csv_file.close()

    else:

        with open(filename, 'w') as csv_file:
            w = csv.DictWriter(csv_file,session_dict.keys())
            w.writeheader()
            w.writerow(session_dict)
            csv_file.close()

     # then proceed to render the html
</code>```

A problem I am facing is dealing with potential race conditions when multiple users are accessing my app at the same time. While the data can be added to the csv file in any order, I don't want some user's to wait longer for a view to load while waiting for a lock to be released on the csv file. As such, I think an Asynchronous queue of string data to be written to the file that can run in the background sounds like a good workaround.

I have been told that Celery is a good framework for adding asynchronous processes to my Django app. But looking through several tutorials, I am seeing that additional frameworks such as Redis are usually required. I worry that this may be overkill for what I aim to accomplish. Will I get away with using a standard multiprocessing approach, such as explained here or are there other drawbacks to using multi-threading in a Django production environment.

答:
First point: you should not have concurrent requests trying to write to the same file. Depending on your use case, you should either store your data in a proper relational database which knows how to handle concurrent access or have per-user files.

Second point: no, you don't necessarily needs celery for async operations, there are quite a few other solutions.

Body:
I'm planning to add some functionality to my Django app that will write a row of data to a csv file when certain views are called:

    session_dict = collectUserDataFromRequest(request) #....collect parameters from  request

     if os.path.isfile(filename):

        with open(filename, 'a') as csv_file:
            a = csv.DictWriter(csv_file,session_dict.keys())
            a.writerow(session_dict)
            csv_file.close()

    else:

        with open(filename, 'w') as csv_file:
            w = csv.DictWriter(csv_file,session_dict.keys())
            w.writeheader()
            w.writerow(session_dict)
            csv_file.close()

     # then proceed to render the html

A problem I am facing is dealing with potential race conditions when multiple users are accessing my app at the same time. While the data can be added to the csv file in any order, I don't want some user's to wait longer for a view to load while waiting for a lock to be released on the csv file. As such, I think an Asynchronous queue of string data to be written to the file that can run in the background sounds like a good workaround.

I have been told that Celery is a good framework for adding asynchronous processes to my Django app. But looking through several tutorials, I am seeing that additional frameworks such as Redis are usually required. I worry that this may be overkill for what I aim to accomplish. Will I get away with using a standard multiprocessing approach, such as explained here or are there other drawbacks to using multi-threading in a Django production environment.


问:
What does "e_lfanew" mean in the DOS header for the PE format?
In the IMAGE_DOS_HEADER for the PE (Windows executable) format there is a field known as e_lfanew, it serves a very important role in that it points to the actual PE header data.

My question is, what does "e_lfanew" actually stand for? what does it mean? It's so cryptic.

EDIT: I'm NOT asking what it does, i know what it does, i want to know what the letters in e_lfanew actually stand for, why was it given that name?

答:
My interpretation would be that it's the logical file address for the New Executable header.

Mainly based on the comment in this P/Invoke C# definition of the IMAGE_DOS_HEADER struct:

```<code>public Int32 e_lfanew;      // File address of new exe header
</code>```

And a comment by @Hans Passant:

The e_ prefix helped deal with old K&R compilers that did not yet keep structure members in its own symbol table.

And a later comment here by @Simon Kissane:

Inside the IMAGE_DOS_HEADER there are two fields starting with e_lfa:

WORD   e_lfarlc; // File address of relocation table

LONG   e_lfanew; // File address of new exe header

The "lfa" would appear to mean "logical file address", meaning the offset relative to the start of the executable file.

Body:
My interpretation would be that it's the logical file address for the New Executable header.

Mainly based on the comment in this P/Invoke C# definition of the IMAGE_DOS_HEADER struct:

public Int32 e_lfanew;      // File address of new exe header

And a comment by @Hans Passant:

The e_ prefix helped deal with old K&R compilers that did not yet keep structure members in its own symbol table.

And a later comment here by @Simon Kissane:

Inside the IMAGE_DOS_HEADER there are two fields starting with e_lfa:

WORD   e_lfarlc; // File address of relocation table

LONG   e_lfanew; // File address of new exe header

The "lfa" would appear to mean "logical file address", meaning the offset relative to the start of the executable file.


问:
Using Alamofire and Codable for put request
I have a simple put request and I am using Alamofire's Parameters type to send data to the server. I would like to use codable. How do I either convert my codable struct to parameters or reconfigure the Alamofire request to take JSON objects as the parameter? What is the best and most efficient way to send post and put requests using Alamofire?

Here is what I am doing right now with Alamofire.

```<code>func addProduct(product:MainProduct, completionHandler:@escaping ((JSON?, Error?)->Void)) {

    let url = "INSERT_URL"

    let headers: HTTPHeaders = [
        "Content-Type": "application/json"
    ]

    var parameters:Parameters = [:]
    parameters["orderId"] = product.orderId
    parameters["orderSize"] = product.orderSize
    parameters["theOrderStatus"] = product.orderStatus
    let purchDate = Int((product.purchaseDate.timeIntervalSince1970)*1000)
    parameters["purchaseDate"] = purchDate
    parameters["archived"] = false

    Alamofire.request(url, method:.put, parameters: parameters, encoding: JSONEncoding.default, headers:headers).responseJSON {response in
        switch response.result {
        case .success(let value):
            print ("finish")
            let swiftyJson = JSON(value)
            completionHandler(swiftyJson, nil)
        case .failure(let error):
            completionHandler(nil, error)
        }
    }
}
</code>```

This is our struct.

```<code>struct MainProduct:Codable{

    var purchaseDate:Date
    var orderId:String
    var orderSize:Double
    var orderStatus:OrderStatus?

    var archived:Bool

    private enum CodingKeys: String, CodingKey {
        case purchaseDate
        case orderId
        case orderSize
        case orderStatus = "theOrderStatus"
        case archived
    }
}
</code>```

答:
You can make a new URLRequest and set httpBody to your encoded jsonData. Try this code...

```<code>func addProduct(product: MainProduct, completionHandler: @escaping ((JSON?, Error?)->Void)) {

    let encoder = JSONEncoder()
    let jsonData = try! encoder.encode(product)

    let url = "INSERT_URL"

    var request = URLRequest(url: url)
    request.httpMethod = HTTPMethod.put.rawValue
    request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
    request.httpBody = jsonData

    Alamofire.request(request).responseJSON { response in
        switch response.result {
        case .success(let value):
            print ("finish")
            let swiftyJson = JSON(value)
            completionHandler(swiftyJson, nil)
        case .failure(let error):
            completionHandler(nil, error)
        }
    }
}
</code>```

Body:
I have a simple put request and I am using Alamofire's Parameters type to send data to the server. I would like to use codable. How do I either convert my codable struct to parameters or reconfigure the Alamofire request to take JSON objects as the parameter? What is the best and most efficient way to send post and put requests using Alamofire?

Here is what I am doing right now with Alamofire.

func addProduct(product:MainProduct, completionHandler:@escaping ((JSON?, Error?)->Void)) {

    let url = "INSERT_URL"

    let headers: HTTPHeaders = [
        "Content-Type": "application/json"
    ]

    var parameters:Parameters = [:]
    parameters["orderId"] = product.orderId
    parameters["orderSize"] = product.orderSize
    parameters["theOrderStatus"] = product.orderStatus
    let purchDate = Int((product.purchaseDate.timeIntervalSince1970)*1000)
    parameters["purchaseDate"] = purchDate
    parameters["archived"] = false

    Alamofire.request(url, method:.put, parameters: parameters, encoding: JSONEncoding.default, headers:headers).responseJSON {response in
        switch response.result {
        case .success(let value):
            print ("finish")
            let swiftyJson = JSON(value)
            completionHandler(swiftyJson, nil)
        case .failure(let error):
            completionHandler(nil, error)
        }
    }
}

This is our struct.

struct MainProduct:Codable{

    var purchaseDate:Date
    var orderId:String
    var orderSize:Double
    var orderStatus:OrderStatus?

    var archived:Bool

    private enum CodingKeys: String, CodingKey {
        case purchaseDate
        case orderId
        case orderSize
        case orderStatus = "theOrderStatus"
        case archived
    }
}

Body:
You can make a new URLRequest and set httpBody to your encoded jsonData. Try this code...

func addProduct(product: MainProduct, completionHandler: @escaping ((JSON?, Error?)->Void)) {

    let encoder = JSONEncoder()
    let jsonData = try! encoder.encode(product)

    let url = "INSERT_URL"

    var request = URLRequest(url: url)
    request.httpMethod = HTTPMethod.put.rawValue
    request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
    request.httpBody = jsonData

    Alamofire.request(request).responseJSON { response in
        switch response.result {
        case .success(let value):
            print ("finish")
            let swiftyJson = JSON(value)
            completionHandler(swiftyJson, nil)
        case .failure(let error):
            completionHandler(nil, error)
        }
    }
}


问:
why can I run 2 or more http servers (with different ports) in one process
It only has 1 node process in my Windows7 task manager. Surprise. How nodejs achieve this and What the difference if I split servers in difference processes? Thanks.</p>

```<code>http.createServer(function(req, res) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello World');
}).listen(5000, '127.0.0.1');

http.createServer(function(req, res) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello World2');
}).listen(5001, '127.0.0.1');

http.createServer(function(req, res) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello World3');
}).listen(5002, '127.0.0.1');
</code>```

答:
You have a multitasking system, nodejs can have one or more threads per port.

The advantage of having a single nodejs process handle multiple ports is that you save a tiny bit of RAM.

The disadvantage is that when one server crashes, both "servers" might be affected.

Body:
It only has 1 node process in my Windows7 task manager. Surprise. How nodejs achieve this and What the difference if I split servers in difference processes? Thanks.

http.createServer(function(req, res) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello World');
}).listen(5000, '127.0.0.1');

http.createServer(function(req, res) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello World2');
}).listen(5001, '127.0.0.1');

http.createServer(function(req, res) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello World3');
}).listen(5002, '127.0.0.1');


答:
Try this
Assuming you are wanting to add the text inside the spans I have used innerHTML, and not i.
Also, the totaalPersonen variable should be declared outside the for loop otherwise it will be reinitialized each time.

```<code>var div = document.getElementById("aantallen");
var spans = div.getElementsByTagName("span");
console.log(spans);
var totaalPersonen = 0;
for(i=0;i<spans.length;i++)
{
    alert(parseInt(spans[i].innerHTML));
    totaalPersonen = parseInt(totaalPersonen) + parseInt(spans[i].innerHTML);
    //alert(totaalPersonen);
}
alert(totaalPersonen);
</code>```

Title: JS: Sum of span values in For loop

Body:
I have the following values within span tags:

 3
 2

In JS I want to get the sum of these values. So I made the following For Loop:

var div = document.getElementById("aantallen");
var spans = div.getElementsByTagName("span");
for(i=0;i<spans.length;i++)
{
    var totaalPersonen = totaalPersonen + i;
    alert(totaalPersonen);
}

However, the 3 and 2 are text, so I get Nan in the alerts. My question: how can in convert the 3 and 2 into strings so that I can make a sum of these values?

I tried with String(i) but couldn't get it to work.

Body:
Try this
Assuming you are wanting to add the text inside the spans I have used innerHTML, and not i.
Also, the totaalPersonen variable should be declared outside the for loop otherwise it will be reinitialized each time.

var div = document.getElementById("aantallen");
var spans = div.getElementsByTagName("span");
console.log(spans);
var totaalPersonen = 0;
for(i=0;i<spans.length;i++)
{
    alert(parseInt(spans[i].innerHTML));
    totaalPersonen = parseInt(totaalPersonen) + parseInt(spans[i].innerHTML);
    //alert(totaalPersonen);
}
alert(totaalPersonen);


问:
Unable to show data from database in Laravel after inserting data into database
I was able to insert data into database in Laravel but when I was trying to show the data in a tabular form I couldn't - it was displaying Route [stock_edit] not defined. (View: C:\wamp\www\pump\core\resources\views\dashboard\stock-show.blade.php)

Like I said in my quetion yesterday, I am new to Laravel and I am yet to understand the environment. I have been on this for the past 48 hours searching for help online but couldn't find a satisfactory ones

Here is my stock-show.blade.php

```<code>@extends('layouts.dashboard')
@section('title', 'All Stock')
@section('content')

    @if(count($stock))

        <div class="row">
            <div class="col-md-12">

                <div class="portlet light bordered">
                    <div class="portlet-title">
                        <div class="caption font-dark">
                        </div>
                        <div class="tools"> </div>
                    </div>
                    <div class="portlet-body">
                        <table class="table table-striped table-bordered table-hover" id="sample_1">

                            <thead>
                            <tr>
                                <th>ID#</th>
                                <th>Product Name</th>
                                <th>Price</th>
                                <th>Action</th>
                            </tr>
                            </thead>

                            <tbody>
                            @foreach($stock as $p)
                                <tr>

                                    <td>{{ $p->id }}</td>
                                    <td>{{ $p->name }}</td>
                                    <td>{{ $p->price }} </td>
                                    <td>

                                        <a href="{{ route('stock_edit',$p->id) }}" class="btn purple btn-sm"><i class="fa fa-edit"></i> EDIT</a>

                                        <button type="button" class="btn btn-danger btn-sm delete_button"
                                                data-toggle="modal" data-target="#DelModal"
                                                data-id="{{ $p->id }}">
                                            <i class='fa fa-times'></i> DELETE
                                        </button>

                                    </td>

                                </tr>
                            @endforeach

                            </tbody>
                        </table>
                    </div>
                </div>

            </div>
        </div><!-- ROW-->

        <div class="text-center">
            {!! $stock->render() !!}
        </div>
    @else

        <div class="text-center">
            <h3>No Data available</h3>
        </div>
        @endif

                <!-- Modal for DELETE -->
        <div class="modal fade" id="DelModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                        <h4 class="modal-title" id="myModalLabel"> <i class='fa fa-trash'></i> Delete !</h4>
                    </div>

                    <div class="modal-body">
                        <strong>Are you sure you want to Delete ?</strong>
                    </div>

                    <div class="modal-footer">
                        <form method="post" action="{{ route('stock_delete') }}" class="form-inline">
                            {!! csrf_field() !!}
                            {{ method_field('DELETE') }}
                            <input type="hidden" name="id" class="abir_id" value="0">

                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-danger">DELETE</button>
                        </form>
                    </div>

                </div>
            </div>
        </div>

@endsection

@section('scripts')

    <script>
        $(document).ready(function () {

            $(document).on("click", '.delete_button', function (e) {
                var id = $(this).data('id');
                $(".abir_id").val(id);

            });

        });
    </script>

@endsection
</code>```

and this is the DashboardController.php

```<code>//Stocks
    public function createStock()
    {
        $data['site_title'] = $this->site_title;
        $data['page_title'] = "Create Stock";
        //$data['currency'] = Currency::all();
        return view('dashboard.stock-create',$data);
    }
    public function storeStock(Request $request)
    {
        $this->validate($request,[
           'name' => 'required|unique:stocks,name',
            'price' => 'required',
            //'currency_id' => 'required'
        ]);
        try {
            $stock = Input::except('_method','_token');
            Stock::create($stock);
            session()->flash('message', 'Stock Create Successfully.');
            Session::flash('type', 'success');
            return redirect()->back();
        } catch (\PDOException $e) {
            session()->flash('message', 'Some Problem Occurs, Please Try Again!');
            Session::flash('type', 'danger');
            return redirect()->back();
        }

    }
    public function showStock()
    {
        $data['site_title'] = $this->site_title;
        $data['page_title'] = "All Stock";
        $data['stock'] = Stock::orderBy('id','ASC')->paginate(100);
        return view('dashboard.stock-show',$data);
    }
    public function editStock($id)
    {
        $data['stock'] = Stock::findOrFail($id);
        $data['site_title'] = $this->site_title;
        $data['page_title'] = 'Edit Product';
        $data['stock'] = Stock::all();
        return view('dashboard.stock-edit',$data);
    }
    public function updateStock(Request $request,$id)
    {
        $stocks = Stock::findOrFail($id);
        $this->validate($request,[
           'name' => 'required|unique:stocks,name,'.$stocks->id,
            'price' => 'required',
            //'currency_id' => 'required',
        ]);
        try {
            $stock = Input::except('_method','_token');
            $stocks->fill($stock)->save();
            session()->flash('message', 'Stock Updated Successfully.');
            Session::flash('type', 'success');
            return redirect()->back();
        } catch (\PDOException $e) {
            session()->flash('message', 'Some Problem Occurs, Please Try Again!');
            Session::flash('type', 'danger');
            return redirect()->back();
        }
    }//Stocks End
</code>```

And lastly the route.php

```<code>/* Stock Route List */
Route::get('stock-create',['as'=>'stock-create','uses'=>'DashboardController@createStock']);
Route::post('stock-create',['as'=>'stock-store','uses'=>'DashboardController@storeStock']);
Route::get('stock-show',['as'=>'stock-show','uses'=>'DashboardController@showStock']);
Route::get('stock-edit/{id}',['as'=>'stock-edit','uses'=>'DashboardController@editStock']);
Route::put('stock-edit/{id}',['as'=>'stock-update','uses'=>'DashboardController@updateStock']);
</code>```

答:
You have a typo in your code,

change stock_edit to stock-edit in your view

Body:
I was able to insert data into database in Laravel but when I was trying to show the data in a tabular form I couldn't - it was displaying Route [stock_edit] not defined. (View: C:\wamp\www\pump\core\resources\views\dashboard\stock-show.blade.php)

Like I said in my quetion yesterday, I am new to Laravel and I am yet to understand the environment. I have been on this for the past 48 hours searching for help online but couldn't find a satisfactory ones

Here is my stock-show.blade.php

@extends('layouts.dashboard')
@section('title', 'All Stock')
@section('content')

    @if(count($stock))

                                ID#
                                Product Name
                                Price
                                Action

                            @foreach($stock as $p)

                                    {{ $p->id }}
                                    {{ $p->name }}
                                    {{ $p->price }}

                                        id) }}" class="btn purple btn-sm"> EDIT

                                        <button type="button" class="btn btn-danger btn-sm delete_button"
                                                data-toggle="modal" data-target="#DelModal"
                                                data-id="{{ $p->id }}">
                                             DELETE
                                        </button>

                            @endforeach

            {!! $stock->render() !!}

    @else

No Data available

        @endif

                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

  Delete !

                        Are you sure you want to Delete ?

                        <form method="post" action="{{ route('stock_delete') }}" class="form-inline">
                            {!! csrf_field() !!}
                            {{ method_field('DELETE') }}
                            <input type="hidden" name="id" class="abir_id" value="0">

                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-danger">DELETE</button>
                        </form>

@endsection

@section('scripts')

@endsection

and this is the DashboardController.php

//Stocks
    public function createStock()
    {
        $data['site_title'] = $this->site_title;
        $data['page_title'] = "Create Stock";
        //$data['currency'] = Currency::all();
        return view('dashboard.stock-create',$data);
    }
    public function storeStock(Request $request)
    {
        $this->validate($request,[
           'name' => 'required|unique:stocks,name',
            'price' => 'required',
            //'currency_id' => 'required'
        ]);
        try {
            $stock = Input::except('_method','_token');
            Stock::create($stock);
            session()->flash('message', 'Stock Create Successfully.');
            Session::flash('type', 'success');
            return redirect()->back();
        } catch (\PDOException $e) {
            session()->flash('message', 'Some Problem Occurs, Please Try Again!');
            Session::flash('type', 'danger');
            return redirect()->back();
        }

    }
    public function showStock()
    {
        $data['site_title'] = $this->site_title;
        $data['page_title'] = "All Stock";
        $data['stock'] = Stock::orderBy('id','ASC')->paginate(100);
        return view('dashboard.stock-show',$data);
    }
    public function editStock($id)
    {
        $data['stock'] = Stock::findOrFail($id);
        $data['site_title'] = $this->site_title;
        $data['page_title'] = 'Edit Product';
        $data['stock'] = Stock::all();
        return view('dashboard.stock-edit',$data);
    }
    public function updateStock(Request $request,$id)
    {
        $stocks = Stock::findOrFail($id);
        $this->validate($request,[
           'name' => 'required|unique:stocks,name,'.$stocks->id,
            'price' => 'required',
            //'currency_id' => 'required',
        ]);
        try {
            $stock = Input::except('_method','_token');
            $stocks->fill($stock)->save();
            session()->flash('message', 'Stock Updated Successfully.');
            Session::flash('type', 'success');
            return redirect()->back();
        } catch (\PDOException $e) {
            session()->flash('message', 'Some Problem Occurs, Please Try Again!');
            Session::flash('type', 'danger');
            return redirect()->back();
        }
    }//Stocks End

And lastly the route.php

/* Stock Route List */
Route::get('stock-create',['as'=>'stock-create','uses'=>'DashboardController@createStock']);
Route::post('stock-create',['as'=>'stock-store','uses'=>'DashboardController@storeStock']);
Route::get('stock-show',['as'=>'stock-show','uses'=>'DashboardController@showStock']);
Route::get('stock-edit/{id}',['as'=>'stock-edit','uses'=>'DashboardController@editStock']);
Route::put('stock-edit/{id}',['as'=>'stock-update','uses'=>'DashboardController@updateStock']);