问:
Cannot move out of borrowed content from closure return value
I found this problem when working on a mid-size project. The following snippet is a minimal summary of the problem.

In the following code I try to map a list of enum variants into a Set of different enum variants. I use a closure so I can capture a mutable reference to my_list which is a list of source enum variants. The closure is then kept inside a MyType instance so it can be called later and the result used inside another method.

To keep the closure, I used a FnMut trait inside a Box. I also wrapped that inside an Option so I can set the closure after instance creation.

I based this a bit from the question asked here: structs with boxed vs. unboxed closures

use std::collections::HashSet;

enum Numbers {
    One,
    Two,
    Three,
}

#[derive(Eq, PartialEq, Hash)]
enum Romans {
    I,
    II,
    III,
}

struct MyType<'a> {
    func: Option<Box<dyn FnMut() -> HashSet<Romans> + 'a>>,
}

impl<'a> MyType<'a> {
    pub fn set_func<F>(&mut self, a_func: F)
        where F: FnMut() -> HashSet<Romans> + 'a {
        self.func = Some(Box::new(a_func));
    }

    pub fn run(&mut self) {
        let result = (self.func.unwrap())();
        if result.contains(&Romans::I) {
            println!("Roman one!");
        }
    }
}

fn main() {
    let my_list = vec![Numbers::One, Numbers::Three];
    let mut my_type = MyType {
        func: None,
    };
    my_type.set_func(|| -> HashSet<Romans> {
        HashSet::from(my_list
            .iter()
            .map(|item| {
                match item {
                    Numbers::One => Romans::I,
                    Numbers::Two => Romans::II,
                    Numbers::Three => Romans::III,
                }
            })
            .collect()
        )
    });

    my_type.run();
}

```

<p>When I try to compile, I get the following error:</p>

<pre class="lang-rust prettyprint-override"><code>error[E0507]: cannot move out of borrowed content
  --> src/main.rs:27:23
   |
27 |         let result = (self.func.unwrap())();
   |                       ^^^^^^^^^ cannot move out of borrowed content

error: aborting due to previous error
</code>```

I don't quite understand what is being moved out. Is it a hidden self? The resulting HashSet? or maybe the values inside the set?
What am I doing wrong?

答:
The trouble you're having is that calling unwrap on an Option will consume it--it takes self as an argument. Inside run(), your MyType only has a &mut self reference to itself, so it cannot take ownership of its field.

The solution is to take mutable reference to the stored function instead:

    pub fn run(&mut self) {
        if let Some(func) = &mut self.func {
            let result = func();
            if result.contains(&Romans::I) {
                println!("Roman one!");
            }
        }
    }
```

Body:
I found this problem when working on a mid-size project. The following snippet is a minimal summary of the problem.

In the following code I try to map a list of enum variants into a Set of different enum variants. I use a closure so I can capture a mutable reference to my_list which is a list of source enum variants. The closure is then kept inside a MyType instance so it can be called later and the result used inside another method.

To keep the closure, I used a FnMut trait inside a Box. I also wrapped that inside an Option so I can set the closure after instance creation.

I based this a bit from the question asked here: structs with boxed vs. unboxed closures

use std::collections::HashSet;

enum Numbers {
    One,
    Two,
    Three,
}

#[derive(Eq, PartialEq, Hash)]
enum Romans {
    I,
    II,
    III,
}

struct MyType<'a> {
    func: Option<Box<dyn FnMut() -> HashSet<Romans> + 'a>>,
}

impl<'a> MyType<'a> {
    pub fn set_func<F>(&mut self, a_func: F)
        where F: FnMut() -> HashSet<Romans> + 'a {
        self.func = Some(Box::new(a_func));
    }

    pub fn run(&mut self) {
        let result = (self.func.unwrap())();
        if result.contains(&Romans::I) {
            println!("Roman one!");
        }
    }
}

fn main() {
    let my_list = vec![Numbers::One, Numbers::Three];
    let mut my_type = MyType {
        func: None,
    };
    my_type.set_func(|| -> HashSet<Romans> {
        HashSet::from(my_list
            .iter()
            .map(|item| {
                match item {
                    Numbers::One => Romans::I,
                    Numbers::Two => Romans::II,
                    Numbers::Three => Romans::III,
                }
            })
            .collect()
        )
    });

    my_type.run();
}

When I try to compile, I get the following error:

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:27:23
   |
27 |         let result = (self.func.unwrap())();
   |                       ^^^^^^^^^ cannot move out of borrowed content

error: aborting due to previous error

I don't quite understand what is being moved out. Is it a hidden self? The resulting HashSet? or maybe the values inside the set?
What am I doing wrong?


来源: stackexchange

问:
How to style a checkbox using CSS
I am trying to style a checkbox using the following:

<input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" />```

But the style is not applied. The checkbox still displays its default style. How do I give it the specified style?

答:
With pure CSS, nothing fancy with :before and :after, no transforms, you can turn off the default appearance and then style it with an inline background image like the following example. This works in Chrome, Firefox, Safari, and now Edge (Chromium Edge).

INPUT[type=checkbox]:focus
{
    outline: 1px solid rgba(0, 0, 0, 0.2);
}

INPUT[type=checkbox]
{
    background-color: #DDD;
    border-radius: 2px;
    appearance: none;
    -webkit-appearance: none;
    -moz-appearance: none;
    width: 17px;
    height: 17px;
    cursor: pointer;
    position: relative;
    top: 5px;
}

INPUT[type=checkbox]:checked
{
    background-color: #409fd6;
    background: #409fd6 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <label><input type="checkbox"> I Agree To Terms & Conditions</label>
</form></code>```

ContentLicense: CC BY-SA 4.0

Title: How to style a checkbox using CSS

Body:
I am trying to style a checkbox using the following:

<input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" />

But the style is not applied. The checkbox still displays its default style. How do I give it the specified style?

Body:
With pure CSS, nothing fancy with :before and :after, no transforms, you can turn off the default appearance and then style it with an inline background image like the following example. This works in Chrome, Firefox, Safari, and now Edge (Chromium Edge).

INPUT[type=checkbox]:focus
{
    outline: 1px solid rgba(0, 0, 0, 0.2);
}

INPUT[type=checkbox]
{
    background-color: #DDD;
    border-radius: 2px;
    appearance: none;
    -webkit-appearance: none;
    -moz-appearance: none;
    width: 17px;
    height: 17px;
    cursor: pointer;
    position: relative;
    top: 5px;
}

INPUT[type=checkbox]:checked
{
    background-color: #409fd6;
    background: #409fd6 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
}

<form>
  <label><input type="checkbox"> I Agree To Terms &amp; Conditions</label>
</form>


问:
How to dynamically position an absolute div?
Let's say I have a 1000px page width, my header contains 10 horizontal nav elements using justify-content: space-between.
If I hover nav 1 link, an absolute menu div will appear width a specific width and left: 0, if I hover nav 2, another menu div will appear still with left: 0. But when I hover nav 7 or nav 8, how can I automatically make the menu get aligned right (right: 0)?

here is a code snippet of my html & css:

```<code><nav>
  <ul>
    <li>
      <a href="#">Nav menu1</a>
      <div class="menu">Content menu 1</div>
    </li>
    <li>
      <a href="#">Nav menu2</a>
      <div class="menu">Content menu 2</div>
    </li>
    <li>
      <a href="#">Nav menu3</a>
      <div class="menu">Content menu 3</div>
    </li>
    <li>
      <a href="#">Nav menu4</a>
      <div class="menu">Content menu 4</div>
    </li>
    <li>
      <a href="#">Nav menu5</a>
      <div class="menu">Content menu 5</div>
    </li>
    <li>
      <a href="#">Nav menu6</a>
      <div class="menu">Content menu 6</div>
    </li>
    <li>
      <a href="#">Nav menu7</a>
      <div class="menu">Content menu 7</div>
    </li>
    <li>
      <a href="#">Nav menu8</a>
      <div class="menu">Content menu 8</div>
    </li>
    <li>
      <a href="#">Nav menu9</a>
      <div class="menu">Content menu 9</div>
    </li>
    <li>
      <a href="#">Nav menu10</a>
      <div class="menu">Content menu 10</div>
    </li>
  </ul>
</nav>

ul {
    display: flex;
    font-size: 15px;
    height: 100%;
    border: solid 1px #ccc;
    max-width: 1200px;
    margin: 0 auto;
    padding: 24px;
    align-items: center;
    justify-content: space-between;
}

ul > li {
  display: flex;
  position: relative;
  cursor: pointer;
  padding-left: 6px;
  padding-right: 6px;
  height: 40px;
  align-items: center;
  white-space: nowrap;
  list-style: none;
}

.menu {
  display: block;
  position: absolute;
  visibility: hidden;
  color: #333;
    width: 500px;
  background: #fff;
  padding: 18px;
  min-height: 80px;
  box-shadow: 0px 2px 1px -1px rgba(0,0,0,0.2), 0px 1px 1px 0px rgba(0,0,0,0.14), 0px 1px 3px 0px rgba(0,0,0,0.12);
  opacity: 0;
  transition: all .4s ease;
  transition-delay: .3s;
  left: 0;
  top: 140%;
  z-index: 99999;
}

ul > li:hover .menu {
    display: block;
    visibility: visible;
    opacity: 1;
    top: 100%;
}
</code>```

答:
Your question is missing a lot of information including the code you are working with. It seems you may be looking for the nth child pseudo class to define a range.

The following is generic as you have not provided an HTML sample and will affect the 6th to 10th children.

CSS:

```<code> li:nth-child(n+6):nth-child(-n+10){
 right:0;
 }
</code>```

Edit: Updated answer now that the question is clearer...

See the below example with added (vanilla) Javascript.

```<code><!doctype html>
<html>
<head>

<style>
ul{
display:flex;
  font-size:15px;
  height:100%;
  border:solid 1px #ccc;
  max-width:1200px;
  margin:0 auto;
  padding:24px;
  align-items:center;
  justify-content:space-between;
}
ul > li{
  display:flex;
  position:relative;
  cursor:pointer;
  padding-left:6px;
  padding-right:6px;
  height:40px;
  align-items:center;
  white-space:nowrap;
  list-style:none;
}
.menu{
  display:block;
  position:absolute;
  visibility:hidden;
  color:#333;
  width:500px;
  background:#fff;
  padding:18px;
  min-height:80px;
  box-shadow:0px 2px 1px -1px rgba(0,0,0,0.2), 0px 1px 1px 0px rgba(0,0,0,0.14), 0px 1px 3px 0px rgba(0,0,0,0.12);
  opacity:0;
  transition:all .4s ease;
  transition-delay:.3s;
  top:140%;
}
ul > li:hover .menu{
  display:block;
  visibility:visible;
  opacity:1;
  top:100%;
}
</style>

</head>
<body>

<nav>
 <ul>
  <li>
    <a href="#">Nav menu1</a>
    <div class="menu">Content menu 1</div>
  </li><li>
    <a href="#">Nav menu2</a>
    <div class="menu">Content menu 2</div>
  </li><li>
    <a href="#">Nav menu3</a>
    <div class="menu">Content menu 3</div>
  </li><li>
    <a href="#">Nav menu4</a>
    <div class="menu">Content menu 4</div>
  </li><li>
    <a href="#">Nav menu5</a>
    <div class="menu">Content menu 5</div>
  </li><li>
    <a href="#">Nav menu6</a>
    <div class="menu">Content menu 6</div>
  </li><li>
    <a href="#">Nav menu7</a>
    <div class="menu">Content menu 7</div>
  </li><li>
    <a href="#">Nav menu8</a>
    <div class="menu">Content menu 8</div>
  </li><li>
    <a href="#">Nav menu9</a>
    <div class="menu">Content menu 9</div>
  </li><li>
    <a href="#">Nav menu10</a>
    <div class="menu">Content menu 10</div>
  </li>
 </ul>
</nav>

<script>
var elems=document.querySelectorAll('div.menu');  //Get NodeList of elements
elems.forEach(function(elem){                     //Iterate
var pos=elem.getBoundingClientRect();             //Get element info
let stat=document.elementFromPoint(pos.right,0);  //Check position
if(stat===null){                                  //Will be null if out of viewport
elem.style.right='0';                             //Add the right:0; style
}else{
elem.style.left='0';                              //Add the left:0; style
}});
</script>

</body>
</html>
</code>```

Edit 2: As requested, just change the JavaScript to check against the container.

As it is now this will match against the first
 found in the document. You will probably want to
 and match with the id instead:

```<code><script>
//var cont=document.getElementById('cont');       //Match by ID
var cont=document.querySelector('ul');            //Match first <ul>

var posc=cont.getBoundingClientRect();            //Get container info
var elems=document.querySelectorAll('div.menu');  //Get NodeList of elements
elems.forEach(function(elem){                     //Iterate
var posv=elem.getBoundingClientRect();            //Get element info
var offset=posc.right-posv.right;                 //Calculate difference
if(offset<0){                                     //Will be <0 if out of container
elem.style.right='0';                             //Add the right:0; style
}else{
elem.style.left='0';                              //Add the left:0; style
}});
</script>
</code>```

Body:
Let's say I have a 1000px page width, my header contains 10 horizontal nav elements using justify-content: space-between.
If I hover nav 1 link, an absolute menu div will appear width a specific width and left: 0, if I hover nav 2, another menu div will appear still with left: 0. But when I hover nav 7 or nav 8, how can I automatically make the menu get aligned right (right: 0)?

here is a code snippet of my html & css:

      Nav menu1

Content menu 1

      Nav menu2

Content menu 2

      Nav menu3

Content menu 3

      Nav menu4

Content menu 4

      Nav menu5

Content menu 5

      Nav menu6

Content menu 6

      Nav menu7

Content menu 7

      Nav menu8

Content menu 8

      Nav menu9

Content menu 9

      Nav menu10

Content menu 10

ul {
    display: flex;
    font-size: 15px;
    height: 100%;
    border: solid 1px #ccc;
    max-width: 1200px;
    margin: 0 auto;
    padding: 24px;
    align-items: center;
    justify-content: space-between;
}

ul > li {
  display: flex;
  position: relative;
  cursor: pointer;
  padding-left: 6px;
  padding-right: 6px;
  height: 40px;
  align-items: center;
  white-space: nowrap;
  list-style: none;
}

.menu {
  display: block;
  position: absolute;
  visibility: hidden;
  color: #333;
    width: 500px;
  background: #fff;
  padding: 18px;
  min-height: 80px;
  box-shadow: 0px 2px 1px -1px rgba(0,0,0,0.2), 0px 1px 1px 0px rgba(0,0,0,0.14), 0px 1px 3px 0px rgba(0,0,0,0.12);
  opacity: 0;
  transition: all .4s ease;
  transition-delay: .3s;
  left: 0;
  top: 140%;
  z-index: 99999;
}

ul > li:hover .menu {
    display: block;
    visibility: visible;
    opacity: 1;
    top: 100%;
}

Body:
Your question is missing a lot of information including the code you are working with. It seems you may be looking for the nth child pseudo class to define a range.

The following is generic as you have not provided an HTML sample and will affect the 6th to 10th children.

CSS:

 li:nth-child(n+6):nth-child(-n+10){
 right:0;
 }

Edit: Updated answer now that the question is clearer...

See the below example with added (vanilla) Javascript.

<!doctype html>
<html>
<head>

<style>
ul{
display:flex;
  font-size:15px;
  height:100%;
  border:solid 1px #ccc;
  max-width:1200px;
  margin:0 auto;
  padding:24px;
  align-items:center;
  justify-content:space-between;
}
ul > li{
  display:flex;
  position:relative;
  cursor:pointer;
  padding-left:6px;
  padding-right:6px;
  height:40px;
  align-items:center;
  white-space:nowrap;
  list-style:none;
}
.menu{
  display:block;
  position:absolute;
  visibility:hidden;
  color:#333;
  width:500px;
  background:#fff;
  padding:18px;
  min-height:80px;
  box-shadow:0px 2px 1px -1px rgba(0,0,0,0.2), 0px 1px 1px 0px rgba(0,0,0,0.14), 0px 1px 3px 0px rgba(0,0,0,0.12);
  opacity:0;
  transition:all .4s ease;
  transition-delay:.3s;
  top:140%;
}
ul > li:hover .menu{
  display:block;
  visibility:visible;
  opacity:1;
  top:100%;
}
</style>

</head>
<body>

<nav>
 <ul>
  <li>
    <a href="#">Nav menu1</a>
    <div class="menu">Content menu 1</div>
  </li><li>
    <a href="#">Nav menu2</a>
    <div class="menu">Content menu 2</div>
  </li><li>
    <a href="#">Nav menu3</a>
    <div class="menu">Content menu 3</div>
  </li><li>
    <a href="#">Nav menu4</a>
    <div class="menu">Content menu 4</div>
  </li><li>
    <a href="#">Nav menu5</a>
    <div class="menu">Content menu 5</div>
  </li><li>
    <a href="#">Nav menu6</a>
    <div class="menu">Content menu 6</div>
  </li><li>
    <a href="#">Nav menu7</a>
    <div class="menu">Content menu 7</div>
  </li><li>
    <a href="#">Nav menu8</a>
    <div class="menu">Content menu 8</div>
  </li><li>
    <a href="#">Nav menu9</a>
    <div class="menu">Content menu 9</div>
  </li><li>
    <a href="#">Nav menu10</a>
    <div class="menu">Content menu 10</div>
  </li>
 </ul>
</nav>

<script>
var elems=document.querySelectorAll('div.menu');  //Get NodeList of elements
elems.forEach(function(elem){                     //Iterate
var pos=elem.getBoundingClientRect();             //Get element info
let stat=document.elementFromPoint(pos.right,0);  //Check position
if(stat===null){                                  //Will be null if out of viewport
elem.style.right='0';                             //Add the right:0; style
}else{
elem.style.left='0';                              //Add the left:0; style
}});
</script>

</body>
</html>

Edit 2: As requested, just change the JavaScript to check against the container.

As it is now this will match against the first <ul> found in the document. You will probably want to <ul id="cont"> and match with the id instead:

<script>
//var cont=document.getElementById('cont');       //Match by ID
var cont=document.querySelector('ul');            //Match first <ul>

var posc=cont.getBoundingClientRect();            //Get container info
var elems=document.querySelectorAll('div.menu');  //Get NodeList of elements
elems.forEach(function(elem){                     //Iterate
var posv=elem.getBoundingClientRect();            //Get element info
var offset=posc.right-posv.right;                 //Calculate difference
if(offset<0){                                     //Will be <0 if out of container
elem.style.right='0';                             //Add the right:0; style
}else{
elem.style.left='0';                              //Add the left:0; style
}});
</script>


问:
Is there a way to visualize an azimuthal average a 3D Cartesian space?
I have a dataset containing values in a 200x200x38 3D space. The data is centered at [100,100,z] where z is height, and the first two values are horizontal x and y coordinates. I am trying to create a visualization of a cross section that averages the values in the dataset along a radial and at each height (making a height-radius average).

Most efficient way to calculate radial profile
This post describes how to do a radial average for a 2D dataset,̶b̶u̶t̶ ̶I̶ ̶d̶o̶n̶'̶t̶ ̶q̶u̶i̶t̶e̶ ̶u̶n̶d̶e̶r̶s̶t̶a̶n̶d̶ ̶h̶o̶w̶ ̶t̶h̶e̶y̶ ̶d̶i̶d̶ ̶t̶h̶e̶y̶ ̶b̶i̶n̶n̶e̶d̶ ̶t̶h̶e̶i̶r̶ ̶d̶a̶t̶a̶ ̶i̶n̶t̶o̶ ̶d̶i̶f̶f̶e̶r̶e̶n̶t̶ ̶r̶a̶d̶i̶i̶ ̶e̶i̶t̶h̶e̶r̶ ̶s̶i̶n̶c̶e̶.̶ ̶ ̶I̶'̶v̶e̶ ̶d̶e̶f̶i̶n̶e̶d̶ ̶f̶u̶n̶c̶t̶i̶o̶n̶s̶ ̶f̶o̶r̶ ̶r̶a̶d̶i̶i̶ ̶a̶n̶d̶ ̶a̶n̶g̶l̶e̶ ̶f̶r̶o̶m̶ ̶c̶e̶n̶t̶e̶r̶,̶ ̶b̶u̶t̶ ̶d̶o̶n̶'̶t̶ ̶k̶n̶o̶w̶ ̶h̶o̶w̶ ̶t̶o̶ ̶c̶o̶n̶v̶e̶r̶t̶ ̶m̶y̶ ̶C̶a̶r̶t̶e̶s̶i̶a̶n̶ ̶d̶a̶t̶a̶ ̶i̶n̶t̶o̶ ̶a̶ ̶c̶y̶l̶i̶n̶d̶r̶i̶c̶a̶l̶ ̶c̶o̶o̶r̶d̶i̶n̶a̶t̶e̶ ̶s̶h̶a̶p̶e̶.̶

```<code>def radial_profile(data, center):
    y, x = np.indices((data.shape))
    r = np.sqrt((x - center[0])**2 + (y - center[1])**2)
    r = r.astype(np.int)

    tbin = np.bincount(r.ravel(), data.ravel())
    nr = np.bincount(r.ravel())
    radialprofile = tbin / nr
    return radialprofile
Cent=[100,100]
Rav=[]
for i in range(37):
    B=ref[:,:,i,0]
    if B == -999.9:
        B=np.nan
    RRR=radial_profile(B,Cent)
    Rav.append(RRR)
plt.imshow(Rav, vmin=-15, vmax=70)
plt.colorbar();
plt.show()
</code>```

Using this I've been able to plot it, but have to figure out a way to remove the -999.9 values from the average. I have tried to assign it as null, but to no success. The plot otherwise works.

答:
```<code>def radial_profile(data, center):
    y, x = np.indices((data.shape))
    r = np.sqrt((x - center[0])**2 + (y - center[1])**2)
    r = r.astype(np.int)

    tbin = np.bincount(r.ravel(), data.ravel())
    nr = np.bincount(r.ravel())
    radialprofile = tbin / nr
    return radialprofile
Cent=[100,100]
Rav=[]
for i in range(37):
    dbz=np.array(ref)
    dbz[dbz == -999.9]=np.nan
    B=dbz[:,:,i,0]
    RRR=radial_profile(B,Cent)
    Rav.append(RRR)
plt.imshow(Rav, vmin=-15, vmax=70)
plt.colorbar();
plt.show()
</code>```

My apologies, I should have taken a harder look at trying to understand the post I was referring to in my question.

If anyone has any more clean or efficient solutions I would appreciate it

Body:
I have a dataset containing values in a 200x200x38 3D space. The data is centered at [100,100,z] where z is height, and the first two values are horizontal x and y coordinates. I am trying to create a visualization of a cross section that averages the values in the dataset along a radial and at each height (making a height-radius average).

Most efficient way to calculate radial profile
This post describes how to do a radial average for a 2D dataset,̶b̶u̶t̶ ̶I̶ ̶d̶o̶n̶'̶t̶ ̶q̶u̶i̶t̶e̶ ̶u̶n̶d̶e̶r̶s̶t̶a̶n̶d̶ ̶h̶o̶w̶ ̶t̶h̶e̶y̶ ̶d̶i̶d̶ ̶t̶h̶e̶y̶ ̶b̶i̶n̶n̶e̶d̶ ̶t̶h̶e̶i̶r̶ ̶d̶a̶t̶a̶ ̶i̶n̶t̶o̶ ̶d̶i̶f̶f̶e̶r̶e̶n̶t̶ ̶r̶a̶d̶i̶i̶ ̶e̶i̶t̶h̶e̶r̶ ̶s̶i̶n̶c̶e̶.̶ ̶ ̶I̶'̶v̶e̶ ̶d̶e̶f̶i̶n̶e̶d̶ ̶f̶u̶n̶c̶t̶i̶o̶n̶s̶ ̶f̶o̶r̶ ̶r̶a̶d̶i̶i̶ ̶a̶n̶d̶ ̶a̶n̶g̶l̶e̶ ̶f̶r̶o̶m̶ ̶c̶e̶n̶t̶e̶r̶,̶ ̶b̶u̶t̶ ̶d̶o̶n̶'̶t̶ ̶k̶n̶o̶w̶ ̶h̶o̶w̶ ̶t̶o̶ ̶c̶o̶n̶v̶e̶r̶t̶ ̶m̶y̶ ̶C̶a̶r̶t̶e̶s̶i̶a̶n̶ ̶d̶a̶t̶a̶ ̶i̶n̶t̶o̶ ̶a̶ ̶c̶y̶l̶i̶n̶d̶r̶i̶c̶a̶l̶ ̶c̶o̶o̶r̶d̶i̶n̶a̶t̶e̶ ̶s̶h̶a̶p̶e̶.̶

def radial_profile(data, center):
    y, x = np.indices((data.shape))
    r = np.sqrt((x - center[0])**2 + (y - center[1])**2)
    r = r.astype(np.int)

    tbin = np.bincount(r.ravel(), data.ravel())
    nr = np.bincount(r.ravel())
    radialprofile = tbin / nr
    return radialprofile
Cent=[100,100]
Rav=[]
for i in range(37):
    B=ref[:,:,i,0]
    if B == -999.9:
        B=np.nan
    RRR=radial_profile(B,Cent)
    Rav.append(RRR)
plt.imshow(Rav, vmin=-15, vmax=70)
plt.colorbar();
plt.show()

Using this I've been able to plot it, but have to figure out a way to remove the -999.9 values from the average. I have tried to assign it as null, but to no success. The plot otherwise works.

Body:
def radial_profile(data, center):
    y, x = np.indices((data.shape))
    r = np.sqrt((x - center[0])**2 + (y - center[1])**2)
    r = r.astype(np.int)

    tbin = np.bincount(r.ravel(), data.ravel())
    nr = np.bincount(r.ravel())
    radialprofile = tbin / nr
    return radialprofile
Cent=[100,100]
Rav=[]
for i in range(37):
    dbz=np.array(ref)
    dbz[dbz == -999.9]=np.nan
    B=dbz[:,:,i,0]
    RRR=radial_profile(B,Cent)
    Rav.append(RRR)
plt.imshow(Rav, vmin=-15, vmax=70)
plt.colorbar();
plt.show()

My apologies, I should have taken a harder look at trying to understand the post I was referring to in my question.

If anyone has any more clean or efficient solutions I would appreciate it


问:
TypeError: 'numpy.uint32' object is not iterable in using numpy.full function
In some lines within a huge python script, there is a 3d array of 74537000 elements that are all float numbers:

```<code>import numpy as np
prop_shape = [74537000, 3]  # to produce this however a long script is written and this will be printed (just before the controversial line below) in the first run of the code assuming it's a vector quantity like position.
prop_in_dtype = np.float32  # position array with the shape (74537000, 3) is made up of float32 values. In general, however, prop_in_dtype is changing across the script due to the nature of the array
</code>```

When we are trying to make an identical array whose elements are all -1, we can use numpy as follows:

```<code>.
.
.
my_array = np.full(tuple(prop_shape), -1, prop_in_dtype)
.
.
.
</code>```

While running this, I have the following error message:

```<code>Traceback (most recent call last):
  File "DLA_DM.py", line 19, in <module>
    settings_centroid.init()
  File "/usr5/username/settings_centroid.py", line 43, in init
    part=gizmo.io.Read.read_snapshots(species, snapshot_value_kind, snapshot_number, simulation_directory='.', snapshot_directory='output/', simulation_name='', properties=properties, element_indices=None, particle_subsample_factor=0, separate_dark_lowres=True, sort_dark_by_id=False, convert_float32=True, host_number=1, assign_host_coordinates=True, assign_host_principal_axes=False, assign_host_orbits=False, assign_formation_coordinates=False, assign_pointers=False, check_properties=True)
  File "/usr5/username/simulation/gizmo/gizmo_io.py", line 649, in read_snapshots
    element_indices, convert_float32, header)
  File "/usr5/username/simulation/gizmo/gizmo_io.py", line 1164, in read_particles
    part[spec_name][prop] = np.full(tuple(prop_shape), - 1, prop_in_dtype)
TypeError: 'numpy.uint32' object is not iterable
</code>```

答:
prop_shape is iterating in the original code. Sometimes it's a single integer (for scalar quantities e.g. 74537000) and sometimes a two-element list (for vector quantities, e.g. [74537000, 3]). I was assuming that it's fixed to be a two-element list (hence a vector). That's why tuple of a single scalar would give such error if the scalar is not a float32 dtype. To avoid that, I made an if statement where each time it checks for the dtype of the variable before making the array:

```<code>if isinstance(prop_shape, list):
    my_array = np.full(tuple(prop_shape), -1, prop_in_dtype)
else:
    my_array = np.full(prop_shape, -1, prop_in_dtype)
</code>```

However, as I said in my comment to Warren's suggestion, I end up with a MemoryError as follows:

```<code>Traceback (most recent call last):
  File "DLA_DM.py", line 96, in <module>
    gizmo.plot.Image.plot_image(settings_centroid.part, 'dark', 'mass', settings_centroid.image_kind, [0,1], settings_centroid.dimensions_select, settings_centroid.distance_max, settings_centroid.distance_bin_width_generic, distance_bin_number=settings_centroid.distance_bin_number, part_indices=part_indices, write_plot=write_plot, plot_directory=plot_directory, background_color=background_color, use_column_units=False, center_position=settings_centroid.center_position, rotation=settings_centroid.rotation, property_select={'mass.bound':[1e9,1e13]}, subsample_factor=subsample_factor, image_limits=settings_centroid.image_limits_xy, hal=settings_centroid.hal, hal_indices=settings_centroid.hal_indices, hal_position_kind=hal_position_kind, hal_radius_kind=hal_radius_kind, return_halo_info=settings_centroid.return_halo_info_value_dark)
  File "/usr5/username/simulation/gizmo/gizmo_plot.py", line 825, in plot_image
    settings_centroid.init()
  File "/usr5/username/settings_centroid.py", line 43, in init
    part=gizmo.io.Read.read_snapshots(species, snapshot_value_kind, snapshot_number, simulation_directory='.', snapshot_directory='output/', simulation_name='', properties=properties, element_indices=None, particle_subsample_factor=0, separate_dark_lowres=True, sort_dark_by_id=False, convert_float32=True, host_number=1, assign_host_coordinates=True, assign_host_principal_axes=False, assign_host_orbits=False, assign_formation_coordinates=False, assign_pointers=False, check_properties=True)
  File "/usr5/username/simulation/gizmo/gizmo_io.py", line 649, in read_snapshots
    element_indices, convert_float32, header)
  File "/usr5/username/simulation/gizmo/gizmo_io.py", line 1171, in read_particles
    part[spec_name][prop] = np.full(prop_shape, -1, prop_in_dtype)
  File "/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/numeric.py", line 309, in full
    a = empty(shape, dtype, order)
MemoryError
</code>```

Body:
In some lines within a huge python script, there is a 3d array of 74537000 elements that are all float numbers:

import numpy as np
prop_shape = [74537000, 3]  # to produce this however a long script is written and this will be printed (just before the controversial line below) in the first run of the code assuming it's a vector quantity like position.
prop_in_dtype = np.float32  # position array with the shape (74537000, 3) is made up of float32 values. In general, however, prop_in_dtype is changing across the script due to the nature of the array

When we are trying to make an identical array whose elements are all -1, we can use numpy as follows:

.
.
.
my_array = np.full(tuple(prop_shape), -1, prop_in_dtype)
.
.
.

While running this, I have the following error message:

Traceback (most recent call last):
  File "DLA_DM.py", line 19, in <module>
    settings_centroid.init()
  File "/usr5/username/settings_centroid.py", line 43, in init
    part=gizmo.io.Read.read_snapshots(species, snapshot_value_kind, snapshot_number, simulation_directory='.', snapshot_directory='output/', simulation_name='', properties=properties, element_indices=None, particle_subsample_factor=0, separate_dark_lowres=True, sort_dark_by_id=False, convert_float32=True, host_number=1, assign_host_coordinates=True, assign_host_principal_axes=False, assign_host_orbits=False, assign_formation_coordinates=False, assign_pointers=False, check_properties=True)
  File "/usr5/username/simulation/gizmo/gizmo_io.py", line 649, in read_snapshots
    element_indices, convert_float32, header)
  File "/usr5/username/simulation/gizmo/gizmo_io.py", line 1164, in read_particles
    part[spec_name][prop] = np.full(tuple(prop_shape), - 1, prop_in_dtype)
TypeError: 'numpy.uint32' object is not iterable

Body:
prop_shape is iterating in the original code. Sometimes it's a single integer (for scalar quantities e.g. 74537000) and sometimes a two-element list (for vector quantities, e.g. [74537000, 3]). I was assuming that it's fixed to be a two-element list (hence a vector). That's why tuple of a single scalar would give such error if the scalar is not a float32 dtype. To avoid that, I made an if statement where each time it checks for the dtype of the variable before making the array:

if isinstance(prop_shape, list):
    my_array = np.full(tuple(prop_shape), -1, prop_in_dtype)
else:
    my_array = np.full(prop_shape, -1, prop_in_dtype)

However, as I said in my comment to Warren's suggestion, I end up with a MemoryError as follows:

Traceback (most recent call last):
  File "DLA_DM.py", line 96, in <module>
    gizmo.plot.Image.plot_image(settings_centroid.part, 'dark', 'mass', settings_centroid.image_kind, [0,1], settings_centroid.dimensions_select, settings_centroid.distance_max, settings_centroid.distance_bin_width_generic, distance_bin_number=settings_centroid.distance_bin_number, part_indices=part_indices, write_plot=write_plot, plot_directory=plot_directory, background_color=background_color, use_column_units=False, center_position=settings_centroid.center_position, rotation=settings_centroid.rotation, property_select={'mass.bound':[1e9,1e13]}, subsample_factor=subsample_factor, image_limits=settings_centroid.image_limits_xy, hal=settings_centroid.hal, hal_indices=settings_centroid.hal_indices, hal_position_kind=hal_position_kind, hal_radius_kind=hal_radius_kind, return_halo_info=settings_centroid.return_halo_info_value_dark)
  File "/usr5/username/simulation/gizmo/gizmo_plot.py", line 825, in plot_image
    settings_centroid.init()
  File "/usr5/username/settings_centroid.py", line 43, in init
    part=gizmo.io.Read.read_snapshots(species, snapshot_value_kind, snapshot_number, simulation_directory='.', snapshot_directory='output/', simulation_name='', properties=properties, element_indices=None, particle_subsample_factor=0, separate_dark_lowres=True, sort_dark_by_id=False, convert_float32=True, host_number=1, assign_host_coordinates=True, assign_host_principal_axes=False, assign_host_orbits=False, assign_formation_coordinates=False, assign_pointers=False, check_properties=True)
  File "/usr5/username/simulation/gizmo/gizmo_io.py", line 649, in read_snapshots
    element_indices, convert_float32, header)
  File "/usr5/username/simulation/gizmo/gizmo_io.py", line 1171, in read_particles
    part[spec_name][prop] = np.full(prop_shape, -1, prop_in_dtype)
  File "/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/numeric.py", line 309, in full
    a = empty(shape, dtype, order)
MemoryError


问:
C# Am I doing "Bays & Durham Randomization by Shuffling" correctly?
I tried to improvise a random number generator by using the "Bays & Durham Randomization by Shuffling" algorithm. I followed a tutorial online and made this code:

```<code> public int[] GenerateRandomSequence_Improved(int n, int min, int max)
 {
       int[] seq = new int[n];
       for(int i = 0; i < n; i++)
       {
           int rand = GenerateNextRandomNumber(min, max);

           rand = min + rand % (max + 1 - min);
           seq[i] = rand;
       }
       return seq;
 }
</code>```

I wanna know if I did it correctly or not..

EDIT: This is the code for the GenerateNextRandomNumber method

```<code>public int GenerateNextRandomNumber(int min, int max)
{
       return cSharpRNG.Next(min,max);
}
</code>```

答:
Here is what I believe proper implementation of the Bays-Durham shuffling. Warning wrt bias in indexing due to modulo operation is right though.

.NET Core 2.2, x64 Win10

```<code>using System;
using System.Diagnostics;

namespace BaysDurhamShuffling
{
    public class BaysDurhamRNG
    {
        public int[] _table;
        public int   _xnext;

        public Random _rng = null;

        public BaysDurhamRNG(int n, int seed = 312357) {
            Debug.Assert(n > 1);

            _rng = new Random(seed);
            _table = new int [n];
            for(int k = 0; k != n; ++k) {
                _table[k] = _rng.Next();
            }
            _xnext = _rng.Next();
        }

        public int next() {
            var x = _xnext; // store return value

            var j  = _xnext % _table.Length; // form the index j into the table
            _xnext = _table[j];              // get jth element of table and to copy it to the output stream on next call
            _table[j] = _rng.Next();         // replace jth element of table with next random value from input stream

            return x; // return what was stored in next value
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var rng = new BaysDurhamRNG (16, 12345);

            for(int k = 0; k != 30; ++k) {
                var x = rng.next();
                Console.WriteLine($"RV = {x}");
            }
        }
    }
}
</code>```

Body:
I tried to improvise a random number generator by using the "Bays & Durham Randomization by Shuffling" algorithm. I followed a tutorial online and made this code:

 public int[] GenerateRandomSequence_Improved(int n, int min, int max)
 {
       int[] seq = new int[n];
       for(int i = 0; i < n; i++)
       {
           int rand = GenerateNextRandomNumber(min, max);

           rand = min + rand % (max + 1 - min);
           seq[i] = rand;
       }
       return seq;
 }

I wanna know if I did it correctly or not..

EDIT: This is the code for the GenerateNextRandomNumber method

public int GenerateNextRandomNumber(int min, int max)
{
       return cSharpRNG.Next(min,max);
}

Body:
Here is what I believe proper implementation of the Bays-Durham shuffling. Warning wrt bias in indexing due to modulo operation is right though.

.NET Core 2.2, x64 Win10

using System;
using System.Diagnostics;

namespace BaysDurhamShuffling
{
    public class BaysDurhamRNG
    {
        public int[] _table;
        public int   _xnext;

        public Random _rng = null;

        public BaysDurhamRNG(int n, int seed = 312357) {
            Debug.Assert(n > 1);

            _rng = new Random(seed);
            _table = new int [n];
            for(int k = 0; k != n; ++k) {
                _table[k] = _rng.Next();
            }
            _xnext = _rng.Next();
        }

        public int next() {
            var x = _xnext; // store return value

            var j  = _xnext % _table.Length; // form the index j into the table
            _xnext = _table[j];              // get jth element of table and to copy it to the output stream on next call
            _table[j] = _rng.Next();         // replace jth element of table with next random value from input stream

            return x; // return what was stored in next value
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var rng = new BaysDurhamRNG (16, 12345);

            for(int k = 0; k != 30; ++k) {
                var x = rng.next();
                Console.WriteLine($"RV = {x}");
            }
        }
    }
}


问:
Using oracle db through ssh tunnel. Error "ORA-12541: TNS:no listener"
Hello I've got a problem accessing Oracle DB from our datacenter through a tunnel.

We've got a pretty standard datacenter with one machine being accessible from the outside
(I put it's IP in the /etc/hosts file as dc) and the Oracle DB inside. The IP address of our oracle database on internal network is 192.168.1.7

To create a tunnel I'm using the command:

```<code> ssh -L 1521:192.168.1.7:1521 root@dc
</code>```

and of course it works (sometimes I also add some debug -vv to see if anything is passing through).

Now the difficult part - connecting to Oracle. I installed instantclient 11.2. and my tnsnames.ora looks like that:

```<code>testdb =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = dbname)
    )
  )
</code>```

And when I try to connect using the command:

```<code>./sqlplus username/pass@testdb
</code>```

It starts connecting through the tunnel (I see it in the ssh debug) but then it fails
telling:

```<code>./sqlplus username/pass@testdb

SQL*Plus: Release 11.2.0.1.0 Production on Wed Jan 13 20:46:07 2010

Copyright (c) 1982, 2009, Oracle.  All rights reserved.

ERROR:
ORA-12541: TNS:no listener

Enter user-name:
</code>```

When I'm trying to execute this same command on when I'm on the intranet it works (obviously the only difference is that in the tnsnames.ora HOST we have 192.168.1.7 and not the localhost).

I also tried to use the simple command line:

```<code>./sqlplus username/pass@//localhost:1521/testdb
</code>```

or alternatively

```<code>./sqlplus username/pass@//localhost:1521/testdb
</code>```

But nothing helped :)

I would appreciate any help or suggestions. Am I missing some ssh flag to make it possible?

Probably the log file:

```<code>***********************************************************************

Fatal NI connect error 12541, connecting to:
 (DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=DBNAME)(CID=(PROGRAM=sqlplus@velvet)(HOST=velvet)(USER=johndoe))))

  VERSION INFORMATION:
    TNS for Linux: Version 11.2.0.1.0 - Production
    TCP/IP NT Protocol Adapter for Linux: Version 11.2.0.1.0 - Production
  Time: 13-JAN-2010 20:48:42
  Tracing not turned on.
  Tns error struct:
    ns main err code: 12541

TNS-12541: Message 12541 not found; No message file for product=network, facility=TNS
    ns secondary err code: 12560
    nt main err code: 511

TNS-00511: Message 511 not found; No message file for product=network, facility=TNS
    nt secondary err code: 111
    nt OS err code: 0
</code>```

where velvet is my local hostname and johndoe is my local username.
Why is it sent to the other side?

UPDATE:

After investigating a little bit more from inside datacenter and  it looks like:
- the first connection is going to the port 1521
- but then sqlplus is redirected to the port number > 3300, which is different everytime and incrementing by 3 (at least few tries I had)
- when we are trying to connect trough a tunnel sqlplus will try to connect to localhost and it will obviously fail

So the error "No Listener" comes probably from the fact that we are not redirecting those ports. Is there any way (probably some option in tnsnames.ora file) to force some specific port to be used?

答:
Normally this should work. I would not use a default listener port as an entry for the ssh tunnel but that should not be the problem. I would also not user the root account to create the ssh connection, preferably a dedicated regular account. Are you using shared servers or does the database happen to be a RAC database with a load balance configuration?
A nice explanation is here How can I connect to ORACLE DB through ssh tunnel chain (double tunnel, server in company network) ?, a bit more complicated .....

update
checkout DbVisualizer, it now has integrated ssh tunneling. I think it is worth to al least give it a try. It's not free but good. Multi platform and multi database and very flexible.

ContentLicense: CC BY-SA 2.5

Body:
Hello I've got a problem accessing Oracle DB from our datacenter through a tunnel.

We've got a pretty standard datacenter with one machine being accessible from the outside
(I put it's IP in the /etc/hosts file as dc) and the Oracle DB inside. The IP address of our oracle database on internal network is 192.168.1.7

To create a tunnel I'm using the command:

 ssh -L 1521:192.168.1.7:1521 root@dc

and of course it works (sometimes I also add some debug -vv to see if anything is passing through).

Now the difficult part - connecting to Oracle. I installed instantclient 11.2. and my tnsnames.ora looks like that:

testdb =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = dbname)
    )
  )

And when I try to connect using the command:

./sqlplus username/pass@testdb

It starts connecting through the tunnel (I see it in the ssh debug) but then it fails
telling:

./sqlplus username/pass@testdb

SQL*Plus: Release 11.2.0.1.0 Production on Wed Jan 13 20:46:07 2010

Copyright (c) 1982, 2009, Oracle.  All rights reserved.

ERROR:
ORA-12541: TNS:no listener

Enter user-name:

When I'm trying to execute this same command on when I'm on the intranet it works (obviously the only difference is that in the tnsnames.ora HOST we have 192.168.1.7 and not the localhost).

I also tried to use the simple command line:

./sqlplus username/pass@//localhost:1521/testdb

or alternatively

./sqlplus username/pass@//localhost:1521/testdb

But nothing helped :)

I would appreciate any help or suggestions. Am I missing some ssh flag to make it possible?

Probably the log file:

***********************************************************************

Fatal NI connect error 12541, connecting to:
 (DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=DBNAME)(CID=(PROGRAM=sqlplus@velvet)(HOST=velvet)(USER=johndoe))))

  VERSION INFORMATION:
    TNS for Linux: Version 11.2.0.1.0 - Production
    TCP/IP NT Protocol Adapter for Linux: Version 11.2.0.1.0 - Production
  Time: 13-JAN-2010 20:48:42
  Tracing not turned on.
  Tns error struct:
    ns main err code: 12541

TNS-12541: Message 12541 not found; No message file for product=network, facility=TNS
    ns secondary err code: 12560
    nt main err code: 511

TNS-00511: Message 511 not found; No message file for product=network, facility=TNS
    nt secondary err code: 111
    nt OS err code: 0

where velvet is my local hostname and johndoe is my local username.
Why is it sent to the other side?

UPDATE:

After investigating a little bit more from inside datacenter and  it looks like:
- the first connection is going to the port 1521
- but then sqlplus is redirected to the port number > 3300, which is different everytime and incrementing by 3 (at least few tries I had)
- when we are trying to connect trough a tunnel sqlplus will try to connect to localhost and it will obviously fail

So the error "No Listener" comes probably from the fact that we are not redirecting those ports. Is there any way (probably some option in tnsnames.ora file) to force some specific port to be used?

ContentLicense: CC BY-SA 3.0


问:
How can I insert mutiple items in a DynamoDB table and wait if it exceeds maximum capacity?
I have a json file with about 700 items I need to insert in a DynamoDB table. I'm currently using transactWrite but it's taking too long to insert all those items. How can I use batchWrite and if exceeds 25 items then wait and run the function again until all items are inserted?</p>

```<code>data.forEach(async item => {
    const params = {
      TransactItems: [
        {
          Put: {
            Item: {
              pk: `User_${id}`,
              sk: 'v0_User_Info',
              val: item.User,
              editTimeStamp: `${+new Date()}`,
              latest: 1,
            },
            TableName: 'ddb-table',
          },
        },
        {
          Put: {
            Item: {
              pk: `User_${id}`,
              sk: 'v1_User_Info',
              user: item.User,
              editTimeStamp: `${+new Date()}`,
            },
            TableName: 'ddb-table',
          },
        },
      ],
    };
     await docClient.transactWrite(params).promise()
     .then(response => console.log(response))
     .catch(err => console.table(err))
  })
};
</code>```

答:
batchWriteItem returns a field called UnprocessedItems which contains which items couldn't be processed and should be retried.  If this list is empty, then everything was written successfully.  UnprocessedItems is the exact same format as the batch request so you should be able to directly pass it to a new batch request.

For some sample code on looping and retrying the UnprocessedItems, check out this answer to a similar question.

Body:
I have a json file with about 700 items I need to insert in a DynamoDB table. I'm currently using transactWrite but it's taking too long to insert all those items. How can I use batchWrite and if exceeds 25 items then wait and run the function again until all items are inserted?

data.forEach(async item => {
    const params = {
      TransactItems: [
        {
          Put: {
            Item: {
              pk: `User_${id}`,
              sk: 'v0_User_Info',
              val: item.User,
              editTimeStamp: `${+new Date()}`,
              latest: 1,
            },
            TableName: 'ddb-table',
          },
        },
        {
          Put: {
            Item: {
              pk: `User_${id}`,
              sk: 'v1_User_Info',
              user: item.User,
              editTimeStamp: `${+new Date()}`,
            },
            TableName: 'ddb-table',
          },
        },
      ],
    };
     await docClient.transactWrite(params).promise()
     .then(response => console.log(response))
     .catch(err => console.table(err))
  })
};


问:
unable to get the address of the element in the list by variant
I was trying to loop a list and getting the address of the element.
But all of the element's address is the same when using variant class.

```<code>int main()
{
    std::list<std::variant<std::list<int>, std::list<std::string>>> list_of_lists;
    std::list<int> int_list = {1, 2, 3};
    string a1 ="one";
    std::list<std::string> string_list = {a1, "two", "three"};

    list_of_lists.push_back(int_list);
    list_of_lists.push_back(string_list);

    // Iterate over all std::variant elements.
    for (const auto& v : list_of_lists) {
        // Check if the variant holds a list of ints.
        if (std::holds_alternative<std::list<int>>(v)) {
            // 'v' holds a list of ints.
            for (auto i : std::get<std::list<int>>(v)) {
                std::cout << i << ' ';
                cout<<&i<<endl;
            }
            std::cout << '\n';
        }
            // Check if the variant holds a list of strings.
        else if (std::holds_alternative<std::list<std::string>>(v)) {
            // 'v' holds a list of strings.
            for (const auto& s : std::get<std::list<std::string>>(v)) {
                std::cout << s << ' ';
                cout<<"string: "<<&std::get<std::list<std::string>>(v)<<endl;
                cout<<&s<<endl;
            }
            std::cout << '\n';
        }
    }
    cout<<"a1 address: "<<&a1<<endl;
}
output:
1 0x8dfcac
2 0x8dfcac
3 0x8dfcac

one string: 0x8f2890
0x8f27d0
two string: 0x8f2890
0x8f2810
three string: 0x8f2890
0x8f2850

a1 address: 0x8dfcc0
</code>```

As you ## Heading ##

It looks like the variant std library cannot get the original variable's own address. Thus, every time I try to loop through the linked list, all the address of elements in the mother list are changed. Thus, I can only display and I can not push back for those linked lists in the mother linked list. One of my friends told me c++ is all about pointer and he hates Java because it does have pointer! And now I can not use a pointer in c++ with this library. I have heard this problem can be solved by boot:: variant, std:: optional or polymorphism. But I have no idea how these work. Anyway, some people said the reason this library does not touch the address idea is because they have a disagreement about how what assignment

答:
For the int loop, you created a local variable and take its address.

```<code>for (auto i : std::get<std::list<int>>(v))  // local variable, same address each time
</code>```

should be

```<code>for (auto& i : std::get<std::list<int>>(v)) // reference, refers to the actual element
</code>```

This has nothing to do with variants.

For the string loop, you already use a reference.

```<code>for (const auto& s : std::get<std::list<std::string>>(v)) // reference
</code>```

That's why things work as expected.

Body:
I was trying to loop a list and getting the address of the element.
But all of the element's address is the same when using variant class.

int main()
{
    std::list<std::variant<std::list<int>, std::list<std::string>>> list_of_lists;
    std::list<int> int_list = {1, 2, 3};
    string a1 ="one";
    std::list<std::string> string_list = {a1, "two", "three"};

    list_of_lists.push_back(int_list);
    list_of_lists.push_back(string_list);

    // Iterate over all std::variant elements.
    for (const auto& v : list_of_lists) {
        // Check if the variant holds a list of ints.
        if (std::holds_alternative<std::list<int>>(v)) {
            // 'v' holds a list of ints.
            for (auto i : std::get<std::list<int>>(v)) {
                std::cout << i << ' ';
                cout<<&i<<endl;
            }
            std::cout << '\n';
        }
            // Check if the variant holds a list of strings.
        else if (std::holds_alternative<std::list<std::string>>(v)) {
            // 'v' holds a list of strings.
            for (const auto& s : std::get<std::list<std::string>>(v)) {
                std::cout << s << ' ';
                cout<<"string: "<<&std::get<std::list<std::string>>(v)<<endl;
                cout<<&s<<endl;
            }
            std::cout << '\n';
        }
    }
    cout<<"a1 address: "<<&a1<<endl;
}
output:
1 0x8dfcac
2 0x8dfcac
3 0x8dfcac

one string: 0x8f2890
0x8f27d0
two string: 0x8f2890
0x8f2810
three string: 0x8f2890
0x8f2850

a1 address: 0x8dfcc0

As you ## Heading ##

It looks like the variant std library cannot get the original variable's own address. Thus, every time I try to loop through the linked list, all the address of elements in the mother list are changed. Thus, I can only display and I can not push back for those linked lists in the mother linked list. One of my friends told me c++ is all about pointer and he hates Java because it does have pointer! And now I can not use a pointer in c++ with this library. I have heard this problem can be solved by boot:: variant, std:: optional or polymorphism. But I have no idea how these work. Anyway, some people said the reason this library does not touch the address idea is because they have a disagreement about how what assignment

Body:
For the int loop, you created a local variable and take its address.

for (auto i : std::get<std::list<int>>(v))  // local variable, same address each time

should be

for (auto& i : std::get<std::list<int>>(v)) // reference, refers to the actual element

This has nothing to do with variants.

For the string loop, you already use a reference.

for (const auto& s : std::get<std::list<std::string>>(v)) // reference

That's why things work as expected.


问:
Copying to arrays in NASM
I have to write in assembly code which copy 100 bytes in memory in loop. I wrote it like this:

```<code>section .data
    a times 100 db 1 ;reserve 100 bytes and fill with 1
    b times 100 db 0 ;reserve 100 bytes and fill with 0

    section _start
    global _start

    _start:
    mov rsi, a ;get array a address
    mov rdi, b ;get arrat b address

    _for: ;początek pętli
    cmp cx, 100     ;loop
    jae _end_for        ;loop
    push cx         ;loop

    mov byte al, [rsi]  ;get one byte from array a from al
    mov byte [rdi], al  ;put one byte from al to array b
    inc rsi         ;set rsi to next byte in array a
    inc rdi         ;set rdi to next byte in array b

    pop cx          ;loop
    inc cx          ;loop
    jmp _for        ;loop

_end_for:

_end:
    mov rax, 60
    mov rdi, 0
    syscall
</code>```

I'm not sure about the copying part. I read the value from the address to the register and then put it into another. That looks good to me, but I'm not sure about incrementing rsi and rdi.

Is it really enough?

I'm new to NASM and assembly, so please help :-)

答:
I know about rep movsb but task has been to make it in loop byte after byte,  I don't know if it could be done better way.

If you have to loop 1 byte at a time, here's how to do that efficiently.  It's worth mentioning because looping efficiently is useful for cases other than memcpy as well!

First of all, you know that your loop body should run at least once, so you can use a normal loop structure with a conditional branch at the bottom.  (Why are loops always compiled into "do...while" style (tail jump)?)

Second, if you're not going to unroll at all then you should use an indexed addressing mode to avoid having to increment both pointers.  (But really it would be better to unroll).

And don't use 16-bit registers if you don't have to.  Prefer 32-bit operand-size (ECX); writing a 32-bit register implicitly zero-extends to 64-bit so it's safe to use an index as part of an addressing mode.

You can use an indexed load but a non-indexed store so your store-address uops can still run on port7, making this slightly more hyperthreading-friendly on Haswell/Skylake.  And avoiding un-lamination on Sandybridge.  Obviously copying 1 byte at a time is total garbage for performance, but sometimes you do want to loop and actually do something with each byte while it's in a register, and you can't manually vectorize it with SSE2 (to do 16 bytes at a time).

You can do this by indexing the src relative to the dst.

Or the other trick is to count a negative index up towards zero, so you avoid an extra cmp.  Lets do that first:

```<code>default rel       ; use RIP-relative addressing modes by default

ARR_SIZE  equ 100
section .data
    a:  times ARR_SIZE db 1

section .bss
    b:  resb ARR_SIZE       ;reserve n bytes of space in the BSS

    ;section _start   ; do *not* use custom section names unless you have a good reason
                      ; they might get linked with unexpected read/write/exec permission

section .text
global _start
_start:
    lea     rsi, [a+ARR_SIZE]   ; pointers to one-past-the-end of the arrays
    lea     rdi, [b+ARR_SIZE]   ; RIP-relative LEA is better than mov r64, imm64

    mov     rcx, -ARR_SIZE

.copy_loop:                 ; do {
    movzx   eax, byte [rsi+rcx]  ; load without a false dependency on the old value of RAX
    mov     [rdi+rcx], al
    inc     rcx
    jnz    .copy_loop       ; }while(++idx != 0);

.end:
    mov  eax, 60
    xor  edi, edi
    syscall             ; sys_exit(0)
</code>```

In position-dependent code like a static (or other non-PIE) Linux executable, mov   edi, b+ARR_SIZE is the most efficient way to put a static address into a register.

Don't use _ for all your label names.  _start is named that way because C symbol names that begin with _ are reserved for use by the implementation.  It's not something you should copy; in fact the opposite is true.

Use .foo for a local label name inside a function.  e.g. .foo: is shorthand for _start.foo: if you use it after _start.

Indexing src relative to dst:

Normally your input and output aren't both in static storage, so you have to sub the addresses at runtime.  Here, if we put them both in the same section like you were originally doing, mov rcx, a-b will actually assemble.  But if not, NASM refuses.

In fact instead of a 2-register addressing mode, I could just be doing [rdi + (a-b)], or simply [rdi - ARR_SIZE] because I know they're contiguous.

```<code>_start:
    lea     rdi, [b]   ; RIP-relative LEA is better than mov r64, imm64
    mov     rcx, a-b   ; distance between arrays so  [rdi+rcx] = [a]
;;; for a-b to assemble, I had to move b back to the .data section.

    lea     rdx, [rdi+ARR_SIZE]    ; end_dst pointer

.copy_loop:                 ; do {
    movzx   eax, byte [rdi + rcx]    ; src = dst+(src-dst)
    mov     [rdi], al
    inc     rdi

    cmp     rdi, rdx
    jbe    .copy_loop       ; }while(dst < end_dst);
</code>```

An end-of-the-array pointer is exactly like you'd do in C++ with foo.end() to get a pointer / iterator to one-past-the-end.

This needs INC + CMP/JCC as loop overhead.  On AMD CPUs, CMP/JCC can macro-fuse into 1 uop but INC/JCC can't, so the extra CMP vs. indexing from the end is basically free.  (Except for code-size).

On Intel this avoids an indexed store.  The load is a pure load in this case, so it's a single uop anyway without needing to stay micro-fused with an ALU uop.  Intel can macro-fuse inc/jcc so this does cost an extra uop of loop overhead.

This way of looping is good if you're unrolling, if you don't need to avoid an indexed addressing mode for loads.  But if you're using a memory source for an ALU instruction like vaddps  ymm0, ymm1, [rdi], then yes you should increment both pointers separately so you can use non-indexed addressing modes for both loads and stores, because Intel CPUs are more efficient that way.  (Port 7 store AGU handles non-indexed only, and some micro-fused loads unlaminate with indexed addressing mode.  Micro fusion and addressing modes)

Title: Copying to arrays in NASM

Body:
I have to write in assembly code which copy 100 bytes in memory in loop. I wrote it like this:

section .data
    a times 100 db 1 ;reserve 100 bytes and fill with 1
    b times 100 db 0 ;reserve 100 bytes and fill with 0

    section _start
    global _start

    _start:
    mov rsi, a ;get array a address
    mov rdi, b ;get arrat b address

    _for: ;początek pętli
    cmp cx, 100     ;loop
    jae _end_for        ;loop
    push cx         ;loop

    mov byte al, [rsi]  ;get one byte from array a from al
    mov byte [rdi], al  ;put one byte from al to array b
    inc rsi         ;set rsi to next byte in array a
    inc rdi         ;set rdi to next byte in array b

    pop cx          ;loop
    inc cx          ;loop
    jmp _for        ;loop

_end_for:

_end:
    mov rax, 60
    mov rdi, 0
    syscall

I'm not sure about the copying part. I read the value from the address to the register and then put it into another. That looks good to me, but I'm not sure about incrementing rsi and rdi.

Is it really enough?

I'm new to NASM and assembly, so please help :-)

Body:
I know about rep movsb but task has been to make it in loop byte after byte,  I don't know if it could be done better way.

If you have to loop 1 byte at a time, here's how to do that efficiently.  It's worth mentioning because looping efficiently is useful for cases other than memcpy as well!

First of all, you know that your loop body should run at least once, so you can use a normal loop structure with a conditional branch at the bottom.  (Why are loops always compiled into "do...while" style (tail jump)?)

Second, if you're not going to unroll at all then you should use an indexed addressing mode to avoid having to increment both pointers.  (But really it would be better to unroll).

And don't use 16-bit registers if you don't have to.  Prefer 32-bit operand-size (ECX); writing a 32-bit register implicitly zero-extends to 64-bit so it's safe to use an index as part of an addressing mode.

You can use an indexed load but a non-indexed store so your store-address uops can still run on port7, making this slightly more hyperthreading-friendly on Haswell/Skylake.  And avoiding un-lamination on Sandybridge.  Obviously copying 1 byte at a time is total garbage for performance, but sometimes you do want to loop and actually do something with each byte while it's in a register, and you can't manually vectorize it with SSE2 (to do 16 bytes at a time).

You can do this by indexing the src relative to the dst.

Or the other trick is to count a negative index up towards zero, so you avoid an extra cmp.  Lets do that first:

default rel       ; use RIP-relative addressing modes by default

ARR_SIZE  equ 100
section .data
    a:  times ARR_SIZE db 1

section .bss
    b:  resb ARR_SIZE       ;reserve n bytes of space in the BSS

    ;section _start   ; do *not* use custom section names unless you have a good reason
                      ; they might get linked with unexpected read/write/exec permission

section .text
global _start
_start:
    lea     rsi, [a+ARR_SIZE]   ; pointers to one-past-the-end of the arrays
    lea     rdi, [b+ARR_SIZE]   ; RIP-relative LEA is better than mov r64, imm64

    mov     rcx, -ARR_SIZE

.copy_loop:                 ; do {
    movzx   eax, byte [rsi+rcx]  ; load without a false dependency on the old value of RAX
    mov     [rdi+rcx], al
    inc     rcx
    jnz    .copy_loop       ; }while(++idx != 0);

.end:
    mov  eax, 60
    xor  edi, edi
    syscall             ; sys_exit(0)

In position-dependent code like a static (or other non-PIE) Linux executable, mov   edi, b+ARR_SIZE is the most efficient way to put a static address into a register.

Don't use _ for all your label names.  _start is named that way because C symbol names that begin with _ are reserved for use by the implementation.  It's not something you should copy; in fact the opposite is true.

Use .foo for a local label name inside a function.  e.g. .foo: is shorthand for _start.foo: if you use it after _start.

Indexing src relative to dst:

Normally your input and output aren't both in static storage, so you have to sub the addresses at runtime.  Here, if we put them both in the same section like you were originally doing, mov rcx, a-b will actually assemble.  But if not, NASM refuses.

In fact instead of a 2-register addressing mode, I could just be doing [rdi + (a-b)], or simply [rdi - ARR_SIZE] because I know they're contiguous.

_start:
    lea     rdi, [b]   ; RIP-relative LEA is better than mov r64, imm64
    mov     rcx, a-b   ; distance between arrays so  [rdi+rcx] = [a]
;;; for a-b to assemble, I had to move b back to the .data section.

    lea     rdx, [rdi+ARR_SIZE]    ; end_dst pointer

.copy_loop:                 ; do {
    movzx   eax, byte [rdi + rcx]    ; src = dst+(src-dst)
    mov     [rdi], al
    inc     rdi

    cmp     rdi, rdx
    jbe    .copy_loop       ; }while(dst < end_dst);

An end-of-the-array pointer is exactly like you'd do in C++ with foo.end() to get a pointer / iterator to one-past-the-end.

This needs INC + CMP/JCC as loop overhead.  On AMD CPUs, CMP/JCC can macro-fuse into 1 uop but INC/JCC can't, so the extra CMP vs. indexing from the end is basically free.  (Except for code-size).

On Intel this avoids an indexed store.  The load is a pure load in this case, so it's a single uop anyway without needing to stay micro-fused with an ALU uop.  Intel can macro-fuse inc/jcc so this does cost an extra uop of loop overhead.

This way of looping is good if you're unrolling, if you don't need to avoid an indexed addressing mode for loads.  But if you're using a memory source for an ALU instruction like vaddps  ymm0, ymm1, [rdi], then yes you should increment both pointers separately so you can use non-indexed addressing modes for both loads and stores, because Intel CPUs are more efficient that way.  (Port 7 store AGU handles non-indexed only, and some micro-fused loads unlaminate with indexed addressing mode.  Micro fusion and addressing modes)


问:
Getting n most recent emails using IMAP and Python
I'm looking to return the n (most likely 10) most recent emails from an email accounts inbox using IMAP.

So far I've cobbled together:

```<code>import imaplib
from email.parser import HeaderParser

M = imaplib.IMAP4_SSL('my.server')
user = 'username'
password = 'password'
M.login(user, password)
M.search(None, 'ALL')
for i in range (1,10):
    data = M.fetch(i, '(BODY[HEADER])')
    header_data = data[1][0][1]
    parser = HeaderParser()
    msg = parser.parsestr(header_data)
    print msg['subject']
</code>```

This is returning email headers fine, but it seems to be a semi-random collection of emails that it gets, not the 10 most recent.

If it helps, I'm connecting to an Exchange 2010 server. Other approaches also welcome, IMAP just seemed the most appropriate given that I only wanted to read the emails not send any.

答:
The sort command is available, but it is not guaranteed to be supported by the IMAP server. For example, Gmail does not support the SORT command.

To try the sort command, you would replace:

M.search(None, 'ALL')

with

M.sort(search_critera, 'UTF-8', 'ALL')

Then search_criteria would be a string like:

```<code>search_criteria = 'DATE' #Ascending, most recent email last
search_criteria = 'REVERSE DATE' #Descending, most recent email first

search_criteria = '[REVERSE] sort-key' #format for sorting
</code>```

According to RFC5256 these are valid sort-key's:

"ARRIVAL" / "CC" / "DATE" / "FROM" / "SIZE" / "SUBJECT" / "TO"

Notes:

1. charset is required, try US-ASCII or UTF-8 all others are not required to be supported by the IMAP server

2. search critera is also required. The ALL command is a valid one, but there are many. See more at http://www.networksorcery.com/enp/rfc/rfc3501.txt

The world of IMAP is wild and crazy. Good luck

Body:
I'm looking to return the n (most likely 10) most recent emails from an email accounts inbox using IMAP.

So far I've cobbled together:

import imaplib
from email.parser import HeaderParser

M = imaplib.IMAP4_SSL('my.server')
user = 'username'
password = 'password'
M.login(user, password)
M.search(None, 'ALL')
for i in range (1,10):
    data = M.fetch(i, '(BODY[HEADER])')
    header_data = data[1][0][1]
    parser = HeaderParser()
    msg = parser.parsestr(header_data)
    print msg['subject']

This is returning email headers fine, but it seems to be a semi-random collection of emails that it gets, not the 10 most recent.

If it helps, I'm connecting to an Exchange 2010 server. Other approaches also welcome, IMAP just seemed the most appropriate given that I only wanted to read the emails not send any.

Body:
The sort command is available, but it is not guaranteed to be supported by the IMAP server. For example, Gmail does not support the SORT command.

To try the sort command, you would replace:

M.search(None, 'ALL')

with

M.sort(search_critera, 'UTF-8', 'ALL')

Then search_criteria would be a string like:

search_criteria = 'DATE' #Ascending, most recent email last
search_criteria = 'REVERSE DATE' #Descending, most recent email first

search_criteria = '[REVERSE] sort-key' #format for sorting

According to RFC5256 these are valid sort-key's:

"ARRIVAL" / "CC" / "DATE" / "FROM" / "SIZE" / "SUBJECT" / "TO"

Notes:

1. charset is required, try US-ASCII or UTF-8 all others are not required to be supported by the IMAP server

2. search critera is also required. The ALL command is a valid one, but there are many. See more at http://www.networksorcery.com/enp/rfc/rfc3501.txt

The world of IMAP is wild and crazy. Good luck


问:
Flutter Unable to create directory (OS Error: Read-only file system)
I was following - how to create directory from https://docs.flutter.io/flutter/dart-io/Directory-class.html

```<code>new Directory('dir/subdir').create(recursive: true)
  // The created directory is returned as a Future.
  .then((Directory directory) {
    print(directory.path);
});
</code>```

This is the error I am getting:

FileSystemException: Creation failed, path = 'dir' (OS Error: Read-only file system, errno = 30)

I have enabled Storage(WRITE_EXTERNAL_STORAGE) permission.
(Android device)

What am I missing?

答:
Update : New Flutter plugin permission_handler have taken care below thing so change your plugin to permission_handler

If you are testing in Android Oreo and want to write file in external storage then you need to ask WRITE_EXTERNAL_STORAGE

According to "https://developer.android.com/about/versions/oreo/android-8.0-changes.html#rmp"

If the app targets Android 8.0 (API level 26), the system grants only
  READ_EXTERNAL_STORAGE at that time; however, if the app later requests
  WRITE_EXTERNAL_STORAGE, the system immediately grants that privilege
  without prompting the user.

Permission Plugin ask only READ_EXTERNAL_STORAGE permission by Permission.requestPermissions([PermissionName.Storage]);
so You need to ask for WRITE_EXTERNAL_STORAGE.

You can use my repo for asking WRITE_EXTERNAL_STORAGE in pubspec.yaml:

```<code>permission:
    git:
    url: https://github.com/kamlesh9070/permission
</code>```

Body:
I was following - how to create directory from https://docs.flutter.io/flutter/dart-io/Directory-class.html

new Directory('dir/subdir').create(recursive: true)
  // The created directory is returned as a Future.
  .then((Directory directory) {
    print(directory.path);
});

This is the error I am getting:

FileSystemException: Creation failed, path = 'dir' (OS Error: Read-only file system, errno = 30)

I have enabled Storage(WRITE_EXTERNAL_STORAGE) permission.
(Android device)

What am I missing?

Body:
Update : New Flutter plugin permission_handler have taken care below thing so change your plugin to permission_handler

If you are testing in Android Oreo and want to write file in external storage then you need to ask WRITE_EXTERNAL_STORAGE

According to "https://developer.android.com/about/versions/oreo/android-8.0-changes.html#rmp"

If the app targets Android 8.0 (API level 26), the system grants only
  READ_EXTERNAL_STORAGE at that time; however, if the app later requests
  WRITE_EXTERNAL_STORAGE, the system immediately grants that privilege
  without prompting the user.

Permission Plugin ask only READ_EXTERNAL_STORAGE permission by Permission.requestPermissions([PermissionName.Storage]);
so You need to ask for WRITE_EXTERNAL_STORAGE.

You can use my repo for asking WRITE_EXTERNAL_STORAGE in pubspec.yaml:

permission:
    git:
    url: https://github.com/kamlesh9070/permission


问:
Sublime Syntax Match First Line of the File
I'm trying to match just the first line of a file with sublime 3 syntax highlighting assuming it does not feature a leading number.

```<code>    <dict>
        <key>comment</key>
        <string>Matchs the first line comment</string>
        <key>match</key>
        <string>\A^[^0-9].*</string>
        <key>name</key>
        <string>comment</string>
    </dict>
</code>```

The expression works with ctrl-f but will highlight the entire document when used in the syntax file.

答:
first of all, use the yaml variant so you can see what you're doing lol.

answer: have main be your first line mode. as soon as you see the end of any line, switch to another mode for everything else. never set back to main - other lines mode is your god now. pushing and popping should work as expected since we use set instead of push (so main is not even on the stack any more).

```<code> main: # aka first line mode
  - match: '$'
    set: other.lines
  - match: '.*'
    scope: first.line

 other.lines:
  - match: '.*'
    scope: every.other.line
</code>```

as for the number bit, you can just add that into your $ match as an alternative first line deal breaker regex

```<code>  - match: '^\d|$'
    set: other.lines
</code>```

for bonus points, if you only want to match certain formats of the first line, just have all of them set after you scope, and then add the $ rule as well. if you want to ignore whitespace up until that point, you'll need to set as soon as you peek ahead and see an invalid first line, and when you do set to the normal body matcher. like say you wanted to highlight a first line only if that first line says foo, foobar, or foobaz. maybe something like...

```<code> main:
  - match: 'foo(bar|baz)?'
    scope: valid.first.line
    set: other.lines # done with the first line
  - match: '(?=^\s*\S)'
    set: other.lines # looked ahead, saw non blank line, wasnt valid first line
</code>```

Body:
I'm trying to match just the first line of a file with sublime 3 syntax highlighting assuming it does not feature a leading number.

    <dict>
        <key>comment</key>
        <string>Matchs the first line comment</string>
        <key>match</key>
        <string>\A^[^0-9].*</string>
        <key>name</key>
        <string>comment</string>
    </dict>

The expression works with ctrl-f but will highlight the entire document when used in the syntax file.

Body:
first of all, use the yaml variant so you can see what you're doing lol.

answer: have main be your first line mode. as soon as you see the end of any line, switch to another mode for everything else. never set back to main - other lines mode is your god now. pushing and popping should work as expected since we use set instead of push (so main is not even on the stack any more).

 main: # aka first line mode
  - match: '$'
    set: other.lines
  - match: '.*'
    scope: first.line

 other.lines:
  - match: '.*'
    scope: every.other.line

as for the number bit, you can just add that into your $ match as an alternative first line deal breaker regex

  - match: '^\d|$'
    set: other.lines

for bonus points, if you only want to match certain formats of the first line, just have all of them set after you scope, and then add the $ rule as well. if you want to ignore whitespace up until that point, you'll need to set as soon as you peek ahead and see an invalid first line, and when you do set to the normal body matcher. like say you wanted to highlight a first line only if that first line says foo, foobar, or foobaz. maybe something like...

 main:
  - match: 'foo(bar|baz)?'
    scope: valid.first.line
    set: other.lines # done with the first line
  - match: '(?=^\s*\S)'
    set: other.lines # looked ahead, saw non blank line, wasnt valid first line


问:
Inserting empty values as string to sql table
I have a project which has a Class which has some members as string which equal "". My teacher had shown examples with Class members declared as String = "NULL". I try to insert to SQL and I get this message:

Error insertion... Error converting data type varchar to numeric.

I know many will suggest to use parameterized values for inserting but I like to finish the way I started this.

I have tried to cast query string Object values with CDec, CInt, Cbit and still no clue how to do it right because I got Exceptions for trying to cast an "".

Also, I have changed to default values of members like this;

Dim NumberOfPackage As String = ""
```

<p>instead of;</p>

<pre class="lang-vb prettyprint-override"><code>Dim NumberOfPackage As String = "NULL"
</code>```

Some Columns in SQL table had ALLOW NULL checkBox set to NOT allowed, I changed the design of the Table to make it easier for insertion.

答:
col1 in my Builder database is datatype int and nulls are allowed. This is how it is done with Parameters. TextBox1 will hold the number of packages and TextBox2 the name. I used the object datatype so it could hold either DBNull.Value or an Integer.</p>

```<code>Private Sub InsertRecord()
    Dim myValue As Object
    Dim myInt As Integer
    If Integer.TryParse(TextBox1.Text, myInt) Then
        myValue = myInt
    Else
        myValue = DBNull.Value
    End If

    Using cn As New SqlConnection(My.Settings.BuildersConnectio)
        Using cmd As New SqlCommand("Insert Into Builders (BuilderName, col1) VALUES (@Name, @NoOfPackages);", cn)
            cmd.Parameters.Add("@Name", SqlDbType.VarChar, 100).Value = TextBox2.Text
            cmd.Parameters.Add("NoOfPackages", SqlDbType.Int).Value = myValue
            cn.Open()
            cmd.ExecuteNonQuery()
        End Using
    End Using
End Sub
</code>```

Body:
I have a project which has a Class which has some members as string which equal "". My teacher had shown examples with Class members declared as String = "NULL". I try to insert to SQL and I get this message:

Error insertion... Error converting data type varchar to numeric.

I know many will suggest to use parameterized values for inserting but I like to finish the way I started this.

I have tried to cast query string Object values with CDec, CInt, Cbit and still no clue how to do it right because I got Exceptions for trying to cast an "".

Also, I have changed to default values of members like this;

Dim NumberOfPackage As String = ""

instead of;

Dim NumberOfPackage As String = "NULL"

Some Columns in SQL table had ALLOW NULL checkBox set to NOT allowed, I changed the design of the Table to make it easier for insertion.

Body:
col1 in my Builder database is datatype int and nulls are allowed. This is how it is done with Parameters. TextBox1 will hold the number of packages and TextBox2 the name. I used the object datatype so it could hold either DBNull.Value or an Integer.

Private Sub InsertRecord()
    Dim myValue As Object
    Dim myInt As Integer
    If Integer.TryParse(TextBox1.Text, myInt) Then
        myValue = myInt
    Else
        myValue = DBNull.Value
    End If

    Using cn As New SqlConnection(My.Settings.BuildersConnectio)
        Using cmd As New SqlCommand("Insert Into Builders (BuilderName, col1) VALUES (@Name, @NoOfPackages);", cn)
            cmd.Parameters.Add("@Name", SqlDbType.VarChar, 100).Value = TextBox2.Text
            cmd.Parameters.Add("NoOfPackages", SqlDbType.Int).Value = myValue
            cn.Open()
            cmd.ExecuteNonQuery()
        End Using
    End Using
End Sub


问:
How to spawn a part at the current mouse position in Roblox Lua?
I've been working on a script for Roblox. Here's the code:

```<code>local UIS = game:GetService("UserInputService")
local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
local Activation =
Instance.new("Sound",game.Players.LocalPlayer.Character.Head)
local char = Player.Character
local hum = char.Humanoid
local root = char.HumanoidRootPart

UIS.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.F then
    Activation.SoundId = "rbxassetid://1581091676" --Plays Mangekyou Sharingan Activation Sound.
    Activation:Play()
    wait(0.3)
    game.Players.LocalPlayer.Character.Head.face.Texture = "rbxassetid://76285632" --When F is pressed, face texture changes to sharingan decal.
    game:GetService("Chat"):Chat(Player.Character.Head, "Mangekyou Sharingan!")
end
end)

UIS.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.R then
    Activation.SoundId = "rbxassetid://1580990602" --Plays Amaterasu Activation Sound.
    Activation:Play()
    game:GetService("Chat"):Chat(Player.Character.Head, "Amaterasu!")
    local Target = Instance.new("Part") --makes a part
    Target.Parent = game.Workspace
    Target.Position = Vector3.new(Mouse.target.Position) --makes the part spawn where the mouse is
    Target.Transparency = 1
    Target.Anchored = true
    Target.CanCollide = false

    local Amaterasu = Instance.new("Fire")
    Amaterasu.Parent = game.Workspace.Part
    Amaterasu.Color = Color3.new(0,0,0)
    Amaterasu.SecondaryColor = Color3.new(0,0,0) --amaterasu properties
    Amaterasu.Size = 25

    local R = Instance.new("RocketPropulsion") --rocket propulsion, parents amaterasu
    R.Parent = Amaterasu
    R.MaxThrust = 300
    R.ThrustP = 30
    R:Fire()
end
end)

UIS.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.G then
    game.Players.LocalPlayer.Character.Head.face.Texture = "rbxassetid://22557247" --When G is pressed, face texture changes back to normal.(leaves face blank isnt working :/)
end
end)
-----------------------------
</code>```

What I need help with is spawning a the part that parents the amaterasu fire at the current position of my mouse in game. I have researched and tried both Target.Position = Vector3.new(Mouse.target.Position), and Target.Position = Vector3.new(Mouse.Hit).

These both don't work and the end result is the part spawning in the middle of the baseplate no matter where my mouse's position is in game.

答:
What we need is a CFrame. So we'll do:

```<code>Target.CFrame = CFrame.new(Mouse.target.Position)
</code>```

Body:
I've been working on a script for Roblox. Here's the code:

local UIS = game:GetService("UserInputService")
local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
local Activation =
Instance.new("Sound",game.Players.LocalPlayer.Character.Head)
local char = Player.Character
local hum = char.Humanoid
local root = char.HumanoidRootPart

UIS.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.F then
    Activation.SoundId = "rbxassetid://1581091676" --Plays Mangekyou Sharingan Activation Sound.
    Activation:Play()
    wait(0.3)
    game.Players.LocalPlayer.Character.Head.face.Texture = "rbxassetid://76285632" --When F is pressed, face texture changes to sharingan decal.
    game:GetService("Chat"):Chat(Player.Character.Head, "Mangekyou Sharingan!")
end
end)

UIS.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.R then
    Activation.SoundId = "rbxassetid://1580990602" --Plays Amaterasu Activation Sound.
    Activation:Play()
    game:GetService("Chat"):Chat(Player.Character.Head, "Amaterasu!")
    local Target = Instance.new("Part") --makes a part
    Target.Parent = game.Workspace
    Target.Position = Vector3.new(Mouse.target.Position) --makes the part spawn where the mouse is
    Target.Transparency = 1
    Target.Anchored = true
    Target.CanCollide = false

    local Amaterasu = Instance.new("Fire")
    Amaterasu.Parent = game.Workspace.Part
    Amaterasu.Color = Color3.new(0,0,0)
    Amaterasu.SecondaryColor = Color3.new(0,0,0) --amaterasu properties
    Amaterasu.Size = 25

    local R = Instance.new("RocketPropulsion") --rocket propulsion, parents amaterasu
    R.Parent = Amaterasu
    R.MaxThrust = 300
    R.ThrustP = 30
    R:Fire()
end
end)

UIS.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.G then
    game.Players.LocalPlayer.Character.Head.face.Texture = "rbxassetid://22557247" --When G is pressed, face texture changes back to normal.(leaves face blank isnt working :/)
end
end)
-----------------------------

What I need help with is spawning a the part that parents the amaterasu fire at the current position of my mouse in game. I have researched and tried both Target.Position = Vector3.new(Mouse.target.Position), and Target.Position = Vector3.new(Mouse.Hit).

These both don't work and the end result is the part spawning in the middle of the baseplate no matter where my mouse's position is in game.

Body:
What we need is a CFrame. So we'll do:

Target.CFrame = CFrame.new(Mouse.target.Position)


问:
Specify percentage instead of time to ffmpeg
To get a thumbnail from an image halfway through the video I can do ffmpeg -ss 100 -i /tmp/video.mp4 -frames:v 1 -s 200x100 image.jpg. By using -ss 100 it gets a thumbnail at 100 seconds (which would be halfway through the video assuming the video is 200 seconds long).

But if I don't know the exact length of the video, in my application code I would need to use something like ffprobe to first determine the length of the video, and then divide it by 2 to get the thumbnail time.

Is there a way to get ffmpeg to get the thumbnail at the percentage of the video you want? So instead of specifying -ss 100, something like -ss 50% or -ss 20% to get a thumbnail from halfway or 20% into the file?

I know I can do this through application code, but it would be more efficient if there's a way for ffmpeg to handle this itself.

答:
It's not pretty but:

ffmpeg -y -i logo-13748357.mp4 -vf "select=gte(n\,$(shuf -i 1-$(ffprobe -v error -select_streams v:0 -show_entries stream=nb_frames -of default=nokey=1:noprint_wrappers=1 logo-13748357.mp4)  -n 1))" -vframes 1 out_img.png

The above command is an example of a one liner that grabs the number of frames in a video and passes that to the "shuf" command https://linux.die.net/man/1/shuf which randomly selects a number in the range of frames and the result of that is passed to ffmpeg.

So the above is able to randomly select a frame from a video with just one line.

You might be able to adapt this approach to your specific goal.  Presuming of course it still matters seven years down the track.