问:
Specified time, move the first (date format)sheet to the last place in tabs
How to make it possible to run the script every night at 23:00,
the sheet name's based on that day's date, e.g. today's date (2022.02.11)

the sheet: 2022.02.11
move it to the last place in the tabs?

as an example I would like to achieve this with script

now:

today after 23:00

since, it should work on android and other platforms, i think its not an option to have a sidebar or maybe a macro..

I found one like this, but it just does what you do when you click on an active sheet
moves it to left

```<code>function tab() {
  var reportDate = new Date();
  var tabName = Utilities.formatDate(reportDate, "GMT+", 'yyyy.MM.dd').toString();
  var tab = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(tabName);
  SpreadsheetApp.setActiveSheet(tab);
  SpreadsheetApp.getActiveSpreadsheet().moveActiveSheet(1);
}
</code>```

it was mentioned familiar here, and this script above is also from there, I just changed the date format to mine
Move Sheet Tab to the Far Left Using Script

Thanks in advance for your help!

答:
In order to move a tab to the most right side, in your script, how about the following modification?

Modified script:

function tab() {
  var reportDate = new Date();
  var tabName = Utilities.formatDate(reportDate, "GMT+", 'yyyy.MM.dd').toString();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var tab = ss.getSheetByName(tabName);
  SpreadsheetApp.setActiveSheet(tab);
  SpreadsheetApp.getActiveSpreadsheet().moveActiveSheet(ss.getSheets().length);
}
```

When you want to run this script at 23:00, please install the time-driven trigger. Ref

Reference:

moveActiveSheet(pos)

Body:
How to make it possible to run the script every night at 23:00,
the sheet name's based on that day's date, e.g. today's date (2022.02.11)

the sheet: 2022.02.11
move it to the last place in the tabs?

as an example I would like to achieve this with script

now:

today after 23:00

since, it should work on android and other platforms, i think its not an option to have a sidebar or maybe a macro..

I found one like this, but it just does what you do when you click on an active sheet
moves it to left

function tab() {
  var reportDate = new Date();
  var tabName = Utilities.formatDate(reportDate, "GMT+", 'yyyy.MM.dd').toString();
  var tab = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(tabName);
  SpreadsheetApp.setActiveSheet(tab);
  SpreadsheetApp.getActiveSpreadsheet().moveActiveSheet(1);
}

it was mentioned familiar here, and this script above is also from there, I just changed the date format to mine
Move Sheet Tab to the Far Left Using Script

Thanks in advance for your help!

Body:
In order to move a tab to the most right side, in your script, how about the following modification?

Modified script:

function tab() {
  var reportDate = new Date();
  var tabName = Utilities.formatDate(reportDate, "GMT+", 'yyyy.MM.dd').toString();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var tab = ss.getSheetByName(tabName);
  SpreadsheetApp.setActiveSheet(tab);
  SpreadsheetApp.getActiveSpreadsheet().moveActiveSheet(ss.getSheets().length);
}

When you want to run this script at 23:00, please install the time-driven trigger. Ref

Reference:

moveActiveSheet(pos)


来源: stackexchange

问:
grep: Search for multiple strings in files recursively, to find source code
I am fairly confident this can't be done with grep, unless there are some features that I don't know about. However I am hoping that if this is the case there might be some other Linux/Unix command line tool which will do the job I want.

This is a frequent problem when working with source code, so I am pretty sure there must be an adequete solution.

Problem:

I am working with some C++ source code, and I want to be able to grep for objects in my code to find the files containing the relevant information.

Here is a simple example:

Search for all files which contain matches for "MyClass" in the namespace "MYNAMESPACE".

Assume that although MyClass and MYNAMESPACE appear to be likely to be unique strings, in general they might not be.

In my case, the namespace "MYNAMESPACE" appears in hundreds of source files.

The actual name of the class I am searching for is "Parameter", which is such a generic word that it too appears in hundreds of files.

Here is what I want a grep-like tool to do:

Specify a list of words to search for

Return the list of files found where ALL words in the list of search words are found in the same file

Do this recursively to obtain all results in all files in a directory

Surely there is a way to do this? This is essentially a filtering problem: Take all the files found (recursively) inside a directory, and apply a filter to them for each of the words in the input list. Files pass the filter if they contain at least one instance of each word.

答:
I suggest to use gawk (standard Linux awk) script.
Scanning each file once for all the words (read each file as a single record).

Count matched words in file.

Print file name only if all words matched.

script.awk

```<code>BEGIN {
  RS="!@!@!@!@!@!@!@"; # set record seperator to something unlikely matched, causing each file to be read entirely as a single record
  getline wordsListStr < wordsListFile ; # read wordsListFile as single string wordsListStr
  close(wordsListFile) ;
  wordsListCount = split(wordsListStr, wordsListArr, "\n"); # split wordsListStr by newLine into array wordsListArr, saved array length into wordsListCount
  for (currWord in wordsListArr) wordsMatchArr[currWord] = 0; # reset array wordsMatchArr to 0
}
{ # for each file (read as single record)
  for (currWord in wordsListArr) { # for each matching word
    if ($0 ~ currWord) wordsMatchArr[currWord] = 1; # if a word was matched mark it a match in wordsMatchArr
  }
}
ENDFILE { # post processing each file
  for (currWord in wordsListArr) {  # scan wordsListArr
    wordsMatchCountInFile += wordsMatchArr[currWord]; # count number of matched words
    wordsMatchArr[currWord] = 0; # reset wordsMatchArr for next file
  }
  if (wordsMatchCountInFile == wordsListCount) print FILENAME; # print current file if all words matched
  wordsMatchCountInFile = 0; # reset words counter in file
}
</code>```

Testing files

input.1.txt

```<code>word1
word2
word3
</code>```

input.2.txt

```<code>word1
word2
</code>```

input.3.txt

```<code>word3
word7
word8
</code>```

input.4.txt

```<code>word3
word3
word7
word8
word1
word1
word7
word2
word8
</code>```

testing output:

```<code>awk -v wordsListFile=input.1.txt -f script.awk input.{2,3,4}.txt
input.4.txt
</code>```

scanning all C++ files under current directory

```<code>awk -v wordsListFile=nameSpacesListFile.txt -f script.awk $(find . -type f -name "*cpp")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I suggest to use gawk (standard Linux awk) script.
Scanning each file once for all the words (read each file as a single record).

Count matched words in file.

Print file name only if all words matched.

script.awk

BEGIN {
  RS="!@!@!@!@!@!@!@"; # set record seperator to something unlikely matched, causing each file to be read entirely as a single record
  getline wordsListStr < wordsListFile ; # read wordsListFile as single string wordsListStr
  close(wordsListFile) ;
  wordsListCount = split(wordsListStr, wordsListArr, "\n"); # split wordsListStr by newLine into array wordsListArr, saved array length into wordsListCount
  for (currWord in wordsListArr) wordsMatchArr[currWord] = 0; # reset array wordsMatchArr to 0
}
{ # for each file (read as single record)
  for (currWord in wordsListArr) { # for each matching word
    if ($0 ~ currWord) wordsMatchArr[currWord] = 1; # if a word was matched mark it a match in wordsMatchArr
  }
}
ENDFILE { # post processing each file
  for (currWord in wordsListArr) {  # scan wordsListArr
    wordsMatchCountInFile += wordsMatchArr[currWord]; # count number of matched words
    wordsMatchArr[currWord] = 0; # reset wordsMatchArr for next file
  }
  if (wordsMatchCountInFile == wordsListCount) print FILENAME; # print current file if all words matched
  wordsMatchCountInFile = 0; # reset words counter in file
}

Testing files

input.1.txt

word1
word2
word3

input.2.txt

word1
word2

input.3.txt

word3
word7
word8

input.4.txt

word3
word3
word7
word8
word1
word1
word7
word2
word8

testing output:

awk -v wordsListFile=input.1.txt -f script.awk input.{2,3,4}.txt
input.4.txt

scanning all C++ files under current directory

awk -v wordsListFile=nameSpacesListFile.txt -f script.awk $(find . -type f -name "*cpp")


问:
What is token-based authentication?
I want to understand what token-based authentication means. I searched the internet but couldn't find anything understandable.</p>

答:
A token is a piece of data created by server, and contains information to identify a particular user and token validity. The token will contain the user's information, as well as a special token code that user can pass to the server with every method that supports authentication, instead of passing a username and password directly.

Token-based authentication is a security technique that authenticates the users who attempt to log in to a server, a network, or some other secure system, using a security token provided by the server.

An authentication is successful if a user can prove to a server that he or she is a valid user by passing a security token. The service validates the security token and processes the user request.

After the token is validated by the service, it is used to establish security context for the client, so the service can make authorization decisions or audit activity for successive user requests.

<s>Source</s> (Web Archive)

Title: What is token-based authentication?


问:
Python win32com - Class not registered error
I'm trying to control a device (Gamry Interface 5000 Potentiostat) via its COM interface using win32com.

# Imports
import win32com.client as client

# Get device list
devices = client.Dispatch('GamryCOM.GamryDeviceList')

# Iterate through devices
for i in range(devices.Count()):
    # Get device (this wors as we only have one connected yet)
    device = devices.EnumSections()[i]
    print(device)

# Setup potentiostat object
potentiostat = client.Dispatch('GamryCOM.GamryPstat')
```
<p>When I run this, I got the following error message:</p>
```IFC5000-10519
Traceback (most recent call last):
  File "c:\Users\Rob\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 86, in _GetGoodDispatch
    IDispatch = pythoncom.connect(IDispatch)
pywintypes.com_error: (-2147221021, 'Operation unavailable', None, None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\Users\[...]\gamry_control_01.py", line 23, in <module>
    potentiostat = client.Dispatch('GamryCOM.GamryPstat', clsctx = pythoncom.CLSCTX_LOCAL_SERVER )
  File "c:\Users\Rob\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\__init__.py", line 117, in Dispatch
    dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch, userName, clsctx)
  File "c:\Users\Rob\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 106, in _GetGoodDispatchAndUserName
    return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "c:\Users\Rob\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 88, in _GetGoodDispatch
    IDispatch = pythoncom.CoCreateInstance(
pywintypes.com_error: (-2147221164, 'Class not registered', None, None)
```

Funnily enough, the first dispatch-statement just works fine, Just the second one fails.

I'm using a 64 Bit Windows 11 setup and tested different Python environments:

Python 3.10 64 Bit, win32com-303 64 Bit

Python 3.9 32 Bit, win32com-303 32 Bit

I also tried using comtypes instead of win32com which resulted in the same error.

Thank you very much for your help!

Regards

答:
I had the same problem and contacted a Salesman.
He sent me a document, saying that on some devices you have to use
pstat = client.CreateObject('GamryCOM.GamryPC5Pstat') for the Reference family and
pstat = client.CreateObject('GamryCOM.GamryPC6Pstat') for the Interface family.
For me, at least the OSError: [WinError -2147221164] Class not registered disappears.
I've used "comtypes".

Body:
I'm trying to control a device (Gamry Interface 5000 Potentiostat) via its COM interface using win32com.

# Imports
import win32com.client as client

# Get device list
devices = client.Dispatch('GamryCOM.GamryDeviceList')

# Iterate through devices
for i in range(devices.Count()):
    # Get device (this wors as we only have one connected yet)
    device = devices.EnumSections()[i]
    print(device)

# Setup potentiostat object
potentiostat = client.Dispatch('GamryCOM.GamryPstat')

When I run this, I got the following error message:

IFC5000-10519
Traceback (most recent call last):
  File "c:\Users\Rob\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 86, in _GetGoodDispatch
    IDispatch = pythoncom.connect(IDispatch)
pywintypes.com_error: (-2147221021, 'Operation unavailable', None, None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\Users\[...]\gamry_control_01.py", line 23, in <module>
    potentiostat = client.Dispatch('GamryCOM.GamryPstat', clsctx = pythoncom.CLSCTX_LOCAL_SERVER )
  File "c:\Users\Rob\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\__init__.py", line 117, in Dispatch
    dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch, userName, clsctx)
  File "c:\Users\Rob\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 106, in _GetGoodDispatchAndUserName
    return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "c:\Users\Rob\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 88, in _GetGoodDispatch
    IDispatch = pythoncom.CoCreateInstance(
pywintypes.com_error: (-2147221164, 'Class not registered', None, None)

Funnily enough, the first dispatch-statement just works fine, Just the second one fails.

I'm using a 64 Bit Windows 11 setup and tested different Python environments:

Python 3.10 64 Bit, win32com-303 64 Bit

Python 3.9 32 Bit, win32com-303 32 Bit

I also tried using comtypes instead of win32com which resulted in the same error.

Thank you very much for your help!

Regards


问:
Node autoscaler based on CPU utilisation
We are working with HPA. Currently we are handling 100/rps per pod.

Use case is when the input rps is at 500/rps for 2 mins after that it goes up to 3k/rps.

We want to scale the number of pods from 5 upto 30 within 30 to 40 sec.

We are able to scale the pods in available resources for example default cluster size is 3 nodes. Problem comes when existing nodes are exhausted and cluster need additional node to schedule a pod.

Scheduling a new node in cluster it takes around 3min 40 sec to 4 min(approx.)

To overcome this problem we want to schedule new node when existing node cluster limit cross certain threshold (cpu utilisation upto 70%).

We are able to configure pod autoscaler using HorizontalPodAutoscaler kind. How can we solve the problem of node autoscaler wrt resource metrics.

答: You can automatically scale your GKE workloads based on metrics available in Cloud Monitoring. In this tutorial, you will see how to set up autoscaling based on CPU utilization.</p>


问:
Is it possible to split one large file into n files without copying?
Is it possible to split one large file into n files without copying ?

Ex.
We have a large 1000 MB file and we want to spit these into say 10 individual files of 100 MB each.

The only way I know is to create 10 new files and copy from the large file given starting and ending position of each individual file.

Is it possible to achieve it without employing copying ?

答: I'd say it's impossible without copying. File data are (for files larger than one MFT record, which 100 MB file usually is) are located in clusters. Let's say you have a 5000 bytes long file that occupies 3 clusters, where 1 cluster is 2048 bytes long - and you want to split it into two files. Then you'll need to use 4 clusters and copy data from second and third cluster, and that's bare minimum of R/W operations, usually you'll need to read these three clusters and write four clusters.</p>


问:
How to know currently logged in username in Oracle SQL?
How to know currently logged in username in Oracle SQL, if we are dealing with multiple users within the same DB, it is little bit confusing to understand!</p>

答:
There are many different ways.

Option 1

Use the V$SESSION view.

```<code>SELECT USERNAME FROM V$SESSION;
</code>```

Option 2

This one gives all the detailed information because there are times that you have to locate locked sessions.

```<code>select
       substr(a.spid,1,9) pid,
       substr(b.sid,1,5) sid,
       substr(b.serial#,1,5) ser#,
       substr(b.machine,1,6) box,
       substr(b.username,1,10) username,
--     b.server,
       substr(b.osuser,1,8) os_user,
       substr(b.program,1,30) program
from v$session b, v$process a
where
b.paddr = a.addr
and type='USER'
order by os_user,username;
</code>```

Body:
There are many different ways.

Option 1

Use the V$SESSION view.

SELECT USERNAME FROM V$SESSION;

Option 2

This one gives all the detailed information because there are times that you have to locate locked sessions.

select
       substr(a.spid,1,9) pid,
       substr(b.sid,1,5) sid,
       substr(b.serial#,1,5) ser#,
       substr(b.machine,1,6) box,
       substr(b.username,1,10) username,
--     b.server,
       substr(b.osuser,1,8) os_user,
       substr(b.program,1,30) program
from v$session b, v$process a
where
b.paddr = a.addr
and type='USER'
order by os_user,username;


问:
Handle state variable initialization
I'm trying to fill form data using state variable. Data of state variable is getting from redux store as shown below :

```<code>  const [location, setLocation] = useState(post && post.location);
  const [hastage, setHastage] = useState(post && post.hastage);
  const [caption, setCaption] = useState(post && post.caption);
  const [postImg, setPostImg] = useState(post && post.postImg);
</code>```

In above code 'post' is redux store instance.

Every thing is working Fine. However, Problem is that :

When I refresh page 'post' data is async call therefore before getting post data all variable is initialized with " "(Blank). and form is getting empty.

Hoe to initialize all state variable after 'post' data is ready ?

答:
You should initialize all state value inside of a useEffect hook, which can allow you to perform some execution after after the DOM have been rendered.

Firstly you 'll initialize all state to an empty string like this

```<code>const [location, setLocation] = useState('');
const [hastage, setHastage] = useState('');
const [caption, setCaption] = useState('');
const [postImg, setPostImg] = useState('');
</code>```

And in the second place you will add useEffect which will allow you to perform side effect

```<code>useEffect(() => {
    // here you can check for existence of any attribute on the `post` object
    if(post && post.location) {
        setLocation(post.location);
    }
    // etc.
}, [post]);
</code>```

You can also pass the post object to the second argument of the useEffect hook, this will trigger the rerender of the component each time the value of post change.

Title: Handle state variable initialization

Body:
I'm trying to fill form data using state variable. Data of state variable is getting from redux store as shown below :

  const [location, setLocation] = useState(post && post.location);
  const [hastage, setHastage] = useState(post && post.hastage);
  const [caption, setCaption] = useState(post && post.caption);
  const [postImg, setPostImg] = useState(post && post.postImg);

In above code 'post' is redux store instance.

Every thing is working Fine. However, Problem is that :

When I refresh page 'post' data is async call therefore before getting post data all variable is initialized with " "(Blank). and form is getting empty.

Hoe to initialize all state variable after 'post' data is ready ?

Body:
You should initialize all state value inside of a useEffect hook, which can allow you to perform some execution after after the DOM have been rendered.

Firstly you 'll initialize all state to an empty string like this

const [location, setLocation] = useState('');
const [hastage, setHastage] = useState('');
const [caption, setCaption] = useState('');
const [postImg, setPostImg] = useState('');

And in the second place you will add useEffect which will allow you to perform side effect

useEffect(() => {
    // here you can check for existence of any attribute on the `post` object
    if(post && post.location) {
        setLocation(post.location);
    }
    // etc.
}, [post]);

You can also pass the post object to the second argument of the useEffect hook, this will trigger the rerender of the component each time the value of post change.


问:
Library is not writable
I have this issue during package installation in R version 3.0.2 (2013-09-25) on an Ubuntu machine:

```<code>install.packages("randomForest")
Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning in install.packages :
  'lib = "/usr/local/lib/R/site-library"' is not writable
</code>```

How to resolve it?

答: The "XX" is not writable error can also mean that the library path you're providing does not exist.

OwnerDisplayName: Priya

ContentLicense: CC BY-SA 3.0

Title: Library is not writable

Body:
I have this issue during package installation in R version 3.0.2 (2013-09-25) on an Ubuntu machine:

install.packages("randomForest")
Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning in install.packages :
  'lib = "/usr/local/lib/R/site-library"' is not writable

How to resolve it?


问:
How to start content div below fixed header without giving margin?
Div with id header is fixed but the div with the id content is going behind the header div. What can I do if I want to fix this issue without adding margin-top to the content div?

I tried adding margin-top but it occurs the problem with other elements in responsive view.

My code

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>

    <style>
        body {
            margin: 0;
            padding: 0;
        }
        #header {
            color: white;
            font-size: 18px;
            background-color: black;
            text-align: center;
            position: fixed;
            width: 100%;
            top: 0;
            opacity: 0.8;
        }

        #header div {
            display: flex;
            justify-content: center;
            align-items: center;
            border: 1px solid grey;
        }

        #content {
            background-color: orange;
        }
    </style>
</head>

<body>
    <div id="header">
        <div>
            <p>This is header</p>
        </div>
    </div>

    <div id="content">
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
    </div>
</body>
</html>
</code>```

答:
 body {
            margin: 0;
            padding: 0;
        }
        #header {
            color: white;
            font-size: 18px;
            background-color: black;
            text-align: center;
            position: fixed;
            z-index: 1;
            width: 100%;
            top: 0;
            opacity: 0.8;
        }

        #header div {
            display: flex;
            justify-content: center;
            align-items: center;
            border: 1px solid grey;
        }

        #content {
            background-color: orange;
            position: relative;
            top: 55px;
            padding-top:10px;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
</head>

<body>
    <div id="header">
        <div>
            <p>This is header</p>
        </div>
    </div>

    <div id="content">
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
    </div>
</body>
</html></code>```

Body:
Div with id header is fixed but the div with the id content is going behind the header div. What can I do if I want to fix this issue without adding margin-top to the content div?

I tried adding margin-top but it occurs the problem with other elements in responsive view.

My code

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>

This is header

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Body:
 body {
            margin: 0;
            padding: 0;
        }
        #header {
            color: white;
            font-size: 18px;
            background-color: black;
            text-align: center;
            position: fixed;
            z-index: 1;
            width: 100%;
            top: 0;
            opacity: 0.8;
        }

        #header div {
            display: flex;
            justify-content: center;
            align-items: center;
            border: 1px solid grey;
        }

        #content {
            background-color: orange;
            position: relative;
            top: 55px;
            padding-top:10px;
        }

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
</head>

<body>
    <div id="header">
        <div>
            <p>This is header</p>
        </div>
    </div>

    <div id="content">
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
    </div>
</body>
</html>


问:
SurfaceView in a Frame Layout problem (InflateException)
I am trying to put a SurfaceView in a Frame Layout in order to insert some buttons into the frame layout for some control over the SurfaceView. But I got this InflateException, which i have no idea what it is. Below is the code for my Preview class and my main.xml

```<code>class Preview extends ViewGroup implements SurfaceHolder.Callback {
private final String TAG = "Preview";

SurfaceView mSurfaceView;
SurfaceHolder mHolder;
Size mPreviewSize;
List<Size> mSupportedPreviewSizes;
Camera mCamera;

Preview(Context context) {
    super(context);
     mSurfaceView = new SurfaceView(context);
     addView(mSurfaceView);

     mHolder = mSurfaceView.getHolder();
     mHolder.addCallback(this);
     mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

public void setCamera(Camera camera) {
    mCamera = camera;
    if(mCamera != null) {
        mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
        requestLayout();
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
    final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
    setMeasuredDimension(width, height);

    if(mSupportedPreviewSizes != null) {
        mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
    }
}

protected void onLayout(boolean changed, int l, int t, int r, int b) {
    if (changed && getChildCount() > 0) {
        final View child = getChildAt(0);

        final int width = r - l;
        final int height = b - t;

        int previewWidth = width;
        int previewHeight = height;
        if(mPreviewSize != null) {
            previewWidth = mPreviewSize.width;
            previewHeight = mPreviewSize.height;
        }

        if(width*previewHeight > height * previewWidth) {
            final int scaledChildWidth = previewWidth * height / previewHeight;
            child.layout(((width) - scaledChildWidth) /2, 0, ((width) + scaledChildWidth) /2, height);
        }
        else {
            final int scaledChildHeight = previewHeight * width / previewWidth;
            child.layout(0, ((height)-scaledChildHeight) / 2, width, ((height) + scaledChildHeight) /2);
        }

    }

}

public void surfaceCreated(SurfaceHolder holder) {
    try {
        if(mCamera != null) {
            mCamera.setPreviewDisplay(holder);
        }
    }
    catch (IOException exception) {

    }
}

Camera.PreviewCallback mPreviewCallback = new Camera.PreviewCallback() {

                public void onPreviewFrame(byte[] data, Camera camera) {
                    int ARRAY_LENGTH = mPreviewSize.width*mPreviewSize.height*3/2;
                    int argb8888[] = new int[ARRAY_LENGTH];

                    decodeYUV(argb8888, data, mPreviewSize.width, mPreviewSize.height);
                    Bitmap bitmap = Bitmap.createBitmap(argb8888, mPreviewSize.width, mPreviewSize.height, Config.ARGB_8888);

                    FileOutputStream fos;
                    try {
                        fos = new FileOutputStream(String.format("/sdcard/testImage/%d.jpg", System.currentTimeMillis()));

                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    bitmap.compress(CompressFormat.JPEG, 75, bos);
            try {
                bos.flush();
            } catch (IOException ex) {
                Logger.getLogger(Preview.class.getName()).log(Level.SEVERE, null, ex);
            }
                    bos.close();
                    fos.close();
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(Preview.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    catch (IOException ex) {
                            Logger.getLogger(Preview.class.getName()).log(Level.SEVERE, null, ex);
                        }

                }
            };

// decode Y, U, and V values on the YUV 420 buffer described as YCbCr_422_SP by Android
// David Manpearl 081201
public void decodeYUV(int[] out, byte[] fg, int width, int height)
    throws NullPointerException, IllegalArgumentException {
int sz = width * height;
if (out == null)
    throw new NullPointerException("buffer out is null");
if (out.length < sz)
    throw new IllegalArgumentException("buffer out size " + out.length
            + " < minimum " + sz);
if (fg == null)
    throw new NullPointerException("buffer 'fg' is null");
if (fg.length < sz)
    throw new IllegalArgumentException("buffer fg size " + fg.length
            + " < minimum " + sz * 3 / 2);
int i, j;
int Y, Cr = 0, Cb = 0;
for (j = 0; j < height; j++) {
    int pixPtr = j * width;
    final int jDiv2 = j >> 1;
    for (i = 0; i < width; i++) {
        Y = fg[pixPtr];
        if (Y < 0)
            Y += 255;
        if ((i & 0x1) != 1) {
            final int cOff = sz + jDiv2 * width + (i >> 1) * 2;
            Cb = fg[cOff];
            if (Cb < 0)
                Cb += 127;
            else
                Cb -= 128;
            Cr = fg[cOff + 1];
            if (Cr < 0)
                Cr += 127;
            else
                Cr -= 128;
        }
        int R = Y + Cr + (Cr >> 2) + (Cr >> 3) + (Cr >> 5);
        if (R < 0)
            R = 0;
        else if (R > 255)
            R = 255;
        int G = Y - (Cb >> 2) + (Cb >> 4) + (Cb >> 5) - (Cr >> 1)
                + (Cr >> 3) + (Cr >> 4) + (Cr >> 5);
        if (G < 0)
            G = 0;
        else if (G > 255)
            G = 255;
        int B = Y + Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6);
        if (B < 0)
            B = 0;
        else if (B > 255)
            B = 255;
        out[pixPtr++] = 0xff000000 + (B << 16) + (G << 8) + R;
    }
}

}

public void surfaceDestroyed(SurfaceHolder holder) {
    if(mCamera != null) {
        mCamera.stopPreview();
    }
}

private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
    final double ASPECT_TOLERANCE = 0.1;
    double targetRatio = (double)w/h;
    if(sizes==null) {
        return null;
    }
    Size optimalSize = null;
    double minDiff = Double.MAX_VALUE;

    int targetHeight = h;

    for(Size size : sizes) {
        double ratio = (double) size.width/size.height;
        if(Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
        if(Math.abs(size.height - targetHeight) < minDiff) {
            optimalSize = size;
            minDiff = Math.abs(size.height - targetHeight);
        }
    }

    if(optimalSize == null) {
        minDiff = Double.MAX_VALUE;
        for (Size size : sizes) {
            if(Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }

        }
    }
    return optimalSize;
}

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    Camera.Parameters parameters = mCamera.getParameters();
    parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
    requestLayout();
    //mCamera.setPreviewCallback(mPreviewCallback);
    mCamera.setParameters(parameters);
    mCamera.startPreview();
}
}
</code>```

my main.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">

    <Button
     android:id="@+id/showhide"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="Toggle The Another Button Show/Hide" />
    <Button
     android:id="@+id/dummy"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="a Button" />
    <FrameLayout
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">
    <camera.test.Preview
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"/>
    </FrameLayout>
</code>```

Logcat

```<code>                        08-18 14:01:37.896: ERROR/AndroidRuntime(401): FATAL EXCEPTION: main
    08-18 14:01:37.896: ERROR/AndroidRuntime(401): java.lang.RuntimeException: Unable to start activity ComponentInfo{camera.test/camera.test.MainActivity}: android.view.InflateException: Binary XML file line #21: Error inflating class camera.test.Preview
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.os.Handler.dispatchMessage(Handler.java:99)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.os.Looper.loop(Looper.java:123)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.app.ActivityThread.main(ActivityThread.java:3683)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at java.lang.reflect.Method.invokeNative(Native Method)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at java.lang.reflect.Method.invoke(Method.java:507)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at dalvik.system.NativeStart.main(Native Method)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401): Caused by: android.view.InflateException: Binary XML file line #21: Error inflating class camera.test.Preview
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.view.LayoutInflater.createView(LayoutInflater.java:508)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.app.Activity.setContentView(Activity.java:1657)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at camera.test.MainActivity.onCreate(MainActivity.java:45)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     ... 11 more
    08-18 14:01:37.896: ERROR/AndroidRuntime(401): Caused by: java.lang.NoSuchMethodException: Preview(Context,AttributeSet)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at java.lang.Class.getMatchingConstructor(Class.java:643)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at java.lang.Class.getConstructor(Class.java:472)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.view.LayoutInflater.createView(LayoutInflater.java:480)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     ... 22 more
</code>```

答:
If you want to inflate a custom widget from XML, you have to implement a constructor with two arguments. In your case it will be:

```<code>public Preview(Context context, AttributeSet attrs) {
    super(context, attrs);
    // implementation ...
}
</code>```

EDIT: And a little out-of-context hint. Do not implement camera preview like this. This is an incorrect way and you'll get a lot of strange bugs. I know this exactly because I implemented a preview for the first time using the same approach. Take a look at Camera application's sources. This is a way better implemetation.

Body:
I am trying to put a SurfaceView in a Frame Layout in order to insert some buttons into the frame layout for some control over the SurfaceView. But I got this InflateException, which i have no idea what it is. Below is the code for my Preview class and my main.xml

class Preview extends ViewGroup implements SurfaceHolder.Callback {
private final String TAG = "Preview";

SurfaceView mSurfaceView;
SurfaceHolder mHolder;
Size mPreviewSize;
List<Size> mSupportedPreviewSizes;
Camera mCamera;

Preview(Context context) {
    super(context);
     mSurfaceView = new SurfaceView(context);
     addView(mSurfaceView);

     mHolder = mSurfaceView.getHolder();
     mHolder.addCallback(this);
     mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

public void setCamera(Camera camera) {
    mCamera = camera;
    if(mCamera != null) {
        mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
        requestLayout();
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
    final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
    setMeasuredDimension(width, height);

    if(mSupportedPreviewSizes != null) {
        mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
    }
}

protected void onLayout(boolean changed, int l, int t, int r, int b) {
    if (changed && getChildCount() > 0) {
        final View child = getChildAt(0);

        final int width = r - l;
        final int height = b - t;

        int previewWidth = width;
        int previewHeight = height;
        if(mPreviewSize != null) {
            previewWidth = mPreviewSize.width;
            previewHeight = mPreviewSize.height;
        }

        if(width*previewHeight > height * previewWidth) {
            final int scaledChildWidth = previewWidth * height / previewHeight;
            child.layout(((width) - scaledChildWidth) /2, 0, ((width) + scaledChildWidth) /2, height);
        }
        else {
            final int scaledChildHeight = previewHeight * width / previewWidth;
            child.layout(0, ((height)-scaledChildHeight) / 2, width, ((height) + scaledChildHeight) /2);
        }

    }

}

public void surfaceCreated(SurfaceHolder holder) {
    try {
        if(mCamera != null) {
            mCamera.setPreviewDisplay(holder);
        }
    }
    catch (IOException exception) {

    }
}

Camera.PreviewCallback mPreviewCallback = new Camera.PreviewCallback() {

                public void onPreviewFrame(byte[] data, Camera camera) {
                    int ARRAY_LENGTH = mPreviewSize.width*mPreviewSize.height*3/2;
                    int argb8888[] = new int[ARRAY_LENGTH];

                    decodeYUV(argb8888, data, mPreviewSize.width, mPreviewSize.height);
                    Bitmap bitmap = Bitmap.createBitmap(argb8888, mPreviewSize.width, mPreviewSize.height, Config.ARGB_8888);

                    FileOutputStream fos;
                    try {
                        fos = new FileOutputStream(String.format("/sdcard/testImage/%d.jpg", System.currentTimeMillis()));

                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    bitmap.compress(CompressFormat.JPEG, 75, bos);
            try {
                bos.flush();
            } catch (IOException ex) {
                Logger.getLogger(Preview.class.getName()).log(Level.SEVERE, null, ex);
            }
                    bos.close();
                    fos.close();
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(Preview.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    catch (IOException ex) {
                            Logger.getLogger(Preview.class.getName()).log(Level.SEVERE, null, ex);
                        }

                }
            };

// decode Y, U, and V values on the YUV 420 buffer described as YCbCr_422_SP by Android
// David Manpearl 081201
public void decodeYUV(int[] out, byte[] fg, int width, int height)
    throws NullPointerException, IllegalArgumentException {
int sz = width * height;
if (out == null)
    throw new NullPointerException("buffer out is null");
if (out.length < sz)
    throw new IllegalArgumentException("buffer out size " + out.length
            + " < minimum " + sz);
if (fg == null)
    throw new NullPointerException("buffer 'fg' is null");
if (fg.length < sz)
    throw new IllegalArgumentException("buffer fg size " + fg.length
            + " < minimum " + sz * 3 / 2);
int i, j;
int Y, Cr = 0, Cb = 0;
for (j = 0; j < height; j++) {
    int pixPtr = j * width;
    final int jDiv2 = j >> 1;
    for (i = 0; i < width; i++) {
        Y = fg[pixPtr];
        if (Y < 0)
            Y += 255;
        if ((i & 0x1) != 1) {
            final int cOff = sz + jDiv2 * width + (i >> 1) * 2;
            Cb = fg[cOff];
            if (Cb < 0)
                Cb += 127;
            else
                Cb -= 128;
            Cr = fg[cOff + 1];
            if (Cr < 0)
                Cr += 127;
            else
                Cr -= 128;
        }
        int R = Y + Cr + (Cr >> 2) + (Cr >> 3) + (Cr >> 5);
        if (R < 0)
            R = 0;
        else if (R > 255)
            R = 255;
        int G = Y - (Cb >> 2) + (Cb >> 4) + (Cb >> 5) - (Cr >> 1)
                + (Cr >> 3) + (Cr >> 4) + (Cr >> 5);
        if (G < 0)
            G = 0;
        else if (G > 255)
            G = 255;
        int B = Y + Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6);
        if (B < 0)
            B = 0;
        else if (B > 255)
            B = 255;
        out[pixPtr++] = 0xff000000 + (B << 16) + (G << 8) + R;
    }
}

}

public void surfaceDestroyed(SurfaceHolder holder) {
    if(mCamera != null) {
        mCamera.stopPreview();
    }
}

private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
    final double ASPECT_TOLERANCE = 0.1;
    double targetRatio = (double)w/h;
    if(sizes==null) {
        return null;
    }
    Size optimalSize = null;
    double minDiff = Double.MAX_VALUE;

    int targetHeight = h;

    for(Size size : sizes) {
        double ratio = (double) size.width/size.height;
        if(Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
        if(Math.abs(size.height - targetHeight) < minDiff) {
            optimalSize = size;
            minDiff = Math.abs(size.height - targetHeight);
        }
    }

    if(optimalSize == null) {
        minDiff = Double.MAX_VALUE;
        for (Size size : sizes) {
            if(Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }

        }
    }
    return optimalSize;
}

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    Camera.Parameters parameters = mCamera.getParameters();
    parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
    requestLayout();
    //mCamera.setPreviewCallback(mPreviewCallback);
    mCamera.setParameters(parameters);
    mCamera.startPreview();
}
}

my main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">

    <Button
     android:id="@+id/showhide"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="Toggle The Another Button Show/Hide" />
    <Button
     android:id="@+id/dummy"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="a Button" />
    <FrameLayout
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">
    <camera.test.Preview
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"/>
    </FrameLayout>

Logcat

                        08-18 14:01:37.896: ERROR/AndroidRuntime(401): FATAL EXCEPTION: main
    08-18 14:01:37.896: ERROR/AndroidRuntime(401): java.lang.RuntimeException: Unable to start activity ComponentInfo{camera.test/camera.test.MainActivity}: android.view.InflateException: Binary XML file line #21: Error inflating class camera.test.Preview
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.os.Handler.dispatchMessage(Handler.java:99)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.os.Looper.loop(Looper.java:123)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.app.ActivityThread.main(ActivityThread.java:3683)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at java.lang.reflect.Method.invokeNative(Native Method)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at java.lang.reflect.Method.invoke(Method.java:507)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at dalvik.system.NativeStart.main(Native Method)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401): Caused by: android.view.InflateException: Binary XML file line #21: Error inflating class camera.test.Preview
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.view.LayoutInflater.createView(LayoutInflater.java:508)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.app.Activity.setContentView(Activity.java:1657)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at camera.test.MainActivity.onCreate(MainActivity.java:45)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     ... 11 more
    08-18 14:01:37.896: ERROR/AndroidRuntime(401): Caused by: java.lang.NoSuchMethodException: Preview(Context,AttributeSet)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at java.lang.Class.getMatchingConstructor(Class.java:643)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at java.lang.Class.getConstructor(Class.java:472)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     at android.view.LayoutInflater.createView(LayoutInflater.java:480)
    08-18 14:01:37.896: ERROR/AndroidRuntime(401):     ... 22 more

Body:
If you want to inflate a custom widget from XML, you have to implement a constructor with two arguments. In your case it will be:

public Preview(Context context, AttributeSet attrs) {
    super(context, attrs);
    // implementation ...
}

EDIT: And a little out-of-context hint. Do not implement camera preview like this. This is an incorrect way and you'll get a lot of strange bugs. I know this exactly because I implemented a preview for the first time using the same approach. Take a look at Camera application's sources. This is a way better implemetation.


问:
.htaccess redirect Home page to query string
I need to redirect

```<code>example.com/
</code>```

to new path on same domain:

```<code>example.com/?viewr=UNESCO/$1
</code>```

How can do it using .htaccess?

Any help would be appreciated.

答:
To redirect example.com/ to example.com/?viewr=UNESCO/$1 then you would need to use mod_rewrite in order to check the query string. Try the following at the top of root .htaccess file:

```<code>RewriteEngine On

RewriteCond %{QUERY_STRING} ^$
RewriteRule ^$ /?viewr=UNESCO/\$1 [R=302,L]
</code>```

The literal $ in the substitution string (2nd argument to the RewriteRule directive) needs to be backslash-escaped to prevent $1 being interpreted as a backreference (which is empty).

UPDATE: If you are using this in a virtualhost context (ie. directly in the <VirtualHost> container, not inside a <Directory> container) then you will need to adjust the RewriteRule pattern from ^$ to ^/$. In other words:

```<code>:
RewriteRule ^/$ /?viewr=UNESCO/\$1 [R=302,L]
</code>```

Reference:

https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#rewriterule

Body:
I need to redirect

example.com/

to new path on same domain:

example.com/?viewr=UNESCO/$1

How can do it using .htaccess?

Any help would be appreciated.

Body:
To redirect example.com/ to example.com/?viewr=UNESCO/$1 then you would need to use mod_rewrite in order to check the query string. Try the following at the top of root .htaccess file:

RewriteEngine On

RewriteCond %{QUERY_STRING} ^$
RewriteRule ^$ /?viewr=UNESCO/\$1 [R=302,L]

The literal $ in the substitution string (2nd argument to the RewriteRule directive) needs to be backslash-escaped to prevent $1 being interpreted as a backreference (which is empty).

UPDATE: If you are using this in a virtualhost context (ie. directly in the <VirtualHost> container, not inside a <Directory> container) then you will need to adjust the RewriteRule pattern from ^$ to ^/$. In other words:

:
RewriteRule ^/$ /?viewr=UNESCO/\$1 [R=302,L]

Reference:

https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#rewriterule


问:
Find specific values in a txt file and adding them up with python
I have a txt file which looks like that:

```<code>[Chapter.Title1]
Irrevelent=90 B
Volt=0.10 ienl
Watt=2 W
Ampere=3 A
Irrevelent=91 C

[Chapter.Title2]
Irrevelent=999
Irrevelent=999

[Chapter.Title3]
Irrevelent=92 B
Volt=0.20 ienl
Watt=5 W
Ampere=6 A
Irrevelent=93 C
</code>```

What I want is that it catches "Title1" and the values "0,1", "2" and "3". Then adds them up (which would be 5.1).

I don't care about the lines with "irrevelent" at the beginning.

And then the same with the third block. Catching "Title3" and adding "0.2", "5" and "6".

The second block with "Title2" does not contain "Volt", Watt" and "Ampere" and is therefore not relevant.

Can anyone please help me out with this?

Thank you and cheers

答:
Here's a quick and dirty way to do this, reading line by line, if the input file is predictable enough.

In the example I just print out the titles and the values; you can of course process them however you want.

```<code>f = open('file.dat','r')

for line in f.readlines():

    ## Catch the title of the line:
    if '[Chapter' in line:
        print(line[9:-2])

    ## catch the values of Volt, Watt, Amere parameters
    elif line[:4] in ['Volt','Watt','Ampe']:
        value = line[line.index('=')+1:line.index(' ')]
        print(value)

    ## if line is "Irrelevant", or blank, do nothing

f.close()
</code>```

Body:
I have a txt file which looks like that:

[Chapter.Title1]
Irrevelent=90 B
Volt=0.10 ienl
Watt=2 W
Ampere=3 A
Irrevelent=91 C

[Chapter.Title2]
Irrevelent=999
Irrevelent=999

[Chapter.Title3]
Irrevelent=92 B
Volt=0.20 ienl
Watt=5 W
Ampere=6 A
Irrevelent=93 C

What I want is that it catches "Title1" and the values "0,1", "2" and "3". Then adds them up (which would be 5.1).

I don't care about the lines with "irrevelent" at the beginning.

And then the same with the third block. Catching "Title3" and adding "0.2", "5" and "6".

The second block with "Title2" does not contain "Volt", Watt" and "Ampere" and is therefore not relevant.

Can anyone please help me out with this?

Thank you and cheers

Body:
Here's a quick and dirty way to do this, reading line by line, if the input file is predictable enough.

In the example I just print out the titles and the values; you can of course process them however you want.

f = open('file.dat','r')

for line in f.readlines():

    ## Catch the title of the line:
    if '[Chapter' in line:
        print(line[9:-2])

    ## catch the values of Volt, Watt, Amere parameters
    elif line[:4] in ['Volt','Watt','Ampe']:
        value = line[line.index('=')+1:line.index(' ')]
        print(value)

    ## if line is "Irrelevant", or blank, do nothing

f.close()


问:
jquery filter xml data by attribute value
xml code:

```<code><area>
 <point area="54" lat="44.744081" lng="-62.790818" />
 <point area="54" lat="44.743851" lng="-62.792953" />
 <point area="54" lat="44.744439" lng="-62.794366" />
 <point area="55" lat="44.786528" lng="-62.835136" />
 <point area="55" lat="44.787447" lng="-62.835955" />
 <point area="55" lat="44.786528" lng="-62.835136" />
 <point area="56" lat="44.746209" lng="-62.83688" />
 <point area="56" lat="44.745966" lng="-62.836843" />
 <point area="56" lat="44.746246" lng="-62.836481" />
 <point area="56" lat="44.746209" lng="-62.83688" />
</area>
</code>```

I would like to retrieve filtered information by the area number.  in my jQuery code, I have:

```<code>$(xml).find('point').each(function(){
  var area = $(this).attr('area');
  if(area == 56){
    var alat=$(this).attr('lat');
    var alng=$(this).attr('lng');
    string += 'lat= ' + alat + ', lng=' + alng;
    }
  });
</code>```

I saw some suggestions online and thought I could do it this way:

```<code>$(xml).find("point[area='56']").each(function(){
    var alat=$(this).attr('lat');
    var alng=$(this).attr('lng');
    string += 'lat= ' + alat + ', lng=' + alng;
  });
</code>```

So how I can streamline my code well so I can use loop through xml files to get each area for different arrangements?

答:
You could use a selector like this:

```<code>$(xml).find("[area][area!=]")
</code>```

which will find all elements in the xml text that have an area attribute that isn't empty

Body:
xml code:

<area>
 <point area="54" lat="44.744081" lng="-62.790818" />
 <point area="54" lat="44.743851" lng="-62.792953" />
 <point area="54" lat="44.744439" lng="-62.794366" />
 <point area="55" lat="44.786528" lng="-62.835136" />
 <point area="55" lat="44.787447" lng="-62.835955" />
 <point area="55" lat="44.786528" lng="-62.835136" />
 <point area="56" lat="44.746209" lng="-62.83688" />
 <point area="56" lat="44.745966" lng="-62.836843" />
 <point area="56" lat="44.746246" lng="-62.836481" />
 <point area="56" lat="44.746209" lng="-62.83688" />
</area>

I would like to retrieve filtered information by the area number.  in my jQuery code, I have:

$(xml).find('point').each(function(){
  var area = $(this).attr('area');
  if(area == 56){
    var alat=$(this).attr('lat');
    var alng=$(this).attr('lng');
    string += 'lat= ' + alat + ', lng=' + alng;
    }
  });

I saw some suggestions online and thought I could do it this way:

$(xml).find("point[area='56']").each(function(){
    var alat=$(this).attr('lat');
    var alng=$(this).attr('lng');
    string += 'lat= ' + alat + ', lng=' + alng;
  });

So how I can streamline my code well so I can use loop through xml files to get each area for different arrangements?

Body:
You could use a selector like this:

$(xml).find("[area][area!=]")

which will find all elements in the xml text that have an area attribute that isn't empty


问:
Why floating point error message is not printing on stderr?
I am running c language code using a java application using java.lang.ProcessBuilder. If any output and error generated by this c language code, I am able to read those via process.getInputStream() and process.getErrorStream(). But in some cases (when exit code = 136 or 139) like if the code execution failed due to floating point error, I am not getting any error in process's error stream.
So, I tried to run my c language code directly on shell and redirected stderr and stdout to seperate files.
Code.c

```<code>#include<stdio.h>

int main() {
    int x = 1/0;
    return 0;
}
</code>```

Command I am running:

```<code># gcc Code.c -o Code.out -std=c99
# ./Code.out 2>err.log 1>out.log
Floating point exception (core dumped)
</code>```

As you can see above error is printing on shell only but not redirecting to err.log. Also, nothing is there in err.log. My question is why this is not printing in stderr stream? As per my understanding if it is not printing in stderr I will not be able to read it via process.getErrorStream. Whatever the error message generated by code execution, I wanted to show it to end user.

答:
As dave_thompson_085 comments, the Floating point exception (core dumped) message is from the Shell rather than the program.

This is a test program:

```<code>#include<stdio.h>

int main() {
    fprintf(stdout, "normal output, %d\n", __LINE__);
    fprintf(stderr, "error output, %d\n", __LINE__);
    fflush(stdout);
    fflush(stderr);

    int x = 1/0;

    fprintf(stdout, "normal output, %d\n", __LINE__);
    fprintf(stderr, "error output, %d\n", __LINE__);
    fflush(stdout);
    fflush(stderr);

    return 0;
}
</code>```

# gcc code.c -o Code -std=c99
# ./Code  2>err.log 1>out.log
normal output, 4
error output, 5
Floating point exception (core dumped)

# cat out.log
normal output, 4

$cat err.log
error output, 5
```

When the float exception occurs, it is captured by the OS and forced to exit.

Body:
I am running c language code using a java application using java.lang.ProcessBuilder. If any output and error generated by this c language code, I am able to read those via process.getInputStream() and process.getErrorStream(). But in some cases (when exit code = 136 or 139) like if the code execution failed due to floating point error, I am not getting any error in process's error stream.
So, I tried to run my c language code directly on shell and redirected stderr and stdout to seperate files.
Code.c

#include<stdio.h>

int main() {
    int x = 1/0;
    return 0;
}

Command I am running:

# gcc Code.c -o Code.out -std=c99
# ./Code.out 2>err.log 1>out.log
Floating point exception (core dumped)

As you can see above error is printing on shell only but not redirecting to err.log. Also, nothing is there in err.log. My question is why this is not printing in stderr stream? As per my understanding if it is not printing in stderr I will not be able to read it via process.getErrorStream. Whatever the error message generated by code execution, I wanted to show it to end user.

Body:
As dave_thompson_085 comments, the Floating point exception (core dumped) message is from the Shell rather than the program.

This is a test program:

#include<stdio.h>

int main() {
    fprintf(stdout, "normal output, %d\n", __LINE__);
    fprintf(stderr, "error output, %d\n", __LINE__);
    fflush(stdout);
    fflush(stderr);

    int x = 1/0;

    fprintf(stdout, "normal output, %d\n", __LINE__);
    fprintf(stderr, "error output, %d\n", __LINE__);
    fflush(stdout);
    fflush(stderr);

    return 0;
}

# gcc code.c -o Code -std=c99
# ./Code  2>err.log 1>out.log
normal output, 4
error output, 5
Floating point exception (core dumped)

# cat out.log
normal output, 4

$cat err.log
error output, 5

When the float exception occurs, it is captured by the OS and forced to exit.


问:
Laravel check for unique rule without itself in update
I am having my validation rules for unique in the update section.

In inserting or adding the unique rule is 'Email' =>  array('unique:driver_details'), and it will check for the unique coloumn.

But this fails for the update section. While updating it satisfies the other rules and in the unique of email it is checking itself for the unique coloumn  and it fails but seeing its own field.

So, how can i check for the unique except its own value in the database ?

答:
```<code>  $validator = validator()->make($request->all(), [
            'product_name'  => 'required|min:10|unique:products,name,'.$id,
            'product_slug'  => 'required|min:10|unique:products,slug,'.$id,
            'product_desc'  => 'required',
            'short_desc'    => 'required',
            'color'         => 'required',
            'product_sku'   => 'required|unique:products,sku,'.$id,
            'offer_price'   => 'required',
            'actual_price'  => 'required',
            'product_size*' => 'required',
            'product_image*'=> 'required|mimes:jpeg,png,jpg',
            'product_brand' => 'required',
            'product_meta'  => 'required',
        ]);

    if($validator->fails()) {
        $messages = $validator->messages();
        return redirect()->back()->withErrors($messages);
    }
</code>```

this $id Forcing a unique rule to ignore a given id this is working for me

Body:
  $validator = validator()->make($request->all(), [
            'product_name'  => 'required|min:10|unique:products,name,'.$id,
            'product_slug'  => 'required|min:10|unique:products,slug,'.$id,
            'product_desc'  => 'required',
            'short_desc'    => 'required',
            'color'         => 'required',
            'product_sku'   => 'required|unique:products,sku,'.$id,
            'offer_price'   => 'required',
            'actual_price'  => 'required',
            'product_size*' => 'required',
            'product_image*'=> 'required|mimes:jpeg,png,jpg',
            'product_brand' => 'required',
            'product_meta'  => 'required',
        ]);

    if($validator->fails()) {
        $messages = $validator->messages();
        return redirect()->back()->withErrors($messages);
    }

this $id Forcing a unique rule to ignore a given id this is working for me


问:
Pythonic way to a double comprehension
I have to get a list of handles and labels from a figure, except in the cases where the label is "True" or "False". The following code accomplishes this:

```<code># h, l = [a for a in ax.get_legend_handles_labels()] #redundant
h, l = ax.get_legend_handles_labels()
handles = [a for a, b in zip(h, l) if (b != 'True' and b != 'False')]
labels = [b for a, b in zip(h, l) if (b != 'True' and b != 'False')]
</code>```

Nevertheless, this seems completely "not-pythonic". Is there a more elegant way to solve this?
I tried the following 2-liner but I got a ValueError: too many values to unpack (expected 2) on line 2:

```<code>h, l = [a for a in ax.get_legend_handles_labels()]
handles, labels = [(a,b) for a, b in zip(h, l) if (b != 'True' and b != 'False')]
</code>```

I'd expect Python to have a one-line solution...is there any?

For reproducibility:

```<code>(h,l)=(['handle1','handle2', 'handle3'],['label1','True', 'False'])
handles = [a for a, b in zip(h, l) if (b != 'True' and b != 'False')]
labels = [b for a, b in zip(h, l) if (b != 'True' and b != 'False')]
</code>```

The intended output for this reproducible example is

```<code>handles=['handle1']
labels=['label1']
</code>```

答:
You can use zip again:

h, l = [a for a in ax.get_legend_handles_labels()]
filtered_hl = [(a,b) for a, b in zip(h, l) if (b != 'True' and b != 'False')]
handles, labels = map(list, zip(*filtered_hl))
```

Title: Pythonic way to a double comprehension

Body:
I have to get a list of handles and labels from a figure, except in the cases where the label is "True" or "False". The following code accomplishes this:

# h, l = [a for a in ax.get_legend_handles_labels()] #redundant
h, l = ax.get_legend_handles_labels()
handles = [a for a, b in zip(h, l) if (b != 'True' and b != 'False')]
labels = [b for a, b in zip(h, l) if (b != 'True' and b != 'False')]

Nevertheless, this seems completely "not-pythonic". Is there a more elegant way to solve this?
I tried the following 2-liner but I got a ValueError: too many values to unpack (expected 2) on line 2:

h, l = [a for a in ax.get_legend_handles_labels()]
handles, labels = [(a,b) for a, b in zip(h, l) if (b != 'True' and b != 'False')]

I'd expect Python to have a one-line solution...is there any?

For reproducibility:

(h,l)=(['handle1','handle2', 'handle3'],['label1','True', 'False'])
handles = [a for a, b in zip(h, l) if (b != 'True' and b != 'False')]
labels = [b for a, b in zip(h, l) if (b != 'True' and b != 'False')]

The intended output for this reproducible example is

handles=['handle1']
labels=['label1']


问:
A minimal reproducible example to show asynchronous behavior using callbacks in Python
Background: To me it seems clear, that the conecpt of callbacks is flexible, but I also thought, it makes code much faster. However, the following example works, but it cannot show that time can be saved using a callback Ref1:

```<code>import time
from time import sleep

def callbackFunc(delay):
  time.sleep(delay)
  print("callback:     message 3 delay " + str(delay))

def saysomething(delay, callback):
  print("saysomething: message 2 delay " + str(delay))
  callback(delay) # hier muss ich schon wissen, dass nur "delay" benötigt wird...
  time.sleep(2)

if __name__ == '__main__':
  t0 = time.time()
  print("main:         message 1.")
  saysomething(2, callbackFunc)
  print("main:         message 4.")
  print("\ntime: ",time.time() - t0)
</code>```

Output

```<code>main:         message 1.
saysomething: message 2 delay 2
callback:     message 3 delay 2
main:         message 4.
time:  4.01
</code>```

So how can I achive something like this

```<code>main:         message 1.
saysomething: message 2 delay 2
callback:     message 3 delay 2
main:         message 4.
time:  2  !!!!!!!!!!!!!
</code>```

Perhaps it was even possible to switch the order of messages 3 & 4? Or do I get anything wrong?

Perhaps, these answers here and here and the following code from here which does not use callbacks but shows asynchronous behavior help?

答:
You are correct about callbacks being a way of providing "flexibilty" but it has really nothing to do with "speed". The typical use case for a callback is the situation where function 1 is calling function 2 that is performing some function whose completion occurs asynchronously so that function 2 will be returning more or less immediately back but function 1 still needs to arrange for a notification to occur when that asynchronous completion occurs. Therefore, function 1 passes to function 2 a callback function that will be invoked with agreed-upon arguments when that completion occurs.

In your case your asynchronous event is the expiration of a time interval and your callback function is passed what that delay time interval was. Now it turns out that Python comes with a sched.scheduler class that allows you to schedule "events" to be run in the future by either specifying an absolute time value or a delay, which will be added to the current time to compute the absolute time at which the event is to be run. This event is just a callback function to which you can specify any arguments you wish. The problem with this class, in my opinion, is that you have to first enter all the events that you will want to be running and then call a run method that will block until all the events are run. Much better would be to just specify a future event you want to run (that is, a callback) and continue without blocking and this event will run asynchronously in another thread. And so I have heavily modified the sched.scheduler class to create a Scheduler class. Your code would then look like:

import time
from scheduler import Scheduler

def callbackFunc(msg_no, delay):
    print(f"callback: message number {msg_no}, delay {delay} at {time.time()}")

def saysomething(msg_no, delay, callback):
    print(f"saysomething: message {msg_no}, delay {delay} at {time.time()}")
    scheduler.enter(delay, callbackFunc, args=(msg_no, delay,))
    time.sleep(2)

if __name__ == '__main__':
    scheduler = Scheduler()
    saysomething(1, 1, callbackFunc)
    saysomething(2, 2, callbackFunc)
    saysomething(3, 3, callbackFunc)
```
<p>Prints:</p>
<pre class="lang-none prettyprint-override"><code>saysomething: message 1, delay 1 at 1644584120.865646
callback: message number 1, delay 1 at 1644584121.8778687
saysomething: message 2, delay 2 at 1644584122.8747876
saysomething: message 3, delay 3 at 1644584124.8790839
callback: message number 2, delay 2 at 1644584124.8790839
callback: message number 3, delay 3 at 1644584127.9029477
</code>```

And the Scheduler class:

"""
Modified sched.schedule class.
"""

import time
import heapq
from collections import namedtuple
import threading

class Event(namedtuple('Event', 'start_time, priority, action, args, kwargs')):
    __slots__ = []
    def __eq__(s, o): return (s.start_time, s.priority) == (o.start_time, o.priority)
    def __lt__(s, o): return (s.start_time, s.priority) <  (o.start_time, o.priority)
    def __le__(s, o): return (s.start_time, s.priority) <= (o.start_time, o.priority)
    def __gt__(s, o): return (s.start_time, s.priority) >  (o.start_time, o.priority)
    def __ge__(s, o): return (s.start_time, s.priority) >= (o.start_time, o.priority)

Event.start_time.__doc__ = ('''Numeric type compatible with the return value from time.monotonic.''')
Event.priority.__doc__ = ('''Events scheduled for the same time will be executed
in the order of their priority.''')
Event.action.__doc__ = ('''Executing the event means executing
action(*args, **kwargs)''')
Event.args.__doc__ = ('''args is a sequence holding the positional
arguments for the action.''')
Event.kwargs.__doc__ = ('''kwargs is a dictionary holding the keyword
arguments for the action.''')

_sentinel = object()

class Scheduler:
    def __init__(self, daemon=False):
        """
        Initialize a new instance.
        If daemon is True, the scheduler thread will run as a daemon so it will be possible
        for the main thread to terminate with scheduled events yet to run.
        Regardless of how the daemon argument is set, when a new event is added a new
        scheduler thread will be started if the previous thread has terminated.
        """
        self._queue = []
        self._daemon=daemon
        self._running = False
        self._got_event = threading.Condition()
        self._queue_exhausted = threading.Event()
        self._queue_exhausted.set()
        self._thread = None

    def __del__(self):
        if not self._daemon and self._thread:
            self._thread.join()

    def enterabs(self, start_time, action, args=(), kwargs=_sentinel, priority=1):
        """Enter a new event in the queue at an absolute time.

        Returns an ID for the event which can be used to remove it,
        if necessary.

        """
        if kwargs is _sentinel:
            kwargs = {}
        event = Event(start_time, priority, action, args, kwargs)
        with self._got_event:
            heapq.heappush(self._queue, event)
            self._queue_exhausted.clear()
            if not self._running:
                if self._thread:
                    self._thread.join() # tidy up
                self._running = True
                self._thread = threading.Thread(target=self._run, daemon=self._daemon).start()
            else:
                self._got_event.notify()

        return event # The ID

    def enter(self, delay, action, args=(), kwargs=_sentinel, priority=1):
        """A variant that specifies the time as a relative time.

        This is actually the more commonly used interface.

        """
        start_time = time.monotonic() + delay
        return self.enterabs(start_time, action, args, kwargs, priority)

    def cancel(self, event):
        """Remove an event from the queue.

        This must be presented the ID as returned by enter().
        If the event is not in the queue, this raises ValueError.

        """
        with self._got_event:
            self._queue.remove(event)
            heapq.heapify(self._queue)

    def empty(self):
        """Check whether the queue is empty."""
        with self._got_event:
            return not self._queue

    def running(self):
        """Check whether the scheduler is running."""
        with self._got_event:
            return self._running

    def _run(self):
        """Execute events until the queue is empty."""

        # localize variable access to minimize overhead
        # and to improve thread safety
        got_event = self._got_event
        q = self._queue
        delayfunc = time.sleep
        timefunc = time.monotonic
        pop = heapq.heappop
        queue_exhausted = self._queue_exhausted
        while True:
            try:
                while True:
                    with got_event:
                        if not q:
                            self._running = False
                            queue_exhausted.set()
                            return
                        start_time, priority, action, args, kwargs = q[0]
                        now = timefunc()
                        if start_time > now:
                            # Wait for either the time to elapse or a new Event to be added:
                            got_event.wait(timeout=(start_time - now))
                            continue
                        pop(q)
                    action(*args, **kwargs)
                    delayfunc(0)   # Let other threads run
            except:
                pass

    @property
    def queue(self):
        """An ordered list of upcoming events.

        Events are named tuples with fields for:
            start_time, priority, action, argss, kwargs

        """
        # Use heapq to sort the queue rather than using 'sorted(self._queue)'.
        # With heapq, two events scheduled at the same time will show in
        # the actual order they would be retrieved.
        with self._got_event:
            events = self._queue[:]
        return list(map(heapq.heappop, [events]*len(events)))

    def wait_for_queue_empty(self):
        """Wait for the queue to become empty."""
        return self._queue_exhausted.wait()
```

Body:
Background: To me it seems clear, that the conecpt of callbacks is flexible, but I also thought, it makes code much faster. However, the following example works, but it cannot show that time can be saved using a callback Ref1:

import time
from time import sleep

def callbackFunc(delay):
  time.sleep(delay)
  print("callback:     message 3 delay " + str(delay))

def saysomething(delay, callback):
  print("saysomething: message 2 delay " + str(delay))
  callback(delay) # hier muss ich schon wissen, dass nur "delay" benötigt wird...
  time.sleep(2)

if __name__ == '__main__':
  t0 = time.time()
  print("main:         message 1.")
  saysomething(2, callbackFunc)
  print("main:         message 4.")
  print("\ntime: ",time.time() - t0)

Output

main:         message 1.
saysomething: message 2 delay 2
callback:     message 3 delay 2
main:         message 4.
time:  4.01

So how can I achive something like this

main:         message 1.
saysomething: message 2 delay 2
callback:     message 3 delay 2
main:         message 4.
time:  2  !!!!!!!!!!!!!

Perhaps it was even possible to switch the order of messages 3 & 4? Or do I get anything wrong?

Perhaps, these answers here and here and the following code from here which does not use callbacks but shows asynchronous behavior help?

Body:
You are correct about callbacks being a way of providing "flexibilty" but it has really nothing to do with "speed". The typical use case for a callback is the situation where function 1 is calling function 2 that is performing some function whose completion occurs asynchronously so that function 2 will be returning more or less immediately back but function 1 still needs to arrange for a notification to occur when that asynchronous completion occurs. Therefore, function 1 passes to function 2 a callback function that will be invoked with agreed-upon arguments when that completion occurs.

In your case your asynchronous event is the expiration of a time interval and your callback function is passed what that delay time interval was. Now it turns out that Python comes with a sched.scheduler class that allows you to schedule "events" to be run in the future by either specifying an absolute time value or a delay, which will be added to the current time to compute the absolute time at which the event is to be run. This event is just a callback function to which you can specify any arguments you wish. The problem with this class, in my opinion, is that you have to first enter all the events that you will want to be running and then call a run method that will block until all the events are run. Much better would be to just specify a future event you want to run (that is, a callback) and continue without blocking and this event will run asynchronously in another thread. And so I have heavily modified the sched.scheduler class to create a Scheduler class. Your code would then look like:

import time
from scheduler import Scheduler

def callbackFunc(msg_no, delay):
    print(f"callback: message number {msg_no}, delay {delay} at {time.time()}")

def saysomething(msg_no, delay, callback):
    print(f"saysomething: message {msg_no}, delay {delay} at {time.time()}")
    scheduler.enter(delay, callbackFunc, args=(msg_no, delay,))
    time.sleep(2)

if __name__ == '__main__':
    scheduler = Scheduler()
    saysomething(1, 1, callbackFunc)
    saysomething(2, 2, callbackFunc)
    saysomething(3, 3, callbackFunc)

Prints:

saysomething: message 1, delay 1 at 1644584120.865646
callback: message number 1, delay 1 at 1644584121.8778687
saysomething: message 2, delay 2 at 1644584122.8747876
saysomething: message 3, delay 3 at 1644584124.8790839
callback: message number 2, delay 2 at 1644584124.8790839
callback: message number 3, delay 3 at 1644584127.9029477

And the Scheduler class:

"""
Modified sched.schedule class.
"""

import time
import heapq
from collections import namedtuple
import threading

class Event(namedtuple('Event', 'start_time, priority, action, args, kwargs')):
    __slots__ = []
    def __eq__(s, o): return (s.start_time, s.priority) == (o.start_time, o.priority)
    def __lt__(s, o): return (s.start_time, s.priority) <  (o.start_time, o.priority)
    def __le__(s, o): return (s.start_time, s.priority) <= (o.start_time, o.priority)
    def __gt__(s, o): return (s.start_time, s.priority) >  (o.start_time, o.priority)
    def __ge__(s, o): return (s.start_time, s.priority) >= (o.start_time, o.priority)

Event.start_time.__doc__ = ('''Numeric type compatible with the return value from time.monotonic.''')
Event.priority.__doc__ = ('''Events scheduled for the same time will be executed
in the order of their priority.''')
Event.action.__doc__ = ('''Executing the event means executing
action(*args, **kwargs)''')
Event.args.__doc__ = ('''args is a sequence holding the positional
arguments for the action.''')
Event.kwargs.__doc__ = ('''kwargs is a dictionary holding the keyword
arguments for the action.''')

_sentinel = object()

class Scheduler:
    def __init__(self, daemon=False):
        """
        Initialize a new instance.
        If daemon is True, the scheduler thread will run as a daemon so it will be possible
        for the main thread to terminate with scheduled events yet to run.
        Regardless of how the daemon argument is set, when a new event is added a new
        scheduler thread will be started if the previous thread has terminated.
        """
        self._queue = []
        self._daemon=daemon
        self._running = False
        self._got_event = threading.Condition()
        self._queue_exhausted = threading.Event()
        self._queue_exhausted.set()
        self._thread = None

    def __del__(self):
        if not self._daemon and self._thread:
            self._thread.join()

    def enterabs(self, start_time, action, args=(), kwargs=_sentinel, priority=1):
        """Enter a new event in the queue at an absolute time.

        Returns an ID for the event which can be used to remove it,
        if necessary.

        """
        if kwargs is _sentinel:
            kwargs = {}
        event = Event(start_time, priority, action, args, kwargs)
        with self._got_event:
            heapq.heappush(self._queue, event)
            self._queue_exhausted.clear()
            if not self._running:
                if self._thread:
                    self._thread.join() # tidy up
                self._running = True
                self._thread = threading.Thread(target=self._run, daemon=self._daemon).start()
            else:
                self._got_event.notify()

        return event # The ID

    def enter(self, delay, action, args=(), kwargs=_sentinel, priority=1):
        """A variant that specifies the time as a relative time.

        This is actually the more commonly used interface.

        """
        start_time = time.monotonic() + delay
        return self.enterabs(start_time, action, args, kwargs, priority)

    def cancel(self, event):
        """Remove an event from the queue.

        This must be presented the ID as returned by enter().
        If the event is not in the queue, this raises ValueError.

        """
        with self._got_event:
            self._queue.remove(event)
            heapq.heapify(self._queue)

    def empty(self):
        """Check whether the queue is empty."""
        with self._got_event:
            return not self._queue

    def running(self):
        """Check whether the scheduler is running."""
        with self._got_event:
            return self._running

    def _run(self):
        """Execute events until the queue is empty."""

        # localize variable access to minimize overhead
        # and to improve thread safety
        got_event = self._got_event
        q = self._queue
        delayfunc = time.sleep
        timefunc = time.monotonic
        pop = heapq.heappop
        queue_exhausted = self._queue_exhausted
        while True:
            try:
                while True:
                    with got_event:
                        if not q:
                            self._running = False
                            queue_exhausted.set()
                            return
                        start_time, priority, action, args, kwargs = q[0]
                        now = timefunc()
                        if start_time > now:
                            # Wait for either the time to elapse or a new Event to be added:
                            got_event.wait(timeout=(start_time - now))
                            continue
                        pop(q)
                    action(*args, **kwargs)
                    delayfunc(0)   # Let other threads run
            except:
                pass

    @property
    def queue(self):
        """An ordered list of upcoming events.

        Events are named tuples with fields for:
            start_time, priority, action, argss, kwargs

        """
        # Use heapq to sort the queue rather than using 'sorted(self._queue)'.
        # With heapq, two events scheduled at the same time will show in
        # the actual order they would be retrieved.
        with self._got_event:
            events = self._queue[:]
        return list(map(heapq.heappop, [events]*len(events)))

    def wait_for_queue_empty(self):
        """Wait for the queue to become empty."""
        return self._queue_exhausted.wait()