问:
CSS print sheet problem
What a maddening problem.

I'm working on a site built on top of a CMS, so the markup is... not clean. I'm trying to write a print style sheet but it's being wildly inconsistent across browsers (I know, a shock).

Link: http://www.gastongov.com/departments/county-commission/contact-info

IE7 and IE9 look fine.

IE8, the text is larger and the footer disclaimer is cut off on the right side of the page.

Firefox 4 is the worst, as the content is bumped down to the 2nd page, and any content that doesn't fit on that page is hacked off never to be seen again.

PLEASE help. I'm at the end of my rope trying to get these browsers to work in Dead Tree Mode.

答:
You've got a few curly problems, but here are some easy things that will at least help diagnosing and fixing them easier, even if they don't fix the problems themselves directly.

Your print style sheet loads before 'page.css' and a bunch of other CSS files which appear to come from the CMS you're using. All of which have an effective media type of 'all'. Any styles which appear in both places can be overridden. I see you've gone crazy with !important in your print.css, which suggests you've maybe already thought of that, or are stuck with it.

For the text sizing issue, I would look at using a print-specific 'reset' stylesheet, to set a base font-size on the  of a sensible point size (10 or 12pt). Points make a lot of sense for print-based styles, and don't rely on the browser remapping a pixel size to points on the printer.

Then for all of your text-based elements you want to give a different size to, specify a multiplying value in ems. So, you might have:

```<code>body {font-size:10pt;}

h1 {font-size:1.8em;}
h2 {font-size:1.4em;}
h3 {font-size:1.2em;}
/*  etc.  */
</code>```

As far as Firefox cutting things off goes, I seem to recall that printing is handled differently inside of forms - but I can't find where I got that information. It might be relevant, because your entire page is wrapped in a <form> element (thanks to your CMS, I guess). As a test, try saving out your page to static HTML, and removing that form element - see if you get a different result when you print.

Good luck - this print stuff is nasty at the best of times - worse yet when you don't control the HTML!

Title: CSS print sheet problem

Body:
You've got a few curly problems, but here are some easy things that will at least help diagnosing and fixing them easier, even if they don't fix the problems themselves directly.

Your print style sheet loads before 'page.css' and a bunch of other CSS files which appear to come from the CMS you're using. All of which have an effective media type of 'all'. Any styles which appear in both places can be overridden. I see you've gone crazy with !important in your print.css, which suggests you've maybe already thought of that, or are stuck with it.

For the text sizing issue, I would look at using a print-specific 'reset' stylesheet, to set a base font-size on the <body> of a sensible point size (10 or 12pt). Points make a lot of sense for print-based styles, and don't rely on the browser remapping a pixel size to points on the printer.

Then for all of your text-based elements you want to give a different size to, specify a multiplying value in ems. So, you might have:

body {font-size:10pt;}

h1 {font-size:1.8em;}
h2 {font-size:1.4em;}
h3 {font-size:1.2em;}
/*  etc.  */

As far as Firefox cutting things off goes, I seem to recall that printing is handled differently inside of forms - but I can't find where I got that information. It might be relevant, because your entire page is wrapped in a <form> element (thanks to your CMS, I guess). As a test, try saving out your page to static HTML, and removing that form element - see if you get a different result when you print.

Good luck - this print stuff is nasty at the best of times - worse yet when you don't control the HTML!


来源: stackexchange

问:
Deleting last node from Firebase Realtime Database via REST API
My Firebase Realtime Database looks like this:

I want to delete last node -M8VOQO11nYo8iMC6NZ_ from it.
In the official document of Firebase REST API the CURL code to delete it is curl -X DELETE \
  'https://[PROJECT_ID].firebaseio.com/Texter.json'
 but it deletes the entire branch. Is there a way to delete only the last node?

答:
You can only write/delete a node if you knows its entire path. So to delete the last child node, you need to take two steps:

Use a query in a GET call to determine the key of the last child node

Use DELETE call to then delete that path.

The query would look something like:

```<code>https://[PROJECT_ID].firebaseio.com/Texter.json?orderBy="$key"&limitToLast=1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can only write/delete a node if you knows its entire path. So to delete the last child node, you need to take two steps:

Use a query in a GET call to determine the key of the last child node

Use DELETE call to then delete that path.

The query would look something like:

https://[PROJECT_ID].firebaseio.com/Texter.json?orderBy="$key"&limitToLast=1


问:
AnalyserNode.getFloatFrequencyData() returns negative values
I'm trying to get the volume of a microphone input using the Web Audio API using AnalyserNode.getFloatFrequencyData().

The spec states that "each item in the array represents the decibel value for a specific frequency" but it returns only negative values although they do look like they are reacting to the level of sound - a whistle will return a value of around -23 and silence around -80 (the values in the dataArray are also all negative, so I don't think it's to do with how I've added them together) . The same code gives the values I'd expect (positive) with AnalyserNode.getByeFrequencyData() but the decibel values returned have been normalised between 0-255 so are more difficult to add together to determine the overall volume.

Why am I not getting the values I expect? And/or is this perhaps not a good way of getting the volume of the microphone input in the first place?

```<code>function getVolume(analyser) {
  analyser.fftSize = 32;
  let bufferLength = analyser.frequencyBinCount;
  let dataArray = new Float32Array(bufferLength);
  analyser.getFloatFrequencyData(dataArray);
  let totalAntilogAmplitude = 0;
  for (let i = 0; i < bufferLength; i++) {
    let thisAmp = dataArray[i]; // amplitude of current bin
      let thisAmpAntilog = Math.pow(10, (thisAmp / 10)) // antilog amplitude for adding
      totalAntilogAmplitude = totalAntilogAmplitude + thisAmpAntilog;
  }
  let amplitude = 10 * Math.log10(totalAntilogAmplitude);
  return amplitude;
}
</code>```

答:
Your code looks correct.  But without an example, it's hard to tell if it's producing the values you expect.  Also, since you're just computing (basically), the sum of all the values of the transform coefficients, you've just done a a more expensive version of summing the squares of the time domain signal.

Another alternative would square the signal, filter it a bit to smooth out variations, and get the output value at various times.  Something like the following, where s is the node that has the signal you're interested in.

```<code>let g = new GainNode(context, {gain: 0});
s.connect(g);
s.connect(g.gain);
// Output of g is now the square of s

let f = new BiquadFilterNode(context, {frequency: 10});
// May want to adjust the frequency some to other value for your needs.
// I arbitrarily chose 10 Hz.
g.connect(f).connect(analyser)

// Now get the time-domain value from the analyser and just take the first
// value from the signal.  This is the energy of the signal and represents
// the volume.
</code>```

Body:
I'm trying to get the volume of a microphone input using the Web Audio API using AnalyserNode.getFloatFrequencyData().

The spec states that "each item in the array represents the decibel value for a specific frequency" but it returns only negative values although they do look like they are reacting to the level of sound - a whistle will return a value of around -23 and silence around -80 (the values in the dataArray are also all negative, so I don't think it's to do with how I've added them together) . The same code gives the values I'd expect (positive) with AnalyserNode.getByeFrequencyData() but the decibel values returned have been normalised between 0-255 so are more difficult to add together to determine the overall volume.

Why am I not getting the values I expect? And/or is this perhaps not a good way of getting the volume of the microphone input in the first place?

function getVolume(analyser) {
  analyser.fftSize = 32;
  let bufferLength = analyser.frequencyBinCount;
  let dataArray = new Float32Array(bufferLength);
  analyser.getFloatFrequencyData(dataArray);
  let totalAntilogAmplitude = 0;
  for (let i = 0; i < bufferLength; i++) {
    let thisAmp = dataArray[i]; // amplitude of current bin
      let thisAmpAntilog = Math.pow(10, (thisAmp / 10)) // antilog amplitude for adding
      totalAntilogAmplitude = totalAntilogAmplitude + thisAmpAntilog;
  }
  let amplitude = 10 * Math.log10(totalAntilogAmplitude);
  return amplitude;
}

Body:
Your code looks correct.  But without an example, it's hard to tell if it's producing the values you expect.  Also, since you're just computing (basically), the sum of all the values of the transform coefficients, you've just done a a more expensive version of summing the squares of the time domain signal.

Another alternative would square the signal, filter it a bit to smooth out variations, and get the output value at various times.  Something like the following, where s is the node that has the signal you're interested in.

let g = new GainNode(context, {gain: 0});
s.connect(g);
s.connect(g.gain);
// Output of g is now the square of s

let f = new BiquadFilterNode(context, {frequency: 10});
// May want to adjust the frequency some to other value for your needs.
// I arbitrarily chose 10 Hz.
g.connect(f).connect(analyser)

// Now get the time-domain value from the analyser and just take the first
// value from the signal.  This is the energy of the signal and represents
// the volume.


问:
Using Map function with Lambda in Python: TypeError: () takes 0 positional arguments but 1 was given
System: WIN10

IDE: MS VSCode

Language: Python version 3.7.3

Library: pandas version 1.0.1

Data source: base data supplied below

Dataset: base data supplied below

I am having an issue for some reason when trying to use the "map" function to map A converter function (I built using lambda) to iterate across a list of sample temperatures. The sample code is supplied below and it keeps throwing the following error: TypeError: () takes 0 positional arguments but 1 was given

Steps were taken:

tested independent pieces of the code to ensure the list of tuples in temps made since

searched online for the error code and could not find anything

Code:

```<code>temps = [('Berlin', 29), ('Cairo', 36), ('Buenos Aires', 19), ('Los Angeles', 26), ('Tokyo', 27), ('New York', 28), ('London', 22), ('Beijing', 32)]

c_to_f = lambda: (data[0], (9/5)*data[1] + 32)

list(map(c_to_f, temps))
</code>```

error

```<code>TypeError: () takes 0 positional arguments but 1 was given
</code>```

答:
The map function will pass each element of temps as an argument to c_to_f.

Change your c_to_f definition so it takes an argument:

```<code>def c_to_f(data):
    return data[0], (9/5)*data[1] + 32
</code>```

or just do:

```<code>list(map(lambda data: (data[0], (9/5)*data[1] + 32), temps))
</code>```

Body:
System: WIN10

IDE: MS VSCode

Language: Python version 3.7.3

Library: pandas version 1.0.1

Data source: base data supplied below

Dataset: base data supplied below

I am having an issue for some reason when trying to use the "map" function to map A converter function (I built using lambda) to iterate across a list of sample temperatures. The sample code is supplied below and it keeps throwing the following error: TypeError: () takes 0 positional arguments but 1 was given

Steps were taken:

tested independent pieces of the code to ensure the list of tuples in temps made since

searched online for the error code and could not find anything

Code:

temps = [('Berlin', 29), ('Cairo', 36), ('Buenos Aires', 19), ('Los Angeles', 26), ('Tokyo', 27), ('New York', 28), ('London', 22), ('Beijing', 32)]

c_to_f = lambda: (data[0], (9/5)*data[1] + 32)

list(map(c_to_f, temps))

error

TypeError: () takes 0 positional arguments but 1 was given

Body:
The map function will pass each element of temps as an argument to c_to_f.

Change your c_to_f definition so it takes an argument:

def c_to_f(data):
    return data[0], (9/5)*data[1] + 32

or just do:

list(map(lambda data: (data[0], (9/5)*data[1] + 32), temps))


问:
Loop until matrix is full?
I have a conditional statement that adds row of binary values from matrix A to matrix B. I want to put this in a loop so that it continues to add rows from matrix A until matrix B is full. Currently matrix B is initialized as 10 by 10 matrix of zeros. Do I need to initialize matrix B differently in order to create this condition or is there a way of doing it as is?

Below is roughly how my code looks so far

```<code>from random import sample
import numpy as np

matrixA = np.random.randint(2, size=(10,10))

matrixB = np.zeros((10,10))

x, y = sample(range(1, 10), k=2)

if someCondition:
    matrixB = np.append(matrixB, [matrixA[x]], axis=0)
else:
    matrixB = np.append(matrixB, [matrixA[y]], axis=0)
</code>```

答:
you don't need a loop for it. It is really easy to just do it using smart indexing. For example:</p>

```<code>import numpy as np

A = np.random.randint(0, 10, size=(20,10))
B = np.empty((10, 10))
print(A)
# Copy till the row that satisfies your conditions. Here I assume it to be 10
B = A[:10, :]
print(B)
</code>```

Title: Loop until matrix is full?

Body:
I have a conditional statement that adds row of binary values from matrix A to matrix B. I want to put this in a loop so that it continues to add rows from matrix A until matrix B is full. Currently matrix B is initialized as 10 by 10 matrix of zeros. Do I need to initialize matrix B differently in order to create this condition or is there a way of doing it as is?

Below is roughly how my code looks so far

from random import sample
import numpy as np

matrixA = np.random.randint(2, size=(10,10))

matrixB = np.zeros((10,10))

x, y = sample(range(1, 10), k=2)

if someCondition:
    matrixB = np.append(matrixB, [matrixA[x]], axis=0)
else:
    matrixB = np.append(matrixB, [matrixA[y]], axis=0)

Body:
you don't need a loop for it. It is really easy to just do it using smart indexing. For example:

import numpy as np

A = np.random.randint(0, 10, size=(20,10))
B = np.empty((10, 10))
print(A)
# Copy till the row that satisfies your conditions. Here I assume it to be 10
B = A[:10, :]
print(B)


问:
Split a string with multiple delimiters in Ruby
Take for instance, I have a string like this:

```<code>options = "Cake or pie, ice cream, or pudding"
</code>```

I want to be able to split the string via or, ,, and , or.

The thing is, is that I have been able to do it, but only by parsing , and , or first, and then splitting each array item at or, flattening the resultant array afterwards as such:

```<code>options = options.split(/(?:\s?or\s)*([^,]+)(?:,\s*)*/).reject(&:empty?);
options.each_index {|index| options[index] = options[index].sub("?","").split(" or "); }
</code>```

The resultant array is as such: ["Cake", "pie", "ice cream", "pudding"]

Is there a more efficient (or easier) way to split my string on those three delimiters?

答:
As "or" and "," does the same thing, the best approach is to tell the regex that multiple cases should be treated the same as a single case:

```<code>options = "Cake or pie, ice cream, or pudding"
regex = /(?:\s*(?:,|or)\s*)+/
options.split(regex)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Take for instance, I have a string like this:

options = "Cake or pie, ice cream, or pudding"

I want to be able to split the string via or, ,, and , or.

The thing is, is that I have been able to do it, but only by parsing , and , or first, and then splitting each array item at or, flattening the resultant array afterwards as such:

options = options.split(/(?:\s?or\s)*([^,]+)(?:,\s*)*/).reject(&:empty?);
options.each_index {|index| options[index] = options[index].sub("?","").split(" or "); }

The resultant array is as such: ["Cake", "pie", "ice cream", "pudding"]

Is there a more efficient (or easier) way to split my string on those three delimiters?

Body:
As "or" and "," does the same thing, the best approach is to tell the regex that multiple cases should be treated the same as a single case:

options = "Cake or pie, ice cream, or pudding"
regex = /(?:\s*(?:,|or)\s*)+/
options.split(regex)


问:
Packages or functions for summarizing matrix in R that works similarly as dplyr?
I am running a very big simulation with 10,000 loops and to achieve better performance I have transformed the codes to generate matrix outputs, rather than data frame. It runs faster. However for each loop I need to summarize the outputs. For example, for below matrix,

```<code>mtx <- matrix(data = c(rep(c(1, 2), each = 6),
                       rep(c(3, 5, 7), each = 4),
                       rnorm(0, 1, n = 12)),
          ncol = 3)
colnames(mtx) <- c("A", "B", "Value")
</code>```

I want to summarize the number of observations in each A and B group, and calculate the mean values of Value, like the way that you could do with group_by() and summarize() in dplyr, if it's a data frame:

```<code>mtx %>% group_by(A, B) %>% summarize(N = n(), MEAN = mean(Value))
</code>```

Are there any functions/packages to do this directly on matrix, without transforming it into data frame? Because the simulation is too big, collecting all the raw outputs and summarizing after the for loop is not an option.

答:
You can use aggregate directly on a matrix.

```<code>aggregate(Value ~ A + B, data=mtx, mean)
  A B      Value
1 1 3 -0.2282783
2 1 5  0.5021404
3 2 5 -0.1693665
4 2 7  0.5118390
</code>```

Body:
I am running a very big simulation with 10,000 loops and to achieve better performance I have transformed the codes to generate matrix outputs, rather than data frame. It runs faster. However for each loop I need to summarize the outputs. For example, for below matrix,

mtx <- matrix(data = c(rep(c(1, 2), each = 6),
                       rep(c(3, 5, 7), each = 4),
                       rnorm(0, 1, n = 12)),
          ncol = 3)
colnames(mtx) <- c("A", "B", "Value")

I want to summarize the number of observations in each A and B group, and calculate the mean values of Value, like the way that you could do with group_by() and summarize() in dplyr, if it's a data frame:

mtx %>% group_by(A, B) %>% summarize(N = n(), MEAN = mean(Value))

Are there any functions/packages to do this directly on matrix, without transforming it into data frame? Because the simulation is too big, collecting all the raw outputs and summarizing after the for loop is not an option.

Body:
You can use aggregate directly on a matrix.

aggregate(Value ~ A + B, data=mtx, mean)
  A B      Value
1 1 3 -0.2282783
2 1 5  0.5021404
3 2 5 -0.1693665
4 2 7  0.5118390


问:
dotnet core no overload method for UseInMemoryDatabase() takes 0 argument
I am trying dotnet core tutorial at https://learn.microsoft.com/en-us/aspnet/core/tutorials/web-api-vsc

TodoContext.cs

```<code>using Microsoft.EntityFrameworkCore;
namespace TodoApi.Models
{
    public class TodoContext : DbContext
    {
        public TodoContext(DbContextOptions<TodoContext> options)
            : base(options)
        {
        }
        public DbSet<TodoItem> TodoItems { get; set; }
    }
}
</code>```

Startup.cs

```<code>using ...
using TodoApi.Models;
using Microsoft.EntityFrameworkCore;

namespace TodoApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase());
            services.AddMvc();
            services.AddScoped<ITodoRepository, TodoRepository>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseMvc();
        }
    }
}
</code>```

So I got this "no overload method for UseInMemoryDatabase() takes 0 argument"
I googled for UseInMemoryDatabase() method signature but could not find any.

What arguments should I provide to UseInMemoryDatabase()?

Update:

Once I downgrade Microsoft.EntityFrameworkCore.InMemory from 2.0.0-preview1-final to 1.1.1 and ran dotnet restore the error disappeared.

```<code>  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0-preview1-final"/>
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="1.1.1"/>
  </ItemGroup>
</code>```

I suspect the error is due to there is no "2.0.0-preview1-final" for Microsoft.EntityFrameworkCore.InMemory? If this is true then the error is not because of the number of argument but because InMemory db was is not installed and therefore UseInMemoryDatabase() was not defined anywhere in the project.

答:
Install-Package Microsoft.EntityFrameworkCore.InMemory

This solved my problem

Body:
I am trying dotnet core tutorial at https://learn.microsoft.com/en-us/aspnet/core/tutorials/web-api-vsc

TodoContext.cs

using Microsoft.EntityFrameworkCore;
namespace TodoApi.Models
{
    public class TodoContext : DbContext
    {
        public TodoContext(DbContextOptions<TodoContext> options)
            : base(options)
        {
        }
        public DbSet<TodoItem> TodoItems { get; set; }
    }
}

Startup.cs

using ...
using TodoApi.Models;
using Microsoft.EntityFrameworkCore;

namespace TodoApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase());
            services.AddMvc();
            services.AddScoped<ITodoRepository, TodoRepository>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseMvc();
        }
    }
}

So I got this "no overload method for UseInMemoryDatabase() takes 0 argument"
I googled for UseInMemoryDatabase() method signature but could not find any.

What arguments should I provide to UseInMemoryDatabase()?

Update:

Once I downgrade Microsoft.EntityFrameworkCore.InMemory from 2.0.0-preview1-final to 1.1.1 and ran dotnet restore the error disappeared.

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0-preview1-final"/>
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="1.1.1"/>
  </ItemGroup>

I suspect the error is due to there is no "2.0.0-preview1-final" for Microsoft.EntityFrameworkCore.InMemory? If this is true then the error is not because of the number of argument but because InMemory db was is not installed and therefore UseInMemoryDatabase() was not defined anywhere in the project.


问:
Laravel how can using the require file
Laravel how can I use the require file when using @section('content') method, how can I require the file into the this?

I want to using the menu bar, but I don't know how to separate it.

I have this code

```<code><div class="links">
            <a href="http://127.0.0.1:8000/aboutme">About Me</a>
            <a href="http://127.0.0.1:8000/employmenthistory">Employment History</a>
            <a href="https://laravel-news.com">News</a>
            <a href="https://blog.laravel.com">Blog</a>
            <a href="https://nova.laravel.com">Nova</a>
            <a href="https://forge.laravel.com">Forge</a>
            <a href="https://vapor.laravel.com">Vapor</a>
            <a href="https://github.com/laravel/laravel">GitHub</a>
        </div>
</code>```

can independent to menu.php

答:
Make menu.blade.php with this code in your views directory.

In place of code write @include('menu')

If location of file is different then @include('path-to-file') will be loaded.

Title: Laravel how can using the require file

Body:
Laravel how can I use the require file when using @section('content') method, how can I require the file into the this?

I want to using the menu bar, but I don't know how to separate it.

I have this code

            About Me
            Employment History
            News
            Blog
            Nova
            Forge
            Vapor
            GitHub

can independent to menu.php


问:
React.js: How do I send search query from react.js frontend to express.js backend?
I'm trying to create a simple search bar using react.js which will connect to my express.js back-end which will return the correct data from the database back to the front-end. But I haven't managed to understand how to send my custom research from my search bar in react to my back-end.

This is my Search component so far, it just creates a simple search bar which is supposed to send the query to the back-end:

```<code>mport React, { Component } from 'react';
import axios from 'axios';

export default class Search extends Component
{
    constructor(){
        super()
        this.state = {
            query: '',
            result: [],
            filteredResult: []
        };
    }

    getData = () => {
        axios.get("/get-data").then(function(response){
            this.setState({
                result: response.data
            })
        });
    };

    handleInputChange = () => (
        this.setState({
            query: this.search.value
        }), () => {
            if (this.state.query) {
                this.getData()
            }
        }
    );

    componentDidMount(){
        this.getData();
    };

    render() {
        return (
            <form>
                <input placeholder="Search for..." ref={input => this.search = input} onChange={this.handleInputChange}/>
                <p>{this.state.query}</p>
            </form>
        );
    }
}
</code>```

I can connect to the get-data rout, but I haven't managed to figure out how to send my search query to it. I've searched for quite a while and every example I've seen used a bunch of different API's from the web which isn't very helpful for my case.

So, how do I receive my search query inside of my back-end? Thanks!

答:
the second param .get() of axios is config which can hold a params object for any query params to add to the request. The keys of that object is the query key and the value of the keys are the values of the query ?searchTerm=searchValue. So it might look something like

```<code>getData = () => {
        axios.get(
           "/get-data",
           {
               params: {searchTerm: this.state.query}
           }
       ).then(function(response){
            this.setState({
                result: response.data
            })
        });
    };
</code>```

Body:
I'm trying to create a simple search bar using react.js which will connect to my express.js back-end which will return the correct data from the database back to the front-end. But I haven't managed to understand how to send my custom research from my search bar in react to my back-end.

This is my Search component so far, it just creates a simple search bar which is supposed to send the query to the back-end:

mport React, { Component } from 'react';
import axios from 'axios';

export default class Search extends Component
{
    constructor(){
        super()
        this.state = {
            query: '',
            result: [],
            filteredResult: []
        };
    }

    getData = () => {
        axios.get("/get-data").then(function(response){
            this.setState({
                result: response.data
            })
        });
    };

    handleInputChange = () => (
        this.setState({
            query: this.search.value
        }), () => {
            if (this.state.query) {
                this.getData()
            }
        }
    );

    componentDidMount(){
        this.getData();
    };

    render() {
        return (
            <form>
                <input placeholder="Search for..." ref={input => this.search = input} onChange={this.handleInputChange}/>

{this.state.query}

            </form>
        );
    }
}

I can connect to the get-data rout, but I haven't managed to figure out how to send my search query to it. I've searched for quite a while and every example I've seen used a bunch of different API's from the web which isn't very helpful for my case.

So, how do I receive my search query inside of my back-end? Thanks!

Body:
the second param .get() of axios is config which can hold a params object for any query params to add to the request. The keys of that object is the query key and the value of the keys are the values of the query ?searchTerm=searchValue. So it might look something like

getData = () => {
        axios.get(
           "/get-data",
           {
               params: {searchTerm: this.state.query}
           }
       ).then(function(response){
            this.setState({
                result: response.data
            })
        });
    };


问:
Typescript: Filter Object by Interface or Class
I would like to sync an object that is provided by an API to a table.
The table is defined in Sequelize and has an interface and a class:

declare interface SampleInterface {
  value1?: string;
  value2?: string;
  value3?: number;
}
```

<pre class="lang-js prettyprint-override"><code>class SampleClass implements SampleInterface {
  value1?: string;
  value2?: string;
  value3?: number;
}
</code>```

The response of the API is not always the same, but could look something like this:

const sampleResponse = {
  value2: "..."
  value3: 0
  value4: "..."
}
```

<p>Now, I would only like create a new object that can be passed to sequelize that has the matching contents, for example:</p>

<pre class="lang-js prettyprint-override"><code>const filteredResponse = {
  value2: "..."
  value3: 0
}
</code>```

How can I match the object properties keys to the interface or class?

Thanks!

答:
I think you need to extend your TypeScript with custom transformer like this one: ts-transformer-keys to be able to get the keys of an interface and the filter your response by copying only those keys.

Plain TypeScript doesn't generally allow pure type information to be passed to runtime code. So you can't see the interface at runtime and you can't know what are its fields to filter them.

You could get property names of a class, but you have to set them in your code:

```<code>class SampleClass implements SampleInterface {
  value1?: string = "";
  value2?: string = "";
  value3?: number = 0;
}

var a = new SampleClass();
for (var k in a) {
    console.log(k);  // prints value1, value2, value3
}
</code>```

Alternatively you could declare interface in this weird roundabout way through enum because enum is one of the TypeScript construct that are accessible at runtime:

```<code>enum Props {
    value1 = "value1",
    value2 = "value2",
    value3 = "value3"
};

declare interface SampleInterface {
  [Props.value1]?: string;
  [Props.value2]?: string;
  [Props.value3]?: number;
}

class SampleClass implements SampleInterface {
  value1?: string = "";
  value2?: string = "";
  value3?: number = 0;
}

for (var k in Props) {
    console.log(k);  // prints value1, value2, value3
}
</code>```

Body:
I would like to sync an object that is provided by an API to a table.
The table is defined in Sequelize and has an interface and a class:

declare interface SampleInterface {
  value1?: string;
  value2?: string;
  value3?: number;
}

class SampleClass implements SampleInterface {
  value1?: string;
  value2?: string;
  value3?: number;
}

The response of the API is not always the same, but could look something like this:

const sampleResponse = {
  value2: "..."
  value3: 0
  value4: "..."
}

Now, I would only like create a new object that can be passed to sequelize that has the matching contents, for example:

const filteredResponse = {
  value2: "..."
  value3: 0
}

How can I match the object properties keys to the interface or class?

Thanks!

Body:
I think you need to extend your TypeScript with custom transformer like this one: ts-transformer-keys to be able to get the keys of an interface and the filter your response by copying only those keys.

Plain TypeScript doesn't generally allow pure type information to be passed to runtime code. So you can't see the interface at runtime and you can't know what are its fields to filter them.

You could get property names of a class, but you have to set them in your code:

class SampleClass implements SampleInterface {
  value1?: string = "";
  value2?: string = "";
  value3?: number = 0;
}

var a = new SampleClass();
for (var k in a) {
    console.log(k);  // prints value1, value2, value3
}

Alternatively you could declare interface in this weird roundabout way through enum because enum is one of the TypeScript construct that are accessible at runtime:

enum Props {
    value1 = "value1",
    value2 = "value2",
    value3 = "value3"
};

declare interface SampleInterface {
  [Props.value1]?: string;
  [Props.value2]?: string;
  [Props.value3]?: number;
}

class SampleClass implements SampleInterface {
  value1?: string = "";
  value2?: string = "";
  value3?: number = 0;
}

for (var k in Props) {
    console.log(k);  // prints value1, value2, value3
}


问:
Passing variable args from macro to a function that expects va_list
```<code>#define exampleA(buf, args...) \
        exampleB(buf, ##args); \
    }

#endif
</code>```

works where the exampleB function declaration is exampleB(char* buf, ...).
But I need to change the declaration as exampleB(char* buf, va_list args). How can change the marco accordingly?

答:
I don't think this is possible the way you imagine it.
Let's consider a function exampleX(char *,...): the arguments you pass must live somewhere and let's say they are pushed to the stack. The va_list macros know that and can access them from there. The moment you leave that function, the arguments cannot be assumed to be on the stack anymore.

Thus, you may not write a helper function like va_list getArgs(char*x,...) { /* use va_start and return the va_list */ } and pass that va_list to exampleB.

The only thing I can think of is to write a trampoline function such as

```<code>void callExampleB(char * buf, ...) {
  va_list ap;
  va_start(ap, buf);
  exampleB(buf, ap);
  va_end(ap);
}
</code>```

and call that in your macro.

Body:
#define exampleA(buf, args...) \
        exampleB(buf, ##args); \
    }

#endif

works where the exampleB function declaration is exampleB(char* buf, ...).
But I need to change the declaration as exampleB(char* buf, va_list args). How can change the marco accordingly?

Body:
I don't think this is possible the way you imagine it.
Let's consider a function exampleX(char *,...): the arguments you pass must live somewhere and let's say they are pushed to the stack. The va_list macros know that and can access them from there. The moment you leave that function, the arguments cannot be assumed to be on the stack anymore.

Thus, you may not write a helper function like va_list getArgs(char*x,...) { /* use va_start and return the va_list */ } and pass that va_list to exampleB.

The only thing I can think of is to write a trampoline function such as

void callExampleB(char * buf, ...) {
  va_list ap;
  va_start(ap, buf);
  exampleB(buf, ap);
  va_end(ap);
}

and call that in your macro.


问:
Access routes in ruby after logged in
I have routes in routes.rb like: get 'users/edit/:id'. I made a login route as well.

I want to check if someone is logged in before he accesses a route, so if we try to access get 'users/edit/:id' without logged in we will redirect to the login screen.

How can I do that? I think I should write something after the routes to check if the user is logged in, but I don't know the syntax.
Thx for the answers

答:
This can be done at the controller level. You can add something called a before_filter to your edit action in the users/edit controller.

```<code>class UsersController < ApplicationController
  before_action :require_login, only: [:edit]

  def edit
    # your code here
  end
end
</code>```

You can also use many authentication gems (e.g. devise). Check devise out here: https://github.com/heartcombo/devise

It allows you to write code like this:

```<code>class MessagesController < ApplicationController
  before_action :authenticate_user!

  def new
    # your code here
  end

end
</code>```

I hope this helps. :)

Title: Access routes in ruby after logged in

Body:
This can be done at the controller level. You can add something called a before_filter to your edit action in the users/edit controller.

class UsersController < ApplicationController
  before_action :require_login, only: [:edit]

  def edit
    # your code here
  end
end

You can also use many authentication gems (e.g. devise). Check devise out here: https://github.com/heartcombo/devise

It allows you to write code like this:

class MessagesController < ApplicationController
  before_action :authenticate_user!

  def new
    # your code here
  end

end

I hope this helps. :)


问:
React context undefined
I have a basic authentication form created that works when I have all the code within the App.js file.
However, when I attempt to refactor the pages into separate files, the context is throwing an exception of it being empty.

App.js

```<code>import 'react-native-gesture-handler';

import * as React from 'react';
import { Button, Text, TextInput, View, StyleSheet } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import AuthContext from './src/utils/AuthContext';
import HomeScreen from './src/components/HomeScreen';
import SignInScreen from './src/components/SignInScreen';
import SplashScreen from './src/components/SplashScreen';

const Stack = createStackNavigator();

export default function App() {
  const [state, dispatch] = React.useReducer(
    (prevState, action) => {
      switch (action.type) {
        case 'RESTORE_TOKEN':
          return {
            ...prevState,
            userToken: action.token,
            isLoading: false,
          };
        case 'SIGN_IN':
          return {
            ...prevState,
            isSignout: false,
            userToken: action.token,
          };
        case 'SIGN_OUT':
          return {
            ...prevState,
            isSignout: true,
            userToken: null,
          };
      }
    },
    {
      isLoading: true,
      isSignout: false,
      userToken: null,
    }
  );

  React.useEffect(() => {
    // Fetch the token from storage then navigate to our appropriate place
    const bootstrapAsync = async () => {
      let userToken;

      try {
        userToken = await AsyncStorage.getItem('userToken');
      } catch (e) {
        // Restoring token failed
        console.log("Restoring token failed" + e);
      }
        dispatch({ type: 'RESTORE_TOKEN', token: userToken });
    };
    bootstrapAsync();
  }, []);

  const authContext = React.useMemo(
    () => ({
      signIn: async data => {
        dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
      },
      signUp: async data => {
        dispatch({ type: 'TO_SIGNUP_PAGE' });
       },
      signOut: () =>
        dispatch({ type: 'SIGN_OUT' }),
    }),
    []
  );

  return (
    <AuthContext.Provider value={authContext}>
      <NavigationContainer>
        <Stack.Navigator>
          {state.isLoading ? (
            // We haven't finished checking for the token yet
            <Stack.Screen name="Splash" component={SplashScreen} />
          ) : state.userToken == null ? (
            // No token found, user isn't signed in
            <Stack.Screen name="SignIn" component={SignInScreen} options={{ title: 'Sign in', animationTypeForReplace: state.isSignout ? 'pop' : 'push',}} />
            ) : (
                // User is signed in
                <Stack.Screen name="Home" component={HomeScreen} />
              )}
        </Stack.Navigator>
      </NavigationContainer>
    </AuthContext.Provider>
  );
}
</code>```

AuthContext.js

```<code>import { createContext } from 'react';

const AuthContext = createContext();

export default AuthContext;
</code>```

HomeScreen.js

```<code>import React, { useContext } from 'react';
import { View, Text, TextInput, Button } from 'react-native';

import AuthContext from '../utils/AuthContext';

const HomeScreen = () => {
    const { signOut } = useContext(AuthContext);

    return (
      <AuthContext>
        <Text>Signed in!</Text>
        <Button title="Sign out" onPress={signOut} />
      </AuthContext>
    );
  }

export default HomeScreen;
</code>```

Error:

I have spent many hours on this and looked through countless tutorials, for the life of me I can't figure out what I'm missing...

答:
You are not exporting the context. Your App.js file exports the App component but you are trying to access the AuthContext from that file.

The best approach to take is to place the context in a separate file and import it to both App.js and HomeScreen.js

Your context file should look like this

```<code>import { createContext } from 'react';

const AppContext = createContext();

export default AppContext;
</code>```

And you can import in other files like below

```<code>import AppContext from './AppContext';
</code>```

Title: React context undefined

Body:
I have a basic authentication form created that works when I have all the code within the App.js file.
However, when I attempt to refactor the pages into separate files, the context is throwing an exception of it being empty.

App.js

import 'react-native-gesture-handler';

import * as React from 'react';
import { Button, Text, TextInput, View, StyleSheet } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import AuthContext from './src/utils/AuthContext';
import HomeScreen from './src/components/HomeScreen';
import SignInScreen from './src/components/SignInScreen';
import SplashScreen from './src/components/SplashScreen';

const Stack = createStackNavigator();

export default function App() {
  const [state, dispatch] = React.useReducer(
    (prevState, action) => {
      switch (action.type) {
        case 'RESTORE_TOKEN':
          return {
            ...prevState,
            userToken: action.token,
            isLoading: false,
          };
        case 'SIGN_IN':
          return {
            ...prevState,
            isSignout: false,
            userToken: action.token,
          };
        case 'SIGN_OUT':
          return {
            ...prevState,
            isSignout: true,
            userToken: null,
          };
      }
    },
    {
      isLoading: true,
      isSignout: false,
      userToken: null,
    }
  );

  React.useEffect(() => {
    // Fetch the token from storage then navigate to our appropriate place
    const bootstrapAsync = async () => {
      let userToken;

      try {
        userToken = await AsyncStorage.getItem('userToken');
      } catch (e) {
        // Restoring token failed
        console.log("Restoring token failed" + e);
      }
        dispatch({ type: 'RESTORE_TOKEN', token: userToken });
    };
    bootstrapAsync();
  }, []);

  const authContext = React.useMemo(
    () => ({
      signIn: async data => {
        dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
      },
      signUp: async data => {
        dispatch({ type: 'TO_SIGNUP_PAGE' });
       },
      signOut: () =>
        dispatch({ type: 'SIGN_OUT' }),
    }),
    []
  );

  return (
    <AuthContext.Provider value={authContext}>
      <NavigationContainer>
        <Stack.Navigator>
          {state.isLoading ? (
            // We haven't finished checking for the token yet
            <Stack.Screen name="Splash" component={SplashScreen} />
          ) : state.userToken == null ? (
            // No token found, user isn't signed in
            <Stack.Screen name="SignIn" component={SignInScreen} options={{ title: 'Sign in', animationTypeForReplace: state.isSignout ? 'pop' : 'push',}} />
            ) : (
                // User is signed in
                <Stack.Screen name="Home" component={HomeScreen} />
              )}
        </Stack.Navigator>
      </NavigationContainer>
    </AuthContext.Provider>
  );
}

AuthContext.js

import { createContext } from 'react';

const AuthContext = createContext();

export default AuthContext;

HomeScreen.js

import React, { useContext } from 'react';
import { View, Text, TextInput, Button } from 'react-native';

import AuthContext from '../utils/AuthContext';

const HomeScreen = () => {
    const { signOut } = useContext(AuthContext);

    return (
      <AuthContext>
        <Text>Signed in!</Text>
        <Button title="Sign out" onPress={signOut} />
      </AuthContext>
    );
  }

export default HomeScreen;

Error:

I have spent many hours on this and looked through countless tutorials, for the life of me I can't figure out what I'm missing...

Body:
You are not exporting the context. Your App.js file exports the App component but you are trying to access the AuthContext from that file.

The best approach to take is to place the context in a separate file and import it to both App.js and HomeScreen.js

Your context file should look like this

import { createContext } from 'react';

const AppContext = createContext();

export default AppContext;

And you can import in other files like below

import AppContext from './AppContext';


问:
Using the same Docker image file permissions differ from machine to machine
I have a problem, that I cannot grasp at all. I'm running my Jenkins pipeline in a Docker container on the master node. Now I added another node and want to run the pipeline there as well.

However, using the same image I get different file permissions in the container:

```<code>### master
> docker image ls node:10.20.1-stretch
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
node                10.20.1-stretch     c5f1efe092a0        13 days ago         912MB
> docker run --rm -ti -u 1000:1000 node:10.20.1-stretch ls -la /home/node
total 20
drwxr-xr-x 2 1000 1000 4096 May 15 20:31 .
drwxr-xr-x 3    0    0 4096 May 15 20:31 ..
-rw-r--r-- 1 1000 1000  220 May 15  2017 .bash_logout
-rw-r--r-- 1 1000 1000 3526 May 15  2017 .bashrc
-rw-r--r-- 1 1000 1000  675 May 15  2017 .profile

### node 1
> docker image ls node:10.20.1-stretch
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
node                10.20.1-stretch     c5f1efe092a0        13 days ago         912MB
> docker run --rm -ti -u 1000:1000 node:10.20.1-stretch ls -la /home/node
total 20
drwxr-xr-x 2 0 0 4096 May 26 05:42 .
drwxr-xr-x 1 0 0 4096 May 26 05:42 ..
-rw-r--r-- 1 0 0  220 May 26 05:42 .bash_logout
-rw-r--r-- 1 0 0 3526 May 26 05:42 .bashrc
-rw-r--r-- 1 0 0  675 May 26 05:42 .profile
</code>```

I observed a similar behavior for the /tmp directory, which has chmod 1777 on master and 1755 on node 1.

```<code># master
> docker -v
Docker version 19.03.9, build 9d988398e7
> dockerd -v
Docker version 19.03.9, build 9d988398e7

# node 1
> docker -v
Docker version 19.03.10, build 9424aeaee9
> dockerd -v
Docker version 19.03.10, build 9424aeaee9
</code>```

I assume the wrong behavior is on node 1, as the /home/node directory and all of its children are owned by root:root there, but the same directory is owned by node:node on the master. However, I already upgraded the Docker version on node 1 from 19.03.8 to 19.03.10 and nothing changed.

It there anything I don't understand about Docker containers? I have been working with them for a while, but never observed such a behavior.

答: I have change the storage driver from overlay2 to aufs. Now I have the correct permissions.

Body:
I have a problem, that I cannot grasp at all. I'm running my Jenkins pipeline in a Docker container on the master node. Now I added another node and want to run the pipeline there as well.

However, using the same image I get different file permissions in the container:

### master
> docker image ls node:10.20.1-stretch
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
node                10.20.1-stretch     c5f1efe092a0        13 days ago         912MB
> docker run --rm -ti -u 1000:1000 node:10.20.1-stretch ls -la /home/node
total 20
drwxr-xr-x 2 1000 1000 4096 May 15 20:31 .
drwxr-xr-x 3    0    0 4096 May 15 20:31 ..
-rw-r--r-- 1 1000 1000  220 May 15  2017 .bash_logout
-rw-r--r-- 1 1000 1000 3526 May 15  2017 .bashrc
-rw-r--r-- 1 1000 1000  675 May 15  2017 .profile

### node 1
> docker image ls node:10.20.1-stretch
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
node                10.20.1-stretch     c5f1efe092a0        13 days ago         912MB
> docker run --rm -ti -u 1000:1000 node:10.20.1-stretch ls -la /home/node
total 20
drwxr-xr-x 2 0 0 4096 May 26 05:42 .
drwxr-xr-x 1 0 0 4096 May 26 05:42 ..
-rw-r--r-- 1 0 0  220 May 26 05:42 .bash_logout
-rw-r--r-- 1 0 0 3526 May 26 05:42 .bashrc
-rw-r--r-- 1 0 0  675 May 26 05:42 .profile

I observed a similar behavior for the /tmp directory, which has chmod 1777 on master and 1755 on node 1.

# master
> docker -v
Docker version 19.03.9, build 9d988398e7
> dockerd -v
Docker version 19.03.9, build 9d988398e7

# node 1
> docker -v
Docker version 19.03.10, build 9424aeaee9
> dockerd -v
Docker version 19.03.10, build 9424aeaee9

I assume the wrong behavior is on node 1, as the /home/node directory and all of its children are owned by root:root there, but the same directory is owned by node:node on the master. However, I already upgraded the Docker version on node 1 from 19.03.8 to 19.03.10 and nothing changed.

It there anything I don't understand about Docker containers? I have been working with them for a while, but never observed such a behavior.


问:
Destroying VM causes Guest Additions Mismatch to Recur
I use vagrant to create Vagrantfile:

```<code>vagrant init somedir/thebox-1.0.0 http://XX.XX.XXX.XXX.XXXX/somedir/thebox-1.0.0.box
</code>```

I run vagrant up:

```<code>vagrant up
</code>```

which displays (among other info)

```<code>[default] GuestAdditions versions on your host (6.1.8) and guest (6.0.2) do not match.
...
Complete!
Copy iso file C:\Program Files\Oracle\VirtualBox\VBoxGuestAdditions.iso into the box
/tmp/VBoxGuestAdditions.iso
Mounting Virtualbox Guest Additions ISO to: /mnt
mount: /dev/loop0 is write-protected, mounting read-only
Installing Virtualbox Guest Additions 6.1.8 - guest version is 6.0.2
Verifying archive integrity... All good.
Uncompressing VirtualBox 6.1.8 Guest Additions for Linux........
VirtualBox Guest Additions installer
Removing installed version 6.0.2 of VirtualBox Guest Additions...
Copying additional installer modules ...
Installing additional modules ...
VirtualBox Guest Additions: Starting.
VirtualBox Guest Additions: Building the VirtualBox Guest Additions kernel
modules.  This may take a while.
VirtualBox Guest Additions: To build modules for other installed kernels, run
VirtualBox Guest Additions:   /sbin/rcvboxadd quicksetup <version>
VirtualBox Guest Additions: or
VirtualBox Guest Additions:   /sbin/rcvboxadd quicksetup all
VirtualBox Guest Additions: Building the modules for kernel
3.10.0-957.1.3.el7.x86_64.
VirtualBox Guest Additions: Running kernel modules will not be replaced until
the system is restarted
An error occurred during installation of VirtualBox Guest Additions 6.1.8. Some functionality may not
work as intended.
In most cases it is OK that the "Window System drivers" installation failed.
Redirecting to /bin/systemctl start vboxadd.service
Redirecting to /bin/systemctl start vboxadd-service.service
Unmounting Virtualbox Guest Additions ISO from: /mnt
Got different reports about installed GuestAdditions version:
Virtualbox on your host claims:   6.0.2
VBoxService inside the vm claims: 6.1.8
Going on, assuming VBoxService is correct...
Got different reports about installed GuestAdditions version:
Virtualbox on your host claims:   6.0.2
VBoxService inside the vm claims: 6.1.8
Going on, assuming VBoxService is correct...
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
    default: /vagrant => C:/vagrant_devbox
</code>```

Now if I destroy the VM by:

```<code>vagrant destroy -f
</code>```

And then turn it on again via:

```<code>vagrant up
</code>```

The mismatch is still reported

```<code>[default] GuestAdditions versions on your host (6.1.8) and guest (6.0.2) do not match.
</code>```

The file already exists locally:

```<code>Copy iso file C:\Program Files\Oracle\VirtualBox\VBoxGuestAdditions.iso into the box
</code>```

How can I avoid getting the error

```<code>[default] GuestAdditions versions on your host (6.1.8) and guest (6.0.2) do not match.
</code>```

when vagrant up is first called?

I've seen answers like How to upgrade to VirtualBox Guest Additions on VM box?.  Installing vagrant-vbguest does not prevent the error when vagrant up is first called.

答:
Why do you have the error ?

You get this message because the vagrant box has been created with a prior version of VirtualBox (6.0.2) and the GuestAdditions has been installed on the box for this version. But now you run a newer version of VBox (6.1.8) so the system needs to copy on the box the updated tool.

You will get this message everytime you spin a new VM against this box and everytime you upgrade VirtualBox on your host.

How can I avoid getting the error

If you really want to avoid the error, you will need to upgrade your box and install the Guest Addition in the box and repackage the box

Body:
I use vagrant to create Vagrantfile:

vagrant init somedir/thebox-1.0.0 http://XX.XX.XXX.XXX.XXXX/somedir/thebox-1.0.0.box

I run vagrant up:

vagrant up

which displays (among other info)

[default] GuestAdditions versions on your host (6.1.8) and guest (6.0.2) do not match.
...
Complete!
Copy iso file C:\Program Files\Oracle\VirtualBox\VBoxGuestAdditions.iso into the box
/tmp/VBoxGuestAdditions.iso
Mounting Virtualbox Guest Additions ISO to: /mnt
mount: /dev/loop0 is write-protected, mounting read-only
Installing Virtualbox Guest Additions 6.1.8 - guest version is 6.0.2
Verifying archive integrity... All good.
Uncompressing VirtualBox 6.1.8 Guest Additions for Linux........
VirtualBox Guest Additions installer
Removing installed version 6.0.2 of VirtualBox Guest Additions...
Copying additional installer modules ...
Installing additional modules ...
VirtualBox Guest Additions: Starting.
VirtualBox Guest Additions: Building the VirtualBox Guest Additions kernel
modules.  This may take a while.
VirtualBox Guest Additions: To build modules for other installed kernels, run
VirtualBox Guest Additions:   /sbin/rcvboxadd quicksetup <version>
VirtualBox Guest Additions: or
VirtualBox Guest Additions:   /sbin/rcvboxadd quicksetup all
VirtualBox Guest Additions: Building the modules for kernel
3.10.0-957.1.3.el7.x86_64.
VirtualBox Guest Additions: Running kernel modules will not be replaced until
the system is restarted
An error occurred during installation of VirtualBox Guest Additions 6.1.8. Some functionality may not
work as intended.
In most cases it is OK that the "Window System drivers" installation failed.
Redirecting to /bin/systemctl start vboxadd.service
Redirecting to /bin/systemctl start vboxadd-service.service
Unmounting Virtualbox Guest Additions ISO from: /mnt
Got different reports about installed GuestAdditions version:
Virtualbox on your host claims:   6.0.2
VBoxService inside the vm claims: 6.1.8
Going on, assuming VBoxService is correct...
Got different reports about installed GuestAdditions version:
Virtualbox on your host claims:   6.0.2
VBoxService inside the vm claims: 6.1.8
Going on, assuming VBoxService is correct...
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
    default: /vagrant => C:/vagrant_devbox

Now if I destroy the VM by:

vagrant destroy -f

And then turn it on again via:

vagrant up

The mismatch is still reported

[default] GuestAdditions versions on your host (6.1.8) and guest (6.0.2) do not match.

The file already exists locally:

Copy iso file C:\Program Files\Oracle\VirtualBox\VBoxGuestAdditions.iso into the box

How can I avoid getting the error

[default] GuestAdditions versions on your host (6.1.8) and guest (6.0.2) do not match.

when vagrant up is first called?

I've seen answers like How to upgrade to VirtualBox Guest Additions on VM box?.  Installing vagrant-vbguest does not prevent the error when vagrant up is first called.


问:
Extract mapAsync to method in AkkaStreams
I have an Akka Streams flow, at one point I need to use mapAsync with a block of code.

```<code>    (...)
    .via(flow1)
    .mapAsync(1)(response =>
     * Several linees of code her*
    )
    .via(flow2)
</code>```

Is there a cleaner way of extracting it into a method?

```<code>    (...)
    .via(flow1)
    .doComputations
    .via(flow2)
</code>```

答:
Add a new flow

```<code>val asyncProc = Flow[T].mapAsync(1) { response =>
// Several lines of code here
}
</code>```

and use it with via

```<code>flow1
  .via(asyncProc)
  .via(flow2)

</code>```

Body:
I have an Akka Streams flow, at one point I need to use mapAsync with a block of code.

    (...)
    .via(flow1)
    .mapAsync(1)(response =>
     * Several linees of code her*
    )
    .via(flow2)

Is there a cleaner way of extracting it into a method?

    (...)
    .via(flow1)
    .doComputations
    .via(flow2)

Body:
Add a new flow

val asyncProc = Flow[T].mapAsync(1) { response =>
// Several lines of code here
}

and use it with via

flow1
  .via(asyncProc)
  .via(flow2)


问:
Where is the output parameter of a mapreduce used?
This is a code example from this tutorial:

http://kylebanker.com/blog/2009/12/mongodb-map-reduce-basics/

He notes that "as of MongoDB v1.8, you must specify an output collection name." But I don't see where this is referred to or why it is needed.

```<code># Running map-reduce from Ruby (irb) assuming
# that @comments references the comments collection

# Specify the map and reduce functions in JavaScript, as strings
>> map    = "function() { emit(this.author, {votes: this.votes}); }"
>> reduce = "function(key, values) { " +
  "var sum = 0; " +
  "values.forEach(function(doc) { " +
  " sum += doc.votes; " +
  "}); " +
  "return {votes: sum}; " +
"};"

# Pass those to the map_reduce helper method
@results = @comments.map_reduce(map, reduce, :out => "mr_results")

# Since this method returns an instantiated results collection,
# we just have to query that collection and iterate over the cursor.
>> @results.find().to_a
=> [{"_id" => "hwaet",   "value"=>{"votes"=>21.0}},
    {"_id" => "kbanker", "value"=>{"votes"=>13.0}}
   ]
</code>```

答:
The new Map / Reduce output options are documented here.

The basic premise is that Map / Reduce would originally just output to a temp collection. There were issues around the temp collection, (why do all of that work just to have it be temporary?) and there were some features added around merging and re-reducing.

In particular, you can now run an M/R that effectively updates what output from a previous M/R. (think of updating daily stats once / hour and only processing the last hour).

However, if you only want an in-memory version of the results, you can use the inline option.

```<code>{out: { inline : 1}}
</code>```

Body:
This is a code example from this tutorial:

http://kylebanker.com/blog/2009/12/mongodb-map-reduce-basics/

He notes that "as of MongoDB v1.8, you must specify an output collection name." But I don't see where this is referred to or why it is needed.

# Running map-reduce from Ruby (irb) assuming
# that @comments references the comments collection

# Specify the map and reduce functions in JavaScript, as strings
>> map    = "function() { emit(this.author, {votes: this.votes}); }"
>> reduce = "function(key, values) { " +
  "var sum = 0; " +
  "values.forEach(function(doc) { " +
  " sum += doc.votes; " +
  "}); " +
  "return {votes: sum}; " +
"};"

# Pass those to the map_reduce helper method
@results = @comments.map_reduce(map, reduce, :out => "mr_results")

# Since this method returns an instantiated results collection,
# we just have to query that collection and iterate over the cursor.
>> @results.find().to_a
=> [{"_id" => "hwaet",   "value"=>{"votes"=>21.0}},
    {"_id" => "kbanker", "value"=>{"votes"=>13.0}}
   ]

Body:
The new Map / Reduce output options are documented here.

The basic premise is that Map / Reduce would originally just output to a temp collection. There were issues around the temp collection, (why do all of that work just to have it be temporary?) and there were some features added around merging and re-reducing.

In particular, you can now run an M/R that effectively updates what output from a previous M/R. (think of updating daily stats once / hour and only processing the last hour).

However, if you only want an in-memory version of the results, you can use the inline option.

{out: { inline : 1}}


问:
Emscripten: How to define webidl for C++ array type
Hi I'm trying to convert the QR library quirc to WASM. For that I wrote a C++ wrapper such that I can use webIDL to make the conversion more straight forward. However I am having troubles with defining array types in webIDL. What would be correct webIDL for the next snippet</p>

```<code>        struct Point {
            int x;
            int y;
        };

        struct Code {
            /* The four corners of the QR-code, from top left, clockwise */
            Point corners[4];

            /* The number of cells across in the QR-code. The cell bitmap
            * is a bitmask giving the actual values of cells. If the cell
            * at (x, y) is black, then the following bit is set:
            *
            *     cell_bitmap[i >> 3] & (1 << (i & 7))
            *
            * where i = (y * size) + x.
            */
            int         size;
            uint8_t     cell_bitmap[QUIRC_MAX_BITMAP];
        };

</code>```

答:
The below idl file works</p>

```<code>interface Point {
    attribute long x;
    attribute long y;
};

interface Code {
    [Value] attribute Point[] corners;
    attribute long size;
    [BoundsChecked] attribute byte[] cell_bitmap;
};
</code>```

Body:
Hi I'm trying to convert the QR library quirc to WASM. For that I wrote a C++ wrapper such that I can use webIDL to make the conversion more straight forward. However I am having troubles with defining array types in webIDL. What would be correct webIDL for the next snippet

        struct Point {
            int x;
            int y;
        };

        struct Code {
            /* The four corners of the QR-code, from top left, clockwise */
            Point corners[4];

            /* The number of cells across in the QR-code. The cell bitmap
            * is a bitmask giving the actual values of cells. If the cell
            * at (x, y) is black, then the following bit is set:
            *
            *     cell_bitmap[i >> 3] & (1 << (i & 7))
            *
            * where i = (y * size) + x.
            */
            int         size;
            uint8_t     cell_bitmap[QUIRC_MAX_BITMAP];
        };

Body:
The below idl file works

interface Point {
    attribute long x;
    attribute long y;
};

interface Code {
    [Value] attribute Point[] corners;
    attribute long size;
    [BoundsChecked] attribute byte[] cell_bitmap;
};


问:
Visual Studio Code Plugins (Format / Spell Check)
Using the new Visual Studio Code editor vs 1. This is not the full Visual Studio IDE but their atom.io based code editor. I would like to install plugins specifically for spell check and formatting my code. How can I do this?

I've followed instructions here: Is there a command for formatting HTML in the Atom editor?
but realized that I do not have a install plugin command.

答:
Nowadays you can use Prettier and Code Spell Checker for the purposes.

Here are some use case for spell check:

Load a CSS, JavaScript, Text, etc. file. Words not in the dictionary files will have a squiggly underline below the text.

To see the list of suggestions just click on the  (lightbulb) in the left hand margin. You have the option to add your own words to the workspace dictionary.


问:
Buffering issue on Open pipe, write to file
I've got a script that opens a process which kicks off an external program.  The external program writes to stdout and in the parent program I'm writing both to stdout and to file.  The print to stdout is immediate but the print to file is buffering. It must be waiting on some kind of Xk number before dumping it to file.  I've tried autoflush on the output file, the pipe, stdout, and also use stdbuf.  But nothing works as it only writes to the file in chunk messages.  Am I missing something?</p>

```<code>      my $output = "/home/output.log";
      open(OL,">$output");
      OL->autoflush(1);
      open(P,'-|',"stdbuf -o0 -e0 external_program.py 2>&1");
      $| = 1;
      P->autoflush(1);
      STDOUT->autoflush(1);
      while(<P>) {
        chomp;
        print OL "$_\n";
        print "$_\n";
      }
      close(OL);
      close(P);
</code>```

答:
I am not sure why stdbuf does not work, but you can use the
unbuffer command instead. Here is a simple example:

```<code>use feature qw(say);
use strict;
use warnings;
my $output = "output.log";
open(my $OL,">", $output) or die "Could not open file '$output': $!";
my $pid = open (my $P, '-|', "unbuffer test.pl 2>&1");
while(<$P>) {
    chomp;
    print $OL "$_\n";
    print "$_\n";
}
close $OL;
close $P;
</code>```

where test.pl is given as:

```<code>#! /usr/bin/env perl
use strict;
use warnings;
for (1..5) {
    print "Hello\n";
    sleep 1;
}
</code>```

You can install the unbuffer command on Ubuntu with sudo apt-get install expect

Without unbuffer command in the above script, all the five line with Hello prints at once after 5 seconds in the terminal window. When the unbuffer command is used, a new line with Hello appears every second.

Update:

Since your script is named external_program.py I assume it is a python program? Then there is a -u command line option to python that turns off buffering and you can use this option instead of running unbuffer.

Body:
I've got a script that opens a process which kicks off an external program.  The external program writes to stdout and in the parent program I'm writing both to stdout and to file.  The print to stdout is immediate but the print to file is buffering. It must be waiting on some kind of Xk number before dumping it to file.  I've tried autoflush on the output file, the pipe, stdout, and also use stdbuf.  But nothing works as it only writes to the file in chunk messages.  Am I missing something?

      my $output = "/home/output.log";
      open(OL,">$output");
      OL->autoflush(1);
      open(P,'-|',"stdbuf -o0 -e0 external_program.py 2>&1");
      $| = 1;
      P->autoflush(1);
      STDOUT->autoflush(1);
      while(
) {
        chomp;
        print OL "$_\n";
        print "$_\n";
      }
      close(OL);
      close(P);

Body:
I am not sure why stdbuf does not work, but you can use the
unbuffer command instead. Here is a simple example:

use feature qw(say);
use strict;
use warnings;
my $output = "output.log";
open(my $OL,">", $output) or die "Could not open file '$output': $!";
my $pid = open (my $P, '-|', "unbuffer test.pl 2>&1");
while(<$P>) {
    chomp;
    print $OL "$_\n";
    print "$_\n";
}
close $OL;
close $P;

where test.pl is given as:

#! /usr/bin/env perl
use strict;
use warnings;
for (1..5) {
    print "Hello\n";
    sleep 1;
}

You can install the unbuffer command on Ubuntu with sudo apt-get install expect

Without unbuffer command in the above script, all the five line with Hello prints at once after 5 seconds in the terminal window. When the unbuffer command is used, a new line with Hello appears every second.

Update:

Since your script is named external_program.py I assume it is a python program? Then there is a -u command line option to python that turns off buffering and you can use this option instead of running unbuffer.


问:
@Value("${welcome}) in springboot is throwing illegal argument exception and could not resolve placeholder
```<code>@RestController
Class MyController{

@Value("${welcome}")
private String welcome;

@RequestMapping("/greet")
public String greetHim(){
  return welcome;
}

}
application.properties:
welcome=welcomeEla
</code>```

The above code is throwing illegal argument exception and saying could not resolve placeholder 'welcome' in value "${welcome}"

If I give a space between '$' and '{' it is not throwing any exception but it is fetching null value.

Also I tried with environment variable as autowired with @PropertySource("application.properties") over the Class it was also fetching null value (env.getProperty("welcome"))

Can anybody help me in this?
Thanks in advance

答:
Firstly ,

```<code>ApplicationContextProvider appContext = new ApplicationContextProvider();
Environment env = appContext.getApplicationContext().getEnvironment();
// env.getProperty() works!!!
String temp = env.getProperty("welcome");
System.out.println(temp) ;
</code>```

you run this code. And make sure it works. Do you try @Value("${welcome.toString()}") if it works

Body:
@RestController
Class MyController{

@Value("${welcome}")
private String welcome;

@RequestMapping("/greet")
public String greetHim(){
  return welcome;
}

}
application.properties:
welcome=welcomeEla

The above code is throwing illegal argument exception and saying could not resolve placeholder 'welcome' in value "${welcome}"

If I give a space between '$' and '{' it is not throwing any exception but it is fetching null value.

Also I tried with environment variable as autowired with @PropertySource("application.properties") over the Class it was also fetching null value (env.getProperty("welcome"))

Can anybody help me in this?
Thanks in advance

Body:
Firstly ,

ApplicationContextProvider appContext = new ApplicationContextProvider();
Environment env = appContext.getApplicationContext().getEnvironment();
// env.getProperty() works!!!
String temp = env.getProperty("welcome");
System.out.println(temp) ;

you run this code. And make sure it works. Do you try @Value("${welcome.toString()}") if it works


问:
Understanding Nested Joins
I've came across nested joins, which logic I cannot understand.

Names of tables are not important, query from which I extracted this - works.

```<code>FROM
    (((sea
    JOIN bold)
    JOIN ((genuine
    LEFT JOIN community_genuine_inspire ON (genuine.id = community_genuine_inspire.id_genuine))
    LEFT JOIN community_genuine ON (community_genuine.id = community_genuine_inspire.id_community)))
    JOIN cooperate)
WHERE
</code>```

There were used a lot of parentheses and JOIN shorthands and the question is - how should I "decode" this to the standard JOIN syntax avoiding all those shorthands?

答:
There is no nesting here. Parenthesis have been dropped here and there to obfuscate the code, which is basically equivalent to:

```<code>select *
FROM sea
JOIN bold
JOIN genuine
LEFT JOIN community_genuine_inspire ON genuine.id = community_genuine_inspire.id_genuine
LEFT JOIN community_genuine ON community_genuine.id = community_genuine_inspire.id_community
JOIN cooperate
</code>```

Is the ON clause optional? Yes, it is. It's what docs refer to as join_specification and is shown in brackets, documentation syntax that means optional:

```<code>joined_table: {
    table_reference {[INNER | CROSS] JOIN | STRAIGHT_JOIN} table_factor [join_specification]
  | table_reference {LEFT|RIGHT} [OUTER] JOIN table_reference join_specification
  | table_reference NATURAL [INNER | {LEFT|RIGHT} [OUTER]] JOIN table_factor
}

join_specification: {
    ON search_condition
  | USING (join_column_list)
}
</code>```

If you omit it I presume you get a CROSS JOIN (Cartesian product).

Title: Understanding Nested Joins

Body:
I've came across nested joins, which logic I cannot understand.

Names of tables are not important, query from which I extracted this - works.

FROM
    (((sea
    JOIN bold)
    JOIN ((genuine
    LEFT JOIN community_genuine_inspire ON (genuine.id = community_genuine_inspire.id_genuine))
    LEFT JOIN community_genuine ON (community_genuine.id = community_genuine_inspire.id_community)))
    JOIN cooperate)
WHERE

There were used a lot of parentheses and JOIN shorthands and the question is - how should I "decode" this to the standard JOIN syntax avoiding all those shorthands?

Body:
There is no nesting here. Parenthesis have been dropped here and there to obfuscate the code, which is basically equivalent to:

select *
FROM sea
JOIN bold
JOIN genuine
LEFT JOIN community_genuine_inspire ON genuine.id = community_genuine_inspire.id_genuine
LEFT JOIN community_genuine ON community_genuine.id = community_genuine_inspire.id_community
JOIN cooperate

Is the ON clause optional? Yes, it is. It's what docs refer to as join_specification and is shown in brackets, documentation syntax that means optional:

joined_table: {
    table_reference {[INNER | CROSS] JOIN | STRAIGHT_JOIN} table_factor [join_specification]
  | table_reference {LEFT|RIGHT} [OUTER] JOIN table_reference join_specification
  | table_reference NATURAL [INNER | {LEFT|RIGHT} [OUTER]] JOIN table_factor
}

join_specification: {
    ON search_condition
  | USING (join_column_list)
}

If you omit it I presume you get a CROSS JOIN (Cartesian product).


问:
Guice Multi-binding Injection in javax.validation.ConstraintValidator
I want to use Guice Multibinding injection in javax.validation.ConstraintValidator.

Not getting any clue to inject map binder in my ConstraintValidator class.

答:
I use the MapBinder in the following way, it does it's job, but I need to refactor to make it better.  To give you some background,  I had to match a legacy program for copying data from a primary database to any number of subsequent databases using a combination of files (don't ask, but it works).  Anyhow, I use a super simple mapping scheme of TableName -> TableTransferHandler, here is how I define the bindings:

```<code>MapBinder<String, TableTransferHandler<?>> binder
    = MapBinder.newMapBinder(
        binder(),
        new TypeLiteral<String>() {},
        new TypeLiteral<TableTransferHandler<?>>(){});

// Add my Table handlers based on table name.
binder.addBinding("table_one").to(TableOneTransferHandlerImpl.class);
binder.addBinding("table_two").to(TableTwoTransferHandlerImpl.class);
</code>```

which gets used as such:

```<code>@Inject
Map<String,TableTransferHandler<?>> handlers;

TableTransferHandler<?> handler = handlers.get(tableName);
handler.process();
</code>```

It's very trivial, and needs to be rewritten, but for the most part it gets the job done.  From what you've explained though, I'm not sure if you want MapBinder, you probably want to return the regular binding for a ConstraintValidator.  If I had chosen to implement a TableTransferHandler by remote system, instead of by name, I would have done this:

```<code>Multibinder<TableTransferHandler<UserAccess>> binder
    = Multibinder.newSetBinder(
        binder(),
        new TypeLiteral<TableTransferHandler<UserAccess>>() {});
// Add all my remote handlers relating to UserAccess
binder.addBinding().to(RemoteOneUserAccessTableHandler.class);
binder.addBinding().to(RemoteTwoUserAccessTableHandler.class);
</code>```

Which would then be used:

```<code>@Inject
Set<TableTransferHandler<UserAccess>> handlers;
for (TableTransferHandler<UserAccess> handler : handlers) {
    handler.process();
}
</code>```

Body:
I use the MapBinder in the following way, it does it's job, but I need to refactor to make it better.  To give you some background,  I had to match a legacy program for copying data from a primary database to any number of subsequent databases using a combination of files (don't ask, but it works).  Anyhow, I use a super simple mapping scheme of TableName -> TableTransferHandler, here is how I define the bindings:

MapBinder<String, TableTransferHandler<?>> binder
    = MapBinder.newMapBinder(
        binder(),
        new TypeLiteral<String>() {},
        new TypeLiteral<TableTransferHandler<?>>(){});

// Add my Table handlers based on table name.
binder.addBinding("table_one").to(TableOneTransferHandlerImpl.class);
binder.addBinding("table_two").to(TableTwoTransferHandlerImpl.class);

which gets used as such:

@Inject
Map<String,TableTransferHandler<?>> handlers;

TableTransferHandler<?> handler = handlers.get(tableName);
handler.process();

It's very trivial, and needs to be rewritten, but for the most part it gets the job done.  From what you've explained though, I'm not sure if you want MapBinder, you probably want to return the regular binding for a ConstraintValidator.  If I had chosen to implement a TableTransferHandler by remote system, instead of by name, I would have done this:

Multibinder<TableTransferHandler<UserAccess>> binder
    = Multibinder.newSetBinder(
        binder(),
        new TypeLiteral<TableTransferHandler<UserAccess>>() {});
// Add all my remote handlers relating to UserAccess
binder.addBinding().to(RemoteOneUserAccessTableHandler.class);
binder.addBinding().to(RemoteTwoUserAccessTableHandler.class);

Which would then be used:

@Inject
Set<TableTransferHandler<UserAccess>> handlers;
for (TableTransferHandler<UserAccess> handler : handlers) {
    handler.process();
}


问:
Assigning callbacks for a $.post call in jQuery
I have this script that works pretty well, but it keeps triggering the "error" callback, even though there is no error:

```<code>$(".comment-form").submit(function(e) {
    e.preventDefault();

    var $form = $(this),
        text = $form.find('textarea').val();
        url = $form.attr('action');

    $.post(url, { comment: text,
        beforeSend: function() {
            alert("before send");
        },
        error: function() {
            alert("error");
        },
        success: function(data) {
            alert(data);
        }
    });
});
</code>```

Am I using the callbacks incorrectly here? Shouldn't the error callback fire only if there's an ajax error?

My intention is react to the request. If it has an error, I want to do something. If it's successful, I want to do something else, etc...

答:
The ".post()" method only allows for a single callback (for "success").  If you want to do what you're doing, you'll need to use "$.ajax()".

edit — Helpful downvoter @trey points out that (as of jQuery 1.5) the return value of the "$.post()" call will be an object to which other handlers can be added, including handlers for "error" (but not for "beforeSend").

Body:
I have this script that works pretty well, but it keeps triggering the "error" callback, even though there is no error:

$(".comment-form").submit(function(e) {
    e.preventDefault();

    var $form = $(this),
        text = $form.find('textarea').val();
        url = $form.attr('action');

    $.post(url, { comment: text,
        beforeSend: function() {
            alert("before send");
        },
        error: function() {
            alert("error");
        },
        success: function(data) {
            alert(data);
        }
    });
});

Am I using the callbacks incorrectly here? Shouldn't the error callback fire only if there's an ajax error?

My intention is react to the request. If it has an error, I want to do something. If it's successful, I want to do something else, etc...


问:
How to show tooltip on disabled Button in Angular without wrapping button tag in div tag with tippy tooltip?
tippyTooltip is directive which uses tippy.js tooltip
<button [disabled]="true" tippyTooltip ></button>

答:
A normal tooltip can be achieved by using title attribute like below :- </p>

```<code><button [title]="'My ToolTip'"> My Button </button>
</code>```

Body:
A normal tooltip can be achieved by using title attribute like below :-

<button [title]="'My ToolTip'"> My Button </button>


问:
MySQL Interview Questions
I've been asked to screen some candidates for a MySQL DBA / Developer position for a role that requires an enterprise level skill set.

I myself am a SQL Server person so I know what I would be looking for from that point of view with regards to scalability / design etc but is there anything specific I should be asking with regards to MySQL?

I would ideally like to ask them about enterprise level features of MySQL that they would typically only use when working on a big database. Need to separate out the enterprise developers from the home / small website kind of guys.

Thanks.

答:
I'd ask about the differences between the the various storage engines, their perceived benefits and drawbacks.

Defiantly cover replication, and dig into the drawbacks of replication, esp when using tables with auto increment keys.

If they are still with you then ask about replication lag, it's effects and standard patterns for monitoring it.

OwnerDisplayName: Campbell

ContentLicense: CC BY-SA 2.5

Title: MySQL Interview Questions

OwnerDisplayName: Dave Cheney


问:
What algorithms there are for failover in a distributed system?
I'm planning on making a distributed database system using a shared-nothing architecture and multiversion concurrency control. Redundancy will be achieved through asynchronous replication (it's allowed to lose some recent changes in case of a failure, as long as the data in the system remains consistent). For each database entry, one node has the master copy (only that node has write access to it), in addition to which one or more nodes have secondary copies of the entry for scalability and redundancy purposes (the secondary copies are read-only). When the master copy of an entry is updated, it is timestamped and sent asynchronously to nodes with secondary copies so that finally they will get the latest version of the entry. The node that has the master copy can change at any time - if another node needs to write that entry, it will request the current owner of the master copy to give that node the ownership of that entry's master copy, and after receiving ownership that node can write the entry (all transactions and writes are local).

Lately I've been thinking about what to do when a node in the cluster goes down, that what strategy to use for failover. Here are some questions. I hope that you would know available alternatives to at least some of them.

What algorithms there are for doing failover in a distributed system?

What algorithms there are for consensus in a distributed system?

How should the nodes in the cluster determine that a node is down?

How should the nodes determine that what database entries had their master copy on the failed node at the time of failure, so that other nodes may recover those entries?

How to decide that which node(s) has the latest secondary copy of some entry?

How to decide that which node's secondary copy should be promoted to be the new master copy?

How to handle it, if the node which was though to be down, suddenly comes back as if nothing happened?

How to avoid split-brain scenarios, where the network is temporarily split into two, and both sides think that the other side has died?

答:
Tackling just a small part of your question: there's no way in the scenario you describe to decide (in the abstract) which node(s) have the latest secondary copy.  At best, some node can poll and determine (after a bit of communication) who among the nodes that they know of / can see, and that know of / can see them, and that can't see the old master has the most current copy.  But:

They can't find out the status of nodes they can't reach

They can't find out the status of nodes that can't reach them

They can't be sure that what they think they know about the status of a node that can see the old master when they can't is current--the master could have updated the shared neighbor after the neighbor reported status.

On the broader issues, you may want to look at how something like memcached and the like handle the issues, and especially read through the lists to see what problems they've encountered when theory met practice.

OwnerDisplayName: Esko Luontola

LastEditorDisplayName: Esko Luontola

OwnerDisplayName: MarkusQ

LastEditorDisplayName: MarkusQ


问:
Using a global variable in JavaScript
How do I do this?

My code is something like this:

```<code>var number = null;

function playSong(artist, title, song, id)
{
    alert('old number was: ' + [number] + '');

    var number = '10';

    alert('' + [number] + '');
}
</code>```

The first alert always returns 'old number was: ' and not 10. Shouldn't it return 10 on both alerts on the second function call?

答:
I’ve come across this answer in 2020 and after searching some more online I have found that apparently in the JavaScript definitions if you place variables outside of functions or even create a file called globals.js and just put all your globally required variables in that file, make that file the first user .js file in your script tags after jQuery and any other plugins you need, globals will load before your other scripts and allow you to call variables from globals.js within any script on the page.

W3C JavaScript Scope

I have tested this theory within a PHP application that I am building and I have been able to call variables from the globals.js file within a page that is loaded via Ajax to a jconfirm dialog for a troubleshooting wizard to set up the return values for when the dialog is closed.

Title: Using a global variable in JavaScript

Body:
How do I do this?

My code is something like this:

var number = null;

function playSong(artist, title, song, id)
{
    alert('old number was: ' + [number] + '');

    var number = '10';

    alert('' + [number] + '');
}

The first alert always returns 'old number was: ' and not 10. Shouldn't it return 10 on both alerts on the second function call?


问:
Department has Maximum Staff
Write a query to display the name of the department that has the maximum staff count order by department name.

This is the schema of my problem:

I tried this:

```<code>select d.department_name
from   department d
       inner join staff s on d.department_id=s.department_id
group by d.department_name
having count(s.staff_id) >= all
       ( select count(s.staff_id) as cnt
         from   department d
                inner join staff s on d.department_id=s.department_id
         group by department_name )
order by d.department_name desc;
</code>```

and I was able to pass one test case which results in 'SE' department, but I wasn't able to pass another test case.I don't know what second testcase want. I am not sure what I have done wrong in my code above.

答:
You can use the windows function as follows:</p>

```<code>select department_name, cnt
from
(select department_name, rank() over (order by cnt desc) as rn, cnt
from
(select d.department_name, count(1) cnt
   from department d inner join staff s
     on d.department_id=s.department_id
      group by d.department_name))
where rn = 1
order by department_name
</code>```

Title: Department has Maximum Staff

Body:
Write a query to display the name of the department that has the maximum staff count order by department name.

This is the schema of my problem:

I tried this:

select d.department_name
from   department d
       inner join staff s on d.department_id=s.department_id
group by d.department_name
having count(s.staff_id) >= all
       ( select count(s.staff_id) as cnt
         from   department d
                inner join staff s on d.department_id=s.department_id
         group by department_name )
order by d.department_name desc;

and I was able to pass one test case which results in 'SE' department, but I wasn't able to pass another test case.I don't know what second testcase want. I am not sure what I have done wrong in my code above.

Body:
You can use the windows function as follows:

select department_name, cnt
from
(select department_name, rank() over (order by cnt desc) as rn, cnt
from
(select d.department_name, count(1) cnt
   from department d inner join staff s
     on d.department_id=s.department_id
      group by d.department_name))
where rn = 1
order by department_name


问:
Xcode swift view wrap content
I'm an Android developer trying my hand at Xcode and it's been unpleasant so far. What I'm trying to do is have a custom view that has three sub views:

UIImageView (for an icon)

UILabel (for the title)

UILabel (for the content)

I want it such that the content label's height grows and shrinks to wrap the text it contains (like Android's wrap_content). And then, I want the custom view to also grow and shrink to wrap all three sub views.

However, I cannot, for the life of me, figure out how these auto layouts/constraints work.

01) How would I make my UILabel's height grow/shrink to match its contained text?

02) How would I make my custom view's height grow/shrink to match its contained sub views?

```<code>override func layoutSubviews() {
    super.layoutSubviews()
    img_icon = UIImageView()
    txt_title = UILabel()
    txt_content = UILabel()

    img_icon.backgroundColor = Palette.white
    img_icon.image = icon
    txt_title.text = title
    txt_title.textAlignment = .Center
    txt_title.font = UIFont(name: "Roboto-Bold", size:14)
    txt_title.textColor = Palette.txt_heading1
    txt_content.text = content
    txt_content.textAlignment = .Center
    txt_content.font = UIFont(name: "Roboto-Regular", size:12)
    txt_content.textColor = Palette.txt_dark
    txt_content.numberOfLines = 0
    txt_content.preferredMaxLayoutWidth = self.frame.width
    txt_content.lineBreakMode = NSLineBreakMode.ByWordWrapping
    self.backgroundColor = Palette.white
    addSubview(img_icon)
    addSubview(txt_title)
    addSubview(txt_content)

    /*snip img_icon and txt_title constraints*/

    let txt_content_x = NSLayoutConstraint(item: txt_content, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0)
    let txt_content_y = NSLayoutConstraint(item: txt_content, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 80)
    let txt_content_w = NSLayoutConstraint(item: txt_content, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: 0)
    let txt_content_h = NSLayoutConstraint(item: txt_content, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 40)
    txt_content.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activateConstraints([
        txt_content_x,
        txt_content_y,
        txt_content_w,
        txt_content_h
    ])
}
</code>```

I understand that, in the above code I've tried, I have the height set to a constant 40. This is only because I don't know how to achieve what I want.

[EDIT]

I've tried setting the height constraint to greater than or equal to but it just crashes Xcode.

[EDIT]

It crashes Xcode if I try to view it but works perfectly fine in the simulator. Question now is, why?

My height constraint is now:

```<code>let txt_content_h = NSLayoutConstraint(item: txt_content, attribute: .Height, relatedBy: .GreaterThanOrEqual, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 40)
</code>```

It works in the simulator and has the desired behaviour. However, if I open the storyboard that contains the view, it crashes. It's definitely that line of code because changing it back to .Equal resolves the crash.

[EDIT]

My temporary fix is:

```<code>#if TARGET_INTERFACE_BUILDER
    //use .Equal for height constraint
#else
    //use .GreaterThanOrEqual for height constraint
#endif
</code>```

This way, it doesn't crash Xcode and still renders the way I want it on the simulator.

[EDIT]

I removed the pre-processor check because I realized there's no actual thing like that defined and it still works now. I swear I've changed nothing else.

I am this close to giving up on iOS development because the interface builder keeps crashing Xcode without a reason when everything works in the simulator. Then, I do some nonsense edits and it works fine again.

答:
You can use a trick with constraints to achieve wrap-content. For example :

```<code>let maximumWidth = frame / 4  //For example
yourView.widthAnchor.constraint(lessThanOrEqualToConstant: maximumWidth).isActive = true
</code>```

The "maximumWidth" depends on your UI and your design and you can change it.

Also, you should set "lineBreakMode" in StoryBoard or in code like :

```<code>yourBtn.titleLabel?.lineBreakMode = .byCharWrapping //For UIButton or
yourTxt.textContainer.lineBreakMode = .byCharWrapping //For UITextView
</code>```

Title: Xcode swift view wrap content

Body:
I'm an Android developer trying my hand at Xcode and it's been unpleasant so far. What I'm trying to do is have a custom view that has three sub views:

UIImageView (for an icon)

UILabel (for the title)

UILabel (for the content)

I want it such that the content label's height grows and shrinks to wrap the text it contains (like Android's wrap_content). And then, I want the custom view to also grow and shrink to wrap all three sub views.

However, I cannot, for the life of me, figure out how these auto layouts/constraints work.

01) How would I make my UILabel's height grow/shrink to match its contained text?

02) How would I make my custom view's height grow/shrink to match its contained sub views?

override func layoutSubviews() {
    super.layoutSubviews()
    img_icon = UIImageView()
    txt_title = UILabel()
    txt_content = UILabel()

    img_icon.backgroundColor = Palette.white
    img_icon.image = icon
    txt_title.text = title
    txt_title.textAlignment = .Center
    txt_title.font = UIFont(name: "Roboto-Bold", size:14)
    txt_title.textColor = Palette.txt_heading1
    txt_content.text = content
    txt_content.textAlignment = .Center
    txt_content.font = UIFont(name: "Roboto-Regular", size:12)
    txt_content.textColor = Palette.txt_dark
    txt_content.numberOfLines = 0
    txt_content.preferredMaxLayoutWidth = self.frame.width
    txt_content.lineBreakMode = NSLineBreakMode.ByWordWrapping
    self.backgroundColor = Palette.white
    addSubview(img_icon)
    addSubview(txt_title)
    addSubview(txt_content)

    /*snip img_icon and txt_title constraints*/

    let txt_content_x = NSLayoutConstraint(item: txt_content, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0)
    let txt_content_y = NSLayoutConstraint(item: txt_content, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 80)
    let txt_content_w = NSLayoutConstraint(item: txt_content, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: 0)
    let txt_content_h = NSLayoutConstraint(item: txt_content, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 40)
    txt_content.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activateConstraints([
        txt_content_x,
        txt_content_y,
        txt_content_w,
        txt_content_h
    ])
}

I understand that, in the above code I've tried, I have the height set to a constant 40. This is only because I don't know how to achieve what I want.

[EDIT]

I've tried setting the height constraint to greater than or equal to but it just crashes Xcode.

[EDIT]

It crashes Xcode if I try to view it but works perfectly fine in the simulator. Question now is, why?

My height constraint is now:

let txt_content_h = NSLayoutConstraint(item: txt_content, attribute: .Height, relatedBy: .GreaterThanOrEqual, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 40)

It works in the simulator and has the desired behaviour. However, if I open the storyboard that contains the view, it crashes. It's definitely that line of code because changing it back to .Equal resolves the crash.

[EDIT]

My temporary fix is:

#if TARGET_INTERFACE_BUILDER
    //use .Equal for height constraint
#else
    //use .GreaterThanOrEqual for height constraint
#endif

This way, it doesn't crash Xcode and still renders the way I want it on the simulator.

[EDIT]

I removed the pre-processor check because I realized there's no actual thing like that defined and it still works now. I swear I've changed nothing else.

I am this close to giving up on iOS development because the interface builder keeps crashing Xcode without a reason when everything works in the simulator. Then, I do some nonsense edits and it works fine again.

Body:
You can use a trick with constraints to achieve wrap-content. For example :

let maximumWidth = frame / 4  //For example
yourView.widthAnchor.constraint(lessThanOrEqualToConstant: maximumWidth).isActive = true

The "maximumWidth" depends on your UI and your design and you can change it.

Also, you should set "lineBreakMode" in StoryBoard or in code like :

yourBtn.titleLabel?.lineBreakMode = .byCharWrapping //For UIButton or
yourTxt.textContainer.lineBreakMode = .byCharWrapping //For UITextView