问:
Python DataFrame: Remove/Replace part of a string for all values in a column
In a Dataframe "df" I have a column called "Company". In there I have a list of companies that end with "- CP" the problem is that the spaces are not always in the same place and in some of the entries the dash "-" is missing. I want to remove the "-CP" from all entries.

Input

Company

Intest Apple - CP

Intest Apple -CP

Intest Apple-CP

Intest Apple - CP

Intest Apple CP

Howard P Delta - CP

Output

Company

Intest Apple

Intest Apple

Intest Apple

Intest Apple

Intest Apple

Howard P Delta

This is the code that I have, but when I run it nothing changes

```<code>df['Company'] = df['Company'].str.replace("-CP'","")
df['Company'] = df['Company'].str.replace("- CP'","")
df['Company'] = df['Company'].str.replace(" - CP'","")
</code>```

答:
You could use str.replace with a regular expression to include the case where the dash can be missing (-?) and all variations of spaces between the CP string.

company = df.Company.str.replace('\s*-?\s*CP\s*$','', regex=True)
```
<p>Output from <em>company</em></p>
<pre class="lang-py prettyprint-override"><code>Out[5]:
0      Intest Apple
1      Intest Apple
2      Intest Apple
3      Intest Apple
4      Intest Apple
5    Howard P Delta
Name: Company, dtype: object
</code>```

Body:
In a Dataframe "df" I have a column called "Company". In there I have a list of companies that end with "- CP" the problem is that the spaces are not always in the same place and in some of the entries the dash "-" is missing. I want to remove the "-CP" from all entries.

Input

Company

Intest Apple - CP

Intest Apple -CP

Intest Apple-CP

Intest Apple - CP

Intest Apple CP

Howard P Delta - CP

Output

Company

Intest Apple

Intest Apple

Intest Apple

Intest Apple

Intest Apple

Howard P Delta

This is the code that I have, but when I run it nothing changes

df['Company'] = df['Company'].str.replace("-CP'","")
df['Company'] = df['Company'].str.replace("- CP'","")
df['Company'] = df['Company'].str.replace(" - CP'","")

Body:
You could use str.replace with a regular expression to include the case where the dash can be missing (-?) and all variations of spaces between the CP string.

company = df.Company.str.replace('\s*-?\s*CP\s*$','', regex=True)

Output from company

Out[5]:
0      Intest Apple
1      Intest Apple
2      Intest Apple
3      Intest Apple
4      Intest Apple
5    Howard P Delta
Name: Company, dtype: object


来源: stackexchange

问:
Interchangeable dictionary
I wish to have a dictionary that is interchangeable i.e. values are mapped with keys & keys are mapped with value so that if we know one element, the other partner can be known. In python dict, using keys, we can get values but not vice-versa. How can I achieve this?
Note: For interchangeability, there has to be a 1-1 mapping between key: value & value: key.

Example:

```<code>key = {'a':'1','b':'2','c':'3'}
So, I should be able to get 1 for key['a'] & 'a' for key['1']
</code>```

答:
Here is an example of how you might create a class to do this for you. Be aware that this is quite slow when setting new / editing existing values.

class DoubleDict:
    def __init__(self, *dicts, **extras):
        self.dict1 = {}
        for dct in dicts:
            self.dict1 |= dct
        self.dict1 |= extras
        self.dict2 = dict(zip(self.dict1.values(), self.dict1.keys()))
    def __getitem__(self, key):
        try: return self.dict1.__getitem__(key)
        except KeyError: return self.dict2.__getitem__(key)
    def __setitem__(self, key, value):
        if key in self.dict1:
            self.dict2.pop(self.dict1[key])
            self.dict1.pop(key)
        elif key in self.dict2:
            self.dict1.pop(self.dict2[key])
            self.dict2.pop(key)
        if value in self.dict1:
            self.dict2.pop(self.dict1[value])
            self.dict1.pop(value)
        elif value in self.dict2:
            self.dict1.pop(self.dict2[value])
            self.dict2.pop(value)
        self.dict1[key] = value
        self.dict2[value] = key
    def __iter__(self):
        total_dict = self.dict1 | self.dict2
        return total_dict.__iter__()
    def __repr__(self):
        return f"DoubleDict({repr(self.dict1)})"
    def __str__(self):
        return "\n".join(f"{key}  <==>  {self.dict1[key]}" for key in self.dict1)
```
<p>Here is how it works:</p>
<pre class="lang-py prettyprint-override"><code>a = DoubleDict({1: 2, 3: 4, 5: 6, 7: 8})
print(a)
# 1  <==>  2
# 3  <==>  4
# 5  <==>  6
# 7  <==>  8
a[1] = 3
# Now the 3,4 pair and the 1,2 pair no longer exist, but there is a new 3,1 pair
print(a[1], a[3])
# 3 1
print(a)
# 5  <==>  6
# 7  <==>  8
# 1  <==>  3
</code>```

ContentLicense: CC BY-SA 4.0

Title: Interchangeable dictionary

Body:
I wish to have a dictionary that is interchangeable i.e. values are mapped with keys & keys are mapped with value so that if we know one element, the other partner can be known. In python dict, using keys, we can get values but not vice-versa. How can I achieve this?
Note: For interchangeability, there has to be a 1-1 mapping between key: value & value: key.

Example:

key = {'a':'1','b':'2','c':'3'}
So, I should be able to get 1 for key['a'] & 'a' for key['1']

Body:
Here is an example of how you might create a class to do this for you. Be aware that this is quite slow when setting new / editing existing values.

class DoubleDict:
    def __init__(self, *dicts, **extras):
        self.dict1 = {}
        for dct in dicts:
            self.dict1 |= dct
        self.dict1 |= extras
        self.dict2 = dict(zip(self.dict1.values(), self.dict1.keys()))
    def __getitem__(self, key):
        try: return self.dict1.__getitem__(key)
        except KeyError: return self.dict2.__getitem__(key)
    def __setitem__(self, key, value):
        if key in self.dict1:
            self.dict2.pop(self.dict1[key])
            self.dict1.pop(key)
        elif key in self.dict2:
            self.dict1.pop(self.dict2[key])
            self.dict2.pop(key)
        if value in self.dict1:
            self.dict2.pop(self.dict1[value])
            self.dict1.pop(value)
        elif value in self.dict2:
            self.dict1.pop(self.dict2[value])
            self.dict2.pop(value)
        self.dict1[key] = value
        self.dict2[value] = key
    def __iter__(self):
        total_dict = self.dict1 | self.dict2
        return total_dict.__iter__()
    def __repr__(self):
        return f"DoubleDict({repr(self.dict1)})"
    def __str__(self):
        return "\n".join(f"{key}  <==>  {self.dict1[key]}" for key in self.dict1)

Here is how it works:

a = DoubleDict({1: 2, 3: 4, 5: 6, 7: 8})
print(a)
# 1  <==>  2
# 3  <==>  4
# 5  <==>  6
# 7  <==>  8
a[1] = 3
# Now the 3,4 pair and the 1,2 pair no longer exist, but there is a new 3,1 pair
print(a[1], a[3])
# 3 1
print(a)
# 5  <==>  6
# 7  <==>  8
# 1  <==>  3


问:
Passing map() .x to a function
This might seem like a silly question, but for the life of me I cannot figure it out so appreciate any help.

I am trying to pass .x (from purrr::map) to a function so in the end I get a list of functions (I will use this eventually to pass a list of column definitions with functions inside to reactable). This is a very basic example of what I want to do:

```<code>a = list("b", "c")

t <- map(a, ~{
  function(.x){
    print(x)
  }
})
</code>```

The result I am looking for is:

```<code>> t
[[1]]
function(b){
    print(x)
  }

[[2]]
function(c){
    print(x)
  }
</code>```

but I get:

```<code>> t
[[1]]
function(.x){
    print(x)
  }

[[2]]
function(.x){
    print(x)
  }
</code>```

Is what I am looking for possible?

答:
You can get what you want by using a wrapper function to create a new function. Within the wrapper, create an empty function, set the args to the value x passed in (so if x="a", with give the equivalent of alist(a=)), and then also parse a string to the body. Then the returned list will be the functions you want.

library(purrr)

function_crafter <- function(x) {
  f <- function() {}
  args <- setNames(list(bquote()), x)
  formals(f) <- args
  body(f) <- parse(text = paste0("print(", x, ")"))
  f
}

a <- list("b", "c")

fl <- map(a, function_crafter)

fl[[1]](b=2)
#> [1] 2
fl[[2]](c=39)
#> [1] 39

fl
#> [[1]]
#> function (b)
#> print(b)
#> <environment: 0x7fb68752aae0>
#>
#> [[2]]
#> function (c)
#> print(c)
#> <environment: 0x7fb687552818>
```

If you actually wanted the print() in each function to simply be print(x) rather than print(b) or print(c), then that's even easier, just define the body of the function in its initialization.

Title: Passing map() .x to a function

Body:
This might seem like a silly question, but for the life of me I cannot figure it out so appreciate any help.

I am trying to pass .x (from purrr::map) to a function so in the end I get a list of functions (I will use this eventually to pass a list of column definitions with functions inside to reactable). This is a very basic example of what I want to do:

a = list("b", "c")

t <- map(a, ~{
  function(.x){
    print(x)
  }
})

The result I am looking for is:

> t
[[1]]
function(b){
    print(x)
  }

[[2]]
function(c){
    print(x)
  }

but I get:

> t
[[1]]
function(.x){
    print(x)
  }

[[2]]
function(.x){
    print(x)
  }

Is what I am looking for possible?

Body:
You can get what you want by using a wrapper function to create a new function. Within the wrapper, create an empty function, set the args to the value x passed in (so if x="a", with give the equivalent of alist(a=)), and then also parse a string to the body. Then the returned list will be the functions you want.

library(purrr)

function_crafter <- function(x) {
  f <- function() {}
  args <- setNames(list(bquote()), x)
  formals(f) <- args
  body(f) <- parse(text = paste0("print(", x, ")"))
  f
}

a <- list("b", "c")

fl <- map(a, function_crafter)

fl[[1]](b=2)
#> [1] 2
fl[[2]](c=39)
#> [1] 39

fl
#> [[1]]
#> function (b)
#> print(b)
#> <environment: 0x7fb68752aae0>
#>
#> [[2]]
#> function (c)
#> print(c)
#> <environment: 0x7fb687552818>

If you actually wanted the print() in each function to simply be print(x) rather than print(b) or print(c), then that's even easier, just define the body of the function in its initialization.


问:
Redeploy Heroku app without code changes
I would like to deploy a Heroku app which will be done ideally using git push -u heroku master. However this will only work if there are any pending commits to be pushed to master.

How can I redeploy the app while there is nothing to push ? I tried git push -u heroku master -f and still get the same below

```<code>Branch master set up to track remote branch master from heroku.
Everything up-to-date
</code>```

PS: I also want to retain the existing app, which means I cannot make use of this answer https://stackoverflow.com/a/22043184/968442

答:
It turns out there is a neat plugin for Heroku called heroku release retry that lets you retry the last deploy without resorting to adding bad commits to your repository.

```<code>// install plugin
heroku plugins:install heroku-releases-retry
// retry release
heroku releases:retry --app {your-app}
</code>```

Source: https://www.darraghoriordan.com/2019/03/02/heroku-push-failed-force-rebuild

ContentLicense: CC BY-SA 3.0

Body:
I would like to deploy a Heroku app which will be done ideally using git push -u heroku master. However this will only work if there are any pending commits to be pushed to master.

How can I redeploy the app while there is nothing to push ? I tried git push -u heroku master -f and still get the same below

Branch master set up to track remote branch master from heroku.
Everything up-to-date

PS: I also want to retain the existing app, which means I cannot make use of this answer https://stackoverflow.com/a/22043184/968442

Body:
It turns out there is a neat plugin for Heroku called heroku release retry that lets you retry the last deploy without resorting to adding bad commits to your repository.

// install plugin
heroku plugins:install heroku-releases-retry
// retry release
heroku releases:retry --app {your-app}

Source: https://www.darraghoriordan.com/2019/03/02/heroku-push-failed-force-rebuild


问:
How to load colorful emojis in pygame?
I want to use Pygame's freetype module to load a colorful emoji via its unicode. Unfortunately I only get a monochrome image with the outline of the emoji:

Minimal, Reproducible Example:

import pygame
import pygame.freetype

pygame.init()
window = pygame.display.set_mode((200, 200))

seguisy80 = pygame.freetype.SysFont("segoeuisymbol", 100)
emoji, rect = seguisy80.render('', "black")
rect.center = window.get_rect().center

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.fill("lightgray")
    window.blit(emoji, rect)
    pygame.display.flip()

pygame.quit()
```

How can I modify this code to get a full RGBA color image of an emoji?

答:
Unfortunately, colored font loading is not natively supported in Pygame. However, there is a workaround.
First you need a colored emoji font. For example, you can download one here: Apple Color Emoji for Linux.

Load this font using https://freetype.org/. Install freetype-py:

pip3 install freetype-py
```
<p>For Windows users, it should be mentioned that the installed package does not support the font and results in an "unimplemented feature" exception.
Download the package from Unofficial Windows Binaries for Python Extension Packages and install it. e.g.:</p>
<pre class="lang-py prettyprint-override"><code>pip3 install freetype_py-2.2.0-cp310-cp310-win_amd64.whl
</code>```

Now you're prepared and can load an emoji from the font.Emojis and their Unicode can be found here: Emoticons (Unicode block).
Copy the emoji or use the unicode and load the glyph:

import freetype

face = freetype.Face("AppleColorEmoji.ttf")
face.set_char_size(int(face.available_sizes[-1].size))

face.load_char('', freetype.FT_LOAD_COLOR) # or face.load_char('\U0001F603', freetype.FT_LOAD_COLOR)
```
<p>The loaded glyph now needs to be turned into a <code>pygame.Surface</code>. To do this, use NumPy.
How this works in detail is explained in the answer to the question: How do I convert an OpenCV (cv2) image (BGR and BGRA) to a pygame.Surface object.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np

ft_bitmap = face.glyph.bitmap
bitmap = np.array(ft_bitmap.buffer, dtype=np.uint8).reshape((ft_bitmap.rows, ft_bitmap.width, 4))
bitmap[:, :, [0, 2]] = bitmap[:, :, [2, 0]]
emoji = pygame.image.frombuffer(bitmap.flatten(), (ft_bitmap.width, ft_bitmap.rows), 'RGBA')
</code>```

See also Text and font - Unicode

Minimal example:

import pygame
import freetype
import numpy as np

class Emojis:
    def __init__(self):
        self. face = freetype.Face("AppleColorEmoji.ttf")
        self.face.set_char_size(int(self.face.available_sizes[-1].size))
    def create_surface(self, unicode):
        self.face.load_char(unicode, freetype.FT_LOAD_COLOR)
        ft_bitmap = self.face.glyph.bitmap
        bitmap = np.array(ft_bitmap.buffer, dtype=np.uint8).reshape((ft_bitmap.rows, ft_bitmap.width, 4))
        bitmap[:, :, [0, 2]] = bitmap[:, :, [2, 0]]
        return pygame.image.frombuffer(bitmap.flatten(), (ft_bitmap.width, ft_bitmap.rows), 'RGBA')

pygame.init()
window = pygame.display.set_mode((200, 200))
emojis = Emojis()

emoji = emojis.create_surface('')
#emoji = emojis.create_surface('\U0001F603')
rect = emoji.get_rect(center = window.get_rect().center)

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.fill("lightgray")
    window.blit(emoji, rect)
    pygame.display.flip()

pygame.quit()
```

Title: How to load colorful emojis in pygame?

Body:
I want to use Pygame's freetype module to load a colorful emoji via its unicode. Unfortunately I only get a monochrome image with the outline of the emoji:

Minimal, Reproducible Example:

import pygame
import pygame.freetype

pygame.init()
window = pygame.display.set_mode((200, 200))

seguisy80 = pygame.freetype.SysFont("segoeuisymbol", 100)
emoji, rect = seguisy80.render('', "black")
rect.center = window.get_rect().center

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.fill("lightgray")
    window.blit(emoji, rect)
    pygame.display.flip()

pygame.quit()

How can I modify this code to get a full RGBA color image of an emoji?

Body:
Unfortunately, colored font loading is not natively supported in Pygame. However, there is a workaround.
First you need a colored emoji font. For example, you can download one here: Apple Color Emoji for Linux.

Load this font using https://freetype.org/. Install freetype-py:

pip3 install freetype-py

For Windows users, it should be mentioned that the installed package does not support the font and results in an "unimplemented feature" exception.
Download the package from Unofficial Windows Binaries for Python Extension Packages and install it. e.g.:

pip3 install freetype_py-2.2.0-cp310-cp310-win_amd64.whl

Now you're prepared and can load an emoji from the font.Emojis and their Unicode can be found here: Emoticons (Unicode block).
Copy the emoji or use the unicode and load the glyph:

import freetype

face = freetype.Face("AppleColorEmoji.ttf")
face.set_char_size(int(face.available_sizes[-1].size))

face.load_char('', freetype.FT_LOAD_COLOR) # or face.load_char('\U0001F603', freetype.FT_LOAD_COLOR)

The loaded glyph now needs to be turned into a pygame.Surface. To do this, use NumPy.
How this works in detail is explained in the answer to the question: How do I convert an OpenCV (cv2) image (BGR and BGRA) to a pygame.Surface object.

import numpy as np

ft_bitmap = face.glyph.bitmap
bitmap = np.array(ft_bitmap.buffer, dtype=np.uint8).reshape((ft_bitmap.rows, ft_bitmap.width, 4))
bitmap[:, :, [0, 2]] = bitmap[:, :, [2, 0]]
emoji = pygame.image.frombuffer(bitmap.flatten(), (ft_bitmap.width, ft_bitmap.rows), 'RGBA')

See also Text and font - Unicode

Minimal example:

import pygame
import freetype
import numpy as np

class Emojis:
    def __init__(self):
        self. face = freetype.Face("AppleColorEmoji.ttf")
        self.face.set_char_size(int(self.face.available_sizes[-1].size))
    def create_surface(self, unicode):
        self.face.load_char(unicode, freetype.FT_LOAD_COLOR)
        ft_bitmap = self.face.glyph.bitmap
        bitmap = np.array(ft_bitmap.buffer, dtype=np.uint8).reshape((ft_bitmap.rows, ft_bitmap.width, 4))
        bitmap[:, :, [0, 2]] = bitmap[:, :, [2, 0]]
        return pygame.image.frombuffer(bitmap.flatten(), (ft_bitmap.width, ft_bitmap.rows), 'RGBA')

pygame.init()
window = pygame.display.set_mode((200, 200))
emojis = Emojis()

emoji = emojis.create_surface('')
#emoji = emojis.create_surface('\U0001F603')
rect = emoji.get_rect(center = window.get_rect().center)

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.fill("lightgray")
    window.blit(emoji, rect)
    pygame.display.flip()

pygame.quit()


问:
Why does this numeric equation using a cosine produce a different result between a console application and windows application?
I write a mathematical function to be benchmark function in my optimization algorithm.

```<code>public static double SolomonFunction(double[] x)
    {
        double f;
        double sum = 0;
        for (int i = 0; i < x.Length; i++)
        {
            sum += x[i] * x[i];
        }

        f = 1 - Math.Cos(2 * Math.PI * Math.Sqrt(sum)) + 0.1 * Math.Sqrt(sum);
        return f;
    }
</code>```

but it has different result in console application and windows application when the input is SolomonFunction(new double[] { -4.74641638144941E+151, -6.49440696607247E+153, -1.0998592442531E+153, 3.58027097738642E+149, 6.28490996716059E+152 })

in console application the result is 6,616968044816507E+152
in windows application the result is -4,09139395927863E+154

Is there something different that I need to do in a windows application that I don't need to do in a console application? Or am I fundamentally misunderstanding something?

答:
In the platform that produces “-4,09139395927863E+154”, the Math.Cos routine is broken. It apparently uses a processor instruction that does not support operands outside [−2−63, +2−63].

Since I do not use C#, here is a C program that reproduces the correct behavior:

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

static double SolomonFunction(size_t length, double *x)
{
    double sum = 0;
    for (int i = 0; i < length; i++)
        sum += x[i] * x[i];

    return 1 - cos(2 * M_PI * sqrt(sum)) + 0.1 * sqrt(sum);
}

#define NumberOf(a) (sizeof (a) / sizeof *(a))

int main(void)
{
    double x[] = { -4.74641638144941E+151, -6.49440696607247E+153, -1.0998592442531E+153, 3.58027097738642E+149, 6.28490996716059E+152 };
    printf("%.16g\n", SolomonFunction(NumberOf(x), x));
}
</code>```

When run with Apple Clang 11 on macOS 10.14.6, this produces “6.616968044816507e+152”. Looking at the calculations, we can see that sum must be huge and the result should be entirely dominated by 0.1 * Math.Sqrt(sum). Since the range of cosine on real numbers in [−1, +1], the 1 - Math.Cos(…) part of the formula should have negligible effect, regardless of the argument to Math.Cos. So this seems like a reasonable result.

Considering the other result, “-4,09139395927863E+154”, we see it is impossible for the formula to produce a negative result when correctly calculated. 1 - Math.Cos(…) should be in [0, 2], and 0.1 * Math.Sqrt(sum) should never be negative, so their sum should be non-negative.

This incorrect result is entirely explained by a defective Math.Cos. Suppose, when the argument is huge, Math.Cos returns its argument instead of its cosine. We can reproduce this with the C code above b y using return 1 - (2 * M_PI * sqrt(sum)) + 0.1 * sqrt(sum);, where cos has been removed, leaving just its argument. Running this produces the output “-4.091393959278625e+154”, matching the reported output (with rounding to a different number of digits), confirming the hypothesis.

This is consistent with behavior of the FCOS instruction. Intel 64 and IA-32 Architecture Software Developer‘s Manual, combined volumes, December 2017, page 906, says, for FCOS:

If the source operand is outside the acceptable range, the C2 flag in the FPU status word is set, and the value in register ST(0) remains unchanged.

Thus, when the cosine argument is out of the supported range (−263 to +263), executing FCOS leaves the argument in the register that is also used for the result. Then Math.Cos apparently uses this value for the result.

Body:
I write a mathematical function to be benchmark function in my optimization algorithm.

public static double SolomonFunction(double[] x)
    {
        double f;
        double sum = 0;
        for (int i = 0; i < x.Length; i++)
        {
            sum += x[i] * x[i];
        }

        f = 1 - Math.Cos(2 * Math.PI * Math.Sqrt(sum)) + 0.1 * Math.Sqrt(sum);
        return f;
    }

but it has different result in console application and windows application when the input is SolomonFunction(new double[] { -4.74641638144941E+151, -6.49440696607247E+153, -1.0998592442531E+153, 3.58027097738642E+149, 6.28490996716059E+152 })

in console application the result is 6,616968044816507E+152
in windows application the result is -4,09139395927863E+154

Is there something different that I need to do in a windows application that I don't need to do in a console application? Or am I fundamentally misunderstanding something?

Body:
In the platform that produces “-4,09139395927863E+154”, the Math.Cos routine is broken. It apparently uses a processor instruction that does not support operands outside [−2−63, +2−63].

Since I do not use C#, here is a C program that reproduces the correct behavior:

#include <math.h>
#include <stdio.h>

static double SolomonFunction(size_t length, double *x)
{
    double sum = 0;
    for (int i = 0; i < length; i++)
        sum += x[i] * x[i];

    return 1 - cos(2 * M_PI * sqrt(sum)) + 0.1 * sqrt(sum);
}

#define NumberOf(a) (sizeof (a) / sizeof *(a))

int main(void)
{
    double x[] = { -4.74641638144941E+151, -6.49440696607247E+153, -1.0998592442531E+153, 3.58027097738642E+149, 6.28490996716059E+152 };
    printf("%.16g\n", SolomonFunction(NumberOf(x), x));
}

When run with Apple Clang 11 on macOS 10.14.6, this produces “6.616968044816507e+152”. Looking at the calculations, we can see that sum must be huge and the result should be entirely dominated by 0.1 * Math.Sqrt(sum). Since the range of cosine on real numbers in [−1, +1], the 1 - Math.Cos(…) part of the formula should have negligible effect, regardless of the argument to Math.Cos. So this seems like a reasonable result.

Considering the other result, “-4,09139395927863E+154”, we see it is impossible for the formula to produce a negative result when correctly calculated. 1 - Math.Cos(…) should be in [0, 2], and 0.1 * Math.Sqrt(sum) should never be negative, so their sum should be non-negative.

This incorrect result is entirely explained by a defective Math.Cos. Suppose, when the argument is huge, Math.Cos returns its argument instead of its cosine. We can reproduce this with the C code above b y using return 1 - (2 * M_PI * sqrt(sum)) + 0.1 * sqrt(sum);, where cos has been removed, leaving just its argument. Running this produces the output “-4.091393959278625e+154”, matching the reported output (with rounding to a different number of digits), confirming the hypothesis.

This is consistent with behavior of the FCOS instruction. Intel 64 and IA-32 Architecture Software Developer‘s Manual, combined volumes, December 2017, page 906, says, for FCOS:

If the source operand is outside the acceptable range, the C2 flag in the FPU status word is set, and the value in register ST(0) remains unchanged.

Thus, when the cosine argument is out of the supported range (−263 to +263), executing FCOS leaves the argument in the register that is also used for the result. Then Math.Cos apparently uses this value for the result.


问:
over-release without a calltrace (using ARC), bad acces in main
I've recently converted to using ARC. However, i'm having a weird crash now, and the crashlogs are really unhelpful. During one of my application initialization processes (getting data from server, parsing it, setting up views), i get a bad_access. This is the error log from the device:

```<code>    Incident Identifier: 7CE05452-7C5D-424A-8529-AE7B17C9FEBC
CrashReporter Key:   b743ede30ce737293cf7444f67bb8a7b590c2fd9
Hardware Model:      iPhone3,1
Process:         BoreBeta [231]
Path:            /var/mobile/Applications/52A15437-459A-4160-95C4-BF5DF5C98C15/BoreBeta.app/BoreBeta
Identifier:      BoreBeta
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2011-08-18 14:53:41.800 +0200
OS Version:      iPhone OS 5.0 (9A5288d)
Report Version:  104

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x80000004
Crashed Thread:  0

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   CoreFoundation                  0x3758e380 CFRelease + 28
1   CoreFoundation                  0x375a93ec -[__NSArrayM dealloc] + 116
2   libobjc.A.dylib                 0x30a4e0be _objc_rootRelease + 30
3   libobjc.A.dylib                 0x30a4fdb0 objc_release + 32
4   libobjc.A.dylib                 0x30a4ee06 (anonymous namespace)::AutoreleasePoolPage::pop(void*) + 218
5   libobjc.A.dylib                 0x30a4ed22 _objc_autoreleasePoolPop + 6
6   CoreFoundation                  0x3759f050 _CFAutoreleasePoolPop + 12
7   Foundation                      0x337cd460 -[NSAutoreleasePool release] + 120
8   UIKit                           0x33b8d948 _UIApplicationHandleEvent + 6664
9   GraphicsServices                0x30ff8ef4 PurpleEventCallback + 876
10  CoreFoundation                  0x3760a9c4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 32
11  CoreFoundation                  0x3760a966 __CFRunLoopDoSource1 + 134
12  CoreFoundation                  0x3760958c __CFRunLoopRun + 1364
13  CoreFoundation                  0x375ab036 CFRunLoopRunSpecific + 294
14  CoreFoundation                  0x375aaefe CFRunLoopRunInMode + 98
15  UIKit                           0x33b8b758 -[UIApplication _run] + 544
16  UIKit                           0x33b8898a UIApplicationMain + 1074
17  BoreBeta                        0x00002d8a main (main.m:14)
18  BoreBeta                        0x000027f8 start + 32

Thread 1 name:  Dispatch queue: com.apple.libdispatch-manager
Thread 1:
0   libsystem_kernel.dylib          0x3140d214 kevent + 24
1   libdispatch.dylib               0x376aaf60 _dispatch_mgr_invoke + 708
2   libdispatch.dylib               0x376aac7e _dispatch_mgr_thread + 30
</code>```

Etcetera, i believe this is the only helpful part. When i let it crash from running in XCode, i see it crashes in main, and i don't get to see any calltrace, apart from main, UIApplicationMain and CFRelease on top..

In the past, i would look through my code for overreleasing objects, but i doubt this is the case because i'm now using ARC. How do you fix errors like this?

Edit: the code for parsing the data is on a seperate thread using GCD, and that's where my only @autoreleasepool lives.

Also, when running with NSZombieEnabled, i'm getting the NSArrayM release call. Unfortunately, that's the same we read in the crash log, so still no real progress here i'm afraid...

Edit: Ok. Once i fixed all my other memory errors without ARC, i got this error once again. So apparently it's not ARC-related...

答:
Have you just recently upgraded to Xcode 4.2 beta 5?  That seems to cause some random issues with ARC such as that, we sara  very similar crash and had to revert back to 4.2 beta 4.

Look on the Apple developer forums for more detail.

Body:
I've recently converted to using ARC. However, i'm having a weird crash now, and the crashlogs are really unhelpful. During one of my application initialization processes (getting data from server, parsing it, setting up views), i get a bad_access. This is the error log from the device:

    Incident Identifier: 7CE05452-7C5D-424A-8529-AE7B17C9FEBC
CrashReporter Key:   b743ede30ce737293cf7444f67bb8a7b590c2fd9
Hardware Model:      iPhone3,1
Process:         BoreBeta [231]
Path:            /var/mobile/Applications/52A15437-459A-4160-95C4-BF5DF5C98C15/BoreBeta.app/BoreBeta
Identifier:      BoreBeta
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2011-08-18 14:53:41.800 +0200
OS Version:      iPhone OS 5.0 (9A5288d)
Report Version:  104

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x80000004
Crashed Thread:  0

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   CoreFoundation                  0x3758e380 CFRelease + 28
1   CoreFoundation                  0x375a93ec -[__NSArrayM dealloc] + 116
2   libobjc.A.dylib                 0x30a4e0be _objc_rootRelease + 30
3   libobjc.A.dylib                 0x30a4fdb0 objc_release + 32
4   libobjc.A.dylib                 0x30a4ee06 (anonymous namespace)::AutoreleasePoolPage::pop(void*) + 218
5   libobjc.A.dylib                 0x30a4ed22 _objc_autoreleasePoolPop + 6
6   CoreFoundation                  0x3759f050 _CFAutoreleasePoolPop + 12
7   Foundation                      0x337cd460 -[NSAutoreleasePool release] + 120
8   UIKit                           0x33b8d948 _UIApplicationHandleEvent + 6664
9   GraphicsServices                0x30ff8ef4 PurpleEventCallback + 876
10  CoreFoundation                  0x3760a9c4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 32
11  CoreFoundation                  0x3760a966 __CFRunLoopDoSource1 + 134
12  CoreFoundation                  0x3760958c __CFRunLoopRun + 1364
13  CoreFoundation                  0x375ab036 CFRunLoopRunSpecific + 294
14  CoreFoundation                  0x375aaefe CFRunLoopRunInMode + 98
15  UIKit                           0x33b8b758 -[UIApplication _run] + 544
16  UIKit                           0x33b8898a UIApplicationMain + 1074
17  BoreBeta                        0x00002d8a main (main.m:14)
18  BoreBeta                        0x000027f8 start + 32

Thread 1 name:  Dispatch queue: com.apple.libdispatch-manager
Thread 1:
0   libsystem_kernel.dylib          0x3140d214 kevent + 24
1   libdispatch.dylib               0x376aaf60 _dispatch_mgr_invoke + 708
2   libdispatch.dylib               0x376aac7e _dispatch_mgr_thread + 30

Etcetera, i believe this is the only helpful part. When i let it crash from running in XCode, i see it crashes in main, and i don't get to see any calltrace, apart from main, UIApplicationMain and CFRelease on top..

In the past, i would look through my code for overreleasing objects, but i doubt this is the case because i'm now using ARC. How do you fix errors like this?

Edit: the code for parsing the data is on a seperate thread using GCD, and that's where my only @autoreleasepool lives.

Also, when running with NSZombieEnabled, i'm getting the NSArrayM release call. Unfortunately, that's the same we read in the crash log, so still no real progress here i'm afraid...

Edit: Ok. Once i fixed all my other memory errors without ARC, i got this error once again. So apparently it's not ARC-related...


问:
java error says JOptionPane cannot be resolved, didn't use JOptionPane
I'm kind of a beginner and I was using a tutorial to make a simple program that displays text fields on a JFrame. I didn't use a JLayeredPane in the whole project, but I still get this error that says, "The type javax.swing.JLayeredPane cannot be resolved. It is indirectly referenced from required .class files." Why do I get this error?
Here's the code (there's two classes):

second class:

```<code>  package eventHandlerTutorial;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JOptionPane;
public class secondClass extends JFrame
{
private JTextField item1;
private JTextField item2;
private JTextField item3;
private JPasswordField passwordField;
public secondClass()
   {
    super("The title");
    setLayout(new FlowLayout());
    item1=new JTextField(10);
    add(item1);
    item2=new JTextField("enter text here");
    add(item2);
    item3=new JTextField("uneditable",20);
    item3.setEditable(false);
    add(item3);
    passwordField=new JPasswordField("mypass");
    add(passwordField);
    theHandler handler=new theHandler();
    item1.addActionListener(handler);
    item2.addActionListener(handler);
    item3.addActionListener(handler);
    passwordField.addActionListener(handler);
   }
private class theHandler implements ActionListener
        {
    public void actionPerformed(ActionEvent event)
            {
            String string="";
            if(event.getSource()==item1)
                string=String.format("field 1: %s",event.getActionCommand());
            else if(event.getSource()==item2)
                string=String.format("field 2: %s",event.getActionCommand());
            else if (event.getSource()==item3)
                string=String.format("field 3: %s",event.getActionCommand());
            else if(event.getSource()==passwordField)
                string=String.format("password field is: %s",event.getActionCommand());
            JOptionPane.showMessageDialog(null,string);
            }
        }
}
</code>```

main class:

```<code> package eventHandlerTutorial;
import javax.swing.JFrame;
public class mainClass
{
 public static void main(String[] args)
  {
  secondClass sc=new secondClass();
  sc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  sc.setSize(350,100);
  sc.setVisible(true);
  }
}
</code>```

答:
The error is explained:

"... cannot be resolved. It is indirectly referenced from required .class files.".

Another thing is, in your question you are saying "JOptionPane"

and

in explanation you are saying "JLayeredPane".

Sometimes (because of IDE errors) you are suppose to import manually.

Add

```<code>import javax.swing.JLayeredPane;
</code>```

manually.

and check it out.

if, still you face issue,
try to clean the project.

Body:
I'm kind of a beginner and I was using a tutorial to make a simple program that displays text fields on a JFrame. I didn't use a JLayeredPane in the whole project, but I still get this error that says, "The type javax.swing.JLayeredPane cannot be resolved. It is indirectly referenced from required .class files." Why do I get this error?
Here's the code (there's two classes):

second class:

  package eventHandlerTutorial;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JOptionPane;
public class secondClass extends JFrame
{
private JTextField item1;
private JTextField item2;
private JTextField item3;
private JPasswordField passwordField;
public secondClass()
   {
    super("The title");
    setLayout(new FlowLayout());
    item1=new JTextField(10);
    add(item1);
    item2=new JTextField("enter text here");
    add(item2);
    item3=new JTextField("uneditable",20);
    item3.setEditable(false);
    add(item3);
    passwordField=new JPasswordField("mypass");
    add(passwordField);
    theHandler handler=new theHandler();
    item1.addActionListener(handler);
    item2.addActionListener(handler);
    item3.addActionListener(handler);
    passwordField.addActionListener(handler);
   }
private class theHandler implements ActionListener
        {
    public void actionPerformed(ActionEvent event)
            {
            String string="";
            if(event.getSource()==item1)
                string=String.format("field 1: %s",event.getActionCommand());
            else if(event.getSource()==item2)
                string=String.format("field 2: %s",event.getActionCommand());
            else if (event.getSource()==item3)
                string=String.format("field 3: %s",event.getActionCommand());
            else if(event.getSource()==passwordField)
                string=String.format("password field is: %s",event.getActionCommand());
            JOptionPane.showMessageDialog(null,string);
            }
        }
}

main class:

 package eventHandlerTutorial;
import javax.swing.JFrame;
public class mainClass
{
 public static void main(String[] args)
  {
  secondClass sc=new secondClass();
  sc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  sc.setSize(350,100);
  sc.setVisible(true);
  }
}

Body:
The error is explained:

"... cannot be resolved. It is indirectly referenced from required .class files.".

Another thing is, in your question you are saying "JOptionPane"

and

in explanation you are saying "JLayeredPane".

Sometimes (because of IDE errors) you are suppose to import manually.

Add

import javax.swing.JLayeredPane;

manually.

and check it out.

if, still you face issue,
try to clean the project.


问:
Parsing Watir Results
I'm using Watir for getting data from published items, 12 on a single page. Structured as presented below, I am expecting 12 items to show up, much like how Nokogiri parses results.  I am using the :css way of obtaining it, or the direct browser.div, but the result isn't what I'm expecting.

How is this different than the way Nokogiri grabs elements?  I'm assuming Watir accomplishes this in the same way.  I then need to iterate through these items to get their data.  I'm searching on the class itemContainer, which wraps around all 12 products on the page.

How can I get that array of divs?

```<code>## HTML
<div data-jplist-item="" class="itemSpace">
  <div class="itemContainer">
    <a href="/en/Products/All/Tipless Chine" target="_blank" title="Click here to learn more about this product">
    <div class="name itemName">Alpha<span style="display:none;">boat part, DELTAUPDATE</span></div>
    <div class="saleDiscount" style="display:none;">25.575</div>
    <div class="itemNo" style="display:none;">1711</div>
    <div class="saleNote">SALE</div></a>
  </div>
</div>
<div data-jplist-item="" class="itemSpace">
  <div class="itemContainer">
    <a href="/en/Products/All/Something" target="_blank" title="Click here to learn more about this product">
    <div class="name itemName">Bravo<span style="display:none;">boat part</span></div>
    <div class="saleDiscount" style="display:none;">300</div>
    <div class="itemNo" style="display:none;">584</div>
    <div class="saleNote">SALE</div></a>
  </div>
</div>
<div data-jplist-item="" class="itemSpace">
  <div class="itemContainer">
    <a href="/en/Products/All/Something Else" target="_blank" title="Click here to learn more about this product">
    <div class="name itemName">Charlie<span style="display:none;">boat part</span></div>
    <div class="saleDiscount" style="display:none;">600</div>
    <div class="itemNo" style="display:none;">413</div>
    <div class="saleNote">SALE</div></a>
  </div>
</div>

## code
##### a is the browser
item = a.div(class: "itemContainer")
ap item.inspect
puts item.class

## result
"#<Watir::Div: located: false; {:class=>\"itemSpace\", :tag_name=>\"div\"}>"
Watir::Div
</code>```

答:
I am not clear about your question. But I have printed link title and first division text here.

```<code>b.divs(class: 'itemContainer').each do |div|
  p div.a.title
  p div.a.div.text
end
</code>```

Output

```<code>"Click here to learn more about this product"
"Alpha"
"Click here to learn more about this product"
"Bravo"
"Click here to learn more about this product"
"Charlie"
</code>```

Title: Parsing Watir Results

Body:
I'm using Watir for getting data from published items, 12 on a single page. Structured as presented below, I am expecting 12 items to show up, much like how Nokogiri parses results.  I am using the :css way of obtaining it, or the direct browser.div, but the result isn't what I'm expecting.

How is this different than the way Nokogiri grabs elements?  I'm assuming Watir accomplishes this in the same way.  I then need to iterate through these items to get their data.  I'm searching on the class itemContainer, which wraps around all 12 products on the page.

How can I get that array of divs?

## HTML

Alphaboat part, DELTAUPDATE

25.575

1711

SALE

Bravoboat part

300

584

SALE

Charlieboat part

600

413

SALE

## code
##### a is the browser
item = a.div(class: "itemContainer")
ap item.inspect
puts item.class

## result
"#<Watir::Div: located: false; {:class=>\"itemSpace\", :tag_name=>\"div\"}>"
Watir::Div

Body:
I am not clear about your question. But I have printed link title and first division text here.

b.divs(class: 'itemContainer').each do |div|
  p div.a.title
  p div.a.div.text
end

Output

"Click here to learn more about this product"
"Alpha"
"Click here to learn more about this product"
"Bravo"
"Click here to learn more about this product"
"Charlie"


问:
Hibernate creating new columns on existing table running with springboot
On running my springboot application hibernate is creating new columns.
Below is my entity class

```<code>@Entity
@Table(name="contst_games")
public class ContestGames {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="cntstName")
    private String contestName;

    @Column(name="cntstType")
    private String contestType;

    @Column(name="phne")
    private int phoneNumbr;

    // getters and setters

    @Override
    public String toString() {
        return "ContestGames [id=" + id + ", contestName=" + contestName + ", contestType=" + contestType + "]";
    }

}
</code>```

Below is the setup of properties

```<code># ==========================================================================
# = JPA / HIBERNATE
# ==========================================================================
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql = true

#60 sec
spring.datasource.hikari.connection-timeout=60000
# max 5
spring.datasource.hikari.maximum-pool-size=5
spring.jpa.hibernate.ddl-auto=update
#============================================================================
</code>```

Below is the newly created table

```<code>'id', 'int(11)', 'NO', 'PRI', NULL, 'auto_increment'
'cntstName', 'varchar(255)', 'YES', '', NULL, ''
'cntstType', 'varchar(255)', 'YES', '', NULL, ''
'phne', 'int(11)', 'YES', '', NULL, ''
'cntst_name', 'varchar(255)', 'YES', '', NULL, ''
'cntst_type', 'varchar(255)', 'YES', '', NULL, ''
</code>```

Below is the alter query that is being run on running the application.

2019-11-28 13:09:23.092  INFO 10615 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2019-11-28 13:09:23.158  INFO 10615 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.4.8.Final}
2019-11-28 13:09:23.344  INFO 10615 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2019-11-28 13:09:23.446  INFO 10615 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-11-28 13:09:23.450  WARN 10615 --- [           main] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
2019-11-28 13:09:23.669  INFO 10615 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-11-28 13:09:23.688  INFO 10615 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Hibernate: alter table contst_games add column cntst_name varchar(255)
Hibernate: alter table contst_games add column cntst_type varchar(255)
2019-11-28 13:09:24.867  INFO 10615 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2019-11-28 13:09:24.891  INFO 10615 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-11-28 13:09:25.482  WARN 10615 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
```

Two new columns cntst_name and cntst_type are being created at runtime. Ideally no new column should be added since the table already exists and spring.jpa.hibernate.ddl-auto=update. Also to be noted no new column for phone number is being created.

答:
That's because of Hibernate&Spring Boot Naming Strategies.
(more info: https://www.jpa-buddy.com/blog/hibernate-naming-strategies-jpa-specification-vs-springboot-opinionation)

So,
the right way is to name your columns strictly in a snake_case, NOT camelCase or PascalCase.

Body:
On running my springboot application hibernate is creating new columns.
Below is my entity class

@Entity
@Table(name="contst_games")
public class ContestGames {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="cntstName")
    private String contestName;

    @Column(name="cntstType")
    private String contestType;

    @Column(name="phne")
    private int phoneNumbr;

    // getters and setters

    @Override
    public String toString() {
        return "ContestGames [id=" + id + ", contestName=" + contestName + ", contestType=" + contestType + "]";
    }

}

Below is the setup of properties

# ==========================================================================
# = JPA / HIBERNATE
# ==========================================================================
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql = true

#60 sec
spring.datasource.hikari.connection-timeout=60000
# max 5
spring.datasource.hikari.maximum-pool-size=5
spring.jpa.hibernate.ddl-auto=update
#============================================================================

Below is the newly created table

'id', 'int(11)', 'NO', 'PRI', NULL, 'auto_increment'
'cntstName', 'varchar(255)', 'YES', '', NULL, ''
'cntstType', 'varchar(255)', 'YES', '', NULL, ''
'phne', 'int(11)', 'YES', '', NULL, ''
'cntst_name', 'varchar(255)', 'YES', '', NULL, ''
'cntst_type', 'varchar(255)', 'YES', '', NULL, ''

Below is the alter query that is being run on running the application.

2019-11-28 13:09:23.092  INFO 10615 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2019-11-28 13:09:23.158  INFO 10615 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.4.8.Final}
2019-11-28 13:09:23.344  INFO 10615 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2019-11-28 13:09:23.446  INFO 10615 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-11-28 13:09:23.450  WARN 10615 --- [           main] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
2019-11-28 13:09:23.669  INFO 10615 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-11-28 13:09:23.688  INFO 10615 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Hibernate: alter table contst_games add column cntst_name varchar(255)
Hibernate: alter table contst_games add column cntst_type varchar(255)
2019-11-28 13:09:24.867  INFO 10615 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2019-11-28 13:09:24.891  INFO 10615 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-11-28 13:09:25.482  WARN 10615 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning

Two new columns cntst_name and cntst_type are being created at runtime. Ideally no new column should be added since the table already exists and spring.jpa.hibernate.ddl-auto=update. Also to be noted no new column for phone number is being created.


问:
Keep same image size while zooming in/out of a website
I stubled upon this website and I would like to know how the design was made:

https://www.zoolana.io/home

There's a background image and some text in the middle, the interesting thing is that no matter how much you zoom in or out, the size of the background image stays the same, only the content changes. How can I replicate the same structure?

答:
This is done by specifying the size of the element in units of viewport height (vh) and/or viewport width (vw).

In the case of your example, the logo in the center is set to width: 55vw, meaning 55% of the viewport's width. The background image is set to height: 100vw, meaning 100% of the viewport's height.


答:
set background-size to cover of div having full width, height & image as background.

*{
    margin:0px;
    padding:0px;
}
div{
    color:white;
    background-image:url("https://images.unsplash.com/photo-1644665154099-57f1f473b0cb?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1469&q=80");
    width:100vw;
    height:100vh;
    background-repeat: no-repeat;
        background-size: cover; /* This to make background image size to cover all dimension of div element.*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  This is testing
</div></code>```

Title: Keep same image size while zooming in/out of a website

Body:
I stubled upon this website and I would like to know how the design was made:

https://www.zoolana.io/home

There's a background image and some text in the middle, the interesting thing is that no matter how much you zoom in or out, the size of the background image stays the same, only the content changes. How can I replicate the same structure?

Body:
set background-size to cover of div having full width, height & image as background.

*{
    margin:0px;
    padding:0px;
}
div{
    color:white;
    background-image:url("https://images.unsplash.com/photo-1644665154099-57f1f473b0cb?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1469&q=80");
    width:100vw;
    height:100vh;
    background-repeat: no-repeat;
        background-size: cover; /* This to make background image size to cover all dimension of div element.*/
}

<div>
  This is testing
</div>


问:
Word2Vec returning vectors for individual character and not words
For the following list:

```<code>words= ['S.B.MILS','Siblings','DEVASTHALY','KOTRESHA','unimodal','7','regarding','random','59','intimating','COMPETITION','prospects','2K15','gather','Mega','SENSOR','NCTT','NETWORKING','orgainsed','acts']
</code>```

I try to:

```<code>from gensim.models import Word2Vec
vec_model= Word2Vec(words, min_count=1, size=30)
vec_model['gather']
</code>```

Which returns:

KeyError: "word 'gather' not in vocabulary"

But

```<code>vec_model['g']
</code>```

Does return a vector, so believe i'm returning all vectors for characters found in the list instead of vectors for all words found in the list.

答:
Word2Vec expects a list of lists as input, where the corpus (main list) is composed of individual documents. The individual documents are composed of individual words (tokens). Word2Vec iterates over all documents and all tokens. In your example you have passed a single list to Word2Vec, therefore Word2Vec interprets each word as an individual document and iterates over each word character which is interpreted as a token. Therefore you have built a vocabulary of characters not words. To build a vocabulary of words you can pass a nested list to Word2Vec as in the example below.

```<code>from gensim.models import Word2Vec

words= [['S.B.MILS','Siblings','DEVASTHALY','KOTRESHA'],
['unimodal','7','regarding','random','59','intimating'],
['COMPETITION','prospects','2K15','gather','Mega'],
['SENSOR','NCTT','NETWORKING','orgainsed','acts']]

vec_model= Word2Vec(words, min_count=1, size=30)
vec_model['gather']
</code>```

Output:

```<code>array([ 0.01106581,  0.00968017, -0.00090574,  0.01115612, -0.00766465,
       -0.01648632, -0.01455364,  0.01107104,  0.00769841,  0.01037362,
        0.01551551, -0.01188449,  0.01262331,  0.01608987,  0.01484082,
        0.00528397,  0.01613582,  0.00437328,  0.00372362,  0.00480989,
       -0.00299072, -0.00261444,  0.00282137, -0.01168992, -0.01402746,
       -0.01165612,  0.00088562,  0.01581018, -0.00671618, -0.00698833],
      dtype=float32)
</code>```

Body:
For the following list:

words= ['S.B.MILS','Siblings','DEVASTHALY','KOTRESHA','unimodal','7','regarding','random','59','intimating','COMPETITION','prospects','2K15','gather','Mega','SENSOR','NCTT','NETWORKING','orgainsed','acts']

I try to:

from gensim.models import Word2Vec
vec_model= Word2Vec(words, min_count=1, size=30)
vec_model['gather']

Which returns:

KeyError: "word 'gather' not in vocabulary"

But

vec_model['g']

Does return a vector, so believe i'm returning all vectors for characters found in the list instead of vectors for all words found in the list.

Body:
Word2Vec expects a list of lists as input, where the corpus (main list) is composed of individual documents. The individual documents are composed of individual words (tokens). Word2Vec iterates over all documents and all tokens. In your example you have passed a single list to Word2Vec, therefore Word2Vec interprets each word as an individual document and iterates over each word character which is interpreted as a token. Therefore you have built a vocabulary of characters not words. To build a vocabulary of words you can pass a nested list to Word2Vec as in the example below.

from gensim.models import Word2Vec

words= [['S.B.MILS','Siblings','DEVASTHALY','KOTRESHA'],
['unimodal','7','regarding','random','59','intimating'],
['COMPETITION','prospects','2K15','gather','Mega'],
['SENSOR','NCTT','NETWORKING','orgainsed','acts']]

vec_model= Word2Vec(words, min_count=1, size=30)
vec_model['gather']

Output:

array([ 0.01106581,  0.00968017, -0.00090574,  0.01115612, -0.00766465,
       -0.01648632, -0.01455364,  0.01107104,  0.00769841,  0.01037362,
        0.01551551, -0.01188449,  0.01262331,  0.01608987,  0.01484082,
        0.00528397,  0.01613582,  0.00437328,  0.00372362,  0.00480989,
       -0.00299072, -0.00261444,  0.00282137, -0.01168992, -0.01402746,
       -0.01165612,  0.00088562,  0.01581018, -0.00671618, -0.00698833],
      dtype=float32)


问:
Is it possible to use core i7 for hard real-time OS?
Some people say the processor is "too smart", so you never know what time will it take to execute some sequence of instructions. I think you always have MIN and MAX time for any instruction and may use the MAX time for your time calculations. </p>

答:
The hard real-time performance really depends on the application and circumstancens. But it's quite a struggle

You need very detailed knowledge about:

CPU

memory management

compilers

your mainboard with it's peripherals

OS

Check here for some ideas:
https://rt.wiki.kernel.org/index.php/HOWTO:_Build_an_RT-application

Next is your time constrains. Is it microseconds, milliseconds or hundreds of milliseconds?
And how hard are your real-time requirements really? Because in a closed loop control you can skip one or two cycles as long as 99.9% of the time you meet the deadline line.

Robotic companies like Kuka are doing it or at least have done it in the past.

In general:

For microseconds precsions: Get a counsulting contract with Intel and
hire someone who has done this before.

For milliseconds precsions: Get a counsulting contract with someone
who has done this before.

And prepare for unforseen issues, because you surely will missed one of the many details!


问:
How to have a scrollbar view in Flutter?

I want to have a scrollbar view like the one in the picture.

So how can I have it using flutter?

I've tried

```<code>SingleChildScrollView(
  ....
),
</code>```

But no scroll bars appeared and I don't know to make them

答:
Wrap the scrollable widget with Scrollbar widget.

```<code>child: Scrollbar(
        isAlwaysShown: true,
        child: ListView(
         ....)
)

</code>```

You can make it always shown.

watch this for further explanation.
https://www.youtube.com/watch?v=DbkIQSvwnZc

Body:
I want to have a scrollbar view like the one in the picture.

So how can I have it using flutter?

I've tried

SingleChildScrollView(
  ....
),

But no scroll bars appeared and I don't know to make them

Body:
Wrap the scrollable widget with Scrollbar widget.

child: Scrollbar(
        isAlwaysShown: true,
        child: ListView(
         ....)
)

You can make it always shown.

watch this for further explanation.
https://www.youtube.com/watch?v=DbkIQSvwnZc


问:
How can bind items details from the listview in flutter?
I need help on how to achive binding items from the list view into other widget. For example, I have a listview of Products to be sold, when a sale person click any product from the list, it should be added on top of the screen with it price, then more product can be added each time a sale person press new product from the listview. I have already tried different ways to achieve this. This is a sample of the screen I want to achieve.

This is what I have achieved so far

```<code>    import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class NewSale extends StatefulWidget {
  const NewSale({Key? key}) : super(key: key);

  @override
  _NewSaleState createState() => _NewSaleState();
}

class _NewSaleState extends State<NewSale> {
  TextEditingController searchingInput = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: IconThemeData(color: Colors.green),
        backgroundColor: Colors.white,
        elevation: 0.0,
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              margin: EdgeInsets.only(top: 8.0),
              child: Text(
                "Sales",
                style: TextStyle(color: Color(0xff444444), fontSize: 19),
              ),
            ),
            Text(
              "Manage Sales",
              style: TextStyle(color: Color(0xffa1a1a1), fontSize: 13),
            ),
          ],
        ),
        actions: [
          Builder(
              builder: (context) => IconButton(
                    icon: Image.asset("assets/images/icons/sync_products.png"),
                    onPressed: () => {},
                  )),
        ],
        leading: Builder(
          builder: (BuildContext context) {
            return IconButton(
              icon: const Icon(
                Icons.arrow_back,
                color: Colors.black,
                size: 40, // Changing Drawer Icon Size
              ),
              onPressed: () {
                Navigator.pop(context);
              },
            );
          },
        ),
      ),
      bottomNavigationBar: new Container(
        height: 70.0,
        padding: EdgeInsets.only(top: 10),
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Flexible(
              child: Container(
                width: MediaQuery.of(context).size.width * 0.4,
                child: Column(
                  children: [
                    MaterialButton(
                      elevation: 0.00,
                      shape: RoundedRectangleBorder(
                          side: BorderSide(
                              color: Color(0xffFA7659),
                              width: 1,
                              style: BorderStyle.solid),
                          borderRadius: BorderRadius.circular(3)),
                      textColor: Colors.white,
                      color: Color(0xffFA7659),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Padding(
                                padding: const EdgeInsets.all(14.0),
                                child: Text('CLEAR',
                                    style: TextStyle(
                                        fontSize: 16,
                                        color: Colors.white,
                                        fontWeight: FontWeight.w300)),
                              ),
                            ],
                          ),
                        ],
                      ),
                      onPressed: () {
                        Navigator.pop(context);
                      },
                    ),
                  ],
                ),
              ),
            ),
            Flexible(
              child: Container(
                width: MediaQuery.of(context).size.width * 0.4,
                child: Column(
                  children: [
                    MaterialButton(
                      elevation: 0.00,
                      shape: RoundedRectangleBorder(
                          side: BorderSide(
                              color: Color(0xff78BD42),
                              width: 1,
                              style: BorderStyle.solid),
                          borderRadius: BorderRadius.circular(3)),
                      textColor: Colors.white,
                      color: Color(0xff78BD42),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Padding(
                                padding: const EdgeInsets.all(14.0),
                                child: Text(
                                  'CONFIRM',
                                  style: TextStyle(
                                      fontSize: 16,
                                      color: Colors.white,
                                      fontWeight: FontWeight.w300),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                      onPressed: () {},
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
      body: SafeArea(
        child: Container(
          color: Colors.red,
          height: MediaQuery.of(context).size.height * 1,
          width: MediaQuery.of(context).size.width * 1,
          child: Column(
            children: [
              Flexible(
                child: Container(
                  height: MediaQuery.of(context).size.height * .5,
                  width: MediaQuery.of(context).size.width * 1,
                  color: Colors.grey,
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      '==== Product Cart ====',
                      style: TextStyle(color: Color(0xff5c5c5c)),
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
              ),
              Flexible(
                child: Container(
                  height: MediaQuery.of(context).size.height * .5,
                  width: MediaQuery.of(context).size.width * 1,
                  color: Colors.white,
                  child: Column(
                    children: [
                      Row(
                        children: [
                          Column(
                            children: [
                              Container(
                                padding: EdgeInsets.fromLTRB(15, 10, 0, 0),
                                child: MaterialButton(
                                  elevation: 0.00,
                                  shape: RoundedRectangleBorder(
                                      side: BorderSide(
                                          color: Color(0xff828282),
                                          width: 1,
                                          style: BorderStyle.solid),
                                      borderRadius: BorderRadius.circular(3)),
                                  textColor: Colors.white,
                                  color: Color(0xff828282),
                                  child: Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.center,
                                        children: [
                                          Row(
                                            children: [
                                              Image.asset(
                                                'assets/images/icons/scan.png',
                                                width: 20,
                                                height: 20,
                                              ),
                                              Padding(
                                                padding:
                                                    const EdgeInsets.all(14.0),
                                                child: Text('SCAN',
                                                    style: TextStyle(
                                                        fontSize: 16,
                                                        color: Colors.white,
                                                        fontWeight:
                                                            FontWeight.w300)),
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                  onPressed: () {},
                                ),
                              ),
                            ],
                          ),
                          Flexible(
                            child: Column(
                              children: [productSearchingField()],
                            ),
                          ),
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Flexible(
                            child: Container(
                              width: MediaQuery.of(context).size.width * 0.6,
                              padding: EdgeInsets.fromLTRB(15, 7, 15, 0),
                              child: Column(
                                children: [
                                  MaterialButton(
                                    elevation: 0.00,
                                    shape: RoundedRectangleBorder(
                                        side: BorderSide(
                                            color: Color(0xff78BD42),
                                            width: 1,
                                            style: BorderStyle.solid),
                                        borderRadius: BorderRadius.circular(3)),
                                    textColor: Colors.white,
                                    color: Color(0xff78BD42),
                                    child: Row(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.center,
                                          children: [
                                            Row(
                                              children: [
                                                Column(
                                                  children: [Icon(Icons.add)],
                                                ),
                                                Column(
                                                  children: [
                                                    Padding(
                                                      padding:
                                                          const EdgeInsets.only(
                                                              top: 14.0,
                                                              bottom: 14.0),
                                                      child: Text(
                                                        'ADD NEW PRODUCT',
                                                        style: TextStyle(
                                                            fontSize: 14,
                                                            color: Colors.white,
                                                            fontWeight:
                                                                FontWeight
                                                                    .w300),
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ],
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                    onPressed: () {},
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                      Flexible(
                        child: Container(
                          child: ListView.builder(
                              itemCount: 10,
                              itemBuilder: (BuildContext context, int index) {
                                return ListTile(
                                  leading: Image.asset(
                                    'assets/images/icons/brand-identity.png',
                                    width: 50,
                                    height: 50,
                                  ),
                                  trailing: Text(
                                    "100,000",
                                    style: TextStyle(
                                        color: Colors.green, fontSize: 15),
                                  ),
                                  title: Text("This is item $index"),
                                  subtitle: Text('Electronics'),
                                );
                              }),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  productSearchingField() {
    return Container(
      padding: EdgeInsets.fromLTRB(15, 10, 15, 0),
      height: 60,
      child: TextFormField(
        controller: searchingInput,
        decoration: InputDecoration(
          border: OutlineInputBorder(),
          labelText: 'Search Product or Barcode',
          prefixIcon: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Icon(
                Icons.search,
                color: Colors.black54,
              )),
        ),
      ),
    );
  }
}
</code>```

答:
Here i manage to do this using the below code hope it will work for you</p>
```<code>  class _DummyDesignState extends State<DummyDesign> {

  List<String> ShoppingItems = ['Ball', 'Clet', 'JoyStick'];
  List<String> PurchasedItem = [];

  @override
  Widget build(BuildContext context) {
    print('List length is ${ShoppingItems.length}');
    print('List length is ${PurchasedItem.length}');
    return Scaffold(
        appBar: AppBar(
          title: Text('Hello'),
        ),
        body: PurchasedItem.isEmpty
            ? Center(
                child: Container(
                  height: MediaQuery.of(context).size.height * 0.2,
                  child: ListView.builder(
                      itemCount: ShoppingItems.length,
                      itemBuilder: (context, index) {
                        return ListTile(
                            onTap: (){
                              PurchasedItem.add(ShoppingItems[index]);
                              setState(() {

                              });
                            },
                            leading: Icon(Icons.list),
                            title: Text(
                              ShoppingItems[index],
                              style: TextStyle(color: Colors.green, fontSize: 15),
                            ));
                      }),
                ),
              )
            : Center(
                child: SingleChildScrollView(
                  child: Column(
                    children: <Widget>[
                      SizedBox(
                        height: MediaQuery.of(context).size.height * 0.4,
                        child: ListView.builder(
                            itemCount: PurchasedItem.length,
                            itemBuilder: (context, index) {
                              return Text(PurchasedItem[index]);
                            }),
                      ),
                      Container(
                        height: MediaQuery.of(context).size.height * 0.4,
                        child: ListView.builder(
                            itemCount: ShoppingItems.length,
                            itemBuilder: (context, index) {
                              return ListTile(
                                onTap: (){
                                  PurchasedItem.add(ShoppingItems[index]);
                                  setState(() {

                                  });
                                },
                                  leading: Icon(Icons.list),
                                  title: Text(
                                    ShoppingItems[index],
                                    style: TextStyle(color: Colors.green, fontSize: 15),
                                  ));
                            }),
                      ),
                    ],
                  ),
                ),
              ));
  }
}
</code>```

Body:
I need help on how to achive binding items from the list view into other widget. For example, I have a listview of Products to be sold, when a sale person click any product from the list, it should be added on top of the screen with it price, then more product can be added each time a sale person press new product from the listview. I have already tried different ways to achieve this. This is a sample of the screen I want to achieve.

This is what I have achieved so far

    import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class NewSale extends StatefulWidget {
  const NewSale({Key? key}) : super(key: key);

  @override
  _NewSaleState createState() => _NewSaleState();
}

class _NewSaleState extends State<NewSale> {
  TextEditingController searchingInput = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: IconThemeData(color: Colors.green),
        backgroundColor: Colors.white,
        elevation: 0.0,
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              margin: EdgeInsets.only(top: 8.0),
              child: Text(
                "Sales",
                style: TextStyle(color: Color(0xff444444), fontSize: 19),
              ),
            ),
            Text(
              "Manage Sales",
              style: TextStyle(color: Color(0xffa1a1a1), fontSize: 13),
            ),
          ],
        ),
        actions: [
          Builder(
              builder: (context) => IconButton(
                    icon: Image.asset("assets/images/icons/sync_products.png"),
                    onPressed: () => {},
                  )),
        ],
        leading: Builder(
          builder: (BuildContext context) {
            return IconButton(
              icon: const Icon(
                Icons.arrow_back,
                color: Colors.black,
                size: 40, // Changing Drawer Icon Size
              ),
              onPressed: () {
                Navigator.pop(context);
              },
            );
          },
        ),
      ),
      bottomNavigationBar: new Container(
        height: 70.0,
        padding: EdgeInsets.only(top: 10),
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Flexible(
              child: Container(
                width: MediaQuery.of(context).size.width * 0.4,
                child: Column(
                  children: [
                    MaterialButton(
                      elevation: 0.00,
                      shape: RoundedRectangleBorder(
                          side: BorderSide(
                              color: Color(0xffFA7659),
                              width: 1,
                              style: BorderStyle.solid),
                          borderRadius: BorderRadius.circular(3)),
                      textColor: Colors.white,
                      color: Color(0xffFA7659),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Padding(
                                padding: const EdgeInsets.all(14.0),
                                child: Text('CLEAR',
                                    style: TextStyle(
                                        fontSize: 16,
                                        color: Colors.white,
                                        fontWeight: FontWeight.w300)),
                              ),
                            ],
                          ),
                        ],
                      ),
                      onPressed: () {
                        Navigator.pop(context);
                      },
                    ),
                  ],
                ),
              ),
            ),
            Flexible(
              child: Container(
                width: MediaQuery.of(context).size.width * 0.4,
                child: Column(
                  children: [
                    MaterialButton(
                      elevation: 0.00,
                      shape: RoundedRectangleBorder(
                          side: BorderSide(
                              color: Color(0xff78BD42),
                              width: 1,
                              style: BorderStyle.solid),
                          borderRadius: BorderRadius.circular(3)),
                      textColor: Colors.white,
                      color: Color(0xff78BD42),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Padding(
                                padding: const EdgeInsets.all(14.0),
                                child: Text(
                                  'CONFIRM',
                                  style: TextStyle(
                                      fontSize: 16,
                                      color: Colors.white,
                                      fontWeight: FontWeight.w300),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                      onPressed: () {},
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
      body: SafeArea(
        child: Container(
          color: Colors.red,
          height: MediaQuery.of(context).size.height * 1,
          width: MediaQuery.of(context).size.width * 1,
          child: Column(
            children: [
              Flexible(
                child: Container(
                  height: MediaQuery.of(context).size.height * .5,
                  width: MediaQuery.of(context).size.width * 1,
                  color: Colors.grey,
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      '==== Product Cart ====',
                      style: TextStyle(color: Color(0xff5c5c5c)),
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
              ),
              Flexible(
                child: Container(
                  height: MediaQuery.of(context).size.height * .5,
                  width: MediaQuery.of(context).size.width * 1,
                  color: Colors.white,
                  child: Column(
                    children: [
                      Row(
                        children: [
                          Column(
                            children: [
                              Container(
                                padding: EdgeInsets.fromLTRB(15, 10, 0, 0),
                                child: MaterialButton(
                                  elevation: 0.00,
                                  shape: RoundedRectangleBorder(
                                      side: BorderSide(
                                          color: Color(0xff828282),
                                          width: 1,
                                          style: BorderStyle.solid),
                                      borderRadius: BorderRadius.circular(3)),
                                  textColor: Colors.white,
                                  color: Color(0xff828282),
                                  child: Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.center,
                                        children: [
                                          Row(
                                            children: [
                                              Image.asset(
                                                'assets/images/icons/scan.png',
                                                width: 20,
                                                height: 20,
                                              ),
                                              Padding(
                                                padding:
                                                    const EdgeInsets.all(14.0),
                                                child: Text('SCAN',
                                                    style: TextStyle(
                                                        fontSize: 16,
                                                        color: Colors.white,
                                                        fontWeight:
                                                            FontWeight.w300)),
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                  onPressed: () {},
                                ),
                              ),
                            ],
                          ),
                          Flexible(
                            child: Column(
                              children: [productSearchingField()],
                            ),
                          ),
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Flexible(
                            child: Container(
                              width: MediaQuery.of(context).size.width * 0.6,
                              padding: EdgeInsets.fromLTRB(15, 7, 15, 0),
                              child: Column(
                                children: [
                                  MaterialButton(
                                    elevation: 0.00,
                                    shape: RoundedRectangleBorder(
                                        side: BorderSide(
                                            color: Color(0xff78BD42),
                                            width: 1,
                                            style: BorderStyle.solid),
                                        borderRadius: BorderRadius.circular(3)),
                                    textColor: Colors.white,
                                    color: Color(0xff78BD42),
                                    child: Row(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.center,
                                          children: [
                                            Row(
                                              children: [
                                                Column(
                                                  children: [Icon(Icons.add)],
                                                ),
                                                Column(
                                                  children: [
                                                    Padding(
                                                      padding:
                                                          const EdgeInsets.only(
                                                              top: 14.0,
                                                              bottom: 14.0),
                                                      child: Text(
                                                        'ADD NEW PRODUCT',
                                                        style: TextStyle(
                                                            fontSize: 14,
                                                            color: Colors.white,
                                                            fontWeight:
                                                                FontWeight
                                                                    .w300),
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ],
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                    onPressed: () {},
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                      Flexible(
                        child: Container(
                          child: ListView.builder(
                              itemCount: 10,
                              itemBuilder: (BuildContext context, int index) {
                                return ListTile(
                                  leading: Image.asset(
                                    'assets/images/icons/brand-identity.png',
                                    width: 50,
                                    height: 50,
                                  ),
                                  trailing: Text(
                                    "100,000",
                                    style: TextStyle(
                                        color: Colors.green, fontSize: 15),
                                  ),
                                  title: Text("This is item $index"),
                                  subtitle: Text('Electronics'),
                                );
                              }),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  productSearchingField() {
    return Container(
      padding: EdgeInsets.fromLTRB(15, 10, 15, 0),
      height: 60,
      child: TextFormField(
        controller: searchingInput,
        decoration: InputDecoration(
          border: OutlineInputBorder(),
          labelText: 'Search Product or Barcode',
          prefixIcon: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Icon(
                Icons.search,
                color: Colors.black54,
              )),
        ),
      ),
    );
  }
}

Body:
Here i manage to do this using the below code hope it will work for you

  class _DummyDesignState extends State<DummyDesign> {

  List<String> ShoppingItems = ['Ball', 'Clet', 'JoyStick'];
  List<String> PurchasedItem = [];

  @override
  Widget build(BuildContext context) {
    print('List length is ${ShoppingItems.length}');
    print('List length is ${PurchasedItem.length}');
    return Scaffold(
        appBar: AppBar(
          title: Text('Hello'),
        ),
        body: PurchasedItem.isEmpty
            ? Center(
                child: Container(
                  height: MediaQuery.of(context).size.height * 0.2,
                  child: ListView.builder(
                      itemCount: ShoppingItems.length,
                      itemBuilder: (context, index) {
                        return ListTile(
                            onTap: (){
                              PurchasedItem.add(ShoppingItems[index]);
                              setState(() {

                              });
                            },
                            leading: Icon(Icons.list),
                            title: Text(
                              ShoppingItems[index],
                              style: TextStyle(color: Colors.green, fontSize: 15),
                            ));
                      }),
                ),
              )
            : Center(
                child: SingleChildScrollView(
                  child: Column(
                    children: <Widget>[
                      SizedBox(
                        height: MediaQuery.of(context).size.height * 0.4,
                        child: ListView.builder(
                            itemCount: PurchasedItem.length,
                            itemBuilder: (context, index) {
                              return Text(PurchasedItem[index]);
                            }),
                      ),
                      Container(
                        height: MediaQuery.of(context).size.height * 0.4,
                        child: ListView.builder(
                            itemCount: ShoppingItems.length,
                            itemBuilder: (context, index) {
                              return ListTile(
                                onTap: (){
                                  PurchasedItem.add(ShoppingItems[index]);
                                  setState(() {

                                  });
                                },
                                  leading: Icon(Icons.list),
                                  title: Text(
                                    ShoppingItems[index],
                                    style: TextStyle(color: Colors.green, fontSize: 15),
                                  ));
                            }),
                      ),
                    ],
                  ),
                ),
              ));
  }
}