问:
react-native-maps conditional markers
I have a map of markers that renders each marker in an array of coordinates. I am trying to render markers conditionally based on a key I give the marker. You can see exactly how I am trying to do this by looking at my snack example here or I have posted the code below.

Thank you, I appreciate it more than you know.

```<code>export default class Map extends React.Component {
  markers = [];
  state = {
    coordinates: [
      {
        name: '1',
        latitude: 36.212111515965525,
        longitude: -81.67527588876025,
        status: 'busy',
      },
      {
        name: '2',
        latitude: 36.21754431261142,
        longitude: -81.68598350040361,
        status: 'open',
      },
      {
        name: '3',
        latitude: 36.21744712906634,
        longitude: -81.68168562889075,
        status: 'busy',
      },
      {
        name: '4',
        latitude: 36.219352000280495,
        longitude: -81.68559146421954,
        status: 'open',
      },
    ],
  };

  render() {
    return (
      <View style={{ ...StyleSheet.absoluteFillObject }}>
        <MapView
          style={styles.map}
          provider={PROVIDER_GOOGLE}
          showsUserLocation={true}
          showsMyLocationButton={true}
          ref={(map) => (this._map = map)}
          initialRegion={{
            latitude: 36.212111515965525,
            longitude: -81.67527588876025,
            latitudeDelta: 0.05,
            longitudeDelta: 0.05
          }}>
          {this.state.coordinates.map((marker, index) => (
            if(marker.status == 'busy'){
            <Marker
              key={marker.name}
              ref={(ref) => {this.markers[index] = ref;}}
              onPress={() => this.onMarkerPress(marker, index)}
              coordinate={{
                latitude: marker.latitude,
                longitude: marker.longitude,
              }}>
              <Image
                source={require('./assets/blueMarker.png')}
                style={{ height: scale(50), width: scale(50) }}
              />
            </Marker>
            } else {
               <Marker
              key={marker.name}
              ref={(ref) => {this.markers[index] = ref;}}
              onPress={() => this.onMarkerPress(marker, index)}
              coordinate={{
                latitude: marker.latitude,
                longitude: marker.longitude,
              }}>
            </Marker>
            }

          ))}
        </MapView>
      </View>
    );
  }
}

</code>```

答:
You're not using correct JSX syntax. You can't use if-then-else, use ternary operator instead.</p>
```<code>{ this.state.coordinates.map((marker, index) => (
  marker.status == 'busy' ?
  <Marker
    key={marker.name}
    ref={(ref) => {this.markers[index] = ref;}}
    onPress={() => this.onMarkerPress(marker, index)}
    coordinate={{
      latitude: marker.latitude,
      longitude: marker.longitude,
    }}>
    <Image
      source={require('./assets/blueMarker.png')}
      style={{ height: scale(50), width: scale(50) }}
    />
  </Marker>
  :
  <Marker
    key={marker.name}
    ref={(ref) => {this.markers[index] = ref;}}
    onPress={() => this.onMarkerPress(marker, index)}
    coordinate={{
      latitude: marker.latitude,
      longitude: marker.longitude,
    }}>
  </Marker>
))}
</code>```

Title: react-native-maps conditional markers

Body:
I have a map of markers that renders each marker in an array of coordinates. I am trying to render markers conditionally based on a key I give the marker. You can see exactly how I am trying to do this by looking at my snack example here or I have posted the code below.

Thank you, I appreciate it more than you know.

export default class Map extends React.Component {
  markers = [];
  state = {
    coordinates: [
      {
        name: '1',
        latitude: 36.212111515965525,
        longitude: -81.67527588876025,
        status: 'busy',
      },
      {
        name: '2',
        latitude: 36.21754431261142,
        longitude: -81.68598350040361,
        status: 'open',
      },
      {
        name: '3',
        latitude: 36.21744712906634,
        longitude: -81.68168562889075,
        status: 'busy',
      },
      {
        name: '4',
        latitude: 36.219352000280495,
        longitude: -81.68559146421954,
        status: 'open',
      },
    ],
  };

  render() {
    return (
      <View style={{ ...StyleSheet.absoluteFillObject }}>
        <MapView
          style={styles.map}
          provider={PROVIDER_GOOGLE}
          showsUserLocation={true}
          showsMyLocationButton={true}
          ref={(map) => (this._map = map)}
          initialRegion={{
            latitude: 36.212111515965525,
            longitude: -81.67527588876025,
            latitudeDelta: 0.05,
            longitudeDelta: 0.05
          }}>
          {this.state.coordinates.map((marker, index) => (
            if(marker.status == 'busy'){
            <Marker
              key={marker.name}
              ref={(ref) => {this.markers[index] = ref;}}
              onPress={() => this.onMarkerPress(marker, index)}
              coordinate={{
                latitude: marker.latitude,
                longitude: marker.longitude,
              }}>
              <Image
                source={require('./assets/blueMarker.png')}
                style={{ height: scale(50), width: scale(50) }}
              />
            </Marker>
            } else {
               <Marker
              key={marker.name}
              ref={(ref) => {this.markers[index] = ref;}}
              onPress={() => this.onMarkerPress(marker, index)}
              coordinate={{
                latitude: marker.latitude,
                longitude: marker.longitude,
              }}>
            </Marker>
            }

          ))}
        </MapView>
      </View>
    );
  }
}

Body:
You're not using correct JSX syntax. You can't use if-then-else, use ternary operator instead.

{ this.state.coordinates.map((marker, index) => (
  marker.status == 'busy' ?
  <Marker
    key={marker.name}
    ref={(ref) => {this.markers[index] = ref;}}
    onPress={() => this.onMarkerPress(marker, index)}
    coordinate={{
      latitude: marker.latitude,
      longitude: marker.longitude,
    }}>
    <Image
      source={require('./assets/blueMarker.png')}
      style={{ height: scale(50), width: scale(50) }}
    />
  </Marker>
  :
  <Marker
    key={marker.name}
    ref={(ref) => {this.markers[index] = ref;}}
    onPress={() => this.onMarkerPress(marker, index)}
    coordinate={{
      latitude: marker.latitude,
      longitude: marker.longitude,
    }}>
  </Marker>
))}


来源: stackexchange

问:
Image Replacement Script (jQuery)
I'm building an employee bios page where the client wants selected thumbnails to display in color at full opacity and all others at lower opacity in black and white. Which wouldn't be hard - the trouble is, every thumbnail has to have a color state and a black and white state. So my next thought was to swap out the black and white image (which would be resting within the div with a color background image) on mouseover.

```<code>$('.thumbnail').mouseenter(function(){
    var current = $(this); // cache thing
    var thishtml = current.html(); // get contents of thing
    current.html('').mouseleave(function(){ //empty the thing
        current.html(thishtml); //put the variable back in the thing
        });
});
</code>```

My HTML would be as follows:

```<code><div class = "thumbnail" style = "background-image: url(color.jpg);">
<img src="blackandwhite.jpg" />
</div>
</code>```

Obviously, since I'm asking the question, my idea didn't work. The mouseover removes the innerHTML, and the variable is converted successfully, but it doesn't get inserted into the DIV again. What am I missing?

答:
You don't need any Javascript to do that, just a piece of CSS:</p>

```<code> div.thumbnail {
   background-image: url(blackandwhite.jpg);
   opacity: 0.7;
 }
 div.thumbnail:hover {
   background-image: url(color.jpg);
   opacity: 1;
 }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Image Replacement Script (jQuery)

Body:
I'm building an employee bios page where the client wants selected thumbnails to display in color at full opacity and all others at lower opacity in black and white. Which wouldn't be hard - the trouble is, every thumbnail has to have a color state and a black and white state. So my next thought was to swap out the black and white image (which would be resting within the div with a color background image) on mouseover.

$('.thumbnail').mouseenter(function(){
    var current = $(this); // cache thing
    var thishtml = current.html(); // get contents of thing
    current.html('').mouseleave(function(){ //empty the thing
        current.html(thishtml); //put the variable back in the thing
        });
});

My HTML would be as follows:

Obviously, since I'm asking the question, my idea didn't work. The mouseover removes the innerHTML, and the variable is converted successfully, but it doesn't get inserted into the DIV again. What am I missing?

Body:
You don't need any Javascript to do that, just a piece of CSS:

 div.thumbnail {
   background-image: url(blackandwhite.jpg);
   opacity: 0.7;
 }
 div.thumbnail:hover {
   background-image: url(color.jpg);
   opacity: 1;
 }


问:
Python regex to find all strings that start with ' and end with '.tr ignoring leading and trailing whitespaces
I am struggling to get the correct regex for my script. I would like to find all Substrings in a file that start with a ' and end with '.tr. And save all these matches in a list.

This is what Ive got so far:

```<code>import glob
import pathlib
import re

libPathString = str(pathlib.Path.cwd().parent.resolve())

for path in glob.glob(libPathString + "/**", recursive=True):
    if(".dart" in path):
        with open(path, 'r+', encoding="utf-8") as file:
            data = [line.strip() for line in file.readlines()]
            data = ''.join(data)
            words = re.findall(r'\'.*\'.tr', data)
            print(words)
</code>```

The first problem is that words is not just the matching substring but the whole file until the substring.

Also it is giving me this file:

```<code>  child: Hero(
    tag: heroTag ?? '',  // <- because of this and the line below starts with `tr`
    transitionOnUserGestures: true,
    child: Material(
</code>```

But this should not match!

And then it is not finding this:

```<code>  AutoSizeText(
      'Das ist ein langer Text, der immer in einer Zeile ist.'
          .tr,
      style: AppTextStyles.montserratH4Regular,
</code>```

This one should match!

What am I missing here?

答:
You can try this

\s*'(.+?)'\s*\.tr
```

However, it looks like your use is to extract the string to be translated from a .dart file. I think it would be more elegant to use a library that can parse the AST of the dart language for this purpose.

ContentLicense: CC BY-SA 4.0

Body:
I am struggling to get the correct regex for my script. I would like to find all Substrings in a file that start with a ' and end with '.tr. And save all these matches in a list.

This is what Ive got so far:

import glob
import pathlib
import re

libPathString = str(pathlib.Path.cwd().parent.resolve())

for path in glob.glob(libPathString + "/**", recursive=True):
    if(".dart" in path):
        with open(path, 'r+', encoding="utf-8") as file:
            data = [line.strip() for line in file.readlines()]
            data = ''.join(data)
            words = re.findall(r'\'.*\'.tr', data)
            print(words)

The first problem is that words is not just the matching substring but the whole file until the substring.

Also it is giving me this file:

  child: Hero(
    tag: heroTag ?? '',  // <- because of this and the line below starts with `tr`
    transitionOnUserGestures: true,
    child: Material(

But this should not match!

And then it is not finding this:

  AutoSizeText(
      'Das ist ein langer Text, der immer in einer Zeile ist.'
          .tr,
      style: AppTextStyles.montserratH4Regular,

This one should match!

What am I missing here?

Body:
You can try this

\s*'(.+?)'\s*\.tr

However, it looks like your use is to extract the string to be translated from a .dart file. I think it would be more elegant to use a library that can parse the AST of the dart language for this purpose.


问:
Who has access to my S3 bucket and its objects?
How can I easily and accurately evaluate access permissions via the Amazon S3 management console or from boto3, to ensure that I am the only person who has access to my bucket and all of its objects?

I am aware that access to my bucket/objects can be given either through a Bucket Policy or ACL. However, ACL access can be given per object, so it is not clear to me how to fully review who has access, even to a single object in the bucket.

答:
It's not easy.

First, let's review the ways that permission might be granted:

Access Control Lists (ACLs) are object-level permissions that can grant public access, or access to a specific user. They are a remnant of the early way that Amazon S3 worked and can be annoying to manage. In fact, a new feature was recently made available that allows ACLs to be disabled -- and that's what AWS recommends!

Bucket Policies allow permissions to be assigned to a bucket, or a path within a bucket. This is a great way to make a bucket public and the only way to provide cross-account access to a bucket.

IAM Policies can be applied to an IAM User, IAM Group or IAM Role. These policies can grant permission to access Amazon S3 resources within the same account. This is a great way to assign permissions to specific IAM Users rather than doing it via a Bucket Policy.

The Amazon S3 console does allow you to Review bucket access using Access Analyzer for S3:

Access Analyzer for S3 alerts you to S3 buckets that are configured to allow access to anyone on the internet or other AWS accounts, including AWS accounts outside of your organization. For each public or shared bucket, you receive findings into the source and level of public or shared access. For example, Access Analyzer for S3 might show that a bucket has read or write access provided through a bucket access control list (ACL), a bucket policy, a Multi-Region Access Point policy, or an access point policy. Armed with this knowledge, you can take immediate and precise corrective action to restore your bucket access to what you intended.

However, it won't give you a full list of who can access which buckets.

You want to "ensure that you are the only one who has access to the bucket" -- this would require checking the Bucket Policy and the permissions of all IAM Users. There's no short-cut for doing this.


问:
Function to insert a HTML element separator every X lines of text (dynamic pagination, just like in a professional text editor)
Working on a responsive white paper for an open-source project.

Research has proven that this challenge has yet to be taken down clearly by anyone on the internet.

My original intention was to create a fully responsive A4 ratio container for each page and write text manually in each page element (this was a nice challenge on it's own and I succeeded to make the container the perfect ratio on any screen, but trying to make the text look the same on any screen seemed impossible), so I gave up.

IMPORTANT!
I remembered that I want to be able to edit the content of the white paper directly from the HTML and allow a JS function to separate the content dynamically. Otherwise, each time I wanted to change something in one page and the text didn't fit anymore, I had to re-edit all the pages manually again, pushing all content down or up, in each page, which is mad.

So, now I want the text to be separated into pages automatically just like when you write in a text editor like Word, only you're writing HTML code.

There is extra difficulty coming from the fact that I am using images, iframes and other unusual elements inside the HTML, which means I cannot use SVG as a solution which would have been easy.

Now.

I prepared this codepen to make things easier:
Responsive white paper (codepen)

So what I am trying to do is to somehow insert a break in the correct position, in my case the breaker is:

```<code></page><page>
</code>```

Using white-space: pre-line or better, white-space: pre-wrap seemed like a sensible first step in making things easier to edit. Using this CSS allows me to detect the exact place where each line of text ends.

Then, I have to take into account not only text-lines, but also images, iframes and maybe other type of elements the height of which I will not know, as they will be responsive.

My ultimate goal:

To insert the page separation elements in the correct place, making separate pages from raw HTML content where all pages are roughly the same if not the same height.

Possible solutions:

Maybe it's possible to work with the splitText function? Or the ES6 split() function? I will try.

Updates:
This Solution is similar to what I need but I can't seem to make it work at the moment, will update.

答:
I managed to eventually make this work, I did not use </page><page> as a breaker as my HTML structure changed a bit to make things simpler.

There is lots of room to improve performance though! It's super slow!
Same codepen as the question: https://codepen.io/lucian_apetrei/pen/QWOvwzm

Extra bonus! Is that I managed to create the perfect CSS calc to create a perfect responsive content inside an A4 ratio container that will look exactly the same on any screen, this is quite cool on it's own and if you want to use it, feel free!

HTML:

```<code><div id="loader">Loading responsive white paper.<br><br><b>Please wait<br><hr><hr><hr></b></div>
<div id="white-paper">
<page id="page0">
    <content>
<h1 class="top0">The shift to a Biosphere Consciousness</h2>
        A new generation is rising and with it different views on how we define freedom, power, and community.
        There is a basic change going on with the younger generation that is strange to older people. There is a change in the way you define “freedom”, the way your define “power”, and the way you define “community”, and these changes really suggest the real revolution.

        For my generation and generations before me, freedom was very simple.

        To be free is to be an autonomous agent, to be self-sufficient, to be independent, to not be beholden to others, to be an island to oneself so that one can have freedom as exclusivity.

<iframe class="fullWidth" src="https://www.youtube-nocookie.com/embed/h5Krh2ZmZkk" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

        For the younger generation that grew up on the Internet, autonomy is death. Being “an island to oneself” is death. Because for your generation, you ask the question, “How can I flourish to the full extent of my possibilities here on the planet?” And it is clear that your answer to that is I flourish to the extent that I am embedded in community after community where I can share my talents and those talents can benefit the network and come back to benefit myself. I am free because I have access and for you, freedom is not exclusivity. It is inclusivity.

        The younger generation has a different sensibility about power which makes the older generation very nervous. We essentially have believed that power always has to be a pyramid. It goes from the top town. That is power. There is no other way to define power. It's a pyramid.
        But young people that grow up on the Internet - it's strange because you grew up thinking that power has to do with the networks you're engaged in. For you, power is not vertical, it's lateral. For you, power is being enmeshed in network after network where you benefit each other. Open source!

<h2>And finally - I think most importantly</h2>
        We are seeing a change in the way our younger generation perceives identity to community. I grew up in a nation state - we were very clear on community - that is each individual is born to be an autonomous agent and we are each sovereign. And each of us compete with other sovereign individuals in the marketplace for scarce resources in a zero sum game. Our nations represent us because they are our sovereigns and they represent all the millions of individual citizens who are sovereigns against other nations and each nation then competes with every other nation for scarce resources in the marketplace or the battlefield in a zero sum game.

        Here's my question: Does anyone here believe that we are going to be able to address climate change and bring the human family together and take our responsibility for our fellow creatures and the Earth we live in with that worldview? Anybody?
        What we're beginning to see with our younger generation, and I don't want to overstretch this but I am beginning to sense a shift from geopolitics to biosphere consciousness. The biosphere is that nineteen kilometers from the stratosphere to the ocean where all life and all the chemicals on the planet interact to maintain the ecosystems and the biology of the Earth.
        These kids are learning ecological footprint. We actually have young people coming home and at dinner time they are asking their parents where the hamburger came from on the table. They are saying, “Did that hamburger come from a rainforest?” “Did they have to destroy the trees for four little inches of topsoil which only gives you three years of grazing so that cow could become my hamburger?” And when those trees are destroyed for the top soil to graze the cow for the hamburger, the kids are smart enough to understand that those trees harbor rare species of plant and animal life that only live in those canopies - they go extinct.

<img class="fullWidth" src="https://useruploads.socratic.org/VPqSrkhiSlmaLgJKbNZA_what-is-in-the-biosphere.png"> <xlines19xlines></xlines19xlines>       And then they connect the dots. If the trees disappear for the soil to graze the cow for the hamburger, those trees are not there to absorb carbon dioxide from industrial emissions and that means the temperature of the planet goes up. They are beginning to understand that everything each of us does intimately affects some other human being, some other creature and the planet we live in. We live in an indivisible, biosphere community. There is no escape. This isn't just academic. Our well-being depends on the well-being of the whole system and all the creatures in it.

        We all have to really come together. We've got one generation to lay down this new biosphere consciousness. Pass on this legacy so when your grandchildren look back at you, they can say you did the right thing. You helped replenish the planet, got us off carbon, and helped show our proper respect to generations not yet here including our fellow creatures.

        We must begin to think, organize, and act from a biosphere consciousness if life as we know it will continue to exist. We are in the midst of the greatest transition upon which humanity has ever embarked.

<h3>How will you respond?</h3>
    </content>
</page>
</div>
</code>```

CSS:

```<code>html, body {background: #232323; margin: 0; padding: 0; height: 100%}
@import url('https://fonts.googleapis.com/css2?family=Dosis:wght@400;700&family=Roboto:wght@300;400;900&display=swap');
page {
  padding: 2em 2em 0 2em; /* these are my page margins */
  width: 69vw;
  height: calc(69vw * 1.4142); /* This is for setting up the white-paper container to be at A4 ratio on any screen */
  font-size: calc(69vw * 1.4142 / 54.0103); /* After days of tests and empty internet queries, I discovered the perfect font-size formula for responsive text on a A4 paper portrait ratio, on any screen, considering my above margins (padding); if you want to have smaller or bigger font sizes or for landscape ratios and margins, you also have to adjust the JavaScript variables */
  line-height: 1;
  font-family: Arial, sans-serif;
  margin: 0 auto 1em auto;
  background:#ffffff;
  overflow: hidden;
  position: relative;
  box-sizing: border-box;
  display: block
}

content {
  position: relative;
  display: inline;
  font-weight: 400;
  z-index: 12;
  font-size: 100%;
  line-height: 1.6;
  white-space: break-spaces;
  font-family: 'Roboto', Arial, sans-serif;
}

content h1, content h2, content h3, content h4 {
  margin: 0 !important;
  padding: 0 !important;
  font-size: 1em;
  font-weight: bold;
  display: inline
}

content h1 {display: flex; align-items: center; white-space: pre-wrap; background: #db463e; color: #ffffff; width: 69vw; height: 2em; position: absolute; left: -2em; text-transform: uppercase;}
content h1:before {content: ''; display: block; width: 1em; height: 1em; background: #ffffff; margin: 0 0.5em 0 1em;}

.top0 {top: -2.19em}

content h2 {font-size: 1.23em}
content h3 {font-size: 1.12em}

content img, content iframe {width: 100%;}
content iframe {height: calc(69vw * 0.5625)}
.fullWidth {width: 69vw; position: absolute; left: -2em}

content div {display: inline}

/* For Mobile */
@media screen and (max-width: 981px) and (orientation: portrait) {
  page {
    width: 100vw;
    height: calc(100vw * 1.4142); /* For Mobile */
    font-size: calc(100vw * 1.4142 / 54.0103); /* For Mobile */
  }
  .fullWidth, content h1 {width: 100vw;}
  content iframe {height: calc(100vw * 0.5625)}
}

#loader {text-align: center; font-size: 1em; width: 100vw; height: 100vh; background: rgba(0,0,0,.9); position: fixed; top: 0; z-index: 999; display: flex; justify-content: center; align-items: center; align-content: center; flex-direction: column; color: #ffffff; font-family: 'Roboto', Arial, sans-serif}
#loader b {font-size: 2em;}
#loader hr {display: inline-block; border: 0; width: 0.23em; height: 0.23em; background: #ffffff; margin: 0 0 0 0.23em; border-radius: 100%; animation: loaderDot 1.8s infinite ease-in-out}
#loader hr:nth-of-type(2) {animation-delay: 0.16s}
#loader hr:nth-of-type(3) {animation-delay: 0.32s}
@keyframes loaderDot {
  0% {transform: scale(1)}
  50% {transform: scale(0)}
  100% {transform: scale(1)}
}
</code>```

JS:

```<code>// Get a single first matching element
var $ = function (selector, parent) {
  return (parent ? parent : document).querySelector(selector);
};

// Get all matching elements
var $$ = function (selector, parent) {
  return (parent ? parent : document).querySelectorAll(selector);
};

document.addEventListener("DOMContentLoaded", function () {
  var whitePaper = $('#white-paper');
  var container = $('#page0');
  var page0 = $('#page0 content');
  var parsedContent = new DOMParser().parseFromString(page0.innerHTML, 'text/html'); // first, we are parsing all content like paragraphs and all other elements into an array using DOMParser
  page0.innerHTML = ''; // let's Tabula Rasa so we can use the first page element to calculate each new addition into it

  var parsedArray = [...parsedContent.body.childNodes]
  .map(child => child.outerHTML || child.textContent);

  var currentPage = 0;
  var lastDiv = 0;
  var pageRects = 0;

  // a function to add the next page
  var addPage = function() {
    // add a new page
    var newPage = document.createElement('page');
    newPage.setAttribute("id", 'page' + currentPage);
    var emptyContent = document.createElement('content');
    newPage.appendChild(emptyContent);
    whitePaper.appendChild(newPage);
  }

  // a function to add each parsed item to the current page in a div or to remove the item if it doesn't fit at the end of the page
  var addRemoveItem = function(item, rects) {
    // if we don't have a manual override for pageRects, get the actual rects nr
    rects ? pageRects = rects : pageRects = $('#page' + currentPage + ' content').getClientRects().length;

    let previousDivContent;
    if (pageRects > 31) { // this will go through only once per new page
      let previousDiv = $('#page' + currentPage + ' content div:last-of-type');
      let previousDivId = previousDiv.id;
      previousDivContent = previousDiv.innerHTML;
      previousDiv.remove();
      currentPage++;
      addPage();
      $('#page'+currentPage+ ' content').innerHTML += '<div id="'+previousDivId+'">'+previousDivContent+'</div>'; // this is the first item on the next page
    }

    // if we have a new element or word / punctuation and the pageRects are smaller than 34, we add the new div ahead of the previous one
    var id = 'i' + lastDiv;
    lastDiv++;
    var newDiv = '<div id="'+id+'">'+item+'</div>';
    $('#page'+currentPage+ ' content').innerHTML += newDiv;

    // Debugging
    //console.log('Page Rects: ' + pageRects + ' | Item: ' + item + ' | Prev end item: ' + previousDivContent);
  }

  // let's loop through all the content parsed with DOMParser (paragraphs, links, headings, images, iframes)
  parsedArray.forEach((item, index) => {
    if (item.match(/<\/?[a-z][\s\S]*>/)) {
      // if the next item is an element
      if (item.match(/xlines/)) {
        let extraLines = item.split(/xlines/);
        let lines = extraLines[1];
        pageRects += parseInt(lines);
        addRemoveItem(item, pageRects);
      } else {
        addRemoveItem(item);
      }
    } else {
      // if the next item is a word / punctuation
      var words = item.split(' ');
      // loop through the words / punctuation
      words.forEach((item, i) => {
        addRemoveItem(item + ' ');
      });
    }
  });
  $('#loader').style.display = 'none';
});
</code>```

IMPORTANT:
Using new lines in HTML works, but not all the time, in some situations, I don't know why, adding extra lines doesn't work properly, you can see this bug after the second image where I used <xlines15xlines></xlines15xlines> as a placeholder, a manual rects count override for when I need extra lines that pushes content correctly.

PROBLEMS TO SOLVE:
If anyone has any idea how to make it work faster, please contribute!

Body:
Working on a responsive white paper for an open-source project.

Research has proven that this challenge has yet to be taken down clearly by anyone on the internet.

My original intention was to create a fully responsive A4 ratio container for each page and write text manually in each page element (this was a nice challenge on it's own and I succeeded to make the container the perfect ratio on any screen, but trying to make the text look the same on any screen seemed impossible), so I gave up.

IMPORTANT!
I remembered that I want to be able to edit the content of the white paper directly from the HTML and allow a JS function to separate the content dynamically. Otherwise, each time I wanted to change something in one page and the text didn't fit anymore, I had to re-edit all the pages manually again, pushing all content down or up, in each page, which is mad.

So, now I want the text to be separated into pages automatically just like when you write in a text editor like Word, only you're writing HTML code.

There is extra difficulty coming from the fact that I am using images, iframes and other unusual elements inside the HTML, which means I cannot use SVG as a solution which would have been easy.

Now.

I prepared this codepen to make things easier:
Responsive white paper (codepen)

So what I am trying to do is to somehow insert a break in the correct position, in my case the breaker is:

</page><page>

Using white-space: pre-line or better, white-space: pre-wrap seemed like a sensible first step in making things easier to edit. Using this CSS allows me to detect the exact place where each line of text ends.

Then, I have to take into account not only text-lines, but also images, iframes and maybe other type of elements the height of which I will not know, as they will be responsive.

My ultimate goal:

To insert the page separation elements in the correct place, making separate pages from raw HTML content where all pages are roughly the same if not the same height.

Possible solutions:

Maybe it's possible to work with the splitText function? Or the ES6 split() function? I will try.

Updates:
This Solution is similar to what I need but I can't seem to make it work at the moment, will update.

Body:
I managed to eventually make this work, I did not use </page><page> as a breaker as my HTML structure changed a bit to make things simpler.

There is lots of room to improve performance though! It's super slow!
Same codepen as the question: https://codepen.io/lucian_apetrei/pen/QWOvwzm

Extra bonus! Is that I managed to create the perfect CSS calc to create a perfect responsive content inside an A4 ratio container that will look exactly the same on any screen, this is quite cool on it's own and if you want to use it, feel free!

HTML:

<div id="loader">Loading responsive white paper.<br><br><b>Please wait<br><hr><hr><hr></b></div>
<div id="white-paper">
<page id="page0">
    <content>
<h1 class="top0">The shift to a Biosphere Consciousness</h2>
        A new generation is rising and with it different views on how we define freedom, power, and community.
        There is a basic change going on with the younger generation that is strange to older people. There is a change in the way you define “freedom”, the way your define “power”, and the way you define “community”, and these changes really suggest the real revolution.

        For my generation and generations before me, freedom was very simple.

        To be free is to be an autonomous agent, to be self-sufficient, to be independent, to not be beholden to others, to be an island to oneself so that one can have freedom as exclusivity.

<iframe class="fullWidth" src="https://www.youtube-nocookie.com/embed/h5Krh2ZmZkk" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

        For the younger generation that grew up on the Internet, autonomy is death. Being “an island to oneself” is death. Because for your generation, you ask the question, “How can I flourish to the full extent of my possibilities here on the planet?” And it is clear that your answer to that is I flourish to the extent that I am embedded in community after community where I can share my talents and those talents can benefit the network and come back to benefit myself. I am free because I have access and for you, freedom is not exclusivity. It is inclusivity.

        The younger generation has a different sensibility about power which makes the older generation very nervous. We essentially have believed that power always has to be a pyramid. It goes from the top town. That is power. There is no other way to define power. It's a pyramid.
        But young people that grow up on the Internet - it's strange because you grew up thinking that power has to do with the networks you're engaged in. For you, power is not vertical, it's lateral. For you, power is being enmeshed in network after network where you benefit each other. Open source!

<h2>And finally - I think most importantly</h2>
        We are seeing a change in the way our younger generation perceives identity to community. I grew up in a nation state - we were very clear on community - that is each individual is born to be an autonomous agent and we are each sovereign. And each of us compete with other sovereign individuals in the marketplace for scarce resources in a zero sum game. Our nations represent us because they are our sovereigns and they represent all the millions of individual citizens who are sovereigns against other nations and each nation then competes with every other nation for scarce resources in the marketplace or the battlefield in a zero sum game.

        Here's my question: Does anyone here believe that we are going to be able to address climate change and bring the human family together and take our responsibility for our fellow creatures and the Earth we live in with that worldview? Anybody?
        What we're beginning to see with our younger generation, and I don't want to overstretch this but I am beginning to sense a shift from geopolitics to biosphere consciousness. The biosphere is that nineteen kilometers from the stratosphere to the ocean where all life and all the chemicals on the planet interact to maintain the ecosystems and the biology of the Earth.
        These kids are learning ecological footprint. We actually have young people coming home and at dinner time they are asking their parents where the hamburger came from on the table. They are saying, “Did that hamburger come from a rainforest?” “Did they have to destroy the trees for four little inches of topsoil which only gives you three years of grazing so that cow could become my hamburger?” And when those trees are destroyed for the top soil to graze the cow for the hamburger, the kids are smart enough to understand that those trees harbor rare species of plant and animal life that only live in those canopies - they go extinct.

<img class="fullWidth" src="https://useruploads.socratic.org/VPqSrkhiSlmaLgJKbNZA_what-is-in-the-biosphere.png"> <xlines19xlines></xlines19xlines>       And then they connect the dots. If the trees disappear for the soil to graze the cow for the hamburger, those trees are not there to absorb carbon dioxide from industrial emissions and that means the temperature of the planet goes up. They are beginning to understand that everything each of us does intimately affects some other human being, some other creature and the planet we live in. We live in an indivisible, biosphere community. There is no escape. This isn't just academic. Our well-being depends on the well-being of the whole system and all the creatures in it.

        We all have to really come together. We've got one generation to lay down this new biosphere consciousness. Pass on this legacy so when your grandchildren look back at you, they can say you did the right thing. You helped replenish the planet, got us off carbon, and helped show our proper respect to generations not yet here including our fellow creatures.

        We must begin to think, organize, and act from a biosphere consciousness if life as we know it will continue to exist. We are in the midst of the greatest transition upon which humanity has ever embarked.

<h3>How will you respond?</h3>
    </content>
</page>
</div>

CSS:

html, body {background: #232323; margin: 0; padding: 0; height: 100%}
@import url('https://fonts.googleapis.com/css2?family=Dosis:wght@400;700&family=Roboto:wght@300;400;900&display=swap');
page {
  padding: 2em 2em 0 2em; /* these are my page margins */
  width: 69vw;
  height: calc(69vw * 1.4142); /* This is for setting up the white-paper container to be at A4 ratio on any screen */
  font-size: calc(69vw * 1.4142 / 54.0103); /* After days of tests and empty internet queries, I discovered the perfect font-size formula for responsive text on a A4 paper portrait ratio, on any screen, considering my above margins (padding); if you want to have smaller or bigger font sizes or for landscape ratios and margins, you also have to adjust the JavaScript variables */
  line-height: 1;
  font-family: Arial, sans-serif;
  margin: 0 auto 1em auto;
  background:#ffffff;
  overflow: hidden;
  position: relative;
  box-sizing: border-box;
  display: block
}

content {
  position: relative;
  display: inline;
  font-weight: 400;
  z-index: 12;
  font-size: 100%;
  line-height: 1.6;
  white-space: break-spaces;
  font-family: 'Roboto', Arial, sans-serif;
}

content h1, content h2, content h3, content h4 {
  margin: 0 !important;
  padding: 0 !important;
  font-size: 1em;
  font-weight: bold;
  display: inline
}

content h1 {display: flex; align-items: center; white-space: pre-wrap; background: #db463e; color: #ffffff; width: 69vw; height: 2em; position: absolute; left: -2em; text-transform: uppercase;}
content h1:before {content: ''; display: block; width: 1em; height: 1em; background: #ffffff; margin: 0 0.5em 0 1em;}

.top0 {top: -2.19em}

content h2 {font-size: 1.23em}
content h3 {font-size: 1.12em}

content img, content iframe {width: 100%;}
content iframe {height: calc(69vw * 0.5625)}
.fullWidth {width: 69vw; position: absolute; left: -2em}

content div {display: inline}

/* For Mobile */
@media screen and (max-width: 981px) and (orientation: portrait) {
  page {
    width: 100vw;
    height: calc(100vw * 1.4142); /* For Mobile */
    font-size: calc(100vw * 1.4142 / 54.0103); /* For Mobile */
  }
  .fullWidth, content h1 {width: 100vw;}
  content iframe {height: calc(100vw * 0.5625)}
}

#loader {text-align: center; font-size: 1em; width: 100vw; height: 100vh; background: rgba(0,0,0,.9); position: fixed; top: 0; z-index: 999; display: flex; justify-content: center; align-items: center; align-content: center; flex-direction: column; color: #ffffff; font-family: 'Roboto', Arial, sans-serif}
#loader b {font-size: 2em;}
#loader hr {display: inline-block; border: 0; width: 0.23em; height: 0.23em; background: #ffffff; margin: 0 0 0 0.23em; border-radius: 100%; animation: loaderDot 1.8s infinite ease-in-out}
#loader hr:nth-of-type(2) {animation-delay: 0.16s}
#loader hr:nth-of-type(3) {animation-delay: 0.32s}
@keyframes loaderDot {
  0% {transform: scale(1)}
  50% {transform: scale(0)}
  100% {transform: scale(1)}
}

JS:

// Get a single first matching element
var $ = function (selector, parent) {
  return (parent ? parent : document).querySelector(selector);
};

// Get all matching elements
var $$ = function (selector, parent) {
  return (parent ? parent : document).querySelectorAll(selector);
};

document.addEventListener("DOMContentLoaded", function () {
  var whitePaper = $('#white-paper');
  var container = $('#page0');
  var page0 = $('#page0 content');
  var parsedContent = new DOMParser().parseFromString(page0.innerHTML, 'text/html'); // first, we are parsing all content like paragraphs and all other elements into an array using DOMParser
  page0.innerHTML = ''; // let's Tabula Rasa so we can use the first page element to calculate each new addition into it

  var parsedArray = [...parsedContent.body.childNodes]
  .map(child => child.outerHTML || child.textContent);

  var currentPage = 0;
  var lastDiv = 0;
  var pageRects = 0;

  // a function to add the next page
  var addPage = function() {
    // add a new page
    var newPage = document.createElement('page');
    newPage.setAttribute("id", 'page' + currentPage);
    var emptyContent = document.createElement('content');
    newPage.appendChild(emptyContent);
    whitePaper.appendChild(newPage);
  }

  // a function to add each parsed item to the current page in a div or to remove the item if it doesn't fit at the end of the page
  var addRemoveItem = function(item, rects) {
    // if we don't have a manual override for pageRects, get the actual rects nr
    rects ? pageRects = rects : pageRects = $('#page' + currentPage + ' content').getClientRects().length;

    let previousDivContent;
    if (pageRects > 31) { // this will go through only once per new page
      let previousDiv = $('#page' + currentPage + ' content div:last-of-type');
      let previousDivId = previousDiv.id;
      previousDivContent = previousDiv.innerHTML;
      previousDiv.remove();
      currentPage++;
      addPage();
      $('#page'+currentPage+ ' content').innerHTML += '<div id="'+previousDivId+'">'+previousDivContent+'</div>'; // this is the first item on the next page
    }

    // if we have a new element or word / punctuation and the pageRects are smaller than 34, we add the new div ahead of the previous one
    var id = 'i' + lastDiv;
    lastDiv++;
    var newDiv = '<div id="'+id+'">'+item+'</div>';
    $('#page'+currentPage+ ' content').innerHTML += newDiv;

    // Debugging
    //console.log('Page Rects: ' + pageRects + ' | Item: ' + item + ' | Prev end item: ' + previousDivContent);
  }

  // let's loop through all the content parsed with DOMParser (paragraphs, links, headings, images, iframes)
  parsedArray.forEach((item, index) => {
    if (item.match(/<\/?[a-z][\s\S]*>/)) {
      // if the next item is an element
      if (item.match(/xlines/)) {
        let extraLines = item.split(/xlines/);
        let lines = extraLines[1];
        pageRects += parseInt(lines);
        addRemoveItem(item, pageRects);
      } else {
        addRemoveItem(item);
      }
    } else {
      // if the next item is a word / punctuation
      var words = item.split(' ');
      // loop through the words / punctuation
      words.forEach((item, i) => {
        addRemoveItem(item + ' ');
      });
    }
  });
  $('#loader').style.display = 'none';
});

IMPORTANT:
Using new lines in HTML works, but not all the time, in some situations, I don't know why, adding extra lines doesn't work properly, you can see this bug after the second image where I used <xlines15xlines></xlines15xlines> as a placeholder, a manual rects count override for when I need extra lines that pushes content correctly.

PROBLEMS TO SOLVE:
If anyone has any idea how to make it work faster, please contribute!


问:
How to forecast continuous in R
I'm novice in R and im doing a forecast for my dataset, as you can see in the diagram, the data before 2019,04 is training data, the part in blue (start from 2019,04- 2019,12) is my forecast and the red line is the test data(2019,04- 2019,12), the time interval is identical, but in the diagram it isn't continuous, how can I fix it?

library(forecast)

fit_ets %>% forecast(h=9) %>%
autoplot()+
autolayer(testing)
```

答:
if by continuous you mean that the black line is not "connected" to the red nor the blue: each line has a first and last observation which are connected via lines (and have possibly more observations).

Your first value to predict (or test) is, chronologically speaking, after the training data, thus the black line will not reach the blue and red. Also the blue and red line can not reach back to connect as the last observation from training data is not included in theire data.

After forecasting you could include the last observation from the training data in test and prediction set. This will lead to a "continuous" line when plotting.

Title: How to forecast continuous in R


问:
How can I shift my Entry and Label widget to the right and align them in Tkinter?
I am making a program on Tkinter,python and I want to move 3 label and entry widgets to the right so that they are in line and one below the other. I am using grid but its very frustrating because the column is not moving further than 6.
Here's the code:</p>
```<code>from tkinter import *
from tkinter import ttk
from tkinter import Text
import tkinter as tk

win = tk.Tk()
win.geometry("1200x988")

def display_text():
    global entry
    string = entry.get()
    label.configure(text=string)

entry = Entry(win, width=40)
entry.focus_set()
label = Label(win, text="Name:", font=("Courier 22 bold"))
label.grid(row=0, column=0, sticky=W, pady=2)
entry.grid(row=1, column=0, pady=2)

label2 = Label(win, text="Number:", font=("Courier 22 bold"))
label2.grid(row=2, column=0, sticky=W, pady=2)
entry2 = Entry(win, width=40)
entry2.focus_set()
entry2.grid(row=3, column=0, sticky=W, pady=2)

label3 = Label(win, text="Address:", font=("Courier 22 bold"))
label3.grid(row=4, column=0, sticky=W, pady=2)
entry3 = tk.Entry(win, width=60)
entry3.grid(row=5, column=0, sticky=W, ipady=20)

ttk.Button(win, text="Okay", width=20,
command=display_text).grid(row=6, column=0, pady=2)

win.mainloop()

</code>```

答:
Use rows and colums:

```<code>from tkinter import ttk
import os
import tkinter as tk

win = tk.Tk()
win.wm_title("Data entry")

def display_text():
    string = entry.get()
    if string:
        label.configure(text=string)

label = tk.Label(win, text="Name:", font=("Courier 22 bold"))
label.grid(row=0, column=0, sticky=tk.W, pady=2)
entry = tk.Entry(win, width=40)
entry.focus_set()
entry.grid(row=0, column=1, sticky=tk.EW, pady=2)

label2 = tk.Label(win, text="Number:", font=("Courier 22 bold"))
label2.grid(row=1, column=0, sticky=tk.W, pady=2)
entry2 = tk.Entry(win, width=40)
entry2.grid(row=1, column=1, sticky=tk.EW, pady=2)

label3 = tk.Label(win, text="Address:", font=("Courier 22 bold"))
label3.grid(row=2, column=0, sticky=tk.W, pady=2)
entry3 = tk.Entry(win, width=60)
entry3.grid(row=2, column=1, sticky=tk.EW, ipady=20)

ttk.Button(win, text="Okay", command=display_text).grid(
    row=3, column=0, pady=2
)

win.mainloop()
</code>```

The window will look like this:

]

I've left out the title bar on purpose; this looks different depending on the OS you use.Some additional points:

Using from tkinter import * is considered bad style these days.

Setting the geometry is not really necessary.

Don't forget to set the window title with wm_title.

Making the Entry widgets sticky on ease and west (tk.EW) makes them fill the column.

Not prescribing the width of the button makes column 0 slimmer.

Personally, I'd rather have all the text the same size, so I would set the font globally:

```<code>import tkinter.font as tkfont

win = tk.Tk()
win.wm_title("Data entry")

default_font = tkfont.nametofont("TkDefaultFont")
default_font.configure(
    family="Courier",
    size=22,
    weight="bold"
)
win.option_add("*Font", default_font)
</code>```

(I've left out the title bar on purpose; this looks different depending on the OS you use.)

Body:
I am making a program on Tkinter,python and I want to move 3 label and entry widgets to the right so that they are in line and one below the other. I am using grid but its very frustrating because the column is not moving further than 6.
Here's the code:

from tkinter import *
from tkinter import ttk
from tkinter import Text
import tkinter as tk

win = tk.Tk()
win.geometry("1200x988")

def display_text():
    global entry
    string = entry.get()
    label.configure(text=string)

entry = Entry(win, width=40)
entry.focus_set()
label = Label(win, text="Name:", font=("Courier 22 bold"))
label.grid(row=0, column=0, sticky=W, pady=2)
entry.grid(row=1, column=0, pady=2)

label2 = Label(win, text="Number:", font=("Courier 22 bold"))
label2.grid(row=2, column=0, sticky=W, pady=2)
entry2 = Entry(win, width=40)
entry2.focus_set()
entry2.grid(row=3, column=0, sticky=W, pady=2)

label3 = Label(win, text="Address:", font=("Courier 22 bold"))
label3.grid(row=4, column=0, sticky=W, pady=2)
entry3 = tk.Entry(win, width=60)
entry3.grid(row=5, column=0, sticky=W, ipady=20)

ttk.Button(win, text="Okay", width=20,
command=display_text).grid(row=6, column=0, pady=2)

win.mainloop()

Body:
Use rows and colums:

from tkinter import ttk
import os
import tkinter as tk

win = tk.Tk()
win.wm_title("Data entry")

def display_text():
    string = entry.get()
    if string:
        label.configure(text=string)

label = tk.Label(win, text="Name:", font=("Courier 22 bold"))
label.grid(row=0, column=0, sticky=tk.W, pady=2)
entry = tk.Entry(win, width=40)
entry.focus_set()
entry.grid(row=0, column=1, sticky=tk.EW, pady=2)

label2 = tk.Label(win, text="Number:", font=("Courier 22 bold"))
label2.grid(row=1, column=0, sticky=tk.W, pady=2)
entry2 = tk.Entry(win, width=40)
entry2.grid(row=1, column=1, sticky=tk.EW, pady=2)

label3 = tk.Label(win, text="Address:", font=("Courier 22 bold"))
label3.grid(row=2, column=0, sticky=tk.W, pady=2)
entry3 = tk.Entry(win, width=60)
entry3.grid(row=2, column=1, sticky=tk.EW, ipady=20)

ttk.Button(win, text="Okay", command=display_text).grid(
    row=3, column=0, pady=2
)

win.mainloop()

The window will look like this:

]

I've left out the title bar on purpose; this looks different depending on the OS you use.Some additional points:

Using from tkinter import * is considered bad style these days.

Setting the geometry is not really necessary.

Don't forget to set the window title with wm_title.

Making the Entry widgets sticky on ease and west (tk.EW) makes them fill the column.

Not prescribing the width of the button makes column 0 slimmer.

Personally, I'd rather have all the text the same size, so I would set the font globally:

import tkinter.font as tkfont

win = tk.Tk()
win.wm_title("Data entry")

default_font = tkfont.nametofont("TkDefaultFont")
default_font.configure(
    family="Courier",
    size=22,
    weight="bold"
)
win.option_add("*Font", default_font)

(I've left out the title bar on purpose; this looks different depending on the OS you use.)


问:
How can I use my own image when site returns fake image with a 404 response code
This is a bit different then the usual question about how to gracefully handle broken images in javascript.

I already have an onerror handler on the image that will replace it with a custom "image not found" image.

However, there is a site that, when you request their image, returns a 404 response code, but in the response body actually returns an image with their own custom not found image.  Apparently, the img onerror event doesn't trigger in this case because there is still an image despite the error code.  (I tested on FireFox, IE8, and Chrome)

Here is a sample of the image in question: http://images.cars.com/preview/DMI/186445/C2121.jpg

Does anyone have any ideas for how to detect this case in javascript and replace their dynamic 404 image with our own?  Thanks!

答:
One simple solution that comes to mind is not to load an image immediately, and then use javascript in document.ready or window.onload to get the image. Then, if the status is 404, put your own noImageAvailable.png in the image. If you get a 200 or other OK status, put the received image in there. There is a problem with this, however.

The same-origin policy does not allow scripts to access content cross-domain. So you would not be able to simply use javascript to get this file. There are a couple workarounds for this, one of which I will explain here (not necessarily the best, just an option).

The benefit of this method is that the javascript can just ask for a file, and display the result. The downside is more backend code. Simply have the javascript request the image from your server (AJAX), and insert the result in the img. On the server side for this request, open a TCP socket to the server hosting the image (you will have to resolve the IP address), and send an HTTP GET request for the image. If the image is returned ok, send it along as a response to the AJAX. If not, send your own noImageAvailable.png back.

Since this may take some time, you may want to replace the image with a default "loading" image at first, until the AJAX returns.

AJAX Tutorial

HTTP Protocol Information

I'd include something on socket programming for you, but I don't know what kind of backend you are using.


问:
Allow users to download files directly django
In the TrainerProfileModel I have file field called cv. I want to allow users to download the file directly when clicking on the link. Could you provide any ways to implement this?

models.py:

```<code>class TrainerProfile(models.Model):
 user = models.OneToOneField(User, on_delete=models.CASCADE,
 null=True, related_name='trainer_profile')
 profile_picture = models.ImageField(blank=True)
 phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone
 number must be entered in the format: '+999999999'. Up to 15 digits
 allowed.")
 mobile_number = models.CharField(validators=[phone_regex],
 max_length=17, blank=True)
 location = models.CharField(max_length=200,null=True,blank=True)
 gender = models.CharField(choices=GENDER_CHOICES,max_length=150,
 blank=True)
 cv = models.FileField(blank=True)
 approval=models.BooleanField(default=False)

 def __str__(self):
    return self.user.username
</code>```

In my template:

```<code><li class="list-group-item">
  <b>Download CV</b>
  <a class="pull-right">{{ trainer.cv }}</a>
</li>
</code>```

答:
We need to till django about our media images so we import the settings in urls.py  by from django.conf import settings  and by this code if settings.DEBUG: urlpatterns += urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
we till django about our media images ,
DONOT forget to add Media root and Media URL by MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and finally we we add image.url in src attribute of image in our html page it will display the image.

Body:
In the TrainerProfileModel I have file field called cv. I want to allow users to download the file directly when clicking on the link. Could you provide any ways to implement this?

models.py:

class TrainerProfile(models.Model):
 user = models.OneToOneField(User, on_delete=models.CASCADE,
 null=True, related_name='trainer_profile')
 profile_picture = models.ImageField(blank=True)
 phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone
 number must be entered in the format: '+999999999'. Up to 15 digits
 allowed.")
 mobile_number = models.CharField(validators=[phone_regex],
 max_length=17, blank=True)
 location = models.CharField(max_length=200,null=True,blank=True)
 gender = models.CharField(choices=GENDER_CHOICES,max_length=150,
 blank=True)
 cv = models.FileField(blank=True)
 approval=models.BooleanField(default=False)

 def __str__(self):
    return self.user.username

In my template:

  Download CV
  {{ trainer.cv }}


问:
Blazor set background color with parameter
I have a card blazor component with css styling, i've tried to pass background color as a parameter to the styling in the following way:

```<code>@inject NavigationManager UriHelper

<SfCard @onclick=@Navigate CssClass="@NavigateUri">
    <CardHeader Title="@Title">
        <span class="fa fa-@CardIcon test-icon" aria-hidden="true"></span>
    </CardHeader>
    <CardContent Content="@Content" />
</SfCard>

<style>
    .e-card .e-card-header {
        background: @CardColor;
        height: 60px;
        align-self: flex-start;
    }

</style>

@code {
    [Parameter]
    public string Title { get; set; } = string.Empty;

    [Parameter]
    public string Content { get; set; } = string.Empty;

    [Parameter]
    public string NavigateUri { get; set; } = string.Empty;

    [Parameter]
    public string CardColor { get; set; } = string.Empty;

    [Parameter]
    public string CardIcon { get; set; } = string.Empty;

    void Navigate()
    {
        UriHelper.NavigateTo(NavigateUri);
    }
}
</code>```

It works with 1 card, but when trying to create multiple instances of cards, like this for example:

```<code>    <Card Title="test1" NavigateUri="test1" CardIcon="random"
        Content="test1 content" CardColor="red">
    </Card>

    <Card Title="test2" NavigateUri="test2" CardIcon="random"
        Content="test2 content" CardColor="blue">
    </Card>
</code>```

They are all colored with the first color provided (red) and not each with its own color

答:
Revised Answer

Something like this should work.  I've used Guids to create uniqueness in each instance of the component.  It's a manual version of component isolated CSS.

```<code><div id="@UID" class="card text-white e-card mb-3" style="max-width: 18rem;">
  <div class="card-header e-card-header">Header</div>
  <div class="card-body">
    <h5 class="card-title">Primary card title</h5>
    <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
  </div>
</div>

<style>
    @css  {
        background: @CardColor;
    }

</style>

@code {
    public string UID = $"xx-{Guid.NewGuid().ToString()}";

    private string css => $"#{UID} .e-card-header";

    [Parameter] public string CardColor { get; set; } = "#004";
}
</code>```

Here's my test page:

```<code>@page "/"

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />
<MyCard CardColor="#004" />
<MyCard CardColor="#040" />
<MyCard CardColor="#800" />

@code {
}
</code>```

And the result:

SyncFusion version:

Here's a "sort of working" Syncfusion version - I got fed up hoop jumping to get it fully installed!

```<code>@using Syncfusion.Blazor.Cards
<SfCard id="@UID" CssClass="@NavigateUri">
    <CardHeader Title="@Title">
        <span class="fa fa-@CardIcon test-icon" aria-hidden="true"></span>
    </CardHeader>
    <CardContent Content="@Content" />
</SfCard>

<style>
    @css {
        background: @CardColor;
    }

</style>

@code {
    [Parameter]
    public string Title { get; set; } = "Hello";

    [Parameter]
    public string Content { get; set; } = "Hello Blazor";

    [Parameter]
    public string NavigateUri { get; set; } = string.Empty;

    [Parameter]
    public string CardColor { get; set; } = string.Empty;

    [Parameter]
    public string CardIcon { get; set; } = string.Empty;

    public string UID = $"xx-{Guid.NewGuid().ToString()}";

    private string css => $"#{UID} .e-card-header";
}
</code>```

And running that shows the background color changes:

Body:
I have a card blazor component with css styling, i've tried to pass background color as a parameter to the styling in the following way:

@inject NavigationManager UriHelper

<SfCard @onclick=@Navigate CssClass="@NavigateUri">
    <CardHeader Title="@Title">

    </CardHeader>
    <CardContent Content="@Content" />
</SfCard>

@code {
    [Parameter]
    public string Title { get; set; } = string.Empty;

    [Parameter]
    public string Content { get; set; } = string.Empty;

    [Parameter]
    public string NavigateUri { get; set; } = string.Empty;

    [Parameter]
    public string CardColor { get; set; } = string.Empty;

    [Parameter]
    public string CardIcon { get; set; } = string.Empty;

    void Navigate()
    {
        UriHelper.NavigateTo(NavigateUri);
    }
}

It works with 1 card, but when trying to create multiple instances of cards, like this for example:

    <Card Title="test1" NavigateUri="test1" CardIcon="random"
        Content="test1 content" CardColor="red">
    </Card>

    <Card Title="test2" NavigateUri="test2" CardIcon="random"
        Content="test2 content" CardColor="blue">
    </Card>

They are all colored with the first color provided (red) and not each with its own color

Body:
Revised Answer

Something like this should work.  I've used Guids to create uniqueness in each instance of the component.  It's a manual version of component isolated CSS.

<div id="@UID" class="card text-white e-card mb-3" style="max-width: 18rem;">
  <div class="card-header e-card-header">Header</div>
  <div class="card-body">
    <h5 class="card-title">Primary card title</h5>
    <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
  </div>
</div>

<style>
    @css  {
        background: @CardColor;
    }

</style>

@code {
    public string UID = $"xx-{Guid.NewGuid().ToString()}";

    private string css => $"#{UID} .e-card-header";

    [Parameter] public string CardColor { get; set; } = "#004";
}

Here's my test page:

@page "/"

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />
<MyCard CardColor="#004" />
<MyCard CardColor="#040" />
<MyCard CardColor="#800" />

@code {
}

And the result:

SyncFusion version:

Here's a "sort of working" Syncfusion version - I got fed up hoop jumping to get it fully installed!

@using Syncfusion.Blazor.Cards
<SfCard id="@UID" CssClass="@NavigateUri">
    <CardHeader Title="@Title">
        <span class="fa fa-@CardIcon test-icon" aria-hidden="true"></span>
    </CardHeader>
    <CardContent Content="@Content" />
</SfCard>

<style>
    @css {
        background: @CardColor;
    }

</style>

@code {
    [Parameter]
    public string Title { get; set; } = "Hello";

    [Parameter]
    public string Content { get; set; } = "Hello Blazor";

    [Parameter]
    public string NavigateUri { get; set; } = string.Empty;

    [Parameter]
    public string CardColor { get; set; } = string.Empty;

    [Parameter]
    public string CardIcon { get; set; } = string.Empty;

    public string UID = $"xx-{Guid.NewGuid().ToString()}";

    private string css => $"#{UID} .e-card-header";
}

And running that shows the background color changes:


问:
Why does removing FetchData.razor from a default Blazor WASM project cause it to fail in Azure App Services?
I am trying to publish a hosted Blazor WASM to an Azure App Service. I am working with VS 2019 and .NET 5.0 (VS 2019 says it cannot support .NET 6.0). I create a default hosted Blazor WASM through the VS UI, and when I publish the Server project to a new Azure App Service (all default settings), everything runs ok.

However, when I remove the FetchData.razor component and republish, I get the following error in my console:

Uncaught (in promise) Can't find bindings module assembly:
System.Private.Runtime.InteropServices.JavaScript blazor.webassembly.js:1

I am completely confused as to why this error happens when a razor page is removed from the project. I searched the project and it isn't referenced anywhere else. When I add the page back and republish suddenly it is working again. Running the app locally with 'dotnet watch run' works perfectly fine.

If anyone is also able to replicate this or has any ideas on how to fix it I would greatly appreciate it.

答:
Just throwing an idea, you deleted fetchdata.razor file but still there might be a reference of this in file NavMenu.razor, like this

```<code> <div class="nav-item px-3">
            <NavLink class="nav-link" href="fetchdata">
                <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
            </NavLink>
 </div>
</code>```

So try removing above code form you project and see if it's all good!

Body:
Just throwing an idea, you deleted fetchdata.razor file but still there might be a reference of this in file NavMenu.razor, like this

 <div class="nav-item px-3">
            <NavLink class="nav-link" href="fetchdata">
                <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
            </NavLink>
 </div>

So try removing above code form you project and see if it's all good!


问:
Nested object in React functional component state with Typescript
I have an nested object in React functional component state, but I only can access first level of object if I use any type.

```<code>export default function Detail() {
    const [user, setUser] = useState<any>({});
    const { id } = useParams();

    useEffect(() => {
        fetch('http://localhost:4000/users/' + id)
        .then(response => {
            return response.json();
        })
        .then(data => {
            setUser(data);
        })
    }, []);

    return (
        <div>
            <h1>Detail view</h1>
            <p>ID: { user.id }</p>
            <p>First name: { user.first_name }</p>
            <p>Last name: { user.last_name }</p>
            <p>Email: { user.email }</p>
            <p>Gender: { user.gender }</p>
        </div>
    );
}
</code>```

When trying to access user.company.name it throws

```<code>Detail.tsx:40 Uncaught TypeError: Cannot read properties of undefined (reading 'name')
</code>```

I made an interface for it, but it gives me an error if I'm trying to use it for state type.

```<code>interface UserInfo {
    id: number;
    first_name: string;
    last_name: string;
    email: string;
    gender: string;
    company: {
        name: string;
        department: string;
    }
}
</code>```
```<code>Argument of type '{}' is not assignable to parameter of type 'UserInfo | (() => UserInfo)'.
</code>```

How can I use defined interface as state type?

答:
Don't use the any type. TypeScript can't help you if you don't use actual types. Type the state narrowly.

Don't use an empty object as your default value. It isn't useful. Use a value that clearly indicates that the data isn't available yet.

```<code>type PossibleUserInfo = UserInfo | null;

const [user, setUser] = useState<PossibleUserInfo>(null);
</code>```

Then, handle the case where you don't have the data yet explicitly.

It isn't useful to spit out a div with a bunch of paragraphs containing a label but not data.

```<code>if (user) {
    return (
        <div>
            <h1>Detail view</h1>
            <p>ID: { user.id }</p>
            <p>First name: { user.first_name }</p>
            <p>Last name: { user.last_name }</p>
            <p>Email: { user.email }</p>
            <p>Gender: { user.gender }</p>
        </div>
    );
}

return (
    <div>
        <h1>Default view</h1>
        <Loading />
    </div>
);
</code>```

… where Loading is a component that shows (for example) a loading spinner.

Body:
I have an nested object in React functional component state, but I only can access first level of object if I use any type.

export default function Detail() {
    const [user, setUser] = useState<any>({});
    const { id } = useParams();

    useEffect(() => {
        fetch('http://localhost:4000/users/' + id)
        .then(response => {
            return response.json();
        })
        .then(data => {
            setUser(data);
        })
    }, []);

    return (

Detail view

ID: { user.id }

First name: { user.first_name }

Last name: { user.last_name }

Email: { user.email }

Gender: { user.gender }

    );
}

When trying to access user.company.name it throws

Detail.tsx:40 Uncaught TypeError: Cannot read properties of undefined (reading 'name')

I made an interface for it, but it gives me an error if I'm trying to use it for state type.

interface UserInfo {
    id: number;
    first_name: string;
    last_name: string;
    email: string;
    gender: string;
    company: {
        name: string;
        department: string;
    }
}

Argument of type '{}' is not assignable to parameter of type 'UserInfo | (() => UserInfo)'.

How can I use defined interface as state type?

Body:
Don't use the any type. TypeScript can't help you if you don't use actual types. Type the state narrowly.

Don't use an empty object as your default value. It isn't useful. Use a value that clearly indicates that the data isn't available yet.

type PossibleUserInfo = UserInfo | null;

const [user, setUser] = useState<PossibleUserInfo>(null);

Then, handle the case where you don't have the data yet explicitly.

It isn't useful to spit out a div with a bunch of paragraphs containing a label but not data.

if (user) {
    return (
        <div>
            <h1>Detail view</h1>
            <p>ID: { user.id }</p>
            <p>First name: { user.first_name }</p>
            <p>Last name: { user.last_name }</p>
            <p>Email: { user.email }</p>
            <p>Gender: { user.gender }</p>
        </div>
    );
}

return (
    <div>
        <h1>Default view</h1>
        <Loading />
    </div>
);

… where Loading is a component that shows (for example) a loading spinner.


问:
Why can the as operator be used with Nullable<T>?
According to the documentation of the as operator, as "is used to perform certain types of conversions between compatible reference types".  Since Nullable is actually a value type, I would expect as not to work with it.  However, this code compiles and runs:

```<code>object o = 7;
int i = o as int? ?? -1;
Console.WriteLine(i); // output: 7
</code>```

Is this correct behavior?  Is the documentation for as wrong?  Am I missing something?

答:
From the documentation about the as keyword:

It is equivalent to the following expression except that expression is evaluated only one time.

expression is type ? (type)expression : (type)null

The reference for is use also states it works with reference types, however, you can also do stuff like this:

```<code>int? temp = null;
if (temp is int?)
{
    // Do something
}
</code>```

I'm guessing it is just an inaccuracy in the reference documentation in that the type must be nullable (ie a nullable type or a reference type) instead of just a reference type.

Body:
According to the documentation of the as operator, as "is used to perform certain types of conversions between compatible reference types".  Since Nullable is actually a value type, I would expect as not to work with it.  However, this code compiles and runs:

object o = 7;
int i = o as int? ?? -1;
Console.WriteLine(i); // output: 7

Is this correct behavior?  Is the documentation for as wrong?  Am I missing something?

Body:
From the documentation about the as keyword:

It is equivalent to the following expression except that expression is evaluated only one time.

expression is type ? (type)expression : (type)null

The reference for is use also states it works with reference types, however, you can also do stuff like this:

int? temp = null;
if (temp is int?)
{
    // Do something
}

I'm guessing it is just an inaccuracy in the reference documentation in that the type must be nullable (ie a nullable type or a reference type) instead of just a reference type.


问:
Error on line 13, column 5 of pubspec.yaml: A dependency may only have one source
I am getting an error while downloading packages in Dart Flutter. In the pubspec.yaml file, I added the following package:

```<code>dependencies:
  flutter:
    sdk: flutter
    flutter_easyloading: ^3.0.3
  cupertino_icons: ^1.0.2
</code>```

The package I want to install is flutter_easyloading.

I press the "Get packages" button in Visual Studio code and I get this error:

```<code>[flutterapppproject] flutter pub get
Running "flutter pub get" in flutterapppproject...
Error on line 13, column 5 of pubspec.yaml: A dependency may only have one source.
   ╷
13 │ ┌     sdk: flutter
14 │ │     shared_preferences: v0.4.2
15 │ │     flutter_easyloading: ^3.0.3
16 │ └
   ╵
pub get failed (65;    ╵)
exit code 65
</code>```

All codes:

```<code>name: flutterapppproject
description: A new Flutter project.

publish_to: 'none'

version: 1.0.0+1

environment:
  sdk: ">=2.15.1 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
    flutter_easyloading: ^3.0.3
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^1.0.0

flutter:
  uses-material-design: true
</code>```

答:
```<code>name: flutterapppproject
description: A new Flutter project.

publish_to: 'none'

version: 1.0.0+1

environment:
  sdk: ">=2.15.1 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  flutter_easyloading: ^3.0.3 // Changed the indentation here
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^1.0.0

flutter:
  uses-material-design: true
</code>```

The issue seems to be with your indentation. Use the updated code and try making a flutter pub get

Body:
I am getting an error while downloading packages in Dart Flutter. In the pubspec.yaml file, I added the following package:

dependencies:
  flutter:
    sdk: flutter
    flutter_easyloading: ^3.0.3
  cupertino_icons: ^1.0.2

The package I want to install is flutter_easyloading.

I press the "Get packages" button in Visual Studio code and I get this error:

[flutterapppproject] flutter pub get
Running "flutter pub get" in flutterapppproject...
Error on line 13, column 5 of pubspec.yaml: A dependency may only have one source.
   ╷
13 │ ┌     sdk: flutter
14 │ │     shared_preferences: v0.4.2
15 │ │     flutter_easyloading: ^3.0.3
16 │ └
   ╵
pub get failed (65;    ╵)
exit code 65

All codes:

name: flutterapppproject
description: A new Flutter project.

publish_to: 'none'

version: 1.0.0+1

environment:
  sdk: ">=2.15.1 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
    flutter_easyloading: ^3.0.3
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^1.0.0

flutter:
  uses-material-design: true

Body:
name: flutterapppproject
description: A new Flutter project.

publish_to: 'none'

version: 1.0.0+1

environment:
  sdk: ">=2.15.1 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  flutter_easyloading: ^3.0.3 // Changed the indentation here
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^1.0.0

flutter:
  uses-material-design: true

The issue seems to be with your indentation. Use the updated code and try making a flutter pub get


问:
Where is the logical 'or' equivalent in the 'operator' module?
Adding or multiplying  a large list of numbers in Python can elegantly be done by folding the list with the addition or multiplication operator:

```<code>import functools, operator
lst = range(1,100)
sum  = functools.reduce(operator.add, lst)
prod = functools.reduce(operator.mul, lst)
</code>```

This needs the function equivalents of the operators + and * which
are provided by the operator module as operator.add and
operator.mul, respectively.

If I want to use the same idiom with the operator or:

```<code>ingredients       = ['onion', 'celery', 'cyanide', 'chicken stock']
soup_is_poisonous = functools.reduce(operator.or, map(is_poisonous, ingredients))
</code>```

... then I discover that operator doesn't have a function equivalent of the logical and and or operators (though it has one for logical not)

Of course, I can trivially write one that works:

```<code>def operator_or(x,y):
  return x or y
</code>```

But I wonder: why are there no operator.or and operator.and in operator? Bitwise and and or are there, but not the logical ones.

Of course this is just a minor annoyance, and the answer may well be
the same as with the missing identity function:
that it is easy to write one. But this holds for * and + as well, so why the difference?

答:
To wrap up all your helpful answers
and comments, in order of somewhat decreasing (to me) convincingness:

the addition of operator.or would break an important promise made by the module

For all operators <op> that have function equivalents
operator.op in the operator module, it is the case that a <op> b is equivalent to (i.e. can always, without changing program
behaviour, replace or be replaced by) operator.op(a, b). This
equivalence is actually mentioned in the module docstring.  This is
impossible to do for the operators and and or as their
evaluation is short-circuiting while Python function calls are always evaluated after  all of their arguments are.

On the values True and False, | and &, hence also the existing (bitwise) operator.and_ and operator.or_
already return the same results (if they return at all, that is) as or and and.

If is_poisonous() returns either True of False (not an unreasonable requirement), I could use

```<code>soup_is_poisonous = reduce(operator.or_, map(is_poisonous, ingredients), False)
</code>```

in the example from the original question. However, many Python
programs conveniently use any "truthy" value as True in idioms like

```<code>your_model_T_color = "black" or any_color_you_like
</code>```

using | or operator.or_ instead of or here will result in a
TypeError or, even worse, some unexpected value (if the operands
are ints)

The functions any and all can be used instead of
functools.reduce(operator.or, ....)

I'm not convinced by this
argument: operator functions are used in many more contexts than
as a first argument to reduce. Moreover, any always returns
either True or False, not the first truthy value:

```<code>any([0,0,0,5,6,7]) # returns True
reduce(lambda x, y: x or y, [0,0,0,5,6,7]) # returns 5
</code>```

so any and reduce(operator.or would not really be equivalent

any([x,y]) does the same (and more, as it accepts iterables) as operator.or(x,y) would.

That is not quite true (see above), any([0,5]) returns True while operator.or(0,5) would return 5. Moreover, the number of arguments matters greatly if we use a function as an argument to another function like  reduce()

Body:
Adding or multiplying  a large list of numbers in Python can elegantly be done by folding the list with the addition or multiplication operator:

import functools, operator
lst = range(1,100)
sum  = functools.reduce(operator.add, lst)
prod = functools.reduce(operator.mul, lst)

This needs the function equivalents of the operators + and * which
are provided by the operator module as operator.add and
operator.mul, respectively.

If I want to use the same idiom with the operator or:

ingredients       = ['onion', 'celery', 'cyanide', 'chicken stock']
soup_is_poisonous = functools.reduce(operator.or, map(is_poisonous, ingredients))

... then I discover that operator doesn't have a function equivalent of the logical and and or operators (though it has one for logical not)

Of course, I can trivially write one that works:

def operator_or(x,y):
  return x or y

But I wonder: why are there no operator.or and operator.and in operator? Bitwise and and or are there, but not the logical ones.

Of course this is just a minor annoyance, and the answer may well be
the same as with the missing identity function:
that it is easy to write one. But this holds for * and + as well, so why the difference?

Body:
To wrap up all your helpful answers
and comments, in order of somewhat decreasing (to me) convincingness:

the addition of operator.or would break an important promise made by the module

For all operators <op> that have function equivalents
operator.op in the operator module, it is the case that a <op> b is equivalent to (i.e. can always, without changing program
behaviour, replace or be replaced by) operator.op(a, b). This
equivalence is actually mentioned in the module docstring.  This is
impossible to do for the operators and and or as their
evaluation is short-circuiting while Python function calls are always evaluated after  all of their arguments are.

On the values True and False, | and &, hence also the existing (bitwise) operator.and_ and operator.or_
already return the same results (if they return at all, that is) as or and and.

If is_poisonous() returns either True of False (not an unreasonable requirement), I could use

soup_is_poisonous = reduce(operator.or_, map(is_poisonous, ingredients), False)

in the example from the original question. However, many Python
programs conveniently use any "truthy" value as True in idioms like

your_model_T_color = "black" or any_color_you_like

using | or operator.or_ instead of or here will result in a
TypeError or, even worse, some unexpected value (if the operands
are ints)

The functions any and all can be used instead of
functools.reduce(operator.or, ....)

I'm not convinced by this
argument: operator functions are used in many more contexts than
as a first argument to reduce. Moreover, any always returns
either True or False, not the first truthy value:

any([0,0,0,5,6,7]) # returns True
reduce(lambda x, y: x or y, [0,0,0,5,6,7]) # returns 5

so any and reduce(operator.or would not really be equivalent

any([x,y]) does the same (and more, as it accepts iterables) as operator.or(x,y) would.

That is not quite true (see above), any([0,5]) returns True while operator.or(0,5) would return 5. Moreover, the number of arguments matters greatly if we use a function as an argument to another function like  reduce()


问:
Saving to .png from an array gives glitchy results
Not a big question,
This is the code:

```<code>def rgb_to_png(rgb, path):
    rgbarray = np.array([np.array([x for x in i]) for i in rgb])
    rgbimage = PIL.Image.fromarray(rgbarray, "RGB")

    rgbimage.save(path+"\sample.png", "PNG", quality=100)
</code>```

This is what it's supposed to look like:
Image1

And this is what the code outputs:
Output

It seems that it's saving each rgb value as a single pixel or something similar, but I don't get what's wrong in the code. What is happening in there?

(Note: Both pictures resolution is 128 by 128)

答:
You need to specify the type of your Numpy arrays as you create them, else they will not be unsigned 8-bit like PIL expects:

```<code>rgbarray = np.array(..., np.uint8)
</code>```

You can check yours with:

```<code>print(rgbarray.dtype)
</code>```

Also, the last 2 parameters of your Image.save() are superfluous.

Body:
Not a big question,
This is the code:

def rgb_to_png(rgb, path):
    rgbarray = np.array([np.array([x for x in i]) for i in rgb])
    rgbimage = PIL.Image.fromarray(rgbarray, "RGB")

    rgbimage.save(path+"\sample.png", "PNG", quality=100)

This is what it's supposed to look like:
Image1

And this is what the code outputs:
Output

It seems that it's saving each rgb value as a single pixel or something similar, but I don't get what's wrong in the code. What is happening in there?

(Note: Both pictures resolution is 128 by 128)

Body:
You need to specify the type of your Numpy arrays as you create them, else they will not be unsigned 8-bit like PIL expects:

rgbarray = np.array(..., np.uint8)

You can check yours with:

print(rgbarray.dtype)

Also, the last 2 parameters of your Image.save() are superfluous.


问:
GraphQL (Apollo), Sequelize, MySQL & using non-standard foreign keys
I am working on a GraphQL server with Apollo, Sequelize, Node and MySQL. The data consists of videos and teams (in those videos). I am also using non-standard foreign keys to connect teams to a specific video (database table Teams has a field called 'inVideo' instead of the default 'VideoId' one). Creating videos and teams as well as querying specific ones (with id) or all items is not a problem. However, when I am trying to query teams belonging to a specific video (by providing the id of the specific video) the SQL SELECT query on the backend contains an additional field name, which is the default foreign key construct 'VideoId", and as that field does not exist on the database, the query fails.

Here is the migration file to create the Teams table (note the inVideo-field definition):

```<code>'use strict';
module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('Teams', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      inVideo: {
        allowNull: false,
        type: Sequelize.INTEGER
      },
      name: {
        allowNull: false,
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('Teams');
  }
};
</code>```

Here is the team model definition for Sequelize (note the foreignKey definition in belongsTo)

```<code>'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Team extends Model {
    static associate(models) {
      Team.belongsTo(models.Video, { foreignKey: "inVideo" })
    }
  }
  Team.init({
    name: {
      allowNull: false,
      type: DataTypes.STRING
    }
  }, {
    sequelize,
    modelName: 'Team',
  });
  return Team;
};
</code>```

There is nothing special in the migration file for generating video table in the database, but here is the Sequelize model file for video (as I added the hasMany relationship in that model):

```<code>'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Video extends Model {
    static associate(models) {
      Video.hasMany(models.Team)
    }
  }
  Video.init({
    videoUrl: {
      allowNull: false,
      type: DataTypes.STRING
    }
  }, {
    sequelize,
    modelName: 'Video',
  });
  return Video;
};
</code>```

Then the GraphQL schema definition

```<code>const { gql } = require('apollo-server');
const typeDefs = gql`
  type Video {
    id: Int!
    videoUrl: String!
    teams: [Team!]!
  }

  type Team {
    id: Int!
    name: String!
    video: Video!
  }

  type Query {
    teams(inVideo: Int!): [Team!]!
  }

  type Mutation {
    createVideo(videoUrl: String!): Video!
    createTeam(inVideo: Int!, name: String!): Team!
  }
`;
module.exports = typeDefs;
</code>```

And finally the resolver definitions for the server:

```<code>const resolvers = {
  Query: {
    async teams(root, { inVideo }, { models }) {
      return models.Team.findAll({
        where: {
          inVideo: inVideo
        }
      });
    },
  },
  Mutation: {
    async createVideo(root, { videoUrl }, { models }) {
      return models.Video.create({ videoUrl });
    },
    async createTeam( root, { inVideo, name }, { models }) {
      return models.Team.create({ inVideo, name });
    },
  },
  Video: {
    async teams(video) {
      return video.getTeams();
    },
  },
  Team: {
    async video(team) {
      return team.getVideo();
    },
  },
};
module.exports = resolvers;
</code>```

As noted, creating the videos and teams works ok, and the data in the database is correct. However when I try to query the server to get the teams for a certain video, the SQL SELECT clause is as follows:

```<code>SELECT `id`, `name`, `createdAt`, `updatedAt`, `inVideo`, `VideoId` FROM `Teams` AS `Team` WHERE `Team`.`inVideo` = 1;
</code>```

The VideoId field should not be in there, as it does not exist in the database (the relation information is stored in the field inVideo).

How can I get rid of this behavior? (I thought that the foreignKey option in the belongsTo method call takes care of this)

Also, my way of defining the relation / querying teams using the relation (using where-option for findAll) might be incorrect. Is there a better way to do this?

答:
When you use your own explicit foreign key field don't forget to indicate it for associations on both ends:

Video.hasMany(models.Team, { foreignKey: "inVideo" })
```

Otherwise, Sequelize will use the default foreign key name ModelName+Id (VideoId in this case).

Body:
I am working on a GraphQL server with Apollo, Sequelize, Node and MySQL. The data consists of videos and teams (in those videos). I am also using non-standard foreign keys to connect teams to a specific video (database table Teams has a field called 'inVideo' instead of the default 'VideoId' one). Creating videos and teams as well as querying specific ones (with id) or all items is not a problem. However, when I am trying to query teams belonging to a specific video (by providing the id of the specific video) the SQL SELECT query on the backend contains an additional field name, which is the default foreign key construct 'VideoId", and as that field does not exist on the database, the query fails.

Here is the migration file to create the Teams table (note the inVideo-field definition):

'use strict';
module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('Teams', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      inVideo: {
        allowNull: false,
        type: Sequelize.INTEGER
      },
      name: {
        allowNull: false,
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('Teams');
  }
};

Here is the team model definition for Sequelize (note the foreignKey definition in belongsTo)

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Team extends Model {
    static associate(models) {
      Team.belongsTo(models.Video, { foreignKey: "inVideo" })
    }
  }
  Team.init({
    name: {
      allowNull: false,
      type: DataTypes.STRING
    }
  }, {
    sequelize,
    modelName: 'Team',
  });
  return Team;
};

There is nothing special in the migration file for generating video table in the database, but here is the Sequelize model file for video (as I added the hasMany relationship in that model):

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Video extends Model {
    static associate(models) {
      Video.hasMany(models.Team)
    }
  }
  Video.init({
    videoUrl: {
      allowNull: false,
      type: DataTypes.STRING
    }
  }, {
    sequelize,
    modelName: 'Video',
  });
  return Video;
};

Then the GraphQL schema definition

const { gql } = require('apollo-server');
const typeDefs = gql`
  type Video {
    id: Int!
    videoUrl: String!
    teams: [Team!]!
  }

  type Team {
    id: Int!
    name: String!
    video: Video!
  }

  type Query {
    teams(inVideo: Int!): [Team!]!
  }

  type Mutation {
    createVideo(videoUrl: String!): Video!
    createTeam(inVideo: Int!, name: String!): Team!
  }
`;
module.exports = typeDefs;

And finally the resolver definitions for the server:

const resolvers = {
  Query: {
    async teams(root, { inVideo }, { models }) {
      return models.Team.findAll({
        where: {
          inVideo: inVideo
        }
      });
    },
  },
  Mutation: {
    async createVideo(root, { videoUrl }, { models }) {
      return models.Video.create({ videoUrl });
    },
    async createTeam( root, { inVideo, name }, { models }) {
      return models.Team.create({ inVideo, name });
    },
  },
  Video: {
    async teams(video) {
      return video.getTeams();
    },
  },
  Team: {
    async video(team) {
      return team.getVideo();
    },
  },
};
module.exports = resolvers;

As noted, creating the videos and teams works ok, and the data in the database is correct. However when I try to query the server to get the teams for a certain video, the SQL SELECT clause is as follows:

SELECT `id`, `name`, `createdAt`, `updatedAt`, `inVideo`, `VideoId` FROM `Teams` AS `Team` WHERE `Team`.`inVideo` = 1;

The VideoId field should not be in there, as it does not exist in the database (the relation information is stored in the field inVideo).

How can I get rid of this behavior? (I thought that the foreignKey option in the belongsTo method call takes care of this)

Also, my way of defining the relation / querying teams using the relation (using where-option for findAll) might be incorrect. Is there a better way to do this?

Body:
When you use your own explicit foreign key field don't forget to indicate it for associations on both ends:

Video.hasMany(models.Team, { foreignKey: "inVideo" })

Otherwise, Sequelize will use the default foreign key name ModelName+Id (VideoId in this case).


问:
Paste code from Python into Word (Macbook)
I want to paste the code I wrote in Python into a Word document. I have a Macbook. I don't want the code to lose its formatting (indentations and colors).
I have already tried it via Insert/Text/Object and with the programs Sublime Text and Atom, unfortunately without success.</p>

答: It seems that Visual Studio Code can copy text with code highlighting, but I don't recommend it. In this case, I think it's best to just post a screenshot to your Word document.</p>


问:
How can I change to the dark mode?
How can I change to the dark mode in SAS9.4

All the videos I found are about prior versions of SAS and not this version.

Thanks in advance

答:
In SAS for Windows, you can edit the colour scheme.

For SAS Studio, you can download an extension, e.g. Dark Reader for Chrome.

Title: How can I change to the dark mode?


问:
Flutter show/hide widget
I'm trying to show a widget onFinished countdown timer but I can't seem to make it work.
I've added var reqPIN = false;

And here is my code:

```<code>        children [
         Countdown(
            seconds: 3,
            build: (_, double time) =>
                RichText(
                  text: TextSpan(
                    text: 'Reset PIN in ',
                    style: TextStyle(
                      color: Theme.of(context).inputDecorationTheme.labelStyle?.color
                    ),
                    children: <TextSpan>[
                      TextSpan(
                        text: time.toString(),
                      style: TextStyle(
                        color: Color(0xFF2481CF),
                        fontWeight: FontWeight.bold
                      )),
                      TextSpan(text: ' sec',
                      style: TextStyle(
                        color: Theme.of(context).inputDecorationTheme.labelStyle?.color
                      ))
                    ]
                  ),
                ),
            onFinished: () {
              setState(() {
                reqPIN = true;
              });
            },
          ),
          SizedBox(
            child: Visibility(
              visible: reqPIN,
              child: Text('Resend PIN',
              style: TextStyle(
                color: Colors.black
              ),),
            ),
          )
        ]
</code>```

Is there any solution?

答:
onlySelectedBorderPinPut() is not getting called on setState...

to fix this, you can wrap your RichText with a Column, and add your Resend button there, you won't need to have a reqPin bool for managing the state, simply handle it with the remaining time like below

Countdown(
  seconds: 3,
  build: (_, double time) => Column(
    children: [
       RichText(
       ...
       ),
       Visibility(
          visible: time == 0,
          child: SizedBox(
                   child: Text('Resend PIN',
                   style: TextStyle(color: Colors.black
                 )
              ),
           ),
         ),
      ],
   ),
),
```

Title: Flutter show/hide widget

Body:
I'm trying to show a widget onFinished countdown timer but I can't seem to make it work.
I've added var reqPIN = false;

And here is my code:

        children [
         Countdown(
            seconds: 3,
            build: (_, double time) =>
                RichText(
                  text: TextSpan(
                    text: 'Reset PIN in ',
                    style: TextStyle(
                      color: Theme.of(context).inputDecorationTheme.labelStyle?.color
                    ),
                    children: <TextSpan>[
                      TextSpan(
                        text: time.toString(),
                      style: TextStyle(
                        color: Color(0xFF2481CF),
                        fontWeight: FontWeight.bold
                      )),
                      TextSpan(text: ' sec',
                      style: TextStyle(
                        color: Theme.of(context).inputDecorationTheme.labelStyle?.color
                      ))
                    ]
                  ),
                ),
            onFinished: () {
              setState(() {
                reqPIN = true;
              });
            },
          ),
          SizedBox(
            child: Visibility(
              visible: reqPIN,
              child: Text('Resend PIN',
              style: TextStyle(
                color: Colors.black
              ),),
            ),
          )
        ]

Is there any solution?