问:
Keycodes / onclick enter, show Multiple innerHTML names
When I move the 4 arrows on the keyboard, the green hover color moves over each button. I want when I press "Enter" to write the number that corresponds to each box. For example now I have "columns" and it writes 0,1,2,3,4,5,6. I want to write One Two Three etc .. Of course I use Handebars, Backcone, Lodash so I do not want to change anything in HTML (Handlebars.compile) Thank you very much ..

var columns = 0;
var rowButtons = 0;

var $rows = $('.multiple');
var liSelected;

var arrows = {
    left: 37,
    up: 38,
    right: 39,
    down: 40,
    enter: 13
    };

$(window).keydown(function(e) {
  if (Object.values(arrows).indexOf(e.which) > -1) {
    e.preventDefault();
    $('.multiple li').removeClass('selected');

switch (e.which) {
  case arrows.up:
    rowButtons = rowButtons == 0 ? $rows.length - 1 : rowButtons - 1;
    break;

  case arrows.down:
    rowButtons = rowButtons == $rows.length - 1 ? 0 : rowButtons + 1;
    break;

  case arrows.left:
    $buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
    columns = columns == 0 ? $buttonsInRow.length - 1 : columns - 1;
    break;

  case arrows.right:
    $buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
    columns = columns == $buttonsInRow.length - 1 ? 0 : columns + 1;
    break;

case arrows.enter:
// find the column and row position:
$buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
var position = (rowButtons * 6 ) + columns + 1;
 rowButtons = rowButtons == $rows.click;

 document.getElementById('screen').innerHTML = columns;

break;
     }

    buttonSelected = $('.multiple:eq(' + rowButtons + ') li:eq(' + columns + ')');
    buttonSelected.addClass('selected');
}
});

// Click function on handlebars
// Affect href ie.  (It doesn't work on enter(13)
var ListView = BacListViewkbone.View.extend({
events: {
'click a': 'onClick'
},
render: function() {
var rawHTML = _template({ items: myList });
this.$el.html(rawHTML);
this.$items = this.$el.find('a');
return this;
},

onClick: function(e) {
var id = $(e.currentTarget).attr('patterns');
dispatcher.trigger(dispatcher.EventKeys.PATTERNS_SELECTED, myList[id]);
}
});
function init(options) {
dispatcher.register(evs);
new ListView(options).render();
}

return {
init: init
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li.selected {
  background: green;
}

.multiple, .allRows li{
    text-align:center;
    position:relative;
    display: flex;
    flex-wrap: nowrap;
}

.allRows a {
  text-decoration:none;
  padding: 3px;
  border: 1px solid #555;
  color: #222;
  margin: 0px;
  text-align: center;
  font-size:20px;

}

#screen {
  background:#222;
  color:#ddd;
  position:absolute;
  top: 100px;
  padding:30px 150px;
}</code>```

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

Eleven

href="#" patterns="twelve" id="twelve" onClick="twelve()">Twelve

Numbers
```

答:
I've simplified your code to do exactly what you want. Try this

$(window).keydown(function(e) {
    if( [37, 38, 39, 40, 13].includes(e.which) ){
        e.preventDefault();

        let $col     = $('.multiple li.selected');
        let $row     = $col.closest('.multiple');
        let $nextCol = $col;
        let $nextRow = $row;

        if( [37, 38, 39, 40].includes(e.which) && $col.length === 0 ){
            $('.multiple:first-child').find('li:first').addClass('selected');
            return;
        }

        switch (e.which) {
            case 38: // up key
                $nextRow = $row.is(':first-child') ? $row.siblings(":last-child") : $row.prev();
                break;

            case 40: // down key
                $nextRow = $row.is(':last-child') ? $row.siblings(":first-child") : $row.next();
                break;

            case 37: // left key
                $nextCol = $col.is(':first-child') ? $col.siblings(":last-child") : $col.prev();
                break;

            case 39: // right key
                $nextCol = $col.is(':last-child') ? $col.siblings(":first-child") : $col.next();
                break;
            case 13: // enter key
                if($col.length > 0) $('#screen').text($col.find('a').trigger('click').text());
                break;
        }

        $('.multiple li').removeClass('selected');
        $nextRow.find('li').eq($nextCol.index()).addClass('selected');
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li.selected {
  background: green;
}

.multiple, .allRows li{
    text-align:center;
    position:relative;
    display: flex;
    flex-wrap: nowrap;
}

.allRows a {
  text-decoration:none;
  padding: 3px;
  border: 1px solid #555;
  color: #222;
  margin: 0px;
  text-align: center;
  font-size:20px;

}

#screen {
  background:#222;
  color:#ddd;
  position:absolute;
  top: 100px;
  padding:30px 150px;
}</code>```

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

Eleven

Twelve

Numbers
```

Body:
When I move the 4 arrows on the keyboard, the green hover color moves over each button. I want when I press "Enter" to write the number that corresponds to each box. For example now I have "columns" and it writes 0,1,2,3,4,5,6. I want to write One Two Three etc .. Of course I use Handebars, Backcone, Lodash so I do not want to change anything in HTML (Handlebars.compile) Thank you very much ..

var columns = 0;
var rowButtons = 0;

var $rows = $('.multiple');
var liSelected;

var arrows = {
    left: 37,
    up: 38,
    right: 39,
    down: 40,
    enter: 13
    };

$(window).keydown(function(e) {
  if (Object.values(arrows).indexOf(e.which) > -1) {
    e.preventDefault();
    $('.multiple li').removeClass('selected');

switch (e.which) {
  case arrows.up:
    rowButtons = rowButtons == 0 ? $rows.length - 1 : rowButtons - 1;
    break;

  case arrows.down:
    rowButtons = rowButtons == $rows.length - 1 ? 0 : rowButtons + 1;
    break;

  case arrows.left:
    $buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
    columns = columns == 0 ? $buttonsInRow.length - 1 : columns - 1;
    break;

  case arrows.right:
    $buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
    columns = columns == $buttonsInRow.length - 1 ? 0 : columns + 1;
    break;

case arrows.enter:
// find the column and row position:
$buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
var position = (rowButtons * 6 ) + columns + 1;
 rowButtons = rowButtons == $rows.click;

 document.getElementById('screen').innerHTML = columns;

break;
     }

    buttonSelected = $('.multiple:eq(' + rowButtons + ') li:eq(' + columns + ')');
    buttonSelected.addClass('selected');
}
});

// Click function on handlebars
// Affect href ie.  (It doesn't work on enter(13)
var ListView = BacListViewkbone.View.extend({
events: {
'click a': 'onClick'
},
render: function() {
var rawHTML = _template({ items: myList });
this.$el.html(rawHTML);
this.$items = this.$el.find('a');
return this;
},

onClick: function(e) {
var id = $(e.currentTarget).attr('patterns');
dispatcher.trigger(dispatcher.EventKeys.PATTERNS_SELECTED, myList[id]);
}
});
function init(options) {
dispatcher.register(evs);
new ListView(options).render();
}

return {
init: init
}

li.selected {
  background: green;
}

.multiple, .allRows li{
    text-align:center;
    position:relative;
    display: flex;
    flex-wrap: nowrap;
}

.allRows a {
  text-decoration:none;
  padding: 3px;
  border: 1px solid #555;
  color: #222;
  margin: 0px;
  text-align: center;
  font-size:20px;

}

#screen {
  background:#222;
  color:#ddd;
  position:absolute;
  top: 100px;
  padding:30px 150px;
}

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

Eleven

Twelve

Numbers

Body:
I've simplified your code to do exactly what you want. Try this

$(window).keydown(function(e) {
    if( [37, 38, 39, 40, 13].includes(e.which) ){
        e.preventDefault();

        let $col     = $('.multiple li.selected');
        let $row     = $col.closest('.multiple');
        let $nextCol = $col;
        let $nextRow = $row;

        if( [37, 38, 39, 40].includes(e.which) && $col.length === 0 ){
            $('.multiple:first-child').find('li:first').addClass('selected');
            return;
        }

        switch (e.which) {
            case 38: // up key
                $nextRow = $row.is(':first-child') ? $row.siblings(":last-child") : $row.prev();
                break;

            case 40: // down key
                $nextRow = $row.is(':last-child') ? $row.siblings(":first-child") : $row.next();
                break;

            case 37: // left key
                $nextCol = $col.is(':first-child') ? $col.siblings(":last-child") : $col.prev();
                break;

            case 39: // right key
                $nextCol = $col.is(':last-child') ? $col.siblings(":first-child") : $col.next();
                break;
            case 13: // enter key
                if($col.length > 0) $('#screen').text($col.find('a').trigger('click').text());
                break;
        }

        $('.multiple li').removeClass('selected');
        $nextRow.find('li').eq($nextCol.index()).addClass('selected');
    }
});

li.selected {
  background: green;
}

.multiple, .allRows li{
    text-align:center;
    position:relative;
    display: flex;
    flex-wrap: nowrap;
}

.allRows a {
  text-decoration:none;
  padding: 3px;
  border: 1px solid #555;
  color: #222;
  margin: 0px;
  text-align: center;
  font-size:20px;

}

#screen {
  background:#222;
  color:#ddd;
  position:absolute;
  top: 100px;
  padding:30px 150px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="allRows">
    <div class="multiple">
        <li><a href="#" patterns="one" id="one">One</a></li>
        <li><a href="#" patterns="two" id="two">Two</a></li>
        <li><a href="#" patterns="three" id="three">Three</a></li>
        <li><a href="#" patterns="four" id="four">Four</a></li>
        <li><a href="#" patterns="five" id="five">Five</a></li>
        <li><a href="#" patterns="six" id="six">Six</a></li>
    </div>
    <div class="multiple">
        <li><a href="#" patterns="seven" id="seven">Seven</a></li>
        <li><a href="#" patterns="eight" id="eight">Eight</a></li>
        <li><a href="#" patterns="nine" id="nine">Nine</a></li>
        <li><a href="#" patterns="ten" id="ten">Ten</a></li>
        <li><a href="#" patterns="eleven" id="eleven">Eleven</a></li>
        <li><a href="#" patterns="twelve" id="twelve">Twelve</a></li>
    </div>
</ul>

<div id="screen">Numbers</div>


来源: stackexchange

问:
How skip some line in R
I have many URLs which I import their text in R.
I use this code:

```<code>setNames(lapply(1:1000, function(x) gettxt(get(paste0("url", x)))), paste0("url", 1:1000, "_txt")) %>%
  list2env(envir = globalenv())
</code>```

However, some URLs can not import and show this error:

Error in file(con, "r") : cannot open the connection In addition:
Warning message: In file(con, "r") :   InternetOpenUrl failed: 'A
connection with the server could not be established'

So, my code doesn't run and doesn't import any text from any URL.
How can I recognize wrong URLs and skip them in other to import correct URLs?

答:
one possible aproach besides trycatch mentioned by @tester can be the purrr-package:

```<code>library(purrr)
# declare function
my_gettxt <- function(x) {
    gettxt(get(paste0("url", x)))
}
# make function error prone by defining the otherwise value (could be empty df with column defintion, etc.) used as output if function fails
my_gettxt <- purrr::possibly(my_gettxt , otherwise = NA)
# use map from purrr instead of apply function
my_data <- purrr::map(1:1000, ~my_gettxt(.x))
</code>```

ContentLicense: CC BY-SA 4.0

Title: How skip some line in R

Body:
I have many URLs which I import their text in R.
I use this code:

setNames(lapply(1:1000, function(x) gettxt(get(paste0("url", x)))), paste0("url", 1:1000, "_txt")) %>%
  list2env(envir = globalenv())

However, some URLs can not import and show this error:

Error in file(con, "r") : cannot open the connection In addition:
Warning message: In file(con, "r") :   InternetOpenUrl failed: 'A
connection with the server could not be established'

So, my code doesn't run and doesn't import any text from any URL.
How can I recognize wrong URLs and skip them in other to import correct URLs?

Body:
one possible aproach besides trycatch mentioned by @tester can be the purrr-package:

library(purrr)
# declare function
my_gettxt <- function(x) {
    gettxt(get(paste0("url", x)))
}
# make function error prone by defining the otherwise value (could be empty df with column defintion, etc.) used as output if function fails
my_gettxt <- purrr::possibly(my_gettxt , otherwise = NA)
# use map from purrr instead of apply function
my_data <- purrr::map(1:1000, ~my_gettxt(.x))


问:
How to create EditText accepts Alphabets only in android?
How can I enter only alphabets in EditText in android?</p>

答:
Just use the attribute android:inputType="text" in your xml file

EX:
if you want the user to provide an email address text:

```<code> <EditText
    android:id="@+id/user_address"
    android:inputType="textEmailAddress"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</code>```

feel free to check many other input attributes using android studio's autocomplete feature:

Auto complete Demo

ContentLicense: CC BY-SA 3.0

Body:
Just use the attribute android:inputType="text" in your xml file

EX:
if you want the user to provide an email address text:

 <EditText
    android:id="@+id/user_address"
    android:inputType="textEmailAddress"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

feel free to check many other input attributes using android studio's autocomplete feature:

Auto complete Demo


问:
Pushing Sign Up & Login buttons to bottom of sidebar
I am trying to recreate this design:

Click to view

However, the below is currently occurring.

Click to view

I am trying to push the SignUp and Login buttons to the bottom of the sidebar to match the first image. Am I missing a CSS class that would allow me to do so, or would this be a JS configuration? Hope I have not overlooked something basic that would allow me to achieve this state.

Sidebar.js

```<code>
import React from "react";
import "../App.css";
import { SidebarData } from './SidebarData'
import Logo from './Logo.svg'
import { Login } from './Login'
import { SignUp } from './SignUp'

function Sidebar() {
    return (
    <div className="Sidebar">
            <div className="Header">
        <div><img src = {Logo} alt='Logo’ className='Logo’ /></div>
            </div>
            <div class="line-break" />
           <ul className="SidebarList">
               {SidebarData.map((val, key) => {
                 return (
                  <li
                    key={key}
                    className="row"
                    id={window.location.pathname == val.link ? "active" : ""}
                    onClick={() => {
                        window.location.pathname = val.link;
                        }}
                    >
                      <div id="icon">{val.icon}</div> <div id="title">{val.title}</div>
                      </li>
               );
               })}

            </ul>
            <div class="line-break" />
<div className="footer">
            <ul className= "SidebarList">
                {Login.map((val, key) => {
                    return (
                        <li
                        key={key}
                        className="Login"
                        id={window.location.pathname == val.link ? "active" : ""}
                        onClick={() => {
                            window.location.pathname = val.link;
                        }}
                        >
                            <div id="title">{val.title}</div>
                        </li>
                    )}

                )}

                 </ul>

                 <ul className= "SidebarList">
                {SignUp.map((val, key) => {
                    return (
                        <li
                        key={key}
                        className="SignUp"
                        id={window.location.pathname == val.link ? "active" : ""}
                        onClick={() => {
                            window.location.pathname = val.link;
                        }}
                        >
                            <div id="title">{val.title}</div>
                        </li>
                    )}

                )}
                 </ul>
                 </div>
                 </div>
</code>```

Here is CSS

```<code>.App {
    width: 100vw;
    height: 100vh;
  }

  body {
    margin: 0;
    padding: 0;

  }

.Sidebar {
    height: 100%;
    width: 300px;
    background-color: white;
    border-right: 1px solid #F0F4FB;
    padding-left: 15px;
    box-sizing: border-box;

  }

  .SidebarList {
    height: auto;
    width: 100%;
    padding-left: 15px;
    font-size: 18px;
    border: 2px #FD954E;
    box-sizing: border-box

  }

  .SidebarList .row {
      width: 100%;
      height: 50px;
      background-color: white;
      list-style-type: none;
      margin: 0%;
      padding-bottom: 15px;
      display: flex;
      color: #A7ACB6;
      justify-content: center;
      align-items: center;
      font-family: Arial, Helvetica, sans-serif;

  }

.SidebarList .row:hover {
  cursor: pointer;
  background-color: #E7E7E7  ;
}

.SidebarList #active {
  background-color: white;
  color: #FD954E
}

.SidebarList .Login {
background-color: white;
color: #FD954E;
width: 90%;
height: 5vh;
right: 1596px;
top: 958px;
border: 1px solid #FD954E;
box-sizing: border-box;
border-radius: 19.5px;
text-align: center;
font-family: Arial, Helvetica, sans-serif
}

.SidebarList .SignUp {

  width: 90%;
  height: 5vh;
  right: 1596px;
  top: 1011px;

  background: #FD954E;
  border-radius: 19.5px;
  border: none;
  text-align: center;
  font-family: Arial, Helvetica, sans-serif;
  }

  .row #icon {
    flex: 30%;
    display: grid;
    place-items: center;
    transform: scale(1.2)

  }

  .row #title {
    flex: 70%;
  }

.Logo {
  padding-left: 25px;
  padding-top: 25px;
  padding-bottom: 30px;
  width: 55%;

}

.line-break {
  height: 1px;
  width: 100%;
  background-color: #F0F4FB;
}

ul.nav {
  list-style-type: none;
  padding: 20px 0 0 40px;
      list-style-type: none;

}

ul.nav li {
  margin-bottom: 14px;
  list-style-type: none;

}

ul.nav li:last-child {
  margin-bottom: 0;
  list-style-type: none;

}

.footer {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.footer button {
  padding: 6px 0;
  width: 80%;
  margin-bottom: 14px;
}

.footer button:last-child {
  margin-bottom: 0;
}

.header .Logo {
  height: 40px;
  width: 200px;
  background-color: grey;
  margin: 20px;
}

</code>```

答:
Without seeing the source for the entire page and not just a couple of the buttons, it is impossible to say for sure, but my guess would be the following is causing your problem:

.Sidebar {
    height: 100%;
    ...
}
```
<p>Setting <code>height: 100%</code> will only tell the sidebar to take up 100% of the space it needs for its content (or 100% of the height of its bounding container, depending on the <code>display</code> properties of both). I would recommend changing it to this to solve your problem:</p>
<pre class="lang-css prettyprint-override"><code>.Sidebar {
    min-height: 100vh;
    ...
}
</code>```

Body:
I am trying to recreate this design:

Click to view

However, the below is currently occurring.

Click to view

I am trying to push the SignUp and Login buttons to the bottom of the sidebar to match the first image. Am I missing a CSS class that would allow me to do so, or would this be a JS configuration? Hope I have not overlooked something basic that would allow me to achieve this state.

Sidebar.js

import React from "react";
import "../App.css";
import { SidebarData } from './SidebarData'
import Logo from './Logo.svg'
import { Login } from './Login'
import { SignUp } from './SignUp'

function Sidebar() {
    return (

               {SidebarData.map((val, key) => {
                 return (

 {
                        window.location.pathname = val.link;
                        }}
                    >

{val.icon}

{val.title}

               );
               })}

                {Login.map((val, key) => {
                    return (

 {
                            window.location.pathname = val.link;
                        }}
                        >

{val.title}

                    )}

                )}

                {SignUp.map((val, key) => {
                    return (

 {
                            window.location.pathname = val.link;
                        }}
                        >

{val.title}

                    )}

                )}

Here is CSS

.App {
    width: 100vw;
    height: 100vh;
  }

  body {
    margin: 0;
    padding: 0;

  }

.Sidebar {
    height: 100%;
    width: 300px;
    background-color: white;
    border-right: 1px solid #F0F4FB;
    padding-left: 15px;
    box-sizing: border-box;

  }

  .SidebarList {
    height: auto;
    width: 100%;
    padding-left: 15px;
    font-size: 18px;
    border: 2px #FD954E;
    box-sizing: border-box

  }

  .SidebarList .row {
      width: 100%;
      height: 50px;
      background-color: white;
      list-style-type: none;
      margin: 0%;
      padding-bottom: 15px;
      display: flex;
      color: #A7ACB6;
      justify-content: center;
      align-items: center;
      font-family: Arial, Helvetica, sans-serif;

  }

.SidebarList .row:hover {
  cursor: pointer;
  background-color: #E7E7E7  ;
}

.SidebarList #active {
  background-color: white;
  color: #FD954E
}

.SidebarList .Login {
background-color: white;
color: #FD954E;
width: 90%;
height: 5vh;
right: 1596px;
top: 958px;
border: 1px solid #FD954E;
box-sizing: border-box;
border-radius: 19.5px;
text-align: center;
font-family: Arial, Helvetica, sans-serif
}

.SidebarList .SignUp {

  width: 90%;
  height: 5vh;
  right: 1596px;
  top: 1011px;

  background: #FD954E;
  border-radius: 19.5px;
  border: none;
  text-align: center;
  font-family: Arial, Helvetica, sans-serif;
  }

  .row #icon {
    flex: 30%;
    display: grid;
    place-items: center;
    transform: scale(1.2)

  }

  .row #title {
    flex: 70%;
  }

.Logo {
  padding-left: 25px;
  padding-top: 25px;
  padding-bottom: 30px;
  width: 55%;

}

.line-break {
  height: 1px;
  width: 100%;
  background-color: #F0F4FB;
}

ul.nav {
  list-style-type: none;
  padding: 20px 0 0 40px;
      list-style-type: none;

}

ul.nav li {
  margin-bottom: 14px;
  list-style-type: none;

}

ul.nav li:last-child {
  margin-bottom: 0;
  list-style-type: none;

}

.footer {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.footer button {
  padding: 6px 0;
  width: 80%;
  margin-bottom: 14px;
}

.footer button:last-child {
  margin-bottom: 0;
}

.header .Logo {
  height: 40px;
  width: 200px;
  background-color: grey;
  margin: 20px;
}

Body:
Without seeing the source for the entire page and not just a couple of the buttons, it is impossible to say for sure, but my guess would be the following is causing your problem:

.Sidebar {
    height: 100%;
    ...
}

Setting height: 100% will only tell the sidebar to take up 100% of the space it needs for its content (or 100% of the height of its bounding container, depending on the display properties of both). I would recommend changing it to this to solve your problem:

.Sidebar {
    min-height: 100vh;
    ...
}


问:
How to Download/Upload Files from Azure Blob using Python in Spyder/Anaconda
I am new to Azure. I created a Blob Storage today. I am trying to run some Python code that I found online, to download files fro this Blob Container. Here is the code that I am testing.

```<code># download_blobs.py
# Python program to bulk download blob files from azure storage
# Uses latest python SDK() for Azure blob storage
# Requires python 3.6 or above
import os
from azure.storage.blob import BlobServiceClient, BlobClient
from azure.storage.blob import ContentSettings, ContainerClient

# IMPORTANT: Replace connection string with your storage account connection string
# Usually starts with DefaultEndpointsProtocol=https;...
MY_CONNECTION_STRING = "DefaultEndpointsProtocol=https;AccountName=ryanpythonstorage;AccountKey=my_account_key;EndpointSuffix=core.windows.net"

# Replace with blob container
MY_BLOB_CONTAINER = "ryanpythonstorage" #copied from Access Keys

# Replace with the local folder where you want files to be downloaded
LOCAL_BLOB_PATH = "C:\\Users\\ryans\\Desktop\\blob\\"

class AzureBlobFileDownloader:
  def __init__(self):
    print("Intializing AzureBlobFileDownloader")

    # Initialize the connection to Azure storage account
    self.blob_service_client =  BlobServiceClient.from_connection_string(MY_CONNECTION_STRING)
    self.my_container = self.blob_service_client.get_container_client(MY_BLOB_CONTAINER)

  def save_blob(self,file_name,file_content):
    # Get full path to the file
    download_file_path = os.path.join(LOCAL_BLOB_PATH, file_name)

    # for nested blobs, create local path as well!
    os.makedirs(os.path.dirname(download_file_path), exist_ok=True)

    with open(download_file_path, "wb") as file:
      file.write(file_content)

  def download_all_blobs_in_container(self):
    my_blobs = self.my_container.list_blobs()
    for blob in my_blobs:
      print(blob.name)
      bytes = self.my_container.get_blob_client(blob).download_blob().readall()
      self.save_blob(blob.name, bytes)

# Initialize class and upload files
azure_blob_file_downloader = AzureBlobFileDownloader()
azure_blob_file_downloader.download_all_blobs_in_container()
</code>```

Here is the result that I see when I run the code.

```<code>Intializing AzureBlobFileDownloader
Traceback (most recent call last):

  File "C:\Users\ryans\AppData\Local\Temp\ipykernel_14020\3010845424.py", line 37, in <module>
    azure_blob_file_downloader.download_all_blobs_in_container()

  File "C:\Users\ryans\AppData\Local\Temp\ipykernel_14020\3010845424.py", line 30, in download_all_blobs_in_container
    for blob in my_blobs:

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\core\paging.py", line 129, in __next__
    return next(self._page_iterator)

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\core\paging.py", line 76, in __next__
    self._response = self._get_next(self.continuation_token)

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\storage\blob\_list_blobs_helper.py", line 79, in _get_next_cb
    process_storage_error(error)

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\storage\blob\_shared\response_handlers.py", line 177, in process_storage_error
    exec("raise error from None")   # pylint: disable=exec-used # nosec

  File "<string>", line 1, in <module>

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\storage\blob\_list_blobs_helper.py", line 72, in _get_next_cb
    return self._command(

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\storage\blob\_generated\operations\_container_operations.py", line 1479, in list_blob_flat_segment
    map_error(status_code=response.status_code, response=response, error_map=error_map)

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\core\exceptions.py", line 105, in map_error
    raise error

ResourceNotFoundError: The specified container does not exist.
RequestId:4d2df1c1-a01e-008b-4209-21e493000000
Time:2022-02-13T18:44:14.1140999Z
ErrorCode:ContainerNotFound
Content: <?xml version="1.0" encoding="utf-8"?><Error><Code>ContainerNotFound</Code><Message>The specified container does not exist.
RequestId:4d2df1c1-a01e-008b-4209-21e493000000
Time:2022-02-13T18:44:14.1140999Z</Message></Error>
</code>```

Ultimately, I want to be able to do two things:

download files from my Blob to my local machine

upload files from my local machine to my Blob.

答:
The error message is that it cannot find the container. It could be:

A problem with rights (connection string)

A problem with the container name

In MY_CONNECTION_STRING and MY_BLOB_CONTAINER the name of your account and the name of your container is the same. If one of these is incorrect it would explain the error.

Body:
I am new to Azure. I created a Blob Storage today. I am trying to run some Python code that I found online, to download files fro this Blob Container. Here is the code that I am testing.

# download_blobs.py
# Python program to bulk download blob files from azure storage
# Uses latest python SDK() for Azure blob storage
# Requires python 3.6 or above
import os
from azure.storage.blob import BlobServiceClient, BlobClient
from azure.storage.blob import ContentSettings, ContainerClient

# IMPORTANT: Replace connection string with your storage account connection string
# Usually starts with DefaultEndpointsProtocol=https;...
MY_CONNECTION_STRING = "DefaultEndpointsProtocol=https;AccountName=ryanpythonstorage;AccountKey=my_account_key;EndpointSuffix=core.windows.net"

# Replace with blob container
MY_BLOB_CONTAINER = "ryanpythonstorage" #copied from Access Keys

# Replace with the local folder where you want files to be downloaded
LOCAL_BLOB_PATH = "C:\\Users\\ryans\\Desktop\\blob\\"

class AzureBlobFileDownloader:
  def __init__(self):
    print("Intializing AzureBlobFileDownloader")

    # Initialize the connection to Azure storage account
    self.blob_service_client =  BlobServiceClient.from_connection_string(MY_CONNECTION_STRING)
    self.my_container = self.blob_service_client.get_container_client(MY_BLOB_CONTAINER)

  def save_blob(self,file_name,file_content):
    # Get full path to the file
    download_file_path = os.path.join(LOCAL_BLOB_PATH, file_name)

    # for nested blobs, create local path as well!
    os.makedirs(os.path.dirname(download_file_path), exist_ok=True)

    with open(download_file_path, "wb") as file:
      file.write(file_content)

  def download_all_blobs_in_container(self):
    my_blobs = self.my_container.list_blobs()
    for blob in my_blobs:
      print(blob.name)
      bytes = self.my_container.get_blob_client(blob).download_blob().readall()
      self.save_blob(blob.name, bytes)

# Initialize class and upload files
azure_blob_file_downloader = AzureBlobFileDownloader()
azure_blob_file_downloader.download_all_blobs_in_container()

Here is the result that I see when I run the code.

Intializing AzureBlobFileDownloader
Traceback (most recent call last):

  File "C:\Users\ryans\AppData\Local\Temp\ipykernel_14020\3010845424.py", line 37, in <module>
    azure_blob_file_downloader.download_all_blobs_in_container()

  File "C:\Users\ryans\AppData\Local\Temp\ipykernel_14020\3010845424.py", line 30, in download_all_blobs_in_container
    for blob in my_blobs:

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\core\paging.py", line 129, in __next__
    return next(self._page_iterator)

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\core\paging.py", line 76, in __next__
    self._response = self._get_next(self.continuation_token)

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\storage\blob\_list_blobs_helper.py", line 79, in _get_next_cb
    process_storage_error(error)

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\storage\blob\_shared\response_handlers.py", line 177, in process_storage_error
    exec("raise error from None")   # pylint: disable=exec-used # nosec

  File "<string>", line 1, in <module>

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\storage\blob\_list_blobs_helper.py", line 72, in _get_next_cb
    return self._command(

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\storage\blob\_generated\operations\_container_operations.py", line 1479, in list_blob_flat_segment
    map_error(status_code=response.status_code, response=response, error_map=error_map)

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\core\exceptions.py", line 105, in map_error
    raise error

ResourceNotFoundError: The specified container does not exist.
RequestId:4d2df1c1-a01e-008b-4209-21e493000000
Time:2022-02-13T18:44:14.1140999Z
ErrorCode:ContainerNotFound
Content: <?xml version="1.0" encoding="utf-8"?><Error>ContainerNotFound<Message>The specified container does not exist.
RequestId:4d2df1c1-a01e-008b-4209-21e493000000
Time:2022-02-13T18:44:14.1140999Z</Message></Error>

Ultimately, I want to be able to do two things:

download files from my Blob to my local machine

upload files from my local machine to my Blob.


问:
How does Autosave in Mac OS X Lion 10.7 work? How can I change the autosave frequency?
Just curious if anyone has some insight into how Autosave works in Lion? For Applications that have been optimized to take advantage of the Autosave API's - is there a frequency with which the document is "auto saved"? can it be manipulated? where is the autosave data stored? Any insight or details would be appreciated. Thank you!</p>

答:
Lion's Autosave is different from previous versions of autosaving in that it saves directly to the user's file (instead of, for example, a "My Document (Autosaved)" file to the side).

Autosaving happens for a multitude of reasons, only one of which is periodic autosaving. You can influence the autosaving frequency by overriding NSDocumentController's -autosavingDelay method, but this is mostly just used as a hint on Lion, not a hard requirement.

If you really want to, you can also override NSDocument's -scheduleAutosaving, but NSDocument has a lot of smarts in that method that you may not override.

There is also the concept of "implicitly cancelable" autosaves, which you can use to cancel a periodic autosave if you think now isn't a good time, for whatever reason.

The Lion AppKit release notes have a lot more info that you'll find useful.


问:
How to ensure correct type-checking in sequelize join-queries (with TypeScript)?
Suppose we have two tables A and B associated like this:

```<code>A.hasMany(B);
B.belongsTo(A);
</code>```

And we have this join query:

```<code>async getAll(): Promise<B[]> {
    return B.findAll({
         include: {
            model: A,
            attributes: ['id'],
            required: true
         }
    });
}
</code>```

TypeScript says the return type for B.findAll() is B,

but this function is returning the type B & {"A": {id:number}} which is not B.

How to handle the fact that for TypeScript's compiler the return type is the same for join-queries and single-table-queries when is not the same at all?

答:
Well, after a little research I found this article talking about TypeScript ORMs and type safety, and the conclusion is that maybe Sequelize is not the best option if type safety is a priority:

[...] Furthermore, when fetching associations using include, the return type does not include information about the nested shape of the fetched data, and to properly compile without errors, the developer must use ! non-null assertions and rejectOnEmpty parameters to override the compiler.

Body:
Suppose we have two tables A and B associated like this:

A.hasMany(B);
B.belongsTo(A);

And we have this join query:

async getAll(): Promise {
    return B.findAll({
         include: {
            model: A,
            attributes: ['id'],
            required: true
         }
    });
}

TypeScript says the return type for B.findAll() is B,

but this function is returning the type B & {"A": {id:number}} which is not B.

How to handle the fact that for TypeScript's compiler the return type is the same for join-queries and single-table-queries when is not the same at all?


问:
Count the number of punctuation symbols in a string Kotlin
I have a question how can I count the number of punctuation symbols in a string.

Here is my code snippet

```<code>fun punctuationCount(stringValue: Editable): Int {
        val trimmedStr = stringValue.trim()
        return if (trimmedStr.isEmpty()) {
            0
        } else {
           return trimmedStr.split("[a-zA-Z&&[ \t]]".toRegex()).size
        }
    }
</code>```

答:
Here's a version of your function that demonstrates what you're asking for:

```<code>fun punctuationCount(stringValue: String): Long {
    val trimmedStr = stringValue.trim()
    return if (trimmedStr.isEmpty()) {
        return 0
    } else {
        val exp = Pattern.compile("\\p{Punct}")
        val matcher = exp.matcher(trimmedStr)
        return matcher.results().count()
    }
}
</code>```

If you don't like the Pattern library's definition of what constitutes punctuation, you can replace the line that computes the Pattern object with something like this that lets you define punctuation characters explicitly:

```<code>val exp = Pattern.compile("[!@#\$%.]")
</code>```

Body:
I have a question how can I count the number of punctuation symbols in a string.

Here is my code snippet

fun punctuationCount(stringValue: Editable): Int {
        val trimmedStr = stringValue.trim()
        return if (trimmedStr.isEmpty()) {
            0
        } else {
           return trimmedStr.split("[a-zA-Z&&[ \t]]".toRegex()).size
        }
    }

Body:
Here's a version of your function that demonstrates what you're asking for:

fun punctuationCount(stringValue: String): Long {
    val trimmedStr = stringValue.trim()
    return if (trimmedStr.isEmpty()) {
        return 0
    } else {
        val exp = Pattern.compile("\\p{Punct}")
        val matcher = exp.matcher(trimmedStr)
        return matcher.results().count()
    }
}

If you don't like the Pattern library's definition of what constitutes punctuation, you can replace the line that computes the Pattern object with something like this that lets you define punctuation characters explicitly:

val exp = Pattern.compile("[!@#\$%.]")


问:
Flex: pass a parameter to itemEditor
I have a datagrid where one column calls a custom an itemEditor like;

```<code>                    <mx:DataGridColumn dataField="city"
                                       width="150"
                                       headerText="City"
                                       itemEditor="components.ComboCity"
                                       editorDataField="city"/>
</code>```

And my custom itemEditor looks like;

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <s:MXDataGridItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
                              xmlns:s="library://ns.adobe.com/flex/spark"
                              xmlns:mx="library://ns.adobe.com/flex/mx"
                              focusEnabled="true">
        <mx:ComboBox id="comboBox"/>
        <fx:Script>
            <![CDATA[
                public var myString:String;
                .
                .
                .
</code>```

How can I pass from my main application a value to myString ?

答:
The best solution for me:

```<code><mx:Script>
    <![CDATA[

        import mx.events.DataGridEvent;

        private function itemEditorCreateHandle(event:DataGridEvent):void
        {
            ComboCity(DataGrid(event.target).itemEditorInstance).myString = "Put here the value";
        }

    ]]>
</mx:Script>

<mx:DataGridColumn
    dataField="city"
    width="150"
    headerText="City"
    itemEditor="components.ComboCity"
    itemEditorCreate="itemEditorCreateHandle(event);"
    editorDataField="city"/>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Flex: pass a parameter to itemEditor

Body:
I have a datagrid where one column calls a custom an itemEditor like;

                    <mx:DataGridColumn dataField="city"
                                       width="150"
                                       headerText="City"
                                       itemEditor="components.ComboCity"
                                       editorDataField="city"/>

And my custom itemEditor looks like;

    <?xml version="1.0" encoding="utf-8"?>
    <s:MXDataGridItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
                              xmlns:s="library://ns.adobe.com/flex/spark"
                              xmlns:mx="library://ns.adobe.com/flex/mx"
                              focusEnabled="true">
        <mx:ComboBox id="comboBox"/>
        <fx:Script>
            <![CDATA[
                public var myString:String;
                .
                .
                .

How can I pass from my main application a value to myString ?

Body:
The best solution for me:

<mx:Script>
    <![CDATA[

        import mx.events.DataGridEvent;

        private function itemEditorCreateHandle(event:DataGridEvent):void
        {
            ComboCity(DataGrid(event.target).itemEditorInstance).myString = "Put here the value";
        }

    ]]>
</mx:Script>

<mx:DataGridColumn
    dataField="city"
    width="150"
    headerText="City"
    itemEditor="components.ComboCity"
    itemEditorCreate="itemEditorCreateHandle(event);"
    editorDataField="city"/>


问:
How to convert svg string to svg file using Python?
Using AJAX I send a svg image to Django using the following function:

```<code>function uploadSVG(){

    var svgImage = document.getElementById("SVG");

    var serializer = new XMLSerializer();
    var svgStr = serializer.serializeToString(svgImage);

    $(document).ready(function(){
        $.post("ajax_upload_svg/",
      {
        csrfmiddlewaretoken: csrftoken,
        svgImage: svgStr
      },
      function(){
        console.log('Done')
      });
    });
}
</code>```

In Django I end up with the svg image as a string using the following function:

```<code>def uploadSVG(request):

    svgImg = request.POST.get('svgImage')

    return HttpResponse('')
</code>```

The string I get looks like this:

```<code><svg xmlns="http://www.w3.org/2000/svg" id="SVG" width="460" height="300" style="border:2px solid #000000"><rect x="150" y="70" width="160" height="130" fill="#292b2c"/></svg>
</code>```

How can I convert this svg string into a svg file?

答:
The solution is:</p>
```<code>with open("svgTest.svg", "w") as svg_file:
        svg_file.write(svgImg)
</code>```

Body:
Using AJAX I send a svg image to Django using the following function:

function uploadSVG(){

    var svgImage = document.getElementById("SVG");

    var serializer = new XMLSerializer();
    var svgStr = serializer.serializeToString(svgImage);

    $(document).ready(function(){
        $.post("ajax_upload_svg/",
      {
        csrfmiddlewaretoken: csrftoken,
        svgImage: svgStr
      },
      function(){
        console.log('Done')
      });
    });
}

In Django I end up with the svg image as a string using the following function:

def uploadSVG(request):

    svgImg = request.POST.get('svgImage')

    return HttpResponse('')

The string I get looks like this:

<svg xmlns="http://www.w3.org/2000/svg" id="SVG" width="460" height="300" style="border:2px solid #000000"><rect x="150" y="70" width="160" height="130" fill="#292b2c"/></svg>

How can I convert this svg string into a svg file?

Body:
The solution is:

with open("svgTest.svg", "w") as svg_file:
        svg_file.write(svgImg)


问:
How to add and use a stylesheet in a react spfx project
Im working on a webpart right now and am having an issue using icons from a sass package I downloaded.

I have some code that composes a set of classes that I assign to an  tag in the return statement of the render function. It generates the correct classes but obviously doesnt generate the icon when I use the webpart.

This is what generates the classes

```<code>this.conditionCode = this.props.data.day.condition.code;
this.conditionClass = "wi wi-wapi-";
this.conditionClass += this.conditionCode;
</code>```

This is whats in the render statement

```<code><i className={this.conditionClass} ></i>
</code>```

And this is the import statement for the sass file:

```<code>import iconStyles from '../weathericons/sass/weather-icons.scss';
</code>```

Obviously its not working but i dont know how else to do this. I know about the method where you reference styles using:

```<code>{styles.somestyle}
</code>```

But that just wont work here since I need to compose the classes before using them.

Do I have any recourse here?

Body:
Im working on a webpart right now and am having an issue using icons from a sass package I downloaded.

I have some code that composes a set of classes that I assign to an  tag in the return statement of the render function. It generates the correct classes but obviously doesnt generate the icon when I use the webpart.

This is what generates the classes

this.conditionCode = this.props.data.day.condition.code;
this.conditionClass = "wi wi-wapi-";
this.conditionClass += this.conditionCode;

This is whats in the render statement

And this is the import statement for the sass file:

import iconStyles from '../weathericons/sass/weather-icons.scss';

Obviously its not working but i dont know how else to do this. I know about the method where you reference styles using:

{styles.somestyle}

But that just wont work here since I need to compose the classes before using them.

Do I have any recourse here?

Body:
First Import SASS classes -
import * as w from '../weathericons/sass/weather-icons.scss';

Allocate the classes in JSON Format -

this.conditionClass = { w.wi, w.wi-wapi };

Then render using -

<i className={ this.conditionClass } >


问:
EF Core DbDataReader result changing in interceptor
guys.

I have a question about EF Core DbCommandInterceptor.

Let's have a class with 2 fields like this

```<code>public class User
{
    public Guid Id { get; set; }
    public string SameData { get; set; }
}

public class TestClass
{
   public Guid Id { get; set; }

   public Guid TestClassId { get; set; }

   [NotMapperd, MyAttr]
   public TestClass TestClass { get; set; }
}
</code>```

where User and TestClass are both located in the different contexts (for example, UserDbContext, TestDbContext). MyAttr is the marker attribute, nothing more.

So, I want to write an interceptor that raises up each time we try to get info about TestClasses, but after data got it should get an additional data about User with cross-request to UserDbContext (It possible, because I have User Id after the command execution and can use this Id in the request)

I know, that it should be DbCommandInterceptor.ReaderExecuted or DbCommandInterceptor.ReaderExecutedAsync in this case, but I cannot understand how to get information about objects in the result (I can get rows but I cannot understand what should I do, how should I map it). I can use additional libraries in the project if needed (like Dapper and others).

Could anyone helps me to get

Result Type - concrete entity type or entity collection type?

Result as a C# object (POCO or POCO collection)?

Thank you.

答:
I know, that it should be DbCommandInterceptor.ReaderExecuted or DbCommandInterceptor.ReaderExecutedAsync in this case, but I cannot understand how to get information about objects in the result

The EF Command interceptors don't support that.  You can replace the DataReader with a different one.  But the query was generated to fill a particular object graph, which is not exposed by the interceptor API.

Body:
guys.

I have a question about EF Core DbCommandInterceptor.

Let's have a class with 2 fields like this

public class User
{
    public Guid Id { get; set; }
    public string SameData { get; set; }
}

public class TestClass
{
   public Guid Id { get; set; }

   public Guid TestClassId { get; set; }

   [NotMapperd, MyAttr]
   public TestClass TestClass { get; set; }
}

where User and TestClass are both located in the different contexts (for example, UserDbContext, TestDbContext). MyAttr is the marker attribute, nothing more.

So, I want to write an interceptor that raises up each time we try to get info about TestClasses, but after data got it should get an additional data about User with cross-request to UserDbContext (It possible, because I have User Id after the command execution and can use this Id in the request)

I know, that it should be DbCommandInterceptor.ReaderExecuted or DbCommandInterceptor.ReaderExecutedAsync in this case, but I cannot understand how to get information about objects in the result (I can get rows but I cannot understand what should I do, how should I map it). I can use additional libraries in the project if needed (like Dapper and others).

Could anyone helps me to get

Result Type - concrete entity type or entity collection type?

Result as a C# object (POCO or POCO collection)?

Thank you.


问:
What Stops Google From Modifying Our APKs That It Signs Via the App Signing Service?
As a follow-up to this question, I am trying to figure out what stops Google from modifying our apps that it signs and distributes. Regardless of whether we distribute an APK or an App Bundle, the App Signing service strips away whatever signature that we have and Google signs the APKs that it distributes. In the case of the App Bundle, this will result in several APKs, akin to what bundletool generates.

But since an APK is just a ZIP archive with compiled code and resources, it seems as though Google could modify that as they see fit before signing, including adding or replacing code.

Google has stated:

we don’t modify and distribute your application code without your knowledge and approval

and:

As stated before, Play will not modify the functionality of your application without your knowledge and approval.

Notably, Google used "don't" and "will not"... as opposed to "can't" and "cannot". In fact, in the same post, we see:

For apps uploaded as app bundles, we will improve this security by introducing what is called a source stamp. This source metadata is inserted into the app’s manifest by bundletool.

So, we know of at least one modification, albeit to metadata.

Plus,
the Amazon AppStore for Android modifies APKs before re-signing them:

Regardless of whether you choose to apply Amazon DRM, Amazon wraps your app with code that enables the app to communicate with the Amazon Appstore client to collect analytics, evaluate and enforce program policies, and share aggregated information with you. Your app will always communicate with the Amazon Appstore client when it starts, even if you choose not to apply DRM.

Amazon removes your signature and re-signs your app with an Amazon signature that is unique to you, does not change, and is the same for all apps in your account.

Amazon has been doing this sort of thing for a decade.

It seems as though Google should have the same technical capability as does Amazon.

So, is there anything that I am missing that prevents Google from adding to or modifying the code in APKs that it re-signs and distributes?

答:
Apologies for potential anachronism here.

When you say

the App Signing service strips away whatever signature that we have

are you sure this is what it does? One could imagine an alternative scheme, which could achieve everything noted in other answers / comments as actually occurring:

Assume that the dev has uploaded their artefacts (let's say as an .obb) and signed it using their upload key. Google appends its additional metadata (think of it as a kind of diff file) and re-signs the resulting expanded payload. On receipt at the device, android checks that the payload it has received was correctly signed by Google (which it was), removes (but keeps) the metadata Google added, then checks the remaining payload (the dev's .obb) against the dev's signature. If that checks out, which it presumably will, it applies the change implicit in the added metadata to the original .obb

That .obb becomes the artifact which android installs. It isn't what the dev uploaded.
Google hasn't stripped the dev's upload signature, they've just added extra payload in a way which doesn't invalidate the original signature, then added some more payload and a signature of their own.

I'm not saying this is what they are doing, just that this is what they might be doing. You would be able to detect this once you had downloaded the payload and installed it on a device. Could it be made to happen or not according to which device the download was sent to? I expect that wouldn't be hard. And in that case, you wouldn't be able to detect it unless you had access to a device which had been targetted for the modification. It would be very difficult to detect the modification process while it was occurring. You could tell the difference between a modified payload and an unmodified payload immediately on receipt at the device because the presence or absence of the metadata "diff" would change the file size.

I don't know whether bundletool could support such a scheme. I guess that's where you could look for clues.

They may just be stripping the dev's upload signature and replacing it with their own. The only protection against signature stripping comes from checks done by the receiver.

When it comes down to it, you cannot trust any crypto scheme if you might consider the receiving endpoint to be compromised. Whether the payload is encrypted (which in this case it isn't) or merely signed, if the endpoint is not going to enforce the scheme, the sender and the user are both potentially exposed.

Technically, in this case, the crypto on the endpoint is in the control of the device manufacturer, although it is questionable whether they would actually exercise that control against the will or interests of the OS provider - Google - assuming that manufacturers even check these things.


问:
Linking to different areas on a page
This may seem like a stupid question, but:

So what i would like to do is set up a menu section so that when the user clicked on the title of the section it would send them to that particular spot on the page with out having to scoll down. I am not entirely sure how this would work or how complicated it is to achieve.

So bacially i would have

Menu

item one (be a link)

item two (be a link)

etc (be a link)

then further down the page

item one (when item one in menu is clicked page comes to here)

"details about it here"

item two (when item two in menu is clicked page comes to here)

"details here"

How exactly would i go about doing this?

Any help or suggestions are greatly appreciated. Thanks.

答:
I (assume) you know about anchor tags & bookmarks...?

Other than that, here's a script that will position your page to the bookmark on postbacks.
http://geekswithblogs.net/jawad/archive/2005/05/25/BookMarkJump.aspx

Title: Linking to different areas on a page


问:
AppleScript to toggle Bluetooth
In OS X 10.8 I had a neat little AppleScript that I used to toggle Bluetooth quickly without using the mouse.

I updated to 10.9 which added several UI changes to System Preferences. Among other things it replaced the element that toggles Bluetooth from a checkbox to a button. My script is now broken, and consequently so is my workflow.

The problem is that the button's name changes from "Turn Bluetooth On" to "Turn Bluetooth Off" depending on its status. I don't have a sufficient grasp in AppleScript to figure out a workaround, and was wondering if you guys could help me out.

答:
Here is a GUI script that should work for macOS 12. It is also language independent:</p>
```<code>tell application "System Preferences"
    set current pane to pane "com.apple.preferences.Bluetooth"
    delay 0.5
end tell

tell application "System Events"
    tell application process "System Preferences"
        click button 1 of window "Bluetooth"
    end tell
end tell
</code>```

Title: AppleScript to toggle Bluetooth

Body:
Here is a GUI script that should work for macOS 12. It is also language independent:

tell application "System Preferences"
    set current pane to pane "com.apple.preferences.Bluetooth"
    delay 0.5
end tell

tell application "System Events"
    tell application process "System Preferences"
        click button 1 of window "Bluetooth"
    end tell
end tell


问:
inputting a certain number for wages doesn't stop the do while loop when it reaches the number
```<code>   #include <stdio.h>

int main()
{
char firstname[20];
char lastname[20];
float wage;
int n_emp;
int e_numemp;
FILE *staff_ptr;

staff_ptr=fopen ("staff", "wage");
printf("Input the numbers employees you would like to add\n");
scanf("%d",&n_emp);
do {
  (e_numemp=n_emp-1);
  printf("Enter the first name of the employee\n");
  scanf("%s",&firstname);
  printf("Enter the second name of the employee\n");
  scanf("%s",&lastname);
  printf("Enter the wage of the employee\n");
  scanf("%f",&wage);
  fwrite (&firstname,sizeof (firstname),1,staff_ptr);
  fwrite (&lastname,sizeof (lastname),1,staff_ptr );
  fwrite (&wage,sizeof (wage),1,staff_ptr );
}
while (e_numemp!=0);
fclose (staff_ptr);
return 0;
}
</code>```

The question for my assignment is "Write a program to ask for the name and wage of each employee in a firm and store the data in a file called "staff"

For some reason when i input a number like 4 for the numbers of employees it just doesn't stop at 4 and keeps going on forever

答:
In every iteration of the loop e_numemp is always set to n_emp - 1 (n_emp is never changed once input).
Assuming you wanted to save the initial value of n_emp, perhaps you meant:

```<code>scanf("%d",&n_emp);
e_numemp = n_emp;
do {
  e_numemp -= 1;
  .
  .
  .
} while ( e_numemp != 0 );
</code>```

Body:
   #include <stdio.h>

int main()
{
char firstname[20];
char lastname[20];
float wage;
int n_emp;
int e_numemp;
FILE *staff_ptr;

staff_ptr=fopen ("staff", "wage");
printf("Input the numbers employees you would like to add\n");
scanf("%d",&n_emp);
do {
  (e_numemp=n_emp-1);
  printf("Enter the first name of the employee\n");
  scanf("%s",&firstname);
  printf("Enter the second name of the employee\n");
  scanf("%s",&lastname);
  printf("Enter the wage of the employee\n");
  scanf("%f",&wage);
  fwrite (&firstname,sizeof (firstname),1,staff_ptr);
  fwrite (&lastname,sizeof (lastname),1,staff_ptr );
  fwrite (&wage,sizeof (wage),1,staff_ptr );
}
while (e_numemp!=0);
fclose (staff_ptr);
return 0;
}

The question for my assignment is "Write a program to ask for the name and wage of each employee in a firm and store the data in a file called "staff"

For some reason when i input a number like 4 for the numbers of employees it just doesn't stop at 4 and keeps going on forever

Body:
In every iteration of the loop e_numemp is always set to n_emp - 1 (n_emp is never changed once input).
Assuming you wanted to save the initial value of n_emp, perhaps you meant:

scanf("%d",&n_emp);
e_numemp = n_emp;
do {
  e_numemp -= 1;
  .
  .
  .
} while ( e_numemp != 0 );


问:
How to vertically center align icon inside table header
I have a dynamic table, with dynamic no of column and rows... In table header, I need to fix sort icon vertically center.. Even table header text size is dynamic and no of lines keeps growing...  how to vertically align sort icon while text size keeps increases?

jsfiddle

```<code><table style="width:100%">
  <tr>
    <th><div class='filter-container header-container'> <div class='header-text'>  Firstname Firstname Firstnam eFirstnam eFirstname Firstname Firstname Firstname Firstname</div><div class='icon-right'> <span    class= "fa fa-sort-asc fa-lg sort-icon "></span><span   class= "fa fa-sort-desc fa-lg sort-icon  "></span></div></div></th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>80</td>
  </tr>
</table>
</code>```

CSS:

```<code>table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}

th, td {
  padding: 5px;
}

.filter-container {
  width: 100%;
  height: 100%;
  position: relative;
  padding: 0px !important;
  margin: 0px !important;
}

.header-container {
  height: 100%;
  vertical-align: middle;
  text-align: center;
}

.header-text {
  font-size: 22px;
  line-height: 24px;
  color: #000000;
  font-weight: normal;
  width: 90%;
  float: left;
  letter-spacing: 0;
  text-align: left;
}

.sort-icon {
  float: right !important;
  clear: right;
  height: 1px !important;
}
</code>```

答:
I don't know how but using absolute position worked for me!

 Title

```
<pre class="lang-css prettyprint-override"><code>.sort-icon {
    position: absolute;
}
</code>```

Body:
I have a dynamic table, with dynamic no of column and rows... In table header, I need to fix sort icon vertically center.. Even table header text size is dynamic and no of lines keeps growing...  how to vertically align sort icon while text size keeps increases?

jsfiddle

  Firstname Firstname Firstnam eFirstnam eFirstname Firstname Firstname Firstname Firstname

    Lastname
    Age

    Jill
    Smith
    50

    Eve
    Jackson
    94

    John
    Doe
    80

CSS:

table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}

th, td {
  padding: 5px;
}

.filter-container {
  width: 100%;
  height: 100%;
  position: relative;
  padding: 0px !important;
  margin: 0px !important;
}

.header-container {
  height: 100%;
  vertical-align: middle;
  text-align: center;
}

.header-text {
  font-size: 22px;
  line-height: 24px;
  color: #000000;
  font-weight: normal;
  width: 90%;
  float: left;
  letter-spacing: 0;
  text-align: left;
}

.sort-icon {
  float: right !important;
  clear: right;
  height: 1px !important;
}

Body:
I don't know how but using absolute position worked for me!

<th>
 Title <span class="sort-icon"><i class="fa fa-sort"></i></span>
</th>

.sort-icon {
    position: absolute;
}


问:
For loop in function to move the item of the list
I want to move the negative numbers to the end of the list until I encounter the positive number.

List:

```<code>a=[-1,-2,2,3,4,-5]
</code>```

The result i want:

```<code>[-2, 2, 3, 4, -5, -1]
[2, 3, 4, -5, -1, -2]
</code>```

My function:

```<code>def f1(A):
  for i in A:
    if i>=0:
      break
    if 'Z' not in globals() or 'Z' not in locals():
     X=A
     X1=X[0]
     X.remove(X1)
     X.append(X1)
     Z=X
    else:
      X=Z
      X1=X[0]
      X.remove(X1)
      X.append(X1)
      Z=X
    print(Z)

a=[-1,-2,2,3,4,-5]
print (f1 (a))
</code>```

But the result

```<code>[-2, 2, 3, 4, -5, -1]
None
</code>```

can we solve it with this function?

答:
```<code>while A[0] < 0: # While the list still begins with negative values
    A.append(A.pop(0)) # Rotate left
</code>```

This should work. For the explanation look at the comments.

What's more your function f1 doesn't have a returned value, so:

```<code>print(f1(a))
</code>```

doesn't produce any output (only None, since there's no returned value)

Since in Python the lists are "passed by reference", you can do something like this:

```<code>while A[0] < 0:
    ...
return A # The list is already edited in global scope BUT doing this you allow the print statement above
</code>```

Body:
I want to move the negative numbers to the end of the list until I encounter the positive number.

List:

a=[-1,-2,2,3,4,-5]

The result i want:

[-2, 2, 3, 4, -5, -1]
[2, 3, 4, -5, -1, -2]

My function:

def f1(A):
  for i in A:
    if i>=0:
      break
    if 'Z' not in globals() or 'Z' not in locals():
     X=A
     X1=X[0]
     X.remove(X1)
     X.append(X1)
     Z=X
    else:
      X=Z
      X1=X[0]
      X.remove(X1)
      X.append(X1)
      Z=X
    print(Z)

a=[-1,-2,2,3,4,-5]
print (f1 (a))

But the result

[-2, 2, 3, 4, -5, -1]
None

can we solve it with this function?

Body:
while A[0] < 0: # While the list still begins with negative values
    A.append(A.pop(0)) # Rotate left

This should work. For the explanation look at the comments.

What's more your function f1 doesn't have a returned value, so:

print(f1(a))

doesn't produce any output (only None, since there's no returned value)

Since in Python the lists are "passed by reference", you can do something like this:

while A[0] < 0:
    ...
return A # The list is already edited in global scope BUT doing this you allow the print statement above


问:
Eiffel Studio ARM Apple Silicon M1
I am hoping to create some software with Eiffel & Eiffel Studio

I have a Mac mini with the Apple M1 Arm Processor.

Is there a port of EiffelStudio to native Mac M1?

Does Eiffel Studio support native MacOS Windowing or is it still requiring Windows?

答:
EiffelStudio 21.11 download page does not list a native build for macOS running on M1, only on x86-64. Provided that there are builds for Linux running on ARM, there should be no obstacles to make a build for M1, though.

As to the GUI part, starting from 21.11, non-Windows installations of EiffelStudio rely on GTK 3, that utilizes Quartz API. So, it should not require X Windows.

Title: Eiffel Studio ARM Apple Silicon M1


问:
Namespace in method parameters
I'm surprised that the namespace of function parameters in a method is the class and not the global scope.

```<code>def a(x):
    print("Global A from {}".format(x))

class Test:
    def a(self, f=a):
        print("A")
        f("a")  # this will call the global method a()

    def b(self, f=a):
        print("B")
        f("b")   # this will call the class method a()

t=Test()
t.b()
</code>```

How to explain that? And how would I access the global a() from the parameters of b?

答:
Namespace lookups always check the local scope first. In a method definition, that is the class.

At the time of the definition of Test.a, there is no local named a, only the global a. By the time Test.b is defined, Test.a has already been defined, so the local name a exists, and the global scope is not checked.

If you want to point f in Test.b to the global a, use:

```<code>def a(x):
    print("Global A from {}".format(x))

class Test:

    def a(self, f=a):
        print("A")
        f("a")  # this will call the global method a()

    def b(self, f=None):
        f = f or a
        print("B")
        f("b")   # this will call the class method a()

t=Test()
t.b()
</code>```

which prints

```
B
Global A from b
```

as expected.

Title: Namespace in method parameters

Body:
I'm surprised that the namespace of function parameters in a method is the class and not the global scope.

def a(x):
    print("Global A from {}".format(x))

class Test:
    def a(self, f=a):
        print("A")
        f("a")  # this will call the global method a()

    def b(self, f=a):
        print("B")
        f("b")   # this will call the class method a()

t=Test()
t.b()

How to explain that? And how would I access the global a() from the parameters of b?

Body:
Namespace lookups always check the local scope first. In a method definition, that is the class.

At the time of the definition of Test.a, there is no local named a, only the global a. By the time Test.b is defined, Test.a has already been defined, so the local name a exists, and the global scope is not checked.

If you want to point f in Test.b to the global a, use:

def a(x):
    print("Global A from {}".format(x))

class Test:

    def a(self, f=a):
        print("A")
        f("a")  # this will call the global method a()

    def b(self, f=None):
        f = f or a
        print("B")
        f("b")   # this will call the class method a()

t=Test()
t.b()

which prints

B
Global A from b

as expected.


问:
How to get multiselect checkbox data in update action and save it in junction table
I have two models (Video, Category). In my video form i am fetching the categories (from Category model) and show them as checkboxes (note that: there is no categories field inside video table). each video can have single or multiple categories. I need to save the video categories (which are to be selected inside video form) inside a junction table (video_categories). I will save the categories using afterSave() inside Video model.
My main problem is that how can i fetch my checked categories from video form inside updateAction() of VideoController, and assign them to some public member (of Video model) and then use that member in afterSave() to save the categories inside that junction table (video_categories).
One more thing is that I want to save the categories inside updateAction() only. In createAction() i am saving just the video file. all other details about video needs to be saved inside updateAction().

This is how I displayed Categories inside video form.

```<code><ul class="catgss_list">
<?php
$category = common\models\Category::find()->all();
foreach($category as $cat):
?>
<li>
    <div class="chekbox-lg">
        <label>
            <input type="checkbox" name="category[]" value="<?php echo $cat->id ?>">
            <b class="checkmark"></b>
            <span><?= $cat->category_name ?></span>
        </label>
    </div>
</li>
<?php endforeach; ?>
</ul>
</code>```

this is how my form looks like https://ibb.co/tpZXrVw

答:
i have solved my problem. what I did is written below:-
my Video model

```<code>public $categories;// i declare a public attribute.
public function afterSave($insert, $changedAttributes) {
    parent::afterSave($insert, $changedAttributes);
    $this->deleteExistingCategories();
    if (isset($_POST['Video']['categories'])) {
        $this->saveVideoCategories($_POST['Video']['categories']);
    }
}

public function deleteExistingCategories() {
    VideoCategory::deleteAll(['video_id' => $this->video_id]);
}

public function saveVideoCategories($categoriesList) {
  foreach ($categoriesList as $category) {
      $videoCategory = new VideoCategory();
      $videoCategory->video_id = $this->video_id;
      $videoCategory->category_id = $category;
      $videoCategory->save();
  }
}
</code>```

my video form code

```<code><ul class="catgss_list">
<?php
$checkedCategories = VideoCategory::findAll(['video_id' => $model->video_id]);
if (isset($checkedCategories)) {
    foreach ($checkedCategories as $selectedCategory) {
        $savedCategories[] = $selectedCategory->category_id;
    }
}
$category = Category::find()->all();
foreach ($category as $cat):
?>
<li>
    <div class="chekbox-lg">
        <label>
            <input type="checkbox" name="Video[categories][]" value="<?php echo $cat->id ?>"
            <?php
            if (isset($savedCategories)) {
                $isCategory = in_array($cat->id, $savedCategories);
                if (isset($isCategory) && $isCategory == true) {
                    echo "checked";
                }
            }
            ?>
                   >
            <b class="checkmark"></b>
            <span><?php echo $cat->category_name ?></span>
        </label>
    </div>
</li>
<?php endforeach; ?>
</ul>
</code>```

Body:
I have two models (Video, Category). In my video form i am fetching the categories (from Category model) and show them as checkboxes (note that: there is no categories field inside video table). each video can have single or multiple categories. I need to save the video categories (which are to be selected inside video form) inside a junction table (video_categories). I will save the categories using afterSave() inside Video model.
My main problem is that how can i fetch my checked categories from video form inside updateAction() of VideoController, and assign them to some public member (of Video model) and then use that member in afterSave() to save the categories inside that junction table (video_categories).
One more thing is that I want to save the categories inside updateAction() only. In createAction() i am saving just the video file. all other details about video needs to be saved inside updateAction().

This is how I displayed Categories inside video form.

<?php
$category = common\models\Category::find()->all();
foreach($category as $cat):
?>

            <input type="checkbox" name="category[]" value="<?php echo $cat->id ?>">

            <?= $cat->category_name ?>

<?php endforeach; ?>

this is how my form looks like https://ibb.co/tpZXrVw

Body:
i have solved my problem. what I did is written below:-
my Video model

public $categories;// i declare a public attribute.
public function afterSave($insert, $changedAttributes) {
    parent::afterSave($insert, $changedAttributes);
    $this->deleteExistingCategories();
    if (isset($_POST['Video']['categories'])) {
        $this->saveVideoCategories($_POST['Video']['categories']);
    }
}

public function deleteExistingCategories() {
    VideoCategory::deleteAll(['video_id' => $this->video_id]);
}

public function saveVideoCategories($categoriesList) {
  foreach ($categoriesList as $category) {
      $videoCategory = new VideoCategory();
      $videoCategory->video_id = $this->video_id;
      $videoCategory->category_id = $category;
      $videoCategory->save();
  }
}

my video form code

<ul class="catgss_list">
<?php
$checkedCategories = VideoCategory::findAll(['video_id' => $model->video_id]);
if (isset($checkedCategories)) {
    foreach ($checkedCategories as $selectedCategory) {
        $savedCategories[] = $selectedCategory->category_id;
    }
}
$category = Category::find()->all();
foreach ($category as $cat):
?>
<li>
    <div class="chekbox-lg">
        <label>
            <input type="checkbox" name="Video[categories][]" value="<?php echo $cat->id ?>"
            <?php
            if (isset($savedCategories)) {
                $isCategory = in_array($cat->id, $savedCategories);
                if (isset($isCategory) && $isCategory == true) {
                    echo "checked";
                }
            }
            ?>
                   >
            <b class="checkmark"></b>
            <span><?php echo $cat->category_name ?></span>
        </label>
    </div>
</li>
<?php endforeach; ?>
</ul>


问:
AWS Application load balancer throwing 502
I am currently learning about AWS and I have a single EC2 instance running with a nodejs server on port 3000, an Application load balancer with SSL setup that listen on port 80 and 443 (http & https). When I make requests to the http route it returns back the successful health check message. But when I try to access my api via the https method, I get a 502 Error. I googled around and read some articles and they pointed out that the nodejs server keepAliveTimeout and headersTimeout should be higher than the timeout option of the ALB. I tried that and it didn't work. I also tried to set the max-http-header-value to 16384, I also tried to check the access logs for the load balancer on my S3 bucket and the logs just showed that I am getting a 502 error and nothing more. What could be the issue? Because I have tried all solutions that presented but they don't seem to work.

答:
The first thing to check is that your server is responding to requests. Try connecting to port 3000 on the server, either from the server itself (eg curl localhost:3000) or from outside the server (which will require the Security Group to permit access to port 3000).

Once you have confirm that the server is responding, configure Security Groups as:

A Security Group on the Application Load Balancer (ALB-SG) that permits Inbound access on ports 80 and 443

A Security Group on the Amazon EC2 instance (App-SG) that permits inbound access on port 3000 from ALB-SG

That is, App-SG should specifically refer to ALB-SG in its Inbound rules.

Then, configure the Load Balancer to have a Target Group that points at port 3000 on the app server and provide it a URL for the Health Check (that could simply be /).

Then, connect to the Application Load Balancer and see whether you can access your app.


问:
How to convert create-react-app to Preact?
As per Preact documentation, to convert a React app to Preact you have to alias webpack:

```<code>{
  "resolve": {
    "alias": {
      "react": "preact-compat",
      "react-dom": "preact-compat"
    }
  }
}
</code>```

How can you do this with create-react-app since that hides webpack under react-scripts dependency?

Thank you!

答:
Alternatively, you can get it working with craco:

// craco.config.js
module.exports = {
  webpack: {
    alias: {
      "react": "preact/compat",
      "react-dom": "preact/compat"
    }
  }
}
```

Note: Do not uninstall react, @types/react, or @types/react-dom after adding preact!

react is still required by react-scripts to run craco start and friends.

@types/* are still required by your IDE for type suggestions.

Note: Bundle analyzers may still report that you're using React!

Make sure to double-check your output directory for real build sizes.

Body:
As per Preact documentation, to convert a React app to Preact you have to alias webpack:

{
  "resolve": {
    "alias": {
      "react": "preact-compat",
      "react-dom": "preact-compat"
    }
  }
}

How can you do this with create-react-app since that hides webpack under react-scripts dependency?

Thank you!

Body:
Alternatively, you can get it working with craco:

// craco.config.js
module.exports = {
  webpack: {
    alias: {
      "react": "preact/compat",
      "react-dom": "preact/compat"
    }
  }
}

Note: Do not uninstall react, @types/react, or @types/react-dom after adding preact!

react is still required by react-scripts to run craco start and friends.

@types/* are still required by your IDE for type suggestions.

Note: Bundle analyzers may still report that you're using React!

Make sure to double-check your output directory for real build sizes.


问:
Join range of row using arrayformula

I have a range of data on column A and B. In Column D , i have a reference for the shotID. I want to make a list for the artist involved for specific shotID.

In E2 i use this :

```<code>=JOIN( "," , FILTER($B$2:$B, $A$2:$A= D2))
</code>```

then copy down to E3,E4. It works as i expected, but i want to do it using array formula. So only use single formula in E2 and that doesn't work that simple :

```<code>=arrayformula( JOIN( "," , FILTER($B$2:$B, $A$2:$A= D2:D4)) )
</code>```

How can i do this ?

答:
One more possibility that I learned from player0 and surprised he didn't suggest...</p>
```<code>=ARRAYFORMULA(SPLIT(TRANSPOSE(SUBSTITUTE(TRIM(QUERY(QUERY(A2:B&{"|",CHAR(10)},"select MAX(Col2) where Col1<>'|' group by Col2 pivot Col1"),,100)),CHAR(10),",")),"| ",0))
</code>```

Title: Join range of row using arrayformula

Body:
I have a range of data on column A and B. In Column D , i have a reference for the shotID. I want to make a list for the artist involved for specific shotID.

In E2 i use this :

=JOIN( "," , FILTER($B$2:$B, $A$2:$A= D2))

then copy down to E3,E4. It works as i expected, but i want to do it using array formula. So only use single formula in E2 and that doesn't work that simple :

=arrayformula( JOIN( "," , FILTER($B$2:$B, $A$2:$A= D2:D4)) )

How can i do this ?

Body:
One more possibility that I learned from player0 and surprised he didn't suggest...

=ARRAYFORMULA(SPLIT(TRANSPOSE(SUBSTITUTE(TRIM(QUERY(QUERY(A2:B&{"|",CHAR(10)},"select MAX(Col2) where Col1<>'|' group by Col2 pivot Col1"),,100)),CHAR(10),",")),"| ",0))


问:
Correct way to refer to a file in a directory treee
I have this directory tree:

```<code> main_dir
     data_folder
       file.csv
     script_folder
           script.py
</code>```

Inside script.pyI have:

```<code>df=pd.read_csv('file.csv')
</code>```

What is the correct way to refers to the file.csv in the pandas read_csv

I don't want to use the full path "home/user/main_folder/data/file.csv"

What's the best way to do this?

答:
It depends on where your script is executed (current working directory). To use relative path from your script, use __file__ variable:

```<code>import pandas as pd
import pathlib

data_dir = pathlib.Path(__file__).parent.parent / 'data_dir'

df = pd.read_csv(data_dir / 'file.csv')
</code>```

Body:
I have this directory tree:

 main_dir
     data_folder
       file.csv
     script_folder
           script.py

Inside script.pyI have:

df=pd.read_csv('file.csv')

What is the correct way to refers to the file.csv in the pandas read_csv

I don't want to use the full path "home/user/main_folder/data/file.csv"

What's the best way to do this?

Body:
It depends on where your script is executed (current working directory). To use relative path from your script, use __file__ variable:

import pandas as pd
import pathlib

data_dir = pathlib.Path(__file__).parent.parent / 'data_dir'

df = pd.read_csv(data_dir / 'file.csv')


问:
Check if two times overlap
I want to see if a time I read from a db overlaps with a time provided by a user.

My database looks like this:

```<code>-----------------------------------------------
|organiser|meeting_start|meeting_end|boardroom|
-----------------------------------------------
| John Doe| 1340193600  | 1340195400| big     |
-----------------------------------------------
</code>```

My code looks like this:

```<code>date_default_timezone_set('Africa/Johannesburg');
$from = strtotime($_GET['meeting_date'] . ' ' . $_GET['meeting_start']);
$to = strtotime($_GET['meeting_date'] . ' ' . $_GET['meeting_end']);
$another_meeting = false;
$meeting_date = strtotime($_GET['meeting_date']);
$meeting_next = $meeting_date + 86400;

$result = mysql_query("SELECT meeting_start, meeting_end FROM admin_boardroom_booking WHERE boardroom = '" . $_GET['boardroom'] . "' AND meeting_start >= '" . $meeting_date . "' AND meeting_end < '" . $meeting_next . "'")or die(mysql_error());
while($row = mysql_fetch_array($result)) {
    $from_compare = $row['meeting_start'];
    $to_compare = $row['meeting_end'];

    $intersect = min($to, $to_compare) - max($from, $from_compare);
    if ( $intersect < 0 )
        $intersect = 0;

    $overlap = $intersect / 3600;
    if ( $overlap <= 0 ) {
        $another_meeting = true;
        break;
    }
}

if ($another_meeting)
    echo 'ERROR';
</code>```

If I type two overlapping times on purpose, it doesn't echo error. What am I doing wrong?

答:
My solution that deals with the edge cases and is quite compact:</p>
```<code>    private function meetingOverlap($meeting1, $meeting2){
        if ($meeting1['start']>$meeting2['start'] && $meeting1['start']<$meeting2['end'] ) return true;
        if ($meeting2['start']>$meeting1['start'] && $meeting2['start']<$meeting1['end'] ) return true;
        if ($meeting2['start']==$meeting2['start'] && $meeting1['end']==$meeting2['end'] ) return true;
        return false;
    }
</code>```

Title: Check if two times overlap

Body:
I want to see if a time I read from a db overlaps with a time provided by a user.

My database looks like this:

-----------------------------------------------
|organiser|meeting_start|meeting_end|boardroom|
-----------------------------------------------
| John Doe| 1340193600  | 1340195400| big     |
-----------------------------------------------

My code looks like this:

date_default_timezone_set('Africa/Johannesburg');
$from = strtotime($_GET['meeting_date'] . ' ' . $_GET['meeting_start']);
$to = strtotime($_GET['meeting_date'] . ' ' . $_GET['meeting_end']);
$another_meeting = false;
$meeting_date = strtotime($_GET['meeting_date']);
$meeting_next = $meeting_date + 86400;

$result = mysql_query("SELECT meeting_start, meeting_end FROM admin_boardroom_booking WHERE boardroom = '" . $_GET['boardroom'] . "' AND meeting_start >= '" . $meeting_date . "' AND meeting_end < '" . $meeting_next . "'")or die(mysql_error());
while($row = mysql_fetch_array($result)) {
    $from_compare = $row['meeting_start'];
    $to_compare = $row['meeting_end'];

    $intersect = min($to, $to_compare) - max($from, $from_compare);
    if ( $intersect < 0 )
        $intersect = 0;

    $overlap = $intersect / 3600;
    if ( $overlap <= 0 ) {
        $another_meeting = true;
        break;
    }
}

if ($another_meeting)
    echo 'ERROR';

If I type two overlapping times on purpose, it doesn't echo error. What am I doing wrong?

Body:
My solution that deals with the edge cases and is quite compact:

    private function meetingOverlap($meeting1, $meeting2){
        if ($meeting1['start']>$meeting2['start'] && $meeting1['start']<$meeting2['end'] ) return true;
        if ($meeting2['start']>$meeting1['start'] && $meeting2['start']<$meeting1['end'] ) return true;
        if ($meeting2['start']==$meeting2['start'] && $meeting1['end']==$meeting2['end'] ) return true;
        return false;
    }


问:
How to use gin as a server to write prometheus exporter metrics
This is the official prometheus golang-client example：

```<code>package main

import (
    "log"
    "net/http"

    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/promhttp"
)

var cpuTemp = prometheus.NewGauge(prometheus.GaugeOpts{
        Name: "cpu_temperature_celsius",
        Help: "Current temperature of the CPU.",
    })

func init() {
    // Metrics have to be registered to be exposed:
    prometheus.MustRegister(cpuTemp)
}

func main() {
    cpuTemp.Set(65.3)

    // The Handler function provides a default handler to expose metrics
    // via an HTTP server. "/metrics" is the usual endpoint for that.
    http.Handle("/metrics", promhttp.Handler())
    log.Fatal(http.ListenAndServe(":8080", nil))
}
</code>```

In this code, the http server uses the promhttp library.

How to modify the metrics handler when using the gin framework? I did not find answers in the documentation.

答:
Use gin wrapper</p>
```<code>router.GET("/metrics", gin.WrapH(promhttp.Handler()))
</code>```

Body:
This is the official prometheus golang-client example：

package main

import (
    "log"
    "net/http"

    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/promhttp"
)

var cpuTemp = prometheus.NewGauge(prometheus.GaugeOpts{
        Name: "cpu_temperature_celsius",
        Help: "Current temperature of the CPU.",
    })

func init() {
    // Metrics have to be registered to be exposed:
    prometheus.MustRegister(cpuTemp)
}

func main() {
    cpuTemp.Set(65.3)

    // The Handler function provides a default handler to expose metrics
    // via an HTTP server. "/metrics" is the usual endpoint for that.
    http.Handle("/metrics", promhttp.Handler())
    log.Fatal(http.ListenAndServe(":8080", nil))
}

In this code, the http server uses the promhttp library.

How to modify the metrics handler when using the gin framework? I did not find answers in the documentation.

Body:
Use gin wrapper

router.GET("/metrics", gin.WrapH(promhttp.Handler()))


问:
Unhashable type 'np.ndarray' in matplotlib 3d stem example from documentation
The matplotlib documentation contains the following code sample

```<code>import matplotlib.pyplot as plt
import numpy as np

theta = np.linspace(0, 2*np.pi)
x = np.cos(theta - np.pi/2)
y = np.sin(theta - np.pi/2)
z = theta

fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
ax.stem(x, y, z)

plt.show()
</code>```

However, when I copy and paste this into a juypter notebook, I get an error:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-42-b5d3d05087f2> in <module>
      8
      9 fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
---> 10 ax.stem(x, y, z)
     11
     12 plt.show()

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
   1445     def inner(ax, *args, data=None, **kwargs):
   1446         if data is None:
-> 1447             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1448
   1449         bound = new_sig.bind(ax, *args, **kwargs)

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in stem(self, linefmt, markerfmt, basefmt, bottom, label, use_line_collection, *args)
   2812             else:
   2813                 linestyle, linemarker, linecolor = \
-> 2814                     _process_plot_format(linefmt)
   2815         else:
   2816             linestyle, linemarker, linecolor = _process_plot_format(linefmt)

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _process_plot_format(fmt)
    130     while i < len(fmt):
    131         c = fmt[i]
--> 132         if fmt[i:i+2] in mlines.lineStyles:  # First, the two-char styles.
    133             if linestyle is not None:
    134                 raise ValueError(

TypeError: unhashable type: 'numpy.ndarray'
</code>```

I suspect there's something wrong with my python kernel, rather than the matplotlib documentation, but I can't figure it out. Any help would be appreciated.

Numpy version: 1.19.5

Matplotlib version: 3.3.4

答:
Like many matplotlib functions that accept multiple inputs, stem wants the multiple inputs as a sequence.  So:

```<code>ax.stem( [x,y,z] )
</code>```

What you're doing specifies x as the input, y as the line styles, and z as the marker format.  Thus, when it went to look up the line styles, it was the wrong kind of structure.

99.99% of the time when you start thinking it's a bug in Python, you're wrong.

Body:
The matplotlib documentation contains the following code sample

import matplotlib.pyplot as plt
import numpy as np

theta = np.linspace(0, 2*np.pi)
x = np.cos(theta - np.pi/2)
y = np.sin(theta - np.pi/2)
z = theta

fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
ax.stem(x, y, z)

plt.show()

However, when I copy and paste this into a juypter notebook, I get an error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-42-b5d3d05087f2> in <module>
      8
      9 fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
---> 10 ax.stem(x, y, z)
     11
     12 plt.show()

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
   1445     def inner(ax, *args, data=None, **kwargs):
   1446         if data is None:
-> 1447             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1448
   1449         bound = new_sig.bind(ax, *args, **kwargs)

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in stem(self, linefmt, markerfmt, basefmt, bottom, label, use_line_collection, *args)
   2812             else:
   2813                 linestyle, linemarker, linecolor = \
-> 2814                     _process_plot_format(linefmt)
   2815         else:
   2816             linestyle, linemarker, linecolor = _process_plot_format(linefmt)

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _process_plot_format(fmt)
    130     while i < len(fmt):
    131         c = fmt[i]
--> 132         if fmt[i:i+2] in mlines.lineStyles:  # First, the two-char styles.
    133             if linestyle is not None:
    134                 raise ValueError(

TypeError: unhashable type: 'numpy.ndarray'

I suspect there's something wrong with my python kernel, rather than the matplotlib documentation, but I can't figure it out. Any help would be appreciated.

Numpy version: 1.19.5

Matplotlib version: 3.3.4

Body:
Like many matplotlib functions that accept multiple inputs, stem wants the multiple inputs as a sequence.  So:

ax.stem( [x,y,z] )

What you're doing specifies x as the input, y as the line styles, and z as the marker format.  Thus, when it went to look up the line styles, it was the wrong kind of structure.

99.99% of the time when you start thinking it's a bug in Python, you're wrong.


问:
FastAPI: Swagger UI does not render because of custom Middleware
So I have a custom middleware like this:

Its objective is to add some meta_data fields to every response from all endpoints of my FastAPI app.

@app.middelware("http")
async def add_metadata_to_response_payload(request: Request, call_next):

    response = await call_next(request)

    body = b""
    async for chunk in response.body_iterator:
        body+=chunk

    data = {}
    data["data"] = json.loads(body.decode())
    data["metadata"] = {
        "some_data_key_1": "some_data_value_1",
        "some_data_key_2": "some_data_value_2",
        "some_data_key_3": "some_data_value_3"
    }

    body = json.dumps(data, indent=2, default=str).encode("utf-8")

    return Response(
        content=body,
        status_code=response.status_code,
        media_type=response.media_type
    )

```
<p>However, when I served my app using uvicorn, and launched the swagger URL, here is what I see:</p>
```
Unable to render this definition

The provided definition does not specify a valid version field.

Please indicate a valid Swagger or OpenAPI version field. Supported version fields are
Swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0)

```
<p>With a lot of debugging, I found that this error was due to the custom middleware and specifically this line:</p>
<pre class="lang-py prettyprint-override"><code>body = json.dumps(data, indent=2, default=str).encode("utf-8")
</code>```

If I simply comment out this line, swagger renders just fine for me. However, I need this line for passing the content argument in Response from Middleware. How to sort this out?

UPDATE:

I tried the following:
body = json.dumps(data, indent=2).encode("utf-8")
by removing default arg, the swagger did successfully load. But now when I hit any of the APIs, here is what swagger tells me along with response payload on screen:
Unrecognised response type; displaying content as text

More Updates (6th April 2022):

Got a solution to fix 1 part of the problem by Chris, but the swagger wasn't still loading. The code was hung up in the middleware level indefinitely and the page was not still loading.

So, I found in all these places:

https://github.com/encode/starlette/issues/919

Blocked code while using middleware and dependency injections to log requests in FastAPI(Python)

https://github.com/tiangolo/fastapi/issues/394

that this way of adding custom middleware works by inheriting from BaseHTTPMiddleware in Starlette and has its own issues (something to do with awaiting inside middleware, streamingresponse and normal response, and the way it is called). I don't understand it yet.

答:
You are substituting the body of the swagger html with json data taken from both middleware and response (html response in this case).

You'll end up with something like

```<code>{
    "data": "<html>....</html>",
    "metadata": {
        "some_data_key_1": "some_data_value_1",
        "some_data_key_2": "some_data_value_2",
        "some_data_key_3": "some_data_value_3"
    }
}
</code>```

Of course this won't work.

Possible Solution

Perform a check on the content type of the response in the middleware. Extend the response if it json, otherwise leave it as it is.

Note:
This can only be done if it can be safely assumed that every json response needs the metadata to be added, while html content type doesn't. (you can change the check according to your needs)

Another possible solution

Wait for the following issue to be merged into the current starlettes implementation and fastapi to start using this version.

https://github.com/tiangolo/fastapi/issues/1174
https://github.com/encode/starlette/pull/1286

Body:
So I have a custom middleware like this:

Its objective is to add some meta_data fields to every response from all endpoints of my FastAPI app.

@app.middelware("http")
async def add_metadata_to_response_payload(request: Request, call_next):

    response = await call_next(request)

    body = b""
    async for chunk in response.body_iterator:
        body+=chunk

    data = {}
    data["data"] = json.loads(body.decode())
    data["metadata"] = {
        "some_data_key_1": "some_data_value_1",
        "some_data_key_2": "some_data_value_2",
        "some_data_key_3": "some_data_value_3"
    }

    body = json.dumps(data, indent=2, default=str).encode("utf-8")

    return Response(
        content=body,
        status_code=response.status_code,
        media_type=response.media_type
    )

However, when I served my app using uvicorn, and launched the swagger URL, here is what I see:

Unable to render this definition

The provided definition does not specify a valid version field.

Please indicate a valid Swagger or OpenAPI version field. Supported version fields are
Swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0)

With a lot of debugging, I found that this error was due to the custom middleware and specifically this line:

body = json.dumps(data, indent=2, default=str).encode("utf-8")

If I simply comment out this line, swagger renders just fine for me. However, I need this line for passing the content argument in Response from Middleware. How to sort this out?

UPDATE:

I tried the following:
body = json.dumps(data, indent=2).encode("utf-8")
by removing default arg, the swagger did successfully load. But now when I hit any of the APIs, here is what swagger tells me along with response payload on screen:
Unrecognised response type; displaying content as text

More Updates (6th April 2022):

Got a solution to fix 1 part of the problem by Chris, but the swagger wasn't still loading. The code was hung up in the middleware level indefinitely and the page was not still loading.

So, I found in all these places:

https://github.com/encode/starlette/issues/919

Blocked code while using middleware and dependency injections to log requests in FastAPI(Python)

https://github.com/tiangolo/fastapi/issues/394

that this way of adding custom middleware works by inheriting from BaseHTTPMiddleware in Starlette and has its own issues (something to do with awaiting inside middleware, streamingresponse and normal response, and the way it is called). I don't understand it yet.

Body:
You are substituting the body of the swagger html with json data taken from both middleware and response (html response in this case).

You'll end up with something like

{
    "data": "<html>....</html>",
    "metadata": {
        "some_data_key_1": "some_data_value_1",
        "some_data_key_2": "some_data_value_2",
        "some_data_key_3": "some_data_value_3"
    }
}

Of course this won't work.

Possible Solution

Perform a check on the content type of the response in the middleware. Extend the response if it json, otherwise leave it as it is.

Note:
This can only be done if it can be safely assumed that every json response needs the metadata to be added, while html content type doesn't. (you can change the check according to your needs)

Another possible solution

Wait for the following issue to be merged into the current starlettes implementation and fastapi to start using this version.

https://github.com/tiangolo/fastapi/issues/1174
https://github.com/encode/starlette/pull/1286