问:
How to put a tooltip centered under a div?
How can I place the tooltip centered and directly under the red circle without Javascript? Thank you in advance! :-)

Here is an image of my problem and the marked position where it should be:

My code currently looks like this:

HTML code:

```<code><li>
   <a class="ovm-oup_tooltip" href="#">
     <div id="ovm-oup_under_item_1" class="ovm-oup_under_item">
        <span>Text</span>
        <img src="Example_Logo.svg" alt="">
     </div>
   </a>
</li>
</code>```

CSS code:

```<code>#ovm-oup_under ul{
  text-align: center;
  list-style-type: none;
  padding: 0;
}
#ovm-oup_under li{
  padding: 20px;
  margin: 15px;
  display: inline-block;
}
.ovm-oup_under_item{
  width: 96px;
  height: 96px;
  border-radius: 50%;
  box-shadow: 0 0 20px 5px rgba(0,0,0,.2);
  margin: 5px 5px 35px 5px;
}

.ovm-oup_tooltip {
    position: relative;
    display: inline;
}
.ovm-oup_tooltip span {
    position: absolute;
    width: auto;
    padding: 3px 15px;
    color: #FFFFFF;
    background: #000000;
    height: 30px;
    line-height: 30px;
    text-align: center;
    visibility: hidden;
    border-radius: 4px;
}
.ovm-oup_tooltip span:after {
    content: '';
    position: absolute;
    bottom: 100%;
    left: 50%;
    margin-left: -8px;
    width: 0; height: 0;
    border-bottom: 8px solid #000000;
    border-right: 8px solid transparent;
    border-left: 8px solid transparent;
}
.ovm-oup_tooltip:hover span {
    visibility: visible;
    margin: 0;
    top: 0%;
    left: 50%;
    z-index: 999;
}
</code>```

答:
One solution would be to combine absolute placement of the tooltip (relative to the parent div), with a translation transformation on the tooltip, which would achieve the required placement:

/* Extracted styling to top of style sheet to show the required additions */

.ovm-oup_tooltip span {
  /* Offset the tooltip 50% from left side of parent (div) width
  and 100% from top edge of parent height */
  left: 50%;
  top: 100%;

  /* Pull the tooltip back 50% of it's own width, nudge the tool
  tip downward 8px to account for arrow point */
  transform: translate(-50%, 8px);
}

.ovm-oup_under_item {
  /* Allow absolute placement of children (tooltip) */
  position: relative;
}

/* Your existing styling starts here */
.ovm-oup_under_item {
  width: 96px;
  height: 96px;
  border-radius: 50%;
  box-shadow: 0 0 20px 5px rgba(0, 0, 0, .2);
  margin: 5px 5px 35px 5px;
}

.ovm-oup_tooltip {
  position: relative;
  display: inline;
}

.ovm-oup_tooltip span {
  position: absolute;
  width: auto;
  padding: 3px 15px;
  color: #FFFFFF;
  background: #000000;
  height: 30px;
  line-height: 30px;
  text-align: center;
  visibility: hidden;
  border-radius: 4px;
}

.ovm-oup_tooltip span:after {
  content: '';
  position: absolute;
  bottom: 100%;
  left: 50%;
  margin-left: -8px;
  width: 0;
  height: 0;
  border-bottom: 8px solid #000000;
  border-right: 8px solid transparent;
  border-left: 8px solid transparent;
}

.ovm-oup_tooltip:hover span {
  visibility: visible;
  margin: 0;
  /* Remove
  top: 0%;
  */
  left: 50%;
  z-index: 999;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
  <div id="ovm-oup_under_item_1" class="ovm-oup_under_item">
    <span>Text</span>
    <img src="Example_Logo.svg" alt="">
  </div>
</code>```

The idea here is to use absolute placement of the tooltip (ie the span), to position the top-left corner of that span at the horizontal center, and bottom edge of the parent div. The transform rule is then used to offset the tooltip span relative to it's own dimensions, to achieve the final center/baseline placement.

You can merge the additions above with your existing styling - I extracted the changes to the top of the stylesheet to clarify the additons that were made to achieve the desired result. Hope that helps!

Body:
How can I place the tooltip centered and directly under the red circle without Javascript? Thank you in advance! :-)

Here is an image of my problem and the marked position where it should be:

My code currently looks like this:

HTML code:

        Text

CSS code:

#ovm-oup_under ul{
  text-align: center;
  list-style-type: none;
  padding: 0;
}
#ovm-oup_under li{
  padding: 20px;
  margin: 15px;
  display: inline-block;
}
.ovm-oup_under_item{
  width: 96px;
  height: 96px;
  border-radius: 50%;
  box-shadow: 0 0 20px 5px rgba(0,0,0,.2);
  margin: 5px 5px 35px 5px;
}

.ovm-oup_tooltip {
    position: relative;
    display: inline;
}
.ovm-oup_tooltip span {
    position: absolute;
    width: auto;
    padding: 3px 15px;
    color: #FFFFFF;
    background: #000000;
    height: 30px;
    line-height: 30px;
    text-align: center;
    visibility: hidden;
    border-radius: 4px;
}
.ovm-oup_tooltip span:after {
    content: '';
    position: absolute;
    bottom: 100%;
    left: 50%;
    margin-left: -8px;
    width: 0; height: 0;
    border-bottom: 8px solid #000000;
    border-right: 8px solid transparent;
    border-left: 8px solid transparent;
}
.ovm-oup_tooltip:hover span {
    visibility: visible;
    margin: 0;
    top: 0%;
    left: 50%;
    z-index: 999;
}

Body:
One solution would be to combine absolute placement of the tooltip (relative to the parent div), with a translation transformation on the tooltip, which would achieve the required placement:

/* Extracted styling to top of style sheet to show the required additions */

.ovm-oup_tooltip span {
  /* Offset the tooltip 50% from left side of parent (div) width
  and 100% from top edge of parent height */
  left: 50%;
  top: 100%;

  /* Pull the tooltip back 50% of it's own width, nudge the tool
  tip downward 8px to account for arrow point */
  transform: translate(-50%, 8px);
}

.ovm-oup_under_item {
  /* Allow absolute placement of children (tooltip) */
  position: relative;
}

/* Your existing styling starts here */
.ovm-oup_under_item {
  width: 96px;
  height: 96px;
  border-radius: 50%;
  box-shadow: 0 0 20px 5px rgba(0, 0, 0, .2);
  margin: 5px 5px 35px 5px;
}

.ovm-oup_tooltip {
  position: relative;
  display: inline;
}

.ovm-oup_tooltip span {
  position: absolute;
  width: auto;
  padding: 3px 15px;
  color: #FFFFFF;
  background: #000000;
  height: 30px;
  line-height: 30px;
  text-align: center;
  visibility: hidden;
  border-radius: 4px;
}

.ovm-oup_tooltip span:after {
  content: '';
  position: absolute;
  bottom: 100%;
  left: 50%;
  margin-left: -8px;
  width: 0;
  height: 0;
  border-bottom: 8px solid #000000;
  border-right: 8px solid transparent;
  border-left: 8px solid transparent;
}

.ovm-oup_tooltip:hover span {
  visibility: visible;
  margin: 0;
  /* Remove
  top: 0%;
  */
  left: 50%;
  z-index: 999;
}

<a class="ovm-oup_tooltip" href="#">
  <div id="ovm-oup_under_item_1" class="ovm-oup_under_item">
    <span>Text</span>
    <img src="Example_Logo.svg" alt="">
  </div>
</a>

The idea here is to use absolute placement of the tooltip (ie the span), to position the top-left corner of that span at the horizontal center, and bottom edge of the parent div. The transform rule is then used to offset the tooltip span relative to it's own dimensions, to achieve the final center/baseline placement.

You can merge the additions above with your existing styling - I extracted the changes to the top of the stylesheet to clarify the additons that were made to achieve the desired result. Hope that helps!


来源: stackexchange

问:
Best practice to deliver Core Data App with content?
Hey guys,

what would you say is the best way to ship initial data with an Core Data iOS App?

Is it maybe to once run the app, store the data and then insert the datafile in the build?
There must be a better way..

答: I've been toying around with the same problem myself, recently; and what I opted for was to store the data in the app in some easily parsable (for me) format, and parse and incorporate it on first run.</p>

ContentLicense: CC BY-SA 3.0


问:
How to seperate data from a file stream in c++
I just started learning c++ in college and for our first project we are asked to create a five function calculator (+, -, *, /, %) that reads input from a file, performs the arithmetic operation on it and outputs it to the screen. I am given an input file that as all the numbers like so :

```<code>/   100     10
109.5 +     1.0
25    /     2
25.5  /     2
0     /     0
8     *     8
10    -    10
ab    -    ab
100   -     1
10    *   -10
10.5  +  1000
1000  -  1.05
1000  *  1000
1000  /  1000
1000  /     0
</code>```

For my code, this is the best I have been able to come up with:

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

using namespace std;
const string file_name = "input.txt";

float calculate_number (float first_number, char symbol, float last_number);

int main () {
    ifstream input_file;
    ofstream output_file;

    // Open file to get input_file from
    input_file.open(file_name, ios::in);

    // Error checking
    if (!input_file) {
        cout << "Error: file input.txt does not exists\n";
        exit(1);
    } else {

        string data_from_file;           // Declare string to store data from file
        input_file >> data_from_file;    // Pass file content to data

        while (getline(input_file, data_from_file)) {
            istringstream ss(data_from_file);

            char symbol;
            int first_number, last_number;

            ss >> first_number >> symbol >> last_number;
            cout << first_number << symbol << last_number << endl;
        }
    }

    return 0;
}
```

<p>The above code gives the following output which is a mess, but still a huge step forward:</p>

```10010
109.5
25/2
25.5
0/0
8*8
10-10
0-10
100-1
10*-10
10.5
1000-1
1000*1000
1000/1000
1000/0

```

My question is, is their a way to separate each number and arithmetic operator from the input stream, add them together and display the output to the screen. Thanks in advance

答:
The simplest way to get the information from the input file is to extract it while iterating over the results gotten from the input file and passing it to a variable for easy reference.

#include <iostream>
#include <string>
#include <fstream>

using namespace std;
const string INPUT_FILE = "input.txt";
const string OUTPUT_FILE = "result.txt";

// Global variables

float first_number, second_number, answer;
char arithemetic_op;
ifstream input_file;     // File to get input from
ofstream output_file;    // File to put result in

// function prototype

float calculate (float first_number, char arithemetic_op, float second_number);

int main () {

    // Open file to get input_file from
    input_file.open(INPUT_FILE, ios::in);

    // Error if file does not exists
    if (!input_file) {
        cout << "Error: file `input.txt` does not exists\n";
        exit(1);
    }

    while (input_file >> first_number >> arithemetic_op >> second_number) {
        answer = calculate(first_number, arithemetic_op, second_number);

        output_file.open(OUTPUT_FILE, ios::out);
        output_file << first_number << " " << arithemetic_op << " " << second_number << " = " << answer << endl;
        output_file.close();
    }
    return 0;
}

float calculate (float first_number, char arithemetic_op, float second_number) {
    switch (arithemetic_op) {
        case '-':
            answer = first_number - second_number;
            return answer;
        case '+':
            answer = first_number + second_number;
            return answer;
        case '*':
            answer = first_number * second_number;
            return answer;
        case '/':
            answer = first_number / second_number;
            return answer;
    }
}
```

Cheers!

ContentLicense: CC BY-SA 4.0

Body:
I just started learning c++ in college and for our first project we are asked to create a five function calculator (+, -, *, /, %) that reads input from a file, performs the arithmetic operation on it and outputs it to the screen. I am given an input file that as all the numbers like so :

/   100     10
109.5 +     1.0
25    /     2
25.5  /     2
0     /     0
8     *     8
10    -    10
ab    -    ab
100   -     1
10    *   -10
10.5  +  1000
1000  -  1.05
1000  *  1000
1000  /  1000
1000  /     0

For my code, this is the best I have been able to come up with:

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

using namespace std;
const string file_name = "input.txt";

float calculate_number (float first_number, char symbol, float last_number);

int main () {
    ifstream input_file;
    ofstream output_file;

    // Open file to get input_file from
    input_file.open(file_name, ios::in);

    // Error checking
    if (!input_file) {
        cout << "Error: file input.txt does not exists\n";
        exit(1);
    } else {

        string data_from_file;           // Declare string to store data from file
        input_file >> data_from_file;    // Pass file content to data

        while (getline(input_file, data_from_file)) {
            istringstream ss(data_from_file);

            char symbol;
            int first_number, last_number;

            ss >> first_number >> symbol >> last_number;
            cout << first_number << symbol << last_number << endl;
        }
    }

    return 0;
}

The above code gives the following output which is a mess, but still a huge step forward:

10010
109.5
25/2
25.5
0/0
8*8
10-10
0-10
100-1
10*-10
10.5
1000-1
1000*1000
1000/1000
1000/0

My question is, is their a way to separate each number and arithmetic operator from the input stream, add them together and display the output to the screen. Thanks in advance

Body:
The simplest way to get the information from the input file is to extract it while iterating over the results gotten from the input file and passing it to a variable for easy reference.

#include <iostream>
#include <string>
#include <fstream>

using namespace std;
const string INPUT_FILE = "input.txt";
const string OUTPUT_FILE = "result.txt";

// Global variables

float first_number, second_number, answer;
char arithemetic_op;
ifstream input_file;     // File to get input from
ofstream output_file;    // File to put result in

// function prototype

float calculate (float first_number, char arithemetic_op, float second_number);

int main () {

    // Open file to get input_file from
    input_file.open(INPUT_FILE, ios::in);

    // Error if file does not exists
    if (!input_file) {
        cout << "Error: file `input.txt` does not exists\n";
        exit(1);
    }

    while (input_file >> first_number >> arithemetic_op >> second_number) {
        answer = calculate(first_number, arithemetic_op, second_number);

        output_file.open(OUTPUT_FILE, ios::out);
        output_file << first_number << " " << arithemetic_op << " " << second_number << " = " << answer << endl;
        output_file.close();
    }
    return 0;
}

float calculate (float first_number, char arithemetic_op, float second_number) {
    switch (arithemetic_op) {
        case '-':
            answer = first_number - second_number;
            return answer;
        case '+':
            answer = first_number + second_number;
            return answer;
        case '*':
            answer = first_number * second_number;
            return answer;
        case '/':
            answer = first_number / second_number;
            return answer;
    }
}

Cheers!


问:
Python - Except statement excepting ALL errors
I would expect this code to only catch an EOFError, but instead, it catches ALL exceptions...

    try:
        rpg.data.load("playerdata.dat")
    except EOFError:
        playerdata = rpg.data()
        titleList = ["Start", t.gray30("[DISABLED] Continue"), "Help/Credits", "Exit\n\n" + "  *" + " "* int(stream.width()/tfactor) + t.white("CONTROLS:") + t.gray30("\n\t[ENTER] and [Z] - Confirm Selection\n\tArrow Keys - Move Cursor")]
    else:
        playerdata = rpg.data.load("playerdata.dat")
        titleList = ["Start", "Continue", "Help/Credits", "Exit\n\n" + "  *" + " "* int(stream.width()/tfactor) + t.white("CONTROLS:") + t.gray30("\n\t[ENTER] and [Z] - Confirm Selection\n\tArrow Keys - Move Cursor")]
    finally:
        title_screen = menuClosure(game_title, titleList, delay_ms = 24, tfactor = 6)
```

<p>But it doesn't, because I got a NameError, which was caught:</p>

```EOFError: Ran out of input

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:\Users\capta\OneDrive\Desktop\WHAT\main.py", line 43, in <module>
    titleList = ["Start", t.gray30("[DISABLED] Continue"), "Help/Credits", "Exit\n\n" + "  *" + " "* int(stream.width()/tfactor) + t.white("CONTROLS:") + t.gray30("\n\t[ENTER] and [Z] - Confirm Selection\n\tArrow Keys - Move Cursor")]
NameError: name 'tfactor' is not defined

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:\Users\capta\OneDrive\Desktop\WHAT\main.py", line 48, in <module>
    title_screen = menuClosure(game_title, titleList, delay_ms = 24, tfactor = 6)
NameError: name 'titleList' is not defined
```

Even though I didn't have any other try/except blocks

答: Your code didn't catch the NameError. They were thrown inside your try-except-else-finally. It seems you haven't defined tfactor and titleList.</p>

Body:
I would expect this code to only catch an EOFError, but instead, it catches ALL exceptions...

    try:
        rpg.data.load("playerdata.dat")
    except EOFError:
        playerdata = rpg.data()
        titleList = ["Start", t.gray30("[DISABLED] Continue"), "Help/Credits", "Exit\n\n" + "  *" + " "* int(stream.width()/tfactor) + t.white("CONTROLS:") + t.gray30("\n\t[ENTER] and [Z] - Confirm Selection\n\tArrow Keys - Move Cursor")]
    else:
        playerdata = rpg.data.load("playerdata.dat")
        titleList = ["Start", "Continue", "Help/Credits", "Exit\n\n" + "  *" + " "* int(stream.width()/tfactor) + t.white("CONTROLS:") + t.gray30("\n\t[ENTER] and [Z] - Confirm Selection\n\tArrow Keys - Move Cursor")]
    finally:
        title_screen = menuClosure(game_title, titleList, delay_ms = 24, tfactor = 6)

But it doesn't, because I got a NameError, which was caught:

EOFError: Ran out of input

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:\Users\capta\OneDrive\Desktop\WHAT\main.py", line 43, in <module>
    titleList = ["Start", t.gray30("[DISABLED] Continue"), "Help/Credits", "Exit\n\n" + "  *" + " "* int(stream.width()/tfactor) + t.white("CONTROLS:") + t.gray30("\n\t[ENTER] and [Z] - Confirm Selection\n\tArrow Keys - Move Cursor")]
NameError: name 'tfactor' is not defined

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:\Users\capta\OneDrive\Desktop\WHAT\main.py", line 48, in <module>
    title_screen = menuClosure(game_title, titleList, delay_ms = 24, tfactor = 6)
NameError: name 'titleList' is not defined

Even though I didn't have any other try/except blocks


问:
Template format error: Every Mappings attribute must be a String or a List
I wanted to have some quick references at the top of my CloudFormation template, so that I don't have to write out a complex reference every time i need it throughout the template.

So I wrote this:

```<code>Mappings:
  StandardResourcesMap:
    AWSExecuteApi:
      string: !Join [ ':' , ['arn', !Sub '${AWS::Partition}', 'execute-api', !Sub '${AWS::Region}', !Sub '${AWS::AccountId}'] ]
    AWSLambdaFunctions:
      string: !Join [ ':' , ['arn', !Sub '${AWS::Partition}', 'apigateway', !Sub '${AWS::Region}', 'lambda:path/2015-03-31/functions/'] ]
</code>```

The rest of the CloudFormation template follows this, and, without the lines above, the template deploys (an S3 bucket, DynamoDB table and a python 3.7-based Lambda).

The hope was that I could then just use:

```<code>!FindInMap [StandardResourcesMap,AWSExecuteApi,string]
</code>```

whenever i needed the long-winded value, however the template fails validation with:

```<code>An error occurred (ValidationError) when calling the CreateChangeSet operation: Template format error: Every Mappings attribute must be a String or a List.
</code>```

as the title says.

I have tried a number of variations on the Mappings such as using the !Ref variant:

```<code>Mappings:
  StandardResourcesMap:
    AWSExecuteApi:
      string: !Join [ ':' , ['arn', !Ref 'AWS::Partition', 'execute-api', !Ref 'AWS::Region', !Ref 'AWS::AccountId'] ]
    AWSLambdaFunctions:
      string: !Join [ ':' , ['arn', !Ref 'AWS::Partition', 'apigateway', !Ref 'AWS::Region', 'lambda:path/2015-03-31/functions/'] ]
</code>```

and I just get pulled up on various validation errors, centring on the one presented above.

any help would be greatly appreciated.

答: The problem is this: You cannot include parameters, pseudo parameters, or intrinsic functions in the Mappings section. Mappings

Body:
I wanted to have some quick references at the top of my CloudFormation template, so that I don't have to write out a complex reference every time i need it throughout the template.

So I wrote this:

Mappings:
  StandardResourcesMap:
    AWSExecuteApi:
      string: !Join [ ':' , ['arn', !Sub '${AWS::Partition}', 'execute-api', !Sub '${AWS::Region}', !Sub '${AWS::AccountId}'] ]
    AWSLambdaFunctions:
      string: !Join [ ':' , ['arn', !Sub '${AWS::Partition}', 'apigateway', !Sub '${AWS::Region}', 'lambda:path/2015-03-31/functions/'] ]

The rest of the CloudFormation template follows this, and, without the lines above, the template deploys (an S3 bucket, DynamoDB table and a python 3.7-based Lambda).

The hope was that I could then just use:

!FindInMap [StandardResourcesMap,AWSExecuteApi,string]

whenever i needed the long-winded value, however the template fails validation with:

An error occurred (ValidationError) when calling the CreateChangeSet operation: Template format error: Every Mappings attribute must be a String or a List.

as the title says.

I have tried a number of variations on the Mappings such as using the !Ref variant:

Mappings:
  StandardResourcesMap:
    AWSExecuteApi:
      string: !Join [ ':' , ['arn', !Ref 'AWS::Partition', 'execute-api', !Ref 'AWS::Region', !Ref 'AWS::AccountId'] ]
    AWSLambdaFunctions:
      string: !Join [ ':' , ['arn', !Ref 'AWS::Partition', 'apigateway', !Ref 'AWS::Region', 'lambda:path/2015-03-31/functions/'] ]

and I just get pulled up on various validation errors, centring on the one presented above.

any help would be greatly appreciated.


问:
how to pass selenium-standalone port configuration from the command line
I created 3 jenkins jobs linked to the same github project, i'm using wdio v5 and cucumber, i want to run each job on a different port this is why i'm trying to pass the port from the jenkins post-build task : execute shell
I tryed this -- --seleniumArgs.seleniumArgs= ['-port', '7777']
then this
 -- --seleniumArgs.seleniumArgs= ["-port", "7777"]
then
-- --seleniumArgs.seleniumArgs= '-port: 7777'
but nothing works

答:
i found a solution :

so this is the wdio.conf.js file :

```<code>var myArgs = process.argv.slice(2);
Port= myArgs[1]

    exports.config = {

    ////////////////////////

services: ['selenium-standalone'],
seleniumArgs: {
seleniumArgs: ['-port', Port]
},

//////////////////////

}
</code>```

myArg will receive an array with the arguments passed in the command line

and this is the command

```<code>npm test 7777 -- --port 7777
</code>```

the 7777 is the argument number 2, thus the index 1 in the array,
the index 0 is : wdio.conf.js, which is in the "test" script in package.json
         ===> "test": "wdio wdio.conf.js"

Body:
i found a solution :

so this is the wdio.conf.js file :

var myArgs = process.argv.slice(2);
Port= myArgs[1]

    exports.config = {

    ////////////////////////

services: ['selenium-standalone'],
seleniumArgs: {
seleniumArgs: ['-port', Port]
},

//////////////////////

}

myArg will receive an array with the arguments passed in the command line

and this is the command

npm test 7777 -- --port 7777

the 7777 is the argument number 2, thus the index 1 in the array,
the index 0 is : wdio.conf.js, which is in the "test" script in package.json
         ===> "test": "wdio wdio.conf.js"


问:
Selecting a word based on transition matrix weights in python
I am trying to select the likely next word based on the current word, using previous word pair occurrences as "weights". I am having trouble implementing np.random.choice() in the actual choice of the next word.

```<code>import pandas as pd
import numpy as np

texty = "won't you celebrate with me what i have shaped into a kind of life i had no model born in babylon both nonwhite and woman what did i see to be except myself i made it up here on this bridge between starshine and clay my one hand holding tight my other hand come celebrate with me that everyday
something has tried to kill me and has failed."

# https://www.poetryfoundation.org/poems/50974/wont-you-celebrate-with-me

words = texty.split()

# Creating the text-based transition matrix

x = pd.crosstab(pd.Series(words[1:],name='next'),
            pd.Series(words[:-1],name='word'),normalize=1)

print(x)

# Selecting the next word based on the current word.
# https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.choice.html

current = "and"

# this part isn't working--->
next = np.random.choice(current,1,current) # was "y"
</code>```

I don't know how to refer to the transition matrix from here. I would like this choice to be based on the probabilities of previous occurrences. For example, the probability of "clay" following "and" is 33%.

答:
x is a Pandas DataFrame.

You can access any of the columns of that DataFrame as if the column names were keys into a dictionary.

```<code>> print(x['won\'t'])
next
a            0.0
and          0.0
babylon      0.0
...
with         0.0
woman        0.0
you          1.0
Name: won't, dtype: float64
</code>```

The column returns as a Pandas Series.  If you select a column from the DataFrame (your transition matrix x), the index of the Series you select will be available words from the text, and the values will be their associated probabilities.  You can provide each of these to np.random.choice to get the next word, with probabilities weighted from your transition matrix.

```<code>> current_word = 'won\'t'
> current_column = x[current_word]
> next_word = np.random.choice(current_column.index,
                 p=current_column.values)
> print(next_word)
you
</code>```

Body:
I am trying to select the likely next word based on the current word, using previous word pair occurrences as "weights". I am having trouble implementing np.random.choice() in the actual choice of the next word.

import pandas as pd
import numpy as np

texty = "won't you celebrate with me what i have shaped into a kind of life i had no model born in babylon both nonwhite and woman what did i see to be except myself i made it up here on this bridge between starshine and clay my one hand holding tight my other hand come celebrate with me that everyday
something has tried to kill me and has failed."

# https://www.poetryfoundation.org/poems/50974/wont-you-celebrate-with-me

words = texty.split()

# Creating the text-based transition matrix

x = pd.crosstab(pd.Series(words[1:],name='next'),
            pd.Series(words[:-1],name='word'),normalize=1)

print(x)

# Selecting the next word based on the current word.
# https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.choice.html

current = "and"

# this part isn't working--->
next = np.random.choice(current,1,current) # was "y"

I don't know how to refer to the transition matrix from here. I would like this choice to be based on the probabilities of previous occurrences. For example, the probability of "clay" following "and" is 33%.

Body:
x is a Pandas DataFrame.

You can access any of the columns of that DataFrame as if the column names were keys into a dictionary.

> print(x['won\'t'])
next
a            0.0
and          0.0
babylon      0.0
...
with         0.0
woman        0.0
you          1.0
Name: won't, dtype: float64

The column returns as a Pandas Series.  If you select a column from the DataFrame (your transition matrix x), the index of the Series you select will be available words from the text, and the values will be their associated probabilities.  You can provide each of these to np.random.choice to get the next word, with probabilities weighted from your transition matrix.

> current_word = 'won\'t'
> current_column = x[current_word]
> next_word = np.random.choice(current_column.index,
                 p=current_column.values)
> print(next_word)
you


问:
Java priority queue
Java's priority queue is a data structure with O(log n) complexity for put (insertion) and O(log n) for poll (retrieval and removal of the min element).

C++ STL's multimap has the same functionality but O(1) complexity for retrieval and removal of the min element (begin and erase). Is there an equivalent in Java ?

答:
Try the Apache Commons Collections.

MultiHashMap and MultiValueMap (linked from that page) actually implement the interface.

There's actually a Priority Queue in there too, but it's depreciated in favour of the buffer package.

OwnerDisplayName: Helltone

Title: Java priority queue

OwnerDisplayName: Stephen Pape

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Stephen Pape


问:
Number of elements in Char array
How can I get the size of char array if I define the size but put less elements

```<code>#define N 100

char a[N];
cin >> a;
</code>```

supoose I enter 126,
then what do i do to get the number of elemens (3 in this case) in this array now

答:
You can use strlen() which returns the number of characters in char array.Check my solution.

```<code>#include <iostream>
#include <string.h>
#define N 100

using namespace std;

int main()
{

 char a[N];

 cout << "Enter number: ";
 cin >> a;

 cout << "Length: " << strlen(a);
}
</code>```

Title: Number of elements in Char array

Body:
How can I get the size of char array if I define the size but put less elements

#define N 100

char a[N];
cin >> a;

supoose I enter 126,
then what do i do to get the number of elemens (3 in this case) in this array now

Body:
You can use strlen() which returns the number of characters in char array.Check my solution.

#include <iostream>
#include <string.h>
#define N 100

using namespace std;

int main()
{

 char a[N];

 cout << "Enter number: ";
 cin >> a;

 cout << "Length: " << strlen(a);
}


问:
how to use custom regular expression for more than one call?
edit: This part was solved, but I have one last problem with my code, see last answer.

I have a textfile structured as follow:

```<code>Name1 (Middlename1) LastName
Birthyear
Name2 (Middlename2) LastName
Birthyear
...
NameN (MiddlenameM) LastName
Birthyear
</code>```

I'm trying to use RE to find the name and the year automatically but I don't know how to combine the two REs since both information are not on the same line:

```<code>import re
regexp = re.compile(  r'(( )*)(?P<name>([a-zA-Z]*)( [a-zA-Z]+)? ROCHE)\n'
                      r'(( )*)(?P<year>18\d\d)\n'
                   )
</code>```

The two REs are working independently but not together. How am I supposed to do it?

答:
You want one regex that scans a string that spans across two lines. You then want to find successive matches. But first:

Names, at least in English-speaking countries, can contain hyphens (Anne-Marie), apostrophes (O'Donnell), periods (John Q. Public), etc. So I am using a regular expression that allows these characters. Also, people may have more than one middle name. What I am trying to illustrate is how to iterate through name/year pairs; you can customize the actual regex to suit your own particular requirements.

Regex:

```<code>^(?P<name>(?:[a-z.'-]+(?:\s+[a-z.'-]+)*))\n(?P<year>\d{4})$  Flags: re.M|re.I
</code>```

^ Matches the start start of a line.

[a-z.'-]+ Matches one or more alpha, period, ', or - characters. This is a name element.

(?:\s+[a-z.'-]+)* Matches one or more white space characters followed by name element. This is repeated 0 or more times. Thus the named group name consists of 1 or more name elements separated by one or more white space characters.

\n Matches a newline.

(?P<year>\d{4})$ Matches 4 digits followed by the end of line or the end of string.

The MULTILINE flag treats the ^ and $ anchors special so that they match in addition to the start and end of string, the start and end of a line.

The code relies on re.finditer to find successive matches:

```<code>import re

text = """John Doe
1921
John Q. Public
1987
Anne-Marie Smith
1989
Paul O'Donnell
2001
J. P. Marquand
1893
"""

regexp = re.compile(r"^(?P<name>(?:[a-z.'-]+(?:\s+[a-z.'-]+)*))\n(?P<year>\d{4})$", flags=re.M|re.I)
for m in regexp.finditer(text):
    name = m['name']
    year = m['year']
    # do something with name and year in the second file. Here we are just printing the values.
    print(name, year)
</code>```

Prints:

```<code>John Doe 1921
John Q. Public 1987
Anne-Marie Smith 1989
Paul O'Donnell 2001
J. P. Marquand 1893
</code>```

Body:
edit: This part was solved, but I have one last problem with my code, see last answer.

I have a textfile structured as follow:

Name1 (Middlename1) LastName
Birthyear
Name2 (Middlename2) LastName
Birthyear
...
NameN (MiddlenameM) LastName
Birthyear

I'm trying to use RE to find the name and the year automatically but I don't know how to combine the two REs since both information are not on the same line:

import re
regexp = re.compile(  r'(( )*)(?P<name>([a-zA-Z]*)( [a-zA-Z]+)? ROCHE)\n'
                      r'(( )*)(?P<year>18\d\d)\n'
                   )

The two REs are working independently but not together. How am I supposed to do it?

Body:
You want one regex that scans a string that spans across two lines. You then want to find successive matches. But first:

Names, at least in English-speaking countries, can contain hyphens (Anne-Marie), apostrophes (O'Donnell), periods (John Q. Public), etc. So I am using a regular expression that allows these characters. Also, people may have more than one middle name. What I am trying to illustrate is how to iterate through name/year pairs; you can customize the actual regex to suit your own particular requirements.

Regex:

^(?P<name>(?:[a-z.'-]+(?:\s+[a-z.'-]+)*))\n(?P<year>\d{4})$  Flags: re.M|re.I

^ Matches the start start of a line.

[a-z.'-]+ Matches one or more alpha, period, ', or - characters. This is a name element.

(?:\s+[a-z.'-]+)* Matches one or more white space characters followed by name element. This is repeated 0 or more times. Thus the named group name consists of 1 or more name elements separated by one or more white space characters.

\n Matches a newline.

(?P<year>\d{4})$ Matches 4 digits followed by the end of line or the end of string.

The MULTILINE flag treats the ^ and $ anchors special so that they match in addition to the start and end of string, the start and end of a line.

The code relies on re.finditer to find successive matches:

import re

text = """John Doe
1921
John Q. Public
1987
Anne-Marie Smith
1989
Paul O'Donnell
2001
J. P. Marquand
1893
"""

regexp = re.compile(r"^(?P<name>(?:[a-z.'-]+(?:\s+[a-z.'-]+)*))\n(?P<year>\d{4})$", flags=re.M|re.I)
for m in regexp.finditer(text):
    name = m['name']
    year = m['year']
    # do something with name and year in the second file. Here we are just printing the values.
    print(name, year)

Prints:

John Doe 1921
John Q. Public 1987
Anne-Marie Smith 1989
Paul O'Donnell 2001
J. P. Marquand 1893


问:
networkPlugin cni failed to set up pod issue while Kubernetes deployment
I am trying to deploy my sample Spring Boot micro service into Kubernetes cluster. My every nodes are showing ready state. And when I am trying to deploy, my pod is only showing ContainerCreating.

And when I am describing the pod, then I am getting the message by saying  networkPlugin cni failed to set up pod and network unable to allocate IP address.

My pod describe command result like the following:

```<code>Events:
 Type     Reason                  Age                    From                   Message
  ----     ------                  ----                   ----                   -------
  Normal   Scheduled               <unknown>              default-scheduler      Successfully assigned
default/spacestudysecurityauthcontrol-deployment-57596f4795-jxxvj to mildevkub040
  Warning  FailedCreatePodSandBox  53m                    kubelet, mildevkub040  Failed to create pod sandbox: rpc error: code = Unknown desc = [failed to set up sandbox container "2499f91b4a1173fb854a47ba1910d1fc3f18cfb35bf5c38c9a3008e19d385e15" network for pod "spacestudysecurityauthcontrol-deployment-57596f4795-jxxvj": networkPlugin cni failed to set up pod "spacestudysecurityauthcontrol-deployment-57596f4795-jxxvj_default" network: unable to allocate IP address: Post http://127.0.0.1:6784/ip/2499f91b4a1173fb854a47ba1910d1fc3f18cfb35bf5c38c9a3008e19d385e15: dial tcp 127.0.0.1:6784: connect: connection refused, failed to clean up sandbox container "2499f91b4a1173fb854a47ba1910d1fc3f18cfb35bf5c38c9a3008e19d385e15" network for pod "spacestudysecurityauthcontrol-deployment-57596f4795-jxxvj": networkPlugin cni failed to teardown pod "spacestudysecurityauthcontrol-deployment-57596f4795-jxxvj_default" network: Delete http://127.0.0.1:6784/ip/2499f91b4a1173fb854a47ba1910d1fc3f18cfb35bf5c38c9a3008e19d385e15: dial tcp 127.0.0.1:6784: connect: connection refused]
  Normal   SandboxChanged          3m40s (x228 over 53m)  kubelet, mildevkub040  Pod sandbox changed, it will be killed and re-created.
</code>```

When I am checking the container weave log I am getting like the following,

```<code>INFO: 2020/01/09 12:18:12.061328 ->[192.168.16.178:42838] connection shutting down due to error during handshake: write tcp 192.168.16.177:6783->192.168.16.178:42838: write: connection reset by peer
INFO: 2020/01/09 12:18:18.998360 ->[192.168.16.178:37570] connection accepted
INFO: 2020/01/09 12:18:20.653339 ->[192.168.16.178:45223] connection shutting down due to error during handshake: write tcp 192.168.16.177:6783->192.168.16.178:45223: write: connection reset by peer
INFO: 2020/01/09 12:18:21.122204 overlay_switch ->[56:60:12:a9:76:d1(mildevkub050)] using fastdp
INFO: 2020/01/09 12:18:21.742168 ->[192.168.16.178:6783|56:60:12:a9:76:d1(mildevkub050)]: connection deleted
INFO: 2020/01/09 12:18:21.800670 ->[192.168.16.178:6783] attempting connection
INFO: 2020/01/09 12:18:22.470207 ->[192.168.16.175:59923] connection accepted
INFO: 2020/01/09 12:18:22.912690 ->[192.168.16.175:6783|be:b1:3f:a4:34:88(mildevkub020)]: connection deleted
INFO: 2020/01/09 12:18:22.918075 Removed unreachable peer be:b1:3f:a4:34:88(mildevkub020)
INFO: 2020/01/09 12:18:22.918144 Removed unreachable peer 56:60:12:a9:76:d1(mildevkub050)
INFO: 2020/01/09 12:18:24.602093 ->[192.168.16.175:6783] attempting connection
INFO: 2020/01/09 12:18:26.782123 ->[192.168.16.178:6783|56:60:12:a9:76:d1(mildevkub050)]: connection ready; using protocol version 2
INFO: 2020/01/09 12:18:27.918518 ->[192.168.16.175:59923|be:b1:3f:a4:34:88(mildevkub020)]: connection ready; using protocol version 2
INFO: 2020/01/09 12:18:29.365629 ->[192.168.16.178:37570|56:60:12:a9:76:d1(mildevkub050)]: connection ready; using protocol version 2
INFO: 2020/01/09 12:18:29.864370 overlay_switch ->[56:60:12:a9:76:d1(mildevkub050)] using fastdp
INFO: 2020/01/09 12:18:30.086645 overlay_switch ->[56:60:12:a9:76:d1(mildevkub050)] using fastdp
INFO: 2020/01/09 12:18:30.090275 overlay_switch ->[be:b1:3f:a4:34:88(mildevkub020)] using fastdp
INFO: 2020/01/09 12:18:30.100874 ->[192.168.16.178:37570|56:60:12:a9:76:d1(mildevkub050)]: connection added (new peer)
INFO: 2020/01/09 12:18:30.104237 ->[192.168.16.178:37570|56:60:12:a9:76:d1(mildevkub050)]: connection deleted
INFO: 2020/01/09 12:18:30.104284 ->[192.168.16.178:6783|56:60:12:a9:76:d1(mildevkub050)]: connection added (new peer)
INFO: 2020/01/09 12:18:30.104371 ->[192.168.16.175:59923|be:b1:3f:a4:34:88(mildevkub020)]: connection added (new peer)
INFO: 2020/01/09 12:18:30.776275 ->[192.168.16.178:37570|56:60:12:a9:76:d1(mildevkub050)]: connection shutting down due to error: Multiple connections to 56:60:12:a9:76:d1(mildevkub050) added to 5a:67:92:b3:58:ce(mildevkub040)
INFO: 2020/01/09 12:18:44.305079 ->[192.168.16.175:6783|be:b1:3f:a4:34:88(mildevkub020)]: connection ready; using protocol version 2
INFO: 2020/01/09 12:18:45.200565 overlay_switch ->[be:b1:3f:a4:34:88(mildevkub020)] using fastdp
INFO: 2020/01/09 12:18:45.458203 ->[192.168.16.175:59923|be:b1:3f:a4:34:88(mildevkub020)]: connection fully established
INFO: 2020/01/09 12:18:45.461157 ->[192.168.16.175:6783|be:b1:3f:a4:34:88(mildevkub020)]: connection shutting down due to error: Multiple connections to be:b1:3f:a4:34:88(mildevkub020) added to 5a:67:92:b3:58:ce(mildevkub040)
INFO: 2020/01/09 12:18:45.470667 ->[192.168.16.178:6783|56:60:12:a9:76:d1(mildevkub050)]: connection fully established
INFO: 2020/01/09 12:18:45.688871 sleeve ->[192.168.16.178:6783|56:60:12:a9:76:d1(mildevkub050)]: Effective MTU verified at 1438
INFO: 2020/01/09 12:18:45.874380 sleeve ->[192.168.16.175:6783|be:b1:3f:a4:34:88(mildevkub020)]: Effective MTU verified at 1438
INFO: 2020/01/09 12:24:12.026645 ->[192.168.16.178:6783|56:60:12:a9:76:d1(mildevkub050)]: connection shutting down due to error: write tcp 192.168.16.177:38313->192.168.16.178:6783: write: connection reset by peer
INFO: 2020/01/09 12:25:56.708405 ->[192.168.16.178:44120] connection accepted
INFO: 2020/01/09 12:26:31.769826 overlay_switch ->[56:60:12:a9:76:d1(mildevkub050)] sleeve timed out waiting for UDP heartbeat
INFO: 2020/01/09 12:26:41.819554 ->[192.168.16.175:59923|be:b1:3f:a4:34:88(mildevkub020)]: connection shutting down due to error: write tcp 192.168.16.177:6783->192.168.16.175:59923: write: connection reset by peer
INFO: 2020/01/09 12:28:17.563133 ->[192.168.16.178:6783|56:60:12:a9:76:d1(mildevkub050)]: connection deleted
INFO: 2020/01/09 12:30:49.548347 ->[192.168.16.178:60937] connection accepted
</code>```

When I am running the command  kubectl exec -n kube-system weave-net-fj9mm -c weave -- /home/weave/weave --local status ipam , I am getting the response like "Error from server (NotFound): pods "weave-net-fj9mm" not found"

How I can resolve this issue?

答:
The url that is appearing in the pod describe command, if you curl it. You will get something like this.

```<code># curl 'http://127.0.0.1:6784/status'
        Version: 1.8.2 (version 1.9.1 available - please upgrade!)

        Service: router
       Protocol: weave 1..2
           Name: 66:2b:6a:ca:34:88(ip-10-128-152-185)
     Encryption: disabled
  PeerDiscovery: enabled
        Targets: 4
    Connections: 4 (3 established, 1 failed)
          Peers: 4 (with 12 established connections)
 TrustedSubnets: none

        Service: ipam
         Status: waiting for IP range grant from peers
          Range: 10.32.0.0/12
  DefaultSubnet: 10.32.0.0/12
</code>```

"waiting for IP range grant from peers" status indicates that Weave Net's IPAM believes that all the IP address space is owned by other nodes in the cluster, but actually none of those nodes are able to be contacted at the moment.

Here's the workaround. Big red warnings:

All unreachable hosts were first identified as gone forever.

Do not run this on more than one node.

This may screw up your kubernetes cluster if something goes wrong.

There is a failsafe 'echo' added to the command in case you didn't read the above warnings.

```<code>% for i in $(curl -s 'http://127.0.0.1:6784/status/ipam' | grep 'unreachable\!$' | sort -k2 -n -r | awk -F'(' '{print $2}' | sed 's/).*//'); do echo curl -X DELETE 127.0.0.1:6784/peer/$i; done
65536 IPs taken over from ip-10-128-184-15
32768 IPs taken over from ip-10-128-159-154
32768 IPs taken over from ip-10-128-170-84
</code>```

Reference -
https://github.com/weaveworks/weave/issues/2822

Body:
I am trying to deploy my sample Spring Boot micro service into Kubernetes cluster. My every nodes are showing ready state. And when I am trying to deploy, my pod is only showing ContainerCreating.

And when I am describing the pod, then I am getting the message by saying  networkPlugin cni failed to set up pod and network unable to allocate IP address.

My pod describe command result like the following:

Events:
 Type     Reason                  Age                    From                   Message
  ----     ------                  ----                   ----                   -------
  Normal   Scheduled               <unknown>              default-scheduler      Successfully assigned
default/spacestudysecurityauthcontrol-deployment-57596f4795-jxxvj to mildevkub040
  Warning  FailedCreatePodSandBox  53m                    kubelet, mildevkub040  Failed to create pod sandbox: rpc error: code = Unknown desc = [failed to set up sandbox container "2499f91b4a1173fb854a47ba1910d1fc3f18cfb35bf5c38c9a3008e19d385e15" network for pod "spacestudysecurityauthcontrol-deployment-57596f4795-jxxvj": networkPlugin cni failed to set up pod "spacestudysecurityauthcontrol-deployment-57596f4795-jxxvj_default" network: unable to allocate IP address: Post http://127.0.0.1:6784/ip/2499f91b4a1173fb854a47ba1910d1fc3f18cfb35bf5c38c9a3008e19d385e15: dial tcp 127.0.0.1:6784: connect: connection refused, failed to clean up sandbox container "2499f91b4a1173fb854a47ba1910d1fc3f18cfb35bf5c38c9a3008e19d385e15" network for pod "spacestudysecurityauthcontrol-deployment-57596f4795-jxxvj": networkPlugin cni failed to teardown pod "spacestudysecurityauthcontrol-deployment-57596f4795-jxxvj_default" network: Delete http://127.0.0.1:6784/ip/2499f91b4a1173fb854a47ba1910d1fc3f18cfb35bf5c38c9a3008e19d385e15: dial tcp 127.0.0.1:6784: connect: connection refused]
  Normal   SandboxChanged          3m40s (x228 over 53m)  kubelet, mildevkub040  Pod sandbox changed, it will be killed and re-created.

When I am checking the container weave log I am getting like the following,

INFO: 2020/01/09 12:18:12.061328 ->[192.168.16.178:42838] connection shutting down due to error during handshake: write tcp 192.168.16.177:6783->192.168.16.178:42838: write: connection reset by peer
INFO: 2020/01/09 12:18:18.998360 ->[192.168.16.178:37570] connection accepted
INFO: 2020/01/09 12:18:20.653339 ->[192.168.16.178:45223] connection shutting down due to error during handshake: write tcp 192.168.16.177:6783->192.168.16.178:45223: write: connection reset by peer
INFO: 2020/01/09 12:18:21.122204 overlay_switch ->[56:60:12:a9:76:d1(mildevkub050)] using fastdp
INFO: 2020/01/09 12:18:21.742168 ->[192.168.16.178:6783|56:60:12:a9:76:d1(mildevkub050)]: connection deleted
INFO: 2020/01/09 12:18:21.800670 ->[192.168.16.178:6783] attempting connection
INFO: 2020/01/09 12:18:22.470207 ->[192.168.16.175:59923] connection accepted
INFO: 2020/01/09 12:18:22.912690 ->[192.168.16.175:6783|be:b1:3f:a4:34:88(mildevkub020)]: connection deleted
INFO: 2020/01/09 12:18:22.918075 Removed unreachable peer be:b1:3f:a4:34:88(mildevkub020)
INFO: 2020/01/09 12:18:22.918144 Removed unreachable peer 56:60:12:a9:76:d1(mildevkub050)
INFO: 2020/01/09 12:18:24.602093 ->[192.168.16.175:6783] attempting connection
INFO: 2020/01/09 12:18:26.782123 ->[192.168.16.178:6783|56:60:12:a9:76:d1(mildevkub050)]: connection ready; using protocol version 2
INFO: 2020/01/09 12:18:27.918518 ->[192.168.16.175:59923|be:b1:3f:a4:34:88(mildevkub020)]: connection ready; using protocol version 2
INFO: 2020/01/09 12:18:29.365629 ->[192.168.16.178:37570|56:60:12:a9:76:d1(mildevkub050)]: connection ready; using protocol version 2
INFO: 2020/01/09 12:18:29.864370 overlay_switch ->[56:60:12:a9:76:d1(mildevkub050)] using fastdp
INFO: 2020/01/09 12:18:30.086645 overlay_switch ->[56:60:12:a9:76:d1(mildevkub050)] using fastdp
INFO: 2020/01/09 12:18:30.090275 overlay_switch ->[be:b1:3f:a4:34:88(mildevkub020)] using fastdp
INFO: 2020/01/09 12:18:30.100874 ->[192.168.16.178:37570|56:60:12:a9:76:d1(mildevkub050)]: connection added (new peer)
INFO: 2020/01/09 12:18:30.104237 ->[192.168.16.178:37570|56:60:12:a9:76:d1(mildevkub050)]: connection deleted
INFO: 2020/01/09 12:18:30.104284 ->[192.168.16.178:6783|56:60:12:a9:76:d1(mildevkub050)]: connection added (new peer)
INFO: 2020/01/09 12:18:30.104371 ->[192.168.16.175:59923|be:b1:3f:a4:34:88(mildevkub020)]: connection added (new peer)
INFO: 2020/01/09 12:18:30.776275 ->[192.168.16.178:37570|56:60:12:a9:76:d1(mildevkub050)]: connection shutting down due to error: Multiple connections to 56:60:12:a9:76:d1(mildevkub050) added to 5a:67:92:b3:58:ce(mildevkub040)
INFO: 2020/01/09 12:18:44.305079 ->[192.168.16.175:6783|be:b1:3f:a4:34:88(mildevkub020)]: connection ready; using protocol version 2
INFO: 2020/01/09 12:18:45.200565 overlay_switch ->[be:b1:3f:a4:34:88(mildevkub020)] using fastdp
INFO: 2020/01/09 12:18:45.458203 ->[192.168.16.175:59923|be:b1:3f:a4:34:88(mildevkub020)]: connection fully established
INFO: 2020/01/09 12:18:45.461157 ->[192.168.16.175:6783|be:b1:3f:a4:34:88(mildevkub020)]: connection shutting down due to error: Multiple connections to be:b1:3f:a4:34:88(mildevkub020) added to 5a:67:92:b3:58:ce(mildevkub040)
INFO: 2020/01/09 12:18:45.470667 ->[192.168.16.178:6783|56:60:12:a9:76:d1(mildevkub050)]: connection fully established
INFO: 2020/01/09 12:18:45.688871 sleeve ->[192.168.16.178:6783|56:60:12:a9:76:d1(mildevkub050)]: Effective MTU verified at 1438
INFO: 2020/01/09 12:18:45.874380 sleeve ->[192.168.16.175:6783|be:b1:3f:a4:34:88(mildevkub020)]: Effective MTU verified at 1438
INFO: 2020/01/09 12:24:12.026645 ->[192.168.16.178:6783|56:60:12:a9:76:d1(mildevkub050)]: connection shutting down due to error: write tcp 192.168.16.177:38313->192.168.16.178:6783: write: connection reset by peer
INFO: 2020/01/09 12:25:56.708405 ->[192.168.16.178:44120] connection accepted
INFO: 2020/01/09 12:26:31.769826 overlay_switch ->[56:60:12:a9:76:d1(mildevkub050)] sleeve timed out waiting for UDP heartbeat
INFO: 2020/01/09 12:26:41.819554 ->[192.168.16.175:59923|be:b1:3f:a4:34:88(mildevkub020)]: connection shutting down due to error: write tcp 192.168.16.177:6783->192.168.16.175:59923: write: connection reset by peer
INFO: 2020/01/09 12:28:17.563133 ->[192.168.16.178:6783|56:60:12:a9:76:d1(mildevkub050)]: connection deleted
INFO: 2020/01/09 12:30:49.548347 ->[192.168.16.178:60937] connection accepted

When I am running the command  kubectl exec -n kube-system weave-net-fj9mm -c weave -- /home/weave/weave --local status ipam , I am getting the response like "Error from server (NotFound): pods "weave-net-fj9mm" not found"

How I can resolve this issue?

Body:
The url that is appearing in the pod describe command, if you curl it. You will get something like this.

# curl 'http://127.0.0.1:6784/status'
        Version: 1.8.2 (version 1.9.1 available - please upgrade!)

        Service: router
       Protocol: weave 1..2
           Name: 66:2b:6a:ca:34:88(ip-10-128-152-185)
     Encryption: disabled
  PeerDiscovery: enabled
        Targets: 4
    Connections: 4 (3 established, 1 failed)
          Peers: 4 (with 12 established connections)
 TrustedSubnets: none

        Service: ipam
         Status: waiting for IP range grant from peers
          Range: 10.32.0.0/12
  DefaultSubnet: 10.32.0.0/12

"waiting for IP range grant from peers" status indicates that Weave Net's IPAM believes that all the IP address space is owned by other nodes in the cluster, but actually none of those nodes are able to be contacted at the moment.

Here's the workaround. Big red warnings:

All unreachable hosts were first identified as gone forever.

Do not run this on more than one node.

This may screw up your kubernetes cluster if something goes wrong.

There is a failsafe 'echo' added to the command in case you didn't read the above warnings.

% for i in $(curl -s 'http://127.0.0.1:6784/status/ipam' | grep 'unreachable\!$' | sort -k2 -n -r | awk -F'(' '{print $2}' | sed 's/).*//'); do echo curl -X DELETE 127.0.0.1:6784/peer/$i; done
65536 IPs taken over from ip-10-128-184-15
32768 IPs taken over from ip-10-128-159-154
32768 IPs taken over from ip-10-128-170-84

Reference -
https://github.com/weaveworks/weave/issues/2822


问:
Python JSON serialize a Decimal object
I have a Decimal('3.9') as part of an object, and wish to encode this to a JSON string which should look like {'x': 3.9}. I don't care about precision on the client side, so a float is fine.

Is there a good way to serialize this? JSONDecoder doesn't accept Decimal objects, and converting to a float beforehand yields {'x': 3.8999999999999999} which is wrong, and will be a big waste of bandwidth.

答:
For those who don't want to use a third-party library...  An issue with Elias Zamaria's answer is that it converts to float, which can run into problems.  For example:

```<code>>>> json.dumps({'x': Decimal('0.0000001')}, cls=DecimalEncoder)
'{"x": 1e-07}'
>>> json.dumps({'x': Decimal('100000000000.01734')}, cls=DecimalEncoder)
'{"x": 100000000000.01733}'
</code>```

The JSONEncoder.encode() method lets you return the literal json content, unlike JSONEncoder.default(), which has you return a json compatible type (like float) that then gets encoded in the normal way.  The problem with encode() is that it (normally) only works at the top level.  But it's still usable, with a little extra work (python 3.x):

```<code>import json
from collections.abc import Mapping, Iterable
from decimal import Decimal

class DecimalEncoder(json.JSONEncoder):
    def encode(self, obj):
        if isinstance(obj, Mapping):
            return '{' + ', '.join(f'{self.encode(k)}: {self.encode(v)}' for (k, v) in obj.items()) + '}'
        if isinstance(obj, Iterable) and (not isinstance(obj, str)):
            return '[' + ', '.join(map(self.encode, obj)) + ']'
        if isinstance(obj, Decimal):
            return f'{obj.normalize():f}'  # using normalize() gets rid of trailing 0s, using ':f' prevents scientific notation
        return super().encode(obj)
</code>```

Which gives you:

```<code>>>> json.dumps({'x': Decimal('0.0000001')}, cls=DecimalEncoder)
'{"x": 0.0000001}'
>>> json.dumps({'x': Decimal('100000000000.01734')}, cls=DecimalEncoder)
'{"x": 100000000000.01734}'
</code>```

Title: Python JSON serialize a Decimal object

Body:
For those who don't want to use a third-party library...  An issue with Elias Zamaria's answer is that it converts to float, which can run into problems.  For example:

>>> json.dumps({'x': Decimal('0.0000001')}, cls=DecimalEncoder)
'{"x": 1e-07}'
>>> json.dumps({'x': Decimal('100000000000.01734')}, cls=DecimalEncoder)
'{"x": 100000000000.01733}'

The JSONEncoder.encode() method lets you return the literal json content, unlike JSONEncoder.default(), which has you return a json compatible type (like float) that then gets encoded in the normal way.  The problem with encode() is that it (normally) only works at the top level.  But it's still usable, with a little extra work (python 3.x):

import json
from collections.abc import Mapping, Iterable
from decimal import Decimal

class DecimalEncoder(json.JSONEncoder):
    def encode(self, obj):
        if isinstance(obj, Mapping):
            return '{' + ', '.join(f'{self.encode(k)}: {self.encode(v)}' for (k, v) in obj.items()) + '}'
        if isinstance(obj, Iterable) and (not isinstance(obj, str)):
            return '[' + ', '.join(map(self.encode, obj)) + ']'
        if isinstance(obj, Decimal):
            return f'{obj.normalize():f}'  # using normalize() gets rid of trailing 0s, using ':f' prevents scientific notation
        return super().encode(obj)

Which gives you:

>>> json.dumps({'x': Decimal('0.0000001')}, cls=DecimalEncoder)
'{"x": 0.0000001}'
>>> json.dumps({'x': Decimal('100000000000.01734')}, cls=DecimalEncoder)
'{"x": 100000000000.01734}'


问:
How to create cube window with css?

I found this image online and tryed to create these boxes with css. I failed. Has anyone an idea how to solve this problem?

This is my code. The problem is the left bar:

.box {
  position: relative;
  margin: 10px;
  display: inline-block;
}

.content {
  border-top: 2px solid red;
  border-right: 2px solid red;
  padding: 5px;
}

.box:before {
  content: '';
  position: absolute;
  top: 0;
  left: -10px;
  height: 100%;
  width: 10px;
  background-color: red;
  transform: skew(-45deg) rotate(-45deg);
}

.box:after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: -5px;
  height: 10px;
  width: 100%;
  background-color: red;
  transform: skew(-45deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <div class="content">
  CONTENT<br />
  Some more content
  </div>
</div></code>```

答:
border-image with linear-gradient can do it:

.box {
  margin: 10px;
  display: inline-block;
  border-style:solid;
  border-width:2px 2px 15px 15px;
  border-image-slice:2 2 15 15; /* same as border-width*/
  border-image-source:linear-gradient(-45deg,transparent 9px,red 0 calc(100% - 9px),transparent 0);
}

.content {
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <div class="content">
    CONTENT<br> Some more Content
  </div>
</div>

<div class="box">
  <div class="content">
    CONTENT<br> more Content
  </div>
</div>

<div class="box">
  <div class="content">
    AA BB
  </div>
</div></code>```

With CSS variables to have better control:

.box {
  --b:2;   /* border length (without unit!!)*/
  --c:15;  /* the cube perspective (without unit!!)*/

  --g:calc((var(--c) - var(--b))*0.707px); /* 0.707 = cos(45deg) = sin(45deg) */
  margin: 10px;
  display: inline-block;
  border-style:solid;
  border-width:calc(var(--b)*1px) calc(var(--b)*1px) calc(var(--c)*1px) calc(var(--c)*1px);
  border-image-slice:var(--b) var(--b) var(--c) var(--c);
  border-image-source:linear-gradient(-45deg,transparent var(--g),red 0 calc(100% - var(--g)),transparent 0);
}

.content {
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <div class="content">
    CONTENT<br> Some more Content
  </div>
</div>

<div class="box" style="--b:3;--c:10">
  <div class="content">
    CONTENT<br> more Content
  </div>
</div>

<div class="box" style="--b:1;--c:20">
  <div class="content">
    AA BB
  </div>
</div>
<div class="box" style="--b:1;--c:5">
  <div class="content">
    AA BB
  </div>
</div></code>```

You can also have it in any direction you want:

.box {
  --b:2;   /* border length (without unit!!)*/
  --c:15;  /* the cube perspective (without unit!!)*/

  --g:calc((var(--c) - var(--b))*0.707px); /* 0.707 = cos(45deg) = sin(45deg) */
  margin: 10px;
  display: inline-block;
  border-style:solid;
}

.bottom-left {
  border-width:calc(var(--b)*1px) calc(var(--b)*1px) calc(var(--c)*1px) calc(var(--c)*1px);
  border-image-slice:var(--b) var(--b) var(--c) var(--c);
  border-image-source:linear-gradient(-45deg,transparent var(--g),red 0 calc(100% - var(--g)),transparent 0);
}
.top-right {
  border-width:calc(var(--c)*1px) calc(var(--c)*1px) calc(var(--b)*1px) calc(var(--b)*1px) ;
  border-image-slice: var(--c) var(--c) var(--b) var(--b);
  border-image-source:linear-gradient(-45deg,transparent var(--g),red 0 calc(100% - var(--g)),transparent 0);
}
.top-left {
  border-width:calc(var(--c)*1px) calc(var(--b)*1px) calc(var(--b)*1px) calc(var(--c)*1px) ;
  border-image-slice:var(--c) var(--b) var(--b) var(--c);
  border-image-source:linear-gradient(45deg,transparent var(--g),red 0 calc(100% - var(--g)),transparent 0);
}
.bottom-right {
  border-width:calc(var(--b)*1px) calc(var(--c)*1px) calc(var(--c)*1px) calc(var(--b)*1px) ;
  border-image-slice:var(--b) var(--c) var(--c) var(--b);
  border-image-source:linear-gradient(45deg,transparent var(--g),red 0 calc(100% - var(--g)),transparent 0);
}

.content {
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box bottom-left">
  <div class="content">
    CONTENT<br> Some more Content
  </div>
</div>

<div class="box top-right" style="--b:3;--c:10">
  <div class="content">
    CONTENT<br> more Content
  </div>
</div>

<div class="box bottom-right" style="--b:1;--c:20">
  <div class="content">
    AA BB
  </div>
</div>
<div class="box top-left" style="--b:1;--c:5">
  <div class="content">
    AA BB
  </div>
</div></code>```

We can also add more 3D effect by adjusting the coloration and using a different technique with clip-path

.box {
  --b:2px;   /* border length*/
  --c:15px;  /* the cube perspective */

  --g:calc(var(--c)*0.707); /* 0.707 = cos(45deg) = sin(45deg) */
  margin: 10px;
  display: inline-block;
  padding:var(--b) var(--b) var(--c) var(--c);
  background:
    linear-gradient(-45deg,transparent var(--g),#cc0404 0) left   /var(--c) 100%,
    linear-gradient(135deg,transparent var(--g),red 0)     bottom /100% var(--c),
    linear-gradient(red,red)                               top    /100% var(--b),
    linear-gradient(red,red)                               right  /var(--b) 100%;
  background-repeat:no-repeat;
  clip-path:
    polygon(0% calc(var(--c) - var(--b)), calc(var(--c) - var(--b)) 0%,
    100% 0%,
    100% calc(100% - var(--c) + var(--b)), calc(100% - var(--c) + var(--b)) 100%,
    0% 100%);

}

.content {
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <div class="content">
    CONTENT<br> Some more Content
  </div>
</div>

<div class="box" style="--b:3px;--c:10px">
  <div class="content">
    CONTENT<br> more Content
  </div>
</div>

<div class="box" style="--b:1px;--c:20px">
  <div class="content">
    AA BB
  </div>
</div>
<div class="box" style="--b:1px;--c:5px">
  <div class="content">
    AA BB
  </div>
</div></code>```

A Codepen demo to play with the code

Title: How to create cube window with css?

Body:
I found this image online and tryed to create these boxes with css. I failed. Has anyone an idea how to solve this problem?

This is my code. The problem is the left bar:

.box {
  position: relative;
  margin: 10px;
  display: inline-block;
}

.content {
  border-top: 2px solid red;
  border-right: 2px solid red;
  padding: 5px;
}

.box:before {
  content: '';
  position: absolute;
  top: 0;
  left: -10px;
  height: 100%;
  width: 10px;
  background-color: red;
  transform: skew(-45deg) rotate(-45deg);
}

.box:after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: -5px;
  height: 10px;
  width: 100%;
  background-color: red;
  transform: skew(-45deg);
}

  CONTENT

  Some more content

Body:
border-image with linear-gradient can do it:

.box {
  margin: 10px;
  display: inline-block;
  border-style:solid;
  border-width:2px 2px 15px 15px;
  border-image-slice:2 2 15 15; /* same as border-width*/
  border-image-source:linear-gradient(-45deg,transparent 9px,red 0 calc(100% - 9px),transparent 0);
}

.content {
  padding: 5px;
}

<div class="box">
  <div class="content">
    CONTENT<br> Some more Content
  </div>
</div>

<div class="box">
  <div class="content">
    CONTENT<br> more Content
  </div>
</div>

<div class="box">
  <div class="content">
    AA BB
  </div>
</div>

With CSS variables to have better control:

.box {
  --b:2;   /* border length (without unit!!)*/
  --c:15;  /* the cube perspective (without unit!!)*/

  --g:calc((var(--c) - var(--b))*0.707px); /* 0.707 = cos(45deg) = sin(45deg) */
  margin: 10px;
  display: inline-block;
  border-style:solid;
  border-width:calc(var(--b)*1px) calc(var(--b)*1px) calc(var(--c)*1px) calc(var(--c)*1px);
  border-image-slice:var(--b) var(--b) var(--c) var(--c);
  border-image-source:linear-gradient(-45deg,transparent var(--g),red 0 calc(100% - var(--g)),transparent 0);
}

.content {
  padding: 5px;
}

<div class="box">
  <div class="content">
    CONTENT<br> Some more Content
  </div>
</div>

<div class="box" style="--b:3;--c:10">
  <div class="content">
    CONTENT<br> more Content
  </div>
</div>

<div class="box" style="--b:1;--c:20">
  <div class="content">
    AA BB
  </div>
</div>
<div class="box" style="--b:1;--c:5">
  <div class="content">
    AA BB
  </div>
</div>

You can also have it in any direction you want:

.box {
  --b:2;   /* border length (without unit!!)*/
  --c:15;  /* the cube perspective (without unit!!)*/

  --g:calc((var(--c) - var(--b))*0.707px); /* 0.707 = cos(45deg) = sin(45deg) */
  margin: 10px;
  display: inline-block;
  border-style:solid;
}

.bottom-left {
  border-width:calc(var(--b)*1px) calc(var(--b)*1px) calc(var(--c)*1px) calc(var(--c)*1px);
  border-image-slice:var(--b) var(--b) var(--c) var(--c);
  border-image-source:linear-gradient(-45deg,transparent var(--g),red 0 calc(100% - var(--g)),transparent 0);
}
.top-right {
  border-width:calc(var(--c)*1px) calc(var(--c)*1px) calc(var(--b)*1px) calc(var(--b)*1px) ;
  border-image-slice: var(--c) var(--c) var(--b) var(--b);
  border-image-source:linear-gradient(-45deg,transparent var(--g),red 0 calc(100% - var(--g)),transparent 0);
}
.top-left {
  border-width:calc(var(--c)*1px) calc(var(--b)*1px) calc(var(--b)*1px) calc(var(--c)*1px) ;
  border-image-slice:var(--c) var(--b) var(--b) var(--c);
  border-image-source:linear-gradient(45deg,transparent var(--g),red 0 calc(100% - var(--g)),transparent 0);
}
.bottom-right {
  border-width:calc(var(--b)*1px) calc(var(--c)*1px) calc(var(--c)*1px) calc(var(--b)*1px) ;
  border-image-slice:var(--b) var(--c) var(--c) var(--b);
  border-image-source:linear-gradient(45deg,transparent var(--g),red 0 calc(100% - var(--g)),transparent 0);
}

.content {
  padding: 5px;
}

<div class="box bottom-left">
  <div class="content">
    CONTENT<br> Some more Content
  </div>
</div>

<div class="box top-right" style="--b:3;--c:10">
  <div class="content">
    CONTENT<br> more Content
  </div>
</div>

<div class="box bottom-right" style="--b:1;--c:20">
  <div class="content">
    AA BB
  </div>
</div>
<div class="box top-left" style="--b:1;--c:5">
  <div class="content">
    AA BB
  </div>
</div>

We can also add more 3D effect by adjusting the coloration and using a different technique with clip-path

.box {
  --b:2px;   /* border length*/
  --c:15px;  /* the cube perspective */

  --g:calc(var(--c)*0.707); /* 0.707 = cos(45deg) = sin(45deg) */
  margin: 10px;
  display: inline-block;
  padding:var(--b) var(--b) var(--c) var(--c);
  background:
    linear-gradient(-45deg,transparent var(--g),#cc0404 0) left   /var(--c) 100%,
    linear-gradient(135deg,transparent var(--g),red 0)     bottom /100% var(--c),
    linear-gradient(red,red)                               top    /100% var(--b),
    linear-gradient(red,red)                               right  /var(--b) 100%;
  background-repeat:no-repeat;
  clip-path:
    polygon(0% calc(var(--c) - var(--b)), calc(var(--c) - var(--b)) 0%,
    100% 0%,
    100% calc(100% - var(--c) + var(--b)), calc(100% - var(--c) + var(--b)) 100%,
    0% 100%);

}

.content {
  padding: 5px;
}

<div class="box">
  <div class="content">
    CONTENT<br> Some more Content
  </div>
</div>

<div class="box" style="--b:3px;--c:10px">
  <div class="content">
    CONTENT<br> more Content
  </div>
</div>

<div class="box" style="--b:1px;--c:20px">
  <div class="content">
    AA BB
  </div>
</div>
<div class="box" style="--b:1px;--c:5px">
  <div class="content">
    AA BB
  </div>
</div>

A Codepen demo to play with the code


问:
How can I avoid seeing the loading delay from datatables?
When loading datatables, there is a split second where you can see the plain table (which looks large and generic), then it turns into a smaller, better styled table with all the bells and whistles datatables provides. How can I avoid the user seeing this ugly split second transformation?</p>

答:
Datatables wraps your table element inside a div.dataTables_wrapper. Capitalize on that:

table { display: none; }
.dataTables_wrapper table { display: table; }
```


问:
What is the difference between admin.firestore.Timestamp.now() and admin.firestore.FieldValue.serverTimestamp()?
https://firebase.google.com/docs/reference/js/firebase.firestore.FieldValue.html#servertimestamp

https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp.html#now

I am not sure I understand the difference. Could someone explain this ?

That is: what difference would I obtain if I just used firebase.firestore.Timestamp.now() as a timestamp property of the object I am about to write instead of firebase.firestore.FieldValue.servertimestamp() ?

I would imagine there are some precision gains ? How much ? Or is it something else ?

答:
Timestamp.now() generates the timestamp using the client machine's clock, which could be wrong, even drastically wrong.

FieldValue.serverTimestamp() encodes a token into the document field that gets translated into a timestamp using the clock on Google's servers whenever the write operation is received (not at the time it was issued from the client).  The clock time on all Google services are meticulously guaranteed to be correct, no matter what a malicious user does.

If you absolutely need a correct time, especially one that needs to get checked by security rules using request.time, you should use the server timestamp.  If you need the client's clock time, use Timestamp.now().  It's almost always the case that a server timestamp is preferred.


问:
VS code is ignoring the breakpoint in c++ debugging
I am debugging a c++ code in VS Code but it doesn't stop on breakpoint and visualize the variables, watch and call stack, which it was supposed to do. Instead of this, it prints this in debug console:

```<code>Breakpoint 1, 0x000000000040074a in main ()
[Inferior 1 (process 9445) exited normally]
The program '/home/hashir/x/a.out' has exited with code 0 (0x00000000)
</code>```

here is launch.json file:

```<code>{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(gdb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "/home/hashir/x/a.out",
            "args": [],
            "stopAtEntry": false,
            "cwd": "/home/hashir/x/",
            "environment": [],
            "externalConsole": true,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ]
        }
    ]
}
</code>```

答:
I've figured out that if your source-code file name contains white spaces, like "Binary Search.cpp", VSCode will ignore the breakpoints regardless of "stop at entry" configuration. Removing the white spaces from my source files' names worked, although their paths contain white spaces. For example "C++ Exercises/BinarySearch.cpp" seems to be valid.

In this issue opened on GitHub, it is suggested that non-ascii characters might cause such problems.

Body:
I am debugging a c++ code in VS Code but it doesn't stop on breakpoint and visualize the variables, watch and call stack, which it was supposed to do. Instead of this, it prints this in debug console:

Breakpoint 1, 0x000000000040074a in main ()
[Inferior 1 (process 9445) exited normally]
The program '/home/hashir/x/a.out' has exited with code 0 (0x00000000)

here is launch.json file:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(gdb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "/home/hashir/x/a.out",
            "args": [],
            "stopAtEntry": false,
            "cwd": "/home/hashir/x/",
            "environment": [],
            "externalConsole": true,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ]
        }
    ]
}


问:
How do I pass a function that takes a float and returns a float to another function?
I am trying to write a "map" function on one of my classes in Java. How do I pass a function that takes a float and return a float to another function? Something like this: </p>

```<code>void map( MapFn fn )
{
    for ( int  i = 0 ; i < this.rows; ++i )
    {
        for ( int  j = 0 ; j < this.cols; ++j )
        {
            this.inner[i][j] = fn(this.inner[i][j])
        }
    }
}
</code>```

答:
I'm not really sure what you mean, but I think you want to do this:</p>

```<code>public float map(float value) {
    float mappedValue = value * 20;
    return mappedValue;
}
</code>```

Body:
I am trying to write a "map" function on one of my classes in Java. How do I pass a function that takes a float and return a float to another function? Something like this:

void map( MapFn fn )
{
    for ( int  i = 0 ; i < this.rows; ++i )
    {
        for ( int  j = 0 ; j < this.cols; ++j )
        {
            this.inner[i][j] = fn(this.inner[i][j])
        }
    }
}

Body:
I'm not really sure what you mean, but I think you want to do this:

public float map(float value) {
    float mappedValue = value * 20;
    return mappedValue;
}


问:
How to change from array of values to array of objects?
I got data like this:

```<code>{"my_data":{"labels":[1,2,3,...], "idx":["idx1", "idx2", ...]}}
</code>```

But I need it like this:

```<code>["my_data":{"labels":1, "idx": "idx1"},{"labels":2, "idx": "idx2"},... ]
</code>```

I tried to loop like this to change the format:

```<code>var arr = [];
for (let [key, value] of Object.entries(my_data)) {
    arr.push({[key]:value});
}
console.log(key, value);
</code>```

But the result is a format I can not use with ag-grid

```<code>labels: [1,2,...]
idx: [idx1, idx2,...]
</code>```

答:
One way you can approach this is by using the map method like in the following example:

const temp = { my_data: { labels: [1, 2, 3], idx: ["idx1", "idx2", "idx3"] } };

const result = temp.my_data.labels.map((label, index) => {
  const idx = temp.my_data.idx[index];

  return {
    label,
    idx
  };
});

console.log(result)```

This way, you're mapping through labels then extracting the value for idx based on the index of the label.

Body:
I got data like this:

{"my_data":{"labels":[1,2,3,...], "idx":["idx1", "idx2", ...]}}

But I need it like this:

["my_data":{"labels":1, "idx": "idx1"},{"labels":2, "idx": "idx2"},... ]

I tried to loop like this to change the format:

var arr = [];
for (let [key, value] of Object.entries(my_data)) {
    arr.push({[key]:value});
}
console.log(key, value);

But the result is a format I can not use with ag-grid

labels: [1,2,...]
idx: [idx1, idx2,...]

Body:
One way you can approach this is by using the map method like in the following example:

const temp = { my_data: { labels: [1, 2, 3], idx: ["idx1", "idx2", "idx3"] } };

const result = temp.my_data.labels.map((label, index) => {
  const idx = temp.my_data.idx[index];

  return {
    label,
    idx
  };
});

console.log(result)

This way, you're mapping through labels then extracting the value for idx based on the index of the label.


问:
How to nest multiple property delegates in Kotlin
I've come accross a case where I want to "chain" mutliple delegates (piping the output of one into the other).

This seems to be possible:

private val errorLogList by listSO(listOf<StateObject<Luxeption>>(), SODest.NONE, publicSOAccessRights())
val errorLog: StateObject<List<StateObject<Luxeption>>> by addToSet(errorLogList)
```

<p>However, this does not look too well :). I'd like to do it in one line like this:</p>

<pre class="lang-kt prettyprint-override"><code>val errorLog: StateObject<List<StateObject<Luxeption>>> by addToSet(
   listSO(listOf<StateObject<Luxeption>>(), SODest.NONE, publicSOAccessRights())
)
</code>```

My question: Is this type of creating properties through delegates possible in Kotlin?

Here are both implementations of my delegates:

addToSet:

open class ChildSOReturner {

    val set: Set<StateObject<*>> = setOf()

    inline fun <reified T> addToSet(so: T) = object: ReadOnlyProperty<Any?, T> {
        override operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
            if (thisRef is T) {
                set.plus(so)
                return so
            } else throw IllegalArgumentException()
        }
    }
}
```

<p>listSo:</p>

<pre class="lang-kt prettyprint-override"><code>fun <O> listSO(
    initialState: List<StateObject<O>>,
    soDest: SODest,
    soAccessRights: SOAccessRights
) = object : ReadOnlyProperty<Any?, StateObject<List<StateObject<O>>>> {

    override operator fun getValue(thisRef: Any?, property: KProperty<*>): StateObject<List<StateObject<O>>> {
        val meta = SOMeta(SOId(property.name), soDest, soAccessRights)
        return StateObjectList(initialState, meta)
    }

}
</code>```

答:
It turned out to be quite tricky, but possible (unless I am missing something, and it isn't tested but the idea should work):

```<code>fun <T, U, V> composeProperties(prop: ReadOnlyProperty<T, U>, f: (U) -> ReadOnlyProperty<T, V>) : ReadOnlyProperty<T, V> {
    var props = mutableMapOf<Pair<T, KProperty<*>>, ReadOnlyProperty<T, V>>()
    return object : ReadOnlyProperty<T, V> {
        override operator fun getValue(thisRef: T, property: KProperty<*>): V {
            val prop1 = props.getOrPut(Pair(thisRef, property)) {
                f(prop.getValue(thisRef, property))
            }
            return prop1.getValue(thisRef, property)
        }
    }
}
</code>```

And then to use

```<code>val errorLog: ... by composeProperties(listSO(...)) { addToSet(it) }
</code>```

Body:
I've come accross a case where I want to "chain" mutliple delegates (piping the output of one into the other).

This seems to be possible:

private val errorLogList by listSO(listOf<StateObject<Luxeption>>(), SODest.NONE, publicSOAccessRights())
val errorLog: StateObject<List<StateObject<Luxeption>>> by addToSet(errorLogList)

However, this does not look too well :). I'd like to do it in one line like this:

val errorLog: StateObject<List<StateObject<Luxeption>>> by addToSet(
   listSO(listOf<StateObject<Luxeption>>(), SODest.NONE, publicSOAccessRights())
)

My question: Is this type of creating properties through delegates possible in Kotlin?

Here are both implementations of my delegates:

addToSet:

open class ChildSOReturner {

    val set: Set<StateObject<*>> = setOf()

    inline fun <reified T> addToSet(so: T) = object: ReadOnlyProperty<Any?, T> {
        override operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
            if (thisRef is T) {
                set.plus(so)
                return so
            } else throw IllegalArgumentException()
        }
    }
}

listSo:

fun <O> listSO(
    initialState: List<StateObject<O>>,
    soDest: SODest,
    soAccessRights: SOAccessRights
) = object : ReadOnlyProperty<Any?, StateObject<List<StateObject<O>>>> {

    override operator fun getValue(thisRef: Any?, property: KProperty<*>): StateObject<List<StateObject<O>>> {
        val meta = SOMeta(SOId(property.name), soDest, soAccessRights)
        return StateObjectList(initialState, meta)
    }

}

Body:
It turned out to be quite tricky, but possible (unless I am missing something, and it isn't tested but the idea should work):

fun <T, U, V> composeProperties(prop: ReadOnlyProperty<T, U>, f: (U) -> ReadOnlyProperty<T, V>) : ReadOnlyProperty<T, V> {
    var props = mutableMapOf<Pair<T, KProperty<*>>, ReadOnlyProperty<T, V>>()
    return object : ReadOnlyProperty<T, V> {
        override operator fun getValue(thisRef: T, property: KProperty<*>): V {
            val prop1 = props.getOrPut(Pair(thisRef, property)) {
                f(prop.getValue(thisRef, property))
            }
            return prop1.getValue(thisRef, property)
        }
    }
}

And then to use

val errorLog: ... by composeProperties(listSO(...)) { addToSet(it) }


问:
remove inner shadow of text input
So I have a text input, im using html5, on chrome, and I want to change the look of a text input, I've removed the outline on focus (orange on chrome), I set the background to a light color #f1f1f1 but now there is like a thicker border on the top and left sides, like it's meant to look pushed in, when there is no change in background color this doesn't happen. How do I remove it? Sorry I can't provide a picture, on a mobile device.

It happens on chrome, ie, and Firefox, can't test any others.

答:
here is a small snippet that might be cool to try out:

```<code>input {
border-radius: 10px;
border-color: violet;
border-style: solid;
}
</code>```

note that: border-style removes the inner shadow.

input {
    border-radius: 10px;
    border-color: violet;
    border-style: solid;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text"/></code>```

Title: remove inner shadow of text input

Body:
here is a small snippet that might be cool to try out:

input {
border-radius: 10px;
border-color: violet;
border-style: solid;
}

note that: border-style removes the inner shadow.

input {
    border-radius: 10px;
    border-color: violet;
    border-style: solid;
  }

<input type="text"/>


问:
Issues With Arrow Syntax and Binding in React for Grandchild Element
I'm trying to create a test page and I'm having trouble with getting some buttons to work.

```<code>import React from 'react'
import { Dropdown, Icon, Menu, Segment } from 'semantic-ui-react'

export class Page extends React.Component<any, any> {

    constructor(props: any) {
        super(props);
        this.state = {
            sidebarVisible: false
        }
    }

    render() {
        return (
            <Header name='test' onCLick={this.handleIconClick}/>
        )
    }

    handleIconClick = () => {

        console.log('CLICKED');
        let visible = !this.state.sidebarVisible;
        this.setState({sidebarVisible: visible});

    }

}

export class Header extends React.Component<any, any> {

    constructor(props: any) {
        super(props);
        this.state = {
            iconName: this.props.visible ? 'angle double left' : 'angle double right'
        };
        console.log(this.props)
    }

    render() {
        return (
            <div>
                <Menu>
                    <Menu.Item onClick={this.props.onClick}>
                        <Icon name={this.state.iconName}/>
                    </Menu.Item>
                </Menu>
            </div>
        )
    }
}
</code>```

In the above example which I've arrived at from following documentation, looking online for solutions, etc... does not even allow me to click the button ("CLICKED" is never logged).

When I change

```<code><Menu.Item onClick={this.props.onClick}>
</code>```

to

```<code><Menu.Item onClick={() => this.props.onClick()}>
</code>```

I get an error stating that:

this.props.onClick is not a function

I've spent quite some time on this so your help would be greatly appreciated.

Thanks.

答:
It's not related to arrow syntax. You have onCLick instead of onClick when you call  component in <Page /> component.

Change as the following:

```<code><Header name='test' onClick={this.handleIconClick} />
</code>```

I hope that helps!

Body:
I'm trying to create a test page and I'm having trouble with getting some buttons to work.

import React from 'react'
import { Dropdown, Icon, Menu, Segment } from 'semantic-ui-react'

export class Page extends React.Component<any, any> {

    constructor(props: any) {
        super(props);
        this.state = {
            sidebarVisible: false
        }
    }

    render() {
        return (

        )
    }

    handleIconClick = () => {

        console.log('CLICKED');
        let visible = !this.state.sidebarVisible;
        this.setState({sidebarVisible: visible});

    }

}

export class Header extends React.Component<any, any> {

    constructor(props: any) {
        super(props);
        this.state = {
            iconName: this.props.visible ? 'angle double left' : 'angle double right'
        };
        console.log(this.props)
    }

    render() {
        return (

                <Menu>
                    <Menu.Item onClick={this.props.onClick}>
                        <Icon name={this.state.iconName}/>
                    </Menu.Item>
                </Menu>

        )
    }
}

In the above example which I've arrived at from following documentation, looking online for solutions, etc... does not even allow me to click the button ("CLICKED" is never logged).

When I change

<Menu.Item onClick={this.props.onClick}>

to

<Menu.Item onClick={() => this.props.onClick()}>

I get an error stating that:

this.props.onClick is not a function

I've spent quite some time on this so your help would be greatly appreciated.

Thanks.

Body:
It's not related to arrow syntax. You have onCLick instead of onClick when you call <Header /> component in <Page /> component.

Change as the following:

<Header name='test' onClick={this.handleIconClick} />

I hope that helps!


问:
Offset html scroll-behavior
I have the following layout:

html {
  scroll-behavior:smooth;
}

header {
  height: 234px;
  position: sticky;
  top: 0;
  padding: 24px;
  background-color: rgba(255,255,255,0.5);
  border-bottom: 1px solid #dedede;
}

nav {
  height: 88px;
  position: sticky;
  top: 234px;
  padding: 24px;
  background: #f5f5f5;
}

section {
  height: 100vh;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <p>I'm the header</p>
</header>

<section>
  <p>I'm a video</p>
</section>

<nav>
  Section 1
  Section 2
  Section 3
</nav>

<section id="1">
  <p>I'm section 1</p>
</section>

<section id="2">
  <p>I'm section 2</p>
</section>

<section id="3">
  <p>I'm section 3</p>
</section></code>```

As you can see, I have the main header at the top of the page with position: sticky;. I then have a  further down the page which sticks underneath the main header. You can then click the links to scroll to each
.

When clicking on each link in the , each
 scrolls to the very top the page.

Is there a way to offset the top position? In this case, I'd need to offset from the top by 322px ( and  heights combined).

I've tried adding a :before pseudo element to each
 with a height of 322px, but this doesn't work.

答:
It is a little bit hacky, but works for your case.

Add a class .section for each section and a span inside with the ID.

```<code><nav>
  <a href="#section1">Section 1</a>
  <a href="#section2">Section 2</a>
  <a href="#section3">Section 3</a>
</nav>

<section class="section">
  <span id="section1"></span>
  <p>I'm section 1</p>
</section>

<section class="section">
  <span id="section2"></span>
  <p>I'm section 2</p>
</section>

<section class="section">
  <span id="section3"></span>
  <p>I'm section 3</p>
</section>
</code>```

Then, absolutely position each span 322px up.

It is also necessary to add z-index to the header and nav due to the relative position of the sections.

```<code>.section {
  position: relative;
}
.section span {
  top: -322px;
  pointer-events: none;
  position: absolute;
}
header, nav {
  z-index: 1;
}
</code>```

Title: Offset html scroll-behavior

Body:
I have the following layout:

html {
  scroll-behavior:smooth;
}

header {
  height: 234px;
  position: sticky;
  top: 0;
  padding: 24px;
  background-color: rgba(255,255,255,0.5);
  border-bottom: 1px solid #dedede;
}

nav {
  height: 88px;
  position: sticky;
  top: 234px;
  padding: 24px;
  background: #f5f5f5;
}

section {
  height: 100vh;
  text-align: center;
}

I'm the header

I'm a video

  Section 1
  Section 2
  Section 3

I'm section 1

I'm section 2

I'm section 3

As you can see, I have the main header at the top of the page with position: sticky;. I then have a  further down the page which sticks underneath the main header. You can then click the links to scroll to each
.

When clicking on each link in the , each
 scrolls to the very top the page.

Is there a way to offset the top position? In this case, I'd need to offset from the top by 322px ( and  heights combined).

I've tried adding a :before pseudo element to each
 with a height of 322px, but this doesn't work.

Body:
It is a little bit hacky, but works for your case.

Add a class .section for each section and a span inside with the ID.

<nav>
  <a href="#section1">Section 1</a>
  <a href="#section2">Section 2</a>
  <a href="#section3">Section 3</a>
</nav>

<section class="section">
  <span id="section1"></span>
  <p>I'm section 1</p>
</section>

<section class="section">
  <span id="section2"></span>
  <p>I'm section 2</p>
</section>

<section class="section">
  <span id="section3"></span>
  <p>I'm section 3</p>
</section>

Then, absolutely position each span 322px up.

It is also necessary to add z-index to the header and nav due to the relative position of the sections.

.section {
  position: relative;
}
.section span {
  top: -322px;
  pointer-events: none;
  position: absolute;
}
header, nav {
  z-index: 1;
}


问:
FMDB / sqlite query problem with function
I am really new to swift and trying to understand ios programming. Basically I have a table where "id" and "fact" columns. id is primary key'd  and here is the swift fuction I am trying to query the values

```<code>func getItemsFromRow(fact_cid: String) ->[FactsData]{
    var rowData: [FactsData]!
    let rawQ = "select * from facts where \(facts_id)=?"
    if (openDatabase()){
        do{
            let results = try database.executeQuery(rawQ, value(forKey: fact_cid))
            while results.next(){
                let currentFact = FactsData(factid: results.string(forColumn: facts_id), factsdata: results.string(forColumn: facts_fld))
                if rowData == nil {
                    rowData = [FactsData]()
                }
                rowData.append(currentFact)
            }
        }
    }
    return rowData
}
</code>```

But this line gives me error

```<code>let results = try database.executeQuery(rawQ, value(forKey: fact_cid))
</code>```

Error is

```<code>Cannot invoke 'executeQuery' with an argument list of type '(String, Any?)'
</code>```

I am trying to pass the id as string. Not sure what I am doing wrong here.

Any help is much appreciated.

答:
Change it to

```<code>let results = try database.executeQuery(rawQ, values: [fact_cid])
</code>```

since the second parameter should be an array

Body:
I am really new to swift and trying to understand ios programming. Basically I have a table where "id" and "fact" columns. id is primary key'd  and here is the swift fuction I am trying to query the values

func getItemsFromRow(fact_cid: String) ->[FactsData]{
    var rowData: [FactsData]!
    let rawQ = "select * from facts where \(facts_id)=?"
    if (openDatabase()){
        do{
            let results = try database.executeQuery(rawQ, value(forKey: fact_cid))
            while results.next(){
                let currentFact = FactsData(factid: results.string(forColumn: facts_id), factsdata: results.string(forColumn: facts_fld))
                if rowData == nil {
                    rowData = [FactsData]()
                }
                rowData.append(currentFact)
            }
        }
    }
    return rowData
}

But this line gives me error

let results = try database.executeQuery(rawQ, value(forKey: fact_cid))

Error is

Cannot invoke 'executeQuery' with an argument list of type '(String, Any?)'

I am trying to pass the id as string. Not sure what I am doing wrong here.

Any help is much appreciated.

Body:
Change it to

let results = try database.executeQuery(rawQ, values: [fact_cid])

since the second parameter should be an array


问:
I'm trying to use multiplot to combine plot and splot but x,y labels seem to be shifted
```<code>set xrange [-2:2]
set yrange [-2:2]

set xlabel 'X'
set ylabel 'Y'

set samples 300
set isosamples 300

set lmargin screen 0.1
set rmargin screen 0.9
set tmargin screen 0.9
set bmargin screen 0.1

set multiplot

set pm3d map
set palette grey
unset colorbox
splot x**2+y**2 < 1 ? 0:0.2
unset pm3d

plot sin(x) lc 0
</code>```

This code displays the problem - different positionning of x/y labels by splot, plot.

答:
It is quite possible that you can create your composite plot entirely with splot and therefore do not need to use multiplot, bypassing the whole issue.  I realize that the example you give may be over-simplified but as it stands the plot can be created by

```<code>set xrange [-2:2]
set yrange [-2:2]
set trange [-2:2]

set xlabel 'X'
set ylabel 'Y'

set samples 300
set isosamples 300

set view map
set pm3d at b
set palette grey
unset colorbox

splot x**2+y**2 < 1 ? 0:0.2 with pm3d, \
      '+' using 1:(sin($1)):(0) with lines lc "blue" lw 3
</code>```

Body:
set xrange [-2:2]
set yrange [-2:2]

set xlabel 'X'
set ylabel 'Y'

set samples 300
set isosamples 300

set lmargin screen 0.1
set rmargin screen 0.9
set tmargin screen 0.9
set bmargin screen 0.1

set multiplot

set pm3d map
set palette grey
unset colorbox
splot x**2+y**2 < 1 ? 0:0.2
unset pm3d

plot sin(x) lc 0

This code displays the problem - different positionning of x/y labels by splot, plot.

Body:
It is quite possible that you can create your composite plot entirely with splot and therefore do not need to use multiplot, bypassing the whole issue.  I realize that the example you give may be over-simplified but as it stands the plot can be created by

set xrange [-2:2]
set yrange [-2:2]
set trange [-2:2]

set xlabel 'X'
set ylabel 'Y'

set samples 300
set isosamples 300

set view map
set pm3d at b
set palette grey
unset colorbox

splot x**2+y**2 < 1 ? 0:0.2 with pm3d, \
      '+' using 1:(sin($1)):(0) with lines lc "blue" lw 3


问:
OCaml syntax error in the general statement with a module declaration
```<code>  1 module type Dictionary = sig
  2     type ('k, 'v) t
  3
  4     val empty : ('k, 'v) t
  5     val insert : 'k -> 'v -> ('k, 'v) t -> ('k, 'v) t
  6     val lookup : 'k -> ('k, 'v) t -> 'v
  7 end
  8
  9 module DictionaryImpl : Dictionary = struct
 10     type ('k, 'v) t = ('k * 'v) list
 11     let empty = []
 12     let insert k v t = (k,v)::t
 13     (*let lookup k t = List.assoc k t*)
 14     let rec lookup k t =
 15         match t with
 16         | [] -> failwith "No data"
 17         | hd::tl ->
 18                if fst hd = k then snd hd
 19                else lookup k tl
 20 end
 21
 22 let _ =
 23     let a = DictionaryImpl.empty in
 24     let b = DictionaryImpl.insert "first" 1 a in
 25     DictionaryImpl.lookup "first" b
 26
</code>```

Please focus on the lines between 22 and 25.

If I change with the following code, a syntax error is occurred but I don't know why.

```<code>let a = DictionaryImpl.empty in
let b = DictionaryImpl.insert "first" 1 a in
DictionaryImpl.lookup "first" b
</code>```

The key point that I'm thinking is whether underscore statement is existed or not.
I know that underscore means just ignore receiver variable but I'd like to know what has that I don't know in this context.

答:
The difference is that

```<code>let _ =
  let a = DictionaryImpl.empty in
  let b = DictionaryImpl.insert "first" 1 a in
  DictionaryImpl.lookup "first" b
</code>```

is a definition (even if this definition is not binding any variables). Contrarily

```<code>let a = DictionaryImpl.empty in
let b = DictionaryImpl.insert "first" 1 a in
DictionaryImpl.lookup "first" b
</code>```

is an expression.
Toplevel expressions require to be separated from definitions by ;;:

```<code>;;
let a = DictionaryImpl.empty in
let b = DictionaryImpl.insert "first" 1 a in
DictionaryImpl.lookup "first" b
</code>```

However, this form is not completely idiomatic and lot of people prefer to forego toplevel definitions and use only definitions. For instance, one may write

```<code>let location="universe"
let () = Format.printf "Hello, %s" location
</code>```

rather than

```<code>let location="universe"
;;
Format.printf "Hello, %s" location
</code>```

Body:
  1 module type Dictionary = sig
  2     type ('k, 'v) t
  3
  4     val empty : ('k, 'v) t
  5     val insert : 'k -> 'v -> ('k, 'v) t -> ('k, 'v) t
  6     val lookup : 'k -> ('k, 'v) t -> 'v
  7 end
  8
  9 module DictionaryImpl : Dictionary = struct
 10     type ('k, 'v) t = ('k * 'v) list
 11     let empty = []
 12     let insert k v t = (k,v)::t
 13     (*let lookup k t = List.assoc k t*)
 14     let rec lookup k t =
 15         match t with
 16         | [] -> failwith "No data"
 17         | hd::tl ->
 18                if fst hd = k then snd hd
 19                else lookup k tl
 20 end
 21
 22 let _ =
 23     let a = DictionaryImpl.empty in
 24     let b = DictionaryImpl.insert "first" 1 a in
 25     DictionaryImpl.lookup "first" b
 26

Please focus on the lines between 22 and 25.

If I change with the following code, a syntax error is occurred but I don't know why.

let a = DictionaryImpl.empty in
let b = DictionaryImpl.insert "first" 1 a in
DictionaryImpl.lookup "first" b

The key point that I'm thinking is whether underscore statement is existed or not.
I know that underscore means just ignore receiver variable but I'd like to know what has that I don't know in this context.

Body:
The difference is that

let _ =
  let a = DictionaryImpl.empty in
  let b = DictionaryImpl.insert "first" 1 a in
  DictionaryImpl.lookup "first" b

is a definition (even if this definition is not binding any variables). Contrarily

let a = DictionaryImpl.empty in
let b = DictionaryImpl.insert "first" 1 a in
DictionaryImpl.lookup "first" b

is an expression.
Toplevel expressions require to be separated from definitions by ;;:

;;
let a = DictionaryImpl.empty in
let b = DictionaryImpl.insert "first" 1 a in
DictionaryImpl.lookup "first" b

However, this form is not completely idiomatic and lot of people prefer to forego toplevel definitions and use only definitions. For instance, one may write

let location="universe"
let () = Format.printf "Hello, %s" location

rather than

let location="universe"
;;
Format.printf "Hello, %s" location