问:
Here Maps Geocode API leads to Cross-Origin error
I use the first example here in order to get the geo coordinates based on an address:
https://developer.here.com/documentation/maps/3.1.15.1/dev_guide/topics/geocoding.html

My JavaScript coding looks almost the same as in the official documentation:

```<code>var platform = new H.service.Platform({
  'apikey': 'HERE IS MY API KEY'
});

// Get an instance of the geocoding service:
var service = platform.getSearchService();

service.geocode({
  q: 'Berlin'
}, (result) => {
  result.items.forEach((item) => {
    console.log("test");
  });
}, alert);
</code>```

However, when the geocode request is sent, I get the following error:

```<code>Access to XMLHttpRequest at '**https://geocode.search.hereapi.com/v1/geocode?xnlp=CL_JSMv3.1.16.1&apikey=[HERE IS MY API KEY]&q=Berlin**' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

The API key is sent correctly, why do I still get the CORS error?
If I enter the request URL manually in the browser, I get a response and everything is fine.

答:
Yes, the server will help with the issue. I'm here to suggest the alternative.

You can do the geocoding with the HERE Maps REST as well see docs — https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics/endpoint-geocode-brief.html.

Since not all the browsers historically support the CORS (learn more about the CORS — https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) there is an approach, called JSONP. See some JSONP explanation Here Maps related in the old docs https://developer.here.com/documentation/places/dev_guide/topics/request-cross-domain-js.html.

Eventually the https://www.npmjs.com/package/jsonp npm package could be a good follow up and we can get something like this after installing the package (npm install jsonp --save).

import jsonp from 'jsonp';

jsonp('https://geocode.search.hereapi.com/v1/geocode?q=5+Rue+Daunou%2C+75000+Paris%2C+France&apiKey=my-api-key',
null,
(err, data) => {
  if (err) {
    console.error(err.message);
  } else {
    console.log(data);
  }
});

```

This works great from my experience.

Body:
I use the first example here in order to get the geo coordinates based on an address:
https://developer.here.com/documentation/maps/3.1.15.1/dev_guide/topics/geocoding.html

My JavaScript coding looks almost the same as in the official documentation:

var platform = new H.service.Platform({
  'apikey': 'HERE IS MY API KEY'
});

// Get an instance of the geocoding service:
var service = platform.getSearchService();

service.geocode({
  q: 'Berlin'
}, (result) => {
  result.items.forEach((item) => {
    console.log("test");
  });
}, alert);

However, when the geocode request is sent, I get the following error:

Access to XMLHttpRequest at '**https://geocode.search.hereapi.com/v1/geocode?xnlp=CL_JSMv3.1.16.1&apikey=[HERE IS MY API KEY]&q=Berlin**' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The API key is sent correctly, why do I still get the CORS error?
If I enter the request URL manually in the browser, I get a response and everything is fine.

Body:
Yes, the server will help with the issue. I'm here to suggest the alternative.

You can do the geocoding with the HERE Maps REST as well see docs — https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics/endpoint-geocode-brief.html.

Since not all the browsers historically support the CORS (learn more about the CORS — https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) there is an approach, called JSONP. See some JSONP explanation Here Maps related in the old docs https://developer.here.com/documentation/places/dev_guide/topics/request-cross-domain-js.html.

Eventually the https://www.npmjs.com/package/jsonp npm package could be a good follow up and we can get something like this after installing the package (npm install jsonp --save).

import jsonp from 'jsonp';

jsonp('https://geocode.search.hereapi.com/v1/geocode?q=5+Rue+Daunou%2C+75000+Paris%2C+France&apiKey=my-api-key',
null,
(err, data) => {
  if (err) {
    console.error(err.message);
  } else {
    console.log(data);
  }
});

This works great from my experience.


来源: stackexchange

问:
How to change date format in cypress
Scenario:

I have a data_value in field input_date as: 30/06/2020 13:40
How can I test another div contains the same value in another format - 23rd June 2020 13:40

```<code>const inp_date = cy.get('input_date').invoke('val')
cy.get('div').should('contain', inp_date)
</code>```

How will I format inp_date so that it is in the format 23rd June 2020 13:40

NOTE:  input_date and  are in two different pages. Means, When I am in the page where I need to test the div, input will not be available

答:
Refer: Cypress includes moment.js

I have used Cypress.env to transfer data between pages for validation.

Page 1:

Markup:

```<code><input type="text" id="input_date" value="30/06/2020 13:40" />
</code>```

Page 2:

Markup:

```<code><div>23rd June 2020 13:40</div>
<div>30th June 2020 13:40</div>
</code>```

Test:

```<code>cy.get('#input_date').then(($el) => {
    return new Cypress.Promise((resolve, reject) => {
        const formattedDate = Cypress.moment($el.val(), 'DD/MM/YYYY HH:mm').format('Do MMMM YYYY HH:mm');
        if (formattedDate) {
            resolve(formattedDate);
        } else {
            reject(0); // handle reject;
        }
    })
}).then(formattedDate => {
    Cypress.env('inputDate', formattedDate);
    cy.log('created new user on ' + Cypress.env('inputDate'));
});

cy.wait(0);
cy.log('created new user on ' + Cypress.env('inputDate'));
cy.wait(1000);
cy.log('created new user on ' + Cypress.env('inputDate'));
cy.visit('http://localhost:8081/page2');
cy.get('div').should('contain', Cypress.env('inputDate'));
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to change date format in cypress

Body:
Scenario:

I have a data_value in field input_date as: 30/06/2020 13:40
How can I test another div contains the same value in another format - 23rd June 2020 13:40

const inp_date = cy.get('input_date').invoke('val')
cy.get('div').should('contain', inp_date)

How will I format inp_date so that it is in the format 23rd June 2020 13:40

NOTE:  input_date and  are in two different pages. Means, When I am in the page where I need to test the div, input will not be available

Body:
Refer: Cypress includes moment.js

I have used Cypress.env to transfer data between pages for validation.

Page 1:

Markup:

<input type="text" id="input_date" value="30/06/2020 13:40" />

Page 2:

Markup:

<div>23rd June 2020 13:40</div>
<div>30th June 2020 13:40</div>

Test:

cy.get('#input_date').then(($el) => {
    return new Cypress.Promise((resolve, reject) => {
        const formattedDate = Cypress.moment($el.val(), 'DD/MM/YYYY HH:mm').format('Do MMMM YYYY HH:mm');
        if (formattedDate) {
            resolve(formattedDate);
        } else {
            reject(0); // handle reject;
        }
    })
}).then(formattedDate => {
    Cypress.env('inputDate', formattedDate);
    cy.log('created new user on ' + Cypress.env('inputDate'));
});

cy.wait(0);
cy.log('created new user on ' + Cypress.env('inputDate'));
cy.wait(1000);
cy.log('created new user on ' + Cypress.env('inputDate'));
cy.visit('http://localhost:8081/page2');
cy.get('div').should('contain', Cypress.env('inputDate'));


问:
Split a string ignoring quoted sections
Given a string like this:

a,"string, with",various,"values, and some",quoted

What is a good algorithm to split this based on commas while ignoring the commas inside the quoted sections?

The output should be an array:

[ "a", "string, with", "various", "values, and some", "quoted" ]

答:
Of course using a CSV parser is better but just for the fun of it you could:</p>

```<code>Loop on the string letter by letter.
    If current_letter == quote :
        toggle inside_quote variable.
    Else if (current_letter ==comma and not inside_quote) :
        push current_word into array and clear current_word.
    Else
        append the current_letter to current_word
When the loop is done push the current_word into array
</code>```

OwnerDisplayName: Jason

LastEditorDisplayName: Nickolay

ContentLicense: CC BY-SA 2.5

Title: Split a string ignoring quoted sections

Body:
Of course using a CSV parser is better but just for the fun of it you could:

Loop on the string letter by letter.
    If current_letter == quote :
        toggle inside_quote variable.
    Else if (current_letter ==comma and not inside_quote) :
        push current_word into array and clear current_word.
    Else
        append the current_letter to current_word
When the loop is done push the current_word into array

LastEditorDisplayName: Pat


问:
How can I find the current DNS server?
I'm using Delphi and need to get the current Windows DNS server IP address so I can do a lookup. What function should I call to find it? The only solution I have right now does an ipconfig/all to get it, which is horrible.</p>

答:
Found a nice one using the function GetNetworkParams().Seems to work quite good.
You can find it here:
http://www.swissdelphicenter.ch/torry/showcode.php?id=2452</p>

Title: How can I find the current DNS server?

LastEditorDisplayName: Nick Berardi

OwnerDisplayName: DubCee


问:
Schedule Controls for ASP.Net MVC
Are there any scheduling components, commercial or otherwise, for ASP.Net MVC?  Our company currently uses the Infragistics WebSchedule controls, but they don't appear to support MVC.

Edit:
I think I may have been a bit unclear, I am not looking for a task scheduler, rather I am looking for a web calendar/appointment/schedule management framework or component set.  Something that would include a Month/Week/Day view of a calendar and allow me to create and display appointment items.

A framework that would let me build something like Google calendar, except the appointments would be stored in my database, not Googles.

答: Take a look at Keyvan Nayyeri's Abidar 1.0: http://nayyeri.net/blog/abidar-1.0-beta-1/</p>

ContentLicense: CC BY-SA 3.0

Title: Schedule Controls for ASP.Net MVC

OwnerDisplayName: Mahdi


问:
Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
What might be causing the error Error: EACCES: permission denied, access '/usr/local/lib/node_modules'?

```<code>npm ERR! path /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR!  { Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/macbookmd101/.npm/_logs/2018-02-21T16_26_08_421Z-debug.log
</code>```

答: Just add "sudo" before npm command. Thats it.</p>

Body:
What might be causing the error Error: EACCES: permission denied, access '/usr/local/lib/node_modules'?

npm ERR! path /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR!  { Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/macbookmd101/.npm/_logs/2018-02-21T16_26_08_421Z-debug.log


问:
Why is tqdm printing to a newline instead of updating the same line?
I'm working on a small command-line game in python where I am showing a progress bar using the tqdm module. I listen for user input using the msvcrt module to interrupt the progress. Once interrupted, the user can restart by entering 'restart' into the command line prompt. The second time the progress bar is shown, instead of updating the same line with the progress, it creates a new line each time.

How would I get it to show the progress on the same line?

This code snippet illustrates my use of the progress bar.

```<code>def transfer():
    for i in tqdm.tqdm(range(1000), desc="Transfer progress", ncols=100, bar_format='{l_bar}{bar}|'):
        sleep(.1)
        if msvcrt.kbhit():
            if msvcrt.getwche() == ' ':
                interrupt()
                break

def interrupt():
    type("File transfer interrupted, to restart the transfer, type 'restart'")
</code>```

答:
from tqdm import notebook

Instead of tqdm(looping)

Use notebook.tqdm(looping)

Body:
I'm working on a small command-line game in python where I am showing a progress bar using the tqdm module. I listen for user input using the msvcrt module to interrupt the progress. Once interrupted, the user can restart by entering 'restart' into the command line prompt. The second time the progress bar is shown, instead of updating the same line with the progress, it creates a new line each time.

How would I get it to show the progress on the same line?

This code snippet illustrates my use of the progress bar.

def transfer():
    for i in tqdm.tqdm(range(1000), desc="Transfer progress", ncols=100, bar_format='{l_bar}{bar}|'):
        sleep(.1)
        if msvcrt.kbhit():
            if msvcrt.getwche() == ' ':
                interrupt()
                break

def interrupt():
    type("File transfer interrupted, to restart the transfer, type 'restart'")


问:
how to find user input value in the dictionary and display them, if it exists
```<code>MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: "
movies = []

# And another function here for the user menu
selection = input(MENU_PROMPT)

def movie_data():
    title = input("Enter the movie title: ")
    director = input("Enter the movie director: ")
    year = input("Enter the movie release year: ")

    movies.append({
        'title': title,
        'director': director,
        'year': year
    })

def display():
    print("movies =", end =" ")
    for movie in movies:
        print(movie['title'])

while selection != 'q':
    if selection == "a":
        movie_data()
    elif selection == "l":
        display()
    elif selection == "f":
        find = input("enter the movie title")
        if find in movies:
            print("movie found.", movies)
        else:
            print(f'No Such Movie, Named {find}, Found!, Try Other Movie Name.')
    else:
        print('Unknown command. Please try again.')

    selection = input(MENU_PROMPT)

</code>```

if the user inputs the f for finding the movie name in the movies dictionary then what do I write in the last elif function, can anyone explain it??

I want - (userinput movie name) - avengers
output - match found! movie name - avengers, director - (what the userinputs) & year - (what the userinputs)

答:
You can make a search function which iterates over each element in the list and searches for the title attribute in dictionary.   </p>

```<code>MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: "
movies = []

# And another function here for the user menu
selection = input(MENU_PROMPT)

def movie_data():
    title = input("Enter the movie title: ")
    director = input("Enter the movie director: ")
    year = input("Enter the movie release year: ")

    movies.append({
        'title': title,
        'director': director,
        'year': year
    })

def display():
    print("movies =", end =" ")
    for movie in movies:
        print(movie['title'])

def search(title):
    for i in range(len(movies)):
        if(movies[i]['title']== str(title)):
            return movies[i]

    return None

while selection != 'q':
    if selection == "a":
        movie_data()
    elif selection == "l":
        display()
    elif selection == "f":
        find = input("enter the movie title:")
        movie = search(find)
        if (movie):

            print("movie found:", movie)
        else:
            print(f'No Such Movie, Named {find}, Found!, Try Other Movie Name.')
    else:
        print('Unknown command. Please try again.')

    selection = input(MENU_PROMPT)
</code>```

Body:
MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: "
movies = []

# And another function here for the user menu
selection = input(MENU_PROMPT)

def movie_data():
    title = input("Enter the movie title: ")
    director = input("Enter the movie director: ")
    year = input("Enter the movie release year: ")

    movies.append({
        'title': title,
        'director': director,
        'year': year
    })

def display():
    print("movies =", end =" ")
    for movie in movies:
        print(movie['title'])

while selection != 'q':
    if selection == "a":
        movie_data()
    elif selection == "l":
        display()
    elif selection == "f":
        find = input("enter the movie title")
        if find in movies:
            print("movie found.", movies)
        else:
            print(f'No Such Movie, Named {find}, Found!, Try Other Movie Name.')
    else:
        print('Unknown command. Please try again.')

    selection = input(MENU_PROMPT)

if the user inputs the f for finding the movie name in the movies dictionary then what do I write in the last elif function, can anyone explain it??

I want - (userinput movie name) - avengers
output - match found! movie name - avengers, director - (what the userinputs) & year - (what the userinputs)

Body:
You can make a search function which iterates over each element in the list and searches for the title attribute in dictionary.

MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: "
movies = []

# And another function here for the user menu
selection = input(MENU_PROMPT)

def movie_data():
    title = input("Enter the movie title: ")
    director = input("Enter the movie director: ")
    year = input("Enter the movie release year: ")

    movies.append({
        'title': title,
        'director': director,
        'year': year
    })

def display():
    print("movies =", end =" ")
    for movie in movies:
        print(movie['title'])

def search(title):
    for i in range(len(movies)):
        if(movies[i]['title']== str(title)):
            return movies[i]

    return None

while selection != 'q':
    if selection == "a":
        movie_data()
    elif selection == "l":
        display()
    elif selection == "f":
        find = input("enter the movie title:")
        movie = search(find)
        if (movie):

            print("movie found:", movie)
        else:
            print(f'No Such Movie, Named {find}, Found!, Try Other Movie Name.')
    else:
        print('Unknown command. Please try again.')

    selection = input(MENU_PROMPT)


问:
Ionic React - do you have to use Ionic UI components and routing?
Looking at the ionic documentation they are pushing very heavily towards using Ionic components for UI and routing.

Is it possible to use your own components and frameworks instead of Ionic and simply use Ionic for its native feature support?

答:
Actually, You can just use Cordova. Because the Ionic is built on top of Cordova (It's just the wrapper). So you can reuse all Libs of Ionic with Cordova.

You can check these repositories:

https://github.com/unimonkiez/react-cordova-boilerplate

https://github.com/gitsad/react-cordova-boilerplate


问:
How to open deep link from mobile browser?
I have created a deep link for my app, myapp://video or let say i have also added uber:// but when i open these from chrome browser, it takes me to google, it does not treat this as a link, So how will user reach to the content of this link, if its not opening from browser.

I tried this, but it opened the Google search, and not take me to the play store.

Kindly guide me how a user can use deep link? and reach to the app by using deep link.

Manifest

```<code><intent-filter>
    <data android:scheme="myapp" android:host="video/>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.BROWSABLE" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</code>```

答: Firefox browser worked for me. I believe it handles private URI schemes</p>

Body:
I have created a deep link for my app, myapp://video or let say i have also added uber:// but when i open these from chrome browser, it takes me to google, it does not treat this as a link, So how will user reach to the content of this link, if its not opening from browser.

I tried this, but it opened the Google search, and not take me to the play store.

Kindly guide me how a user can use deep link? and reach to the app by using deep link.

Manifest

<intent-filter>
    <data android:scheme="myapp" android:host="video/>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.BROWSABLE" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>


问:
How to search entire hard drive for a specific file (Java Eclipse)?
```<code>    public static void fileSearcher() throws IOException {
    File dire = new File ("C:/");
    String[] allFile = dire.list();
    for (int i = 0;i<10;i++) {
        String FilIn = allFile[i];                   // here is where I need to scan entire pc for file
        if(FilIn.equals("eclipse.exe")){
            System.out.println("Found Eclipse!");
            break;
        }
        else {
            System.out.println("Eclipse not found on local drive.");
        }
</code>```

Is there a simple way to scan an entire HHD/SSD for a specific file ?

答:
This will do the job for you and it works too when there are multiple drives or partitions. It will also search for additional files with that same name.

```<code>import java.io.File;
import javax.swing.filechooser.FileSystemView;

public class HardDiskSearcher {

    private static boolean fileFound = false;

    private static String searchTerm = "eclipse.exe";

    public static void main(String[] args) {

        fileFound = false;

        File[] systemRoots = File.listRoots();
        FileSystemView fsv = FileSystemView.getFileSystemView();

        for (File root: systemRoots) {
            if (fsv.getSystemTypeDescription(root).equals("Local Disk")) {
                File[] filesFromRoot = root.listFiles();
                recursiveSearch(searchTerm, filesFromRoot);
            }
        }

        System.out.println("File you searched for was found?  : " + fileFound);

    }

    private static void recursiveSearch(String searchTerm, File... files) {

        for (File file: files) {

            if (file.isDirectory()) {
                File[] filesInFolder = file.listFiles();

                if (filesInFolder != null) {
                    for (File f : filesInFolder) {
                        if (f.isFile()) {
                            if (isTheSearchedFile(f, searchTerm)) {
                                fileFound = true;
                            }
                        }
                    }

                    for (File f : filesInFolder) {
                        if (f.isDirectory()) {
                            recursiveSearch(searchTerm, f);
                        }
                    }
                }
            }
            else if (isTheSearchedFile(file, searchTerm)) {
                fileFound = true;
            }
        }
    }

    private static boolean isTheSearchedFile(File file, String searchTerm) {
        if (file.isFile() && (searchTerm.equals(file.getName())) ) {
            System.out.println("The file you searched for has been found! " +
                    "It was found at: " + file.getAbsolutePath());
            return true;
        }
        return false;
    }

}

</code>```

I am not 100% sure about why the if-statement (filesInFolder != null) is necessary here but i suspect Windows returns null when trying to list files from specific system folder or something.

Body:
    public static void fileSearcher() throws IOException {
    File dire = new File ("C:/");
    String[] allFile = dire.list();
    for (int i = 0;i<10;i++) {
        String FilIn = allFile[i];                   // here is where I need to scan entire pc for file
        if(FilIn.equals("eclipse.exe")){
            System.out.println("Found Eclipse!");
            break;
        }
        else {
            System.out.println("Eclipse not found on local drive.");
        }

Is there a simple way to scan an entire HHD/SSD for a specific file ?

Body:
This will do the job for you and it works too when there are multiple drives or partitions. It will also search for additional files with that same name.

import java.io.File;
import javax.swing.filechooser.FileSystemView;

public class HardDiskSearcher {

    private static boolean fileFound = false;

    private static String searchTerm = "eclipse.exe";

    public static void main(String[] args) {

        fileFound = false;

        File[] systemRoots = File.listRoots();
        FileSystemView fsv = FileSystemView.getFileSystemView();

        for (File root: systemRoots) {
            if (fsv.getSystemTypeDescription(root).equals("Local Disk")) {
                File[] filesFromRoot = root.listFiles();
                recursiveSearch(searchTerm, filesFromRoot);
            }
        }

        System.out.println("File you searched for was found?  : " + fileFound);

    }

    private static void recursiveSearch(String searchTerm, File... files) {

        for (File file: files) {

            if (file.isDirectory()) {
                File[] filesInFolder = file.listFiles();

                if (filesInFolder != null) {
                    for (File f : filesInFolder) {
                        if (f.isFile()) {
                            if (isTheSearchedFile(f, searchTerm)) {
                                fileFound = true;
                            }
                        }
                    }

                    for (File f : filesInFolder) {
                        if (f.isDirectory()) {
                            recursiveSearch(searchTerm, f);
                        }
                    }
                }
            }
            else if (isTheSearchedFile(file, searchTerm)) {
                fileFound = true;
            }
        }
    }

    private static boolean isTheSearchedFile(File file, String searchTerm) {
        if (file.isFile() && (searchTerm.equals(file.getName())) ) {
            System.out.println("The file you searched for has been found! " +
                    "It was found at: " + file.getAbsolutePath());
            return true;
        }
        return false;
    }

}

I am not 100% sure about why the if-statement (filesInFolder != null) is necessary here but i suspect Windows returns null when trying to list files from specific system folder or something.


问:
Passing a symbol as a function in clojure
I'm learning clojure and I've written a small function that given a directory pathname returns a sorted-map of files in descending order according to their mtimes. Here it is:

```<code>(defn get-sorted-mtimes [dir]
  (loop [sm (sorted-map-by >)
         lst (for [f (.listFiles (File. dir))]
               (let [k (.lastModified f)
                     v (.getName f)]
                 [k v]))]
    (if (seq lst)
      (recur (assoc sm ((first lst) 0) ((first lst) 1))
        (rest lst))
      sm)))
</code>```

My question is: is there a way to pass the comparator method as a symbol name to the function and make it sort by asc or desc order accordingly? I mean something like:

```<code>(defn get-sorted-mtimes [dir <sym>]
  (loop [sm (sorted-map-by <sym>)
       ...
</code>```

Also, is there a more clojuresque way of accomplishing this task?

Well, for the record, this is the final form of the function that does exactly what I need it to:

```<code>(defn get-sorted-mtimes [dir comp]
  (loop [sm (sorted-map-by (comparator comp))
         lst (for [f (.listFiles (File. dir))]
               (let [k (.lastModified f)
                     v (.getName f)]
                 [k v]))]
    (if (seq lst)
      (recur (assoc sm ((first lst) 0) ((first lst) 1))
        (rest lst))
      sm)))
</code>```

If the (comparator) function isn't used, you get a java.lang.ClassCastException exception.

答:
> is just a function like any other in Clojure. So there is nothing to stop you passing it as an argument.

In fact I'd say that is good Clojure style to do it this way. Clojure is a functional programming language at heart, so there's nothing wrong with using higher order functions where appropriate!

Some other minor suggestions:

Use comparator instead of <sym> as a name for your function parameter. I think that's more descriptive and also more consistent with Clojure's normal naming conventions.

You could also add another function parameter to determine what you are comparing so that you can pass a function like get-mtime (a simple function that returns the mtime of a file).

I would suggest making a sequence of files the input to the function rather than a directory. Then your function is more general and can del with things like e.g. recursive directory scans in exactly the same manner

I'd suggest using (into sm lst) - much simpler than your big loop/if/recur construct!

Then you can do really nice things like (get-sorted-files (list-files-recursive dir) > get-mtime) - or any similar combinations you can think of!

Body:
I'm learning clojure and I've written a small function that given a directory pathname returns a sorted-map of files in descending order according to their mtimes. Here it is:

(defn get-sorted-mtimes [dir]
  (loop [sm (sorted-map-by >)
         lst (for [f (.listFiles (File. dir))]
               (let [k (.lastModified f)
                     v (.getName f)]
                 [k v]))]
    (if (seq lst)
      (recur (assoc sm ((first lst) 0) ((first lst) 1))
        (rest lst))
      sm)))

My question is: is there a way to pass the comparator method as a symbol name to the function and make it sort by asc or desc order accordingly? I mean something like:

(defn get-sorted-mtimes [dir <sym>]
  (loop [sm (sorted-map-by <sym>)
       ...

Also, is there a more clojuresque way of accomplishing this task?

Well, for the record, this is the final form of the function that does exactly what I need it to:

(defn get-sorted-mtimes [dir comp]
  (loop [sm (sorted-map-by (comparator comp))
         lst (for [f (.listFiles (File. dir))]
               (let [k (.lastModified f)
                     v (.getName f)]
                 [k v]))]
    (if (seq lst)
      (recur (assoc sm ((first lst) 0) ((first lst) 1))
        (rest lst))
      sm)))

If the (comparator) function isn't used, you get a java.lang.ClassCastException exception.


问:
Updating specific elements in C array
I'm having trouble conceptualising how to go about some of my code.

My C program wishes to compare each individual element of an array of structs aka arr_person[i].name against a user's input to see if there's a match. (i.e. if the user types in "Billy" and "Billy" is also a string in arr_person[].name array)

```<code>for(i=0;i<num_of_lines;i++)
{
    if(strcmp(nameInput, arr_person[i].name)==0) {
        printf("Match at element %d\n", i);
    }
}
</code>```

Then, a separate function finds reoccurring elements within arr_person[i].name by iterating through the array, and if the same name occurs twice, it will take the corresponding integer values of the same elemental positions and will add them up and store in new variable newChange. For example, if "Billy" occurs twice in the array, at arr_person[0].name and arr_person[4].name, and arr_person[0].number = 15 and arr_person[4].number = 10, then I want to update the number such that it becomes 25.

```<code>for(i = 0; i < num_of_lines; i++) {
        for(j=0;j<num_of_lines;j++) {
            if(strcmp(arr_person[j].name, arr_person[i].name)==0)
                *newNumber = arr_person[i].number + arr_person[j].number;
            }
        }
</code>```

How do I go about this so that any elements in the array that don't reoccur are still kept the same?

If the user inputs "Rachel" and Rachel only appears once in the array, and her corresponding number is 85, I want to print

Rachel 85

But if the user inputs "Billy" and Billy occurs twice, and he has the two numbers 10 and 15 as corresponding integers in another array, I want to print

Billy 25

I've only been programming for a few months. Thanks in advance.

答:
Seems like the only thing you need to do is this:

```<code>int sum = 0;
for(int i=0;i<num_of_lines;i++)
{
    if(strcmp(nameInput, arr_person[i].name)==0)
        sum += arr_person[i].number;
}
</code>```

I would structure it like this:

```<code>// Previous code from your post slightly modified to function
// returns -1 on no match and index otherwise
int match(struct person *arr_person, char *nameInput, int num_of_lines)
{
    for(int i=0;i<num_of_lines;i++) {
        if(strcmp(nameInput, arr_person[i].name)==0)
            return i;
    }
    return -1;
}

int sum(struct person *arr_person, char *nameInput, int num_of_lines)
{
    int sum = 0;
    for(int i=0;i<num_of_lines;i++) {
        if(strcmp(nameInput, arr_person[i].name)==0)
            sum += arr_person[i].number;
    }
    return sum;
}

int main()
{
    // Insert code for declaration and initialization

    int index = match(arr_person, nameInput, num_of_lines);
    if(index >= 0) {
        printf("Match at element %d\n", index);
        printf("%s %d\n", nameInput, sum(arr_person, nameInput, num_of_lines));
    } else {
        printf("No match\n");
    }
}
</code>```

Title: Updating specific elements in C array

Body:
I'm having trouble conceptualising how to go about some of my code.

My C program wishes to compare each individual element of an array of structs aka arr_person[i].name against a user's input to see if there's a match. (i.e. if the user types in "Billy" and "Billy" is also a string in arr_person[].name array)

for(i=0;i<num_of_lines;i++)
{
    if(strcmp(nameInput, arr_person[i].name)==0) {
        printf("Match at element %d\n", i);
    }
}

Then, a separate function finds reoccurring elements within arr_person[i].name by iterating through the array, and if the same name occurs twice, it will take the corresponding integer values of the same elemental positions and will add them up and store in new variable newChange. For example, if "Billy" occurs twice in the array, at arr_person[0].name and arr_person[4].name, and arr_person[0].number = 15 and arr_person[4].number = 10, then I want to update the number such that it becomes 25.

for(i = 0; i < num_of_lines; i++) {
        for(j=0;j<num_of_lines;j++) {
            if(strcmp(arr_person[j].name, arr_person[i].name)==0)
                *newNumber = arr_person[i].number + arr_person[j].number;
            }
        }

How do I go about this so that any elements in the array that don't reoccur are still kept the same?

If the user inputs "Rachel" and Rachel only appears once in the array, and her corresponding number is 85, I want to print

Rachel 85

But if the user inputs "Billy" and Billy occurs twice, and he has the two numbers 10 and 15 as corresponding integers in another array, I want to print

Billy 25

I've only been programming for a few months. Thanks in advance.

Body:
Seems like the only thing you need to do is this:

int sum = 0;
for(int i=0;i<num_of_lines;i++)
{
    if(strcmp(nameInput, arr_person[i].name)==0)
        sum += arr_person[i].number;
}

I would structure it like this:

// Previous code from your post slightly modified to function
// returns -1 on no match and index otherwise
int match(struct person *arr_person, char *nameInput, int num_of_lines)
{
    for(int i=0;i<num_of_lines;i++) {
        if(strcmp(nameInput, arr_person[i].name)==0)
            return i;
    }
    return -1;
}

int sum(struct person *arr_person, char *nameInput, int num_of_lines)
{
    int sum = 0;
    for(int i=0;i<num_of_lines;i++) {
        if(strcmp(nameInput, arr_person[i].name)==0)
            sum += arr_person[i].number;
    }
    return sum;
}

int main()
{
    // Insert code for declaration and initialization

    int index = match(arr_person, nameInput, num_of_lines);
    if(index >= 0) {
        printf("Match at element %d\n", index);
        printf("%s %d\n", nameInput, sum(arr_person, nameInput, num_of_lines));
    } else {
        printf("No match\n");
    }
}


问:
Camera Intrinsic Matrix for DJI Phantom 4
I am trying to estimate a gues for the intrinsic matrix, K, of a DJI Phantom 4 drone. I know that the form of this matrix is:

but i cant seem to get the units right. Looking up the specs at https://www.dji.com/phantom-4/info#specs I find that the focal length is 8.88 (dosnt say units...) and the image dimensions are 4000x3000. WHat would K look like with these?

*PS, I am scaling down the images so they are smaller. Will this effect the K matrix I should use for openCV?

答:
I think it is much better to work from the focal length in mm

https://www.dxomark.com/Cameras/DJI/Phantom4-Pro---Specifications

For P4 Pro:

```<code>13.2 x 8.8  so pixel size is = 0.00241 or 2.41 um focal length is 8.8mm
</code>```

so focal length in pixel = 8.8 / 0.00241 = 3684.6 pixels

Incidentally in the image metadata, there is a field:

CalibratedFocalLength 3666.666504 (use exiftool to find it) so I think K should be

```<code>K = [ [3666.6, 0   , 2432],
    [0   , 3666.6, 1824],
    [0   , 0   , 1   ] ]
</code>```

Body:
I think it is much better to work from the focal length in mm

https://www.dxomark.com/Cameras/DJI/Phantom4-Pro---Specifications

For P4 Pro:

13.2 x 8.8  so pixel size is = 0.00241 or 2.41 um focal length is 8.8mm

so focal length in pixel = 8.8 / 0.00241 = 3684.6 pixels

Incidentally in the image metadata, there is a field:

CalibratedFocalLength 3666.666504 (use exiftool to find it) so I think K should be

K = [ [3666.6, 0   , 2432],
    [0   , 3666.6, 1824],
    [0   , 0   , 1   ] ]


问:
Mean of elements from arbitrary number of nested lists
If I have a list, say:

```<code>foo =  [[4, 6, 2, 7], [1.2, 8.3, 9, 16]]
</code>```

I can get the mean of each element as follows:

```<code>[(a + b) / 2 for a, b in zip(foo[0], foo[1])]
</code>```

or

```<code>import statistics
[statistics.mean(i) for i in zip(foo[0], foo[1])]
</code>```

How can I do the same with an arbitrary number of nested lists in foo?

I tried several things but they do not work, for example:

```<code>[statistics.mean(i) for i in zip(list(foo))]
</code>```

I would strongly prefer to just use comprehension.

答:
If you don't want to use any package:

```<code>[statistics.mean([foo[j][i] for j in range(len(foo))]) for i in range(len(foo[0]))]
</code>```

With numpy it would be

```<code>import numpy as np
arr = np.array(foo)
means = np.mean(arr,axis=0)
</code>```

edit

without any package:

```<code>[sum([foo[j][i] for j in range(len(foo))])/len(foo) for i in range(len(foo[0]))]
</code>```

Body:
If I have a list, say:

foo =  [[4, 6, 2, 7], [1.2, 8.3, 9, 16]]

I can get the mean of each element as follows:

[(a + b) / 2 for a, b in zip(foo[0], foo[1])]

or

import statistics
[statistics.mean(i) for i in zip(foo[0], foo[1])]

How can I do the same with an arbitrary number of nested lists in foo?

I tried several things but they do not work, for example:

[statistics.mean(i) for i in zip(list(foo))]

I would strongly prefer to just use comprehension.

Body:
If you don't want to use any package:

[statistics.mean([foo[j][i] for j in range(len(foo))]) for i in range(len(foo[0]))]

With numpy it would be

import numpy as np
arr = np.array(foo)
means = np.mean(arr,axis=0)

edit

without any package:

[sum([foo[j][i] for j in range(len(foo))])/len(foo) for i in range(len(foo[0]))]


问:
React problem with AdminLTE3 sidebar treeview
So I want to make a React sidebar with an item 'Employee' that when clicked will expand three child items.

Here is the code

```<code>import React, { Component } from "react";

export default class Sidebar extends Component {

  constructor(props) {
    super(props);

    this.state = {
      user: {}
    }
  }

  componentDidMount() {
    let userData = JSON.parse(localStorage.getItem('user'))
    this.setState({user: userData})
  }

  render() {
    return (
      <aside className="main-sidebar sidebar-dark-primary elevation-4" >
        {/* Brand Logo */}
        <a href="/" className="brand-link">
          <span className="brand-text font-weight-light ml-1">HRMS</span>
        </a>
        {/* Sidebar */}
        <div className="sidebar">
          {/* Sidebar user panel (optional) */}
          <div className="user-panel mt-3 pb-3 mb-3 d-flex">
            <div className="image">
              <img
                src={process.env.PUBLIC_URL + '/dist/img/user2-160x160.jpg'}
                className="img-circle elevation-2"
                alt="User Image"
              />
            </div>
            <div className="info">
              <a href="#" className="d-block">
                {this.state.user.fullname}
              </a>
            </div>
          </div>
          {/* Sidebar Menu */}
          <nav className="mt-2">
            <ul
              className="nav nav-pills nav-sidebar flex-column"
              data-widget="treeview"
              role="menu"
              data-accordion="false"
            >
              {/* Add icons to the links using the .nav-icon class
         with font-awesome or any other icon font library */}
              <li className="nav-item">
                <a href="/" className="nav-link active">
                  <i className="nav-icon fas fa-tachometer-alt" />
                  <p>
                    Dashboard
                    <span className="right badge badge-success">Home</span>
                  </p>
                </a>
              </li>
              <li className="nav-item">
                <a href="pages/widgets.html" className="nav-link">
                  <i className="nav-icon fas fa-th" />
                  <p>
                    Widgets
                    <span className="right badge badge-danger">New</span>
                  </p>
                </a>
              </li>
              <li className="nav-item has-treeview">
                <a href="#" className="nav-link">
                  <i className="nav-icon fa fa-user" />
                  <p>
                    Employee
                    <i className="right fas fa-angle-left" />
                  </p>
                </a>
                <ul className="nav nav-treeview">
                  <li className="nav-item">
                    <a href="/employee-add" className="nav-link">
                      <i className="fa fa-user-plus nav-icon" />
                      <p>Add Employee</p>
                    </a>
                  </li>
                  <li className="nav-item">
                    <a href="/employee-list" className="nav-link">
                      <i className="fas fa-users nav-icon" />
                      <p>Employee List</p>
                    </a>
                  </li>
                  <li className="nav-item">
                    <a href="/employee-add" className="nav-link">
                      <i className="far fa-circle nav-icon" />
                      <p>Employee Award</p>
                    </a>
                  </li>
                </ul>
              </li>
</code>```

The problem is after login redirects to this page and I click the Employee item, the href activates and just reloads the page (what href="#" usually does). However if i remove the  tag or the href the css gets all messed up.

I am using AdminLTE3 so here is the documentation: https://adminlte.io/docs/3.0/javascript/treeview.html

答:
I found the answer as it is a problem to many people. The problem occurs when you redirect from another page (i.e login page)

Here is the link to the answer: https://github.com/ColorlibHQ/AdminLTE/issues/1570#issuecomment-615841382

Body:
So I want to make a React sidebar with an item 'Employee' that when clicked will expand three child items.

Here is the code

import React, { Component } from "react";

export default class Sidebar extends Component {

  constructor(props) {
    super(props);

    this.state = {
      user: {}
    }
  }

  componentDidMount() {
    let userData = JSON.parse(localStorage.getItem('user'))
    this.setState({user: userData})
  }

  render() {
    return (

        {/* Brand Logo */}

          HRMS

        {/* Sidebar */}

          {/* Sidebar user panel (optional) */}

                {this.state.user.fullname}

          {/* Sidebar Menu */}

              {/* Add icons to the links using the .nav-icon class
         with font-awesome or any other icon font library */}

                    Dashboard
                    Home

                    Widgets
                    New

                    Employee

Add Employee

Employee List

Employee Award

The problem is after login redirects to this page and I click the Employee item, the href activates and just reloads the page (what href="#" usually does). However if i remove the  tag or the href the css gets all messed up.

I am using AdminLTE3 so here is the documentation: https://adminlte.io/docs/3.0/javascript/treeview.html


问:
NHibernate Linq property-ref behavior
NHibernate Linq is producing an unexcepted query. Here are my class mappings:

```<code>public class OrderClassMap : ClassMap<Order> {
    public OrderClassMap() {
        Id(x => x.PersistenceId).Column("RowId").GeneratedBy.Assigned();
        Version(x => x.PersistenceVersion).Column("RowVersion");
        Map(x => x.OrderId).Generated.Insert().Not.Update();
        Map(x => x.OrderDate);
        References(x => x.Overseer).Column("OverseerId").PropertyRef(x => x.OverseerId);
        References(x => x.Overseer2).Column("OverseerId2").PropertyRef(x => x.OverseerId2);
    }
}

public class OverseerClassMap : ClassMap<Overseer> {
    public OverseerClassMap() {
        Id(x => x.PersistenceId).Column("RowId").Generated.Assigned();
        Version(x => x.PersistenceVersion).Column("RowVersion");
        Map(x => x.OverseerId).Generated.Insert().Not.Update();
        Map(x => x.Name);
        Map(x => x.Email);
    }
}
</code>```

Here is the Linq query I have:

```<code>var orders = session.Query<Order>()
                    .Where(o => ((o.Overseer.OverseerId == 1) || (o.Overseer.OverseerId == 2)))
                    .Fetch(o => o.Overseer)
                    .Fetch(o => o.Overseer2);
</code>```

The SQL query that is generated is not what I would expect. Instead of doing a left outer join, it does a cartesian join. Here is a shortened example of the query NHibernate produces:

```<code>SELECT ...
FROM Orders o LEFT OUTER JOIN
     Overseers v1 ON o.OverseerId = v1.OverseerId LEFT OUTER JOIN
     Overseers v2 ON o.OverseerId2 = v1.OverseerId,
     Overseers v3,
     Overseers v4
WHERE o.OverseerId = v3.OverseerId AND
      o.OverseerId2 = v4.OverseerId AND
      (v3.OverseerId = 1 OR v4.OverseerId = 1)
</code>```

The query I expected would be like:

```<code>SELECT ...
FROM Orders o LEFT OUTER JOIN
     Overseers v1 ON o.OverseerId = v1.OverseerId LEFT OUTER JOIN
     Overseers v2 ON o.OverseerId2 = v1.OverseerId
WHERE (v1.OverseerId = 1 OR v2.OverseerId = 1)
</code>```

I think it is doing this because I have a legacy database and am using PropertyRef in my mapping. Is there any way to fix this unexpected behavior? Why does NHibernate behave this way? It doesn't make sense to me because by specifying PropertyRef, I'm saying "Use this key instead of the primary key".

答: Try using QueryOver<>, and specify the left outer join.</p>

Title: NHibernate Linq property-ref behavior

Body:
NHibernate Linq is producing an unexcepted query. Here are my class mappings:

public class OrderClassMap : ClassMap<Order> {
    public OrderClassMap() {
        Id(x => x.PersistenceId).Column("RowId").GeneratedBy.Assigned();
        Version(x => x.PersistenceVersion).Column("RowVersion");
        Map(x => x.OrderId).Generated.Insert().Not.Update();
        Map(x => x.OrderDate);
        References(x => x.Overseer).Column("OverseerId").PropertyRef(x => x.OverseerId);
        References(x => x.Overseer2).Column("OverseerId2").PropertyRef(x => x.OverseerId2);
    }
}

public class OverseerClassMap : ClassMap<Overseer> {
    public OverseerClassMap() {
        Id(x => x.PersistenceId).Column("RowId").Generated.Assigned();
        Version(x => x.PersistenceVersion).Column("RowVersion");
        Map(x => x.OverseerId).Generated.Insert().Not.Update();
        Map(x => x.Name);
        Map(x => x.Email);
    }
}

Here is the Linq query I have:

var orders = session.Query<Order>()
                    .Where(o => ((o.Overseer.OverseerId == 1) || (o.Overseer.OverseerId == 2)))
                    .Fetch(o => o.Overseer)
                    .Fetch(o => o.Overseer2);

The SQL query that is generated is not what I would expect. Instead of doing a left outer join, it does a cartesian join. Here is a shortened example of the query NHibernate produces:

SELECT ...
FROM Orders o LEFT OUTER JOIN
     Overseers v1 ON o.OverseerId = v1.OverseerId LEFT OUTER JOIN
     Overseers v2 ON o.OverseerId2 = v1.OverseerId,
     Overseers v3,
     Overseers v4
WHERE o.OverseerId = v3.OverseerId AND
      o.OverseerId2 = v4.OverseerId AND
      (v3.OverseerId = 1 OR v4.OverseerId = 1)

The query I expected would be like:

SELECT ...
FROM Orders o LEFT OUTER JOIN
     Overseers v1 ON o.OverseerId = v1.OverseerId LEFT OUTER JOIN
     Overseers v2 ON o.OverseerId2 = v1.OverseerId
WHERE (v1.OverseerId = 1 OR v2.OverseerId = 1)

I think it is doing this because I have a legacy database and am using PropertyRef in my mapping. Is there any way to fix this unexpected behavior? Why does NHibernate behave this way? It doesn't make sense to me because by specifying PropertyRef, I'm saying "Use this key instead of the primary key".


问:
Task scheduler running power shell script - Username error?
So I have a powershell script that when a user logs into a PC it emails details of the login to me, for example username,IP,location etc. It runs from task scheduler and has a trigger on login.

The script runs fine through powershell my issue I am having that no matter who logs in it always runs the script on my account in task scheduler hence always inputting my name as the Username even tough a different user may be logged in. I've tried calling the username multiple ways but always shows my name as It runs off my account.

For calling the username I have used :

$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name

$env:UserName

$env:UserDomain

All return the user of who is running the scheduled task.

Any help to get it to print the true user who has logged in would be much appreciated.

Thanks.

答:
It may be because your scheduled task is executing with your credentials. There's no way around this, sadly. That said you can kind of side-step the behaviour by getting the user account associated with the explorer.exe process:

```<code>$username = Get-WmiObject Win32_Process -Filter "Name='explorer.exe'" | ForEach-Object { $_.GetOwner() } | Select-Object -Unique -Expand User
</code>```

This should work fine, as long as you aren't ever in a situation where multiple users could be logged into a machine at the same time (fast user switching, terminal services etc.)

EDIT: To get what you're after, you might need something more like this

```<code>$op = @()
$owners = Get-WmiObject Win32_Process -Filter "Name='explorer.exe'" | ForEach-Object { $_.GetOwner() } | Select-Object -Unique -Expand User
foreach($owner in $owners)
{
    $wmiprocs = get-wmiobject win32_process -filter "Name='explorer.exe'" | where { $_.getowner().user -eq $owner } | select-object processid
    $procs = $wmiprocs | % { get-process -id $_.processid | select-object starttime }
    $obj = new-object object
    $obj | add-member -type noteproperty -name Username $owner
    $obj | add-member -type noteproperty -name Logon ($procs | sort -descending)[0].starttime
    $op += $obj
}

$op | ft -auto
</code>```

Note that your PowerShell instance will need to be running as Admin to query the processes of other users.

Body:
It may be because your scheduled task is executing with your credentials. There's no way around this, sadly. That said you can kind of side-step the behaviour by getting the user account associated with the explorer.exe process:

$username = Get-WmiObject Win32_Process -Filter "Name='explorer.exe'" | ForEach-Object { $_.GetOwner() } | Select-Object -Unique -Expand User

This should work fine, as long as you aren't ever in a situation where multiple users could be logged into a machine at the same time (fast user switching, terminal services etc.)

EDIT: To get what you're after, you might need something more like this

$op = @()
$owners = Get-WmiObject Win32_Process -Filter "Name='explorer.exe'" | ForEach-Object { $_.GetOwner() } | Select-Object -Unique -Expand User
foreach($owner in $owners)
{
    $wmiprocs = get-wmiobject win32_process -filter "Name='explorer.exe'" | where { $_.getowner().user -eq $owner } | select-object processid
    $procs = $wmiprocs | % { get-process -id $_.processid | select-object starttime }
    $obj = new-object object
    $obj | add-member -type noteproperty -name Username $owner
    $obj | add-member -type noteproperty -name Logon ($procs | sort -descending)[0].starttime
    $op += $obj
}

$op | ft -auto

Note that your PowerShell instance will need to be running as Admin to query the processes of other users.


问:
Consumer_failed_message in kafka stream: Records not pushed from topic
I have a flow where from IBM mainframe IIDR, I am sending records to Kafka topic. The value_format of the message coming to Kafka topic is AVRO and the key is in AVRO format too. The records are pushed into the Kafka topic. I have a stream associated with that topic. But the records are not passed into the stream.
Example of the test_iidr topic -

```<code>rowtime: 5/30/20 7:06:34 PM UTC, key: {"col1": "A", "col2": 1}, value: {"col1": "A", "col2": 11, "col3": 2, "iidr_tran_type": "QQ", "iidr_a_ccid": "0", "iidr_a_user": " ", "iidr_src_upd_ts": "2020-05-30 07:06:33.262931000", "iidr_a_member": " "}
</code>```

The value_format in the stream is AVRO and the column names are all checked.

The stream creation query -

CREATE STREAM test_iidr (
  col1 STRING,
  col2 DECIMAL(2,0),
  col3 DECIMAL(1,0),
  iidr_tran_type STRING,
  iidr_a_ccid STRING,
  iidr_a_user STRING,
  iidr_src_upd_ts STRING,
  iidr_a_member STRING)
WITH (KAFKA_TOPIC='test_iidr', PARTITIONS=1, REPLICAS=3, VALUE_FORMAT='AVRO');
```

Is it failing to load into the stream from the topic as the KEY is not mentioned in WITH statement?
The schema registry has the test_iidr-value and test_iidr-key subjects registered in it.

The key.converter and value.converter in the Kafka-connect docker is set as - org.apache.kafka.connect.json.JsonConverter. Is this JsonConverter creating this issue?

I created a completely different pipeline with different stream and inserted the same data manually using insert into statements. It worked. Only the IIDR flow is not working and the records are not pushed into the stream from the topic.

I am using Confluent kafka version 5.5.0.

答:
The JsonConverter in the connect config could well be converting your Avro data to JSON.

To determine the key and value serialization formats you can use the PRINT command, (which I can see you've already run).  PRINT will output the key and value formats when it runs. For example:

```<code>ksql> PRINT some_topic FROM BEGINNING LIMIT 1;
Key format: JSON or KAFKA_STRING
Value format: JSON or KAFKA_STRING
rowtime: 5/30/20 7:06:34 PM UTC, key: {"col1": "A", "col2": 1}, value: {"col1": "A", "col2": 11, "col3": 2, "iidr_tran_type": "QQ", "iidr_a_ccid": "0", "iidr_a_user": " ", "iidr_src_upd_ts": "2020-05-30 07:06:33.262931000", "iidr_a_member": " "}
</code>```

So the first thing to check is the formats output for the key and value by PRINT and then update your CREATE statement accordingly.

Note, ksqlDB does not yet support Avro/Json keys, so you may want/need to repartition your data, see: https://docs.ksqldb.io/en/latest/developer-guide/syntax-reference/#what-to-do-if-your-key-is-not-set-or-is-in-a-different-format

Side note: If the schema for the value is stored in the Schema Registry, then you don't need to define the columns in your CREATE statement as ksqlDB will load the columns from the Schema Registry

Side note: you don't need PARTITIONS=1, REPLICAS=3 in the WITH clause for existing topics, only if you want ksqlDB to create the topic for you.

Body:
I have a flow where from IBM mainframe IIDR, I am sending records to Kafka topic. The value_format of the message coming to Kafka topic is AVRO and the key is in AVRO format too. The records are pushed into the Kafka topic. I have a stream associated with that topic. But the records are not passed into the stream.
Example of the test_iidr topic -

rowtime: 5/30/20 7:06:34 PM UTC, key: {"col1": "A", "col2": 1}, value: {"col1": "A", "col2": 11, "col3": 2, "iidr_tran_type": "QQ", "iidr_a_ccid": "0", "iidr_a_user": " ", "iidr_src_upd_ts": "2020-05-30 07:06:33.262931000", "iidr_a_member": " "}

The value_format in the stream is AVRO and the column names are all checked.

The stream creation query -

CREATE STREAM test_iidr (
  col1 STRING,
  col2 DECIMAL(2,0),
  col3 DECIMAL(1,0),
  iidr_tran_type STRING,
  iidr_a_ccid STRING,
  iidr_a_user STRING,
  iidr_src_upd_ts STRING,
  iidr_a_member STRING)
WITH (KAFKA_TOPIC='test_iidr', PARTITIONS=1, REPLICAS=3, VALUE_FORMAT='AVRO');

Is it failing to load into the stream from the topic as the KEY is not mentioned in WITH statement?
The schema registry has the test_iidr-value and test_iidr-key subjects registered in it.

The key.converter and value.converter in the Kafka-connect docker is set as - org.apache.kafka.connect.json.JsonConverter. Is this JsonConverter creating this issue?

I created a completely different pipeline with different stream and inserted the same data manually using insert into statements. It worked. Only the IIDR flow is not working and the records are not pushed into the stream from the topic.

I am using Confluent kafka version 5.5.0.

Body:
The JsonConverter in the connect config could well be converting your Avro data to JSON.

To determine the key and value serialization formats you can use the PRINT command, (which I can see you've already run).  PRINT will output the key and value formats when it runs. For example:

ksql> PRINT some_topic FROM BEGINNING LIMIT 1;
Key format: JSON or KAFKA_STRING
Value format: JSON or KAFKA_STRING
rowtime: 5/30/20 7:06:34 PM UTC, key: {"col1": "A", "col2": 1}, value: {"col1": "A", "col2": 11, "col3": 2, "iidr_tran_type": "QQ", "iidr_a_ccid": "0", "iidr_a_user": " ", "iidr_src_upd_ts": "2020-05-30 07:06:33.262931000", "iidr_a_member": " "}

So the first thing to check is the formats output for the key and value by PRINT and then update your CREATE statement accordingly.

Note, ksqlDB does not yet support Avro/Json keys, so you may want/need to repartition your data, see: https://docs.ksqldb.io/en/latest/developer-guide/syntax-reference/#what-to-do-if-your-key-is-not-set-or-is-in-a-different-format

Side note: If the schema for the value is stored in the Schema Registry, then you don't need to define the columns in your CREATE statement as ksqlDB will load the columns from the Schema Registry

Side note: you don't need PARTITIONS=1, REPLICAS=3 in the WITH clause for existing topics, only if you want ksqlDB to create the topic for you.


问:
How do I add a "popup" shadow to an HTML element
How can I give my  a popup effect with a shadow? I see it commonly on different websites (e.g. https://www.smartrecruiters.com)   At the edge of the content holder, it has this dark shadow popup effect.

Is there a specific name for it? What can I do to create this effect on both side of the body?

Is element style alright or all styles are recommended to be in CSS?

答:
Shadow on whole page!!!
My idea!</p>

```<code>box-shadow: 0 0 0 100000px rgba(0,0,0,.2);
</code>```

OwnerDisplayName: RainbowHat

Body:
Shadow on whole page!!!
My idea!

box-shadow: 0 0 0 100000px rgba(0,0,0,.2);


答:
What nvidia-smi shows is not the CUDA version that you have installed, but the maximum CUDA version that your driver supports.

CUDA 11.0 has been announced but not released yet (as of June 2nd 2020), so you should use CUDA 10.2 as it's the latest available version.

Title: What is the correct version of CUDNN for CUDA 11.0

Body:
I want to start using tensorflow-gpu, and I looked some stuff up, and found out that I need to ensure that I have both CUDA and CUDNN. So, I opened up the command prompt and ran the command nvidia-smi to check my CUDA version:

C:\Program Files\NVIDIA Corporation\NVSMI>nvidia-smi
Tue Jun 02 14:13:03 2020
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 445.87       Driver Version: 445.87       CUDA Version: 11.0     |
|-------------------------------+----------------------+----------------------+
| GPU  Name            TCC/WDDM | Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 1050   WDDM  | 00000000:01:00.0 Off |                  N/A |
| N/A   40C    P8    N/A /  N/A |     77MiB /  4096MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU                  PID   Type   Process name                  GPU Memory |
|                                                                  Usage      |
|=============================================================================|
|    0                10488    C+G   ...n64\EpicGamesLauncher.exe    N/A      |
|    0                12636    C+G   ...4\UnrealCEFSubProcess.exe    N/A      |
+-----------------------------------------------------------------------------+

Now that I see my CUDA version is 11.0, I went to the NVidia's website to select a version of CUDNN that can work with CUDA 11.0, but the latest ones support up to CUDA 10.2 currently. What should I do? Can I use the one for CUDA 10.2?


问:
Error NG8003: No directive found with exportAs 'ngForm'
I have just updated to angular 9! and suddenly I got this exception:
Error occurs in the template of *, error NG8003: No directive found with exportAs 'ngForm'

Here is the template:

```<code> <form (ngSubmit)="onLogin(frm.value)" #frm="ngForm" style="margin:0 auto;"> //All of these was working fine before the update
</code>```

I also imported FormsModule, ReactiveFormsModule, CommonModule in app.module.ts:

```<code>imports: [
BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
HttpClientModule,
FormsModule,
ReactiveFormsModule,
CommonModule,
</code>```

Note, I am using Visual Studio angular template.

Thank you for help.

答:
You will have to add the ngForm directive to the form:

```<code><form (ngSubmit)="onLogin(frm.value)" ngForm #frm style="margin:0 auto;">
</code>```

Body:
I have just updated to angular 9! and suddenly I got this exception:
Error occurs in the template of *, error NG8003: No directive found with exportAs 'ngForm'

Here is the template:

 <form (ngSubmit)="onLogin(frm.value)" #frm="ngForm" style="margin:0 auto;"> //All of these was working fine before the update

I also imported FormsModule, ReactiveFormsModule, CommonModule in app.module.ts:

imports: [
BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
HttpClientModule,
FormsModule,
ReactiveFormsModule,
CommonModule,

Note, I am using Visual Studio angular template.

Thank you for help.

Body:
You will have to add the ngForm directive to the form:

<form (ngSubmit)="onLogin(frm.value)" ngForm #frm style="margin:0 auto;">


问:
How to call outside method inside the highcharts tree map click event?
i am using highcharts tree map. i want to call some other method(this.callOutsidemethod) inside the tree map click event. But my code is not working and have added my code below. i want to know how to call
outside method inside the tree map click function in typescript.

```<code>export class AppComponent implements OnInit {
  name = `Angular! v${VERSION.full}`;
  @ViewChild("container", { read: ElementRef }) container: ElementRef;

  constructor() {
  }
  ngOnInit() {
    Highcharts.chart(this.container.nativeElement, {
          colorAxis: {
        minColor: '#FFFFFF',
        maxColor: Highcharts.getOptions().colors[0]
    },

    plotOptions: {
        series: {
            cursor: 'pointer',
            events: {
                click: function (event) {
                   this.callOutsidemethod();
                }
            }
        }
    },
    series: [{
        type: 'treemap',
        //layoutAlgorithm: 'squarified',
        data: [{
            name: 'A',
            value: 6,
            colorValue: 1
        }, {
            name: 'B',
            value: 6,
            colorValue: 2
        }, {
            name: 'C',
            value: 4,
            colorValue: 3
        }, {
            name: 'D',
            value: 3,
            colorValue: 4
        }, {
            name: 'E',
            value: 2,
            colorValue: 5
        }, {
            name: 'F',
            value: 2,
            colorValue: 6
        }, {
            name: 'G',
            value: 1,
            colorValue: 7
        }]
    }],
    title: {
        text: 'Highcharts Treemap'
    }
    })
  }

  callOutsidemethod(){
     alert("hii")
  }

}```
```

答:
You could use the arrow function notation to refer to member variables using this keyword. Try the following

events: {
  click: (event) => {
    // do something
    this.callOutsidemethod();
  }
}
```

Body:
i am using highcharts tree map. i want to call some other method(this.callOutsidemethod) inside the tree map click event. But my code is not working and have added my code below. i want to know how to call
outside method inside the tree map click function in typescript.

export class AppComponent implements OnInit {
  name = `Angular! v${VERSION.full}`;
  @ViewChild("container", { read: ElementRef }) container: ElementRef;

  constructor() {
  }
  ngOnInit() {
    Highcharts.chart(this.container.nativeElement, {
          colorAxis: {
        minColor: '#FFFFFF',
        maxColor: Highcharts.getOptions().colors[0]
    },

    plotOptions: {
        series: {
            cursor: 'pointer',
            events: {
                click: function (event) {
                   this.callOutsidemethod();
                }
            }
        }
    },
    series: [{
        type: 'treemap',
        //layoutAlgorithm: 'squarified',
        data: [{
            name: 'A',
            value: 6,
            colorValue: 1
        }, {
            name: 'B',
            value: 6,
            colorValue: 2
        }, {
            name: 'C',
            value: 4,
            colorValue: 3
        }, {
            name: 'D',
            value: 3,
            colorValue: 4
        }, {
            name: 'E',
            value: 2,
            colorValue: 5
        }, {
            name: 'F',
            value: 2,
            colorValue: 6
        }, {
            name: 'G',
            value: 1,
            colorValue: 7
        }]
    }],
    title: {
        text: 'Highcharts Treemap'
    }
    })
  }

  callOutsidemethod(){
     alert("hii")
  }

}```


问:
Replace values outside range with NA using replace_with_na function
I have the following dataset

```<code>structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, 1, 9, 12,
NA), c = c(50, 34, 77, 88, 33, 60)), class = "data.frame", row.names = c(NA,
-6L))

  a  b  c
1 2  4 50
2 1  5 34
3 9  1 77
4 2  9 88
5 9 12 33
6 8 NA 60
</code>```

From column b I only want values between 4-9. Column c between 50-80. Replacing the values outside the range with NA, resulting in

```<code>structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, NA, 9, NA,
NA), c = c(50, NA, 77, NA, NA, 60)), class = "data.frame", row.names = c(NA,
-6L))

  a  b  c
1 2  4 50
2 1  5 NA
3 9 NA 77
4 2  9 NA
5 9 NA NA
6 8 NA 60
</code>```

I've tried several things with replace_with_na_at function where this seemed most logical:

```<code>test <- replace_with_na_at(data = test, .vars="c",
                          condition = ~.x < 2 & ~.x > 2)
</code>```

However, nothing I tried works. Does somebody know why? Thanks in advance! :)

答:
You should mention the packages you are using. From googling, i'm guessing you are using naniar. The problem appears to be that you did not properly specify the condition, but the following should work:

library(naniar)

test <- structure(list(a = c(2, 1, 9, 2, 9, 8),
                    b = c(4, 5, 1, 9, 12, NA),
                    c = c(50, 34, 77, 88, 33, 60)),
               class = "data.frame",
               row.names = c(NA, -6L))

replace_with_na_at(test, "c", ~.x < 50 | .x > 80)
#>   a  b  c
#> 1 2  4 50
#> 2 1  5 NA
#> 3 9  1 77
#> 4 2  9 NA
#> 5 9 12 NA
#> 6 8 NA 60
```

Created on 2020-06-02 by the reprex package (v0.3.0)

Body:
I have the following dataset

structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, 1, 9, 12,
NA), c = c(50, 34, 77, 88, 33, 60)), class = "data.frame", row.names = c(NA,
-6L))

  a  b  c
1 2  4 50
2 1  5 34
3 9  1 77
4 2  9 88
5 9 12 33
6 8 NA 60

From column b I only want values between 4-9. Column c between 50-80. Replacing the values outside the range with NA, resulting in

structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, NA, 9, NA,
NA), c = c(50, NA, 77, NA, NA, 60)), class = "data.frame", row.names = c(NA,
-6L))

  a  b  c
1 2  4 50
2 1  5 NA
3 9 NA 77
4 2  9 NA
5 9 NA NA
6 8 NA 60

I've tried several things with replace_with_na_at function where this seemed most logical:

test <- replace_with_na_at(data = test, .vars="c",
                          condition = ~.x < 2 & ~.x > 2)

However, nothing I tried works. Does somebody know why? Thanks in advance! :)

Body:
You should mention the packages you are using. From googling, i'm guessing you are using naniar. The problem appears to be that you did not properly specify the condition, but the following should work:

library(naniar)

test <- structure(list(a = c(2, 1, 9, 2, 9, 8),
                    b = c(4, 5, 1, 9, 12, NA),
                    c = c(50, 34, 77, 88, 33, 60)),
               class = "data.frame",
               row.names = c(NA, -6L))

replace_with_na_at(test, "c", ~.x < 50 | .x > 80)
#>   a  b  c
#> 1 2  4 50
#> 2 1  5 NA
#> 3 9  1 77
#> 4 2  9 NA
#> 5 9 12 NA
#> 6 8 NA 60

Created on 2020-06-02 by the reprex package (v0.3.0)


问:
Numpy array_equal and float exact equality check
I know that similar precision questions have been asked here however I am reading a code of a project that is doing an exact equality comparison among floats and is puzzling me.

Assume that x1 and x2 are of type numpy.ndarray and of dtype np.float32. These two variables have been computed by the same code executed on the same data but x1 has been computed by one machine and x2 by another (this is done on an AWS cluster which communicates with MPI).

Then the values are compared as follows

numpy.array_equal(x1, x2)

Hence, exact equality (no tolerance) is crucial for this program to work and it seems to work fine. This is confusing me. How can one compare two np.float32 computed on different machines and face no precision issues? When can these two (or more) floats can be equal?

答:
The arithmetic specified by IEEE-754 is deterministic given certain constraints discussed in its clause 11 (2008 version), including suitable rules for expression evaluation (such as unambiguous translation from expressions in a programming language to IEEE-754 operations, such as a+b+c must give (a+b)+c, not a+(b+c)).

If parallelism is not used or is constructed suitably, such as always partitioning a job into the same pieces and combining their results in the same way regardless of order of completion of computations, then obtaining identical results is not surprising.

Some factors that prevent reproducibility include varying parallelism, using different math libraries (with different implementations of functions such as pow), and using languages that are not strict about floating-point evaluation (such as permitting, but not requiring, extra precision).


问:
Vue-i18n translation in script part of component not updating when changing lang
I have a pretty simple landing page in Vue.js and Bootstrap vue and I managed to get i18n running pretty well on the whole page, however, on the subject part of the contact form I have some options to choose from (with a default value that says "Select one"), that I also want them to be translated.

```<code>import i18n from "@/i18n";

export default {
data() {
return {
  errors: [],
  form: {
    email: "",
    subject: null,
    message: "",
  },
  subject: [
    { text: i18n.t("contact.subjectoption"), value: null },
    this.$t("contact.subjectoption1"),
    "Business Inquiry",
    "Social Media",
    "Other",
  ],
  msg: "",
  show: true,
};}}
</code>```

However when I change languages, the whole landing page updates the language but the options do not!

Is there something I missed?

Thanks in advance!

答:
Data isn't smart enough to know that you locale changed.

You can instead create a computed property, which unlike data can detect and recompute when your language changes.

export default {
  computed: {
    subject() {
      return [
        { text: this.$t("contact.subjectoption"), value: null },
        this.$t("contact.subjectoption1"),
        "Business Inquiry",
        "Social Media",
        "Other"
      ]
    }
  }
  data() {
    return {
      errors: [],
      form: {
        email: "",
        subject: null,
        message: ""
      },
      msg: "",
      show: true
    }
  }
}
```

Body:
I have a pretty simple landing page in Vue.js and Bootstrap vue and I managed to get i18n running pretty well on the whole page, however, on the subject part of the contact form I have some options to choose from (with a default value that says "Select one"), that I also want them to be translated.

import i18n from "@/i18n";

export default {
data() {
return {
  errors: [],
  form: {
    email: "",
    subject: null,
    message: "",
  },
  subject: [
    { text: i18n.t("contact.subjectoption"), value: null },
    this.$t("contact.subjectoption1"),
    "Business Inquiry",
    "Social Media",
    "Other",
  ],
  msg: "",
  show: true,
};}}

However when I change languages, the whole landing page updates the language but the options do not!

Is there something I missed?

Thanks in advance!


问:
Android Independent viewModel for recyclerView's adapter
We have a problem in mvvm design pattern with recyclerView:

We have a fragment with own view model (FragmentViewModel)

and a list adapter with it's own view model (ListViewModel)

the problems are these:

Inside our fragment's view model(FragmentViewModel), we get our data from api repository,How to set these values to our adapter's view model(ListViewModel)?

Inside of adapter's view model(ListViewModel),when row item clicked, How to call a function inside our fragments's view model(FragmentViewModel) to do something with fragment's view?

Notes:

- We use dagger to inject our viewModels and adapter.

- Our list adapter will reuse with other fragments.

答:
My suggestion would be, /n
Never use Fragment own's ViewModel, instead used activity one with a key. which differentiate between different fragment.

```<code>ViewModelProviders.of(requireActivity(), factory).get(detail.getJobId(), TimelineActivityViewModel.class);
</code>```

here detail.getJobId() is an ID.

Body:
My suggestion would be, /n
Never use Fragment own's ViewModel, instead used activity one with a key. which differentiate between different fragment.

ViewModelProviders.of(requireActivity(), factory).get(detail.getJobId(), TimelineActivityViewModel.class);

here detail.getJobId() is an ID.


问:
bash - loop through subdirectories, cat files and rename with directory name
I have a folder structure like this ...

```<code>data/
---B1/
name_x_1.gz
name_y_1.gz
name_z_2.gz
name_p_2.gz
---C1
name_s_1.gz
name_t_1.gz
name_u_2.gz
name_v_2.gz
</code>```

I need to go in to each subdirectory (e.g. B1) and perform the following:

```<code>cat *_1.gz > B1_1.gz
cat *_2.gz > B1_2.gz
</code>```

I'm having problems with the file naming part. I can get in directories using the following:

```<code>for d in */; do
cat *_1.gz > $d_1.gz
cat *_2.gz > $d_2.gz
done
</code>```

However I get an error that $d is a directory -- how do I strip the name to create the concatenated filename?

Thanks

答:
This requires Ed, which should hopefully be present on your machine.  If not, I trust your distribution will have a package for it.</p>

```<code>#!/bin/sh

cat >> edprint+.txt << EOF
  1p
  q
EOF

cat >> edpop+.txt << EOF
  1d
  wq
EOF

b1="${PWD}/data/B1"
c1="${PWD}/$data/C1"

find "${b1}" -maxdepth 1 -type f > b1stack
find "${c1}" -maxdepth 1 -type f > c1stack

while [ $(wc -l b1stack | cut -d' ' -f1) -gt 0 ]
do
  b1line=$(ed -s b1stack < edprint+.txt)
  b1name=$(basename "${b1line}")
  b1suffix=$(echo "${b1name}" | cut -d'_' -f3)
  b1fixed=$(echo "B1_${b1suffix}"
  mv -v "${b1}/${b1line}" "${b1}/${b1fixed}"
  ed -s b1stack < edpop+.txt
done

while [ $(wc -l c1stack | cut -d' ' -f1) -gt 0 ]
do
  c1line=$(ed -s c1stack < edprint+.txt)
  c1name=$(basename "${c1line}")
  c1suffix=$(echo "${c1name}" | cut -d'_' -f3)
  c1fixed=$(echo "B1_${c1suffix}"
  mv -v "${c1}/${c1line}" "${c1}/${c1fixed}"
  ed -s c1stack < edpop+.txt
done

rm -v ./edprint+.txt
rm -v ./edpop+.txt
rm -v ./b1stack
rm -v ./c1stack
</code>```

Body:
I have a folder structure like this ...

data/
---B1/
name_x_1.gz
name_y_1.gz
name_z_2.gz
name_p_2.gz
---C1
name_s_1.gz
name_t_1.gz
name_u_2.gz
name_v_2.gz

I need to go in to each subdirectory (e.g. B1) and perform the following:

cat *_1.gz > B1_1.gz
cat *_2.gz > B1_2.gz

I'm having problems with the file naming part. I can get in directories using the following:

for d in */; do
cat *_1.gz > $d_1.gz
cat *_2.gz > $d_2.gz
done

However I get an error that $d is a directory -- how do I strip the name to create the concatenated filename?

Thanks

Body:
This requires Ed, which should hopefully be present on your machine.  If not, I trust your distribution will have a package for it.

#!/bin/sh

cat >> edprint+.txt << EOF
  1p
  q
EOF

cat >> edpop+.txt << EOF
  1d
  wq
EOF

b1="${PWD}/data/B1"
c1="${PWD}/$data/C1"

find "${b1}" -maxdepth 1 -type f > b1stack
find "${c1}" -maxdepth 1 -type f > c1stack

while [ $(wc -l b1stack | cut -d' ' -f1) -gt 0 ]
do
  b1line=$(ed -s b1stack < edprint+.txt)
  b1name=$(basename "${b1line}")
  b1suffix=$(echo "${b1name}" | cut -d'_' -f3)
  b1fixed=$(echo "B1_${b1suffix}"
  mv -v "${b1}/${b1line}" "${b1}/${b1fixed}"
  ed -s b1stack < edpop+.txt
done

while [ $(wc -l c1stack | cut -d' ' -f1) -gt 0 ]
do
  c1line=$(ed -s c1stack < edprint+.txt)
  c1name=$(basename "${c1line}")
  c1suffix=$(echo "${c1name}" | cut -d'_' -f3)
  c1fixed=$(echo "B1_${c1suffix}"
  mv -v "${c1}/${c1line}" "${c1}/${c1fixed}"
  ed -s c1stack < edpop+.txt
done

rm -v ./edprint+.txt
rm -v ./edpop+.txt
rm -v ./b1stack
rm -v ./c1stack


问:
Get All The youtube video from specific channel in reactjs
I am trying to get video from a specific channel in youtube using youtube data api using reactjs.But my api query doesnot return anything.Here is what i've tried for getting the video.What am i doing wrong here.</p>

```<code>    componentDidMount() {
        console.log('componentDidMount colling ...');

        fetch('https://www.googleapis.com/youtube/v3/channels?key="MYAPIKEY"&channelId="MYCHANNELID"&part=snippet,id&order=date&maxResults=2')
            .then(results => {
                this.setState({videos: results.json()});
                this.setState({playingVideoId: this.state.videos[this.index]});
                console.log("videos",this.state.videos)
                console.log("videos",this.state.playingVideoId)

            })
 }
</code>```

答:
First try to use postman to see if URL is returning correct data.

Second: setState is asynchronous which means, if you console.log right after setting state, you won't get correct results. Also, your second call to setState is using data from first call therefore you won't get right results. Just call setState once and use callback to log what you got.

```<code>componentDidMount() {
    console.log('componentDidMount colling ...');

    fetch('https://www.googleapis.com/youtube/v3/channels?key="MYAPIKEY"&channelId="MYCHANNELID"&part=snippet,id&order=date&maxResults=2')
        .then(results => {
            const videosObj = results.json();
            this.setState({
                videos: videosObj,
                playingVideoId: videosObj[this.index]
            }, (updatedState) => {
                console.log("videos", updatedState.videos);
                console.log("videos", updatedState.playingVideoId);
            });
        })
}
</code>```

Body:
I am trying to get video from a specific channel in youtube using youtube data api using reactjs.But my api query doesnot return anything.Here is what i've tried for getting the video.What am i doing wrong here.

    componentDidMount() {
        console.log('componentDidMount colling ...');

        fetch('https://www.googleapis.com/youtube/v3/channels?key="MYAPIKEY"&channelId="MYCHANNELID"&part=snippet,id&order=date&maxResults=2')
            .then(results => {
                this.setState({videos: results.json()});
                this.setState({playingVideoId: this.state.videos[this.index]});
                console.log("videos",this.state.videos)
                console.log("videos",this.state.playingVideoId)

            })
 }

Body:
First try to use postman to see if URL is returning correct data.

Second: setState is asynchronous which means, if you console.log right after setting state, you won't get correct results. Also, your second call to setState is using data from first call therefore you won't get right results. Just call setState once and use callback to log what you got.

componentDidMount() {
    console.log('componentDidMount colling ...');

    fetch('https://www.googleapis.com/youtube/v3/channels?key="MYAPIKEY"&channelId="MYCHANNELID"&part=snippet,id&order=date&maxResults=2')
        .then(results => {
            const videosObj = results.json();
            this.setState({
                videos: videosObj,
                playingVideoId: videosObj[this.index]
            }, (updatedState) => {
                console.log("videos", updatedState.videos);
                console.log("videos", updatedState.playingVideoId);
            });
        })
}


答:
You can subset with a logical vector testing your conditions.

```<code>x$b[x$b < 4 | x$b > 9] <- NA
x$c[x$c < 50 | x$c > 80] <- NA
x
#  a  b  c
#1 2  4 50
#2 1  5 NA
#3 9 NA 77
#4 2  9 NA
#5 9 NA NA
#6 8 NA 60
</code>```

Data:

```<code>x <- structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, 1, 9, 12,
NA), c = c(50, 34, 77, 88, 33, 60)), class = "data.frame", row.names = c(NA,
-6L))
</code>```

Title: Replace values outside range with NA using replace_with_na function

Body:
You can subset with a logical vector testing your conditions.

x$b[x$b < 4 | x$b > 9] <- NA
x$c[x$c < 50 | x$c > 80] <- NA
x
#  a  b  c
#1 2  4 50
#2 1  5 NA
#3 9 NA 77
#4 2  9 NA
#5 9 NA NA
#6 8 NA 60

Data:

x <- structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, 1, 9, 12,
NA), c = c(50, 34, 77, 88, 33, 60)), class = "data.frame", row.names = c(NA,
-6L))


问:
how to read the response from a web site?
I have a website url which gives corresponding city names by taking zip code as input parameter. Now I want to know how to read the response from the site.

This is the link I am using http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680

答:
first of all, you better find a good Web Service for this purpose.

and this is an HttpWebRequest example:

```<code>HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680");
                httpRequest.Credentials = CredentialCache.DefaultCredentials;
                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();

                Stream dataStream = httpResponse.GetResponseStream();
</code>```

Body:
first of all, you better find a good Web Service for this purpose.

and this is an HttpWebRequest example:

HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680");
                httpRequest.Credentials = CredentialCache.DefaultCredentials;
                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();

                Stream dataStream = httpResponse.GetResponseStream();


答:
Try this:</p>

```<code>import statistics
foo =  [[4, 6, 2, 7], [1.2, 8.3, 9, 16]]
x = [statistics.mean(i) for i in zip(*foo)]
print(x)
</code>```

Title: Mean of elements from arbitrary number of nested lists

Body:
If I have a list, say:

foo =  [[4, 6, 2, 7], [1.2, 8.3, 9, 16]]

I can get the mean of each element as follows:

[(a + b) / 2 for a, b in zip(foo[0], foo[1])]

or

import statistics
[statistics.mean(i) for i in zip(foo[0], foo[1])]

How can I do the same with an arbitrary number of nested lists in foo?

I tried several things but they do not work, for example:

[statistics.mean(i) for i in zip(list(foo))]

I would strongly prefer to just use comprehension.

Body:
Try this:

import statistics
foo =  [[4, 6, 2, 7], [1.2, 8.3, 9, 16]]
x = [statistics.mean(i) for i in zip(*foo)]
print(x)


问:
Combining data from one column into one with multiplication

I am trying to find a way to add up amount with the same ID and different units but also perform multiplication or division on them before adding them together.
The column time describes the amount of time spent doing a certain task.
There are four different values the time column can have which are:
- Uur (which stands for Hours)
- Minuut (which stands for Minutes)
- Etmaal (which stands for 24 hours)
- Dagdeel (which stands for 4 hours)

What I'd like is to transform them all into hours which should eventually return the row:

```<code>ID | Amount  | Time |
---------------------
82 | 1690634 | Uur  |
</code>```

So only one unit remains.

This means rows that contain minuut will have their amount divided by 60
Rows that contain etmaal will have their amount multiplied by 24
and rows that contain dagdeel will have their amount multiplied by 4

答:
I think the logic is:</p>

```<code>select id,
       (case when time = 'minuut' then amount / 60
             when time = 'etmaal' then amount * 24
             when time = 'dagdeel' then amount / 4
             when time = 'uur' then amount
        end) as amount,
       time
from table
</code>```

Body:
I am trying to find a way to add up amount with the same ID and different units but also perform multiplication or division on them before adding them together.
The column time describes the amount of time spent doing a certain task.
There are four different values the time column can have which are:
- Uur (which stands for Hours)
- Minuut (which stands for Minutes)
- Etmaal (which stands for 24 hours)
- Dagdeel (which stands for 4 hours)

What I'd like is to transform them all into hours which should eventually return the row:

ID | Amount  | Time |
---------------------
82 | 1690634 | Uur  |

So only one unit remains.

This means rows that contain minuut will have their amount divided by 60
Rows that contain etmaal will have their amount multiplied by 24
and rows that contain dagdeel will have their amount multiplied by 4

Body:
I think the logic is:

select id,
       (case when time = 'minuut' then amount / 60
             when time = 'etmaal' then amount * 24
             when time = 'dagdeel' then amount / 4
             when time = 'uur' then amount
        end) as amount,
       time
from table


问:
Get List of Last 15 Days Date in SQL
Could SQL get list of date of last 15 days date in a single query?

We can get today date with

select current_date()

We also can get last 15 days date with

select date_add(current_date(), -15)

But how to show the list of last 15 days date?
For example the output is

```<code>2020-05-17,
2020-05-18,
2020-05-19,
2020-05-20,
2020-05-21,
2020-05-22,
2020-05-23,
2020-05-24,
2020-05-25,
2020-05-26,
2020-05-27,
2020-05-28,
2020-05-29,
2020-05-30,
2020-05-31
</code>```

Title: Get List of Last 15 Days Date in SQL

Body:
Could SQL get list of date of last 15 days date in a single query?

We can get today date with

select current_date()

We also can get last 15 days date with

select date_add(current_date(), -15)

But how to show the list of last 15 days date?
For example the output is

2020-05-17,
2020-05-18,
2020-05-19,
2020-05-20,
2020-05-21,
2020-05-22,
2020-05-23,
2020-05-24,
2020-05-25,
2020-05-26,
2020-05-27,
2020-05-28,
2020-05-29,
2020-05-30,
2020-05-31

Body:
In Hive or Spark-SQL:

select date_add (date_add(current_date,-15),s.i) as dt
  from ( select posexplode(split(space(15),' ')) as (i,x)) s

Result:

2020-05-18
2020-05-19
2020-05-20
2020-05-21
2020-05-22
2020-05-23
2020-05-24
2020-05-25
2020-05-26
2020-05-27
2020-05-28
2020-05-29
2020-05-30
2020-05-31
2020-06-01
2020-06-02

See also this answer.


问:
Where my application's database is stored
I`m new to Android developement.  I want to know by adding this code where the database physically exists in my application folder.</p>

```<code>SQLiteDatabase myDB = info.this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
 myDB.execSQL("CREATE TABLE IF NOT EXISTS "
     + TableName
     + " (Field1 VARCHAR, Field2 INT(3));");
 Toast.makeText(this,"Database Created", Toast.LENGTH_SHORT).show();
   /* Insert data to a Table*/
   myDB.execSQL("INSERT INTO "
     + TableName
     + " (Field1, Field2)"
     + " VALUES ('Raj Gaurav', 24);");
</code>```

答:
```<code>String path = myDB.getPath()
</code>```

SQLiteDatabase.getPath()

Body:
I`m new to Android developement.  I want to know by adding this code where the database physically exists in my application folder.

SQLiteDatabase myDB = info.this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
 myDB.execSQL("CREATE TABLE IF NOT EXISTS "
     + TableName
     + " (Field1 VARCHAR, Field2 INT(3));");
 Toast.makeText(this,"Database Created", Toast.LENGTH_SHORT).show();
   /* Insert data to a Table*/
   myDB.execSQL("INSERT INTO "
     + TableName
     + " (Field1, Field2)"
     + " VALUES ('Raj Gaurav', 24);");

Body:
String path = myDB.getPath()

SQLiteDatabase.getPath()


问:
Is there a lower_bound() function in C++ for long long data type?
pos is an iterator to the lower bound of q. Here q is a long long integer and prefix is a vector which stores long long elements.

```<code>vector <int> :: iterator pos;
pos = lower_bound(prefix.begin(), prefix.end(), q);
</code>```

I get the following error:

```<code>no operator "=" matches these operands -- operand types are: __gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int>>> = __gnu_cxx::__normal_iterator<long long *, std::vector<long long, std::allocator<long long>>>
</code>```

Is there any way to fix this?

答:
Your declaration of pos is incorrect. You vector - prefix is of declared as vector<long long>prefix;. The iterator should also be of the same type.

You can try using the following -

```<code>vector<long long>::iterator pos = lower_bound(prefix.begin(), prefix.end(), q);
</code>```

You can always choose the following syntax as well if you are not sure of how to declare the variable(iterator in this case) properly :

```<code>auto pos = lower_bound(prefix.begin(), prefix.end(), q);
</code>```

The auto keyword can only be used in C++11 and above. But, if you are sure of the syntax and type of the variable you are declaring, it's always preferable to declare it manually rather than having it inferred by your program. It will increase the reliability as well as readability of your program.

Hope this solves your issue !

Body:
pos is an iterator to the lower bound of q. Here q is a long long integer and prefix is a vector which stores long long elements.

vector <int> :: iterator pos;
pos = lower_bound(prefix.begin(), prefix.end(), q);

I get the following error:

no operator "=" matches these operands -- operand types are: __gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int>>> = __gnu_cxx::__normal_iterator<long long *, std::vector<long long, std::allocator<long long>>>

Is there any way to fix this?

Body:
Your declaration of pos is incorrect. You vector - prefix is of declared as vector<long long>prefix;. The iterator should also be of the same type.

You can try using the following -

vector<long long>::iterator pos = lower_bound(prefix.begin(), prefix.end(), q);

You can always choose the following syntax as well if you are not sure of how to declare the variable(iterator in this case) properly :

auto pos = lower_bound(prefix.begin(), prefix.end(), q);

The auto keyword can only be used in C++11 and above. But, if you are sure of the syntax and type of the variable you are declaring, it's always preferable to declare it manually rather than having it inferred by your program. It will increase the reliability as well as readability of your program.

Hope this solves your issue !


问:
Mean of elements from arbitrary number of nested lists
If I have a list, say:

```<code>foo =  [[4, 6, 2, 7], [1.2, 8.3, 9, 16]]
</code>```

I can get the mean of each element as follows:

```<code>[(a + b) / 2 for a, b in zip(foo[0], foo[1])]
</code>```

or

```<code>import statistics
[statistics.mean(i) for i in zip(foo[0], foo[1])]
</code>```

How can I do the same with an arbitrary number of nested lists in foo?

I tried several things but they do not work, for example:

```<code>[statistics.mean(i) for i in zip(list(foo))]
</code>```

I would strongly prefer to just use comprehension.

答:
The following code should do the work:

[sum(i)/len(i) for i in zip(*foo)]
```


问:
How do I specify a mediatype of text/plain;charset=UTF-8 in a Spring Boot Test
Here's my test :

```<code> @Test
 fun `test config properties`() {
    mockMvc.request(HttpMethod.GET,"someUrl") {
        accept = MediaType.TEXT_PLAIN
    }.andExpect {
        status { isOk }
        content { contentType(MediaType.TEXT_PLAIN) }
    }
}
</code>```

and it fails with this:

Expected :text/plain Actual   :text/plain;charset=UTF-8

This is using the Kotlin DSL for MockMVC.

How do I change the accept to allow for charset=UTF-8 ?

答:
There is one factory method which accepts custom value. Try:</p>

```<code>MediaType.valueOf("text/plain;charset=UTF-8")
</code>```

Body:
Here's my test :

 @Test
 fun `test config properties`() {
    mockMvc.request(HttpMethod.GET,"someUrl") {
        accept = MediaType.TEXT_PLAIN
    }.andExpect {
        status { isOk }
        content { contentType(MediaType.TEXT_PLAIN) }
    }
}

and it fails with this:

Expected :text/plain Actual   :text/plain;charset=UTF-8

This is using the Kotlin DSL for MockMVC.

How do I change the accept to allow for charset=UTF-8 ?

Body:
There is one factory method which accepts custom value. Try:

MediaType.valueOf("text/plain;charset=UTF-8")


问:
Problem adjusting to different screen sizes
I have a problem to adjust some UI-text between iPhoneX and iPad (gen 5 testing).

All except some text works. I think I have tried all kinds of different setups but still do not succeed. The number boxes, in screenshot, have it's markers in the four corners. I think you can see what is missing. I have googled etc. and would appreciate some tip's for this.

Screenshot 1, iPhoneX:

Screenshot 2: iPad Gen 5:

Screenshot 3:
Changed with or height in Canvas, changed the left marker to upper left corned and the other on right-upper corner and got this result:

Didn't manage to get the titles aligned so I guess I have to live with this.

答: Try set the canvas scaler -> UI scale mode to scale with screen size</p>


问:
Does mysqldump support a progress bar?
Is there any way to determine, while mysqldump is running, how much of the backup has completed or how much is remaining?

答:
After MySQL 5.7+, you can use mysqlpump.
Although it doesn't show a progress bar, it still shows some progress like this:</p>

```<code>Dump progress: 1/1 tables, 0/191 rows
Dump progress: 16/17 tables, 19959/116836 rows
Dump progress: 18/19 tables, 22959/117032 rows
Dump progress: 19/21 tables, 24459/118851 rows
Dump progress: 19/22 tables, 26959/118852 rows
Dump progress: 21/23 tables, 28545/119020 rows
Dump progress: 22/23 tables, 30045/119020 rows
...
</code>```

Title: Does mysqldump support a progress bar?

Body:
After MySQL 5.7+, you can use mysqlpump.
Although it doesn't show a progress bar, it still shows some progress like this:

Dump progress: 1/1 tables, 0/191 rows
Dump progress: 16/17 tables, 19959/116836 rows
Dump progress: 18/19 tables, 22959/117032 rows
Dump progress: 19/21 tables, 24459/118851 rows
Dump progress: 19/22 tables, 26959/118852 rows
Dump progress: 21/23 tables, 28545/119020 rows
Dump progress: 22/23 tables, 30045/119020 rows
...


问:
Android toolbar icon color not so bright
I am developing an app in which there are multiple tabs with icon without any title. The problem is that the icons are not looking as bright it should. I used white color(FFFFFF) in creating icon assets. Still it doesn't looks so good.

The pic above shows Facebook Messenger and my App. There is difference between color(although both are white).
Any suggestion will be appreciated.

答:
Note: The question is old, but I consider sharing this information could be useful for anyone who could stumble upon this issue in the future.

If you use the Asset Studio tool from the Android Studio your icons will contain
alpha channel with a value of 60% (value depends on selected colour). I provided an example below.

In case you can use vector graphics it should work for you because you can freely edit XML file describing the generated image. Just remove android:alpha=".." attribute.

If you cannot use vector graphics and want to avoid transparency use this official online tool from Google to generate material icons for your application.

This tool supports multiple sizes, black and white colours, and SVG as well as PNG format:

Issues example of 60% alpha channel in Android Studio: