问:
How to improve performance of setting HTML video currentTime in LitElement
I am using a range input slider to capture user input:

```<code><input class="slider" type="range" oninput="change">
</code>```

There also is a video:

```<code><video class"output" src="video.mp4"></video>
</code>```

My JavaScript function change looks something like this:

```<code>change(e){
this.shadowRoot.querySelector('.output').currentTime = this.shadowRoot.querySelector('.slider').value;
}
</code>```

This works and I can control the video current time with the slider. However, it is quite laggy and performance isn't as good as I think it could be.
Is there any smarter/more performant way of doing this?

Thanks!

答:
Selecting the elements on each input event is probably not very performant and should be done just once (ie in firstUpdated()). However if you don't have a specific reason for manually selecting the elements, consider using lit-html bindings instead:

import { LitElement, html, property, customElement } from 'lit-element';

@customElement('my-video')
export class MyVideo extends LitElement {
  @property() currentTime = 0;

  render() {
    return html`
      <video src="..." .currentTime=${this.currentTime}></video>
      <input type="range" @input=${e => this.currentTime = e.target.value}>
    `;
  }
}
```

Here's a demo.

Body:
I am using a range input slider to capture user input:

<input class="slider" type="range" oninput="change">

There also is a video:

<video class"output" src="video.mp4"></video>

My JavaScript function change looks something like this:

change(e){
this.shadowRoot.querySelector('.output').currentTime = this.shadowRoot.querySelector('.slider').value;
}

This works and I can control the video current time with the slider. However, it is quite laggy and performance isn't as good as I think it could be.
Is there any smarter/more performant way of doing this?

Thanks!

Body:
Selecting the elements on each input event is probably not very performant and should be done just once (ie in firstUpdated()). However if you don't have a specific reason for manually selecting the elements, consider using lit-html bindings instead:

import { LitElement, html, property, customElement } from 'lit-element';

@customElement('my-video')
export class MyVideo extends LitElement {
  @property() currentTime = 0;

  render() {
    return html`
      <video src="..." .currentTime=${this.currentTime}></video>
      <input type="range" @input=${e => this.currentTime = e.target.value}>
    `;
  }
}

Here's a demo.


来源: stackexchange

问:
Automatic update from database
I'm developing in WPF and want my DataGrid to automatically refresh when there's a change in the DB, and vice versa.

Today I'm using Timers and simple Selects to perform the updates.
Is there something in .Net that provides that functionality ?

答:
try to use SQL Server Notification Services.
i didn't use it before but u can do that using it</p>

ContentLicense: CC BY-SA 3.0

Title: Automatic update from database


问:
No module named 'sklearn.svm._classes' when loading model from colab
I've trained a model on google colab and want to load it on my local machine. But I get ModuleNotFoundError: No module named 'sklearn.svm._classes'. Loading the model on colab, is no problem.

colab:

```<code>[1] import sys
    sys.version
'3.6.9 (default, Nov  7 2019, 10:44:02) \n[GCC 8.3.0]'
[2] import joblib
    import numpy as np
    from sklearn import svm
    clf = svm.SVC(gamma=0.001)
    clf.fit(np.random.rand(9,8).astype(int), np.arange(9))
    joblib.dump(clf, 'simple_classifier')
[3] joblib.load('simple_classifier')
</code>```

My local machine:

```<code>>>> import sys
>>> sys.version
'3.6.9 (default, Nov  7 2019, 10:44:02) \n[GCC 8.3.0]'
>>> import numpy as np
>>> import joblib
>>> from sklearn import svm
>>> joblib.load('simple_classifier')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/.../ml-env/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 605, in load
    obj = _unpickle(fobj, filename, mmap_mode)
  File "/home/.../ml-env/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 529, in _unpickle
    obj = unpickler.load()
  File "/usr/lib/python3.6/pickle.py", line 1050, in load
    dispatch[key[0]](self)
  File "/usr/lib/python3.6/pickle.py", line 1338, in load_global
    klass = self.find_class(module, name)
  File "/usr/lib/python3.6/pickle.py", line 1388, in find_class
    __import__(module, level=0)
ModuleNotFoundError: No module named 'sklearn.svm._classes'
</code>```

答:
Upgrade the sklearn library using:

```<code>pip install scikit-learn --upgrade
</code>```

Occurs when the model was built with a specific version of the library and tested with other versions.

ContentLicense: CC BY-SA 4.0

Body:
I've trained a model on google colab and want to load it on my local machine. But I get ModuleNotFoundError: No module named 'sklearn.svm._classes'. Loading the model on colab, is no problem.

colab:

[1] import sys
    sys.version
'3.6.9 (default, Nov  7 2019, 10:44:02) \n[GCC 8.3.0]'
[2] import joblib
    import numpy as np
    from sklearn import svm
    clf = svm.SVC(gamma=0.001)
    clf.fit(np.random.rand(9,8).astype(int), np.arange(9))
    joblib.dump(clf, 'simple_classifier')
[3] joblib.load('simple_classifier')

My local machine:

>>> import sys
>>> sys.version
'3.6.9 (default, Nov  7 2019, 10:44:02) \n[GCC 8.3.0]'
>>> import numpy as np
>>> import joblib
>>> from sklearn import svm
>>> joblib.load('simple_classifier')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/.../ml-env/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 605, in load
    obj = _unpickle(fobj, filename, mmap_mode)
  File "/home/.../ml-env/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 529, in _unpickle
    obj = unpickler.load()
  File "/usr/lib/python3.6/pickle.py", line 1050, in load
    dispatch[key[0]](self)
  File "/usr/lib/python3.6/pickle.py", line 1338, in load_global
    klass = self.find_class(module, name)
  File "/usr/lib/python3.6/pickle.py", line 1388, in find_class
    __import__(module, level=0)
ModuleNotFoundError: No module named 'sklearn.svm._classes'

Body:
Upgrade the sklearn library using:

pip install scikit-learn --upgrade

Occurs when the model was built with a specific version of the library and tested with other versions.


问:
How get products from product table based on the category search in django restframework, How do inner join in django restframework
I am very much new in django restframework,I tried to create a search api.

I have 2 models designed

```<code>class Category(models.Model):
    name = models.CharField(max_length=200)

    def __str__(self):
        return self.name

class Product(models.Model):
    product_name = models.CharField(max_length=255)
    product_Comments = models.CharField(max_length=255)
    size = models.CharField(max_length=10, null=True)
    product_Status = models.BooleanField(default=True)
    category = models.ForeignKey(Category,  on_delete=models.CASCADE, null=True)

    def __str__(self):
        return self.product_Description
</code>```

I want to create a rest API, in which I can search the category and based on the search i want to list the product which related to that category. How can I do it.

My Views.py

```<code>class productList(generics.ListAPIView):
   serializer_class = productSerializer
   def get_queryset(self):
       queryset = Product.objects.all()
       search = self.request.query_params.get('search', None)
       if search is not None:
           queryset = queryset.filter(product_name__icontains=search)
</code>```

my urls

```<code>path('product_search/',views.productList.as_view()),
</code>```

答:
For filtering the Products based on category name is,</p>

```<code>Product.object.filter( category__name = 'category_name')
</code>```

Body:
I am very much new in django restframework,I tried to create a search api.

I have 2 models designed

class Category(models.Model):
    name = models.CharField(max_length=200)

    def __str__(self):
        return self.name

class Product(models.Model):
    product_name = models.CharField(max_length=255)
    product_Comments = models.CharField(max_length=255)
    size = models.CharField(max_length=10, null=True)
    product_Status = models.BooleanField(default=True)
    category = models.ForeignKey(Category,  on_delete=models.CASCADE, null=True)

    def __str__(self):
        return self.product_Description

I want to create a rest API, in which I can search the category and based on the search i want to list the product which related to that category. How can I do it.

My Views.py

class productList(generics.ListAPIView):
   serializer_class = productSerializer
   def get_queryset(self):
       queryset = Product.objects.all()
       search = self.request.query_params.get('search', None)
       if search is not None:
           queryset = queryset.filter(product_name__icontains=search)

my urls

path('product_search/',views.productList.as_view()),

Body:
For filtering the Products based on category name is,

Product.object.filter( category__name = 'category_name')


问:
Is there a way to schedule Cloud Shell commands in Google Cloud Platform?
I want to schedule some of my BigQuery table load commands that I execute in the Cloud Shell CLI. How can I schedule my CLI commands in Google Cloud Platform?</p>

答:
Cloud Shell isn't a tool intended to use as part of your production environment, you should take a look into it's terms and conditions. you might find this part especially blocking for this purpose:

Non-interactive sessions will be ended automatically after a warning.
  Note that Cloud Shell sessions are capped at 12 hours, after which
  sessions are automatically terminated.

What you can actually do is to create a Cloud Function and trigger it by a cron job or use a Compute Engine instance and schedule a command on linux


问:
bash integration with terraform
i am writing az copy script which captures linux 18.04 system log using azcopy and store it into storage account container, but this whole steps I am doing with terraform automation. i have created machine code and I integrate shell script file with terraform extension.

so the issue is when azcopy copy the file from system and pass to a storage account need azcopy login to authenticate this process but these steps we can't perform through automation.

using following azcopy script and version is v10 please help me on this

```<code>AzCopy /Source:/var/log/syslog/Dest:https://testingwt.blob.core.windows.net/insights-operational-logs//SourceKey:y/bUACOu/wogikUT1EG0XeaPC4Y6spHcZly2d26QeENKwMiRpjFu5PwmXrThRbNGS3PiPfqEX8WsYC3dg== /S
</code>```

updated error of azcopy using linux machine in azure

答:
To upload files to the Storage Blob with a shell script automatically, you can use the SAS token of the storage, or use the azcopy login with a service principal or the VM managed identity.

For the SAS token:

```<code>azcopy copy "/path/to/file" "https://account.blob.core.windows.net/mycontainer1/?sv=2018-03-28&ss=bjqt&srt=sco&sp=rwddgcup&se=2019-05-01T05:01:17Z&st=2019-04-30T21:01:17Z&spr=https&sig=MGCXiyEzbtttkr3ewJIh2AR8KrghSy1DGM9ovN734bQF4%3D" --recursive=true
</code>```

For the Service Principal, you need to set the environment variable AZCOPY_SPA_CLIENT_SECRET with the secret of the service principal as value and assign the role Storage Blob Data Contributor or role Storage Blob Data Owner of the storage Blob:

```<code>azcopy login --service-principal --application-id <application-id> --tenant-id=<tenant-id>
azcopy copy "/path/to/file" "https://account.blob.core.windows.net/mycontainer1/" --recursive=true
</code>```

For the VM managed identity, you need also to assign the VM managed identity with the role Storage Blob Data Contributor or role Storage Blob Data Owner of the storage Blob:

```<code>azcopy login --identity
azcopy copy "/path/to/file" "https://account.blob.core.windows.net/mycontainer1/" --recursive=true
</code>```

But when you use the VM managed identity, you need to execute the shell script in the Azure VM, it means you need to deploy the Terraform in the Azure VM. So the best way is that use a service principal, you can execute the shell script in other Linux OS, for example, your local Linux machine. The SAS token is also a good way without assigning the role. For more details, see the Use Azcopy for the Azure Storage Blob.

Title: bash integration with terraform

Body:
i am writing az copy script which captures linux 18.04 system log using azcopy and store it into storage account container, but this whole steps I am doing with terraform automation. i have created machine code and I integrate shell script file with terraform extension.

so the issue is when azcopy copy the file from system and pass to a storage account need azcopy login to authenticate this process but these steps we can't perform through automation.

using following azcopy script and version is v10 please help me on this

AzCopy /Source:/var/log/syslog/Dest:https://testingwt.blob.core.windows.net/insights-operational-logs//SourceKey:y/bUACOu/wogikUT1EG0XeaPC4Y6spHcZly2d26QeENKwMiRpjFu5PwmXrThRbNGS3PiPfqEX8WsYC3dg== /S

updated error of azcopy using linux machine in azure

Body:
To upload files to the Storage Blob with a shell script automatically, you can use the SAS token of the storage, or use the azcopy login with a service principal or the VM managed identity.

For the SAS token:

azcopy copy "/path/to/file" "https://account.blob.core.windows.net/mycontainer1/?sv=2018-03-28&ss=bjqt&srt=sco&sp=rwddgcup&se=2019-05-01T05:01:17Z&st=2019-04-30T21:01:17Z&spr=https&sig=MGCXiyEzbtttkr3ewJIh2AR8KrghSy1DGM9ovN734bQF4%3D" --recursive=true

For the Service Principal, you need to set the environment variable AZCOPY_SPA_CLIENT_SECRET with the secret of the service principal as value and assign the role Storage Blob Data Contributor or role Storage Blob Data Owner of the storage Blob:

azcopy login --service-principal --application-id <application-id> --tenant-id=<tenant-id>
azcopy copy "/path/to/file" "https://account.blob.core.windows.net/mycontainer1/" --recursive=true

For the VM managed identity, you need also to assign the VM managed identity with the role Storage Blob Data Contributor or role Storage Blob Data Owner of the storage Blob:

azcopy login --identity
azcopy copy "/path/to/file" "https://account.blob.core.windows.net/mycontainer1/" --recursive=true

But when you use the VM managed identity, you need to execute the shell script in the Azure VM, it means you need to deploy the Terraform in the Azure VM. So the best way is that use a service principal, you can execute the shell script in other Linux OS, for example, your local Linux machine. The SAS token is also a good way without assigning the role. For more details, see the Use Azcopy for the Azure Storage Blob.


问:
How to extract specific patterns from HTML with BeautifulSoup
I'm trying to extract some specific parts of an HTML with repeated pattern inside.

Pattern looks like this:

```<code><script type="text/javascript">
    $(document).ready(function() {
        itemJS.ProductsList({"Status":"true",
            "description":"sku_01",
            "id": "00000001"
        });
    });
</script>
</code>```

Unfortunately this HTML has many javascripts inside and i'm interested in the above pattern only .
Using BeatifulSoup library, i can get all "javascripts" in HTML with find.All function:

```<code>soup.findAll('script', attrs={"type": "text/javascript"})
</code>```

But how to extract these specific patterns only ?
I would like to obtain this "dict" as results:

```<code>({"Status":"true",
 "description":"sku_01",
 "id": "00000001"
})
</code>```

Thanks

答:
You can use .find() with text= parameter, then re/json module to decode data.

For example:

```<code>import re
import json
from bs4 import BeautifulSoup

txt = '''
<script type="text/javascript">
    $(document).ready(function() {
        itemJS.ProductsList({"Status":"true",
            "description":"sku_01",
            "id": "00000001"
        });
    });
</script>'''

soup = BeautifulSoup(txt, 'html.parser')

# locate the <script>
t = soup.find('script', text=lambda t: 'ProductsList' in t).contents[0]

# get the raw string using `re` module
json_data = re.search(r'itemJS\.ProductsList\((.*?)\);', t, flags=re.DOTALL).group(1)

# decode the data
json_data = json.loads(json_data)

# print the data to screen
print(json.dumps(json_data, indent=4))
</code>```

Prints:

```<code>{
    "Status": "true",
    "description": "sku_01",
    "id": "00000001"
}
</code>```

EDIT: If you have multiple <scipt> tags, you can do:

```<code>import re
import json
from bs4 import BeautifulSoup

txt = '''
<script type="text/javascript">
    $(document).ready(function() {
        itemJS.ProductsList({"Status":"true",
            "description":"sku_01",
            "id": "00000001"
        });
    });
</script>

<script type="text/javascript">
    $(document).ready(function() {
        itemJS.ProductsList({"Status":"true",
            "description":"sku_02",
            "id": "00000002"
        });
    });
</script>
'''

soup = BeautifulSoup(txt, 'html.parser')

for script_tag in soup.find_all('script', text=lambda t: 'ProductsList' in t):
    json_data = re.search(r'itemJS\.ProductsList\((.*?)\);', script_tag.contents[0], flags=re.DOTALL).group(1)
    json_data = json.loads(json_data)
    print(json.dumps(json_data, indent=4))
</code>```

This prints:

```<code>{
    "Status": "true",
    "description": "sku_01",
    "id": "00000001"
}
{
    "Status": "true",
    "description": "sku_02",
    "id": "00000002"
}
</code>```

Body:
I'm trying to extract some specific parts of an HTML with repeated pattern inside.

Pattern looks like this:

Unfortunately this HTML has many javascripts inside and i'm interested in the above pattern only .
Using BeatifulSoup library, i can get all "javascripts" in HTML with find.All function:

soup.findAll('script', attrs={"type": "text/javascript"})

But how to extract these specific patterns only ?
I would like to obtain this "dict" as results:

({"Status":"true",
 "description":"sku_01",
 "id": "00000001"
})

Thanks

Body:
You can use .find() with text= parameter, then re/json module to decode data.

For example:

import re
import json
from bs4 import BeautifulSoup

txt = '''
<script type="text/javascript">
    $(document).ready(function() {
        itemJS.ProductsList({"Status":"true",
            "description":"sku_01",
            "id": "00000001"
        });
    });
</script>'''

soup = BeautifulSoup(txt, 'html.parser')

# locate the <script>
t = soup.find('script', text=lambda t: 'ProductsList' in t).contents[0]

# get the raw string using `re` module
json_data = re.search(r'itemJS\.ProductsList\((.*?)\);', t, flags=re.DOTALL).group(1)

# decode the data
json_data = json.loads(json_data)

# print the data to screen
print(json.dumps(json_data, indent=4))

Prints:

{
    "Status": "true",
    "description": "sku_01",
    "id": "00000001"
}

EDIT: If you have multiple <scipt> tags, you can do:

import re
import json
from bs4 import BeautifulSoup

txt = '''
<script type="text/javascript">
    $(document).ready(function() {
        itemJS.ProductsList({"Status":"true",
            "description":"sku_01",
            "id": "00000001"
        });
    });
</script>

<script type="text/javascript">
    $(document).ready(function() {
        itemJS.ProductsList({"Status":"true",
            "description":"sku_02",
            "id": "00000002"
        });
    });
</script>
'''

soup = BeautifulSoup(txt, 'html.parser')

for script_tag in soup.find_all('script', text=lambda t: 'ProductsList' in t):
    json_data = re.search(r'itemJS\.ProductsList\((.*?)\);', script_tag.contents[0], flags=re.DOTALL).group(1)
    json_data = json.loads(json_data)
    print(json.dumps(json_data, indent=4))

This prints:

{
    "Status": "true",
    "description": "sku_01",
    "id": "00000001"
}
{
    "Status": "true",
    "description": "sku_02",
    "id": "00000002"
}


问:
Set div width equal to window size
I have a container of width 1300 px. Inside the container i have other div.

I need to set the inner div width equal to browser window size eg) 1900px.

The content should be responsive to the window size.

My html code is like below:

```<code><div class="container">
  <div class="content">Some style goes here </div>
</div>
</code>```

Css:

```<code>.container {
   width: 1300px;
}

.content{
  width: 100%
}`
</code>```

答:
remove default(bootstrap) max-width of container and set content width to 100%</p>

```<code>.content{
      width: 100%;
}

.contianer{
       max-width: none;
}
</code>```

Title: Set div width equal to window size

Body:
I have a container of width 1300 px. Inside the container i have other div.

I need to set the inner div width equal to browser window size eg) 1900px.

The content should be responsive to the window size.

My html code is like below:

Some style goes here

Css:

.container {
   width: 1300px;
}

.content{
  width: 100%
}`

Body:
remove default(bootstrap) max-width of container and set content width to 100%

.content{
      width: 100%;
}

.contianer{
       max-width: none;
}


问:
How to map values from selected checkboxes to state using ngrx-forms?
I want to map selected checkboxes to state using ngrx-forms.

I have found similar example, but it uses selects for outputting selected values.

How can I change this example to use checkboxes instead of select, so that final result well be something like that?

答: For the checkboxes it won't work and you need to write your own wrapper that listens to all of them, combines their states and updates the ngrx forms.</p>


问:
cURL says certificate is expired, Firefox disagrees
I'm trying to access an internal site via cURL (which I could access several days ago). However, cURL gives the error curl: (60) SSL certificate problem: certificate has expired. If I use openssl to check the start and end dates of the certificate, it gives a timeframe that I'm well within:

```<code>echo | openssl s_client -connect internalsite.example.com:443 2>/dev/null | openssl x509 -noout -dates
notBefore=Nov 30 00:00:00 2012 GMT
notAfter=Mar 30 12:00:00 2016 GMT
# For reference, the day I'm posting this is July 30th, 2014
</code>```

Additionally, if I use cURL on a different computer, or connect via the browser (Firefox, Chrome, or IE), I can connect without error.

Also, I'm unable to connect with any version of cURL on my own computer; this includes cURL in Cygwin and cURL on Ubuntu inside a virtual machine, as well as the Windows version.

What might give rise to this behaviour?

答:
If you need a quick and temporary workaround, you can always disable SSL verification, as shown below. Don’t do that if you can avoid it, especially in production or if that request is transmitting sensitive data. Remember that you might be making a request to https://stackoverflow.com but actually sending data to another computer entirely.</p>
```<code>curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
</code>```

Body:
I'm trying to access an internal site via cURL (which I could access several days ago). However, cURL gives the error curl: (60) SSL certificate problem: certificate has expired. If I use openssl to check the start and end dates of the certificate, it gives a timeframe that I'm well within:

echo | openssl s_client -connect internalsite.example.com:443 2>/dev/null | openssl x509 -noout -dates
notBefore=Nov 30 00:00:00 2012 GMT
notAfter=Mar 30 12:00:00 2016 GMT
# For reference, the day I'm posting this is July 30th, 2014

Additionally, if I use cURL on a different computer, or connect via the browser (Firefox, Chrome, or IE), I can connect without error.

Also, I'm unable to connect with any version of cURL on my own computer; this includes cURL in Cygwin and cURL on Ubuntu inside a virtual machine, as well as the Windows version.

What might give rise to this behaviour?

Body:
If you need a quick and temporary workaround, you can always disable SSL verification, as shown below. Don’t do that if you can avoid it, especially in production or if that request is transmitting sensitive data. Remember that you might be making a request to https://stackoverflow.com but actually sending data to another computer entirely.

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);


问:
how to save image,audio,video files to database as link?
i m not getting how to store a file to database so that at time application is uploaded to webserver user can download that file.
till now i was just saving the file name to database and it is wrong.so do i need to save the link to database?
i m getting confused?any suggession?
till now i m using this code to store file in database,</p>

```<code>protected void dbInsert(string fileType,string fileName,string fileExt)
{
     String getSQL1 = "INSERT into tbluploadedfilesdetail (FileDownloaded,FileType,FileName,FileExt) VALUES ("+0+",'"+fileType+"','"+fileName+"','"+fileExt+"');";

     MySqlConnection objMyCon1 = new MySqlConnection(strProvider);
     objMyCon1.Open();

     MySqlCommand cmd1 = new MySqlCommand(getSQL1, objMyCon1);
     cmd1.ExecuteNonQuery();
     objMyCon1.Close();
     dbLoad();
}
</code>```

答:
All you are doing here is saving the filename to the server, not the actual file. If you want to save a file to a database then the database field type needs to be binary. There are a lot of tutorials online to show you how. See http://www.codeproject.com/KB/aspnet/fileupload.aspx

For MySql you should use BLOB type or it's alternatives. Check out http://www.abbeyworkshop.com/howto/lamp/my_fieldtypes/index.html

Body:
i m not getting how to store a file to database so that at time application is uploaded to webserver user can download that file.
till now i was just saving the file name to database and it is wrong.so do i need to save the link to database?
i m getting confused?any suggession?
till now i m using this code to store file in database,

protected void dbInsert(string fileType,string fileName,string fileExt)
{
     String getSQL1 = "INSERT into tbluploadedfilesdetail (FileDownloaded,FileType,FileName,FileExt) VALUES ("+0+",'"+fileType+"','"+fileName+"','"+fileExt+"');";

     MySqlConnection objMyCon1 = new MySqlConnection(strProvider);
     objMyCon1.Open();

     MySqlCommand cmd1 = new MySqlCommand(getSQL1, objMyCon1);
     cmd1.ExecuteNonQuery();
     objMyCon1.Close();
     dbLoad();
}


问:
Query on a view ,Postgres and Laravel
I try to do a query on a view from DB,  with Laravel but I get an error, and I am not sure why.

```<code>ViewData::query()->where('page', '=', '918');
</code>```

"SQLSTATE[42601]: Syntax error: 7 ERROR:  zero-length delimited
  identifier at or near """"↵LINE 1: ...data" where "page" = $1 order by
  "view_full_data"."" asc lim...↵

  ^ (SQL: select * from "view_full_data" where "page" = 918 order by
  "view_full_data"."" asc limit 1000 offset 0)"

From Postgres, a working one.

```<code>Select * from view_full_data where "page = 918;
</code>```

答:
I found the problem.

From Maatwebsite\Excel I get an order_by that is not ok (Maybe because I don't have an ID column).

I had to add orderBy manually.

```<code>ViewData::query()->where("page", '=', "918")->orderBy('page', 'asc');
</code>```

Title: Query on a view ,Postgres and Laravel

Body:
I try to do a query on a view from DB,  with Laravel but I get an error, and I am not sure why.

ViewData::query()->where('page', '=', '918');

"SQLSTATE[42601]: Syntax error: 7 ERROR:  zero-length delimited
  identifier at or near """"↵LINE 1: ...data" where "page" = $1 order by
  "view_full_data"."" asc lim...↵

  ^ (SQL: select * from "view_full_data" where "page" = 918 order by
  "view_full_data"."" asc limit 1000 offset 0)"

From Postgres, a working one.

Select * from view_full_data where "page = 918;

Body:
I found the problem.

From Maatwebsite\Excel I get an order_by that is not ok (Maybe because I don't have an ID column).

I had to add orderBy manually.

ViewData::query()->where("page", '=', "918")->orderBy('page', 'asc');


问:
Granting Cognitive Services Face API access to a sharepoint folder
I have a flow that stores a photo to sharepoint and then passes the url for this image to Face API preview connector in flow.

I currently get a "forbidden" error, which makes sense as the face api does not have access to the sharepoint location.

How do i grant the face api access to a sharepoint location to see all files in a folder?

答:
For now, there is no built-in mechanism for Azure Cognitive  connector to access SharePoint, you could check this feedback Nicolas R shared no indexer for Sharepoint documents.

So you could use SharePoint connector to get the file directly and pass the file content to the face API connector.


问:
Syntax error when running setup.py egg_info
I am trying to run the installation of the OBITools package using the developers python script.

When running the installation as suggested python get-obitools.py, I receive the following error message:

```<code>    Traceback (most recent call last):
  File "<string>", line 17, in <module>
  File "/tmp/pip_build_tamara/OBITools/setup.py", line 39, in <module>
    from obidistutils.core import setup
  File "distutils.ext/obidistutils/core.py", line 27, in <module>
    from obidistutils.command.build_sphinx import build_sphinx
  File "distutils.ext/obidistutils/command/build_sphinx.py", line 15, in <module>
    from sphinx.setup_command import BuildDoc as ori_build_sphinx
  File "/usr/local/lib/python2.7/dist-packages/sphinx/setup_command.py", line 23, in <module>
    from sphinx.application import Sphinx
  File "/usr/local/lib/python2.7/dist-packages/sphinx/application.py", line 22, in <module>
    from docutils.parsers.rst import Directive, directives, roles
  File "/usr/local/lib/python2.7/dist-packages/docutils/parsers/rst/__init__.py", line 75, in <module>
    from docutils.parsers.rst import roles, states
  File "/usr/local/lib/python2.7/dist-packages/docutils/parsers/rst/roles.py", line 78, in <module>
    from docutils.utils.code_analyzer import Lexer, LexerError
  File "/usr/local/lib/python2.7/dist-packages/docutils/utils/code_analyzer.py", line 19, in <module>
    from pygments.formatters.html import _get_ttype_class
  File "/usr/local/lib/python2.7/dist-packages/pygments/formatters/html.py", line 554
    file=sys.stderr)
        ^
SyntaxError: invalid syntax
</code>```

What am I doing wrong?

I am using:
Ubuntu 19.10
Python 2.7.17
Python 3.7.5

Thank you very much in advance!

答:
You'll be a bit stuck: OBITools requires Sphinx version < 2. Sphinx version requires Pygments version >= 2. The most recent Pygments verion(s) require Python 3, but OBITools requires Python 2.

So it appears the problem is in Sphinx's dependency settings.

One possibility is to install a Pygments version that is still Python 2 compatible (but still is version >= 2 for Sphinx). Then, Sphinx should pick that up automatically when it gets installed through OBITools dependencies.

Pygments version 2.5 might just do the trick:

```<code>pip install pygments==2.5
</code>```

Alternatively, you could try and push for a Python 3 version of OBITools, since Python 2 has been abandoned since 1-1-2020. However, since there has a been a ticket in its repository for a while without any response, this appears unlikely to happen (especially given that Python 3 has been out for years).

My preferred advice would be to abandon OBITools, given that it appears to live in the past.

Body:
I am trying to run the installation of the OBITools package using the developers python script.

When running the installation as suggested python get-obitools.py, I receive the following error message:

    Traceback (most recent call last):
  File "<string>", line 17, in <module>
  File "/tmp/pip_build_tamara/OBITools/setup.py", line 39, in <module>
    from obidistutils.core import setup
  File "distutils.ext/obidistutils/core.py", line 27, in <module>
    from obidistutils.command.build_sphinx import build_sphinx
  File "distutils.ext/obidistutils/command/build_sphinx.py", line 15, in <module>
    from sphinx.setup_command import BuildDoc as ori_build_sphinx
  File "/usr/local/lib/python2.7/dist-packages/sphinx/setup_command.py", line 23, in <module>
    from sphinx.application import Sphinx
  File "/usr/local/lib/python2.7/dist-packages/sphinx/application.py", line 22, in <module>
    from docutils.parsers.rst import Directive, directives, roles
  File "/usr/local/lib/python2.7/dist-packages/docutils/parsers/rst/__init__.py", line 75, in <module>
    from docutils.parsers.rst import roles, states
  File "/usr/local/lib/python2.7/dist-packages/docutils/parsers/rst/roles.py", line 78, in <module>
    from docutils.utils.code_analyzer import Lexer, LexerError
  File "/usr/local/lib/python2.7/dist-packages/docutils/utils/code_analyzer.py", line 19, in <module>
    from pygments.formatters.html import _get_ttype_class
  File "/usr/local/lib/python2.7/dist-packages/pygments/formatters/html.py", line 554
    file=sys.stderr)
        ^
SyntaxError: invalid syntax

What am I doing wrong?

I am using:
Ubuntu 19.10
Python 2.7.17
Python 3.7.5

Thank you very much in advance!

Body:
You'll be a bit stuck: OBITools requires Sphinx version < 2. Sphinx version requires Pygments version >= 2. The most recent Pygments verion(s) require Python 3, but OBITools requires Python 2.

So it appears the problem is in Sphinx's dependency settings.

One possibility is to install a Pygments version that is still Python 2 compatible (but still is version >= 2 for Sphinx). Then, Sphinx should pick that up automatically when it gets installed through OBITools dependencies.

Pygments version 2.5 might just do the trick:

pip install pygments==2.5

Alternatively, you could try and push for a Python 3 version of OBITools, since Python 2 has been abandoned since 1-1-2020. However, since there has a been a ticket in its repository for a while without any response, this appears unlikely to happen (especially given that Python 3 has been out for years).

My preferred advice would be to abandon OBITools, given that it appears to live in the past.


问:
CFile & CStdioFile produces different results in writing & reading
To my understanding, when creating with typeBinary flag, CFile & CStdioFile should works indentically, except the latter is buffering the data so has a better performance.

So I write the following codes to confirm this:

```<code>ULONGLONG GetRand(ULONGLONG uMax)
{
    UINT uValue;

    if (rand_s(&uValue) == 0)
        return  (ULONGLONG)(((double)uValue / (double)UINT_MAX) * uMax);
    else
        return  0;
}

void CheckOffset(CFile& File1, CFile& File2)
{
    ULONGLONG uOffset1, uOffset2;
    CString strMsg;

    uOffset1 = File1.GetPosition();
    uOffset2 = File2.GetPosition();

    if (uOffset1 != uOffset2)
    {
        strMsg.Format(_T("Difference offset. Offset1 = %I64u. Offset2 = %I64u."), uOffset1, uOffset2);
        AfxMessageBox(strMsg);
    }
}

void CheckLength(CFile& File1, CFile& File2)
{
    ULONGLONG uLength1, uLength2;
    CString strMsg;

    uLength1 = File1.GetLength();
    uLength2 = File2.GetLength();

    if (uLength1 != uLength2)
    {
        strMsg.Format(_T("Difference length. Length1 = %I64u. Length2 = %I64u."), uLength1, uLength2);
        AfxMessageBox(strMsg);
    }
}

void CheckSeek(CFile& File1, CFile& File2, ULONGLONG uOffset)
{
    ULONGLONG uOffset1, uOffset2;
    CString strMsg;

    uOffset1 = File1.Seek(uOffset, CFile::begin);
    uOffset2 = File2.Seek(uOffset, CFile::begin);

    if (uOffset1 != uOffset2)
    {
        strMsg.Format(_T("Difference seek results. Offset1 = %I64u. Offset2 = %I64u."), uOffset1, uOffset2);
        AfxMessageBox(strMsg);
    }
}

void CheckRead(CFile& File1, CFile& File2, UINT uSize)
{
    BYTE lpBuf1[4096], lpBuf2[4096];
    UINT uRead1, uRead2;
    CString strMsg;

    //  Read buffer from file1 & file2
    uRead1 = File1.Read(lpBuf1, uSize);
    uRead2 = File2.Read(lpBuf2, uSize);

    if ((uRead1 != uRead2) || (memcmp(lpBuf1, lpBuf2, uRead1) != 0))
    {
        strMsg.Format(_T("Difference read results. uRead1 = %u. uRead2 = %u."), uRead1, uRead2);
        AfxMessageBox(strMsg);
    }
}

void CTestStdioFile64Dlg::OnBnClickedButton1()
{
    // TODO: Add your control notification handler code here
    CFile File1;
    CStdioFile File2;
    UINT uSize;
    BYTE lpBuf[4096];
    CString strMsg;

    if (File1.Open(_T("F:\\Temp\\Test1.dat"), CFile::modeCreate | CFile::modeReadWrite | CFile::shareExclusive | CFile::typeBinary))
    {
        if (File2.Open(_T("F:\\Temp\\Test2.dat"), CFile::modeCreate | CFile::modeReadWrite | CFile::shareExclusive | CFile::typeBinary))
        {
            CheckOffset(File1, File2);
            CheckLength(File1, File2);

            //  Write data
            for (UINT uIndex = 0; uIndex < 20000; uIndex ++)
            {
                //  Generate a randome size for write
                uSize = (UINT)GetRand(4096);

                //  Generate buffer with random data
                for (UINT j = 0; j < uSize; j++)
                    lpBuf[j] = (BYTE)GetRand(255);

                //  Write buffer to file1 & file2
                File1.Write(lpBuf, uSize);
                File2.Write(lpBuf, uSize);

                File1.Flush();
                File2.Flush();

                CheckOffset(File1, File2);
                CheckLength(File1, File2);

                //  Seek to a randome location
                CheckSeek(File1, File2, GetRand(File1.GetLength()));

                //  Generate a randome size for read
                uSize = (UINT)GetRand(4096);

                CheckRead(File1, File2, uSize);
                CheckOffset(File1, File2);
            }

            File2.Close();
        }

        File1.Close();
    }
}
</code>```

To my surprise, in the test process, there are many CFileException raised because CStdioFile::Write will write out less amount of data than expected.

Also there are many different read data reported.

Why?

答:
When I run your code in Debug mode, I am getting the following ASSERT.

"Flush between consecutive read and write.",
  !stream.has_any_of(_IOREAD)

The reason is following:

From C Standard documentation:
(Page 306, 7.21.5.3).

When a file is opened with update mode ('+' as the second or third
  character in the above list of mode argument values), both input and
  output may be performed on the associated stream. However, output
  shall not be directly followed by input without an intervening call to
  the fflush function or to a file positioning function (fseek, fsetpos,
  or rewind), and input shall not be directly followed by output without
  an intervening call to a file positioning function, unless the input
  operation encounters endof-file.

In your code, you are calling for CheckRead function at the end of the loop, but calling for File1.Write and File2.Write in the next iteration without calling for fseek/flush.

As a quick fix, you can add the following lines at the bottom of your CheckRead function:

```<code>File1.Seek(0, SEEK_CUR);
File2.Seek(0, SEEK_CUR);
</code>```

Body:
To my understanding, when creating with typeBinary flag, CFile & CStdioFile should works indentically, except the latter is buffering the data so has a better performance.

So I write the following codes to confirm this:

ULONGLONG GetRand(ULONGLONG uMax)
{
    UINT uValue;

    if (rand_s(&uValue) == 0)
        return  (ULONGLONG)(((double)uValue / (double)UINT_MAX) * uMax);
    else
        return  0;
}

void CheckOffset(CFile& File1, CFile& File2)
{
    ULONGLONG uOffset1, uOffset2;
    CString strMsg;

    uOffset1 = File1.GetPosition();
    uOffset2 = File2.GetPosition();

    if (uOffset1 != uOffset2)
    {
        strMsg.Format(_T("Difference offset. Offset1 = %I64u. Offset2 = %I64u."), uOffset1, uOffset2);
        AfxMessageBox(strMsg);
    }
}

void CheckLength(CFile& File1, CFile& File2)
{
    ULONGLONG uLength1, uLength2;
    CString strMsg;

    uLength1 = File1.GetLength();
    uLength2 = File2.GetLength();

    if (uLength1 != uLength2)
    {
        strMsg.Format(_T("Difference length. Length1 = %I64u. Length2 = %I64u."), uLength1, uLength2);
        AfxMessageBox(strMsg);
    }
}

void CheckSeek(CFile& File1, CFile& File2, ULONGLONG uOffset)
{
    ULONGLONG uOffset1, uOffset2;
    CString strMsg;

    uOffset1 = File1.Seek(uOffset, CFile::begin);
    uOffset2 = File2.Seek(uOffset, CFile::begin);

    if (uOffset1 != uOffset2)
    {
        strMsg.Format(_T("Difference seek results. Offset1 = %I64u. Offset2 = %I64u."), uOffset1, uOffset2);
        AfxMessageBox(strMsg);
    }
}

void CheckRead(CFile& File1, CFile& File2, UINT uSize)
{
    BYTE lpBuf1[4096], lpBuf2[4096];
    UINT uRead1, uRead2;
    CString strMsg;

    //  Read buffer from file1 & file2
    uRead1 = File1.Read(lpBuf1, uSize);
    uRead2 = File2.Read(lpBuf2, uSize);

    if ((uRead1 != uRead2) || (memcmp(lpBuf1, lpBuf2, uRead1) != 0))
    {
        strMsg.Format(_T("Difference read results. uRead1 = %u. uRead2 = %u."), uRead1, uRead2);
        AfxMessageBox(strMsg);
    }
}

void CTestStdioFile64Dlg::OnBnClickedButton1()
{
    // TODO: Add your control notification handler code here
    CFile File1;
    CStdioFile File2;
    UINT uSize;
    BYTE lpBuf[4096];
    CString strMsg;

    if (File1.Open(_T("F:\\Temp\\Test1.dat"), CFile::modeCreate | CFile::modeReadWrite | CFile::shareExclusive | CFile::typeBinary))
    {
        if (File2.Open(_T("F:\\Temp\\Test2.dat"), CFile::modeCreate | CFile::modeReadWrite | CFile::shareExclusive | CFile::typeBinary))
        {
            CheckOffset(File1, File2);
            CheckLength(File1, File2);

            //  Write data
            for (UINT uIndex = 0; uIndex < 20000; uIndex ++)
            {
                //  Generate a randome size for write
                uSize = (UINT)GetRand(4096);

                //  Generate buffer with random data
                for (UINT j = 0; j < uSize; j++)
                    lpBuf[j] = (BYTE)GetRand(255);

                //  Write buffer to file1 & file2
                File1.Write(lpBuf, uSize);
                File2.Write(lpBuf, uSize);

                File1.Flush();
                File2.Flush();

                CheckOffset(File1, File2);
                CheckLength(File1, File2);

                //  Seek to a randome location
                CheckSeek(File1, File2, GetRand(File1.GetLength()));

                //  Generate a randome size for read
                uSize = (UINT)GetRand(4096);

                CheckRead(File1, File2, uSize);
                CheckOffset(File1, File2);
            }

            File2.Close();
        }

        File1.Close();
    }
}

To my surprise, in the test process, there are many CFileException raised because CStdioFile::Write will write out less amount of data than expected.

Also there are many different read data reported.

Why?

Body:
When I run your code in Debug mode, I am getting the following ASSERT.

"Flush between consecutive read and write.",
  !stream.has_any_of(_IOREAD)

The reason is following:

From C Standard documentation:
(Page 306, 7.21.5.3).

When a file is opened with update mode ('+' as the second or third
  character in the above list of mode argument values), both input and
  output may be performed on the associated stream. However, output
  shall not be directly followed by input without an intervening call to
  the fflush function or to a file positioning function (fseek, fsetpos,
  or rewind), and input shall not be directly followed by output without
  an intervening call to a file positioning function, unless the input
  operation encounters endof-file.

In your code, you are calling for CheckRead function at the end of the loop, but calling for File1.Write and File2.Write in the next iteration without calling for fseek/flush.

As a quick fix, you can add the following lines at the bottom of your CheckRead function:

File1.Seek(0, SEEK_CUR);
File2.Seek(0, SEEK_CUR);


问:
Junit test 5 (Exception)
I am doing a Junit test and in one of the tests I have problems but I don't understand why.

You do not have to allow more objects to be added to the list at any given time, that the size of the list is greater than 5, in short, if I add the sixth object to the list, the exception must be skipped, but I do not understand the reason why It does not work, I leave the code of what I am doing.

Code:

```<code> @Test
 void testAddTank() throws KeeperException, TankException {
  List<Tank> NumTanques = new ArrayList<Tank>();

  Tank tank1 = new Tank("TANQUE1","pedro1","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank2 = new Tank("TANQUE2","pedro2","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank3 = new Tank("TANQUE3","pedro3","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank4 = new Tank("TANQUE4","pedro4","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank5 = new Tank("TANQUE5","pedro5","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank6 = new Tank("TANQUE6","pedro6","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank7 = new Tank("TANQUE7","pedro6","hola",3.0,2.0,1.0,"/image",17.0,7);

  NumTanques.add(tank1);
  NumTanques.add(tank2);
  NumTanques.add(tank3);
  NumTanques.add(tank4);
  NumTanques.add(tank5);

  assertEquals(5, NumTanques.size());

  KeeperException excepcionTanques = assertThrows(KeeperException.class,()->NumTanques.add(tank6));
  assertEquals("[ERROR] A keeper cannot care of more than 5
  thanks!!",excepcionTanques.MSG_ERR_MAX_TANKS);

}
</code>```

As you can see, I create the list of type tank and create some tank objects, which I add to the list. Then with the assert what I tell you is that 5 has to be the size of the list so that it returns true ...

Then in the exception that I create I add a new tank to the list and the exception should jump, but it does not, it exits and gives an error on the line:

```<code> KeeperException excepcionTanques = assertThrows(KeeperException.class,()->NumTanques.add(tank6));
</code>```

I do not see clearly what is happening.

答:
Why Arraylist will throw and exception if you add anything to it. It has its own algorithm to manage addition.

What you need to do is add a method in your service class (maybe KeeperService.java)

And throw exception there.
Something like

```<code>@sneakyThrows
public void countKeeperCheck(Object o){

List<Tank> NumTanques = new ArrayList<Tank>();
NumTanques.add(o);

if(listOfBanks.size() >5){
throw new KeeperException("write whatever here")
}
}

//add to try/catch if you have specific things to handle
</code>```

And you can call that method from your test. You cant write business logic in your test. From tests you call methods that holds your business logic.

----------------Edit After Comments and detailed code-----------------

```<code>public void addTank(List<Tank> tank) throws KeeperException{// in the comment you add wrong signature, method should accept List, the only you will have contains operation

        if(tanks.size()>=5){
        throw new KeeperException(KeeperException.MSG_ERR_MAX_TANKS);
        }

        if(!tanks.contains(tank)){
            tanks.add(tank);
    }
}

// and this is how your test will look like
@Test
 void testAddTank() throws KeeperException, TankException {
         List<Tank> NumTanques = new ArrayList<Tank>();

        Tank tank1 = new Tank("TANQUE1","pedro1","hola",3.0,2.0,1.0,"/image",17.0,7);
        Tank tank2 = new Tank("TANQUE2","pedro2","hola",3.0,2.0,1.0,"/image",17.0,7);
        Tank tank3 = new Tank("TANQUE3","pedro3","hola",3.0,2.0,1.0,"/image",17.0,7);
        Tank tank4 = new Tank("TANQUE4","pedro4","hola",3.0,2.0,1.0,"/image",17.0,7);
        Tank tank5 = new Tank("TANQUE5","pedro5","hola",3.0,2.0,1.0,"/image",17.0,7);
        Tank tank6 = new Tank("TANQUE6","pedro6","hola",3.0,2.0,1.0,"/image",17.0,7);

        NumTanques.add(tank1);
        NumTanques.add(tank2);
        NumTanques.add(tank3);
        NumTanques.add(tank4);
        NumTanques.add(tank5);

        KeeperException excepcionTanques = assertThrows(KeeperException.class,()->yourServiceClass.addTank(tank6));
        assertEquals("[ERROR] A keeper cannot care of more than 5  thanks!!",excepcionTanques.MSG_ERR_MAX_TANKS);
        }
</code>```

declare YourServiceClass the way you want.

Title: Junit test 5 (Exception)

Body:
I am doing a Junit test and in one of the tests I have problems but I don't understand why.

You do not have to allow more objects to be added to the list at any given time, that the size of the list is greater than 5, in short, if I add the sixth object to the list, the exception must be skipped, but I do not understand the reason why It does not work, I leave the code of what I am doing.

Code:

 @Test
 void testAddTank() throws KeeperException, TankException {
  List<Tank> NumTanques = new ArrayList<Tank>();

  Tank tank1 = new Tank("TANQUE1","pedro1","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank2 = new Tank("TANQUE2","pedro2","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank3 = new Tank("TANQUE3","pedro3","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank4 = new Tank("TANQUE4","pedro4","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank5 = new Tank("TANQUE5","pedro5","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank6 = new Tank("TANQUE6","pedro6","hola",3.0,2.0,1.0,"/image",17.0,7);
  Tank tank7 = new Tank("TANQUE7","pedro6","hola",3.0,2.0,1.0,"/image",17.0,7);

  NumTanques.add(tank1);
  NumTanques.add(tank2);
  NumTanques.add(tank3);
  NumTanques.add(tank4);
  NumTanques.add(tank5);

  assertEquals(5, NumTanques.size());

  KeeperException excepcionTanques = assertThrows(KeeperException.class,()->NumTanques.add(tank6));
  assertEquals("[ERROR] A keeper cannot care of more than 5
  thanks!!",excepcionTanques.MSG_ERR_MAX_TANKS);

}

As you can see, I create the list of type tank and create some tank objects, which I add to the list. Then with the assert what I tell you is that 5 has to be the size of the list so that it returns true ...

Then in the exception that I create I add a new tank to the list and the exception should jump, but it does not, it exits and gives an error on the line:

 KeeperException excepcionTanques = assertThrows(KeeperException.class,()->NumTanques.add(tank6));

I do not see clearly what is happening.

Body:
Why Arraylist will throw and exception if you add anything to it. It has its own algorithm to manage addition.

What you need to do is add a method in your service class (maybe KeeperService.java)

And throw exception there.
Something like

@sneakyThrows
public void countKeeperCheck(Object o){

List<Tank> NumTanques = new ArrayList<Tank>();
NumTanques.add(o);

if(listOfBanks.size() >5){
throw new KeeperException("write whatever here")
}
}

//add to try/catch if you have specific things to handle

And you can call that method from your test. You cant write business logic in your test. From tests you call methods that holds your business logic.

----------------Edit After Comments and detailed code-----------------

public void addTank(List<Tank> tank) throws KeeperException{// in the comment you add wrong signature, method should accept List, the only you will have contains operation

        if(tanks.size()>=5){
        throw new KeeperException(KeeperException.MSG_ERR_MAX_TANKS);
        }

        if(!tanks.contains(tank)){
            tanks.add(tank);
    }
}

// and this is how your test will look like
@Test
 void testAddTank() throws KeeperException, TankException {
         List<Tank> NumTanques = new ArrayList<Tank>();

        Tank tank1 = new Tank("TANQUE1","pedro1","hola",3.0,2.0,1.0,"/image",17.0,7);
        Tank tank2 = new Tank("TANQUE2","pedro2","hola",3.0,2.0,1.0,"/image",17.0,7);
        Tank tank3 = new Tank("TANQUE3","pedro3","hola",3.0,2.0,1.0,"/image",17.0,7);
        Tank tank4 = new Tank("TANQUE4","pedro4","hola",3.0,2.0,1.0,"/image",17.0,7);
        Tank tank5 = new Tank("TANQUE5","pedro5","hola",3.0,2.0,1.0,"/image",17.0,7);
        Tank tank6 = new Tank("TANQUE6","pedro6","hola",3.0,2.0,1.0,"/image",17.0,7);

        NumTanques.add(tank1);
        NumTanques.add(tank2);
        NumTanques.add(tank3);
        NumTanques.add(tank4);
        NumTanques.add(tank5);

        KeeperException excepcionTanques = assertThrows(KeeperException.class,()->yourServiceClass.addTank(tank6));
        assertEquals("[ERROR] A keeper cannot care of more than 5  thanks!!",excepcionTanques.MSG_ERR_MAX_TANKS);
        }

declare YourServiceClass the way you want.


问:
Is it possible to replace an existing pip package with specific name by my own package?
I would like to add my package to pip installer with a specific name, however, somebody else has created a similar module with the same name and it is not maintained anymore by them.
Is it possible to take somehow the name of an existing module? I ask because the name I wanted to use is very descriptive and so it would be nice to use it for the module.</p>

答:
It's possible, under some conditions:

How do I claim an abandoned or previously registered project name?

Follow the "How to request a name transfer" section of PEP 541.

-- https://pypi.org/help/#project-name-claim


问:
Can I have multiple POSIX FIFOs in a single process?
I am creating three FIFO pipes for a single process where multiple writer threads write to a single reader thread.  The goal is a separate file descriptor for each writer thread with a corresponding reader file descriptor for each writer file descriptor so that I know which writer thread belongs to each record.  My setup works fine with one writer file descriptor shared among all writer threads and a single reader file descriptor.

The multiple reader/writer setup works successfully to set up three writer fds (6, 7, 8) and three reader fds (9, 10 and 11).  All writer threads successfully send data, BUT the reader fds do not successfully read the data (return zero bytes read).

When I open the fd on the writer side, I get the error message "open: Bad file descriptor" but it still returns a unique fd, and that fd is used successfully to write, but not to read.

I call the C programs from NASM in a loop, one iteration for each writer thread:

```<code>xor r12,r12
mov r13,[Number_Of_Cores_Calc]
Setup_pipe:
lea rdi,[fifo_base_name]
mov rax,r12
add rax,48
mov byte[rdi+11],al
call fifo_delete wrt ..plt
call fifo_setup wrt ..plt
push rdi
call fifo_close wrt ..plt
pop rdi
Open_FIFO_Write:
mov rsi,1
call fifo_open wrt ..plt
lea rbp,[fifo_write_fds]
mov [rbp+r12*8],rax
add r12,1
cmp r12,r13
jl Setup_pipe
</code>```

The corresponding C programs:

```<code>int64_t fifo_setup(char * fifo_name)
{

    remove(fifo_name);

    if (mkfifo(fifo_name, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH) == -1) {
        perror("mkfifo");
        exit(EXIT_FAILURE); }

        return 0;
}

int64_t fifo_open(char * fifo_name, int64_t read_write) {

    int c;

    if (read_write == 1) {
        c = open(fifo_name, O_CREAT | O_RDWR);} //O_WRONLY
    if (read_write == 2) {
        c = open(fifo_name, O_CREAT | O_RDWR);} //O_RDONLY

    perror("open");

    return (c);
}

int64_t fifo_read(int fd, void *buf, size_t count) {

    int status_read = read(fd, buf, count);
    return status_read;
}

int64_t fifo_write(int fd, const void *buf, size_t count) {

    int status_write = write(fd, buf, count);
    return status_write; }

int64_t fifo_close(int fifo_fdes) {

    close(fifo_fdes);

    return 0; }

// Delete pre-existing file
int64_t fifo_delete(char * fifo_name) {

    if( access( fifo_name, F_OK ) != -1 ) {
        if (remove(fifo_name) == 0)
        printf("File deleted successfully");
    else
        printf("Unable to delete the file");
    }

    return 0; }
</code>```

So my questions are:

Can I write from multiple threads to a single reader thread using separate fds for each thread on both the write and read sides?

If I can, what did I do wrong above -- especially why am I getting "open: Bad file descriptor" but I still get what looks like a valid file descriptor.

If I can't use POSIX FIFOs, what IPC methods can I use so each writer thread has its own unique fd on both writer and reader sides?  Datagram sockets?

Thanks for any help on this.

答: If all the communication is going to be between threads in a single process, you can use pipe(2) system call and give fd[0] to the reader thread while giving fd[1] to the writer.  You don't even need to open() or have a name in the filesytem associated to the fifo.  You still will need to close fd[1] if you want to signal end of file to the reader.

Body:
I am creating three FIFO pipes for a single process where multiple writer threads write to a single reader thread.  The goal is a separate file descriptor for each writer thread with a corresponding reader file descriptor for each writer file descriptor so that I know which writer thread belongs to each record.  My setup works fine with one writer file descriptor shared among all writer threads and a single reader file descriptor.

The multiple reader/writer setup works successfully to set up three writer fds (6, 7, 8) and three reader fds (9, 10 and 11).  All writer threads successfully send data, BUT the reader fds do not successfully read the data (return zero bytes read).

When I open the fd on the writer side, I get the error message "open: Bad file descriptor" but it still returns a unique fd, and that fd is used successfully to write, but not to read.

I call the C programs from NASM in a loop, one iteration for each writer thread:

xor r12,r12
mov r13,[Number_Of_Cores_Calc]
Setup_pipe:
lea rdi,[fifo_base_name]
mov rax,r12
add rax,48
mov byte[rdi+11],al
call fifo_delete wrt ..plt
call fifo_setup wrt ..plt
push rdi
call fifo_close wrt ..plt
pop rdi
Open_FIFO_Write:
mov rsi,1
call fifo_open wrt ..plt
lea rbp,[fifo_write_fds]
mov [rbp+r12*8],rax
add r12,1
cmp r12,r13
jl Setup_pipe

The corresponding C programs:

int64_t fifo_setup(char * fifo_name)
{

    remove(fifo_name);

    if (mkfifo(fifo_name, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH) == -1) {
        perror("mkfifo");
        exit(EXIT_FAILURE); }

        return 0;
}

int64_t fifo_open(char * fifo_name, int64_t read_write) {

    int c;

    if (read_write == 1) {
        c = open(fifo_name, O_CREAT | O_RDWR);} //O_WRONLY
    if (read_write == 2) {
        c = open(fifo_name, O_CREAT | O_RDWR);} //O_RDONLY

    perror("open");

    return (c);
}

int64_t fifo_read(int fd, void *buf, size_t count) {

    int status_read = read(fd, buf, count);
    return status_read;
}

int64_t fifo_write(int fd, const void *buf, size_t count) {

    int status_write = write(fd, buf, count);
    return status_write; }

int64_t fifo_close(int fifo_fdes) {

    close(fifo_fdes);

    return 0; }

// Delete pre-existing file
int64_t fifo_delete(char * fifo_name) {

    if( access( fifo_name, F_OK ) != -1 ) {
        if (remove(fifo_name) == 0)
        printf("File deleted successfully");
    else
        printf("Unable to delete the file");
    }

    return 0; }

So my questions are:

Can I write from multiple threads to a single reader thread using separate fds for each thread on both the write and read sides?

If I can, what did I do wrong above -- especially why am I getting "open: Bad file descriptor" but I still get what looks like a valid file descriptor.

If I can't use POSIX FIFOs, what IPC methods can I use so each writer thread has its own unique fd on both writer and reader sides?  Datagram sockets?

Thanks for any help on this.


问:
How to store .pdf file in Sqlite using R programming
I am creating an application on R-Shiny where i am taking inputs from users which i am storing into SQLite  database in backed.But my concern is on my form i have one upload file input which basically accepts files like (.PDF,.jpeg,.png)(screenshot below).

If users upload any file using that i want that file to be stored in my SQLite database table for further use.But i am not aware of how to achieve this using r programming.

Any help would be appreciated.

答:
You can store objects (any R output which is not tabular, model's output for example) as BLOBs in SQLite, in R use serialize/unserialize for this, but before you need to read the raw PDF using readBin, here an example :

```<code>path <- file.path(Sys.getenv("R_DOC_DIR"), "NEWS.pdf")

# see the PDF
browseURL(path)

# Read raw PDF
pdf <- readBin(con = path, what = raw(), n = file.info(path)$size)

library(RSQLite)

# Connect to DB
con <- dbConnect(RSQLite::SQLite(), ":memory:")

# Serialize raw pdf
pdf_serialized <- serialize(pdf, NULL)
# Create a data.frame
df <- data.frame(pdfs = I(list(pdf_serialized)))

# Write the table in database
dbWriteTable(conn = con, name = "mytable", value = df, overwrite = TRUE)

# Read your table
out <- dbReadTable(conn = con, name = "mytable")

# unserialize
pdf_out <- unserialize(out$pdfs[[1]])

# Write the PDF in a temporary file
tmp <- tempfile(fileext = ".pdf")
writeBin(object = pdf_out, con = tmp)

# open it
browseURL(tmp)
</code>```

Body:
You can store objects (any R output which is not tabular, model's output for example) as BLOBs in SQLite, in R use serialize/unserialize for this, but before you need to read the raw PDF using readBin, here an example :

path <- file.path(Sys.getenv("R_DOC_DIR"), "NEWS.pdf")

# see the PDF
browseURL(path)

# Read raw PDF
pdf <- readBin(con = path, what = raw(), n = file.info(path)$size)

library(RSQLite)

# Connect to DB
con <- dbConnect(RSQLite::SQLite(), ":memory:")

# Serialize raw pdf
pdf_serialized <- serialize(pdf, NULL)
# Create a data.frame
df <- data.frame(pdfs = I(list(pdf_serialized)))

# Write the table in database
dbWriteTable(conn = con, name = "mytable", value = df, overwrite = TRUE)

# Read your table
out <- dbReadTable(conn = con, name = "mytable")

# unserialize
pdf_out <- unserialize(out$pdfs[[1]])

# Write the PDF in a temporary file
tmp <- tempfile(fileext = ".pdf")
writeBin(object = pdf_out, con = tmp)

# open it
browseURL(tmp)


问:
Java applet doesn't works on IE8
When I run an applet in Firefox it works but not in internet explorer 8 (but it works in IE7)

Java version in use is 6, update 18 (1.6.0_18)

Output of JVM in Firefox is:

```<code>URL sin parametro: http://..../..../AppJava/
Parametro añadido a la URL codificado en UTF-8: ...IHgzC...
basic: Applet initialized
basic: Receptor de progreso suprimido: sun.plugin.util.GrayBoxPainter$GrayBoxProgressListener@1dd7056
basic: Applet made visible
basic: Starting applet
basic: completed perf rollup
basic: Applet started
basic: Told clients applet is started
basic: Starting applet teardown
basic: Finished applet teardown
</code>```

Output of JVM in IE8 is:

```<code>URL sin parametro: http://......./...../AppJava/
Parametro añadido a la URL codificado en UTF-8: ...IHgzCC.....
basic: Applet initialized
basic: Receptor de progreso suprimido:   sun.plugin.util.GrayBoxPainter$GrayBoxProgressListener@e86da0
basic: Applet made visible
basic: Starting applet
basic: completed perf rollup
basic: Applet started
basic: Told clients applet is started
</code>```

Note that in IE8 the last line is "Told clients applet is started" while in Firefox is "Finished applet teardown".

I also checked the security settings of IE8 but I think they are correct.

Any idea?

Thanks

答:
It is nothing wrong with IE 8. It should be working.
As per the java console/jvm messages, your applet is running.

The java should be compatable==> it is recommended that your browser java plug-in version should be same or higher than the version of the java compiler used to compile your applet.

Put some S.o.P statements in your applet and check again.

* below is sample java console messages when you run applet in FF & IE browsers *

The java console message looks like below (FF 4 and FF 3.x)

```<code>basic: Applet loaded.
basic: Applet resized and added to parent container
basic: PERF: AppletExecutionRunnable - applet.init() BEGIN ; jvmLaunch dt 125583 us, pluginInit dt 1492613 us, TotalTime: 1618196 us
basic: Applet initialized
basic: Removed progress listener: sun.plugin.util.GrayBoxPainter$GrayBoxProgressListener@1f14ceb
basic: Applet made visible
basic: Starting applet
basic: completed perf rollup
basic: Finished applet teardown
</code>```

********* In  IE 8 ********

```<code>basic: Applet loaded.
basic: Applet resized and added to parent container
basic: PERF: AppletExecutionRunnable - applet.init() BEGIN ; jvmLaunch dt 177363 us, pluginInit dt 390916 us, TotalTime: 568279 us
basic: Applet initialized
basic: Removed progress listener: sun.plugin.util.GrayBoxPainter$GrayBoxProgressListener@116471f
basic: Applet made visible
basic: Starting applet
basic: completed perf rollup
basic: Applet started
basic: Told clients applet is started
</code>```

ContentLicense: CC BY-SA 2.5

Title: Java applet doesn't works on IE8

Body:
When I run an applet in Firefox it works but not in internet explorer 8 (but it works in IE7)

Java version in use is 6, update 18 (1.6.0_18)

Output of JVM in Firefox is:

URL sin parametro: http://..../..../AppJava/
Parametro añadido a la URL codificado en UTF-8: ...IHgzC...
basic: Applet initialized
basic: Receptor de progreso suprimido: sun.plugin.util.GrayBoxPainter$GrayBoxProgressListener@1dd7056
basic: Applet made visible
basic: Starting applet
basic: completed perf rollup
basic: Applet started
basic: Told clients applet is started
basic: Starting applet teardown
basic: Finished applet teardown

Output of JVM in IE8 is:

URL sin parametro: http://......./...../AppJava/
Parametro añadido a la URL codificado en UTF-8: ...IHgzCC.....
basic: Applet initialized
basic: Receptor de progreso suprimido:   sun.plugin.util.GrayBoxPainter$GrayBoxProgressListener@e86da0
basic: Applet made visible
basic: Starting applet
basic: completed perf rollup
basic: Applet started
basic: Told clients applet is started

Note that in IE8 the last line is "Told clients applet is started" while in Firefox is "Finished applet teardown".

I also checked the security settings of IE8 but I think they are correct.

Any idea?

Thanks

Body:
It is nothing wrong with IE 8. It should be working.
As per the java console/jvm messages, your applet is running.

The java should be compatable==> it is recommended that your browser java plug-in version should be same or higher than the version of the java compiler used to compile your applet.

Put some S.o.P statements in your applet and check again.

* below is sample java console messages when you run applet in FF & IE browsers *

The java console message looks like below (FF 4 and FF 3.x)

basic: Applet loaded.
basic: Applet resized and added to parent container
basic: PERF: AppletExecutionRunnable - applet.init() BEGIN ; jvmLaunch dt 125583 us, pluginInit dt 1492613 us, TotalTime: 1618196 us
basic: Applet initialized
basic: Removed progress listener: sun.plugin.util.GrayBoxPainter$GrayBoxProgressListener@1f14ceb
basic: Applet made visible
basic: Starting applet
basic: completed perf rollup
basic: Finished applet teardown

********* In  IE 8 ********

basic: Applet loaded.
basic: Applet resized and added to parent container
basic: PERF: AppletExecutionRunnable - applet.init() BEGIN ; jvmLaunch dt 177363 us, pluginInit dt 390916 us, TotalTime: 568279 us
basic: Applet initialized
basic: Removed progress listener: sun.plugin.util.GrayBoxPainter$GrayBoxProgressListener@116471f
basic: Applet made visible
basic: Starting applet
basic: completed perf rollup
basic: Applet started
basic: Told clients applet is started


问:
How to customize <pagination-controls> color?
I am using angular pagination and I want to customize this blue color into another , Can anyone help me.

I have tried below code stuff also, but it didn't work for me. Below one from this link >>> " https://www.npmjs.com/package/ngx-pagination"

```<code>  // head
<style>
  .my-pagination /deep/ .ngx-pagination .current {
    background: red;
  }
</style>

// body
<pagination-controls class="my-pagination"><pagination-controls>
</code>```

答:
You could try to assign the color for the following selectors

::ng-deep ul > li:not(.active) > a {
  background-color: red !important;
  border-color: black !important;
}

::ng-deep ul > li.disabled > span {
  background-color: brown !important;
  border-color: black !important;
}

::ng-deep ul > li.active > a {
  background-color: green !important;
  border-color: red !important;
}
```

Working example: Stackblitz

Body:
I am using angular pagination and I want to customize this blue color into another , Can anyone help me.

I have tried below code stuff also, but it didn't work for me. Below one from this link >>> " https://www.npmjs.com/package/ngx-pagination"

  // head

// body
<pagination-controls class="my-pagination"><pagination-controls>

Body:
You could try to assign the color for the following selectors

::ng-deep ul > li:not(.active) > a {
  background-color: red !important;
  border-color: black !important;
}

::ng-deep ul > li.disabled > span {
  background-color: brown !important;
  border-color: black !important;
}

::ng-deep ul > li.active > a {
  background-color: green !important;
  border-color: red !important;
}

Working example: Stackblitz


问:
PL/SQL Developer GUI not showing number result in text format
PL/SQL Developer is showing number results like 9.15734383345614E18.
What config change is needed to show number result in text format?

答:
Try to convert it to char:

```<code>select F1 , to_char(F1) from T1;
</code>```

or simply go to this path and do the config in PL/SQL Developer:

```<code>Configure -> Preferences -> SQL Window -> Number fields to_char
</code>```

Body:
Try to convert it to char:

select F1 , to_char(F1) from T1;

or simply go to this path and do the config in PL/SQL Developer:

Configure -> Preferences -> SQL Window -> Number fields to_char


问:
How to create multiple horizontal `GridView` in the same screen using flutter
Is there's a way to create a lists of GridViews as the below image in one screen...

I have a some Screen as the below one:

```<code>class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  var _showOnlyFavorites = false;
  AnimationController animationController;
  bool multiple = true;

  @override
  void initState() {
    animationController = AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);
    super.initState();
  }

  Future<bool> getData() async {
    await Future<dynamic>.delayed(const Duration(milliseconds: 0));
    return true;
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.white,
      body: FutureBuilder<bool>(
        future: getData(),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (!snapshot.hasData) {
            return const SizedBox();
          } else {
            return Padding(
              padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  appBar(),
                  Expanded(
                    child: FutureBuilder<bool>(
                      future: getData(),
                      builder:
                          (BuildContext context, AsyncSnapshot<bool> snapshot) {
                        if (!snapshot.hasData) {
                          return const SizedBox();
                        } else {
                          return PropertiesGrid(_showOnlyFavorites);
                        }
                      },
                    ),
                  ),
                ],
              ),
            );
          }
        },
      ),
    );
  }

  Widget appBar() {
    return SizedBox(
      height: AppBar().preferredSize.height,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top: 8, left: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
            ),
          ),
          Expanded(
            child: Center(
              child: Padding(
                padding: const EdgeInsets.only(top: 4),
                child:
                    Image.asset('assets/images/logo.png', fit: BoxFit.contain),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 8, right: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
              color: Colors.white,
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  borderRadius:
                      BorderRadius.circular(AppBar().preferredSize.height),
                  child: Icon(
                    multiple ? Icons.dashboard : Icons.view_agenda,
                    color: AppTheme.dark_grey,
                  ),
                  onTap: () {
                    setState(() {
                      multiple = !multiple;
                    });
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

as I have a widget which have the GridView.builder as the below code:

```<code>import 'package:aradi_online_vtwo/providers/properties.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../providers/properties.dart';
import './property_item.dart';

class PropertiesGrid extends StatelessWidget {
  final bool showFavs;

  PropertiesGrid(this.showFavs);

  @override
  Widget build(BuildContext context) {
    final productsData = Provider.of<Properties>(context);
    final products = showFavs ? productsData.favoriteItems : productsData.items;
    return GridView.builder(
      padding: const EdgeInsets.all(10.0),
      itemCount: products.length,
      itemBuilder: (ctx, i) => ChangeNotifierProvider.value(
            // builder: (c) => products[i],
            value: products[i],
            child: PropertyItem(
                // products[i].id,
                // products[i].title,
                // products[i].imageUrl,
                ),
          ),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 1,
        childAspectRatio: 3 / 2,
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
      ), scrollDirection: Axis.horizontal,
    );
  }
}

</code>```

I tried to set the height of the grid by wrapping it with a Container and set the height of it as to add more grids but it doesn't work.

and here's my Grid Item widget code:

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

import '../providers/property.dart';

class PropertyItem extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final property = Provider.of<Property>(context, listen: false);
    return InkWell(
      onTap: () => {},
      child: Card(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(15),
        ),
        elevation: 7,
        margin: EdgeInsets.all(2),
        child: Stack(
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(15),
                topRight: Radius.circular(15),
              ),
              // color: Colors.transparent,
              child: Image.asset(
                property.image,
                fit: BoxFit.fill,
              ),
            ),
            Positioned(
              top: 8,
              right: 8,
              child: Consumer<Property>(
                builder: (ctx, property, _) => IconButton(
                  icon: Icon(
                    property.isFavorite ? Icons.favorite : Icons.favorite_border,
                  ),
                  color: Colors.red,
                  onPressed: () {
                    property.toggleFavoriteStatus();
                  },
                ),
              ),
            ),
            Positioned(
                  right: 20,
                  top: 100,
                  child: Container(
                    width: 300,
                    color: Colors.black54,
                    padding: EdgeInsets.symmetric(
                      vertical: 5,
                      horizontal: 20,
                    ),
                    child: Text(
                      property.title,
                      style: TextStyle(
                        fontSize: 20,
                        color: Colors.white,
                      ),
                      softWrap: true,
                      overflow: TextOverflow.fade,
                    ),
                  ),
                )
          ],
        ),
      ),
    );
  }
}

</code>```

答:
You'll need a column where each ListView or GridView is wrapped inside a SizedBox (if you have a specific height) and you also can use Expanded to take whatever available space (like the last one in the given example):

You can post the code below in dartpad.dev and see how it works:

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

void main() {
  runApp(MaterialApp(
    theme: ThemeData(
      primarySwatch: Colors.blue,
    ),
    home: MyApp(),
  ));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          SizedBox(
            height: 100,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: 10,
              itemBuilder: (c, i) {
                return Card(
                  child: Container(
                    height: 100,
                    width: 100,
                    child: Center(child: Text("$i")),
                  ),
                );
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Align(
              child: Text("The Second List"),
              alignment: Alignment.centerRight,
            ),
          ),
          SizedBox(
            height: 100,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: 10,
              itemBuilder: (c, i) {
                return Card(
                  child: Container(
                    height: 100,
                    width: 100,
                    child: Center(child: Text("$i")),
                  ),
                );
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Align(
              child: Text("The Third List"),
              alignment: Alignment.centerRight,
            ),
          ),
          Expanded(
            //height: 200,
            child: GridView.builder(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                childAspectRatio: 3 / 2,
                crossAxisSpacing: 10,
                mainAxisSpacing: 10,
              ),
              scrollDirection: Axis.vertical,
              itemCount: 20,
              itemBuilder: (c, i) {
                return Card(
                  child: Container(
                    height: 100,
                    width: 100,
                    child: Center(child: Text("$i")),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

Body:
Is there's a way to create a lists of GridViews as the below image in one screen...

I have a some Screen as the below one:

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  var _showOnlyFavorites = false;
  AnimationController animationController;
  bool multiple = true;

  @override
  void initState() {
    animationController = AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);
    super.initState();
  }

  Future<bool> getData() async {
    await Future<dynamic>.delayed(const Duration(milliseconds: 0));
    return true;
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.white,
      body: FutureBuilder<bool>(
        future: getData(),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (!snapshot.hasData) {
            return const SizedBox();
          } else {
            return Padding(
              padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  appBar(),
                  Expanded(
                    child: FutureBuilder<bool>(
                      future: getData(),
                      builder:
                          (BuildContext context, AsyncSnapshot<bool> snapshot) {
                        if (!snapshot.hasData) {
                          return const SizedBox();
                        } else {
                          return PropertiesGrid(_showOnlyFavorites);
                        }
                      },
                    ),
                  ),
                ],
              ),
            );
          }
        },
      ),
    );
  }

  Widget appBar() {
    return SizedBox(
      height: AppBar().preferredSize.height,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top: 8, left: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
            ),
          ),
          Expanded(
            child: Center(
              child: Padding(
                padding: const EdgeInsets.only(top: 4),
                child:
                    Image.asset('assets/images/logo.png', fit: BoxFit.contain),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 8, right: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
              color: Colors.white,
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  borderRadius:
                      BorderRadius.circular(AppBar().preferredSize.height),
                  child: Icon(
                    multiple ? Icons.dashboard : Icons.view_agenda,
                    color: AppTheme.dark_grey,
                  ),
                  onTap: () {
                    setState(() {
                      multiple = !multiple;
                    });
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

as I have a widget which have the GridView.builder as the below code:

import 'package:aradi_online_vtwo/providers/properties.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../providers/properties.dart';
import './property_item.dart';

class PropertiesGrid extends StatelessWidget {
  final bool showFavs;

  PropertiesGrid(this.showFavs);

  @override
  Widget build(BuildContext context) {
    final productsData = Provider.of<Properties>(context);
    final products = showFavs ? productsData.favoriteItems : productsData.items;
    return GridView.builder(
      padding: const EdgeInsets.all(10.0),
      itemCount: products.length,
      itemBuilder: (ctx, i) => ChangeNotifierProvider.value(
            // builder: (c) => products[i],
            value: products[i],
            child: PropertyItem(
                // products[i].id,
                // products[i].title,
                // products[i].imageUrl,
                ),
          ),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 1,
        childAspectRatio: 3 / 2,
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
      ), scrollDirection: Axis.horizontal,
    );
  }
}

I tried to set the height of the grid by wrapping it with a Container and set the height of it as to add more grids but it doesn't work.

and here's my Grid Item widget code:

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

import '../providers/property.dart';

class PropertyItem extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final property = Provider.of<Property>(context, listen: false);
    return InkWell(
      onTap: () => {},
      child: Card(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(15),
        ),
        elevation: 7,
        margin: EdgeInsets.all(2),
        child: Stack(
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(15),
                topRight: Radius.circular(15),
              ),
              // color: Colors.transparent,
              child: Image.asset(
                property.image,
                fit: BoxFit.fill,
              ),
            ),
            Positioned(
              top: 8,
              right: 8,
              child: Consumer<Property>(
                builder: (ctx, property, _) => IconButton(
                  icon: Icon(
                    property.isFavorite ? Icons.favorite : Icons.favorite_border,
                  ),
                  color: Colors.red,
                  onPressed: () {
                    property.toggleFavoriteStatus();
                  },
                ),
              ),
            ),
            Positioned(
                  right: 20,
                  top: 100,
                  child: Container(
                    width: 300,
                    color: Colors.black54,
                    padding: EdgeInsets.symmetric(
                      vertical: 5,
                      horizontal: 20,
                    ),
                    child: Text(
                      property.title,
                      style: TextStyle(
                        fontSize: 20,
                        color: Colors.white,
                      ),
                      softWrap: true,
                      overflow: TextOverflow.fade,
                    ),
                  ),
                )
          ],
        ),
      ),
    );
  }
}

Body:
You'll need a column where each ListView or GridView is wrapped inside a SizedBox (if you have a specific height) and you also can use Expanded to take whatever available space (like the last one in the given example):

You can post the code below in dartpad.dev and see how it works:

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    theme: ThemeData(
      primarySwatch: Colors.blue,
    ),
    home: MyApp(),
  ));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          SizedBox(
            height: 100,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: 10,
              itemBuilder: (c, i) {
                return Card(
                  child: Container(
                    height: 100,
                    width: 100,
                    child: Center(child: Text("$i")),
                  ),
                );
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Align(
              child: Text("The Second List"),
              alignment: Alignment.centerRight,
            ),
          ),
          SizedBox(
            height: 100,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: 10,
              itemBuilder: (c, i) {
                return Card(
                  child: Container(
                    height: 100,
                    width: 100,
                    child: Center(child: Text("$i")),
                  ),
                );
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Align(
              child: Text("The Third List"),
              alignment: Alignment.centerRight,
            ),
          ),
          Expanded(
            //height: 200,
            child: GridView.builder(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                childAspectRatio: 3 / 2,
                crossAxisSpacing: 10,
                mainAxisSpacing: 10,
              ),
              scrollDirection: Axis.vertical,
              itemCount: 20,
              itemBuilder: (c, i) {
                return Card(
                  child: Container(
                    height: 100,
                    width: 100,
                    child: Center(child: Text("$i")),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}


问:
How to change color of individual chart elements color in powerpoint
I have an issue, suppose a chart (with all data required) is already inserted in powerpoint slide .Now what i want to do is if a person clicks on chart title or bars/columns or legend or chart background, the back color of that element should change to, say, black color.
In word app I am able to do same with

```<code>application.Selection.InlineShapes[1].Fill.ForeColor.RGB = setColor;
</code>```

How to do same in powerpoint.

What I tried in powerpoint is:

```<code>application.ActiveWindow.Selection.ShapeRange[1].Fill.BackColor.RGB = 0;
</code>```

But this always changes color of chart background and Selection.ShapeRange[1].Name is always "placeholder".

Only want to change color of single element. If user click on 1 bar, the color of that bar should change to black and no other element should change similarly if chart title is clicked background of that only should change. I am new to .net and help on this. And I think I am able to explain my concern .
Last thing what i tried is

```<code>ColorStyle colorstyle2 = MyAddin.AddinModule.CurrentInstance.SelectedColorStyle;
int setColor = ColorTranslator.ToOle(System.Drawing.Color.FromArgb(colorstyle2.R, colorstyle2.G, colorstyle2.B));
int position = app.ActiveWindow.Selection.ShapeRange.ZOrderPosition;
Slide slide2 = (Slide)app.ActiveWindow.View.Slide;// SELECTS CHART FROM SHAPE RANGE AS SELECTION HAS SHAPERANGE not shape
powerPoint.Shape s = slide2.Shapes[position];
if (s.HasChart==MsoTriState.msoTrue)
{
    object cht = s.GetType().InvokeMember("Chart", BindingFlags.GetProperty, null, (object)s, null);
    object chtFormat = cht.GetType().InvokeMember("Format", BindingFlags.GetProperty, null, (object)cht, null);
    object chtFill = cht.GetType().InvokeMember("Fill", BindingFlags.GetProperty, null, (object)chtFormat, null);
    object chtBackcolor = chtFill.GetType().InvokeMember("Backcolor", BindingFlags.GetProperty, null, (object)chtFill, null);
    object[] args = { 0 };//also used {0} here
    object chtRGB = chtBackcolor.GetType().InvokeMember("RGB", BindingFlags.SetProperty, null, (object)chtBackcolor, args);
}
</code>```

答:
I have posted this questions on many forums but seems like there is no solution.Although I have a work around there is a property
chart.GetChartElement use it like

```<code>int ElementId = -1, arg1 = -1, arg2 = -1;
chart.GetChartElement(X, Y, ref ElementId, ref arg1, ref arg2)
//in which
//X is relative position of element wrt to chart
// similarly Y
var chartitem = (powerPoint.XlChartItem)ElementId;
switch (chartitem)
{
 case powerPoint.XlChartItem.xlDataLabel:break;
 case powerPoint.XlChartItem.xlChartArea:break;
 case powerPoint.XlChartItem.xlSeries:break;
 case powerPoint.XlChartItem.xlChartTitle:break;
 case powerPoint.XlChartItem.xlDataTable:break;
 case powerPoint.XlChartItem.xlMajorGridlines:break;
 case powerPoint.XlChartItem.xlMinorGridlines:break;
 case powerPoint.XlChartItem.xlAxisTitle:break;
 case powerPoint.XlChartItem.xlPlotArea:break;
 case powerPoint.XlChartItem.xlAxis:break;
 case powerPoint.XlChartItem.xlLegendEntry:break;
 case powerPoint.XlChartItem.xlLegendKey:break;
 case powerPoint.XlChartItem.xlLegend:break;
 default: break;
}
</code>```

agr1 and arg2 gives extra info like which series/data label is clicked and which point .The result is 90 percent accurate as it depends on position which is clicked.

Body:
I have an issue, suppose a chart (with all data required) is already inserted in powerpoint slide .Now what i want to do is if a person clicks on chart title or bars/columns or legend or chart background, the back color of that element should change to, say, black color.
In word app I am able to do same with

application.Selection.InlineShapes[1].Fill.ForeColor.RGB = setColor;

How to do same in powerpoint.

What I tried in powerpoint is:

application.ActiveWindow.Selection.ShapeRange[1].Fill.BackColor.RGB = 0;

But this always changes color of chart background and Selection.ShapeRange[1].Name is always "placeholder".

Only want to change color of single element. If user click on 1 bar, the color of that bar should change to black and no other element should change similarly if chart title is clicked background of that only should change. I am new to .net and help on this. And I think I am able to explain my concern .
Last thing what i tried is

ColorStyle colorstyle2 = MyAddin.AddinModule.CurrentInstance.SelectedColorStyle;
int setColor = ColorTranslator.ToOle(System.Drawing.Color.FromArgb(colorstyle2.R, colorstyle2.G, colorstyle2.B));
int position = app.ActiveWindow.Selection.ShapeRange.ZOrderPosition;
Slide slide2 = (Slide)app.ActiveWindow.View.Slide;// SELECTS CHART FROM SHAPE RANGE AS SELECTION HAS SHAPERANGE not shape
powerPoint.Shape s = slide2.Shapes[position];
if (s.HasChart==MsoTriState.msoTrue)
{
    object cht = s.GetType().InvokeMember("Chart", BindingFlags.GetProperty, null, (object)s, null);
    object chtFormat = cht.GetType().InvokeMember("Format", BindingFlags.GetProperty, null, (object)cht, null);
    object chtFill = cht.GetType().InvokeMember("Fill", BindingFlags.GetProperty, null, (object)chtFormat, null);
    object chtBackcolor = chtFill.GetType().InvokeMember("Backcolor", BindingFlags.GetProperty, null, (object)chtFill, null);
    object[] args = { 0 };//also used {0} here
    object chtRGB = chtBackcolor.GetType().InvokeMember("RGB", BindingFlags.SetProperty, null, (object)chtBackcolor, args);
}

Body:
I have posted this questions on many forums but seems like there is no solution.Although I have a work around there is a property
chart.GetChartElement use it like

int ElementId = -1, arg1 = -1, arg2 = -1;
chart.GetChartElement(X, Y, ref ElementId, ref arg1, ref arg2)
//in which
//X is relative position of element wrt to chart
// similarly Y
var chartitem = (powerPoint.XlChartItem)ElementId;
switch (chartitem)
{
 case powerPoint.XlChartItem.xlDataLabel:break;
 case powerPoint.XlChartItem.xlChartArea:break;
 case powerPoint.XlChartItem.xlSeries:break;
 case powerPoint.XlChartItem.xlChartTitle:break;
 case powerPoint.XlChartItem.xlDataTable:break;
 case powerPoint.XlChartItem.xlMajorGridlines:break;
 case powerPoint.XlChartItem.xlMinorGridlines:break;
 case powerPoint.XlChartItem.xlAxisTitle:break;
 case powerPoint.XlChartItem.xlPlotArea:break;
 case powerPoint.XlChartItem.xlAxis:break;
 case powerPoint.XlChartItem.xlLegendEntry:break;
 case powerPoint.XlChartItem.xlLegendKey:break;
 case powerPoint.XlChartItem.xlLegend:break;
 default: break;
}

agr1 and arg2 gives extra info like which series/data label is clicked and which point .The result is 90 percent accurate as it depends on position which is clicked.


问:
Nuxt: using `optional chaining operator` operator (.?)
Nuxt 2.12.2 throw error on build when trying to use object?.key.

Module parse failed: Unexpected token (311:25)                                                                                friendly-errors 10:36:40
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file
```

<p>So it because <code>babel</code> in Nuxt configured to support older browsers like <code>IE9</code> that I did not need in my project. </p>

<p>In another project, I just put <code>.bablelrc</code></p>

```{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 2 Chrome versions"]
      }
    }]
  ]
}
```

but in Nuxt .bablelrc are disabled. so how can I make optional chaining operator work ?

by telling Nuxt to support just modern browsers. or added the @babel/plugin-proposal-optional-chaining

答:
As Nuxtjs Doc describe, .babelrc is ignored by default.

I solved this question by the below config.

// in nuxt.config.js
{
  // ...
  build: {
    // ....
    babel: {
      plugins: [
        '@babel/plugin-proposal-optional-chaining'
      ]
    }
  }
}
```

<p>Of course, before that, you should install <code>@babel/plugin-proposal-optional-chaining</code></p>

<pre class="lang-sh prettyprint-override"><code>npm i -D @babel/plugin-proposal-optional-chaining
</code>```

I hope it helps you.

Body:
Nuxt 2.12.2 throw error on build when trying to use object?.key.

Module parse failed: Unexpected token (311:25)                                                                                friendly-errors 10:36:40
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file

So it because babel in Nuxt configured to support older browsers like IE9 that I did not need in my project.

In another project, I just put .bablelrc

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 2 Chrome versions"]
      }
    }]
  ]
}

but in Nuxt .bablelrc are disabled. so how can I make optional chaining operator work ?

by telling Nuxt to support just modern browsers. or added the @babel/plugin-proposal-optional-chaining

Body:
As Nuxtjs Doc describe, .babelrc is ignored by default.

I solved this question by the below config.

// in nuxt.config.js
{
  // ...
  build: {
    // ....
    babel: {
      plugins: [
        '@babel/plugin-proposal-optional-chaining'
      ]
    }
  }
}

Of course, before that, you should install @babel/plugin-proposal-optional-chaining

npm i -D @babel/plugin-proposal-optional-chaining

I hope it helps you.