问:
What is wrong with this sorting of dictionary?
I am trying to sort the dictionary here:

```<code>car =   {
  "brand": ["Ford","Honda","Toyota","Tesla","Ford"],
  "model": ["Mustang","CRV","RAV4","X","Transit"],
  "year": [1964,2010,2015,2022,1964],
  "color": ["Red","Yellow","Green","Blue","Black"]
}

sortedbyval1={k: v for k, v in sorted(car.items(),key=lambda v:v[1])}
</code>```

I keep getting error message like below. There is no < in the code!!!

```<code>TypeError: '<' not supported between instances of 'int' and 'str'
</code>```

I am trying to sort the car dictionary by model, year, color etc.

If possible, by color AND year.

答:
It doesn't work because you have a dictionary of a bunch of car attributes, not a collection of cars. That's why when you use key=lambda v:v[1], sorted is trying to compare lists that contain different types. For example, "year" only contains ints, yet you want to compare it with "brand" which contains strings, so you get the TypeError.

You could rework that dictionary to create a list of cars. Assuming the same index value corresponds to the same car, you can iterate over the zipped car.values() and create a list of dictionaries using the dict constructor where each dictionary is a car.

Then use list.sort where the sorting key is by model, year and color to sort the list of cars.

```<code>list_of_cars = [dict(zip(car.keys(), tpl)) for tpl in zip(*car.values())]
list_of_cars.sort(key=lambda car: (car['model'], car['year'], car['color']))
</code>```

Output:

```<code>>>> print(list_of_cars)
[{'brand': 'Honda', 'model': 'CRV', 'year': 2010, 'color': 'Yellow'},
 {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'Red'},
 {'brand': 'Toyota', 'model': 'RAV4', 'year': 2015, 'color': 'Green'},
 {'brand': 'Ford', 'model': 'Transit', 'year': 1964, 'color': 'Black'},
 {'brand': 'Tesla', 'model': 'X', 'year': 2022, 'color': 'Blue'}]
</code>```

Body:
I am trying to sort the dictionary here:

car =   {
  "brand": ["Ford","Honda","Toyota","Tesla","Ford"],
  "model": ["Mustang","CRV","RAV4","X","Transit"],
  "year": [1964,2010,2015,2022,1964],
  "color": ["Red","Yellow","Green","Blue","Black"]
}

sortedbyval1={k: v for k, v in sorted(car.items(),key=lambda v:v[1])}

I keep getting error message like below. There is no < in the code!!!

TypeError: '<' not supported between instances of 'int' and 'str'

I am trying to sort the car dictionary by model, year, color etc.

If possible, by color AND year.

Body:
It doesn't work because you have a dictionary of a bunch of car attributes, not a collection of cars. That's why when you use key=lambda v:v[1], sorted is trying to compare lists that contain different types. For example, "year" only contains ints, yet you want to compare it with "brand" which contains strings, so you get the TypeError.

You could rework that dictionary to create a list of cars. Assuming the same index value corresponds to the same car, you can iterate over the zipped car.values() and create a list of dictionaries using the dict constructor where each dictionary is a car.

Then use list.sort where the sorting key is by model, year and color to sort the list of cars.

list_of_cars = [dict(zip(car.keys(), tpl)) for tpl in zip(*car.values())]
list_of_cars.sort(key=lambda car: (car['model'], car['year'], car['color']))

Output:

>>> print(list_of_cars)
[{'brand': 'Honda', 'model': 'CRV', 'year': 2010, 'color': 'Yellow'},
 {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'Red'},
 {'brand': 'Toyota', 'model': 'RAV4', 'year': 2015, 'color': 'Green'},
 {'brand': 'Ford', 'model': 'Transit', 'year': 1964, 'color': 'Black'},
 {'brand': 'Tesla', 'model': 'X', 'year': 2022, 'color': 'Blue'}]


来源: stackexchange

问:
Non-blocking reading from the file using Reactor
Do you know if it's possible to create Flux of file lines really non-blocking way?

The best solution I've found is next:

```<code>Flux.using(
           () -> Files.lines(PATH),
           Flux::fromStream,
           Stream::close
 );
</code>```

Even though it looks non-blocking but it is blocking under the hood.

https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-java.nio.charset.Charset-

Read all lines from a file as a Stream. Unlike readAllLines, this
method does not read all lines into a List, but instead populates
lazily as the stream is consumed.

The returned stream encapsulates a Reader.

Is it possible to create Flux from AsynchronousFileChannel?

Thank you in advance

答:
If you have Spring Framework on classpath, then you can do the following:

import org.springframework.core.codec.StringDecoder;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;

import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class AsyncFileRead {
    public static void main(String[] args) {
        StringDecoder stringDecoder = StringDecoder.textPlainOnly();

        DataBufferUtils.readAsynchronousFileChannel(() -> AsynchronousFileChannel.open(Path.of("test/sample.txt"),
                StandardOpenOption.READ), DefaultDataBufferFactory.sharedInstance, 4096)
            .transform(dataBufferFlux -> stringDecoder.decode(dataBufferFlux, null, null, null))
            .blockLast();
    }
}
```
<p>Alternatively, you can use RxIo library which provides a nice abstraction similar to <code>java.nio.file.Files</code> just with async/reactive support:</p>
<pre class="lang-java prettyprint-override"><code>import org.javaync.io.AsyncFiles;
import reactor.core.publisher.Flux;

import java.nio.file.Path;

public class AsyncFileRead {
    public static void main(String[] args) {
        Flux.from(AsyncFiles.lines(Path.of("test/sample.txt")))
            .blockLast();
    }
}
</code>```

Although, it's important to note that even these solutions are not truly non-blocking as depending on the platform (Windows, Linux) AsynchronousFileChannel implementation can be blocking under the hood but at least it delegates that task to a dedicated thread pool.

ContentLicense: CC BY-SA 4.0

Body:
Do you know if it's possible to create Flux of file lines really non-blocking way?

The best solution I've found is next:

Flux.using(
           () -> Files.lines(PATH),
           Flux::fromStream,
           Stream::close
 );

Even though it looks non-blocking but it is blocking under the hood.

https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-java.nio.charset.Charset-

Read all lines from a file as a Stream. Unlike readAllLines, this
method does not read all lines into a List, but instead populates
lazily as the stream is consumed.

The returned stream encapsulates a Reader.

Is it possible to create Flux from AsynchronousFileChannel?

Thank you in advance

Body:
If you have Spring Framework on classpath, then you can do the following:

import org.springframework.core.codec.StringDecoder;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;

import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class AsyncFileRead {
    public static void main(String[] args) {
        StringDecoder stringDecoder = StringDecoder.textPlainOnly();

        DataBufferUtils.readAsynchronousFileChannel(() -> AsynchronousFileChannel.open(Path.of("test/sample.txt"),
                StandardOpenOption.READ), DefaultDataBufferFactory.sharedInstance, 4096)
            .transform(dataBufferFlux -> stringDecoder.decode(dataBufferFlux, null, null, null))
            .blockLast();
    }
}

Alternatively, you can use RxIo library which provides a nice abstraction similar to java.nio.file.Files just with async/reactive support:

import org.javaync.io.AsyncFiles;
import reactor.core.publisher.Flux;

import java.nio.file.Path;

public class AsyncFileRead {
    public static void main(String[] args) {
        Flux.from(AsyncFiles.lines(Path.of("test/sample.txt")))
            .blockLast();
    }
}

Although, it's important to note that even these solutions are not truly non-blocking as depending on the platform (Windows, Linux) AsynchronousFileChannel implementation can be blocking under the hood but at least it delegates that task to a dedicated thread pool.


问:
React rsuite reset select box value
I have rsuite SelectBox, I want to reset its value from outside.  when I set it to null or undefined or empty string, it doesnt work.

I read the source code, I get the felling that it is by design, only when you use it as part of a form. but this complicate things.
Do you see any possible way to reset the combo value without creating a form?

https://codesandbox.io/s/select-picker-types-forked-ivjn8?file=/src/App.tsx:164-477

```<code>export default function App() {
  const [value, setValue] = useState<string | undefined>();

  return (
    <>
      <SelectPicker
        data={[{ label: "test", value: "test" }]}
        value={value}
        onChange={setValue}
      />
      <button onClick={() => setValue("")}>reset</button>
    </>
  );
}
</code>```

Thanks

答:
I know it's not so sweet and I have no idea what props this one takes, but you could unmount/mount it completely on button click.</p>
```<code>import { useState, useEffect } from "react";
import { SelectPicker, Button } from "rsuite";
import "./styles.css";
import "rsuite/dist/styles/rsuite-default.css";

export default function App() {
  const [value, setValue] = useState<string | undefined>("");
  const [down, setDown] = useState(false);

  useEffect(() => {
    setValue("");
    console.log(down);
  }, [down]);

  return (
    <>
      {!down ? (
        <SelectPicker
          data={[{ label: "test", value: "test" }]}
          value={value}
          onChange={setValue}
        />
      ) : (
        <SelectPicker value={""} />
      )}
      <br />
      <br />
      <button
        onMouseUp={() => setDown(false)}
        onMouseDown={() => setDown(true)}
      >
        reset
      </button>
    </>
  );
}
</code>```

Title: React rsuite reset select box value

Body:
I have rsuite SelectBox, I want to reset its value from outside.  when I set it to null or undefined or empty string, it doesnt work.

I read the source code, I get the felling that it is by design, only when you use it as part of a form. but this complicate things.
Do you see any possible way to reset the combo value without creating a form?

https://codesandbox.io/s/select-picker-types-forked-ivjn8?file=/src/App.tsx:164-477

export default function App() {
  const [value, setValue] = useState<string | undefined>();

  return (
    <>
      <SelectPicker
        data={[{ label: "test", value: "test" }]}
        value={value}
        onChange={setValue}
      />
      <button onClick={() => setValue("")}>reset</button>
    </>
  );
}

Thanks

Body:
I know it's not so sweet and I have no idea what props this one takes, but you could unmount/mount it completely on button click.

import { useState, useEffect } from "react";
import { SelectPicker, Button } from "rsuite";
import "./styles.css";
import "rsuite/dist/styles/rsuite-default.css";

export default function App() {
  const [value, setValue] = useState<string | undefined>("");
  const [down, setDown] = useState(false);

  useEffect(() => {
    setValue("");
    console.log(down);
  }, [down]);

  return (
    <>
      {!down ? (
        <SelectPicker
          data={[{ label: "test", value: "test" }]}
          value={value}
          onChange={setValue}
        />
      ) : (
        <SelectPicker value={""} />
      )}
      <br />
      <br />
      <button
        onMouseUp={() => setDown(false)}
        onMouseDown={() => setDown(true)}
      >
        reset
      </button>
    </>
  );
}


问:
How can I frequently/automatically compare the structure of the same Database?
Does anyone know a tool that automatically compares the structure of a database and gives a report of what was changed?  If it can be integrated into a CruiseControl, even better.

By structure I also mean functions and stored procedures. Which is probably not clear at first sight ;-)

The idea was to integrate that into a cruise control server

答: SQL Effects Clarity is very good at comparing two Databases, and it's free (it has a paid version that allows you to do a bit more as well)</p>

OwnerDisplayName: Fatboss

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eddie


问:
Sharing link for my website
I wish to have a sharing bar like in this page. http://www.templatebasics.com/wt00784bl/

How to make a sharing tab like this ?

I found that shareaholic is available only for blogs ? So, can I implement it on my website ??

Thanks in advance :)

答: You can use something like Apture, seems to provide the same service :-) Picture of the bar here.</p>

ContentLicense: CC BY-SA 3.0

Title: Sharing link for my website


问:
How do i stop pause a task in c# .net
I have tried but it is not working i want to stop and pause this task:: code below

```<code>private void checkingTimer()
        {
            System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(startPollingAwaitingURLs);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000);
            dispatcherTimer.Start();
        }

        private static object _lock_CrawlingSync = new object();
        private static bool blBeingProcessed = false;
        private static List<Task> lstCrawlingTasks = new List<Task>();
        private static List<string> lstCurrentlyCrawlingUrls = new List<string>();
        private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            using (WebCrawlerEntities1 db = new WebCrawlerEntities1())
            {
                db.tblMainUrls.RemoveRange(db.tblMainUrls);
                db.SaveChanges();
            }
        }

        private void clearDBandStart(object sender, RoutedEventArgs e)
        {
            dtStartDate = DateTime.Now;

            crawlPage(urlTextbox.Text.normalizeUrl(), 0, urlTextbox.Text.normalizeUrl(), DateTime.Now);
            checkingTimer();
        }

        private void startPollingAwaitingURLs(object sender, EventArgs e)
        {
            lock (UserLogs)
            {
                string srPerMinCrawlingspeed = (irCrawledUrlCount.ToDouble() / (DateTime.Now - dtStartDate).TotalMinutes).ToString("N2");

                string srPerMinDiscoveredLinkSpeed = (irDiscoveredUrlCount.ToDouble() / (DateTime.Now - dtStartDate).TotalMinutes).ToString("N2");

                string srPassedTime = (DateTime.Now - dtStartDate).TotalMinutes.ToString("N2");

                UserLogs.Insert(0, $"{DateTime.Now} polling awaiting urls \t processing: {blBeingProcessed} \t number of crawling tasks: {lstCrawlingTasks.Count}");

                UserLogs.Insert(0, $"Total Time: {srPassedTime} Minutes \t Total Crawled Links Count: {irCrawledUrlCount.ToString("N0")} \t Crawling Speed Per Minute: {srPerMinCrawlingspeed} \t Total Discovered Links : {irDiscoveredUrlCount.ToString("N0")} \t Discovered Url Speed: {srPerMinDiscoveredLinkSpeed} ");
            }

            logMesssage($"polling awaiting urls \t processing: {blBeingProcessed} \t number of crawling tasks: {lstCrawlingTasks.Count}");

            if (blBeingProcessed)
                return;

            lock (_lock_CrawlingSync)
            {

                blBeingProcessed = true;

                lstCrawlingTasks = lstCrawlingTasks.Where(pr => pr.Status != TaskStatus.RanToCompletion && pr.Status != TaskStatus.Faulted).ToList();

                int irTasksCountToStart = _irNumberOfTotalConcurrentCrawling - lstCrawlingTasks.Count;

                if (irTasksCountToStart > 0)
                    using (WebCrawlerEntities1 db = new WebCrawlerEntities1())
                    {
                        var vrReturnedList = db.tblMainUrls.Where(x => x.isCrawled == false && x.CrawlTryCounter < _irMaximumTryCount)
                                  .OrderBy(pr => pr.DiscoverDate)
                            .Select(x => new
                            {
                                x.Url,
                                x.LinkDepthLevel
                            }).Take(irTasksCountToStart * 2).ToList();

                        logMesssage(string.Join(" , ", vrReturnedList.Select(pr => pr.Url)));

                        foreach (var vrPerReturned in vrReturnedList)
                        {
                            var vrUrlToCrawl = vrPerReturned.Url;
                            int irDepth = vrPerReturned.LinkDepthLevel;
                            lock (lstCurrentlyCrawlingUrls)
                            {
                                if (lstCurrentlyCrawlingUrls.Contains(vrUrlToCrawl))
                                {
                                    logMesssage($"bypass url since already crawling: \t {vrUrlToCrawl}");
                                    continue;
                                }
                                lstCurrentlyCrawlingUrls.Add(vrUrlToCrawl);
                            }

                            logMesssage($"starting crawling url: \t {vrUrlToCrawl}");

                            lock (UserLogs)
                            {
                                UserLogs.Insert(0, $"{DateTime.Now} starting crawling url: \t {vrUrlToCrawl}");
                            }

                            var vrStartedTask = Task.Factory.StartNew(() => { crawlPage(vrUrlToCrawl, irDepth, null, DateTime.MinValue); }).ContinueWith((pr) =>
                            {

                                lock (lstCurrentlyCrawlingUrls)
                                {
                                    lstCurrentlyCrawlingUrls.Remove(vrUrlToCrawl);
                                    logMesssage($"removing url from list since task completed: \t {vrUrlToCrawl}");
                                }

                            });
                            lstCrawlingTasks.Add(vrStartedTask);

                            if (lstCrawlingTasks.Count > _irNumberOfTotalConcurrentCrawling)
                                break;
                        }
                    }

                blBeingProcessed = false;
            }
        }
</code>```

so is there a way to stop my task up ahead and pause should i mre.set() or .Set()

my application is a web crawler that get links from any website.

so when pressing on a button web crawling task pause or stop and restart ... any methods to do or changes

答:
Technically you can't stop a Task. Task isn't running anything but only waiting for a completion of something it was bound for. You can stop the code, running in the Thread. For example, with ManualResetEventSlim.

private readonly ManualResetEventSlim _mre = new ManualResetEventSlim(true); // not paused initially

public void Pause()
{
    _mre.Reset();
}

public void Resume()
{
    _mre.Set();
}
```
<p>In the method where you want to pause the execution when requested, just add.</p>
```_mre.Wait();
```

Few tips

Use Task.Run instead of Task.Factory.StartNew and learn the difference.

Find something about Producer/Consumer programming pattern and related thread-safe collections.

Say hello to Asynchronous programming.

Title: How do i stop pause a task in c# .net

Body:
I have tried but it is not working i want to stop and pause this task:: code below

private void checkingTimer()
        {
            System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(startPollingAwaitingURLs);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000);
            dispatcherTimer.Start();
        }

        private static object _lock_CrawlingSync = new object();
        private static bool blBeingProcessed = false;
        private static List<Task> lstCrawlingTasks = new List<Task>();
        private static List<string> lstCurrentlyCrawlingUrls = new List<string>();
        private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            using (WebCrawlerEntities1 db = new WebCrawlerEntities1())
            {
                db.tblMainUrls.RemoveRange(db.tblMainUrls);
                db.SaveChanges();
            }
        }

        private void clearDBandStart(object sender, RoutedEventArgs e)
        {
            dtStartDate = DateTime.Now;

            crawlPage(urlTextbox.Text.normalizeUrl(), 0, urlTextbox.Text.normalizeUrl(), DateTime.Now);
            checkingTimer();
        }

        private void startPollingAwaitingURLs(object sender, EventArgs e)
        {
            lock (UserLogs)
            {
                string srPerMinCrawlingspeed = (irCrawledUrlCount.ToDouble() / (DateTime.Now - dtStartDate).TotalMinutes).ToString("N2");

                string srPerMinDiscoveredLinkSpeed = (irDiscoveredUrlCount.ToDouble() / (DateTime.Now - dtStartDate).TotalMinutes).ToString("N2");

                string srPassedTime = (DateTime.Now - dtStartDate).TotalMinutes.ToString("N2");

                UserLogs.Insert(0, $"{DateTime.Now} polling awaiting urls \t processing: {blBeingProcessed} \t number of crawling tasks: {lstCrawlingTasks.Count}");

                UserLogs.Insert(0, $"Total Time: {srPassedTime} Minutes \t Total Crawled Links Count: {irCrawledUrlCount.ToString("N0")} \t Crawling Speed Per Minute: {srPerMinCrawlingspeed} \t Total Discovered Links : {irDiscoveredUrlCount.ToString("N0")} \t Discovered Url Speed: {srPerMinDiscoveredLinkSpeed} ");
            }

            logMesssage($"polling awaiting urls \t processing: {blBeingProcessed} \t number of crawling tasks: {lstCrawlingTasks.Count}");

            if (blBeingProcessed)
                return;

            lock (_lock_CrawlingSync)
            {

                blBeingProcessed = true;

                lstCrawlingTasks = lstCrawlingTasks.Where(pr => pr.Status != TaskStatus.RanToCompletion && pr.Status != TaskStatus.Faulted).ToList();

                int irTasksCountToStart = _irNumberOfTotalConcurrentCrawling - lstCrawlingTasks.Count;

                if (irTasksCountToStart > 0)
                    using (WebCrawlerEntities1 db = new WebCrawlerEntities1())
                    {
                        var vrReturnedList = db.tblMainUrls.Where(x => x.isCrawled == false && x.CrawlTryCounter < _irMaximumTryCount)
                                  .OrderBy(pr => pr.DiscoverDate)
                            .Select(x => new
                            {
                                x.Url,
                                x.LinkDepthLevel
                            }).Take(irTasksCountToStart * 2).ToList();

                        logMesssage(string.Join(" , ", vrReturnedList.Select(pr => pr.Url)));

                        foreach (var vrPerReturned in vrReturnedList)
                        {
                            var vrUrlToCrawl = vrPerReturned.Url;
                            int irDepth = vrPerReturned.LinkDepthLevel;
                            lock (lstCurrentlyCrawlingUrls)
                            {
                                if (lstCurrentlyCrawlingUrls.Contains(vrUrlToCrawl))
                                {
                                    logMesssage($"bypass url since already crawling: \t {vrUrlToCrawl}");
                                    continue;
                                }
                                lstCurrentlyCrawlingUrls.Add(vrUrlToCrawl);
                            }

                            logMesssage($"starting crawling url: \t {vrUrlToCrawl}");

                            lock (UserLogs)
                            {
                                UserLogs.Insert(0, $"{DateTime.Now} starting crawling url: \t {vrUrlToCrawl}");
                            }

                            var vrStartedTask = Task.Factory.StartNew(() => { crawlPage(vrUrlToCrawl, irDepth, null, DateTime.MinValue); }).ContinueWith((pr) =>
                            {

                                lock (lstCurrentlyCrawlingUrls)
                                {
                                    lstCurrentlyCrawlingUrls.Remove(vrUrlToCrawl);
                                    logMesssage($"removing url from list since task completed: \t {vrUrlToCrawl}");
                                }

                            });
                            lstCrawlingTasks.Add(vrStartedTask);

                            if (lstCrawlingTasks.Count > _irNumberOfTotalConcurrentCrawling)
                                break;
                        }
                    }

                blBeingProcessed = false;
            }
        }

so is there a way to stop my task up ahead and pause should i mre.set() or .Set()

my application is a web crawler that get links from any website.

so when pressing on a button web crawling task pause or stop and restart ... any methods to do or changes

Body:
Technically you can't stop a Task. Task isn't running anything but only waiting for a completion of something it was bound for. You can stop the code, running in the Thread. For example, with ManualResetEventSlim.

private readonly ManualResetEventSlim _mre = new ManualResetEventSlim(true); // not paused initially

public void Pause()
{
    _mre.Reset();
}

public void Resume()
{
    _mre.Set();
}

In the method where you want to pause the execution when requested, just add.

_mre.Wait();

Few tips

Use Task.Run instead of Task.Factory.StartNew and learn the difference.

Find something about Producer/Consumer programming pattern and related thread-safe collections.

Say hello to Asynchronous programming.


问:
I'm on windows os, I'm trying to export the data from mysql workbench to my local file system. But showing an error message like (no disk space)
I've searched many threads online but none of them worked for me. I found solutions for linux but there is no solution related to windows operating system

ERROR: Export data to file: ("Error writing file 'C:\WINDOWS\SERVIC~1\NETWOR~1\AppData\Local\Temp\MYacdbk0zgsz0sy8wg' (OS errno 28 - No space left on device)", 3)

答:
If you need only the ddl-dml of some schema, maybe you can do it:</p>
```<code>1 - On Workbench. Select the Schema.
2 - Database -> Reverse Engineer(Ctrl + r)
3 - Next ... Select the Schema -> execute ... -> the result is a EER diagram.
4 - On EER diagram you do: Database -> Forwading Engineer
5 - Select:
    - Generate INSERT statmentes for tables
    - Disable FK checks for INSERTs
    - Generate DROP SCHEMA
    - Omit schema qualifer in object names
    - include model attached scripts
6 - Next ...
7 - Copy the script or download it.
</code>```

Body:
If you need only the ddl-dml of some schema, maybe you can do it:

1 - On Workbench. Select the Schema.
2 - Database -> Reverse Engineer(Ctrl + r)
3 - Next ... Select the Schema -> execute ... -> the result is a EER diagram.
4 - On EER diagram you do: Database -> Forwading Engineer
5 - Select:
    - Generate INSERT statmentes for tables
    - Disable FK checks for INSERTs
    - Generate DROP SCHEMA
    - Omit schema qualifer in object names
    - include model attached scripts
6 - Next ...
7 - Copy the script or download it.


问:
Extracting element from table using selenium web scraping
Using selenium I am trying to scrape a table from a website,
however, data appears compressed into one single column rather than two separate columns; Date and Value- help would be greatly appreciated - now amended to included further improvement

```<code>driver.get("https://www.multpl.com/shiller-pe/table/by-year/")

table_trs = driver.find_elements(By.XPATH, '//table[@id="datatable"]/tbody/tr')

value_list = []
for v in range(len(table_trs )):
    value_list.append(table_trs [v].text)

print(value_list)
df = pd.DataFrame(value_list)
</code>```

The table I am trying to scrape appears on the website as follows....

..and the section of html associated to it.....

答:
Something is missing here or you put wrong xpath.
Valid xpath will be (based on picture) "//div[@id="datatable"]/tbody/tr", but that will only give you the rows. You can iterate by getting the all row nubers and colums, something like //div[@id="datatable"]/tbody/tr[i]/td[j] and then get text fro each element.

Body:
Using selenium I am trying to scrape a table from a website,
however, data appears compressed into one single column rather than two separate columns; Date and Value- help would be greatly appreciated - now amended to included further improvement

driver.get("https://www.multpl.com/shiller-pe/table/by-year/")

table_trs = driver.find_elements(By.XPATH, '//table[@id="datatable"]/tbody/tr')

value_list = []
for v in range(len(table_trs )):
    value_list.append(table_trs [v].text)

print(value_list)
df = pd.DataFrame(value_list)

The table I am trying to scrape appears on the website as follows....

..and the section of html associated to it.....


问:
MongoDB - Count value occurrences for field
Document structure

```<code>{
"A": "1",
"B": "3",
"C": "0.000090213",
},
{
"A": "1",
"B": "3",
"C": "0.000037698",
},
{
"A": "2",
"B": "4",
"C": "0.00016664",
}
</code>```

I'm trying to get the count of value for specific fields with aggregation, desired result for A and B would be

```<code>A: { "1": 2, "2": 1}
B: { "3": 2, "4": 1}
</code>```

Any help is greatly appreciated.

答:
```<code> db.collection.aggregate([
 {
  $facet: {
  "A": [
    {
      $group: {
        _id: "$A",
        v: {
          $sum: 1
        }
      }
    }
   ],
  "B": [
    {
      $group: {
        _id: "$B",
        v: {
          $sum: 1
        }
      }
     }
   ]
  }
  },
  {
   $addFields: {
   A: {
    $map: {
      input: "$A",
      as: "a",
      in: {
        k: "$$a._id",
        v: "$$a.v"
      }
     }
    }
  }
 },
 {
   $addFields: {
     B: {
      $map: {
      input: "$B",
      as: "b",
      in: {
        k: "$$b._id",
        v: "$$b.v"
      }
     }
    }
   }
  },
 {
   $project: {
    A: {
       "$arrayToObject": "$A"
       },
    B: {
    "$arrayToObject": "$B"
       }
      }
     }
   ])
</code>```

Explained:

$group the desired keys in two separate pipes with $facet

$addFields to rename _id to k ( suitable for $arrayToObject )

$project the desired counts with $arrayToObject.

playground

Body:
Document structure

{
"A": "1",
"B": "3",
"C": "0.000090213",
},
{
"A": "1",
"B": "3",
"C": "0.000037698",
},
{
"A": "2",
"B": "4",
"C": "0.00016664",
}

I'm trying to get the count of value for specific fields with aggregation, desired result for A and B would be

A: { "1": 2, "2": 1}
B: { "3": 2, "4": 1}

Any help is greatly appreciated.

Body:
 db.collection.aggregate([
 {
  $facet: {
  "A": [
    {
      $group: {
        _id: "$A",
        v: {
          $sum: 1
        }
      }
    }
   ],
  "B": [
    {
      $group: {
        _id: "$B",
        v: {
          $sum: 1
        }
      }
     }
   ]
  }
  },
  {
   $addFields: {
   A: {
    $map: {
      input: "$A",
      as: "a",
      in: {
        k: "$$a._id",
        v: "$$a.v"
      }
     }
    }
  }
 },
 {
   $addFields: {
     B: {
      $map: {
      input: "$B",
      as: "b",
      in: {
        k: "$$b._id",
        v: "$$b.v"
      }
     }
    }
   }
  },
 {
   $project: {
    A: {
       "$arrayToObject": "$A"
       },
    B: {
    "$arrayToObject": "$B"
       }
      }
     }
   ])

Explained:

$group the desired keys in two separate pipes with $facet

$addFields to rename _id to k ( suitable for $arrayToObject )

$project the desired counts with $arrayToObject.

playground


问:
Calculate the number of vowels and consonants in a word
I want to calculate the number of vowels and consonants in a word in a shell script, but I'm not sure how I can run through the word. Can anyone help me?
What I so far have is:</p>

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

echo 'Give a word'

read word

case $word
in
        a*|e*|i*|o*|u*)
                vowels=&((klinker + 1 ))
        ;;
        *)
                consonants=&((medeklinker + 1 ))
        ;;
esac

echo $vowels
echo $consonants
</code>```

答:
just with bash:</p>

```<code>letters=${word//[^[:alpha:]]/}     # remove all whitespace, punctuation, etc
cnsnnts=${letters//[aeiou]/}       # remove vowels
num_consonents=${#cnsnnts}
num_vowels=$(( ${#letters} - $num_consonents ))
</code>```

Body:
I want to calculate the number of vowels and consonants in a word in a shell script, but I'm not sure how I can run through the word. Can anyone help me?
What I so far have is:

#!/bin/bash

echo 'Give a word'

read word

case $word
in
        a*|e*|i*|o*|u*)
                vowels=&((klinker + 1 ))
        ;;
        *)
                consonants=&((medeklinker + 1 ))
        ;;
esac

echo $vowels
echo $consonants

Body:
just with bash:

letters=${word//[^[:alpha:]]/}     # remove all whitespace, punctuation, etc
cnsnnts=${letters//[aeiou]/}       # remove vowels
num_consonents=${#cnsnnts}
num_vowels=$(( ${#letters} - $num_consonents ))


问:
JavaScript: search for multiple values in a string and return the match
If I have an array of words and a string. How could i do a simple search for the keywords, and then stop at the first hit, and return which keyword that mathed? It is certainly a simple solution but is a bit stuck on the problem.</p>

答:
If you only need the first match you can break out
of the loop over the array with break:

```<code>array = ["red", "green", "blue"];
string = "little red riding hood brought green peppers";

found = false;
for( word of array) {
  if(string.indexOf(word) > -1) {
    found=word;
    break;
  }
}

if(found) {
  console.log("I found the word", found);
} else {
  console.log("non of the words were found);
}
</code>```

Body:
If you only need the first match you can break out
of the loop over the array with break:

array = ["red", "green", "blue"];
string = "little red riding hood brought green peppers";

found = false;
for( word of array) {
  if(string.indexOf(word) > -1) {
    found=word;
    break;
  }
}

if(found) {
  console.log("I found the word", found);
} else {
  console.log("non of the words were found);
}


问:
how can i get the value of a variable outside the arrow function in mern stack
i want to get the value of this variable outside the function const custDetail = await registeredUser.findOne(req.params);

```<code>const dashboardReq = async (req, res, next) => {
      try {
        const regCust = await registeredUser.findOne({ mobile: req.params.mobile });

    if (regCust == null) {
      console.log("No user found");
    } else {
      const custDetail = await registeredUser.findOne(req.params);
    }
    res.status(201).json({
      status: "success",
      data: { regCust },
    });
  } catch (error) {
    res.status(400).json({
      status: "fail",
      data: next(error),
    });
  }
};
</code>```

答:
try to revisit your design since the variable custDetail needs to exist inside the route itself

if this is supposed to be memoized, then maintain a map with some unique identifier from req.params with the result from registeredUser.findOne

Body:
i want to get the value of this variable outside the function const custDetail = await registeredUser.findOne(req.params);

const dashboardReq = async (req, res, next) => {
      try {
        const regCust = await registeredUser.findOne({ mobile: req.params.mobile });

    if (regCust == null) {
      console.log("No user found");
    } else {
      const custDetail = await registeredUser.findOne(req.params);
    }
    res.status(201).json({
      status: "success",
      data: { regCust },
    });
  } catch (error) {
    res.status(400).json({
      status: "fail",
      data: next(error),
    });
  }
};


问:
Convert strings A1.B1.C1+A1.B2+C1 to A1.B1+B2.C1
I would like to convert this v_in string into this v_out in R:

```<code>v_in <- 'A1.B1.C1+A1.B2.C1+A1.B2.C2'
v_out<-'A1.B1+B2.C1+C2'
</code>```

Another example:

```<code>v_in <- 'A1.B1.C1+A2.B1.C1+A3.B1.C1'
v_out <- 'A1+A2+A3.B1.C1'
</code>```

Here other examples:

```<code>in<-'FRA.UNR.A+DEU.UNR.A'
out<-'FRA+DEU.UNR.A'
</code>```
```<code>in<-'FRA.UNR.A+DEU.UNR.A+ITA.GDP.A'
out<-'FRA+DEU+ITA.UNR+GDP.A'
</code>```
```<code>in<-'FRA.UNR.A+FRA.GDP.Q'
out<-'FRA.UNR+GDP.A+Q'
</code>```
```<code>in<-'A.B.C+A.D.E+A.D.F+G.H.I'
out<-'A+G.B+D+H.C+E+F+I'
</code>```

The input pattern is:
S1+S2+S3  (where S1 is A.B.C, and same thing for S1 and S3)

The output should be:
X.Y.Z (where X is unique A codes (separate by+), Y: unique B codes (separate by+), and same thing for Z)

答:
Here is a solution:

In BASE R:

```<code>my_fun <- function(v){
  sapply(strsplit(v, '[+]'),
     function(x)
      do.call(paste, aggregate(.~sep, cbind(read.table(text=x, sep='.'), sep ='.'),
                   function(y)paste(unique(y), collapse = '+'))))
}

my_fun(v_in)
[1] "A1.B1+B2.C1+C2"        "A1+A2+A3.B1.C1"        "FRA+DEU.UNR.A"
[4] "FRA+DEU+ITA.UNR+GDP.A" "FRA.UNR+GDP.A+Q"
</code>```

In tidyverse:

```<code>library(tidyverse)
data.frame(v_in, id = v_in) %>%
  separate_rows(id, sep='[+]') %>%
  separate(id, c('COUNTRY', 'VARIABLE', 'FREQUENCY')) %>%
  group_by(v_in) %>%
  summarise(across(everything(), ~paste0(unique(.x), collapse = '+')))%>%
  unite(v_out,-v_in, sep='.')

v_in                          v_out
  <chr>                         <chr>
1 A1.B1.C1+A1.B2.C1+A1.B2.C2    A1.B1+B2.C1+C2
2 A1.B1.C1+A2.B1.C1+A3.B1.C1    A1+A2+A3.B1.C1
3 FRA.UNR.A+DEU.UNR.A           FRA+DEU.UNR.A
4 FRA.UNR.A+DEU.UNR.A+ITA.GDP.A FRA+DEU+ITA.UNR+GDP.A
5 FRA.UNR.A+FRA.GDP.Q           FRA.UNR+GDP.A+Q
</code>```

DATA:

```<code>v_in <- c("A1.B1.C1+A1.B2.C1+A1.B2.C2", "A1.B1.C1+A2.B1.C1+A3.B1.C1",
"FRA.UNR.A+DEU.UNR.A", "FRA.UNR.A+DEU.UNR.A+ITA.GDP.A", "FRA.UNR.A+FRA.GDP.Q")

</code>```

Body:
I would like to convert this v_in string into this v_out in R:

v_in <- 'A1.B1.C1+A1.B2.C1+A1.B2.C2'
v_out<-'A1.B1+B2.C1+C2'

Another example:

v_in <- 'A1.B1.C1+A2.B1.C1+A3.B1.C1'
v_out <- 'A1+A2+A3.B1.C1'

Here other examples:

in<-'FRA.UNR.A+DEU.UNR.A'
out<-'FRA+DEU.UNR.A'

in<-'FRA.UNR.A+DEU.UNR.A+ITA.GDP.A'
out<-'FRA+DEU+ITA.UNR+GDP.A'

in<-'FRA.UNR.A+FRA.GDP.Q'
out<-'FRA.UNR+GDP.A+Q'

in<-'A.B.C+A.D.E+A.D.F+G.H.I'
out<-'A+G.B+D+H.C+E+F+I'

The input pattern is:
S1+S2+S3  (where S1 is A.B.C, and same thing for S1 and S3)

The output should be:
X.Y.Z (where X is unique A codes (separate by+), Y: unique B codes (separate by+), and same thing for Z)

Body:
Here is a solution:

In BASE R:

my_fun <- function(v){
  sapply(strsplit(v, '[+]'),
     function(x)
      do.call(paste, aggregate(.~sep, cbind(read.table(text=x, sep='.'), sep ='.'),
                   function(y)paste(unique(y), collapse = '+'))))
}

my_fun(v_in)
[1] "A1.B1+B2.C1+C2"        "A1+A2+A3.B1.C1"        "FRA+DEU.UNR.A"
[4] "FRA+DEU+ITA.UNR+GDP.A" "FRA.UNR+GDP.A+Q"

In tidyverse:

library(tidyverse)
data.frame(v_in, id = v_in) %>%
  separate_rows(id, sep='[+]') %>%
  separate(id, c('COUNTRY', 'VARIABLE', 'FREQUENCY')) %>%
  group_by(v_in) %>%
  summarise(across(everything(), ~paste0(unique(.x), collapse = '+')))%>%
  unite(v_out,-v_in, sep='.')

v_in                          v_out
  <chr>                         <chr>
1 A1.B1.C1+A1.B2.C1+A1.B2.C2    A1.B1+B2.C1+C2
2 A1.B1.C1+A2.B1.C1+A3.B1.C1    A1+A2+A3.B1.C1
3 FRA.UNR.A+DEU.UNR.A           FRA+DEU.UNR.A
4 FRA.UNR.A+DEU.UNR.A+ITA.GDP.A FRA+DEU+ITA.UNR+GDP.A
5 FRA.UNR.A+FRA.GDP.Q           FRA.UNR+GDP.A+Q

DATA:

v_in <- c("A1.B1.C1+A1.B2.C1+A1.B2.C2", "A1.B1.C1+A2.B1.C1+A3.B1.C1",
"FRA.UNR.A+DEU.UNR.A", "FRA.UNR.A+DEU.UNR.A+ITA.GDP.A", "FRA.UNR.A+FRA.GDP.Q")


问:
Divide cell by the number of people
Guys I have little problem. I have output from other system to google spreadsheet.

I need to make a worksheet so that all data from this cell is divided into separate rows and the number next to it (D4) divided by the number of separate persons (a = first person, b=2nd person etc) (C4).

So far I have this script (other topic from stack ) -> Split comma delimited cell into multiple rows, keeping row details

```<code>/**
 * Splits the array by commas in the column with given index, by given delimiter
 * @param {A2:B20}  range Range reference
 * @param {2}  colToSplit Column index
 * @param {","}  delimiter Character by which to split
 * @customfunction
 */

function advancedSplit(range, colToSplit, delimiter) {
    var resArr = [], row;
    range.forEach(function (r) {
        r[colToSplit-1].toString().split(delimiter)
            .forEach(function (s) {

                row = [];
                r.forEach(function (c, k) {
                    row.push( (k === colToSplit-1) ? s.trim() : c);
                })
                resArr.push(row);

            })

    })

    return resArr.filter(function (r) {
        return r.toString()

    })

}
</code>```

The problem with dividing a cell by ";" is solved, but not with dividing a cell with a number of persons (phrases)

Sample:

cell A1 contains {a,b,c,d,e,f} and B2 1000

output:
a 200
b 200
c 200
d 200
e 200
f 200

This is dynamic data with 1000+ rows. An appscript should be used in this case

答:
This is not intended to be a cell function but as a standard function it provides the desired output.

```<code>function myfunk() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  const osh = ss.getSheetByName('Sheet1');
  const vs = sh.getRange(2,1,2,4).getValues();
  let a = [];
  vs.forEach((r,i) => {
    let c2 = r[2].toString().split(",");
    c2.forEach(e => {
      a.push([r[0],r[1],e,r[3]/c2.length]);
    });
  });
  osh.clearContents();
  osh.getRange(2,1,a.length,a[0].length).setValues(a);
}
</code>```

input:

data1
data2
a,b,c,d,e
1000

data3
data4
f,g,h,i
2000

output:

A
B
C
D

data1
data2
a
200

data1
data2
b
200

data1
data2
c
200

data1
data2
d
200

data1
data2
e
200

data3
data4
f
500

data3
data4
g
500

data3
data4
h
500

data3
data4
i
500

Try it this way for more rows and columns

```<code>function myfunk() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  const osh = ss.getSheetByName('Sheet1');
  const vs = sh.getRange(2,1,sh.getLastRow() - 1,sh.getLastColumn()).getValues();//gets the entire column
  let a = [];
  vs.forEach((r,i) => {
    let c2 = r[2].toString().split(",");
    c2.forEach(e => {
      let row = r.slice();//keeps each element of the output array independent
      row.splice(2,2,e,row[3]/c2.length);//replace elements 2 and 3
      a.push(row);
    });
  });
  osh.clearContents();
  osh.getRange(2,1,a.length,a[0].length).setValues(a);
}
</code>```

Title: Divide cell by the number of people

Body:
Guys I have little problem. I have output from other system to google spreadsheet.

I need to make a worksheet so that all data from this cell is divided into separate rows and the number next to it (D4) divided by the number of separate persons (a = first person, b=2nd person etc) (C4).

So far I have this script (other topic from stack ) -> Split comma delimited cell into multiple rows, keeping row details

/**
 * Splits the array by commas in the column with given index, by given delimiter
 * @param {A2:B20}  range Range reference
 * @param {2}  colToSplit Column index
 * @param {","}  delimiter Character by which to split
 * @customfunction
 */

function advancedSplit(range, colToSplit, delimiter) {
    var resArr = [], row;
    range.forEach(function (r) {
        r[colToSplit-1].toString().split(delimiter)
            .forEach(function (s) {

                row = [];
                r.forEach(function (c, k) {
                    row.push( (k === colToSplit-1) ? s.trim() : c);
                })
                resArr.push(row);

            })

    })

    return resArr.filter(function (r) {
        return r.toString()

    })

}

The problem with dividing a cell by ";" is solved, but not with dividing a cell with a number of persons (phrases)

Sample:

cell A1 contains {a,b,c,d,e,f} and B2 1000

output:
a 200
b 200
c 200
d 200
e 200
f 200

This is dynamic data with 1000+ rows. An appscript should be used in this case

Body:
This is not intended to be a cell function but as a standard function it provides the desired output.

function myfunk() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  const osh = ss.getSheetByName('Sheet1');
  const vs = sh.getRange(2,1,2,4).getValues();
  let a = [];
  vs.forEach((r,i) => {
    let c2 = r[2].toString().split(",");
    c2.forEach(e => {
      a.push([r[0],r[1],e,r[3]/c2.length]);
    });
  });
  osh.clearContents();
  osh.getRange(2,1,a.length,a[0].length).setValues(a);
}

input:

data1
data2
a,b,c,d,e
1000

data3
data4
f,g,h,i
2000

output:

A
B
C
D

data1
data2
a
200

data1
data2
b
200

data1
data2
c
200

data1
data2
d
200

data1
data2
e
200

data3
data4
f
500

data3
data4
g
500

data3
data4
h
500

data3
data4
i
500

Try it this way for more rows and columns

function myfunk() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  const osh = ss.getSheetByName('Sheet1');
  const vs = sh.getRange(2,1,sh.getLastRow() - 1,sh.getLastColumn()).getValues();//gets the entire column
  let a = [];
  vs.forEach((r,i) => {
    let c2 = r[2].toString().split(",");
    c2.forEach(e => {
      let row = r.slice();//keeps each element of the output array independent
      row.splice(2,2,e,row[3]/c2.length);//replace elements 2 and 3
      a.push(row);
    });
  });
  osh.clearContents();
  osh.getRange(2,1,a.length,a[0].length).setValues(a);
}


问:
how to programmatically show and hide action bar on one activity
i got this one activity wherein i need to hide actionbar on the login interface then once login it will show the action bar.i got one activity only. if i put getActionBar on the main activity it gives me error.

heres the code:

```<code>@SuppressLint("NewApi")
public class MainActivity extends Activity {

ViewPager viewPager;
PagerAdapter adapter;
ProgressDialog pDialog;
ImageView imgLogo;
Menu menu1;

ImageView header;
ImageView footer;

int[] bookCover = new int[] {

                    R.drawable.image1,
                    R.drawable.image2,
                    R.drawable.image3,

                    };

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setupFacebookConnect(savedInstanceState);

    imgLogo = (ImageView)findViewById(R.id.logo);
    share = (ImageView) findViewById(R.id.share);

    // Locate the ViewPager in viewpager_main.xml
    viewPager = (ViewPager) findViewById(R.id.pager);
    // Pass results to ViewPagerAdapter Class
    adapter = new ViewPagerAdapter(this, bookCover);
    // Binds the Adapter to the ViewPager
    viewPager.setAdapter(adapter);

    final OnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {

        @SuppressLint("NewApi")
        @Override
        public void onPageSelected(int position) {

            final int pos = position;
            share.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    switch(pos) {
                    case 0:

                        break;
                    case 1:

                        break;
                    case 2:

                        break;
                    case 3:

                        break;

                    }

                }
            });
         // When changing pages, reset the action bar actions since they are dependent
         // on which page is currently active. An alternative approach is to have each
         // fragment expose actions itself (rather than the activity exposing actions),
         // but for simplicity, the activity provides the actions in this sample.
        invalidateOptionsMenu();

        }

    };
    viewPager.setOnPageChangeListener(pageChangeListener);
    pageChangeListener.onPageSelected(0);

    facebook_connect = (Button) findViewById(R.id.facebook_login);
    facebook_connect.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if (isFacebookConnected()) {
                disConnectFacebook();
            } else {
                connectFacebook();
            }

        }
    });

    // Shared Preferences
    mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);

}

 @SuppressLint({ "InlinedApi", "NewApi" })
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        this.menu1 = menu;

        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.main, menu);

        menu.findItem(R.id.action_previous).setEnabled(viewPager.getCurrentItem() > 0);

        // Add either a "next" or "finish" button to the action bar, depending on which page
        // is currently selected.
        MenuItem item = menu.add(Menu.NONE, R.id.action_next, Menu.NONE,(viewPager.getCurrentItem() == adapter.getCount() - 1)
                        ? R.string.action_finish
                        : R.string.action_next);

        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int itemId = item.getItemId();
        if (itemId == R.id.action_previous) {
            // Go to the previous step in the wizard. If there is no previous step,
            // setCurrentItem will do nothing.
            viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
            return true;
        } else if (itemId == R.id.action_next) {
            // Advance to the next step0.0 in the wizard. If there is no next step, setCurrentItem
            // will do nothing.
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

private Session.StatusCallback statusCallback = new FBSessionStatus();

public void setupFacebookConnect(Bundle savedInstanceState) {
    Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

    Session session = Session.getActiveSession();
    if (session == null) {
        if (savedInstanceState != null) {
            session = Session.restoreSession(this, null, statusCallback,
                    savedInstanceState);
        }
        if (session == null) {
            session = new Session(this);
        }
        Session.setActiveSession(session);
        if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
            session.openForRead(new Session.OpenRequest(this)
                    .setCallback(statusCallback));
        }
    }
}

public boolean isFacebookConnected() {
    Session session = Session.getActiveSession();
    return (session.isOpened()) ? true  : false;

}

public void connectFacebook() {
    Session session = Session.getActiveSession();
    if (!session.isOpened() && !session.isClosed()) {
        getActionBar().show();
        session.openForRead(new Session.OpenRequest(this)
                .setCallback(statusCallback));
    } else {
    Session.openActiveSession(this, true, statusCallback);

    }
}

@Override
public void onStart() {
    super.onStart();
    Session.getActiveSession().addCallback(statusCallback);
}

@Override
public void onStop() {
    super.onStop();
    Session.getActiveSession().removeCallback(statusCallback);
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    Session session = Session.getActiveSession();
    Session.saveSession(session, outState);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Session.getActiveSession().onActivityResult(this, requestCode,
            resultCode, data);
}

public class FBSessionStatus implements Session.StatusCallback {
     @Override
        public void call(Session session, SessionState state, Exception exception) {
            onSessionStateChange(session, state, exception);
        }
}

public void disConnectFacebook() {
    Session session = Session.getActiveSession();
    if (!session.isClosed()) {
        session.closeAndClearTokenInformation();
        viewPager.setVisibility(View.INVISIBLE);
        MenuItem item1 = menu1.findItem(R.id.action_next);
        item1.setVisible(false);
        MenuItem item2 = menu1.findItem(R.id.action_previous);
        item2.setVisible(false);

        imgLogo.setVisibility(View.VISIBLE);
        //btnLoginTwitter.setVisibility(View.VISIBLE);

        share.setVisibility(View.INVISIBLE);

    }

}

private void onSessionStateChange(Session session, SessionState state, Exception exception) {
        // Check if the user is authenticated and
        // a deep link needs to be handled.
        if (state.isOpened()) {

            MenuItem item1 = menu1.findItem(R.id.action_next);
            item1.setVisible(true);
            MenuItem item2 = menu1.findItem(R.id.action_previous);
            item2.setVisible(true);
            //getActionBar().show();

            share.setVisibility(View.VISIBLE);

            //btnLoginTwitter.setVisibility(View.INVISIBLE);
            //btnShare.setVisibility(View.VISIBLE);

            viewPager.setVisibility(View.VISIBLE);

            imgLogo.setVisibility(View.INVISIBLE);

        }
    }

public void shareImage(String name, String caption, String desc, String link, String picture ) {

    Bundle params = new Bundle();
    params.putString("name", name);
    params.putString("caption", caption);
    params.putString("description", desc);
    params.putString("link", link);
    //params.putString("picture", "https://www.facebook.com/photo.php?fbid=10203610233686079&set=a.10203610230766006.1073741829.1523023247&type=1&theater");
    params.putString("picture", picture);

    WebDialog feedDialog = (
        new WebDialog.FeedDialogBuilder(MainActivity.this,
            Session.getActiveSession(),
            params))
        .setOnCompleteListener(new OnCompleteListener() {

            @Override
            public void onComplete(Bundle values,
                FacebookException error) {
                if (error == null) {
                    // When the story is posted, echo the success
                    // and the post Id.
                    final String postId = values.getString("post_id");
                    if (postId != null) {
                        Toast.makeText(MainActivity.this,
                            "Successfuly posted!",
                            Toast.LENGTH_SHORT).show();
                    } else {
                        // User clicked the Cancel button
                        Toast.makeText(MainActivity.this,
                            "Publish cancelled",
                            Toast.LENGTH_SHORT).show();
                    }
                } else if (error instanceof FacebookOperationCanceledException) {
                    // User clicked the "x" button
                    Toast.makeText(MainActivity.this,
                        "Publish cancelled",
                        Toast.LENGTH_SHORT).show();
                } else {
                    // Generic, ex: network error
                    Toast.makeText(MainActivity.this,
                        "Error posting story",
                        Toast.LENGTH_SHORT).show();
                }
            }

        })
        .build();
        feedDialog.show();

    }

    @SuppressWarnings("unused")
    private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
        for (String string : subset) {
            if (!superset.contains(string)) {
                return false;
            }
        }
        return true;
     }

}
</code>```

答:
For Activity

```<code>getActionBar().show();
getActionBar().hide();
</code>```

For AppCompatActivity

```<code>getSupportActionBar().show();
getSupportActionBar().hide();
</code>```

For Fragments

```<code>getActivity().getActionbar().show();
getActivity().getActionbar().hide();
</code>```

Body:
i got this one activity wherein i need to hide actionbar on the login interface then once login it will show the action bar.i got one activity only. if i put getActionBar on the main activity it gives me error.

heres the code:

@SuppressLint("NewApi")
public class MainActivity extends Activity {

ViewPager viewPager;
PagerAdapter adapter;
ProgressDialog pDialog;
ImageView imgLogo;
Menu menu1;

ImageView header;
ImageView footer;

int[] bookCover = new int[] {

                    R.drawable.image1,
                    R.drawable.image2,
                    R.drawable.image3,

                    };

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setupFacebookConnect(savedInstanceState);

    imgLogo = (ImageView)findViewById(R.id.logo);
    share = (ImageView) findViewById(R.id.share);

    // Locate the ViewPager in viewpager_main.xml
    viewPager = (ViewPager) findViewById(R.id.pager);
    // Pass results to ViewPagerAdapter Class
    adapter = new ViewPagerAdapter(this, bookCover);
    // Binds the Adapter to the ViewPager
    viewPager.setAdapter(adapter);

    final OnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {

        @SuppressLint("NewApi")
        @Override
        public void onPageSelected(int position) {

            final int pos = position;
            share.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    switch(pos) {
                    case 0:

                        break;
                    case 1:

                        break;
                    case 2:

                        break;
                    case 3:

                        break;

                    }

                }
            });
         // When changing pages, reset the action bar actions since they are dependent
         // on which page is currently active. An alternative approach is to have each
         // fragment expose actions itself (rather than the activity exposing actions),
         // but for simplicity, the activity provides the actions in this sample.
        invalidateOptionsMenu();

        }

    };
    viewPager.setOnPageChangeListener(pageChangeListener);
    pageChangeListener.onPageSelected(0);

    facebook_connect = (Button) findViewById(R.id.facebook_login);
    facebook_connect.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if (isFacebookConnected()) {
                disConnectFacebook();
            } else {
                connectFacebook();
            }

        }
    });

    // Shared Preferences
    mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);

}

 @SuppressLint({ "InlinedApi", "NewApi" })
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        this.menu1 = menu;

        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.main, menu);

        menu.findItem(R.id.action_previous).setEnabled(viewPager.getCurrentItem() > 0);

        // Add either a "next" or "finish" button to the action bar, depending on which page
        // is currently selected.
        MenuItem item = menu.add(Menu.NONE, R.id.action_next, Menu.NONE,(viewPager.getCurrentItem() == adapter.getCount() - 1)
                        ? R.string.action_finish
                        : R.string.action_next);

        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int itemId = item.getItemId();
        if (itemId == R.id.action_previous) {
            // Go to the previous step in the wizard. If there is no previous step,
            // setCurrentItem will do nothing.
            viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
            return true;
        } else if (itemId == R.id.action_next) {
            // Advance to the next step0.0 in the wizard. If there is no next step, setCurrentItem
            // will do nothing.
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

private Session.StatusCallback statusCallback = new FBSessionStatus();

public void setupFacebookConnect(Bundle savedInstanceState) {
    Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

    Session session = Session.getActiveSession();
    if (session == null) {
        if (savedInstanceState != null) {
            session = Session.restoreSession(this, null, statusCallback,
                    savedInstanceState);
        }
        if (session == null) {
            session = new Session(this);
        }
        Session.setActiveSession(session);
        if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
            session.openForRead(new Session.OpenRequest(this)
                    .setCallback(statusCallback));
        }
    }
}

public boolean isFacebookConnected() {
    Session session = Session.getActiveSession();
    return (session.isOpened()) ? true  : false;

}

public void connectFacebook() {
    Session session = Session.getActiveSession();
    if (!session.isOpened() && !session.isClosed()) {
        getActionBar().show();
        session.openForRead(new Session.OpenRequest(this)
                .setCallback(statusCallback));
    } else {
    Session.openActiveSession(this, true, statusCallback);

    }
}

@Override
public void onStart() {
    super.onStart();
    Session.getActiveSession().addCallback(statusCallback);
}

@Override
public void onStop() {
    super.onStop();
    Session.getActiveSession().removeCallback(statusCallback);
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    Session session = Session.getActiveSession();
    Session.saveSession(session, outState);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Session.getActiveSession().onActivityResult(this, requestCode,
            resultCode, data);
}

public class FBSessionStatus implements Session.StatusCallback {
     @Override
        public void call(Session session, SessionState state, Exception exception) {
            onSessionStateChange(session, state, exception);
        }
}

public void disConnectFacebook() {
    Session session = Session.getActiveSession();
    if (!session.isClosed()) {
        session.closeAndClearTokenInformation();
        viewPager.setVisibility(View.INVISIBLE);
        MenuItem item1 = menu1.findItem(R.id.action_next);
        item1.setVisible(false);
        MenuItem item2 = menu1.findItem(R.id.action_previous);
        item2.setVisible(false);

        imgLogo.setVisibility(View.VISIBLE);
        //btnLoginTwitter.setVisibility(View.VISIBLE);

        share.setVisibility(View.INVISIBLE);

    }

}

private void onSessionStateChange(Session session, SessionState state, Exception exception) {
        // Check if the user is authenticated and
        // a deep link needs to be handled.
        if (state.isOpened()) {

            MenuItem item1 = menu1.findItem(R.id.action_next);
            item1.setVisible(true);
            MenuItem item2 = menu1.findItem(R.id.action_previous);
            item2.setVisible(true);
            //getActionBar().show();

            share.setVisibility(View.VISIBLE);

            //btnLoginTwitter.setVisibility(View.INVISIBLE);
            //btnShare.setVisibility(View.VISIBLE);

            viewPager.setVisibility(View.VISIBLE);

            imgLogo.setVisibility(View.INVISIBLE);

        }
    }

public void shareImage(String name, String caption, String desc, String link, String picture ) {

    Bundle params = new Bundle();
    params.putString("name", name);
    params.putString("caption", caption);
    params.putString("description", desc);
    params.putString("link", link);
    //params.putString("picture", "https://www.facebook.com/photo.php?fbid=10203610233686079&set=a.10203610230766006.1073741829.1523023247&type=1&theater");
    params.putString("picture", picture);

    WebDialog feedDialog = (
        new WebDialog.FeedDialogBuilder(MainActivity.this,
            Session.getActiveSession(),
            params))
        .setOnCompleteListener(new OnCompleteListener() {

            @Override
            public void onComplete(Bundle values,
                FacebookException error) {
                if (error == null) {
                    // When the story is posted, echo the success
                    // and the post Id.
                    final String postId = values.getString("post_id");
                    if (postId != null) {
                        Toast.makeText(MainActivity.this,
                            "Successfuly posted!",
                            Toast.LENGTH_SHORT).show();
                    } else {
                        // User clicked the Cancel button
                        Toast.makeText(MainActivity.this,
                            "Publish cancelled",
                            Toast.LENGTH_SHORT).show();
                    }
                } else if (error instanceof FacebookOperationCanceledException) {
                    // User clicked the "x" button
                    Toast.makeText(MainActivity.this,
                        "Publish cancelled",
                        Toast.LENGTH_SHORT).show();
                } else {
                    // Generic, ex: network error
                    Toast.makeText(MainActivity.this,
                        "Error posting story",
                        Toast.LENGTH_SHORT).show();
                }
            }

        })
        .build();
        feedDialog.show();

    }

    @SuppressWarnings("unused")
    private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
        for (String string : subset) {
            if (!superset.contains(string)) {
                return false;
            }
        }
        return true;
     }

}

Body:
For Activity

getActionBar().show();
getActionBar().hide();

For AppCompatActivity

getSupportActionBar().show();
getSupportActionBar().hide();

For Fragments

getActivity().getActionbar().show();
getActivity().getActionbar().hide();


问:
FFmpeg - Converting AVI to MP4 (no audio in QuickTime player)
I converted an avi file to a mp4 file with the following command, but the converted mp4 file produced no audio when played with QuickTime (no such problem with other players). I was able to convert mkv to mp4 with the same command without the audio problem.

```<code>ffmpeg -i show.avi -vcodec libx264 -vprofile high -crf 28 -acodec copy show.mp4
</code>```

However I was able to fix the problem by the following two commands (first extract the audio into a mp3 file from the mp4 file, then combine the mp4 file with the mp3 file).

```<code>ffmpeg -i show.mp4 -vn -acodec libmp3lame -ac 2 -qscale:a 4 -ar 48000 show.mp3
ffmpeg -i show.mp4 -i show.mp3 show2.mp4
</code>```

show2.mp4 showed no audio problems with QuickTime. Anyone has any ideas as to what was wrong with the first command?

Below is my ffmpeg info.

```<code>% ffmpeg -i show.avi -vcodec libx264 -vprofile high -crf 28 -acodec copy show.mp4
ffmpeg version N-60236-gffb000fff8-static https://johnvansickle.com/ffmpeg/  \
Copyright (c) 2000-2022 the FFmpeg developers
built with gcc 8 (Debian 8.3.0-6)
configuration: --enable-gpl --enable-version3 --enable-static --disable-debug \
--disable-ffplay --disable-indev=sndio --disable-outdev=sndio \
--cc=gcc --enable-fontconfig --enable-frei0r --enable-gnutls \
--enable-gmp --enable-libgme --enable-gray --enable-libaom \
--enable-libfribidi --enable-libass --enable-libvmaf \
--enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb \
--enable-libopencore-amrwb --enable-libopenjpeg --enable-librubberband \
--enable-libsoxr --enable-libspeex --enable-libsrt --enable-libvorbis \
--enable-libopus --enable-libtheora --enable-libvidstab \
--enable-libvo-amrwbenc --enable-libvpx --enable-libwebp \
--enable-libx264 --enable-libx265 --enable-libxml2 \
--enable-libdav1d --enable-libxvid --enable-libzvbi --enable-libzimg
libavutil      57. 18.100 / 57. 18.100
libavcodec     59. 20.100 / 59. 20.100
libavformat    59. 17.100 / 59. 17.100
libavdevice    59.  5.100 / 59.  5.100
libavfilter     8. 25.100 /  8. 25.100
libswscale      6.  5.100 /  6.  5.100
libswresample   4.  4.100 /  4.  4.100
libpostproc    56.  4.100 / 56.  4.100
Input #0, avi, from 'show.avi':
  Metadata:
    software        : Nandub v1.0rc2
  Duration: 01:38:52.93, start: 0.000000, bitrate: 984 kb/s
  Stream #0:0: Video: msmpeg4v3 (DIV3 / 0x33564944), yuv420p, \
576x240, 842 kb/s, 23.98 fps, 23.98 tbr, 23.98 tbn
  Stream #0:1: Audio: mp3 (U[0][0][0] / 0x0055), 48000 Hz, stereo, fltp, 128 kb/s
Stream mapping:
  Stream #0:0 -> #0:0 (msmpeg4v3 (msmpeg4) -> h264 (libx264))
  Stream #0:1 -> #0:1 (copy)
Press [q] to stop, [?] for help
[libx264 @ 0x76824c0] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX
[libx264 @ 0x76824c0] profile High, level 2.1, 4:2:0, 8-bit
[libx264 @ 0x76824c0] 264 - core 164 r3081 19856cc - H.264/MPEG-4 \
AVC codec - Copyleft 2003-2021 - http://www.videolan.org/x264.html \
- options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex \
subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 \
chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 \
fast_pskip=1 chroma_qp_offset=-2 threads=7 lookahead_threads=1 \
sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 \
constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 \
direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=23 \
scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 \
crf=28.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 \
aq=1:1.00
Output #0, mp4, to 'show.mp4':
  Metadata:
    software        : Nandub v1.0rc2
    encoder         : Lavf59.17.100
  Stream #0:0: Video: h264 (avc1 / 0x31637661), yuv420p(progressive),\
 576x240, q=2-31, 23.98 fps, 11988 tbn
    Metadata:
      encoder         : Lavc59.20.100 libx264
    Side data:
      cpb: bitrate max/min/avg: 0/0/0 buffer size: 0 vbv_delay: N/A
  Stream #0:1: Audio: mp3 (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 128 kb/s
frame=    1 fps=0.0 q=0.0 size=       0kB time=00:00:00.48 bitrate=  \
 0.8kbits/sframe=  120 fps=0.0 q=-1.0 Lsize=     148kB \
time=00:00:05.01 bitrate= 242.5kbits/s speed=21.2x
video:71kB audio:73kB subtitle:0kB other streams:0kB global headers:0kB \
muxing overhead: 3.456417%
[libx264 @ 0x76824c0] frame I:1     Avg QP: 9.52  size:    77
[libx264 @ 0x76824c0] frame P:65    Avg QP:26.99  size:  1030
[libx264 @ 0x76824c0] frame B:54    Avg QP:22.71  size:    92
[libx264 @ 0x76824c0] consecutive B-frames: 32.5% 16.7% 17.5% 33.3%
[libx264 @ 0x76824c0] mb I  I16..4: 100.0%  0.0%  0.0%
[libx264 @ 0x76824c0] mb P  I16..4:  0.2%  1.3%  0.1%  P16..4: 13.7%  5.2%  \
4.2%  0.0%  0.0%    skip:75.4%
[libx264 @ 0x76824c0] mb B  I16..4:  0.4%  0.2%  0.0%  B16..8:  7.8%  0.4% \
0.0% direct: 0.1%  skip:91.1%  L0:41.8% L1:50.0% BI: 8.2%
[libx264 @ 0x76824c0] 8x8 transform intra:39.3% inter:58.4%
[libx264 @ 0x76824c0] coded y,uvDC,uvAC intra: 8.9% 6.7% 2.4% inter: 5.5% \
4.8% 1.1%
[libx264 @ 0x76824c0] i16 v,h,dc,p: 80%  9% 11%  0%
[libx264 @ 0x76824c0] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 12% 10% 69%  2%  2%  2%  \
1%  2%  1%
[libx264 @ 0x76824c0] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 20% 13% 38%  5%  6%  6%  \
5%  4%  3%
[libx264 @ 0x76824c0] i8c dc,h,v,p: 68% 14% 17%  0%
[libx264 @ 0x76824c0] Weighted P-Frames: Y:27.7% UV:15.4%
[libx264 @ 0x76824c0] ref P L0: 75.3% 11.5%  8.5%  3.4%  1.3%
[libx264 @ 0x76824c0] ref B L0: 83.8% 11.1%  5.1%
[libx264 @ 0x76824c0] ref B L1: 98.9%  1.1%
[libx264 @ 0x76824c0] kb/s:115.09
</code>```

答:
From your log I can see that your input audio is MP3.

```<code>Stream #0:1: Audio: mp3 (U[0][0][0] / 0x0055), 48000 Hz, stereo, fltp, 128 kb/s
</code>```

Most systems expect MPEG container (MP4) to hold AAC audio as standard.

Actual MP4 audio codecs can be AAC, AC3, ALAC, CELP and many others.

But to keep to one standard, they prefer AAC.

Using AAC yourself is the safest option for universal playback in most media players.

The fastest fix is not to use -acodec copy if the input video has non AAC audio.

Solution:

```<code>ffmpeg -i show.avi -vcodec libx264 -vprofile high -crf 28 show.mp4
</code>```

PS:

Regarding ffmpeg -i show.mp4 -i show.mp3 show2.mp4. It is not necessary to create a temp MP3 file. Here you are telling FFmpeg to ignore the MP3 inside show.mp4 and use the MP3 of show.mp3 which is actually the same thing.

You can achieve same result without middle step of making an MP3 file.

```<code>ffmpeg -i show.mp4 -c:v copy show2.mp4
</code>```

Where the output show2.mp4 will now have AAC audio (it is default choice by FFmpeg for MP4 unless you specify a different codec).

Body:
I converted an avi file to a mp4 file with the following command, but the converted mp4 file produced no audio when played with QuickTime (no such problem with other players). I was able to convert mkv to mp4 with the same command without the audio problem.

ffmpeg -i show.avi -vcodec libx264 -vprofile high -crf 28 -acodec copy show.mp4

However I was able to fix the problem by the following two commands (first extract the audio into a mp3 file from the mp4 file, then combine the mp4 file with the mp3 file).

ffmpeg -i show.mp4 -vn -acodec libmp3lame -ac 2 -qscale:a 4 -ar 48000 show.mp3
ffmpeg -i show.mp4 -i show.mp3 show2.mp4

show2.mp4 showed no audio problems with QuickTime. Anyone has any ideas as to what was wrong with the first command?

Below is my ffmpeg info.

% ffmpeg -i show.avi -vcodec libx264 -vprofile high -crf 28 -acodec copy show.mp4
ffmpeg version N-60236-gffb000fff8-static https://johnvansickle.com/ffmpeg/  \
Copyright (c) 2000-2022 the FFmpeg developers
built with gcc 8 (Debian 8.3.0-6)
configuration: --enable-gpl --enable-version3 --enable-static --disable-debug \
--disable-ffplay --disable-indev=sndio --disable-outdev=sndio \
--cc=gcc --enable-fontconfig --enable-frei0r --enable-gnutls \
--enable-gmp --enable-libgme --enable-gray --enable-libaom \
--enable-libfribidi --enable-libass --enable-libvmaf \
--enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb \
--enable-libopencore-amrwb --enable-libopenjpeg --enable-librubberband \
--enable-libsoxr --enable-libspeex --enable-libsrt --enable-libvorbis \
--enable-libopus --enable-libtheora --enable-libvidstab \
--enable-libvo-amrwbenc --enable-libvpx --enable-libwebp \
--enable-libx264 --enable-libx265 --enable-libxml2 \
--enable-libdav1d --enable-libxvid --enable-libzvbi --enable-libzimg
libavutil      57. 18.100 / 57. 18.100
libavcodec     59. 20.100 / 59. 20.100
libavformat    59. 17.100 / 59. 17.100
libavdevice    59.  5.100 / 59.  5.100
libavfilter     8. 25.100 /  8. 25.100
libswscale      6.  5.100 /  6.  5.100
libswresample   4.  4.100 /  4.  4.100
libpostproc    56.  4.100 / 56.  4.100
Input #0, avi, from 'show.avi':
  Metadata:
    software        : Nandub v1.0rc2
  Duration: 01:38:52.93, start: 0.000000, bitrate: 984 kb/s
  Stream #0:0: Video: msmpeg4v3 (DIV3 / 0x33564944), yuv420p, \
576x240, 842 kb/s, 23.98 fps, 23.98 tbr, 23.98 tbn
  Stream #0:1: Audio: mp3 (U[0][0][0] / 0x0055), 48000 Hz, stereo, fltp, 128 kb/s
Stream mapping:
  Stream #0:0 -> #0:0 (msmpeg4v3 (msmpeg4) -> h264 (libx264))
  Stream #0:1 -> #0:1 (copy)
Press [q] to stop, [?] for help
[libx264 @ 0x76824c0] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX
[libx264 @ 0x76824c0] profile High, level 2.1, 4:2:0, 8-bit
[libx264 @ 0x76824c0] 264 - core 164 r3081 19856cc - H.264/MPEG-4 \
AVC codec - Copyleft 2003-2021 - http://www.videolan.org/x264.html \
- options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex \
subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 \
chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 \
fast_pskip=1 chroma_qp_offset=-2 threads=7 lookahead_threads=1 \
sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 \
constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 \
direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=23 \
scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 \
crf=28.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 \
aq=1:1.00
Output #0, mp4, to 'show.mp4':
  Metadata:
    software        : Nandub v1.0rc2
    encoder         : Lavf59.17.100
  Stream #0:0: Video: h264 (avc1 / 0x31637661), yuv420p(progressive),\
 576x240, q=2-31, 23.98 fps, 11988 tbn
    Metadata:
      encoder         : Lavc59.20.100 libx264
    Side data:
      cpb: bitrate max/min/avg: 0/0/0 buffer size: 0 vbv_delay: N/A
  Stream #0:1: Audio: mp3 (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 128 kb/s
frame=    1 fps=0.0 q=0.0 size=       0kB time=00:00:00.48 bitrate=  \
 0.8kbits/sframe=  120 fps=0.0 q=-1.0 Lsize=     148kB \
time=00:00:05.01 bitrate= 242.5kbits/s speed=21.2x
video:71kB audio:73kB subtitle:0kB other streams:0kB global headers:0kB \
muxing overhead: 3.456417%
[libx264 @ 0x76824c0] frame I:1     Avg QP: 9.52  size:    77
[libx264 @ 0x76824c0] frame P:65    Avg QP:26.99  size:  1030
[libx264 @ 0x76824c0] frame B:54    Avg QP:22.71  size:    92
[libx264 @ 0x76824c0] consecutive B-frames: 32.5% 16.7% 17.5% 33.3%
[libx264 @ 0x76824c0] mb I  I16..4: 100.0%  0.0%  0.0%
[libx264 @ 0x76824c0] mb P  I16..4:  0.2%  1.3%  0.1%  P16..4: 13.7%  5.2%  \
4.2%  0.0%  0.0%    skip:75.4%
[libx264 @ 0x76824c0] mb B  I16..4:  0.4%  0.2%  0.0%  B16..8:  7.8%  0.4% \
0.0% direct: 0.1%  skip:91.1%  L0:41.8% L1:50.0% BI: 8.2%
[libx264 @ 0x76824c0] 8x8 transform intra:39.3% inter:58.4%
[libx264 @ 0x76824c0] coded y,uvDC,uvAC intra: 8.9% 6.7% 2.4% inter: 5.5% \
4.8% 1.1%
[libx264 @ 0x76824c0] i16 v,h,dc,p: 80%  9% 11%  0%
[libx264 @ 0x76824c0] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 12% 10% 69%  2%  2%  2%  \
1%  2%  1%
[libx264 @ 0x76824c0] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 20% 13% 38%  5%  6%  6%  \
5%  4%  3%
[libx264 @ 0x76824c0] i8c dc,h,v,p: 68% 14% 17%  0%
[libx264 @ 0x76824c0] Weighted P-Frames: Y:27.7% UV:15.4%
[libx264 @ 0x76824c0] ref P L0: 75.3% 11.5%  8.5%  3.4%  1.3%
[libx264 @ 0x76824c0] ref B L0: 83.8% 11.1%  5.1%
[libx264 @ 0x76824c0] ref B L1: 98.9%  1.1%
[libx264 @ 0x76824c0] kb/s:115.09

Body:
From your log I can see that your input audio is MP3.

Stream #0:1: Audio: mp3 (U[0][0][0] / 0x0055), 48000 Hz, stereo, fltp, 128 kb/s

Most systems expect MPEG container (MP4) to hold AAC audio as standard.

Actual MP4 audio codecs can be AAC, AC3, ALAC, CELP and many others.

But to keep to one standard, they prefer AAC.

Using AAC yourself is the safest option for universal playback in most media players.

The fastest fix is not to use -acodec copy if the input video has non AAC audio.

Solution:

ffmpeg -i show.avi -vcodec libx264 -vprofile high -crf 28 show.mp4

PS:

Regarding ffmpeg -i show.mp4 -i show.mp3 show2.mp4. It is not necessary to create a temp MP3 file. Here you are telling FFmpeg to ignore the MP3 inside show.mp4 and use the MP3 of show.mp3 which is actually the same thing.

You can achieve same result without middle step of making an MP3 file.

ffmpeg -i show.mp4 -c:v copy show2.mp4

Where the output show2.mp4 will now have AAC audio (it is default choice by FFmpeg for MP4 unless you specify a different codec).


问:
Reusing socket when copying large amounts of data
I am currently sending large amounts of data over a Java socket, and I am using the Apache Commons IOUtils library to copy using the copyLarge method to send/receive the data. The problem is that the copyLarge reads until the the input stream returns -1. I have copied a snippet below

```<code>while (-1 != (n = input.read(buffer))) {
   output.write(buffer, 0, n);
   count += n;
}
</code>```

This method will block until the socket is closed, but the problem is I want to reuse the socket to additional large data. The alternatives I see are to either reopen a new socket for each data being transferred, or to write my own read method that looks for an end of stream token (i.e. a newline character).

It has been a while since I've written low level socket code like this, but am I missing something here? Or is there an easier way to do this?

答:
Do you know how much data you have before sending it over? If so, I'd basically length-prefix the message.

That's much easier to handle cleanly than using an end-of-stream token and having to worry about escaping, over-reading etc.

But yes, you'll need to do something, because TCP/IP is a stream-based protocol. Unless you have some indicator for the end of data somehow, you never know whether there might be some more to come Real Soon Now.

Body:
I am currently sending large amounts of data over a Java socket, and I am using the Apache Commons IOUtils library to copy using the copyLarge method to send/receive the data. The problem is that the copyLarge reads until the the input stream returns -1. I have copied a snippet below

while (-1 != (n = input.read(buffer))) {
   output.write(buffer, 0, n);
   count += n;
}

This method will block until the socket is closed, but the problem is I want to reuse the socket to additional large data. The alternatives I see are to either reopen a new socket for each data being transferred, or to write my own read method that looks for an end of stream token (i.e. a newline character).

It has been a while since I've written low level socket code like this, but am I missing something here? Or is there an easier way to do this?


问:
Flutter: StreamBuilder does not show data on connection.state.active
I been trying to figure this out for the entire weekend so I finaly decided to ask you for your advice.

Got a streambuilder which listens for a stream or recipes (filtered by the category -> soups, deserts etc.).

I were confused because the Text "Nothing" (last return statement) was the only thing showing, even though my print statements in the if condition, which asks for the connectionstate.active shows me all the values.

When I print the connection state out one line above my text widget "Nothing" I get "active".

Of course I could just get rid of my if statement and put the returning widget at the end, but I would like to know and understand, why my return statement in my .active condition does not show me the column etc. even though the print statements are shown in the console.

Btw I saw alot of other resources were a Listview is used but I am not sure weather or not I can use a Listview together with a stack (because I want to show data on top of each other).

Looking forward to your replys!

Regards
Thomas

```<code>new StreamBuilder<QuerySnapshot>(
                    stream: FirebaseFirestore.instance.collection("rezepte").where("kategorie", isEqualTo: ausgewaehlteKategorie).snapshots(),
                    builder: (context, AsyncSnapshot<QuerySnapshot> snapshot){
                      print("***** STREAMBUILDER *****");
                      if (snapshot.connectionState == ConnectionState.waiting) {
                        print(snapshot.connectionState);
                        return CircularProgressIndicator();
                      }

                      if(snapshot.connectionState == ConnectionState.active){
                        print(snapshot.connectionState);
                        print(snapshot.data!.docs);
                        print(snapshot.data!.docs[0]["name"]);
                        print(snapshot.data!.docs[0]["kategorie"]);

                        print(snapshot.data!.docs.length);

                        snapshot.data!.docs.map((docs){
                          print("Test1");
                          listeAllerRezepte.add(
                            Rezept(
                              name: docs["name"].toString(),
                              kategorie: docs["kategorie"].toString(),
                              naehrwertKohlenhydrate: docs["naehrwertKohlenhydrate"],
                              naehrwertFett: docs["naehrwertFett"],
                              naehrwertEiweiss: docs["naehrwertEiweiss"],
                              naehrwertKohlenhydrateProzent: double.parse((100 / (docs["naehrwertKohlenhydrate"] + docs["naehrwertFett"] + docs["naehrwertEiweiss"]) * docs["naehrwertKohlenhydrate"]).toStringAsFixed(2)),
                              naehrwertFettProzent: double.parse((100 / (docs["naehrwertKohlenhydrate"] + docs["naehrwertFett"] + docs["naehrwertEiweiss"]) * docs["naehrwertFett"]).toStringAsFixed(2)),
                              naehrwertEiweissProzent: double.parse((100 / (docs["naehrwertKohlenhydrate"] + docs["naehrwertFett"] + docs["naehrwertEiweiss"]) * docs["naehrwertEiweiss"]).toStringAsFixed(2)),
                              img: docs["img"],
                              favorit: docs["favorit"]
                            )
                          );
                          print("Test2");

                          print(listeAllerRezepte[0]);
                          print(listeAllerRezepte[0].name.toString());
                          print(listeAllerRezepte[0].kategorie.toString());
                          print(listeAllerRezepte[0].img.toString());

                          return new Column(
                            children: [
                              new Stack(
                                alignment: Alignment.bottomCenter,
                                children: [
                                  new Text("Test1"),
                                  new Container(
                                    child: new GestureDetector(
                                      child: new Column(
                                        children: [
                                          new Text("TEST"),
                                          new Image(
                                            image: (docs["img"].toString().length > 0) ? NetworkImage(docs["img"].toString()) : NetworkImage(globals.listeAllerKategorien![nummerAusgewaehleKategorie].img.toString())
                                          ),
                                        ],
                                      ),
                                      onTap: () {
                                      },
                                    ),
                                  ),
                                  new Divider(height: 100.0)
                                ],
                              ),
                              new Divider(height: 15.0)
                            ]
                          );
                        }).toList();
                      }

                      if(snapshot.connectionState == ConnectionState.done){
                        print(snapshot.connectionState);
                      }

                      if(!snapshot.hasData){
                        return Text("Loading");
                      }

                      return new Text("Nothing");
                    }
                  )
</code>```

答:
Once the StreamBuilder has recieved all of the data and a done signal, the state becomes done. It does not sit there in there in active. Your checks should go is waiting,  has data, and a catch all afterwards for no data.

UPDATE: The issue is in your return statement in the if(snapshot.connectionState == ConnectionState.active) block. You are not actually returning a widget from the block, so the function is continuing until it reaches the final return statement.

First, make this if statement if(snaphsot.hasData). Then take a look at this section:

```<code>snapshot.data!.docs.map((docs){
  ...
  return new Column(
  ...
}
</code>```

Here, your return statement is to the anonymous function passed to the map method. The Columns are not being returned out of the builder.

While I am not quite sure what your needs are, I believe some of your widgets are nested improperly as well. Below is my best guess at what you are going for, please adjust accordingly. (I have left out some of your code for brevity, focusing only on building the widgets causing your issues.)

```<code>if(snapshot.hasData){
  return new Column(
    children: snapshot.data!.docs.map((docs){
      return new Stack(
       alignment: Alignment.bottomCenter,
       children: [
         new Text("Test1"),
         new Container(
           child: new GestureDetector(
             child: new Column(
               children: [
                 new Text("TEST"),
                 new Image(
                   image: (docs["img"].toString().length > 0) ? NetworkImage(docs["img"].toString()) : NetworkImage(globals.listeAllerKategorien![nummerAusgewaehleKategorie].img.toString())
                 ),
               ],
             ),
             onTap: () {},
           ),
         ),
         new Divider(height: 100.0)
       ],
     );
   },
 );
}
</code>```

NOTE: A ListView is certainly capable of providing what you need, and it is a much better option than Column. It provides scrolling out of the box, better performance and memory usage, as well as some handy constructors that can provide a Divider where needed. I encourage you to check it out once you are comfortable with these results.

Body:
I been trying to figure this out for the entire weekend so I finaly decided to ask you for your advice.

Got a streambuilder which listens for a stream or recipes (filtered by the category -> soups, deserts etc.).

I were confused because the Text "Nothing" (last return statement) was the only thing showing, even though my print statements in the if condition, which asks for the connectionstate.active shows me all the values.

When I print the connection state out one line above my text widget "Nothing" I get "active".

Of course I could just get rid of my if statement and put the returning widget at the end, but I would like to know and understand, why my return statement in my .active condition does not show me the column etc. even though the print statements are shown in the console.

Btw I saw alot of other resources were a Listview is used but I am not sure weather or not I can use a Listview together with a stack (because I want to show data on top of each other).

Looking forward to your replys!

Regards
Thomas

new StreamBuilder<QuerySnapshot>(
                    stream: FirebaseFirestore.instance.collection("rezepte").where("kategorie", isEqualTo: ausgewaehlteKategorie).snapshots(),
                    builder: (context, AsyncSnapshot<QuerySnapshot> snapshot){
                      print("***** STREAMBUILDER *****");
                      if (snapshot.connectionState == ConnectionState.waiting) {
                        print(snapshot.connectionState);
                        return CircularProgressIndicator();
                      }

                      if(snapshot.connectionState == ConnectionState.active){
                        print(snapshot.connectionState);
                        print(snapshot.data!.docs);
                        print(snapshot.data!.docs[0]["name"]);
                        print(snapshot.data!.docs[0]["kategorie"]);

                        print(snapshot.data!.docs.length);

                        snapshot.data!.docs.map((docs){
                          print("Test1");
                          listeAllerRezepte.add(
                            Rezept(
                              name: docs["name"].toString(),
                              kategorie: docs["kategorie"].toString(),
                              naehrwertKohlenhydrate: docs["naehrwertKohlenhydrate"],
                              naehrwertFett: docs["naehrwertFett"],
                              naehrwertEiweiss: docs["naehrwertEiweiss"],
                              naehrwertKohlenhydrateProzent: double.parse((100 / (docs["naehrwertKohlenhydrate"] + docs["naehrwertFett"] + docs["naehrwertEiweiss"]) * docs["naehrwertKohlenhydrate"]).toStringAsFixed(2)),
                              naehrwertFettProzent: double.parse((100 / (docs["naehrwertKohlenhydrate"] + docs["naehrwertFett"] + docs["naehrwertEiweiss"]) * docs["naehrwertFett"]).toStringAsFixed(2)),
                              naehrwertEiweissProzent: double.parse((100 / (docs["naehrwertKohlenhydrate"] + docs["naehrwertFett"] + docs["naehrwertEiweiss"]) * docs["naehrwertEiweiss"]).toStringAsFixed(2)),
                              img: docs["img"],
                              favorit: docs["favorit"]
                            )
                          );
                          print("Test2");

                          print(listeAllerRezepte[0]);
                          print(listeAllerRezepte[0].name.toString());
                          print(listeAllerRezepte[0].kategorie.toString());
                          print(listeAllerRezepte[0].img.toString());

                          return new Column(
                            children: [
                              new Stack(
                                alignment: Alignment.bottomCenter,
                                children: [
                                  new Text("Test1"),
                                  new Container(
                                    child: new GestureDetector(
                                      child: new Column(
                                        children: [
                                          new Text("TEST"),
                                          new Image(
                                            image: (docs["img"].toString().length > 0) ? NetworkImage(docs["img"].toString()) : NetworkImage(globals.listeAllerKategorien![nummerAusgewaehleKategorie].img.toString())
                                          ),
                                        ],
                                      ),
                                      onTap: () {
                                      },
                                    ),
                                  ),
                                  new Divider(height: 100.0)
                                ],
                              ),
                              new Divider(height: 15.0)
                            ]
                          );
                        }).toList();
                      }

                      if(snapshot.connectionState == ConnectionState.done){
                        print(snapshot.connectionState);
                      }

                      if(!snapshot.hasData){
                        return Text("Loading");
                      }

                      return new Text("Nothing");
                    }
                  )

Body:
Once the StreamBuilder has recieved all of the data and a done signal, the state becomes done. It does not sit there in there in active. Your checks should go is waiting,  has data, and a catch all afterwards for no data.

UPDATE: The issue is in your return statement in the if(snapshot.connectionState == ConnectionState.active) block. You are not actually returning a widget from the block, so the function is continuing until it reaches the final return statement.

First, make this if statement if(snaphsot.hasData). Then take a look at this section:

snapshot.data!.docs.map((docs){
  ...
  return new Column(
  ...
}

Here, your return statement is to the anonymous function passed to the map method. The Columns are not being returned out of the builder.

While I am not quite sure what your needs are, I believe some of your widgets are nested improperly as well. Below is my best guess at what you are going for, please adjust accordingly. (I have left out some of your code for brevity, focusing only on building the widgets causing your issues.)

if(snapshot.hasData){
  return new Column(
    children: snapshot.data!.docs.map((docs){
      return new Stack(
       alignment: Alignment.bottomCenter,
       children: [
         new Text("Test1"),
         new Container(
           child: new GestureDetector(
             child: new Column(
               children: [
                 new Text("TEST"),
                 new Image(
                   image: (docs["img"].toString().length > 0) ? NetworkImage(docs["img"].toString()) : NetworkImage(globals.listeAllerKategorien![nummerAusgewaehleKategorie].img.toString())
                 ),
               ],
             ),
             onTap: () {},
           ),
         ),
         new Divider(height: 100.0)
       ],
     );
   },
 );
}

NOTE: A ListView is certainly capable of providing what you need, and it is a much better option than Column. It provides scrolling out of the box, better performance and memory usage, as well as some handy constructors that can provide a Divider where needed. I encourage you to check it out once you are comfortable with these results.