问:
How to change $route in jest test case +VueJS +Jest
I am newbie to VueJS (and in test cases as well), apologize if this is already asked question,

I added a method in my component which checks the $route.name and returns a boolean accordingly,

BUT the issue appears in the test cases (JEST)
Have tried it with this but not working

isAbc () {
return this.$route.name === 'abc-route
}

This is my method for which I want to write test case,

```<code>const $route = {
  name: 'abc-route'
}

const wrapper = shallowMount(Component, {
  mocks: {
    $route
  }
})
</code>```

I have also tried this approach
https://github.com/facebook/jest/issues/890#issuecomment-209698782
and checked if I can get this.$route.path but no luck with that as well.

Anyone can please mention what am I missing or doing wrong to get this?

答:
In case if anyone gets stucked on it, I have solve it by changing the approach,

Instead of assigning $router, one should do the following

```<code>component.vm.$router.replace({ path: '/some/path', name: 'some-name' })
</code>```

and then test it with

```<code>    expect(component.vm.isAbc()).toBe(false)
</code>```

Body:
I am newbie to VueJS (and in test cases as well), apologize if this is already asked question,

I added a method in my component which checks the $route.name and returns a boolean accordingly,

BUT the issue appears in the test cases (JEST)
Have tried it with this but not working

isAbc () {
return this.$route.name === 'abc-route
}

This is my method for which I want to write test case,

const $route = {
  name: 'abc-route'
}

const wrapper = shallowMount(Component, {
  mocks: {
    $route
  }
})

I have also tried this approach
https://github.com/facebook/jest/issues/890#issuecomment-209698782
and checked if I can get this.$route.path but no luck with that as well.

Anyone can please mention what am I missing or doing wrong to get this?

Body:
In case if anyone gets stucked on it, I have solve it by changing the approach,

Instead of assigning $router, one should do the following

component.vm.$router.replace({ path: '/some/path', name: 'some-name' })

and then test it with

    expect(component.vm.isAbc()).toBe(false)


来源: stackexchange

问:
Making Materialize slider responsive
I'm trying to make Materialize slider responsive using a CSS, but it's doesn't work properly. when I test my code with the adaptive view of Firefox, I get slider images responsive with a grey background much bigger than the height of the slider images(as you can see below).

   .slider .slides li img {

background-size: 100% auto;;
background-repeat: no-repeat;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
<div class="slider " >
  <ul class="slides ">
                <li>
      <img class="responsive-img" id="img" src="{{ asset('font/images/IMG_61.jpg') }}">
    </li>
      <li>
      <img class="responsive-img" id="img" src="{{ asset('font/images/IMG_53.jpg') }}">
    </li>
    <li>
      <img class="responsive-img" id="img" src="{{ asset('font/images/IMG_2.jpg') }}">
    </li>
  </ul>
</div>
</div></code>```

screen shot  size 360×640

答:
here is the solution that worked for me:
Manually assigning the height for the slider as 250px for small and medium-sized devices and 600px slider height for large devices (devices with more than 600px width) </p>

```<code> @media only screen and (max-width: 600px) {
          .slides {
            height: 250px !important;
          }
            .slider {
                 height: 250px !important;
            }
        }

@media only screen and (min-width: 600px) {
          .slides {
            height: 600px !important;
          }
            .slider {
                 height: 600px !important;
            }
        }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Making Materialize slider responsive

Body:
I'm trying to make Materialize slider responsive using a CSS, but it's doesn't work properly. when I test my code with the adaptive view of Firefox, I get slider images responsive with a grey background much bigger than the height of the slider images(as you can see below).

   .slider .slides li img {

background-size: 100% auto;;
background-repeat: no-repeat;
}

screen shot  size 360×640

Body:
here is the solution that worked for me:
Manually assigning the height for the slider as 250px for small and medium-sized devices and 600px slider height for large devices (devices with more than 600px width)

 @media only screen and (max-width: 600px) {
          .slides {
            height: 250px !important;
          }
            .slider {
                 height: 250px !important;
            }
        }

@media only screen and (min-width: 600px) {
          .slides {
            height: 600px !important;
          }
            .slider {
                 height: 600px !important;
            }
        }

ContentLicense: CC BY-SA 4.0


问:
Is Page Object Pattern suitable for Windows Application
I have read that Page Object Pattern is suitable for the Web Application Automation and I have used the Page object pattern with Selenium for one of the Web Apps I have automated.

How ever I am curious to know is Page Object suitable to Windows/Desktop applications  ?. Though there is a scope in Windows Apps as well to create different Top level Windows as Pages and expose the operations as methods.

Has any one tried this and want to know the experiences/Advantages/disadvantages

答: yes we can automate the desktop based application with Page object. you can refer WinAppDriverPageObjectModel</p>


问:
Generating a random & unique 8 character string using MySQL
I'm working on a game which involves vehicles at some point. I have a MySQL table named "vehicles" containing the data about the vehicles, including the column "plate" which stores the License Plates for the vehicles.

Now here comes the part I'm having problems with. I need to find an unused license plate before creating a new vehicle - it should be an alphanumeric 8-char random string. How I achieved this was using a while loop in Lua, which is the language I'm programming in, to generate strings and query the DB to see if it is used. However, as the number of vehicles increases, I expect this to become even more inefficient it is right now. Therefore, I decided to try and solve this issue using a MySQL query.

The query I need should simply generate a 8-character alphanumeric string which is not already in the table. I thought of the generate&check loop approach again, but I'm not limiting this question to that just in case there's a more efficient one. I've been able to generate strings by defining a string containing all the allowed chars and randomly substringing it, and nothing more.

Any help is appreciated.

答:
To create a random 10 digit alphanumeric, excluding lookalike chars 01oOlI:

```<code>LPAD(LEFT(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(TO_BASE64(UNHEX(MD5(RAND()))), "/", ""), "+", ""), "=", ""), "O", ""), "l", ""), "I", ""), "1", ""), "0", ""), "o", ""), 10), 10, 0)
</code>```

This is exactly what I needed to create a voucher code. Confusing characters are removed to reduce errors when typing it into a voucher code form.

Hopes this helps somebody, based on Jan Uhlig's brilliant answer.

Please see Jan's answer for a breakdown on how this code works.

Body:
To create a random 10 digit alphanumeric, excluding lookalike chars 01oOlI:

LPAD(LEFT(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(TO_BASE64(UNHEX(MD5(RAND()))), "/", ""), "+", ""), "=", ""), "O", ""), "l", ""), "I", ""), "1", ""), "0", ""), "o", ""), 10), 10, 0)

This is exactly what I needed to create a voucher code. Confusing characters are removed to reduce errors when typing it into a voucher code form.

Hopes this helps somebody, based on Jan Uhlig's brilliant answer.

Please see Jan's answer for a breakdown on how this code works.


问:
Mocking iOS Firebase Auth sign-in methods
This question is somewhat similar to Mock third party classes (Firebase) in Swift but different enough to warrant a new question, based on the answers to it.

I'm trying to mock the Auth/FIRAuth method signIn(withEmail email: String, password: String, completion: AuthDataResultCallback?) and am running into difficulties with trying to mock the AuthDataResultCallback object, mainly because it has a User property that I also want to mock.  Unfortunately, I'm not able to create my own User or Auth objects because they've been marked as not having an available initializer in Swift.

I have an object (let's call it UserAuthenticationRepository) that's responsible for performing user authentication and database reads.  I'd like to inject a Firebase auth object into it to do these things under the hood, but since I want to test this repository object I'd like to be able to inject a Firebase mock object when I go to unit test it.

What I want to do is something like this (simplified slightly for this question):

```<code>import FirebaseAuth

protocol FirebaseUserType {
    var uid: String { get }
}

extension User: FirebaseUserType {}

protocol FirebaseAuthDataResultType {
    var user: FirebaseUserType { get }
}

extension AuthDataResult: FirebaseAuthDataResultType {
    var user: FirebaseUserType {
        // This is where I'm running into problems because AuthDataResult expects a User object,
        // which I also use in the UserAuthenticationRepository signIn(withEmail:) method
    }
}

protocol FirebaseAuthenticationType {
    func signIn(withEmail email: String, password: String, completion: ((FirebaseAuthDataResultType?, Error?) -> Void)?)
}

extension Auth: FirebaseAuthenticationType {
    func signIn(withEmail email: String, password: String, completion: ((FirebaseAuthDataResultType?, Error?) -> Void)?) {
        let completion = completion as AuthDataResultCallback?
        signIn(withEmail: email, password: password, completion: completion)
    }
}

protocol UserAuthenticationType {
    func loginUser(emailAddress: String, password: String) -> Observable<User>
}

class UserAuthenticationRepository: UserAuthenticationType {
    private let authenticationService: FirebaseAuthenticationType
    private let disposeBag = DisposeBag()

    init(authenticationService: FirebaseAuthenticationType = Auth.auth()) {
        self.authenticationService = authenticationService
    }

    func loginUser(emailAddress: String, password: String) -> Observable<User> {
        return .create { [weak self] observer in
            self?.authenticationService.signIn(withEmail: emailAddress, password: password, completion: { authDataResult, error in
                if let error = error {
                    observer.onError(error)
                } else if let authDataResult = authDataResult {
                    observer.onNext(authDataResult.user)
                }
            })
            return Disposables.create()
        }
    }
</code>```

As noted above, I'm running into problems when I try to extend AuthDataResult to conform to my FirebaseAuthDataResultType protocol.  Is it possible to do what I'm trying to do? I'd ultimately like to pass back a uid string in my Firebase authentication service when testing UserAuthenticationRepository.

答:
I was eventually able to find a way to mock the Firebase Auth objects necessary for me, but I had to resort to subclassing the Firebase User object, adding new properties to it be used during testing (can't create a User object directly or mutate its properties), and then creating a struct which conforms to FirebaseAuthDataResultType which is initialized with a MockUser object during testing.  The protocols and extensions I ended up needing are below:

```<code>protocol FirebaseAuthDataResultType {
    var user: User { get }
}

extension AuthDataResult: FirebaseAuthDataResultType {}

typealias FirebaseAuthDataResultTypeCallback = (FirebaseAuthDataResultType?, Error?) -> Void

protocol FirebaseAuthenticationType {
    func signIn(withEmail email: String, password: String, completion: FirebaseAuthDataResultTypeCallback?)
    func signOut() throws
    func addStateDidChangeListener(_ listener: @escaping AuthStateDidChangeListenerBlock) -> AuthStateDidChangeListenerHandle
    func removeStateDidChangeListener(_ listenerHandle: AuthStateDidChangeListenerHandle)
}

extension Auth: FirebaseAuthenticationType {
    func signIn(withEmail email: String, password: String, completion: FirebaseAuthDataResultTypeCallback?) {
        let completion = completion as AuthDataResultCallback?
        signIn(withEmail: email, password: password, completion: completion)
    }
}
</code>```

Below are the mock objects:

```<code>class MockUser: User {
    let testingUID: String
    let testingEmail: String?
    let testingDisplayName: String?

    init(testingUID: String,
         testingEmail: String? = nil,
         testingDisplayName: String? = nil) {
        self.testingUID = testingUID
        self.testingEmail = testingEmail
        self.testingDisplayName = testingDisplayName
    }
}

struct MockFirebaseAuthDataResult: FirebaseAuthDataResultType {
    var user: User
}
</code>```

An instance of my mock Firebase authentication service with stubs:

```<code>class MockFirebaseAuthenticationService: FirebaseAuthenticationType {
    typealias AuthDataResultType = (authDataResult: FirebaseAuthDataResultType?, error: Error?)
    var authDataResultFactory: (() -> (AuthDataResultType))?

    func signIn(withEmail email: String, password: String, completion: FirebaseAuthDataResultTypeCallback?) {
      // Mock service logic goes here
    }

    // ...rest of protocol functions
}
</code>```

Usage (using RxSwift and RxTest):

```<code>func testLoginUserReturnsUserIfSignInSuccessful() {
    let firebaseAuthService = MockFirebaseAuthenticationService()
    let expectedUID = "aM1RyjpaZcQ4EhaUvDAeCnla3HX2"
    firebaseAuthService.authDataResultFactory = {
        let user = MockUser(testingUID: expectedUID)
        let authDataResult = MockFirebaseAuthDataResult(user: user)
        return (authDataResult, nil)
    }

    let sut = UserSessionRepository(authenticationService: firebaseAuthService)
    let userObserver = testScheduler.createObserver(User.self)

    sut.loginUser(emailAddress: "john@gmail.com", password: "123456")
       .bind(to: userObserver)
       .disposed(by: disposeBag)

    testScheduler.start()

    let user = userObserver.events[0].value.element as? MockUser

    // Assert MockUser properties, events, etc.
}
</code>```

If anyone has any better ideas of how this can be accomplished, please let me know!

Body:
This question is somewhat similar to Mock third party classes (Firebase) in Swift but different enough to warrant a new question, based on the answers to it.

I'm trying to mock the Auth/FIRAuth method signIn(withEmail email: String, password: String, completion: AuthDataResultCallback?) and am running into difficulties with trying to mock the AuthDataResultCallback object, mainly because it has a User property that I also want to mock.  Unfortunately, I'm not able to create my own User or Auth objects because they've been marked as not having an available initializer in Swift.

I have an object (let's call it UserAuthenticationRepository) that's responsible for performing user authentication and database reads.  I'd like to inject a Firebase auth object into it to do these things under the hood, but since I want to test this repository object I'd like to be able to inject a Firebase mock object when I go to unit test it.

What I want to do is something like this (simplified slightly for this question):

import FirebaseAuth

protocol FirebaseUserType {
    var uid: String { get }
}

extension User: FirebaseUserType {}

protocol FirebaseAuthDataResultType {
    var user: FirebaseUserType { get }
}

extension AuthDataResult: FirebaseAuthDataResultType {
    var user: FirebaseUserType {
        // This is where I'm running into problems because AuthDataResult expects a User object,
        // which I also use in the UserAuthenticationRepository signIn(withEmail:) method
    }
}

protocol FirebaseAuthenticationType {
    func signIn(withEmail email: String, password: String, completion: ((FirebaseAuthDataResultType?, Error?) -> Void)?)
}

extension Auth: FirebaseAuthenticationType {
    func signIn(withEmail email: String, password: String, completion: ((FirebaseAuthDataResultType?, Error?) -> Void)?) {
        let completion = completion as AuthDataResultCallback?
        signIn(withEmail: email, password: password, completion: completion)
    }
}

protocol UserAuthenticationType {
    func loginUser(emailAddress: String, password: String) -> Observable<User>
}

class UserAuthenticationRepository: UserAuthenticationType {
    private let authenticationService: FirebaseAuthenticationType
    private let disposeBag = DisposeBag()

    init(authenticationService: FirebaseAuthenticationType = Auth.auth()) {
        self.authenticationService = authenticationService
    }

    func loginUser(emailAddress: String, password: String) -> Observable<User> {
        return .create { [weak self] observer in
            self?.authenticationService.signIn(withEmail: emailAddress, password: password, completion: { authDataResult, error in
                if let error = error {
                    observer.onError(error)
                } else if let authDataResult = authDataResult {
                    observer.onNext(authDataResult.user)
                }
            })
            return Disposables.create()
        }
    }

As noted above, I'm running into problems when I try to extend AuthDataResult to conform to my FirebaseAuthDataResultType protocol.  Is it possible to do what I'm trying to do? I'd ultimately like to pass back a uid string in my Firebase authentication service when testing UserAuthenticationRepository.

Body:
I was eventually able to find a way to mock the Firebase Auth objects necessary for me, but I had to resort to subclassing the Firebase User object, adding new properties to it be used during testing (can't create a User object directly or mutate its properties), and then creating a struct which conforms to FirebaseAuthDataResultType which is initialized with a MockUser object during testing.  The protocols and extensions I ended up needing are below:

protocol FirebaseAuthDataResultType {
    var user: User { get }
}

extension AuthDataResult: FirebaseAuthDataResultType {}

typealias FirebaseAuthDataResultTypeCallback = (FirebaseAuthDataResultType?, Error?) -> Void

protocol FirebaseAuthenticationType {
    func signIn(withEmail email: String, password: String, completion: FirebaseAuthDataResultTypeCallback?)
    func signOut() throws
    func addStateDidChangeListener(_ listener: @escaping AuthStateDidChangeListenerBlock) -> AuthStateDidChangeListenerHandle
    func removeStateDidChangeListener(_ listenerHandle: AuthStateDidChangeListenerHandle)
}

extension Auth: FirebaseAuthenticationType {
    func signIn(withEmail email: String, password: String, completion: FirebaseAuthDataResultTypeCallback?) {
        let completion = completion as AuthDataResultCallback?
        signIn(withEmail: email, password: password, completion: completion)
    }
}

Below are the mock objects:

class MockUser: User {
    let testingUID: String
    let testingEmail: String?
    let testingDisplayName: String?

    init(testingUID: String,
         testingEmail: String? = nil,
         testingDisplayName: String? = nil) {
        self.testingUID = testingUID
        self.testingEmail = testingEmail
        self.testingDisplayName = testingDisplayName
    }
}

struct MockFirebaseAuthDataResult: FirebaseAuthDataResultType {
    var user: User
}

An instance of my mock Firebase authentication service with stubs:

class MockFirebaseAuthenticationService: FirebaseAuthenticationType {
    typealias AuthDataResultType = (authDataResult: FirebaseAuthDataResultType?, error: Error?)
    var authDataResultFactory: (() -> (AuthDataResultType))?

    func signIn(withEmail email: String, password: String, completion: FirebaseAuthDataResultTypeCallback?) {
      // Mock service logic goes here
    }

    // ...rest of protocol functions
}

Usage (using RxSwift and RxTest):

func testLoginUserReturnsUserIfSignInSuccessful() {
    let firebaseAuthService = MockFirebaseAuthenticationService()
    let expectedUID = "aM1RyjpaZcQ4EhaUvDAeCnla3HX2"
    firebaseAuthService.authDataResultFactory = {
        let user = MockUser(testingUID: expectedUID)
        let authDataResult = MockFirebaseAuthDataResult(user: user)
        return (authDataResult, nil)
    }

    let sut = UserSessionRepository(authenticationService: firebaseAuthService)
    let userObserver = testScheduler.createObserver(User.self)

    sut.loginUser(emailAddress: "john@gmail.com", password: "123456")
       .bind(to: userObserver)
       .disposed(by: disposeBag)

    testScheduler.start()

    let user = userObserver.events[0].value.element as? MockUser

    // Assert MockUser properties, events, etc.
}

If anyone has any better ideas of how this can be accomplished, please let me know!


问:
Uploading local images to microsoft cognitive face
Error Screenshot

```<code>import sys
import os, time
import cognitive_face as CF
import global_variables as global_var
import urllib
import sqlite3
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

Key = global_var.key

CF.Key.set(Key)

BASE_URL = global_var.BASE_URL  # Replace with your regional Base URL
CF.BaseUrl.set(BASE_URL)

def get_person_id():
    person_id = ''
    extractId = str(sys.argv[1])[-2:]
    connect = sqlite3.connect("Face-DataBase")
    c = connect.cursor()
    cmd = "SELECT * FROM Students WHERE ID = " + extractId
    c.execute(cmd)
    row = c.fetchone()
    person_id = row[3]
    connect.close()
    return person_id

if len(sys.argv) is not 1:
    currentDir = os.path.dirname(os.path.abspath(__file__))
    imageFolder = os.path.join(currentDir, "dataset/" + str(sys.argv[1]))
    person_id = get_person_id()
    for filename in os.listdir(imageFolder):
        if filename.endswith(".jpg"):
            print(filename)
            imgurl = urllib.request.pathname2url(os.path.join(imageFolder, filename))
            imgurl = imgurl[3:]
            print("imageurl = {}".format(imgurl))
            res = CF.face.detect(imgurl)
            if len(res) != 1:
                print("No face detected in image")
            else:
                res = CF.person.add_face(imgurl, global_var.personGroupId, person_id)
                print(res)
            time.sleep(6)
else:
    print("supply attributes please from dataset folder")
</code>```

I hope images should be converted to byte array but I don't know how to do it. Local images have to be uploaded into cognitive API. Tried many ways but cannot solve the error.

```<code>imgurl = urllib.request.pathname2url(os.path.join(imageFolder, filename))
</code>```

Above line is where error exists

答:
Welcome to Stack Overflow, @arun.

First of all, as per here, the API you're using is deprecated, and you should switch to this one instead.

Second, in this new API, there is a method called detect_with_stream (ref here), that will make a request to the Face Recognition endpoint, using the byte stream instead of an URL (it will use different request headers than the URL-based method). This method accepts a stream of bytes containing your image. I've worked with another cognitive services API that performs text recognition, and so I've faced this problem of sending an image URL or the image byte stream. You can generate a bytestream from the file as follows:

```<code>image_data = open(image_path, "rb").read()
</code>```

The variable image_data can be passed to the method.

Edit: Instructions on how to use the new API with the image bytestream

First, install the following pip package:

pip install azure-cognitiveservices-vision-face

Then, you can try this approach.

```<code>import sys
import os, time
import global_variables as global_var
from azure.cognitiveservices.vision.face import FaceClient
from msrest.authentication import CognitiveServicesCredentials
import urllib
import sqlite3
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

KEY = global_var.key

ENDPOINT = global_var.endpoint

face_client = FaceClient(ENDPOINT,CognitiveServicesCredentials(KEY))

def get_person_id():
    person_id = ''
    extractId = str(sys.argv[1])[-2:]
    connect = sqlite3.connect("Face-DataBase")
    c = connect.cursor()
    cmd = "SELECT * FROM Students WHERE ID = " + extractId
    c.execute(cmd)
    row = c.fetchone()
    person_id = row[3]
    connect.close()
    return person_id

if len(sys.argv) is not 1:
    currentDir = os.path.dirname(os.path.abspath(__file__))
    imageFolder = os.path.join(currentDir, "dataset/" + str(sys.argv[1]))
    person_id = get_person_id()
    for filename in os.listdir(imageFolder):
        if filename.endswith(".jpg"):
            print(filename)
            img_data = open(filename, "rb").read()
            res = face_client.face.detect_with_stream(img_data)
            if not res:
                print('No face detected from image {}'.format(filename))
                continue

            res = face_client.person_group_person.add_face_from_stream(global_var.personGroupId, person_id, img_data)
            print(res)
            time.sleep(6)
else:
    print("supply attributes please from dataset folder")
</code>```

Edit 2: Notes on traversing all the files in a directory

Ok @arun, your current problem stems from the fact that you're using os.listdir which only lists the filenames, so you don't have their paths. The quickest solution would be to open each image inside the loop with:

```<code>img_data = open(os.path.join(imageFolder, filename), "rb").read()
</code>```

Body:
Error Screenshot

import sys
import os, time
import cognitive_face as CF
import global_variables as global_var
import urllib
import sqlite3
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

Key = global_var.key

CF.Key.set(Key)

BASE_URL = global_var.BASE_URL  # Replace with your regional Base URL
CF.BaseUrl.set(BASE_URL)

def get_person_id():
    person_id = ''
    extractId = str(sys.argv[1])[-2:]
    connect = sqlite3.connect("Face-DataBase")
    c = connect.cursor()
    cmd = "SELECT * FROM Students WHERE ID = " + extractId
    c.execute(cmd)
    row = c.fetchone()
    person_id = row[3]
    connect.close()
    return person_id

if len(sys.argv) is not 1:
    currentDir = os.path.dirname(os.path.abspath(__file__))
    imageFolder = os.path.join(currentDir, "dataset/" + str(sys.argv[1]))
    person_id = get_person_id()
    for filename in os.listdir(imageFolder):
        if filename.endswith(".jpg"):
            print(filename)
            imgurl = urllib.request.pathname2url(os.path.join(imageFolder, filename))
            imgurl = imgurl[3:]
            print("imageurl = {}".format(imgurl))
            res = CF.face.detect(imgurl)
            if len(res) != 1:
                print("No face detected in image")
            else:
                res = CF.person.add_face(imgurl, global_var.personGroupId, person_id)
                print(res)
            time.sleep(6)
else:
    print("supply attributes please from dataset folder")

I hope images should be converted to byte array but I don't know how to do it. Local images have to be uploaded into cognitive API. Tried many ways but cannot solve the error.

imgurl = urllib.request.pathname2url(os.path.join(imageFolder, filename))

Above line is where error exists

Body:
Welcome to Stack Overflow, @arun.

First of all, as per here, the API you're using is deprecated, and you should switch to this one instead.

Second, in this new API, there is a method called detect_with_stream (ref here), that will make a request to the Face Recognition endpoint, using the byte stream instead of an URL (it will use different request headers than the URL-based method). This method accepts a stream of bytes containing your image. I've worked with another cognitive services API that performs text recognition, and so I've faced this problem of sending an image URL or the image byte stream. You can generate a bytestream from the file as follows:

image_data = open(image_path, "rb").read()

The variable image_data can be passed to the method.

Edit: Instructions on how to use the new API with the image bytestream

First, install the following pip package:

pip install azure-cognitiveservices-vision-face

Then, you can try this approach.

import sys
import os, time
import global_variables as global_var
from azure.cognitiveservices.vision.face import FaceClient
from msrest.authentication import CognitiveServicesCredentials
import urllib
import sqlite3
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

KEY = global_var.key

ENDPOINT = global_var.endpoint

face_client = FaceClient(ENDPOINT,CognitiveServicesCredentials(KEY))

def get_person_id():
    person_id = ''
    extractId = str(sys.argv[1])[-2:]
    connect = sqlite3.connect("Face-DataBase")
    c = connect.cursor()
    cmd = "SELECT * FROM Students WHERE ID = " + extractId
    c.execute(cmd)
    row = c.fetchone()
    person_id = row[3]
    connect.close()
    return person_id

if len(sys.argv) is not 1:
    currentDir = os.path.dirname(os.path.abspath(__file__))
    imageFolder = os.path.join(currentDir, "dataset/" + str(sys.argv[1]))
    person_id = get_person_id()
    for filename in os.listdir(imageFolder):
        if filename.endswith(".jpg"):
            print(filename)
            img_data = open(filename, "rb").read()
            res = face_client.face.detect_with_stream(img_data)
            if not res:
                print('No face detected from image {}'.format(filename))
                continue

            res = face_client.person_group_person.add_face_from_stream(global_var.personGroupId, person_id, img_data)
            print(res)
            time.sleep(6)
else:
    print("supply attributes please from dataset folder")

Edit 2: Notes on traversing all the files in a directory

Ok @arun, your current problem stems from the fact that you're using os.listdir which only lists the filenames, so you don't have their paths. The quickest solution would be to open each image inside the loop with:

img_data = open(os.path.join(imageFolder, filename), "rb").read()


问:
How to show component inside another dynamically?
I have a component LayersComponent.

```<code>@Component({
  selector: "app-layers",
  templateUrl: "./layers.component.html",
  styleUrls: ["./layers.component.sass"]
})
export class LayersComponent implements OnInit {
}
</code>```

Template is:

```<code><div class="Layers">
  Text

  <!-- Create component below -->
  <app-another-component></app-another-component>
</div>
</code>```

I want to create and show dinamically component <app-another-component></app-another-component> inside current component.

But I need send command create from another component not inside LayersComponent, but somewhere from another component in application.

How to do that?

I have tried:

```<code><div class="Layers">
   Text
   <ng-container *ngTemplateOutlet="app-another-component"></ng-container>
</div>
</code>```

But I dont know how to send command outside LayersComponent?

答:
The solution for the simple case of injecting HTML content is to use <ng-content>.

parent

```<code><child>
  <p>Some injected HTML content</p>
</child>
</code>```

child

```<code><p>
  <!-- inner HTML of <child> will go here -->
  <ng-content></ng-content>
</p>
</code>```

ngTemplateOutlet

If you want to dynamically inject the HTML, you just dynamically declare the HTML inside <child>:

parent

```<code><child>
  <p *ngIf="condition1">Some conditional injected HTML content</p>
  <p *ngIf="condition2">Some different conditional injected HTML content</p>
</child>
</code>```

You would use ngTemplateOutlet if you want to reference a named template:

parent

```<code><child>
   <ng-container *ngTemplateOutlet="body"></ng-container>
</child>

<ng-template #body>
  <p>Some reusable content</p>
</ng-template>
</code>```

Targetting injected HTML

To target specific parts of the injected HTML, use selectors:

parent

```<code><child>
  <span heading>TITLE</span>
  <p body>The body</p>
</child>
</code>```

child

```<code><h1><ng-content select="[heading]"></ng-content></h1>
<div select="[body]">

</div>
</code>```

Body:
I have a component LayersComponent.

@Component({
  selector: "app-layers",
  templateUrl: "./layers.component.html",
  styleUrls: ["./layers.component.sass"]
})
export class LayersComponent implements OnInit {
}

Template is:

  Text

  <app-another-component></app-another-component>

I want to create and show dinamically component <app-another-component></app-another-component> inside current component.

But I need send command create from another component not inside LayersComponent, but somewhere from another component in application.

How to do that?

I have tried:

   Text
   <ng-container *ngTemplateOutlet="app-another-component"></ng-container>

But I dont know how to send command outside LayersComponent?

Body:
The solution for the simple case of injecting HTML content is to use <ng-content>.

parent

<child>
  <p>Some injected HTML content</p>
</child>

child

<p>
  <!-- inner HTML of <child> will go here -->
  <ng-content></ng-content>
</p>

ngTemplateOutlet

If you want to dynamically inject the HTML, you just dynamically declare the HTML inside <child>:

parent

<child>
  <p *ngIf="condition1">Some conditional injected HTML content</p>
  <p *ngIf="condition2">Some different conditional injected HTML content</p>
</child>

You would use ngTemplateOutlet if you want to reference a named template:

parent

<child>
   <ng-container *ngTemplateOutlet="body"></ng-container>
</child>

<ng-template #body>
  <p>Some reusable content</p>
</ng-template>

Targetting injected HTML

To target specific parts of the injected HTML, use selectors:

parent

<child>
  <span heading>TITLE</span>
  <p body>The body</p>
</child>

child

<h1><ng-content select="[heading]"></ng-content></h1>
<div select="[body]">

</div>


问:
Is SSL set on a per machine or per connection basis
Is it possible to have a FTP server using SSL on a application server that does not use SSL?

How would you setup an ASP.NET 2.0 to consume a SSL certificate?

This certianly sounds possible but is it advisable, is it good practice?

答:
The choice on using SSL us made on a per connection level, usually determined by the IP port being used (i.e. will be set up between client and server before any application code involved).

The same service/content could be set up on multiple ports each with a different choice for SSL.

The certificate is per host name, but servers can generally support appearing under different names.

To use SSL with ASP.NET takes nothing special, it just works once the IIS web site is configured to support SSL (or to require it: when connections to port 80 for HTTP are redirected to the SSL port); this choice can be made on a per folder basis.

OwnerDisplayName: Dean

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Richard


问:
Ruby on Rails App Displaying Unwanted Data
Whenever the following code runs i get extra output on the page which looks like the garbage on the bottom.  I have tried to see if it is in my migrations or function calls, but they all seem to be pretty clean (not much too f.name).  If needed I can provide a copy of my migrations and schema.

```<code><%= @subject.Name %>
<%= @subject.formulas.each do |f| %>
  <div class="entry">
    <h3><%= f.name %></h3>
  </div>
<% end %>
</code>```

The extra output is:

```<code>[#<Formula id: 2, name: "Pythagorean Theorem", description: "n any right triangle, the area of the square whose ...", formula: "a^2+b^2=c^2", created_at: "2011-05-17 03:18:44", updated_at: "2011-05-17 03:18:44">]
</code>```

答:
Change

```<code><%= @subject.formulas.each do |f| %>
</code>```

to

```<code><% @subject.formulas.each do |f| %>
</code>```

Body:
Whenever the following code runs i get extra output on the page which looks like the garbage on the bottom.  I have tried to see if it is in my migrations or function calls, but they all seem to be pretty clean (not much too f.name).  If needed I can provide a copy of my migrations and schema.

<%= @subject.Name %>
<%= @subject.formulas.each do |f| %>

<%= f.name %>

<% end %>

The extra output is:

[#<Formula id: 2, name: "Pythagorean Theorem", description: "n any right triangle, the area of the square whose ...", formula: "a^2+b^2=c^2", created_at: "2011-05-17 03:18:44", updated_at: "2011-05-17 03:18:44">]

Body:
Change

<%= @subject.formulas.each do |f| %>

to

<% @subject.formulas.each do |f| %>


问:
Missing colors in my Chart.js, my data looks fine, but no color
I made my first bar with Chart.js library.
My data looks nice, but I can't give my valuest some color.

enter image description here

My function looks like this:

```<code>var $barData =
{
    type: 'bar',
    labels: ['Super mad', 'Middel', 'Ikke ok', 'Gennemsnit'],
    datasets:
    [
        {
            label: 'Antal stemmer',
            data: [
            [$arrStemmer[0]],
            [$arrStemmer[1]],
            [$arrStemmer[2]],
            [$Snit_Vaerdi]
            ],

            backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)'
            ],
            borderColor: [
            'rgba(255, 99, 132, 1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)'
            ],
            borderWidth: 1
        }

    ]
}

// Hent graf initialiserings setup
var $Stemmer = document.getElementById("can_afstemning_graf").getContext("2d");
// Tegn graf, men data fra barData objektet
new Chart($Stemmer).Bar($barData);
</code>```

What am I missing?
I am looking here in the documentation and it look fine: https://www.chartjs.org/docs/latest/.

Thanks,
Nenad

答:
You are setting the data incorrectly.

You should use

```<code>data: [
    $arrStemmer[0],
    $arrStemmer[1],
    $arrStemmer[2],
    $Snit_Vaerdi
],
</code>```

Instead of

```<code>data: [
    [$arrStemmer[0]],
    [$arrStemmer[1]],
    [$arrStemmer[2]],
    [$Snit_Vaerdi]
],
</code>```

Body:
I made my first bar with Chart.js library.
My data looks nice, but I can't give my valuest some color.

enter image description here

My function looks like this:

var $barData =
{
    type: 'bar',
    labels: ['Super mad', 'Middel', 'Ikke ok', 'Gennemsnit'],
    datasets:
    [
        {
            label: 'Antal stemmer',
            data: [
            [$arrStemmer[0]],
            [$arrStemmer[1]],
            [$arrStemmer[2]],
            [$Snit_Vaerdi]
            ],

            backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)'
            ],
            borderColor: [
            'rgba(255, 99, 132, 1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)'
            ],
            borderWidth: 1
        }

    ]
}

// Hent graf initialiserings setup
var $Stemmer = document.getElementById("can_afstemning_graf").getContext("2d");
// Tegn graf, men data fra barData objektet
new Chart($Stemmer).Bar($barData);

What am I missing?
I am looking here in the documentation and it look fine: https://www.chartjs.org/docs/latest/.

Thanks,
Nenad

Body:
You are setting the data incorrectly.

You should use

data: [
    $arrStemmer[0],
    $arrStemmer[1],
    $arrStemmer[2],
    $Snit_Vaerdi
],

Instead of

data: [
    [$arrStemmer[0]],
    [$arrStemmer[1]],
    [$arrStemmer[2]],
    [$Snit_Vaerdi]
],


问:
Styling the UI Fabric Date Picker Callout
How could I modify the style of elements inside the callout of the UI Fabric Date Picker? For example highlight the current month?

According to the documentation, I should be able to use the DatePicker styles property to target sub-components, but I don't know how to reach specific elements:

```<code>styles = {
  callout: {
  ... what goes here?
  }
}
</code>```

I am trying to get this to work without having to rely on yet another third party library like styled-components.

答:
The 'callout' object (as the others e.g. icon, root, textField for DatePicker component) expects css-styles (camelCased, no dash).

'Callout' refers to the HTML-element wrapping the popup, Icon tothe Icon in the DatePicker, etc.

```<code>styles = {
  callout: {
    maxHeight: '300px',
    fontSize: '2rem',
    /* etc */
  },
  icon: {
     color: 'red'
  },
  root: {},
  textField: {}
}
</code>```

Edit:

Highlighting the current month you can archive easily via the DatePicker Prop highlightCurrentMonth (from doc: 'Whether the month picker should highlight the current month')

Link to DatePicker doc

Body:
How could I modify the style of elements inside the callout of the UI Fabric Date Picker? For example highlight the current month?

According to the documentation, I should be able to use the DatePicker styles property to target sub-components, but I don't know how to reach specific elements:

styles = {
  callout: {
  ... what goes here?
  }
}

I am trying to get this to work without having to rely on yet another third party library like styled-components.

Body:
The 'callout' object (as the others e.g. icon, root, textField for DatePicker component) expects css-styles (camelCased, no dash).

'Callout' refers to the HTML-element wrapping the popup, Icon tothe Icon in the DatePicker, etc.

styles = {
  callout: {
    maxHeight: '300px',
    fontSize: '2rem',
    /* etc */
  },
  icon: {
     color: 'red'
  },
  root: {},
  textField: {}
}

Edit:

Highlighting the current month you can archive easily via the DatePicker Prop highlightCurrentMonth (from doc: 'Whether the month picker should highlight the current month')

Link to DatePicker doc


问:
What is the more elegant way to sample a random number until it's not present in the set?
I am wondering what is the more elegant (if this word is appropriate in this case) way to keep generating a random number until it's not in the set of used values. The first option is repetitive in that we have the same line for random type both inside and outside the while-loop.

The second one, however, needs to add a conditional statement to break out of the loop. I understand that this particular case is trivial and both versions work, but which looks more Python/elegant in your opinion?

```<code>def orchestrator(image = None):
    used_values = set()

    for _ in range(7):
        toss = np.random.random()

        if toss >= 0.5:
            random_type = np.random.randint(1,7,1)[0]
            while random_type in used_values:
                random_type = np.random.randint(1,7,1)[0]
            used_values.add(random_type)
            print(random_type)
</code>```

```<code>def orchestrator(image = None):
    used_values = set()

    for _ in range(7):
        toss = np.random.random()

        if toss >= 0.5:
            while True:
                random_type = np.random.randint(1,7,1)[0]
                if random_type not in used_values:
                    break
            used_values.add(random_type)
            print(random_type)
</code>```

答:
Since you have to do some remembering anyway, it's easier to go the opposite way, remember unused things. This solves several problems: you never need to repeat the random generation, and a list is sufficient so you don't get the memory overhead of a set.

```<code>from random import shuffle
unused_values = list(range(7))
shuffle(unused_values)
</code>```

then whenever you need a new non-repeating random number,

```<code>random_type = unused_values.pop()
</code>```

Body:
I am wondering what is the more elegant (if this word is appropriate in this case) way to keep generating a random number until it's not in the set of used values. The first option is repetitive in that we have the same line for random type both inside and outside the while-loop.

The second one, however, needs to add a conditional statement to break out of the loop. I understand that this particular case is trivial and both versions work, but which looks more Python/elegant in your opinion?

def orchestrator(image = None):
    used_values = set()

    for _ in range(7):
        toss = np.random.random()

        if toss >= 0.5:
            random_type = np.random.randint(1,7,1)[0]
            while random_type in used_values:
                random_type = np.random.randint(1,7,1)[0]
            used_values.add(random_type)
            print(random_type)

def orchestrator(image = None):
    used_values = set()

    for _ in range(7):
        toss = np.random.random()

        if toss >= 0.5:
            while True:
                random_type = np.random.randint(1,7,1)[0]
                if random_type not in used_values:
                    break
            used_values.add(random_type)
            print(random_type)

Body:
Since you have to do some remembering anyway, it's easier to go the opposite way, remember unused things. This solves several problems: you never need to repeat the random generation, and a list is sufficient so you don't get the memory overhead of a set.

from random import shuffle
unused_values = list(range(7))
shuffle(unused_values)

then whenever you need a new non-repeating random number,

random_type = unused_values.pop()


问:
log4j log problem
I am writing an servlet.
I having several classes, some of them I want their log to be seperated from each other.
Here is the log4j configuration file:

```<code>log4j.rootLogger=INFO, CONSOLE, SearchPdfBill, Scheduler

# CONSOLE is set to be a ConsoleAppender.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=<%p> %c{1}.%t %d{HH:mm:ss} - %m%n

# LOGFILE is set to be a file
log4j.appender.SearchPdfBill=org.apache.log4j.DailyRollingFileAppender
log4j.appender.SearchPdfBill.File = /bps/app/BpsPdfBill/BpsPdfBill.ear/BpsPdfBill.war/WEB-INF/logs/BpsPdfBill.log
#log4j.appender.SearchPdfBill.File = E:\\Workspace\\Eclipse_Workspace\\BpsPdfBill\\log\\BpsPdfBill.log
log4j.appender.SearchPdfBill.Append = true
log4j.appender.SearchPdfBill.DatePattern = '.'yyyy-MM-dd
log4j.appender.SearchPdfBill.layout=org.apache.log4j.PatternLayout
log4j.appender.SearchPdfBill.layout.ConversionPattern=<%p> %c{1}.%t %d{HH:mm:ss} - %m%n

# LOGFILE is set to be a file
log4j.appender.Scheduler=org.apache.log4j.DailyRollingFileAppender
log4j.appender.Scheduler.File = /bps/app/BpsPdfBill/BpsPdfBill.ear/BpsPdfBill.war/WEB-INF/logs/Schedule.log
#log4j.appender.Scheduler.File = E:\\Workspace\\Eclipse_Workspace\\BpsPdfBill\\log\\BpsPdfBill.log
log4j.appender.Scheduler.Append = true
log4j.appender.Scheduler.DatePattern = '.'yyyy-MM-dd
log4j.appender.Scheduler.layout=org.apache.log4j.PatternLayout
log4j.appender.Scheduler.layout.ConversionPattern=<%p> %c{1}.%t %d{HH:mm:ss} - %m%n
</code>```

I setup a logger here:

```<code>            String logDir = conf.getInitParameter("log_file_path");
        if (logDir == null) {
            initErrMsg = "Param - log_file_path cannot be empty";
            throw new ServletException(initErrMsg);
        }

        if ((logger = Logger.getLogger(SearchPdfBill.class)) != null) {
            //writeLog("Initializing log4j.");
            conf.getServletContext().log("Log4j initialized.");
        } else {
            conf.getServletContext().log("Cannot initialize log4j properly.");
        }
</code>```

And another logger here:

```<code>            logDir = sc.getInitParameter("log_file_path");
        if (logDir == null) {
            initErrMsg = "Param - log_file_path cannot be empty";
            try {
                throw new ServletException(initErrMsg);
            } catch (ServletException e) {
                // TODO Auto-generated catch block
                conditionalWriteLog(logEnabled, e.getMessage());
            }
        }

        if ((logger = Logger.getLogger(Scheduler.class)) != null) {
            //writeLog("Initializing log4j.");
            conditionalWriteLog(logEnabled, "Log4j initialized.");
        } else {
            conditionalWriteLog(logEnabled, "Cannot initialize log4j properly.");
        }
</code>```

However, it end up the 2 two logger are logging the same thing. Every log is log to the 2 file identically. Why?

I think the configuration file is wrong probably, but I don't know where it is, can somebody help me to correct that?

答:
You need to define those two loggers in your configuration file. Are those objects within a package? That is important to the way you will configure them. Say the package is com.gunbuster:

```<code>log4j.category.com.gunbuster.SearchPdfBill=INFO, SearchPdfBill
log4j.additivity.com.gunbuster.SearchPdfBill=false

log4j.category.com.gunbuster.Scheduler=INFO, Scheduler
log4j.additivity.com.gunbuster.Scheduler=false
</code>```

The additivity setting is to prevent those loggers from adding to the rootLogger output to CONSOLE Also, you should make the first line:

```<code>log4j.rootLogger=INFO, CONSOLE
</code>```

So that the rootLogger does not add entries into those files.

Title: log4j log problem

Body:
I am writing an servlet.
I having several classes, some of them I want their log to be seperated from each other.
Here is the log4j configuration file:

log4j.rootLogger=INFO, CONSOLE, SearchPdfBill, Scheduler

# CONSOLE is set to be a ConsoleAppender.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=<%p> %c{1}.%t %d{HH:mm:ss} - %m%n

# LOGFILE is set to be a file
log4j.appender.SearchPdfBill=org.apache.log4j.DailyRollingFileAppender
log4j.appender.SearchPdfBill.File = /bps/app/BpsPdfBill/BpsPdfBill.ear/BpsPdfBill.war/WEB-INF/logs/BpsPdfBill.log
#log4j.appender.SearchPdfBill.File = E:\\Workspace\\Eclipse_Workspace\\BpsPdfBill\\log\\BpsPdfBill.log
log4j.appender.SearchPdfBill.Append = true
log4j.appender.SearchPdfBill.DatePattern = '.'yyyy-MM-dd
log4j.appender.SearchPdfBill.layout=org.apache.log4j.PatternLayout
log4j.appender.SearchPdfBill.layout.ConversionPattern=<%p> %c{1}.%t %d{HH:mm:ss} - %m%n

# LOGFILE is set to be a file
log4j.appender.Scheduler=org.apache.log4j.DailyRollingFileAppender
log4j.appender.Scheduler.File = /bps/app/BpsPdfBill/BpsPdfBill.ear/BpsPdfBill.war/WEB-INF/logs/Schedule.log
#log4j.appender.Scheduler.File = E:\\Workspace\\Eclipse_Workspace\\BpsPdfBill\\log\\BpsPdfBill.log
log4j.appender.Scheduler.Append = true
log4j.appender.Scheduler.DatePattern = '.'yyyy-MM-dd
log4j.appender.Scheduler.layout=org.apache.log4j.PatternLayout
log4j.appender.Scheduler.layout.ConversionPattern=<%p> %c{1}.%t %d{HH:mm:ss} - %m%n

I setup a logger here:

            String logDir = conf.getInitParameter("log_file_path");
        if (logDir == null) {
            initErrMsg = "Param - log_file_path cannot be empty";
            throw new ServletException(initErrMsg);
        }

        if ((logger = Logger.getLogger(SearchPdfBill.class)) != null) {
            //writeLog("Initializing log4j.");
            conf.getServletContext().log("Log4j initialized.");
        } else {
            conf.getServletContext().log("Cannot initialize log4j properly.");
        }

And another logger here:

            logDir = sc.getInitParameter("log_file_path");
        if (logDir == null) {
            initErrMsg = "Param - log_file_path cannot be empty";
            try {
                throw new ServletException(initErrMsg);
            } catch (ServletException e) {
                // TODO Auto-generated catch block
                conditionalWriteLog(logEnabled, e.getMessage());
            }
        }

        if ((logger = Logger.getLogger(Scheduler.class)) != null) {
            //writeLog("Initializing log4j.");
            conditionalWriteLog(logEnabled, "Log4j initialized.");
        } else {
            conditionalWriteLog(logEnabled, "Cannot initialize log4j properly.");
        }

However, it end up the 2 two logger are logging the same thing. Every log is log to the 2 file identically. Why?

I think the configuration file is wrong probably, but I don't know where it is, can somebody help me to correct that?

Body:
You need to define those two loggers in your configuration file. Are those objects within a package? That is important to the way you will configure them. Say the package is com.gunbuster:

log4j.category.com.gunbuster.SearchPdfBill=INFO, SearchPdfBill
log4j.additivity.com.gunbuster.SearchPdfBill=false

log4j.category.com.gunbuster.Scheduler=INFO, Scheduler
log4j.additivity.com.gunbuster.Scheduler=false

The additivity setting is to prevent those loggers from adding to the rootLogger output to CONSOLE Also, you should make the first line:

log4j.rootLogger=INFO, CONSOLE

So that the rootLogger does not add entries into those files.


问:
How to check if external mp3 exists by catching the audio player behavior
When I embed and external mp3 file in my own website, if the target file was removed from the target server, the html5 player will be grayed out and the controls are disabled. How can I catch this event and show the availabilty of mp3 in other ways like a green or red check mark. As the file availabilty STATUS is visible on the browser I think there should be an event or a way to catch the final status. How can I can catch the availabilty status?

This is a sample code I am looking for but by  replacing the STATUS CHANGE and STATUS:

```<code><audio controls id="mymp3">
  <source src="http://example.com/1.mp3" type="audio/mpeg">
</audio>
</code>```

$("#mymp3").on("STATUS CHANGE", function() {
 if (STATUS) {
   $("#checkmark").attr("src","green.png");
 } else {
   $("#checkmark").attr("src","red.png");
 }
})
```

答:
You can check the existence of file using jQuery and head method.

```<code>$.ajax({
    url:'http://site/somefile.mp3',
    type:'HEAD',
    error: function() {
        // not exists
    },
    success: function() {
        // exists
    }
});
</code>```

Body:
When I embed and external mp3 file in my own website, if the target file was removed from the target server, the html5 player will be grayed out and the controls are disabled. How can I catch this event and show the availabilty of mp3 in other ways like a green or red check mark. As the file availabilty STATUS is visible on the browser I think there should be an event or a way to catch the final status. How can I can catch the availabilty status?

This is a sample code I am looking for but by  replacing the STATUS CHANGE and STATUS:

<audio controls id="mymp3">
  <source src="http://example.com/1.mp3" type="audio/mpeg">
</audio>

$("#mymp3").on("STATUS CHANGE", function() {
 if (STATUS) {
   $("#checkmark").attr("src","green.png");
 } else {
   $("#checkmark").attr("src","red.png");
 }
})

Body:
You can check the existence of file using jQuery and head method.

$.ajax({
    url:'http://site/somefile.mp3',
    type:'HEAD',
    error: function() {
        // not exists
    },
    success: function() {
        // exists
    }
});


问:
issue with javascript condition
I am fetching rank count from Html class and I want to show the result on base on rank count

there are 5 questions which  have these 4 options

which have Html like below

var $ = jQuery;
var rank = 0;
 var i;
var x = $(".que").toArray();
var length = x.length+1;
for (i = 1; i < length; i++) {

  var rank_count = ($('.que' + i).find(".selected_answer").attr("class").split(/\s+/));
  //var rank = parseInt(rank) + parseInt(rank_count[1].replace('rank_',''));

  if (i == 5 && rank_count[1] == 'rank_1') {
    rank = parseInt(16);
    //console.log(rank);
  } else {
    rank = parseInt(rank) + parseInt(rank_count[1].replace('rank_', ''));
    //
    console.log(rank);
  }

}
// if rank between 0-4 then show this
if (rank >= parseInt(0) && rank <= parseInt(4)) {
  $('.result').find(".blog1").css('display', 'flex');
}
// if rank between 5-8 then show this
if (rank >= parseInt(5) && rank <= parseInt(8)) {
  $('.result').find(".blog2").css('display', 'flex');
}
// if rank between 9-12 then show this
if (rank >= parseInt(9) && rank <= parseInt(12)) {
  $('.result').find(".blog3").css('display', 'flex');
}
// if rank between 13-16 then show this
if (rank >= parseInt(13) && rank <= parseInt(16)) {
  $('.result').find(".blog4").css('display', 'flex');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<p class="que1 que">question1</p>
<span class="answer rank_1">Simple Blog 1</span>
<span class="answer rank_2 selected_answer">Simple Blog 2</span>
<span class="answer rank_3">Simple Blog 3</span>
<span class="answer rank_4">Simple Blog 4</span>

<p class="que2 que">question2</p>
<span class="answer rank_1 selected_answer">Simple Blog 1</span>
<span class="answer rank_2">Simple Blog 2</span>
<span class="answer rank_3">Simple Blog 3</span>
<span class="answer rank_4">Simple Blog 4</span>

<p class="que3 que">question3</p>
<span class="answer rank_1">Simple Blog 1</span>
<span class="answer rank_2 selected_answer">Simple Blog 2</span>
<span class="answer rank_3">Simple Blog 3</span>
<span class="answer rank_4">Simple Blog 4</span>

<p class="que4 que">question4</p>
<span class="answer rank_1 selected_answer">Simple Blog 1</span>
<span class="answer rank_2">Simple Blog 2</span>
<span class="answer rank_3">Simple Blog 3</span>
<span class="answer rank_4">Simple Blog 4</span>

<p class="que5 que">question5</p>
<span class="answer rank_1 selected_answer">Simple Blog 1</span>
<span class="answer rank_2">Simple Blog 2</span>
<span class="answer rank_3">Simple Blog 3</span>
<span class="answer rank_4">Simple Blog 4</span></code>```

in this, I have set condition if que5 has selected answer rank_1 then set rank 16 else rank count as per selected answer.

but when I set the selected answer as per

```<code>if (i == 5 && rank_count[1] == 'rank_1')
    {
        rank = parseInt(16);
       console.log(rank);
    }else{
       rank = parseInt(rank) + parseInt(rank_count[1].replace('rank_',''));
       console.log(rank);
    }
</code>```

it is not showing proper result or showing 2 result blog3 or blog4

I don't know why is this happen

can anybody help me with this

答:
Changes are needed at three places.

1. define length variable as var length = $("p[class^='que']").length;

2. In HTML
  tag should end after all span elements, only then $('.que' + i).find(".selected_answer") will be able to find span with .selected_answer class

3. condition inside for loop should include <= so that it reaches till 5

//var $ = jQuery;
var rank = 0;
var length = $("p[class^='que']").length;

for (i = 1; i <= length; i++) {

  var rank_count = ($('.que' + i).find(".selected_answer").attr("class").split(/\s+/));
  //var rank = parseInt(rank) + parseInt(rank_count[1].replace('rank_',''));

  if (i == 5 && rank_count[1] == 'rank_1') {
    rank = parseInt(16);

    //console.log(rank);
  } else {
    rank = parseInt(rank) + parseInt(rank_count[1].replace('rank_', ''));
    //
    console.log(rank);
  }

}
alert(rank);
// if rank between 0-4 then show this
if (rank >= parseInt(0) && rank <= parseInt(4)) {
  $('.result').find(".blog1").css('display', 'flex');
}
// if rank between 5-8 then show this
if (rank >= parseInt(5) && rank <= parseInt(8)) {
  $('.result').find(".blog2").css('display', 'flex');
}
// if rank between 9-12 then show this
if (rank >= parseInt(9) && rank <= parseInt(12)) {
  $('.result').find(".blog3").css('display', 'flex');
}
// if rank between 13-16 then show this
if (rank >= parseInt(13) && rank <= parseInt(16)) {
  $('.result').find(".blog4").css('display', 'flex');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<p class="que1">question1
<span class="answer rank_1">Simple Blog 1</span>
<span class="answer rank_2 selected_answer">Simple Blog 2</span>
<span class="answer rank_3">Simple Blog 3</span>
<span class="answer rank_4">Simple Blog 4</span>
</p>

<p class="que2">question2
<span class="answer rank_1 selected_answer">Simple Blog 1</span>
<span class="answer rank_2">Simple Blog 2</span>
<span class="answer rank_3">Simple Blog 3</span>
<span class="answer rank_4">Simple Blog 4</span>
</p>
<p class="que3">question3
<span class="answer rank_1">Simple Blog 1</span>
<span class="answer rank_2 selected_answer">Simple Blog 2</span>
<span class="answer rank_3">Simple Blog 3</span>
<span class="answer rank_4">Simple Blog 4</span>
</p>
<p class="que4">question4
<span class="answer rank_1 selected_answer">Simple Blog 1</span>
<span class="answer rank_2">Simple Blog 2</span>
<span class="answer rank_3">Simple Blog 3</span>
<span class="answer rank_4">Simple Blog 4</span>
</p>
<p class="que5">question5
<span class="answer rank_1 selected_answer">Simple Blog 1</span>
<span class="answer rank_2">Simple Blog 2</span>
<span class="answer rank_3">Simple Blog 3</span>
<span class="answer rank_4">Simple Blog 4</span>
</p></code>```

Title: issue with javascript condition

Body:
I am fetching rank count from Html class and I want to show the result on base on rank count

there are 5 questions which  have these 4 options

which have Html like below

var $ = jQuery;
var rank = 0;
 var i;
var x = $(".que").toArray();
var length = x.length+1;
for (i = 1; i < length; i++) {

  var rank_count = ($('.que' + i).find(".selected_answer").attr("class").split(/\s+/));
  //var rank = parseInt(rank) + parseInt(rank_count[1].replace('rank_',''));

  if (i == 5 && rank_count[1] == 'rank_1') {
    rank = parseInt(16);
    //console.log(rank);
  } else {
    rank = parseInt(rank) + parseInt(rank_count[1].replace('rank_', ''));
    //
    console.log(rank);
  }

}
// if rank between 0-4 then show this
if (rank >= parseInt(0) && rank <= parseInt(4)) {
  $('.result').find(".blog1").css('display', 'flex');
}
// if rank between 5-8 then show this
if (rank >= parseInt(5) && rank <= parseInt(8)) {
  $('.result').find(".blog2").css('display', 'flex');
}
// if rank between 9-12 then show this
if (rank >= parseInt(9) && rank <= parseInt(12)) {
  $('.result').find(".blog3").css('display', 'flex');
}
// if rank between 13-16 then show this
if (rank >= parseInt(13) && rank <= parseInt(16)) {
  $('.result').find(".blog4").css('display', 'flex');
}

question1

Simple Blog 1
Simple Blog 2
Simple Blog 3
Simple Blog 4

question2

Simple Blog 1
Simple Blog 2
Simple Blog 3
Simple Blog 4

question3

Simple Blog 1
Simple Blog 2
Simple Blog 3
Simple Blog 4

question4

Simple Blog 1
Simple Blog 2
Simple Blog 3
Simple Blog 4

question5

Simple Blog 1
Simple Blog 2
Simple Blog 3
Simple Blog 4

in this, I have set condition if que5 has selected answer rank_1 then set rank 16 else rank count as per selected answer.

but when I set the selected answer as per

if (i == 5 && rank_count[1] == 'rank_1')
    {
        rank = parseInt(16);
       console.log(rank);
    }else{
       rank = parseInt(rank) + parseInt(rank_count[1].replace('rank_',''));
       console.log(rank);
    }

it is not showing proper result or showing 2 result blog3 or blog4

I don't know why is this happen

can anybody help me with this

Body:
Changes are needed at three places.

1. define length variable as var length = $("p[class^='que']").length;

2. In HTML < p >  tag should end after all span elements, only then $('.que' + i).find(".selected_answer") will be able to find span with .selected_answer class

3. condition inside for loop should include <= so that it reaches till 5

//var $ = jQuery;
var rank = 0;
var length = $("p[class^='que']").length;

for (i = 1; i <= length; i++) {

  var rank_count = ($('.que' + i).find(".selected_answer").attr("class").split(/\s+/));
  //var rank = parseInt(rank) + parseInt(rank_count[1].replace('rank_',''));

  if (i == 5 && rank_count[1] == 'rank_1') {
    rank = parseInt(16);

    //console.log(rank);
  } else {
    rank = parseInt(rank) + parseInt(rank_count[1].replace('rank_', ''));
    //
    console.log(rank);
  }

}
alert(rank);
// if rank between 0-4 then show this
if (rank >= parseInt(0) && rank <= parseInt(4)) {
  $('.result').find(".blog1").css('display', 'flex');
}
// if rank between 5-8 then show this
if (rank >= parseInt(5) && rank <= parseInt(8)) {
  $('.result').find(".blog2").css('display', 'flex');
}
// if rank between 9-12 then show this
if (rank >= parseInt(9) && rank <= parseInt(12)) {
  $('.result').find(".blog3").css('display', 'flex');
}
// if rank between 13-16 then show this
if (rank >= parseInt(13) && rank <= parseInt(16)) {
  $('.result').find(".blog4").css('display', 'flex');
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<p class="que1">question1
<span class="answer rank_1">Simple Blog 1</span>
<span class="answer rank_2 selected_answer">Simple Blog 2</span>
<span class="answer rank_3">Simple Blog 3</span>
<span class="answer rank_4">Simple Blog 4</span>
</p>

<p class="que2">question2
<span class="answer rank_1 selected_answer">Simple Blog 1</span>
<span class="answer rank_2">Simple Blog 2</span>
<span class="answer rank_3">Simple Blog 3</span>
<span class="answer rank_4">Simple Blog 4</span>
</p>
<p class="que3">question3
<span class="answer rank_1">Simple Blog 1</span>
<span class="answer rank_2 selected_answer">Simple Blog 2</span>
<span class="answer rank_3">Simple Blog 3</span>
<span class="answer rank_4">Simple Blog 4</span>
</p>
<p class="que4">question4
<span class="answer rank_1 selected_answer">Simple Blog 1</span>
<span class="answer rank_2">Simple Blog 2</span>
<span class="answer rank_3">Simple Blog 3</span>
<span class="answer rank_4">Simple Blog 4</span>
</p>
<p class="que5">question5
<span class="answer rank_1 selected_answer">Simple Blog 1</span>
<span class="answer rank_2">Simple Blog 2</span>
<span class="answer rank_3">Simple Blog 3</span>
<span class="answer rank_4">Simple Blog 4</span>
</p>


问:
Django ORM: How to use count method inside values_list method?
To simplify things, I need to perform this query:

 select state,count(*) from Airports group by state order by count(*) desc
```

<p>And the desired return from my query is a dictionary like this:</p>

<pre class="lang-py prettyprint-override"><code>{
 'state1': value1,
 'state2': value2,
 'state3': value3,
        ...
 'staten': valuen,
}
</code>```

I did some research and seems I need to use aggregate and annotate but I'm kinda lost in how to perform this with values_list().

Can I use count inside it like this?

Airport.objects.values_list('state', Airport.objects.count()).annotate('state').order_by(-Airport.objects.count())
```

答:
```<code>from django.db.models import Count

Airport.objects.values('state').annotate(count=Count('state')).order_by('-count')
</code>```

Body:
To simplify things, I need to perform this query:

 select state,count(*) from Airports group by state order by count(*) desc

And the desired return from my query is a dictionary like this:

{
 'state1': value1,
 'state2': value2,
 'state3': value3,
        ...
 'staten': valuen,
}

I did some research and seems I need to use aggregate and annotate but I'm kinda lost in how to perform this with values_list().

Can I use count inside it like this?

Airport.objects.values_list('state', Airport.objects.count()).annotate('state').order_by(-Airport.objects.count())


问:
My VB code appends two nodes instead of only one
I have the following XML file

<?xml version="1.0"?>
<Config>
    <ImgFileName>W10-00</ImgFileName>
    <Index>1</Index>
    <Diag>0</Diag>
</Config>
```

<p>And I want to add a new node 'CanSS' and make the value = '1'.</p>

<p>This is the code I am calling</p>

<pre class="lang-vb prettyprint-override"><code>Private Sub AddNode(ByVal CFGFile As String, ByVal Node As String, ByVal ValStr As String)
    Dim docXMLDOM As DOMDocument
    Dim nodeRoot As IXMLDOMElement
    Dim nodeNewElement As IXMLDOMElement

    ' Initialize the document model
    docXMLDOM = New DOMDocument

    ' Open the XML document
    docXMLDOM.load(CFGFile)

    ' Get a reference to the root node
    nodeRoot = docXMLDOM.documentElement

    nodeNewElement = docXMLDOM.createElement(Node)
    nodeNewElement.text = ValStr
    nodeRoot.appendChild(nodeNewElement)

    ' Save the file
    docXMLDOM.save(CFGFile)

    docXMLDOM = Nothing
End Sub
</code>```

which changes my XML to this

    <?xml version="1.0"?>
<Config>
    <ImgFileName>W10-00</ImgFileName>
    <Index>1</Index>
    <Diag>0</Diag>
<CanSS>1</CanSS><CanSS>1</CanSS></Config>
```

Can anyone see where I'm going wrong?

答: Thank you, everyone! Turns out that some code I was using to gain administrator privileges caused my app to run, close and re-run. I now use the app manifest to elevate privileges, my code only runs once and only one node is created! </p>

Body:
I have the following XML file

<?xml version="1.0"?>
<Config>
    <ImgFileName>W10-00</ImgFileName>
    <Index>1</Index>
    <Diag>0</Diag>
</Config>

And I want to add a new node 'CanSS' and make the value = '1'.

This is the code I am calling

Private Sub AddNode(ByVal CFGFile As String, ByVal Node As String, ByVal ValStr As String)
    Dim docXMLDOM As DOMDocument
    Dim nodeRoot As IXMLDOMElement
    Dim nodeNewElement As IXMLDOMElement

    ' Initialize the document model
    docXMLDOM = New DOMDocument

    ' Open the XML document
    docXMLDOM.load(CFGFile)

    ' Get a reference to the root node
    nodeRoot = docXMLDOM.documentElement

    nodeNewElement = docXMLDOM.createElement(Node)
    nodeNewElement.text = ValStr
    nodeRoot.appendChild(nodeNewElement)

    ' Save the file
    docXMLDOM.save(CFGFile)

    docXMLDOM = Nothing
End Sub

which changes my XML to this

    <?xml version="1.0"?>
<Config>
    <ImgFileName>W10-00</ImgFileName>
    <Index>1</Index>
    <Diag>0</Diag>
<CanSS>1</CanSS><CanSS>1</CanSS></Config>

Can anyone see where I'm going wrong?


问:
jquery selector problem
I'm using this code:

```<code>$('fieldset input[type=checkbox]').each(function () {if($(this).attr('checked','checked')){
    var switches = $(this).parent().find('.switch');
    $(switches).attr('state','on')
    $(switches).css({'left':"52px"});
    $(switches).parent().css({'background-position': "147px -37px"});
}})
</code>```

But somehow it sets all my checkboxes to checked="checked" Am I just stupid or is something else in the code interfering?

Thanks for your help :)

EDIT:
here is the HTML

```<code><fieldset>
        <input checked="checked" />
        <label></label>
        <div class="toggle_box">
            <div class="switch" state="on"></div>
        </div>
    </fieldset>
    <fieldset>
        <input/>
        <label></label>
        <div class="toggle_box">
            <div class="switch"></div>
        </div>
    </fieldset>
</code>```

答:
There is actually a selector specifically for the checked boxes.

```<code>$('fieldset input[type=checkbox]:checked').each(function(){
    var switches = $(this).parent().find('.switch');
    $(switches).attr('state','on')
    $(switches).css({'left':'52px'});
    $(switches).parent().css({'background-position':'147px -37px'});
});
</code>```

If you use that you won't have to do any of that logic by yourself.

Title: jquery selector problem

Body:
I'm using this code:

$('fieldset input[type=checkbox]').each(function () {if($(this).attr('checked','checked')){
    var switches = $(this).parent().find('.switch');
    $(switches).attr('state','on')
    $(switches).css({'left':"52px"});
    $(switches).parent().css({'background-position': "147px -37px"});
}})

But somehow it sets all my checkboxes to checked="checked" Am I just stupid or is something else in the code interfering?

Thanks for your help :)

EDIT:
here is the HTML

<fieldset>
        <input checked="checked" />

    </fieldset>
    <fieldset>
        <input/>

    </fieldset>

Body:
There is actually a selector specifically for the checked boxes.

$('fieldset input[type=checkbox]:checked').each(function(){
    var switches = $(this).parent().find('.switch');
    $(switches).attr('state','on')
    $(switches).css({'left':'52px'});
    $(switches).parent().css({'background-position':'147px -37px'});
});

If you use that you won't have to do any of that logic by yourself.


问:
Add new object based on key:value
I have an object, I want to add a new object before each object based on did value. What I tried is below, but it not what I want, it add for each item, and also it turned into array.

let obj = {
  "district": [{
      "id": 1,
      "uid": 1,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 1,
      "name": "text 1"
    },
    {
      "id": 2,
      "uid": 2,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 2,
      "name": "text 2"
    },
    {
      "id": 3,
      "uid": 3,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 2,
      "name": "text 3"
    },
    {
      "id": 4,
      "uid": 4,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 3,
      "name": "text 4"
    },
    {
      "id": 5,
      "uid": 5,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 3,
      "name": "text 5"
    },
    {
      "id": 6,
      "uid": 6,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 0, // should not add object before this becaus did is 0
      "name": "text 6"
    }
  ]
}

var result = obj.district.map(function(el) {
if(el.did > 0){
  var o = Object.assign({}, obj.district);
  o.divider = {
    "dv": true,
    "name": 'divider ' + el.did
  };
  return o;
}
})

console.log(result)```
</div>
</div>
</p>

<p>Add new object if <code>did</code> value is not null or 0, kinda > 0. the result should be like this:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let obj = {
  "district": [{
      "dv": true,
      "name": "divider 1"
    }, {
      "id": 1,
      "uid": 1,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 1,
      "name": "text 1"
    },
    {
      "dv": true,
      "name": "divider 2"
    },
    {
      "id": 2,
      "uid": 2,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 2,
      "name": "text 2"
    },
    {
      "id": 3,
      "uid": 3,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 2,
      "name": "text 3"
    },
    {
      "dv": true,
      "name": "divider 3"
    },
    {
      "id": 4,
      "uid": 4,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 3,
      "name": "text 4"
    },
    {
      "id": 5,
      "uid": 5,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 3,
      "name": "text 5"
    },
    {
      "id": 6,
      "uid": 6,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 0, // should not add object before this becaus did is 0
      "name": "text 6"
    }
  ]
}

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

It should add before object with common did id, for example if there is 5 item with did 2, it should just add new object once, not for each item. also name of new value should be based on did id, divider 1, divider 2 or ..

答:
Try this:

var lastDivider;
var result = {
  district: []
}

obj.district.forEach(function(el) {
  if (el.did > 0 && lastDivider !== el.did) {
    result.district.push({
      "dv": true,
      "name": 'divider ' + el.did
    });
    lastDivider = el.did;
  }
  result.district.push([Object.assign({}, el)]);
});
```

Title: Add new object based on key:value

Body:
I have an object, I want to add a new object before each object based on did value. What I tried is below, but it not what I want, it add for each item, and also it turned into array.

let obj = {
  "district": [{
      "id": 1,
      "uid": 1,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 1,
      "name": "text 1"
    },
    {
      "id": 2,
      "uid": 2,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 2,
      "name": "text 2"
    },
    {
      "id": 3,
      "uid": 3,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 2,
      "name": "text 3"
    },
    {
      "id": 4,
      "uid": 4,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 3,
      "name": "text 4"
    },
    {
      "id": 5,
      "uid": 5,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 3,
      "name": "text 5"
    },
    {
      "id": 6,
      "uid": 6,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 0, // should not add object before this becaus did is 0
      "name": "text 6"
    }
  ]
}

var result = obj.district.map(function(el) {
if(el.did > 0){
  var o = Object.assign({}, obj.district);
  o.divider = {
    "dv": true,
    "name": 'divider ' + el.did
  };
  return o;
}
})

console.log(result)

Add new object if did value is not null or 0, kinda > 0. the result should be like this:

let obj = {
  "district": [{
      "dv": true,
      "name": "divider 1"
    }, {
      "id": 1,
      "uid": 1,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 1,
      "name": "text 1"
    },
    {
      "dv": true,
      "name": "divider 2"
    },
    {
      "id": 2,
      "uid": 2,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 2,
      "name": "text 2"
    },
    {
      "id": 3,
      "uid": 3,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 2,
      "name": "text 3"
    },
    {
      "dv": true,
      "name": "divider 3"
    },
    {
      "id": 4,
      "uid": 4,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 3,
      "name": "text 4"
    },
    {
      "id": 5,
      "uid": 5,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 3,
      "name": "text 5"
    },
    {
      "id": 6,
      "uid": 6,
      "type": 3,
      "pid": 0,
      "cid": 0,
      "did": 0, // should not add object before this becaus did is 0
      "name": "text 6"
    }
  ]
}

console.log(obj)

It should add before object with common did id, for example if there is 5 item with did 2, it should just add new object once, not for each item. also name of new value should be based on did id, divider 1, divider 2 or ..


问:
Find two closest numbers to zero in given array in Java Script
Is there any better solution than these(Solution 1 and Solution 2 )? Can you please suggest.

Solution 1:

var arr = [2, 5.5, -3, 10, -1, 1.5];

let min1 = arr[0],
  min2 = arr[1];

for (let i = 2; i < arr.length; i++) {
  if (Math.abs(arr[i]) < Math.abs(min1)) {
    min1 = arr[i];

  }
  if (Math.abs(min2) > Math.abs(min1)) {
    let temp = min2;
    min2 = min1;
    min1 = temp;
  }
}

console.log("Closest numbers to Zero = " + min1 + ", " + min2);```
</div>
</div>
</p>

<p><strong>Solution 2:</strong> </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = [2, 5.5, -3, 10, -1, 1.5];
arr.sort((a, b) => Math.abs(a) - Math.abs(b));
console.log("Closest numbers to Zero = " + arr[0] + ", " + arr[1]);</code>```

Body:
Is there any better solution than these(Solution 1 and Solution 2 )? Can you please suggest.

Solution 1:

var arr = [2, 5.5, -3, 10, -1, 1.5];

let min1 = arr[0],
  min2 = arr[1];

for (let i = 2; i < arr.length; i++) {
  if (Math.abs(arr[i]) < Math.abs(min1)) {
    min1 = arr[i];

  }
  if (Math.abs(min2) > Math.abs(min1)) {
    let temp = min2;
    min2 = min1;
    min1 = temp;
  }
}

console.log("Closest numbers to Zero = " + min1 + ", " + min2);

Solution 2:

var arr = [2, 5.5, -3, 10, -1, 1.5];
arr.sort((a, b) => Math.abs(a) - Math.abs(b));
console.log("Closest numbers to Zero = " + arr[0] + ", " + arr[1]);

Body:
Another approach could be:

var arr = [2, 5.5, -3, 10, -1, 1.5];
arr.push(0);
arr.sort();// [-1, -3, 0, 1.5, 10, 2, 5.5]
num1 = arr[arr.indexOf(0)-1];//-3
num2 = arr[arr.indexOf(0)+1];//1.5


问:
Get the username with django profileserializer
I developed api with django. I created a code structure like below.
How do I get the user's first_name and last_name in class ProfileSerializer?

that is, with ProfileSerializer, I want to get information such as the user's name, surname, id number

``

```<code>from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from rest_framework.serializers import ModelSerializer, Serializer
from rest_framework import serializers
from account.models import Profile

class ProfileSerializer(ModelSerializer):

    class Meta:
        model = Profile
        fields = ('id', 'userKey', 'phone', 'email', 'address', 'userState')

class UserSerializer(ModelSerializer):
    profile = ProfileSerializer()

    class Meta:
        model = User
        fields = ('id', 'first_name', 'last_name', 'profile')

    def update(self, instance, validated_data):
        profile = validated_data.pop('profile')
        profile_serializer = ProfileSerializer(instance=instance.profile, data=profile)
        profile_serializer.is_valid(raise_exception=True)
        profile_serializer.save()
        return super(UserSerializer, self).update(instance, validated_data)
</code>```

``

答:
Just change your serializer like this</p>

```<code>class ProfileSerializer(ModelSerializer):

    class Meta:
        model = Profile
        fields = ('id', 'userKey', 'phone', 'email', 'address', 'userState')

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data.update({'username': instance.userKey.username, 'first_name': instance.userKey.first_name, 'last_name': instance.userKey.last_name})
        return data
</code>```

Body:
I developed api with django. I created a code structure like below.
How do I get the user's first_name and last_name in class ProfileSerializer?

that is, with ProfileSerializer, I want to get information such as the user's name, surname, id number

``

from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from rest_framework.serializers import ModelSerializer, Serializer
from rest_framework import serializers
from account.models import Profile

class ProfileSerializer(ModelSerializer):

    class Meta:
        model = Profile
        fields = ('id', 'userKey', 'phone', 'email', 'address', 'userState')

class UserSerializer(ModelSerializer):
    profile = ProfileSerializer()

    class Meta:
        model = User
        fields = ('id', 'first_name', 'last_name', 'profile')

    def update(self, instance, validated_data):
        profile = validated_data.pop('profile')
        profile_serializer = ProfileSerializer(instance=instance.profile, data=profile)
        profile_serializer.is_valid(raise_exception=True)
        profile_serializer.save()
        return super(UserSerializer, self).update(instance, validated_data)

``

Body:
Just change your serializer like this

class ProfileSerializer(ModelSerializer):

    class Meta:
        model = Profile
        fields = ('id', 'userKey', 'phone', 'email', 'address', 'userState')

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data.update({'username': instance.userKey.username, 'first_name': instance.userKey.first_name, 'last_name': instance.userKey.last_name})
        return data


问:
"Layout" folder not appearing in "res" folder
Recently I installed android studio and wanted to create a map, selected java language instead of kotlin.

As I was following a guide on internet,
https://developers.arcgis.com/android/latest/guide/install-and-set-up.htm

it said to select "Main_activity.xml" in res->layout.
But I couldn't find any layout folder.

Here's the image of my project view:Android Project View

Thank You

答:
From your "Android Project View"
In Java folder, you can see  three "com.ecample.hackathon" folders, among these three folders first one is blank, when we create any Activity in our project, java class show at here, and xml file show in layout folder(parent is res folder).

So now, you have to create Activity.

Steps:

1) Right click on this empty folder "com.ecample.hackathon"

2) Select New

3) Than  Select Activity

4) As per your choice you can select the option.
   Ex. Select "Empty Activity

Name as according your use.
You can get java and xml file in proper place.
Hope this help you.


问:
How to create a reusable Map
Is there a way to populate a Map once from the DB (through Mongo repository) data and reuse it when required from multiple classes instead of hitting the Database through the repository.</p>

答:
Premise: I suggest you to use an object-relational mapping tool like Hibernate on your java project to map the object-oriented
  domain model to a relational database and let the tool handle the
  cache mechanism implicitally. Hibernate specifically implements a multi-level
  caching scheme ( take a look at the following link to get more
  informations:
  https://www.tutorialspoint.com/hibernate/hibernate_caching.htm )

Regardless my suggestion on premise you can also manually create a singleton class that will be used from every class in the project that goes to interact with the DB:

```<code>public class MongoDBConnector {

    private static final Logger LOGGER = LoggerFactory.getLogger(MongoDBConnector.class);

    private static MongoDBConnector instance;

    //Cache period in seconds
    public static int DB_ELEMENTS_CACHE_PERIOD = 30;

    //Latest cache update time
    private DateTime latestUpdateTime;

    //The cache data layer from DB
    private Map<KType,VType> elements;

    private MongoDBConnector() {
    }

    public static synchronized MongoDBConnector getInstance() {
        if (instance == null) {
            instance = new MongoDBConnector();
        }
        return instance;
    }

}
</code>```

Here you can define then a load method that goes to update the map with values stored on the DB and also a write method that instead goes to write values on the DB with the following characteristics:

1- These methods should be synchronized in order to avoid issues if multiple calls are performed.

2- The load method should apply a cache period logic ( maybe with period configurable ) to avoid to load for each method call the data from the DB.

Example: Suppose your cache period is 30s. This means that if 10 read are performed from different points of the code within 30s you
  will load data from DB only on the first call while others will read
  from cached map improving the performance.

Note: The greater is the cache period the more is the performance of your code but if the DB is managed you'll create inconsistency
  with cache if an insertion is performed externally ( from another tool
  or manually ). So choose the best value for you.

```<code>public synchronized Map<KType, VType> getElements() throws ConnectorException {
   final DateTime currentTime = new DateTime();
   if (latestUpdateTime == null || (Seconds.secondsBetween(latestUpdateTime, currentTime).getSeconds() > DB_ELEMENTS_CACHE_PERIOD)) {
       LOGGER.debug("Cache is expired. Reading values from DB");
       //Read from DB and update cache
       //....

       sampleTime = currentTime;
   }
  return elements;
}

</code>```

3- The store method should automatically update the cache if insert is performed correctly regardless the cache period is expired:

```<code>public synchronized void storeElement(final VType object) throws ConnectorException {
  //Insert object on DB ( throws a ConnectorException if insert fails )
  //...

  //Update cache regardless the cache period
  loadElementsIgnoreCachePeriod();
}
</code>```

Then you can get elements from every point in your code as follow:

```<code>Map<KType,VType> liveElements = MongoDBConnector.getElements();
</code>```

Title: How to create a reusable Map

Body:
Premise: I suggest you to use an object-relational mapping tool like Hibernate on your java project to map the object-oriented
  domain model to a relational database and let the tool handle the
  cache mechanism implicitally. Hibernate specifically implements a multi-level
  caching scheme ( take a look at the following link to get more
  informations:
  https://www.tutorialspoint.com/hibernate/hibernate_caching.htm )

Regardless my suggestion on premise you can also manually create a singleton class that will be used from every class in the project that goes to interact with the DB:

public class MongoDBConnector {

    private static final Logger LOGGER = LoggerFactory.getLogger(MongoDBConnector.class);

    private static MongoDBConnector instance;

    //Cache period in seconds
    public static int DB_ELEMENTS_CACHE_PERIOD = 30;

    //Latest cache update time
    private DateTime latestUpdateTime;

    //The cache data layer from DB
    private Map<KType,VType> elements;

    private MongoDBConnector() {
    }

    public static synchronized MongoDBConnector getInstance() {
        if (instance == null) {
            instance = new MongoDBConnector();
        }
        return instance;
    }

}

Here you can define then a load method that goes to update the map with values stored on the DB and also a write method that instead goes to write values on the DB with the following characteristics:

1- These methods should be synchronized in order to avoid issues if multiple calls are performed.

2- The load method should apply a cache period logic ( maybe with period configurable ) to avoid to load for each method call the data from the DB.

Example: Suppose your cache period is 30s. This means that if 10 read are performed from different points of the code within 30s you
  will load data from DB only on the first call while others will read
  from cached map improving the performance.

Note: The greater is the cache period the more is the performance of your code but if the DB is managed you'll create inconsistency
  with cache if an insertion is performed externally ( from another tool
  or manually ). So choose the best value for you.

public synchronized Map<KType, VType> getElements() throws ConnectorException {
   final DateTime currentTime = new DateTime();
   if (latestUpdateTime == null || (Seconds.secondsBetween(latestUpdateTime, currentTime).getSeconds() > DB_ELEMENTS_CACHE_PERIOD)) {
       LOGGER.debug("Cache is expired. Reading values from DB");
       //Read from DB and update cache
       //....

       sampleTime = currentTime;
   }
  return elements;
}

3- The store method should automatically update the cache if insert is performed correctly regardless the cache period is expired:

public synchronized void storeElement(final VType object) throws ConnectorException {
  //Insert object on DB ( throws a ConnectorException if insert fails )
  //...

  //Update cache regardless the cache period
  loadElementsIgnoreCachePeriod();
}

Then you can get elements from every point in your code as follow:

Map<KType,VType> liveElements = MongoDBConnector.getElements();


问:
Difference between Fortran 90 and Fortran 95
Can I compile Fortran 90 files with a Fortran 95 compiler?   There seems to be a lot for Fortran 95 but not Fortran 90.</p>

答:
Yes, you can compile Fortran 90 programs with a Fortran 95 compiler.    Actually, most of the compilers out there are now largely but not totally compliant with Fortran 2003.   Unless you have unusual requirements, you are better off with a Fortran 95/2003/2008 compiler rather than a Fortran 90 only one. Fortran 95 is somewhat of a "bug fix" to Fortran 90 ... it was a modest update based upon the experience with actually using Fortran 90, which was a huge change from Fortran 77.  For example, it is easier to have memory leaks in Fortran 90 ... in Fortran 95 local allocatable variables must be automatically deallocated upon exit from a subroutine so the programmer doesn't have to explicitly do the deallocation.   In Fortran 90, if the deallocation wasn't explicitly coded, a memory leak was allowed to occur.

For a free compiler, recent versions of gfortran are quite good.


问:
EditText to restrict entering special characters: single quote, double quote and emojis
I have a problem while inserting special characters: single quote, double quote and emojis into the database from editText.

I want my editText to restrict those characters, and I was successful in restricting emojis, but I failed to restrict users entering single quote and double quote.

E.g. When I try to enter text Today's List from editText into the database it generates an exception.

I have used InputFilter in editText to filter emojis, and I want this filter to restrict single quote and double quotes too.

```<code>public static InputFilter getEditTextFilterEmoji() {
    return new InputFilter() {

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

            CharSequence sourceOriginal = source;
            source = replaceEmoji(source);
            end = source.toString().length();

            if (end == 0)
                return ""; //Return empty string if the input character is already removed

            if (!sourceOriginal.toString().equals(source.toString())) {
                char[] v = new char[end - start];
                TextUtils.getChars(source, start, end, v, 0);

                String s = new String(v);

                if (source instanceof Spanned) {
                    SpannableString sp = new SpannableString(s);
                    TextUtils.copySpansFrom((Spanned) source, start, end, null, sp, 0);
                    return sp;
                } else {
                    return s;
                }
            } else {
                return null; // keep original
            }
        }

        private String replaceEmoji(CharSequence source) {

            String notAllowedCharactersRegex = "[^a-zA-Z0-9@#\\$%\\&\\-\\+\\(\\)\\*;:!\\?\\~`£\\{\\}\\[\\]=\\.,_/\\\\\\s'\\\"<>\\^\\|÷×]";
            return source.toString()
                    .replaceAll(notAllowedCharactersRegex, "");
        }
    };
}
</code>```

Can anyone help me with this ?

答:
As per my understanding all emoji contains /u so I used it like this

```<code>public static InputFilter[] getEmojiFilter(String blockChars) {
    return new InputFilter[]{(source, start, end, dest, dstart, dend) -> {
        String source1= StringEscapeUtils.escapeJava(source.toString());
        for (int i = start; i < end; i++) {
            if (source != null && blockChars.contains("" + source1.charAt(i))) {
                return source.subSequence(start, i);
            }
        }
        return null;
    }};
}
</code>```

and Write below line for Edittext

```<code>editext.setFilters(getEmojiFilter("'\"\\//\\u"));
</code>```

Body:
I have a problem while inserting special characters: single quote, double quote and emojis into the database from editText.

I want my editText to restrict those characters, and I was successful in restricting emojis, but I failed to restrict users entering single quote and double quote.

E.g. When I try to enter text Today's List from editText into the database it generates an exception.

I have used InputFilter in editText to filter emojis, and I want this filter to restrict single quote and double quotes too.

public static InputFilter getEditTextFilterEmoji() {
    return new InputFilter() {

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

            CharSequence sourceOriginal = source;
            source = replaceEmoji(source);
            end = source.toString().length();

            if (end == 0)
                return ""; //Return empty string if the input character is already removed

            if (!sourceOriginal.toString().equals(source.toString())) {
                char[] v = new char[end - start];
                TextUtils.getChars(source, start, end, v, 0);

                String s = new String(v);

                if (source instanceof Spanned) {
                    SpannableString sp = new SpannableString(s);
                    TextUtils.copySpansFrom((Spanned) source, start, end, null, sp, 0);
                    return sp;
                } else {
                    return s;
                }
            } else {
                return null; // keep original
            }
        }

        private String replaceEmoji(CharSequence source) {

            String notAllowedCharactersRegex = "[^a-zA-Z0-9@#\\$%\\&\\-\\+\\(\\)\\*;:!\\?\\~`£\\{\\}\\[\\]=\\.,_/\\\\\\s'\\\"<>\\^\\|÷×]";
            return source.toString()
                    .replaceAll(notAllowedCharactersRegex, "");
        }
    };
}

Can anyone help me with this ?

Body:
As per my understanding all emoji contains /u so I used it like this

public static InputFilter[] getEmojiFilter(String blockChars) {
    return new InputFilter[]{(source, start, end, dest, dstart, dend) -> {
        String source1= StringEscapeUtils.escapeJava(source.toString());
        for (int i = start; i < end; i++) {
            if (source != null && blockChars.contains("" + source1.charAt(i))) {
                return source.subSequence(start, i);
            }
        }
        return null;
    }};
}

and Write below line for Edittext

editext.setFilters(getEmojiFilter("'\"\\//\\u"));