问:
Python speech_recognition pyaudio error
I am writing a python code to detect my microphone but speech_recognition is not able to detect my Input device.

```<code>import speech_recognition as sr
mic_index = 11
    for index, name in enumerate(sr.Microphone.list_microphone_names()):
        if("USB Device" in name):
            mic_index = index
            break
</code>```

But it gives me error. So I checked my Speech Recognition module by running the command python -m speech_recognition and got the following error:

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

File "/home/arqam/anaconda3/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/arqam/anaconda3/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/arqam/anaconda3/lib/python3.6/site-packages/speech_recognition/__main__.py", line 4, in <module>
    m = sr.Microphone()
  File "/home/arqam/anaconda3/lib/python3.6/site-packages/speech_recognition/__init__.py", line 86, in __init__
    device_info = audio.get_device_info_by_index(device_index) if device_index is not None else audio.get_default_input_device_info()
  File "/home/arqam/anaconda3/lib/python3.6/site-packages/pyaudio.py", line 949, in get_default_input_device_info
    device_index = pa.get_default_input_device()
OSError: No Default Input Device Available
</code>```

I checked my IO devices number and pyAudio file location and it gave the following location:

```<code>>>> pa.get_device_count()
0
>>> pyaudio.pa.__file__
'/home/arqam/anaconda3/lib/python3.6/site-packages/_portaudio.cpython-36m-x86_64-linux-gnu.so'
</code>```

I have seen all the stackoverflow answer and have spent a full day for this problem but still could not find an answer.

答: I also had got the same error. Your speech recognition module might not have downloaded properly. To fix that you should search on Google, 'Unofficial Python Binaries'. Click on the first link. The you will see a webpage that contains a lot of python module .wheel files. The find pyaudio link using 'ctrl+f'. On clicking on it you will go to a bunch of pyaudio files. Then you need to find the wheel file that supports your python version. Install it. Then open the folder where you saved that wheel file. Open a powershell or cmd window there and write pip install (name of the wheel file). Then you pyaudio will get downloaded and it should start working!</p>

Title: Python speech_recognition pyaudio error

Body:
I am writing a python code to detect my microphone but speech_recognition is not able to detect my Input device.

import speech_recognition as sr
mic_index = 11
    for index, name in enumerate(sr.Microphone.list_microphone_names()):
        if("USB Device" in name):
            mic_index = index
            break

But it gives me error. So I checked my Speech Recognition module by running the command python -m speech_recognition and got the following error:

Traceback (most recent call last):

File "/home/arqam/anaconda3/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/arqam/anaconda3/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/arqam/anaconda3/lib/python3.6/site-packages/speech_recognition/__main__.py", line 4, in <module>
    m = sr.Microphone()
  File "/home/arqam/anaconda3/lib/python3.6/site-packages/speech_recognition/__init__.py", line 86, in __init__
    device_info = audio.get_device_info_by_index(device_index) if device_index is not None else audio.get_default_input_device_info()
  File "/home/arqam/anaconda3/lib/python3.6/site-packages/pyaudio.py", line 949, in get_default_input_device_info
    device_index = pa.get_default_input_device()
OSError: No Default Input Device Available

I checked my IO devices number and pyAudio file location and it gave the following location:

>>> pa.get_device_count()
0
>>> pyaudio.pa.__file__
'/home/arqam/anaconda3/lib/python3.6/site-packages/_portaudio.cpython-36m-x86_64-linux-gnu.so'

I have seen all the stackoverflow answer and have spent a full day for this problem but still could not find an answer.


来源: stackexchange

问:
Get readable text only from clipboard
I already know how to get plain text from the clipboard in Java, but sometimes the text is encoded in some weird DataFlavor, like when copying from Microsoft Word or from a website or even source code from Eclipse.

How to extract pure plain text from these DataFlavors?

答:
First I haven't worked with clipboard but this seems intresting

From http://docstore.mik.ua/orelly/java/awt/ch16_01.htm

"To read data from the clipboard, a program calls the Transferable.getTransferData() method. If the data is represented by a DataFlavor that doesn't correspond to a Java class (for example, plainTextFlavor), getTransferData() returns an InputStream for you to read the data from."

So if you give it a class which doesn't correspont you get the InputStream and then you can read the "pure" text from the InputStream yourself.

ContentLicense: CC BY-SA 3.0

Title: Get readable text only from clipboard


问:
Gitlab: Maintainer permissions when shared group with group not working as expected
I am running a gitlab-ce instance where we solve access level on group level by sharing groups with user groups. An example:

There is a group products with a couple of projects in there. No user is directly added as member to that group. There is another group called developers. Product developers are  added to developers with maintainer access.

The group products is shared with developers with a maximum role of maintainer.

With that I would assume, that I can transfer a project that I am owner of to group products. However, the list of groups I can transfer my project to only contains groups where I am a direct member with the maintainer role.

TLDR:

Group products is shared with group developers with max role maintainer

User Bob is member of developers with the maintainer role

Bob is owner of project bobs_project

Bob cannot transfer bobs_project to products (but he could transfer it to developers)

From my understanding of the relevant documentation Bob should have the same rights in products as someone directly added as maintainer to products. However, that seems not to be the case.

Am I missing something?

答:
A few points from the documentation you reference might be relevant in your setup:

When transferring groups, note:

You can only transfer groups to groups you manage.

Only explicit group membership is transferred, not inherited membership. If the group’s owners have only inherited membership, this leaves the group without an owner. In this case, the user transferring the group becomes the group’s owner.

Here, Bob has inherited rights in products, not direct rights. That might explain why the group is not listed.

ContentLicense: CC BY-SA 4.0


问:
FileNotFoundError, when I run shutil.copy, 1 particular ".dylib" file throws FileNotFoundError error every time
I am making a python app and one of it's functions involves copying the contents of one directory to several different locations. Some of these files are copied to the same directory in which they currently reside and are renamed. It almost always works except when it hit this one particular file.

This is the code that does the copying.

```<code>shutil.copy(original_path_and_file,os.path.join(redun.path, redun.file_name))
</code>```

The particular copy that causes the crash is when it's trying to copy /Users/<myusername>/Desktop/archive1/test_2_here/myproject/liboqs.dylib to /Users/<myusername>/Desktop/archive1/test_2_here/myproject/liboqs.0.dylib

This is the error that appears in my terminal:

```<code>FileNotFoundError: [Errno 2] No such file or directory: '/Users/<myusername>/Desktop/archive1/test_2_here/myproject/liboqs.dylib'
</code>```

Why does this file throw the error and none of the other files that it copies throw any errors?

Update

The file is actually an "Alias" according to finder:

答:
Perhaps you could attempt to solve it by connecting the directory path and the filename like follows:

One problem here is that you do not specify the path of the file. As you are executing the command from the parent directory, the script has no way of knowing that testfile2.txt is in a subdirectory of your input directory. To fix this, use:

```<code>shutil.copy(os.path.join(foldername, filename), copyDirAbs)
</code>```

or

```<code># Recursively walk the Search Directory, copying matching files
# to the Copy Directory
for foldername, subfolders, filenames in os.walk(searchDirAbs):
    print('Searching files in %s...' % (foldername))
    for filename in filenames:
        if filename.endswith('.%s' % extension):
            print('Copying ' + filename)
            print('Copying to ' + copyDirAbs)
            totalCopyPath = os.path.join(searchDirAbs, filename)
            shutil.copy(totalCopyPath, copyDirAbs)

print('Done.')

</code>```

The Python FileNotFoundError: [Errno 2] No such file or directory error is often raised by the os library. This error tells you that you are trying to access a file or folder that does not exist. To fix this error, check that you are referring to the right file or folder in your program.

Body:
I am making a python app and one of it's functions involves copying the contents of one directory to several different locations. Some of these files are copied to the same directory in which they currently reside and are renamed. It almost always works except when it hit this one particular file.

This is the code that does the copying.

shutil.copy(original_path_and_file,os.path.join(redun.path, redun.file_name))

The particular copy that causes the crash is when it's trying to copy /Users/<myusername>/Desktop/archive1/test_2_here/myproject/liboqs.dylib to /Users/<myusername>/Desktop/archive1/test_2_here/myproject/liboqs.0.dylib

This is the error that appears in my terminal:

FileNotFoundError: [Errno 2] No such file or directory: '/Users/<myusername>/Desktop/archive1/test_2_here/myproject/liboqs.dylib'

Why does this file throw the error and none of the other files that it copies throw any errors?

Update

The file is actually an "Alias" according to finder:

Body:
Perhaps you could attempt to solve it by connecting the directory path and the filename like follows:

One problem here is that you do not specify the path of the file. As you are executing the command from the parent directory, the script has no way of knowing that testfile2.txt is in a subdirectory of your input directory. To fix this, use:

shutil.copy(os.path.join(foldername, filename), copyDirAbs)

or

# Recursively walk the Search Directory, copying matching files
# to the Copy Directory
for foldername, subfolders, filenames in os.walk(searchDirAbs):
    print('Searching files in %s...' % (foldername))
    for filename in filenames:
        if filename.endswith('.%s' % extension):
            print('Copying ' + filename)
            print('Copying to ' + copyDirAbs)
            totalCopyPath = os.path.join(searchDirAbs, filename)
            shutil.copy(totalCopyPath, copyDirAbs)

print('Done.')

The Python FileNotFoundError: [Errno 2] No such file or directory error is often raised by the os library. This error tells you that you are trying to access a file or folder that does not exist. To fix this error, check that you are referring to the right file or folder in your program.


问:
Using the HelpProvider class to show help, UI is always behind help window
I have a C# Winforms app that uses the HelpProvider class.
Whenever i press F1 to bring up help, the help window will always be on top of my application, I cannot bring my application UI to the foreground. I can still interact with my UI, but the help window will remain on top.

Is this by design of HelpProvider? Or am I missing something?

答:
There is a solution to this issue, a bit dirty, but it works.
The thing is, the help window opened by HelpProvider is always on top of its parent window control, which is determined by Control instance in first parameter of Help.ShowHelp. Even if you specify null there, the main application form is still used as parent window.
To avoid this, one can create a dummy form, which will be used as a help parent form. This form will be never shown, but still, help window will be “on top” of it, effectively being NOT on top of all other application windows.

```<code>public static class AppHelp
{
   private static Form mFrmDummyHost = new Form();

   public static void ShowChm()
   {
      Help.ShowHelp(mFrmDummyHost, "my_help.chm");
   }
}
</code>```

Of course, all other Help.ShowHelp overloads can be called this way as well.

Hope this helps people like me, searching for answers to never-getting-old questions ;)

ContentLicense: CC BY-SA 2.5

Body:
There is a solution to this issue, a bit dirty, but it works.
The thing is, the help window opened by HelpProvider is always on top of its parent window control, which is determined by Control instance in first parameter of Help.ShowHelp. Even if you specify null there, the main application form is still used as parent window.
To avoid this, one can create a dummy form, which will be used as a help parent form. This form will be never shown, but still, help window will be “on top” of it, effectively being NOT on top of all other application windows.

public static class AppHelp
{
   private static Form mFrmDummyHost = new Form();

   public static void ShowChm()
   {
      Help.ShowHelp(mFrmDummyHost, "my_help.chm");
   }
}

Of course, all other Help.ShowHelp overloads can be called this way as well.

Hope this helps people like me, searching for answers to never-getting-old questions ;)


问:
ggplot, ggarrange - several plots one legend
I am making two plots showing two different aspects of the same data set.

```<code>profile=ggplot(active,aes(distance,z,group=arm))
profile=profile+geom_line(aes(color=arm),size=0.5)
profile=profile+ggtitle(paste('Configuration',v))+guides(color="none")
slope=ggplot(active,aes(distance,slope,group=arm))
slope=slope+geom_line(aes(color=arm),size=1)
figure=ggarrange(profile, slope,
      labels = c("A", "B"),
      ncol = 1, nrow = 2)
</code>```

This makes the plots stacked on top of each other, so it is easy to compare the two datasets, but it comes out with a redundant legend.

I can remove the legend on the first plot by removing the +guides(color="none")
But then the upper plot is wider and the x-axises does not match up any longer.

How can I plot the upper part as if the legend was there? Preferably I would like something like this, how is that doable? (the example is made manually using gimp, so the plots should line up)

答:
Since I do not have your active dataset, I cannot guarantee the following would work.

ggpubr

```<code>library(tidyverse)
library(ggpubr)

figure = ggpubr::ggarrange(profile, slope,
                           labels = c("A", "B"),
                           ncol = 1, nrow = 2,
                           common.legend = T)
</code>```

patchwork

```<code>library(tidyverse)
library(patchwork)

(profile / slope) + plot_layout(guides = 'collect') +
  plot_annotation(tag_levels = 'A')
</code>```

Body:
I am making two plots showing two different aspects of the same data set.

profile=ggplot(active,aes(distance,z,group=arm))
profile=profile+geom_line(aes(color=arm),size=0.5)
profile=profile+ggtitle(paste('Configuration',v))+guides(color="none")
slope=ggplot(active,aes(distance,slope,group=arm))
slope=slope+geom_line(aes(color=arm),size=1)
figure=ggarrange(profile, slope,
      labels = c("A", "B"),
      ncol = 1, nrow = 2)

This makes the plots stacked on top of each other, so it is easy to compare the two datasets, but it comes out with a redundant legend.

I can remove the legend on the first plot by removing the +guides(color="none")
But then the upper plot is wider and the x-axises does not match up any longer.

How can I plot the upper part as if the legend was there? Preferably I would like something like this, how is that doable? (the example is made manually using gimp, so the plots should line up)

Body:
Since I do not have your active dataset, I cannot guarantee the following would work.

ggpubr

library(tidyverse)
library(ggpubr)

figure = ggpubr::ggarrange(profile, slope,
                           labels = c("A", "B"),
                           ncol = 1, nrow = 2,
                           common.legend = T)

patchwork

library(tidyverse)
library(patchwork)

(profile / slope) + plot_layout(guides = 'collect') +
  plot_annotation(tag_levels = 'A')


问:
what is this format and how to read it in pandas
I have a file like this:

```<code>{"Name": "John", "age": 15}{"Name": "Anna", "age": 12}
</code>```

they are on the same line.  What kind of format this file belongs to?
How to read it into pandas dataframe so that

```<code>name    age
John    15
Anna    12
</code>```

Thanks!

答:
As a supplement for @Raymond Kwok's answer. We don't need know the field names before converting the json to DataFrame.

import pandas as pd
import re
# read file code same, so skip
js = '{"Name": "John", "age": 15}{"Name": "Anna", "age": 12}'
matches = re.findall(r'\{.+?}', js)
print(matches)
df = pd.DataFrame.from_dict(matches)
print(df)
```
<p>output:</p>
<pre class="lang-sh prettyprint-override"><code>['{"Name": "John", "age": 15}', '{"Name": "Anna", "age": 12}']
                             0
0  {"Name": "John", "age": 15}
1  {"Name": "Anna", "age": 12}
</code>```

Body:
I have a file like this:

{"Name": "John", "age": 15}{"Name": "Anna", "age": 12}

they are on the same line.  What kind of format this file belongs to?
How to read it into pandas dataframe so that

name    age
John    15
Anna    12

Thanks!

Body:
As a supplement for @Raymond Kwok's answer. We don't need know the field names before converting the json to DataFrame.

import pandas as pd
import re
# read file code same, so skip
js = '{"Name": "John", "age": 15}{"Name": "Anna", "age": 12}'
matches = re.findall(r'\{.+?}', js)
print(matches)
df = pd.DataFrame.from_dict(matches)
print(df)

output:

['{"Name": "John", "age": 15}', '{"Name": "Anna", "age": 12}']
                             0
0  {"Name": "John", "age": 15}
1  {"Name": "Anna", "age": 12}


问:
React toggle responsive sidebar based on browser width &/or user clicks
React noob here. I am creating a dashboard with three parts. Sidebar | Navbar & content below navbar.
Sidebar behavior should be: open initially; auto-hide when browser-width < 498px; auto-open when browser width is increased beyond 498px; open/close when navbar toggle is hit, regardless of browser window width (ie., mobile or desktop).
I know how to do this in jQuery but want to learn React way. Searching the forums and Google, I created a working model. However, I sense that the code can be simplified or at least audited for issues. Hoping for some senior enlightenment, all help is welcomed. Worried about dependency warnings and calling of 2 handlers. Did not use addEventListener as I read Safari may have issues.
Notes, I avoided using css media query for auto-hide, as I could not figure out how to override css file media query of display:none from React when click component is used. Using react 17.0.2; bootstrap 5.1.3;

Dashboard.js

```<code>import { useEffect, useRef, useState } from 'react';
import "./Dashboard.css";
import Navbar from "./Navbar";
import Sidebar from "./Sidebar";

const Dashboard = () => {
const sidebarRef = useRef(null); // used to get sidebar width
const [usMobile, setMobile] = useState("");
const mq = window.matchmedia("(max-width: 498px)");
const [firsTime, setFirsTime] = useState(true);

useEffect(() => {
  //handle sidebar display clicks from Navbar
  // makes/sets initial sidebar state to open
  // returns true when window is < 498px
  // unmount cleanup handler
  toggleSidebar();
  mq.addListener(toggleSidebar);
  return () => mq.removeListener(toggleSidebar);
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // warning about dependency here

useEffect(() => {
  // handles sidebar display based on resize
  // returns treu when window is < 498
  mq.addListener(hideSideBar);
  return () => mq.removeListener(hideSideBar);
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // warning about dependency here

const hideSideBar = () => {
  if(mq.matches) {
    setMobile(true);
  } else {
    setMobile(false);
  }
}

// toggle sidebar based on user clicks
const toggleSidebar = ( clicked ) => {
  let sidebarWidth = sidebarRef.current.offsetWidth;
  if (firsTime) {
     setShowSidebar(true);
     setMobile(false);
     setFirstTime(false);
  } else {
     if ( clicked = "yes") {
        if (sidebarWidth == 0){
           setShowSidebar(true);
           setMobile(false);
        } else {
           setShowSidebar(false);
        }
        clicked = "";
     }
  }
}

return (
  <span ref={sidebarRef}>
    {!isMobile && showSidebar && <Sidebar onClick={toggleSidebar} />}
  </span>
  <div className="flex-fill content-wrapper">
    <Navbar showSideBar={showSidebar} onClick={toggleSidebar} />
  </div>
);
}

export default Dashboard;
</code>```

Navbar.js

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

const Navbar = (props) => {
  // eslint-disable-next-line no-unused-vars
  // set is unused but it will not work otherwise
  const [clicked, setClicked] = useState("yes");

  return (
    <div className="d-flex justify-content-between bg-white py-2 ps-3 pe-4">
      <div className="col-auto">
        <button
            className="menu-icon-btn"
            onClick={() => props.onClick(clicked)} >
        </button>
      </div>
    </div>
)
}
export default Navbar;
</code>```

Sidebar.js

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

const Sidebar = (props) => {
  const [clicked, setClicked] = useState('yes');

  return (
    <div className="d-flex flex-column flex-shrink-0 text-white bg-dark sidebar">
      <span className="fs4">Sidebar Title</span>
      <ul className="nav nav-pills flex-column mb-auto">
        <li className="nav-item">
            Home
        </li>
      </ul>
      <hr>
      <span id="toggle-x"
            className="btn btn-outline-primary border-0 inline d-md-none mx-auto mb-2">
            aria-label="Toggle Sidebar Nav"
            onClick={() => props.onClick(clicked)} >
              CLOSE
       </span>
    </div>
  )
}

export default Sidebar;
</code>```

Dashboard.css
Most all css is from bootstrap; these are just app custom styles

```<code>.menu-icon-btn {
  background: none;
  border: none;
  padding: 0;
}

.toggle-icon {
  width: 32px;
  height: 32px;
  fill: var(--medium-gray);
  cursor: pointer;
}

.menu-icon {
  width: 20px;
  height: 20px;
  fill: var(--medium-gray);
  cursor: pointer;
}

.sidebar,
.content-wrapper {
  height: 100vh;
}

.sidebar-wrapper {
  width: 200px;
}
/* Omitted the following as I was unable to force it to change from within React. In jQuery(show/hide seem to override this just fine.)*/
/* @media screen and (min-width: 0px) and (max-width: 700px) {
  .sidebar-wrapper {
    display: none;
  }
} */
</code>```

New Dashboard.js

```<code>const Dashboard = () => {
    const isDesktop = () => window.innerWidth > 598;
    const [sidebarStatus, setSidebarStatus] = useState("");

    useEffect(() => {
        window.addEventListener("resize", () => {
            setSidebarStatus(isDesktop());
        });
        return () => window.removeEventListener("resize", isDesktop);
    }, []);

    const toggleSidebar = (open) => {
        setSidebarStatus(open);
    };

    return (

        {sidebarStatus && (
          <Sidebar showSideBar={sidebarStatus} onClick={toggleSidebar} />
        )}

    )
}
</code>```

New Navbar.js

```<code>const Navbar = (props) => {

return (
        <button
          id="toggle"
          className="menu-icon-btn py-2"
          data-menu-icon-btn
          onClick={() => props.onClick(!props.showSideBar)}
        > Toggle Sidebar
        </button>
)
}

</code>```

答:
Your code is broken.. i made a little change to your code:

```<code>import React, { useEffect, useRef, useState } from "react";
import "./Dashboard.css";
import Navbar from "./Navbar";
import Sidebar from "./Sidebar";

const Dashboard = () => {
  // i don't know what is using for..
  const sidebarRef = useRef(null); // used to get sidebar width
  const [isMobile, setMobile] = useState(document.body.clientWidth <= 498);
  // use 'init' | 'open' | 'close', that you don't need remember if suer clicked
  const [sidebarStatus, setSidebarStatus] = useState("init");

  useEffect(() => {
    // add listener only once, or many listeners would be created every render
    const mq = window.matchMedia("(max-width: 498px)");
    mq.addListener((res) => {
      setMobile(res.matches);
    });
    return () => mq.removeListener(toggleSidebar);
  }, []);

  // react use status change fire effects, fire function manually is tired
  // here calculate should show sidebar
  const showSidebar =
    sidebarStatus === "open" || (!isMobile && sidebarStatus === "init");

  const toggleSidebar = (open) => {
    setSidebarStatus(open ? "open" : "close");
  };

  return (
    <>
      <span ref={sidebarRef}>
        {showSidebar && <Sidebar onClick={toggleSidebar} />}
      </span>
      <div className="flex-fill content-wrapper">
        <Navbar showSideBar={showSidebar} onClick={toggleSidebar} />
      </div>
    </>
  );
};

export default Dashboard;
</code>```

attention that toggleSidebar param from navbar and sidebar are const true and false. Do not use status in different file

Body:
React noob here. I am creating a dashboard with three parts. Sidebar | Navbar & content below navbar.
Sidebar behavior should be: open initially; auto-hide when browser-width < 498px; auto-open when browser width is increased beyond 498px; open/close when navbar toggle is hit, regardless of browser window width (ie., mobile or desktop).
I know how to do this in jQuery but want to learn React way. Searching the forums and Google, I created a working model. However, I sense that the code can be simplified or at least audited for issues. Hoping for some senior enlightenment, all help is welcomed. Worried about dependency warnings and calling of 2 handlers. Did not use addEventListener as I read Safari may have issues.
Notes, I avoided using css media query for auto-hide, as I could not figure out how to override css file media query of display:none from React when click component is used. Using react 17.0.2; bootstrap 5.1.3;

Dashboard.js

import { useEffect, useRef, useState } from 'react';
import "./Dashboard.css";
import Navbar from "./Navbar";
import Sidebar from "./Sidebar";

const Dashboard = () => {
const sidebarRef = useRef(null); // used to get sidebar width
const [usMobile, setMobile] = useState("");
const mq = window.matchmedia("(max-width: 498px)");
const [firsTime, setFirsTime] = useState(true);

useEffect(() => {
  //handle sidebar display clicks from Navbar
  // makes/sets initial sidebar state to open
  // returns true when window is < 498px
  // unmount cleanup handler
  toggleSidebar();
  mq.addListener(toggleSidebar);
  return () => mq.removeListener(toggleSidebar);
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // warning about dependency here

useEffect(() => {
  // handles sidebar display based on resize
  // returns treu when window is < 498
  mq.addListener(hideSideBar);
  return () => mq.removeListener(hideSideBar);
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // warning about dependency here

const hideSideBar = () => {
  if(mq.matches) {
    setMobile(true);
  } else {
    setMobile(false);
  }
}

// toggle sidebar based on user clicks
const toggleSidebar = ( clicked ) => {
  let sidebarWidth = sidebarRef.current.offsetWidth;
  if (firsTime) {
     setShowSidebar(true);
     setMobile(false);
     setFirstTime(false);
  } else {
     if ( clicked = "yes") {
        if (sidebarWidth == 0){
           setShowSidebar(true);
           setMobile(false);
        } else {
           setShowSidebar(false);
        }
        clicked = "";
     }
  }
}

return (

    {!isMobile && showSidebar && <Sidebar onClick={toggleSidebar} />}

    <Navbar showSideBar={showSidebar} onClick={toggleSidebar} />

);
}

export default Dashboard;

Navbar.js

import {useState} from 'react';

const Navbar = (props) => {
  // eslint-disable-next-line no-unused-vars
  // set is unused but it will not work otherwise
  const [clicked, setClicked] = useState("yes");

  return (

        <button
            className="menu-icon-btn"
            onClick={() => props.onClick(clicked)} >
        </button>

)
}
export default Navbar;

Sidebar.js

import {useState} from 'react';

const Sidebar = (props) => {
  const [clicked, setClicked] = useState('yes');

  return (

      Sidebar Title

            Home

            aria-label="Toggle Sidebar Nav"
            onClick={() => props.onClick(clicked)} >
              CLOSE

  )
}

export default Sidebar;

Dashboard.css
Most all css is from bootstrap; these are just app custom styles

.menu-icon-btn {
  background: none;
  border: none;
  padding: 0;
}

.toggle-icon {
  width: 32px;
  height: 32px;
  fill: var(--medium-gray);
  cursor: pointer;
}

.menu-icon {
  width: 20px;
  height: 20px;
  fill: var(--medium-gray);
  cursor: pointer;
}

.sidebar,
.content-wrapper {
  height: 100vh;
}

.sidebar-wrapper {
  width: 200px;
}
/* Omitted the following as I was unable to force it to change from within React. In jQuery(show/hide seem to override this just fine.)*/
/* @media screen and (min-width: 0px) and (max-width: 700px) {
  .sidebar-wrapper {
    display: none;
  }
} */

New Dashboard.js

const Dashboard = () => {
    const isDesktop = () => window.innerWidth > 598;
    const [sidebarStatus, setSidebarStatus] = useState("");

    useEffect(() => {
        window.addEventListener("resize", () => {
            setSidebarStatus(isDesktop());
        });
        return () => window.removeEventListener("resize", isDesktop);
    }, []);

    const toggleSidebar = (open) => {
        setSidebarStatus(open);
    };

    return (

        {sidebarStatus && (
          <Sidebar showSideBar={sidebarStatus} onClick={toggleSidebar} />
        )}

    )
}

New Navbar.js

const Navbar = (props) => {

return (
        <button
          id="toggle"
          className="menu-icon-btn py-2"
          data-menu-icon-btn
          onClick={() => props.onClick(!props.showSideBar)}
        > Toggle Sidebar
        </button>
)
}

Body:
Your code is broken.. i made a little change to your code:

import React, { useEffect, useRef, useState } from "react";
import "./Dashboard.css";
import Navbar from "./Navbar";
import Sidebar from "./Sidebar";

const Dashboard = () => {
  // i don't know what is using for..
  const sidebarRef = useRef(null); // used to get sidebar width
  const [isMobile, setMobile] = useState(document.body.clientWidth <= 498);
  // use 'init' | 'open' | 'close', that you don't need remember if suer clicked
  const [sidebarStatus, setSidebarStatus] = useState("init");

  useEffect(() => {
    // add listener only once, or many listeners would be created every render
    const mq = window.matchMedia("(max-width: 498px)");
    mq.addListener((res) => {
      setMobile(res.matches);
    });
    return () => mq.removeListener(toggleSidebar);
  }, []);

  // react use status change fire effects, fire function manually is tired
  // here calculate should show sidebar
  const showSidebar =
    sidebarStatus === "open" || (!isMobile && sidebarStatus === "init");

  const toggleSidebar = (open) => {
    setSidebarStatus(open ? "open" : "close");
  };

  return (
    <>
      <span ref={sidebarRef}>
        {showSidebar && <Sidebar onClick={toggleSidebar} />}
      </span>
      <div className="flex-fill content-wrapper">
        <Navbar showSideBar={showSidebar} onClick={toggleSidebar} />
      </div>
    </>
  );
};

export default Dashboard;

attention that toggleSidebar param from navbar and sidebar are const true and false. Do not use status in different file


问:
Better way to empty all the values of an object by setState in react
I am using React. This is my state

```<code>state = {
customerData: {
      id: '',
      name: '',
      type: '',
      place: '',
      country: '',
      timezone: 'GMT+5:30',
      status: false
    }
}
</code>```

There is an edit functionality where the customerData object gets populated on click of edit button. I am showing this data in a modal.

Now in the modal, when I click the submit button, the modal should hide and the data populated in the customerData object should be empty. I can do it like this:

```<code>this.setState({
customerData: {
      ...this.state.customerData
      id: '',
      name: '',
      type: '',
      place: '',
      country: '',
      timezone: '',
      status: false
    }
}
})
</code>```

I am wondering is there any one line way in ES6 to make the customerData Object empty. Because, if there are too many fields, it will be difficult.

答:
Just facing your problem today and i solved it with this code</p>
```<code>const handleResetState = () => {
    const {customerData} = this.state
    let emptyState = {};
    for (const key in customerData){
        emptyState = {...emptyState, [key] : ""}
    }
    //i think you will more need the second option, so dont use first option
    //normal change (first option)
    this.setState({customerData: emptyState});
    //in case if your key need to have special initial value that are not empty string (second option)
    this.setState({customerData: {...emptyState, status: false} })
}
</code>```

Body:
I am using React. This is my state

state = {
customerData: {
      id: '',
      name: '',
      type: '',
      place: '',
      country: '',
      timezone: 'GMT+5:30',
      status: false
    }
}

There is an edit functionality where the customerData object gets populated on click of edit button. I am showing this data in a modal.

Now in the modal, when I click the submit button, the modal should hide and the data populated in the customerData object should be empty. I can do it like this:

this.setState({
customerData: {
      ...this.state.customerData
      id: '',
      name: '',
      type: '',
      place: '',
      country: '',
      timezone: '',
      status: false
    }
}
})

I am wondering is there any one line way in ES6 to make the customerData Object empty. Because, if there are too many fields, it will be difficult.

Body:
Just facing your problem today and i solved it with this code

const handleResetState = () => {
    const {customerData} = this.state
    let emptyState = {};
    for (const key in customerData){
        emptyState = {...emptyState, [key] : ""}
    }
    //i think you will more need the second option, so dont use first option
    //normal change (first option)
    this.setState({customerData: emptyState});
    //in case if your key need to have special initial value that are not empty string (second option)
    this.setState({customerData: {...emptyState, status: false} })
}


问:
XML not found in android module
I am configuring my android application for on demand delivery.
The app uses Device Administrator API which I am trying to break down in separate module. Now the application have app module and admin module

Device Administrator requires a xml file which list the admin polices that app would like to use. When this xml file is moved to admin module (admin/res/xml/device_admin_policies.xml) android studio generates following android resource linking error

ERROR:...\app\build\intermediates\packaged_manifests\debug\AndroidManifest.xml:376: AAPT: error: resource xml/device_admin_policies (aka com.app.package:xml/device_admin_policies) not found.

Do note that the error is coming in merged manifest generate at compile time. If I move back this file to app module it works.

I am experimenting something with Device Admin API and for that I need this xml file to be in admin module. I am not sure if its possible to point it somehow to get the file from admin module.

Admin Module Manifest

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:dist="http://schemas.android.com/apk/distribution"
    package="com.app.package.ad">

    <dist:module
        dist:instant="false"
        dist:title="@string/title_lock">
        <dist:delivery>
            <dist:install-time />
        </dist:delivery>

        <dist:fusing dist:include="false" />
    </dist:module>

    <application android:hasCode="true">
        <activity
            android:name=".MainActivity"
            android:exported="false" />

        <activity android:name=".AdminPermissionActivity" />

        <receiver
            android:name=".admin.DeviceAdministrator"
            android:permission="android.permission.BIND_DEVICE_ADMIN"
            android:exported="false">
            <meta-data
                android:name="android.app.device_admin"
                android:resource="@xml/device_admin_policies" />

            <intent-filter>
                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
                <action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
                <action android:name="android.app.action.ACTION_PASSWORD_FAILED" />
                <action android:name="android.app.action.ACTION_PASSWORD_SUCCEED" />
                <action android:name="android.intent.action.USER_PRESENT" />
            </intent-filter>
        </receiver>
    </application>

</manifest>
</code>```

xml file (device_admin_policies.xml)

```<code><device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <force-lock />
        <disable-keyguard-features />
        <watch-login />
    </uses-policies>
</device-admin>
</code>```

答:
Eliminating View Lookups

The most basic thing we get with data binding is the elimination of findViewById. To enable this to work for a layout file, first we need to change the layout file by making the outer tag  instead of whatever ViewGroup you use (note that the XML namespaces should also be moved):

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context=".MainActivity">

    <TextView
            android:id="@+id/tvLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

</RelativeLayout>
</code>```

Title: XML not found in android module

Body:
I am configuring my android application for on demand delivery.
The app uses Device Administrator API which I am trying to break down in separate module. Now the application have app module and admin module

Device Administrator requires a xml file which list the admin polices that app would like to use. When this xml file is moved to admin module (admin/res/xml/device_admin_policies.xml) android studio generates following android resource linking error

ERROR:...\app\build\intermediates\packaged_manifests\debug\AndroidManifest.xml:376: AAPT: error: resource xml/device_admin_policies (aka com.app.package:xml/device_admin_policies) not found.

Do note that the error is coming in merged manifest generate at compile time. If I move back this file to app module it works.

I am experimenting something with Device Admin API and for that I need this xml file to be in admin module. I am not sure if its possible to point it somehow to get the file from admin module.

Admin Module Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:dist="http://schemas.android.com/apk/distribution"
    package="com.app.package.ad">

    <dist:module
        dist:instant="false"
        dist:title="@string/title_lock">
        <dist:delivery>
            <dist:install-time />
        </dist:delivery>

        <dist:fusing dist:include="false" />
    </dist:module>

    <application android:hasCode="true">
        <activity
            android:name=".MainActivity"
            android:exported="false" />

        <activity android:name=".AdminPermissionActivity" />

        <receiver
            android:name=".admin.DeviceAdministrator"
            android:permission="android.permission.BIND_DEVICE_ADMIN"
            android:exported="false">
            <meta-data
                android:name="android.app.device_admin"
                android:resource="@xml/device_admin_policies" />

            <intent-filter>
                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
                <action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
                <action android:name="android.app.action.ACTION_PASSWORD_FAILED" />
                <action android:name="android.app.action.ACTION_PASSWORD_SUCCEED" />
                <action android:name="android.intent.action.USER_PRESENT" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

xml file (device_admin_policies.xml)

<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <force-lock />
        <disable-keyguard-features />
        <watch-login />
    </uses-policies>
</device-admin>

Body:
Eliminating View Lookups

The most basic thing we get with data binding is the elimination of findViewById. To enable this to work for a layout file, first we need to change the layout file by making the outer tag  instead of whatever ViewGroup you use (note that the XML namespaces should also be moved):

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context=".MainActivity">

    <TextView
            android:id="@+id/tvLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

</RelativeLayout>


问:
How to make a circular image covered with different color
I have an circular image.It is displaying in list view.In every item of list view there is one text and this image.This circular image has one color.How can i make some portion of this image covered with any other color.Any help will be appreciated.</p>

答:
Make sure the image you have is on a transparent background. Then, cutout a portion of the image which you wish to change colour. Then, in your program call setBackgroundColor(int myColor) and the colour you set will show through.

Edit: Using Photoshop, or your favourite image editing program, prepare your image by ensuring it is on a transparent background. Then cutout the part which you want to change colour. Save the image in your drawable-hdpi folder in your Android project. Then, set the background colour to the colour you want and it will show through the cutout e.g.

```<code>ImageView icon = new ImageView(context);
icon.setId(1);
icon.setImageResource(R.drawable.paint_splat);
icon.setBackgroundColor(pickedColour);
</code>```

In the example above, my paint_splat image shown below:

the white areas are not white - they are translucent. If you don't know how to do this, you need to read up on image editing in whatever image editing program you will use.
Then the last call :

```<code>icon.setBackgroundColor(pickedColour);
</code>```

Sets the background colour but this can only be seen through the translucent part of the image and so it changes the colour, in my case, of the paint splats.

Also, if the colour you use for the foregound matches the main screen colour of your application, in my case the splat image has a black colour foreground and my Android app has a black screen, then ONLY the coloured paint splat is visible so it looks like the whole image is changing colour.

Body:
Make sure the image you have is on a transparent background. Then, cutout a portion of the image which you wish to change colour. Then, in your program call setBackgroundColor(int myColor) and the colour you set will show through.

Edit: Using Photoshop, or your favourite image editing program, prepare your image by ensuring it is on a transparent background. Then cutout the part which you want to change colour. Save the image in your drawable-hdpi folder in your Android project. Then, set the background colour to the colour you want and it will show through the cutout e.g.

ImageView icon = new ImageView(context);
icon.setId(1);
icon.setImageResource(R.drawable.paint_splat);
icon.setBackgroundColor(pickedColour);

In the example above, my paint_splat image shown below:

the white areas are not white - they are translucent. If you don't know how to do this, you need to read up on image editing in whatever image editing program you will use.
Then the last call :

icon.setBackgroundColor(pickedColour);

Sets the background colour but this can only be seen through the translucent part of the image and so it changes the colour, in my case, of the paint splats.

Also, if the colour you use for the foregound matches the main screen colour of your application, in my case the splat image has a black colour foreground and my Android app has a black screen, then ONLY the coloured paint splat is visible so it looks like the whole image is changing colour.


问:
getResourceAsStream returns null
I'm loading a text file from within a package in a compiled JAR of my Java project. The relevant directory structure is as follows:

```<code>/src/initialization/Lifepaths.txt
</code>```

My code loads a file by calling Class::getResourceAsStream to return a InputStream.

```<code>public class Lifepaths {
    public static void execute() {
        System.out.println(Lifepaths.class.getClass().
            getResourceAsStream("/initialization/Lifepaths.txt"));
    }

    private Lifepaths() {}

    //This is temporary; will eventually be called from outside
    public static void main(String[] args) {execute();}
}
</code>```

The print out will always print null, no matter what I use. I'm not sure why the above wouldn't work, so I've also tried:

"/src/initialization/Lifepaths.txt"

"initialization/Lifepaths.txt"

"Lifepaths.txt"

Neither of these work. I've read numerous questions so far on the topic, but none of them have been helpful - usually, they just say to load files using the root path, which I'm already doing. That, or just load the file from the current directory (just load filename), which I've also tried. The file is being compiled into the JAR in the appropriate location with the appropriate name.

How do I solve this?

答:
If you are using IDEA, make sure to mark your resources folder as 'Resources' so that the path can be recognized by IDE correctly.

Let's say you have a file named 'book.json' in 'resources/', then to use the resources in it, you can do it like this

```<code>InputStream input = Main.class.getResourceAsStream("/book.json");
</code>```

Title: getResourceAsStream returns null

Body:
I'm loading a text file from within a package in a compiled JAR of my Java project. The relevant directory structure is as follows:

/src/initialization/Lifepaths.txt

My code loads a file by calling Class::getResourceAsStream to return a InputStream.

public class Lifepaths {
    public static void execute() {
        System.out.println(Lifepaths.class.getClass().
            getResourceAsStream("/initialization/Lifepaths.txt"));
    }

    private Lifepaths() {}

    //This is temporary; will eventually be called from outside
    public static void main(String[] args) {execute();}
}

The print out will always print null, no matter what I use. I'm not sure why the above wouldn't work, so I've also tried:

"/src/initialization/Lifepaths.txt"

"initialization/Lifepaths.txt"

"Lifepaths.txt"

Neither of these work. I've read numerous questions so far on the topic, but none of them have been helpful - usually, they just say to load files using the root path, which I'm already doing. That, or just load the file from the current directory (just load filename), which I've also tried. The file is being compiled into the JAR in the appropriate location with the appropriate name.

How do I solve this?

Body:
If you are using IDEA, make sure to mark your resources folder as 'Resources' so that the path can be recognized by IDE correctly.

Let's say you have a file named 'book.json' in 'resources/', then to use the resources in it, you can do it like this

InputStream input = Main.class.getResourceAsStream("/book.json");


问:
Multiple loop in list comprehension
I have a problem set in hand, the description is something like:

We have 2 lists ie "nums1" and "nums2" and 2 integers m and n

```<code>nums1 = [1, 2, 3, 7, 8, 9]
m = 3
nums2 = [2, 5, 6]
n = 2
</code>```

Here "m" denotes number of elements to be picked from "nums1" and "n" denotes the number of elements to be picked from "nums2".
There are other ways ofcourse, but I want to create a list with only "list comprehension" on the above conditions.

With a simple for loop I can achieve that with:

```<code>li = []
for i in range(m):
  li.append(nums1[i])
for j in range(n):
  li.append(nums2[j])
print(li)
</code>```

I tried the following but the outcome result is not as expected:

```<code>[a for a in nums1 for b in nums2]
</code>```

Expected output:
[1, 2, 2, 3, 5]

Also, does list comprehension supports multiple loop?

答:
Given the following:

```<code>nums1 = [1, 2, 3, 7, 8, 9]
m = 3
nums2 = [2, 5, 6]
n = 2
</code>```

Using strictly list comprehension, the following does what you asked for:

```<code>sorted([nums1[a] for a in range(m)] + [nums2[b] for b in range(n)])
</code>```

Returns:

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

as per the conditions with "List comprehension" to be specific.

Although as others have said in the comment, a slice would have been more pythonic and easier to reason about. But since you asked for a list comprehension implementation, then this is as close to an answer as you'll get.

Title: Multiple loop in list comprehension

Body:
I have a problem set in hand, the description is something like:

We have 2 lists ie "nums1" and "nums2" and 2 integers m and n

nums1 = [1, 2, 3, 7, 8, 9]
m = 3
nums2 = [2, 5, 6]
n = 2

Here "m" denotes number of elements to be picked from "nums1" and "n" denotes the number of elements to be picked from "nums2".
There are other ways ofcourse, but I want to create a list with only "list comprehension" on the above conditions.

With a simple for loop I can achieve that with:

li = []
for i in range(m):
  li.append(nums1[i])
for j in range(n):
  li.append(nums2[j])
print(li)

I tried the following but the outcome result is not as expected:

[a for a in nums1 for b in nums2]

Expected output:
[1, 2, 2, 3, 5]

Also, does list comprehension supports multiple loop?

Body:
Given the following:

nums1 = [1, 2, 3, 7, 8, 9]
m = 3
nums2 = [2, 5, 6]
n = 2

Using strictly list comprehension, the following does what you asked for:

sorted([nums1[a] for a in range(m)] + [nums2[b] for b in range(n)])

Returns:

[1, 2, 2, 3, 5]

as per the conditions with "List comprehension" to be specific.

Although as others have said in the comment, a slice would have been more pythonic and easier to reason about. But since you asked for a list comprehension implementation, then this is as close to an answer as you'll get.


问:
how to hide onStepContinue button for the last step and onStepCancel for the first step on flutter?
This is my first time on flutter framework and Dart programming I have so manny miss of understanding Dart language.

I want to hide onStepContinue button for the last step and onStepCancel for the first step on flutter? this is my code I'm newbe in flutter any help?

```<code>class _MyHomePageState extends State<MyHomePage> {
  int _currentStep = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Stepper(
          controlsBuilder: (BuildContext context, ControlsDetails details) {
            return Row(
              children: <Widget>[
              TextButton(
                onPressed: details.onStepContinue,
                child: const Text('NEXT'),
              ),
              TextButton(
                onPressed: details.onStepCancel,
                child: const Text('BACK'),
              ),
            ],
            );
          },
          steps: const [
            Step(
              title: Text("Step 1"),
              content: Text("Information for step 1"),
            ),
            Step(
              title: Text("Step 2"),
              content: Text("Information for step 2"),
            ),
            Step(
              title: Text("Step 3"),
              content: Text("Information for step 3"),
            ),
          ],
          onStepTapped: (int newIndex){
            setState(() {
              _currentStep = newIndex;
            });
          },
          currentStep: _currentStep,
          onStepContinue: () {
            if (_currentStep != 2) {
              setState(() {
                _currentStep += 1;
              });
            }
          },
          onStepCancel: () {
            if (_currentStep != 0) {
              setState(() {
                _currentStep -= 1;
              });
            }
          },
        ),
      ),
    );
  }
}
</code>```

答:
To Enable/Disable Button you can use this

```<code> class MyHomePage extends StatefulWidget {
      @override
      _MyHomePageState createState() => new _MyHomePageState();
    }

    class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
      bool _isButtonDisabled;

      @override
      void initState() {
        _isButtonDisabled = false;
      }

      void _incrementCounter() {
        setState(() {
          _isButtonDisabled = true;
          _counter++;
        });
      }

      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text("The App"),
          ),
          body: new Center(
            child: new Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Text(
                  'You have pushed the button this many times:',
                ),
                new Text(
                  '$_counter',
                  style: Theme.of(context).textTheme.display1,
                ),
                _buildCounterButton(),
              ],
            ),
          ),
        );
      }

      Widget _buildCounterButton() {
        return new RaisedButton(
          child: new Text(
            _isButtonDisabled ? "Hold on..." : "Increment"
          ),
          onPressed: _isButtonDisabled ? null : _incrementCounter,
        );
      }
    }
</code>```

Body:
This is my first time on flutter framework and Dart programming I have so manny miss of understanding Dart language.

I want to hide onStepContinue button for the last step and onStepCancel for the first step on flutter? this is my code I'm newbe in flutter any help?

class _MyHomePageState extends State<MyHomePage> {
  int _currentStep = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Stepper(
          controlsBuilder: (BuildContext context, ControlsDetails details) {
            return Row(
              children: <Widget>[
              TextButton(
                onPressed: details.onStepContinue,
                child: const Text('NEXT'),
              ),
              TextButton(
                onPressed: details.onStepCancel,
                child: const Text('BACK'),
              ),
            ],
            );
          },
          steps: const [
            Step(
              title: Text("Step 1"),
              content: Text("Information for step 1"),
            ),
            Step(
              title: Text("Step 2"),
              content: Text("Information for step 2"),
            ),
            Step(
              title: Text("Step 3"),
              content: Text("Information for step 3"),
            ),
          ],
          onStepTapped: (int newIndex){
            setState(() {
              _currentStep = newIndex;
            });
          },
          currentStep: _currentStep,
          onStepContinue: () {
            if (_currentStep != 2) {
              setState(() {
                _currentStep += 1;
              });
            }
          },
          onStepCancel: () {
            if (_currentStep != 0) {
              setState(() {
                _currentStep -= 1;
              });
            }
          },
        ),
      ),
    );
  }
}

Body:
To Enable/Disable Button you can use this

 class MyHomePage extends StatefulWidget {
      @override
      _MyHomePageState createState() => new _MyHomePageState();
    }

    class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
      bool _isButtonDisabled;

      @override
      void initState() {
        _isButtonDisabled = false;
      }

      void _incrementCounter() {
        setState(() {
          _isButtonDisabled = true;
          _counter++;
        });
      }

      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text("The App"),
          ),
          body: new Center(
            child: new Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Text(
                  'You have pushed the button this many times:',
                ),
                new Text(
                  '$_counter',
                  style: Theme.of(context).textTheme.display1,
                ),
                _buildCounterButton(),
              ],
            ),
          ),
        );
      }

      Widget _buildCounterButton() {
        return new RaisedButton(
          child: new Text(
            _isButtonDisabled ? "Hold on..." : "Increment"
          ),
          onPressed: _isButtonDisabled ? null : _incrementCounter,
        );
      }
    }


问:
Error while trying to send logs with rsyslog without local storage
I'm trying to send logs into datadog using rsyslog. Ideally, I'm trying to do this without having the logs stored on the server hosting rsyslog. I've run into an error in my config that I haven't been able to find out much about. The error occurs on startup of rsyslog.

omfwd: could not get addrinfo for hostname '(null)':'(null)': Name or service not known [v8.2001.0 try https://www.rsyslog.com/e/2007 ]

Here's the portion I've added into the default rsyslog.config

```<code>module(load="imudp")
input(type="imudp" port="514" ruleset="datadog")

ruleset(name="datadog"){
    action(
        type="omfwd"
        action.resumeRetryCount="-1"
        queue.type="linkedList"
        queue.saveOnShutdown="on"
        queue.maxDiskSpace="1g"
        queue.fileName="fwdRule1"
)

$template DatadogFormat,"00000000000000000 <%pri%>%protocol-version% %timestamp:::date-rfc3339% %HOSTNAME% %app-name% - - - %msg%\n "

$DefaultNetstreamDriverCAFile /etc/ssl/certs/ca-certificates.crt
$ActionSendStreamDriver gtls
$ActionSendStreamDriverMode 1
$ActionSendStreamDriverAuthMode x509/name

$ActionSendStreamDriverPermittedPeer *.logs.datadoghq.com
    *.* @@intake.logs.datadoghq.com:10516;DatadogFormat
}
</code>```

答:
First things first.

The module imudp enables log reception over udp.

The module omfwd enables log forwarding over (tcp, udp, ...)

So most probably - or atleast as far as i can tell - with rsyslog you just want to log messages locally and then send them to datadog.

I don't know anything about the $ActionSendStreamDriver tags, so I can't help you there. But what is jumping out is, that in your action you haven't defined where the logs should be sent to.

```<code>ruleset(name="datadog"){
    action(
        type="omfwd"
        target="10.100.1.1"
        port="514"
        protocol="udp"
        ...
    )
    ...
}
</code>```

Body:
I'm trying to send logs into datadog using rsyslog. Ideally, I'm trying to do this without having the logs stored on the server hosting rsyslog. I've run into an error in my config that I haven't been able to find out much about. The error occurs on startup of rsyslog.

omfwd: could not get addrinfo for hostname '(null)':'(null)': Name or service not known [v8.2001.0 try https://www.rsyslog.com/e/2007 ]

Here's the portion I've added into the default rsyslog.config

module(load="imudp")
input(type="imudp" port="514" ruleset="datadog")

ruleset(name="datadog"){
    action(
        type="omfwd"
        action.resumeRetryCount="-1"
        queue.type="linkedList"
        queue.saveOnShutdown="on"
        queue.maxDiskSpace="1g"
        queue.fileName="fwdRule1"
)

$template DatadogFormat,"00000000000000000 <%pri%>%protocol-version% %timestamp:::date-rfc3339% %HOSTNAME% %app-name% - - - %msg%\n "

$DefaultNetstreamDriverCAFile /etc/ssl/certs/ca-certificates.crt
$ActionSendStreamDriver gtls
$ActionSendStreamDriverMode 1
$ActionSendStreamDriverAuthMode x509/name

$ActionSendStreamDriverPermittedPeer *.logs.datadoghq.com
    *.* @@intake.logs.datadoghq.com:10516;DatadogFormat
}

Body:
First things first.

The module imudp enables log reception over udp.

The module omfwd enables log forwarding over (tcp, udp, ...)

So most probably - or atleast as far as i can tell - with rsyslog you just want to log messages locally and then send them to datadog.

I don't know anything about the $ActionSendStreamDriver tags, so I can't help you there. But what is jumping out is, that in your action you haven't defined where the logs should be sent to.

ruleset(name="datadog"){
    action(
        type="omfwd"
        target="10.100.1.1"
        port="514"
        protocol="udp"
        ...
    )
    ...
}


问:
Play audio data from java ByteArray
I have a 16-bit PCM audio data from an android app and I want to stream and play it on a webpage from the format as seen on this screenshot.

Is there a way to directly play audio buffers on webpage without having a server to serve an audio file? I'm open to suggestions.

答:
You can try using a Data Uri to map the data to a file on-the-fly and input that into something that can play an auio file from a uri (such as the HTML audio component).
You could also just save this buffer to a file and play that.</p>

Title: Play audio data from java ByteArray


问:
Scope is not being added to Access Token returned from Azure Ad
Overview

We have an Azure AD secured API living in Azure as a web app. We need to be able to:

Trigger this API via user interaction from a client application (this part works).

Trigger this API programmatically from a scheduled job that will simply get a token & hit this API (this part does not work due to authentication issues).

Problem

The issue is that when we request a token from Azure AD, scope is not being set in our token claims resulting in the API rejecting the token.

This is the request we are making:

This request returns an access token with the following claims:

```<code>{
  "aud": "<our api client id>",
  "iss": "https://login.microsoftonline.com/<tenantId>/v2.0",
  "iat": 1644421512,
  "nbf": 1644421512,
  "exp": 1644425412,
  "aio": "<value>",
  "azp": "<scheduled job client id>",
  "azpacr": "1",
  "oid": "<guid>",
  "rh": "<value>",
  "sub": "<guid>",
  "tid": "<guid>",
  "uti": "<value>",
  "ver": "2.0"
}
</code>```

As you can see scp (scope) is not included in the token claims even though we include it in the request.

If we use this token to make a request to our API we get the following error:

```<code>System.UnauthorizedAccessException: IDW10201: Neither scope or roles claim was found in the bearer token.
</code>```

Any help on how we can get an access token from Azure AD with the proper scope/permissions to call our API, would be greatly appreciated.

Note

The Azure AD App Registration for our scheduled job that will request a token and then hit our API, does have the Delegated API Permission access_as_user which you can see I am including in the token request's scope.

答:
The above is expected as using client credentials you can't get the delegated permissions i.e. the access_as_user permission and also the scope in client credentials should be used as api://<APP_ID>/.default . So , If you want delegated permissions then you will have to use implicit grant flow instead of client credentials.

For testing , I created two app registrations , One on which API is exposed (Postman) and other which is to be used for authentication (Powershelltest) and then , I have tested the same in 2 different scenarios like one for client credentials and another for implicit grant :

Main APP whose API has been exposed :

App used for authentication:

Scenario 1 Using Client Credential flow :

Scenario 2 using Implicit Grant flow :

Body:
Overview

We have an Azure AD secured API living in Azure as a web app. We need to be able to:

Trigger this API via user interaction from a client application (this part works).

Trigger this API programmatically from a scheduled job that will simply get a token & hit this API (this part does not work due to authentication issues).

Problem

The issue is that when we request a token from Azure AD, scope is not being set in our token claims resulting in the API rejecting the token.

This is the request we are making:

This request returns an access token with the following claims:

{
  "aud": "<our api client id>",
  "iss": "https://login.microsoftonline.com/<tenantId>/v2.0",
  "iat": 1644421512,
  "nbf": 1644421512,
  "exp": 1644425412,
  "aio": "<value>",
  "azp": "<scheduled job client id>",
  "azpacr": "1",
  "oid": "<guid>",
  "rh": "<value>",
  "sub": "<guid>",
  "tid": "<guid>",
  "uti": "<value>",
  "ver": "2.0"
}

As you can see scp (scope) is not included in the token claims even though we include it in the request.

If we use this token to make a request to our API we get the following error:

System.UnauthorizedAccessException: IDW10201: Neither scope or roles claim was found in the bearer token.

Any help on how we can get an access token from Azure AD with the proper scope/permissions to call our API, would be greatly appreciated.

Note

The Azure AD App Registration for our scheduled job that will request a token and then hit our API, does have the Delegated API Permission access_as_user which you can see I am including in the token request's scope.


问:
span background-color & padding problems
I have a design I want to implement that involves title text appearing with its own background color, padded by 10px, over an image, par example:

http://i.stack.imgur.com/E7EpS.png

The first example in this picture works well, and is simple:

```<code>.greenbox {width:520px; height:261px; position:relative;}
.greenbox span { padding:0 10px; background:#000; position:absolute; left:0; bottom:40px; }
</code>```

Trouble arises when the text overflows onto another line, then the span elements padding does not effect the text on the line breaks, it renders like so:

http://i.stack.imgur.com/pY18f.png

Anyone know of an alternative, or how they would set this design out so that the background color & padding was consistent?

Thanks in advance

Edit: I had simplified the code to make it concise, but had missed a vital part. Actually it's like this:

```<code>.greenbox {width:520px; height:261px; position:relative;}
.greenbox a {position:absolute; left:0; bottom:40px; }
.greenbox span { padding:0 10px; background:#000; }
</code>```

With the html as:

```<code><div class="greenbox">

    <a href="link"><span>The Title Goes Here</span></a>

</div>
</code>```

Thus the span remains inline, wrapped in a absolute position anchor.

答:
I've tackled something similar before: Add padding at the beginning and end of each line of text

I've robbed that solution from myself, and fit it to your case.

Note that the line-height and padding adjustments can be very tricky to get right.

See: http://jsbin.com/ahoyug

HTML:

        The Title Goes Here, with overflow

```

<p><strong>CSS:</strong></p>

```.greenbox {width:500px; height:200px; position:relative; background:green}

.greenbox > a {
    font: 50px sans-serif;
    line-height: 1.14;
    padding: 0;
    border-left: 20px solid #000;
    position: absolute;
    left: 0;
    bottom: 60px;
    text-decoration: none;
    color: #fff
}
.greenbox > a > span {
    background: #000
}
.greenbox > a > span > span {
    position: relative;
    left: -10px
}
```

Body:
I have a design I want to implement that involves title text appearing with its own background color, padded by 10px, over an image, par example:

http://i.stack.imgur.com/E7EpS.png

The first example in this picture works well, and is simple:

.greenbox {width:520px; height:261px; position:relative;}
.greenbox span { padding:0 10px; background:#000; position:absolute; left:0; bottom:40px; }

Trouble arises when the text overflows onto another line, then the span elements padding does not effect the text on the line breaks, it renders like so:

http://i.stack.imgur.com/pY18f.png

Anyone know of an alternative, or how they would set this design out so that the background color & padding was consistent?

Thanks in advance

Edit: I had simplified the code to make it concise, but had missed a vital part. Actually it's like this:

.greenbox {width:520px; height:261px; position:relative;}
.greenbox a {position:absolute; left:0; bottom:40px; }
.greenbox span { padding:0 10px; background:#000; }

With the html as:

    The Title Goes Here

Thus the span remains inline, wrapped in a absolute position anchor.

Body:
I've tackled something similar before: Add padding at the beginning and end of each line of text

I've robbed that solution from myself, and fit it to your case.

Note that the line-height and padding adjustments can be very tricky to get right.

See: http://jsbin.com/ahoyug

HTML:

<div class="greenbox">
    <a href="#"><span><span>
        The Title Goes Here, with overflow
    </span></span></a>
</div>

CSS:

.greenbox {width:500px; height:200px; position:relative; background:green}

.greenbox > a {
    font: 50px sans-serif;
    line-height: 1.14;
    padding: 0;
    border-left: 20px solid #000;
    position: absolute;
    left: 0;
    bottom: 60px;
    text-decoration: none;
    color: #fff
}
.greenbox > a > span {
    background: #000
}
.greenbox > a > span > span {
    position: relative;
    left: -10px
}


问:
Unable to copy a file from obj\Debug to bin\Debug
I have a project in C# and I get this error every time I try to compile the project:

(Unable to copy file "obj\Debug\Project1.exe" to "bin\Debug\Project1.exe". The process cannot access the file 'bin\Debug\Project1.exe' because it is being used by another process.)

So I have to close the process from the task manager. My project is only one form and there is no multi-threading.

What is the solution (without restarting VS or killing the process)?

答:
I am having this problem on VS2019 running on Win 7. This felt very similar to a problem I have commonly on Win 7. Specifically, I am occasionally unable to move/delete a file proviosly used by another program, even though I've closed that program. I believe that Windows has lost track of this file for purposes of managing file sharing. I've read many places this can be fixed by modifying the file's security/ownership settings, but this hasn't worked for me. But rebooting my PC (restarting Windows) does fix the problem. Same here - I was able to get past this VS2019 copy problem by rebooting my PC.

It's also worth noting that I was able to figure out what caused this bug - cleaning projects. It doesn't happen all the time, it actually seems quite rare. But when it happens, it seems my only solution is rebooting my PC.


问:
Expo Error getaddrinfo ENOTFOUND assets expo
my app is ejected from expo so i have to do expo publish every time i do release build
the method was working perfectly for more than 50 times but suddenly after doing the expo publish when i try to do archive in xcode or generate the release build in android iam getting the following error

In Xcode :

```<code>Showing All Messages
https://assets/3c851d60ad5ef3f2fe43ebd263490d78
https://assets/1a0e3525dd5df87e77057204129a5e6e
https://assets/2379ae894c2c9f63b852a9f3676c2763
https://assets/5cdf883b18a5651a29a4d1ef276d2457
https://assets/74d124a3caeac2bea111f3ca2f2dd34a
[20:37:23] Error: getaddrinfo ENOTFOUND assets

[20:37:23] Before making a release build, make sure you have run 'expo publish' at least once. Learn more. (https://expo.fyi/release-builds-with-expo-updates)
</code>```

In Android :

```<code>> Task :app:bundleReleaseExpoUpdatesAssets
https://assets/3c851d60ad5ef3f2fe43ebd263490d78
https://assets/1a0e3525dd5df87e77057204129a5e6e
https://assets/2379ae894c2c9f63b852a9f3676c2763
https://assets/5cdf883b18a5651a29a4d1ef276d2457
https://assets/74d124a3caeac2bea111f3ca2f2dd34a
[21:22:20] Error: getaddrinfo ENOTFOUND assets
[21:22:20] Before making a release build, make sure you have run 'expo publish' at least once. Learn more.
</code>```

Even though my expo publish is done and if i try to build archive or apk iam getting the error

I tried clear watchman,
remove node modules,reinstall pod,clear cache.etc
Nothing helps

答:
Did try this solution using the instructions from the pdf but didn't work for me. Spent days looking for solutions but nothing worked for me so I dug into the issue.

My project is using Expo SDK36.

What worked for me is the following solution.

Requirements

Install expo-cli: npm install expo-cli --save-dev.

Whenever we make a build using Xcode Archive or Android Gradle assembleRelease command, these executes the expo bundle-assets command. We are going to replace expo and use the local expo-cli in the following steps.

iOS Specific solution

After installing expo-cli in our project, we need to replace build commands.

Go to Xcode > Project Name > Targets > Select you project > Build Phases

Under Build Phases > Go to Expo Bundle Assets or something similar

Replace: expo bundle-assets --platform ios --dest "$dest" with npx expo-cli bundle-assets --platform ios --dest "$dest"

Run npx expo-cli publish --clear

Clean the project and start archiving/building!

Android specific solution (for MacOS/Linux)

On your project root folder, create a file named run-exp.sh.

Add these lines inside of run-exp.sh:

```<code>#!/usr/bin/env bash

value=$(cat ~/.expo/PATH)
PATH="$PATH:$value" npx expo-cli "$@"
</code>```

Under Project Root Folder, go to android/app/expo.gradle

Replace this line:

```<code>commandLine("./node_modules/expokit/detach-scripts/run-exp.sh", "bundle-assets", expoRoot, "--platform", "android", "--dest", assetsDir)
</code>```

with

```<code>commandLine("./run-exp.sh", "bundle-assets", expoRoot, "--platform", "android", "--dest", assetsDir)
</code>```

Run npx expo-cli publish --clear

On Android studio, clean the project and build the app

Android specific solution (for Windows)

On your project root folder, create a file named run-exp.bat.

Add these lines inside of run-exp.bat:

```<code>SET /P STOREDPATH=<"%USERPROFILE%\.expo\PATH"
SET PATH="\"%PATH%;%STOREDPATH%\""
npx expo-cli %*
</code>```

Under Project Root Folder, go to android/app/expo.gradle

Replace this line:

```<code>commandLine("cmd", "/c", ".\\node_modules\\expokit\\detach-scripts\\run-exp.bat", "bundle-assets", expoRoot, "--platform", "android", "--dest", assetsDir)
</code>```

with

```<code>commandLine("cmd", "/c", ".\\run-exp.bat", "bundle-assets", expoRoot, "--platform", "android", "--dest", assetsDir)
</code>```

Run npx expo-cli publish --clear

On Android studio, clean the project and build the app

Body:
my app is ejected from expo so i have to do expo publish every time i do release build
the method was working perfectly for more than 50 times but suddenly after doing the expo publish when i try to do archive in xcode or generate the release build in android iam getting the following error

In Xcode :

Showing All Messages
https://assets/3c851d60ad5ef3f2fe43ebd263490d78
https://assets/1a0e3525dd5df87e77057204129a5e6e
https://assets/2379ae894c2c9f63b852a9f3676c2763
https://assets/5cdf883b18a5651a29a4d1ef276d2457
https://assets/74d124a3caeac2bea111f3ca2f2dd34a
[20:37:23] Error: getaddrinfo ENOTFOUND assets

[20:37:23] Before making a release build, make sure you have run 'expo publish' at least once. Learn more. (https://expo.fyi/release-builds-with-expo-updates)

In Android :

> Task :app:bundleReleaseExpoUpdatesAssets
https://assets/3c851d60ad5ef3f2fe43ebd263490d78
https://assets/1a0e3525dd5df87e77057204129a5e6e
https://assets/2379ae894c2c9f63b852a9f3676c2763
https://assets/5cdf883b18a5651a29a4d1ef276d2457
https://assets/74d124a3caeac2bea111f3ca2f2dd34a
[21:22:20] Error: getaddrinfo ENOTFOUND assets
[21:22:20] Before making a release build, make sure you have run 'expo publish' at least once. Learn more.

Even though my expo publish is done and if i try to build archive or apk iam getting the error

I tried clear watchman,
remove node modules,reinstall pod,clear cache.etc
Nothing helps

Body:
Did try this solution using the instructions from the pdf but didn't work for me. Spent days looking for solutions but nothing worked for me so I dug into the issue.

My project is using Expo SDK36.

What worked for me is the following solution.

Requirements

Install expo-cli: npm install expo-cli --save-dev.

Whenever we make a build using Xcode Archive or Android Gradle assembleRelease command, these executes the expo bundle-assets command. We are going to replace expo and use the local expo-cli in the following steps.

iOS Specific solution

After installing expo-cli in our project, we need to replace build commands.

Go to Xcode > Project Name > Targets > Select you project > Build Phases

Under Build Phases > Go to Expo Bundle Assets or something similar

Replace: expo bundle-assets --platform ios --dest "$dest" with npx expo-cli bundle-assets --platform ios --dest "$dest"

Run npx expo-cli publish --clear

Clean the project and start archiving/building!

Android specific solution (for MacOS/Linux)

On your project root folder, create a file named run-exp.sh.

Add these lines inside of run-exp.sh:

#!/usr/bin/env bash

value=$(cat ~/.expo/PATH)
PATH="$PATH:$value" npx expo-cli "$@"

Under Project Root Folder, go to android/app/expo.gradle

Replace this line:

commandLine("./node_modules/expokit/detach-scripts/run-exp.sh", "bundle-assets", expoRoot, "--platform", "android", "--dest", assetsDir)

with

commandLine("./run-exp.sh", "bundle-assets", expoRoot, "--platform", "android", "--dest", assetsDir)

Run npx expo-cli publish --clear

On Android studio, clean the project and build the app

Android specific solution (for Windows)

On your project root folder, create a file named run-exp.bat.

Add these lines inside of run-exp.bat:

SET /P STOREDPATH=<"%USERPROFILE%\.expo\PATH"
SET PATH="\"%PATH%;%STOREDPATH%\""
npx expo-cli %*

Under Project Root Folder, go to android/app/expo.gradle

Replace this line:

commandLine("cmd", "/c", ".\\node_modules\\expokit\\detach-scripts\\run-exp.bat", "bundle-assets", expoRoot, "--platform", "android", "--dest", assetsDir)

with

commandLine("cmd", "/c", ".\\run-exp.bat", "bundle-assets", expoRoot, "--platform", "android", "--dest", assetsDir)

Run npx expo-cli publish --clear

On Android studio, clean the project and build the app


问:
Pandas dataframe growing exponentially
I have time series data stored in a series of EXCEL files, whose names are stored in a list.  The times are identical in each file and I would like to extract some of the columns from each file and store them in a Pandas DataFrame.  The date is in column A of the XL file and the data items are in columns B and C.  The code stub is

```<code>for x in a_list:

    # Create temporary dataframe

    tmp_df = pd.read_excel(x, sheet_name="Sheet1", header=None, names=["", x + "_1", x + "_2"],
                           index_col=0, usecols=[0, 1, 2], nrows=444)

    # Merge with existing dataframe

    if df.empty:
        df = tmp_df
    else:
        df = df.join(tmp_df)

    df.drop_duplicates()
</code>```

The first pass gives a dataframe with shape (444,2), the second (536, 4), the third (1440, 6), the fourth (10440, 8) etc. until the script stops running because of a memory error.  The column count is growing as expected but I don't understand why the row count grows rapidly when we read the same 444 dates each time.  I have tried using df.merge instead of dj.join but the result is the same.  I added df.drop_duplicates based on similar StackOverflow posts but that had no effect.  Would appreciate any suggestions - thanks in advance!

Update:
It turned out that the problem was nothing to do with the concatentation/joining method but my using the wrong number of rows when reading from EXCEL.  I read too many so the indices were not the same, as I had assumed.  Implemented @Corralien's first solution (neater than mine) and everything good

答:
Try this pattern:

```<code>data = []
for x in a_list:
    df = pd.read_excel(x, sheet_name='Sheet1', header=None,
                       names=['', x + '_1', x + '_2'],
                       index_col=0, usecols=[0, 1, 2], nrows=444)
    data.append(df)

df = pd.concat(data)  # or pd.concat(data, axis=1)
</code>```

Update

Try:

```<code>data = []
for x in a_list:
    df = pd.read_excel(x, sheet_name='Sheet1', header=None,
                       usecols=[0, 1, 2], nrows=444)
    data.append(df)

df = pd.concat(data).set_index(0).rename_axis(None)
</code>```

Title: Pandas dataframe growing exponentially

Body:
I have time series data stored in a series of EXCEL files, whose names are stored in a list.  The times are identical in each file and I would like to extract some of the columns from each file and store them in a Pandas DataFrame.  The date is in column A of the XL file and the data items are in columns B and C.  The code stub is

for x in a_list:

    # Create temporary dataframe

    tmp_df = pd.read_excel(x, sheet_name="Sheet1", header=None, names=["", x + "_1", x + "_2"],
                           index_col=0, usecols=[0, 1, 2], nrows=444)

    # Merge with existing dataframe

    if df.empty:
        df = tmp_df
    else:
        df = df.join(tmp_df)

    df.drop_duplicates()

The first pass gives a dataframe with shape (444,2), the second (536, 4), the third (1440, 6), the fourth (10440, 8) etc. until the script stops running because of a memory error.  The column count is growing as expected but I don't understand why the row count grows rapidly when we read the same 444 dates each time.  I have tried using df.merge instead of dj.join but the result is the same.  I added df.drop_duplicates based on similar StackOverflow posts but that had no effect.  Would appreciate any suggestions - thanks in advance!

Update:
It turned out that the problem was nothing to do with the concatentation/joining method but my using the wrong number of rows when reading from EXCEL.  I read too many so the indices were not the same, as I had assumed.  Implemented @Corralien's first solution (neater than mine) and everything good

Body:
Try this pattern:

data = []
for x in a_list:
    df = pd.read_excel(x, sheet_name='Sheet1', header=None,
                       names=['', x + '_1', x + '_2'],
                       index_col=0, usecols=[0, 1, 2], nrows=444)
    data.append(df)

df = pd.concat(data)  # or pd.concat(data, axis=1)

Update

Try:

data = []
for x in a_list:
    df = pd.read_excel(x, sheet_name='Sheet1', header=None,
                       usecols=[0, 1, 2], nrows=444)
    data.append(df)

df = pd.concat(data).set_index(0).rename_axis(None)


问:
PHP/SQL Update - update only if value has been change
I have following PHP loop + SQL Update query.

```<code>for ($i=0;$i<count($_POST['id']);$i++) {

    if(!isset($_POST['live'][$i])){
        $_POST['live'][$i] = "0";
    } else { $_POST['live'][$i] = "1"; }

    $id = ($_POST['id'][$i]);
    $live = ($_POST['live'][$i]);
    $usr2 = $_SESSION['usr'];
    $updated = date("F j, Y, g:i a",time()+60*60);

    $sql = "UPDATE news SET live = '$live', usr2 = '$usr2', updated = '$updated' WHERE id = $id";
    $result = mysql_query($sql);
    //echo $sql."<br />";

}
if($result) {
    header("location: notes.php");
    exit();

}else {
    die("Query failed");
}
</code>```

How does it work:

I'm submitting big form will ALL OF THE table rows.

receiving this in different file as an array

if $_POST['live'] is 'not set' - set it to '0', if 'set' set it to 1

update array data within for loop

How to UPDATE only the rows which have been actually been changed?

Those which value from $_POST['live'] is actually different from this saved in DB, as the condition would be change of our $live row.

答:
Bobby tables will destroy your database. All your bits are belong to him (strictly speaking, this is an exaggeration, but you need to wrap all of your db inputs with mysql_real_escape_string or better yet, move to PDO's or MySQLi).

Long and the short? No, there is no reliable way to determine whether user input is the same as what is in the database without actually querying the database first or somehow storing the original output from the DB locally ($_SESSION or whatnot).

There are legitimate use cases for that, but it looks like you're better off just calling the updates. You can prevent them slightly by adding AND LIVE != '$live' AND UR2 != '$ur2', but you'll still need to run that many queries.

BTW -- I generally advise people not to use traditional for loops in PHP pretty much ever. PHP's foreach is better in almost every way. Instead of for ($i=0;$i<count();$i++), use foreach( $_POST['id'] as $i => $id ). You'll already have $id declared.

Body:
I have following PHP loop + SQL Update query.

for ($i=0;$i<count($_POST['id']);$i++) {

    if(!isset($_POST['live'][$i])){
        $_POST['live'][$i] = "0";
    } else { $_POST['live'][$i] = "1"; }

    $id = ($_POST['id'][$i]);
    $live = ($_POST['live'][$i]);
    $usr2 = $_SESSION['usr'];
    $updated = date("F j, Y, g:i a",time()+60*60);

    $sql = "UPDATE news SET live = '$live', usr2 = '$usr2', updated = '$updated' WHERE id = $id";
    $result = mysql_query($sql);
    //echo $sql."
";

}
if($result) {
    header("location: notes.php");
    exit();

}else {
    die("Query failed");
}

How does it work:

I'm submitting big form will ALL OF THE table rows.

receiving this in different file as an array

if $_POST['live'] is 'not set' - set it to '0', if 'set' set it to 1

update array data within for loop

How to UPDATE only the rows which have been actually been changed?

Those which value from $_POST['live'] is actually different from this saved in DB, as the condition would be change of our $live row.


问:
Can an interactive report display the original column name in Apex?
Is it possible for an interactive report to show the original column's name instead of "Beautifying" it? Example: column name is data_id but it is displayed Data Id instead.

答:
Well, nothing prevents you to type any heading you find appropriate. data_id included.

If you wanted Apex to use exact column names by default, I'm not aware of such an option.


问:
Wix toolset Bootstrap - Access the internal msi archive
gI am currently migrating to WiX our old setup projects (from VS2008 to VS2019). After some time spent learning how the toolset works, I managed to create and successfully install our application via the msi package.

Since it needs the .Net Framework 4.8 in order to run, I wanted to repackage it inside a bootstrapper with all the needed checks and verifications and so on.

Sadly I have now an issue: due to backwards compatibility I need to be able to access to some properties of the included MSI package in order to create a configuration file.
What I thought was either to access directly to the msi archive (with something like msi.Database.ExecuteScalar(blabla)) or to somehow export the needed information.

I am not an expert on installer coding, but I'm willing to learn :D

EDIT: Since it may not be clear what is my issue I try to explain here:

I have a MSI package from Wix with the components and everything set up. This does install and behave correctly.

Then I have the EXE bootstrap package, again from Wix, with MSI inside, because I need to check if the target machine has the right .Net framework and such.

Then I have ANOTHER EXE, EXE2 that needs to access to some properties of MSI.

With the old setup project MSI was left outside of EXE (I got two different files, no issue for our situation) and then I could access to it without any issue, but with Wix is all packed together...

答:
After a night of sleep I came to the simplest solution: just set Compressed="no" in the included msi et voilà, here is the separated and accessible msi package.

```<code><MsiPackage
    Id="MainPackage"
    SourceFile="$(var.DoomsDayProject.TargetPath)"
    DisplayInternalUI="yes"
    Compressed="no"
    Vital="yes" />
</code>```

Body:
After a night of sleep I came to the simplest solution: just set Compressed="no" in the included msi et voilà, here is the separated and accessible msi package.

<MsiPackage
    Id="MainPackage"
    SourceFile="$(var.DoomsDayProject.TargetPath)"
    DisplayInternalUI="yes"
    Compressed="no"
    Vital="yes" />


问:
PanZoom catch Touch Up event
I am using Panzoom JS to zoom in on a map. It is working just the way I need it for zooming in and out on mobile and desktop. When you click on an item on the map, I grab the x/y coordinates relative to the top left of the container taking into account any scale applied, then look up that location/page in the database and open it. This all works great on desktop, but not on touch. I need to be able to catch the touch up location (just as if you'd clicked with a mouse) but only if there was no touch move, so I can distinguish between a pan/move, a pinch/zoom and a tap/touch-up (click). I can't find any documentation to work this out. Any help would be appreciated.</p>
```<code>const elem = document.getElementById('map_inner_cont')

window.panzoom = panzoom(elem, {
        zoomDoubleClickSpeed: 1,
        autocenter  : true,
        bounds      : true,
        initialZoom : 0.2,
        animate     : true,
        maxZoom     : 2
})
</code>```

答:
Interesting, digging into panzoom a little, I can see you're managing three different sets of events:

```<code>var events;
if (typeof window.PointerEvent === 'function') {
    events = {
        down: 'pointerdown',
        move: 'pointermove',
        up: 'pointerup pointerleave pointercancel'
    };
}
else if (typeof window.TouchEvent === 'function') {
    events = {
        down: 'touchstart',
        move: 'touchmove',
        up: 'touchend touchcancel'
    };
}
else {
    events = {
        down: 'mousedown',
        move: 'mousemove',
        up: 'mouseup mouseleave'
    };
}
</code>```

And my guess is that event.preventDefault() for pointerdown doesn't affect click, whereas touchstart on an older device would, and that's why we're seeing different behavior.

My temptation is to use this same block used above to change what type of event we're listening for so the propagation is the same, but that seems a little fragile.

I'd prefer that panzoom would optionally pass click-like events down as clicks to its children, perhaps? I could try creating a PR around that, if that makes sense.

e.g. Panzoom({ propagateClicks: true })

Title: PanZoom catch Touch Up event

Body:
I am using Panzoom JS to zoom in on a map. It is working just the way I need it for zooming in and out on mobile and desktop. When you click on an item on the map, I grab the x/y coordinates relative to the top left of the container taking into account any scale applied, then look up that location/page in the database and open it. This all works great on desktop, but not on touch. I need to be able to catch the touch up location (just as if you'd clicked with a mouse) but only if there was no touch move, so I can distinguish between a pan/move, a pinch/zoom and a tap/touch-up (click). I can't find any documentation to work this out. Any help would be appreciated.

const elem = document.getElementById('map_inner_cont')

window.panzoom = panzoom(elem, {
        zoomDoubleClickSpeed: 1,
        autocenter  : true,
        bounds      : true,
        initialZoom : 0.2,
        animate     : true,
        maxZoom     : 2
})

Body:
Interesting, digging into panzoom a little, I can see you're managing three different sets of events:

var events;
if (typeof window.PointerEvent === 'function') {
    events = {
        down: 'pointerdown',
        move: 'pointermove',
        up: 'pointerup pointerleave pointercancel'
    };
}
else if (typeof window.TouchEvent === 'function') {
    events = {
        down: 'touchstart',
        move: 'touchmove',
        up: 'touchend touchcancel'
    };
}
else {
    events = {
        down: 'mousedown',
        move: 'mousemove',
        up: 'mouseup mouseleave'
    };
}

And my guess is that event.preventDefault() for pointerdown doesn't affect click, whereas touchstart on an older device would, and that's why we're seeing different behavior.

My temptation is to use this same block used above to change what type of event we're listening for so the propagation is the same, but that seems a little fragile.

I'd prefer that panzoom would optionally pass click-like events down as clicks to its children, perhaps? I could try creating a PR around that, if that makes sense.

e.g. Panzoom({ propagateClicks: true })


Title: Converting multidimensional array into arrays in list for every row

Body:
I have a data set like this,

data = np.array([[ 5, 31, 61],
                 [ 10, 31, 67],
                 [ 15, 31, 69],
                 [ 4, 31, 72],
                 [ 14, 31, 73],
                 [ 21, 31, 77],
                 [ 19, 31, 78]])

I want to convert it into arrays in list for every single row. I tried,

np.split(data,len(data))

#[array([[ 5, 31, 61]]),
# array([[10, 31, 67]]),
# array([[15, 31, 69]]),
# array([[ 4, 31, 72]]),
# array([[14, 31, 73]]),
# array([[21, 31, 77]]),
# array([[19, 31, 78]])]

But as you can see it gives double [ to me. What I simply want is;

[np.array([5, 31, 61]),
np.array([10, 31, 67]),
np.array([15, 31, 69]),
np.array([4, 31, 72]),
np.array([14, 31, 73]),
np.array([21, 31, 77]),
np.array([19, 31, 78])]

Body:
What about taking advantage of unpacking?

lst = [*data]

or:

lst = list(data)

output:

[array([ 5, 31, 61]),
 array([10, 31, 67]),
 array([15, 31, 69]),
 array([ 4, 31, 72]),
 array([14, 31, 73]),
 array([21, 31, 77]),
 array([19, 31, 78])]


问:
parameterized jenkins build with github webhooks
I configured my jenkins job (freestyle) with dev/test/prod environments using choice parameter with "This project is parameterised" option form jenkins job configuration.

I have setup webhook in my github soouce as https://myjenkins/github-webhook/ . when i commit a change to github repo, it is triggering build in jenkins always with "dev" environment option. how to make it to choose any of the other environment, based on my requirement?

I googled but didn't find correct answer. can someone help me?

答: I don't know if I am late but this is for those who are seeking its answer by date.The answer is Just assign same name of your variable of build parameter  in the post content parameter or any other section like headers or request. Like if I have set the branch name in DEPLOY_TO variable and it create build according to this name. But now we want to take branch name from webhook instead of manually selection. All we need to do is to set variable with same name like we will set DEPLOY_TO of value $.push.changes[0].new.name. It will work like a champ. here in post parameters  and look at this