问:
Why does the echo statement not print my string elements in the correct order in C-shell script?
I am trying to run the following code in a C-shell script. The third echo statement should piece together the $f1 and $org_mod variables to form a Unix command containing two path names.

```<code># compute azimuth for the start and end
set pin1 = `head -1 $2 | awk '{print $1,$2}'`
set f1 = `head -1 tmprecord`
echo $f1    # my addition
echo $org_mod   # my addition
echo "make_s1a_tops $f1/annotation/*iw1*"$org_mod"*xml $f1/measurement/*iw1*"$org_mod"*tiff tmp2 0"
make_s1a_tops $f1/annotation/*iw1*"$org_mod"*xml $f1/measurement/*iw1*"$org_mod"*tiff tmp2 0
ext_orb_s1a tmp2.PRM $orbit tmp2
set tmpazi = `echo $pin1 | awk '{print $1,$2,0}' | SAT_llt2rat tmp2.PRM 1 | awk '{printf("%d",$2+0.5)}'`
 # refine the calculation in case the pin is far away from the starting frame. (baseline error)
shift_atime_PRM.csh tmp2.PRM $tmpazi
set azi1 = `echo $pin1 | awk '{print $1,$2,0}' | SAT_llt2rat tmp2.PRM 1 | awk '{printf("%d",$2+0.5 + '$tmpazi')}'`
</code>```

The shell output is as follows:

```<code>/mnt/d/Projecten/Bodemdaling/Working_directories/Hawaii/asc/data/S1A_IW_SLC__1SDV_20220919T043936_20220919T044006_045069_0562A9_C912.SAFE
vv
/measurement/*iw1*vv*tiff tmp2 0rojecten/Bodemdaling/Working_directories/Hawaii/asc/data/S1A_IW_SLC__1SDV_20220919T043936_20220919T044006_045069_0562A9_C912.SAFE
make_s1a_tops: No match.
 Couldn't open xml file:
 tmp2.PRM
couldn't open master.PRM
</code>```

As can be seen the string does not formulate paths in the correct order, and also causes some changes such as "Projecten" ==> "0rojecten".

What could be the reason for this, and how could I print the string in the correct manner?

I added lines to separately print the variables to check whether these were OK.
I tried to run the code with $f1 in quotation marks, but this did not produce better results.

Body:
I am trying to run the following code in a C-shell script. The third echo statement should piece together the $f1 and $org_mod variables to form a Unix command containing two path names.

# compute azimuth for the start and end
set pin1 = `head -1 $2 | awk '{print $1,$2}'`
set f1 = `head -1 tmprecord`
echo $f1    # my addition
echo $org_mod   # my addition
echo "make_s1a_tops $f1/annotation/*iw1*"$org_mod"*xml $f1/measurement/*iw1*"$org_mod"*tiff tmp2 0"
make_s1a_tops $f1/annotation/*iw1*"$org_mod"*xml $f1/measurement/*iw1*"$org_mod"*tiff tmp2 0
ext_orb_s1a tmp2.PRM $orbit tmp2
set tmpazi = `echo $pin1 | awk '{print $1,$2,0}' | SAT_llt2rat tmp2.PRM 1 | awk '{printf("%d",$2+0.5)}'`
 # refine the calculation in case the pin is far away from the starting frame. (baseline error)
shift_atime_PRM.csh tmp2.PRM $tmpazi
set azi1 = `echo $pin1 | awk '{print $1,$2,0}' | SAT_llt2rat tmp2.PRM 1 | awk '{printf("%d",$2+0.5 + '$tmpazi')}'`

The shell output is as follows:

/mnt/d/Projecten/Bodemdaling/Working_directories/Hawaii/asc/data/S1A_IW_SLC__1SDV_20220919T043936_20220919T044006_045069_0562A9_C912.SAFE
vv
/measurement/*iw1*vv*tiff tmp2 0rojecten/Bodemdaling/Working_directories/Hawaii/asc/data/S1A_IW_SLC__1SDV_20220919T043936_20220919T044006_045069_0562A9_C912.SAFE
make_s1a_tops: No match.
 Couldn't open xml file:
 tmp2.PRM
couldn't open master.PRM

As can be seen the string does not formulate paths in the correct order, and also causes some changes such as "Projecten" ==> "0rojecten".

What could be the reason for this, and how could I print the string in the correct manner?

I added lines to separately print the variables to check whether these were OK.
I tried to run the code with $f1 in quotation marks, but this did not produce better results.


来源: stackexchange

问:
Java OpenCV 3.4 camera resolution cropping image
I have web camera with resolution 2048x1536.
In my project I want to get smaller picture: 1280x960

I'm using

camera.open(device, Videoio.CAP_DSHOW);
camera.set(Videoio.CAP_PROP_FRAME_WIDTH, 1280);
camera.set(Videoio.CAP_PROP_FRAME_HEIGHT, 960);
```

but getting cropped image.

How can I get full image whithout cropping with resolution 1280*960?

ContentLicense: CC BY-SA 4.0

Body:
I have web camera with resolution 2048x1536.
In my project I want to get smaller picture: 1280x960

I'm using

camera.open(device, Videoio.CAP_DSHOW);
camera.set(Videoio.CAP_PROP_FRAME_WIDTH, 1280);
camera.set(Videoio.CAP_PROP_FRAME_HEIGHT, 960);

but getting cropped image.

How can I get full image whithout cropping with resolution 1280*960?


问:
How to fix an AttributeError: 'NoneType' object has no attribute 'get_text'
My problem is that i keep getting this error "AttributeError: 'NoneType' object has no attribute 'get_text'"

Can someone please explain what can I do to fix this type of error. Thanks

This is using python and BeautifulSoup inside jupiternb

URL = 'https://www.amazon.com/Funny-Data-Systems-Business-Analyst/dp/B07FNW9FGJ/ref=sr_1_3?dchild=1&keywords=data%2Banalyst%2Btshirt&qid=1626655184&sr=8'

headers =  {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"}

page = requests.get(URL, headers=headers)

soup1 = BeautifulSoup(page.content, "html.parser")

soup2 = BeautifulSoup(soup1.prettify(), "html.parser")

title = soup2.find(id='title').get_text()

print(title)

Results:

```<code>AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_1944\3978847060.py in <module>
     11 soup2 = BeautifulSoup(soup1.prettify(), "html.parser")
     12
---> 13 title = soup2.find(id='title').get_text()
     14
     15 print(title)

AttributeError: 'NoneType' object has no attribute 'get_text'
</code>```

Body:
My problem is that i keep getting this error "AttributeError: 'NoneType' object has no attribute 'get_text'"

Can someone please explain what can I do to fix this type of error. Thanks

This is using python and BeautifulSoup inside jupiternb

URL = 'https://www.amazon.com/Funny-Data-Systems-Business-Analyst/dp/B07FNW9FGJ/ref=sr_1_3?dchild=1&keywords=data%2Banalyst%2Btshirt&qid=1626655184&sr=8'

headers =  {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"}

page = requests.get(URL, headers=headers)

soup1 = BeautifulSoup(page.content, "html.parser")

soup2 = BeautifulSoup(soup1.prettify(), "html.parser")

title = soup2.find(id='title').get_text()

print(title)

Results:

AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_1944\3978847060.py in <module>
     11 soup2 = BeautifulSoup(soup1.prettify(), "html.parser")
     12
---> 13 title = soup2.find(id='title').get_text()
     14
     15 print(title)

AttributeError: 'NoneType' object has no attribute 'get_text'


问:
Exceding Tags bordor while printing
I'm working on a webapplication (front-end) and I've added the Print option :

I'm working on double monitors :

1920x1080 second monitor

1280x720 laptop screen

So the problem here is happen while printing:

laptop screen :

it works perfectly

Second monitor :

it doesn't work perfectly because as we see here in the yellow cercle ; the design exceeds the tags

I'm using the @print on my CSS file. the first solution that comes to my mind is to fix the screen size while printing so i did :

```<code>@media print {
    @page {
        margin: 0 !important;
        width:1280px;
        height:720px;

    }
</code>```

but it didn't work!

All I need is to print on any screen resolutions without messing the format ?
I need to make all screens have the same resolution as my laptop ( 1280*720 ) **while printing **, because when i print using my laptop screen, it works perfectly :

Thank you !

Title: Exceding Tags bordor while printing

Body:
I'm working on a webapplication (front-end) and I've added the Print option :

I'm working on double monitors :

1920x1080 second monitor

1280x720 laptop screen

So the problem here is happen while printing:

laptop screen :

it works perfectly

Second monitor :

it doesn't work perfectly because as we see here in the yellow cercle ; the design exceeds the tags

I'm using the @print on my CSS file. the first solution that comes to my mind is to fix the screen size while printing so i did :

@media print {
    @page {
        margin: 0 !important;
        width:1280px;
        height:720px;

    }

but it didn't work!

All I need is to print on any screen resolutions without messing the format ?
I need to make all screens have the same resolution as my laptop ( 1280*720 ) **while printing **, because when i print using my laptop screen, it works perfectly :

Thank you !


问:
Django - Form-Select field set as not required not working
I have a form and want to make some fields not required.

It's working for most, but pairing_rum field (and a few others) are causing some difficulties. For this question I removed the other fields as they are in the same format as rum_pairing.

Here is what I tried so far:

using the same format as venue ie forms.ModelChoiceField(queryset = Venue.objects.all() - but how can I filter to only get the choices contained within the field of the model?

I also tried to modify the forms __init__, but no luck (example below - sorry for the formatting, stack is not letting me putting it in a code format)

def init(self, *args, **kwargs):
super(ReviewRating, self).init(*args, **kwargs)
self.fields['pairing_rum'].required = False

Which renders the following error:
super(type, obj): obj must be an instance or subtype of type

What would be the best way to make pairing_rum field not requried?

My current code is as follows:

models

```<code>class ReviewRating(models.Model):
    user = models.ForeignKey(User,blank=True,null=True, on_delete=models.SET_NULL, related_name="usercomments")     product=models.ForeignKey(Product,related_name="comments",null=True, on_delete=models.SET_NULL)
    pairing_coffee = models.IntegerField(choices=COFFEE_PAIRING, default=0, blank=True, null=True)
    pairing_rum = models.IntegerField(choices=RUM_PAIRING, default=0, blank=True, null=True)
    pairing_gin = models.IntegerField(choices=GIN_PAIRING, default=0, blank=True, null=True)
    pairing_whisky = models.IntegerField(choices=WHISKY_PAIRING, default=0, blank=True, null=True)
    pairing_event = models.ForeignKey(CatalogueEvent, related_name="pairing_event",on_delete=models.SET_NULL,blank=True, null=True)
    pairing_venue = models.ForeignKey(Catalogue, related_name="pairing_venue",on_delete=models.SET_NULL,blank=True, null=True)
    review =models.TextField(max_length=250, blank=True)
    rating =models.IntegerField(choices=RATING, default=0)
    venue = models.ForeignKey(Venue, blank=True, null=True, related_name="venues", on_delete=models.SET_NULL)
</code>```

forms

```<code>class ReviewForm(forms.ModelForm):
    venue = forms.ModelChoiceField(queryset = Venue.objects.all(),required=False)

    class Meta:
        model = ReviewRating
        fields = ['review', 'rating','venue','pairing_coffee', 'pairing_rum','pairing_gin','pairing_whisky', 'pairing_event','pairing_venue']
        widgets = {
                    'venue': forms.TextInput(attrs={'class':'form-select', 'placeholder':'Enter name'}),
                    'pairing_coffee': forms.Select(attrs={'class':'form-select', 'placeholder':'Enter name'}),
                    'pairing_rum': forms.Select(attrs={'class':'form-select', 'placeholder':'Enter name'}),
                    'pairing_gin': forms.Select(attrs={'class':'form-select', 'placeholder':'Enter name'}),
                    'pairing_whisky': forms.Select(attrs={'class':'form-select', 'placeholder':'Enter name'}),
                    'pairing_event': forms.Select(attrs={'class':'form-select', 'placeholder':'Enter name'}),
                    'pairing_venue': forms.Select(attrs={'class':'form-select', 'placeholder':'Enter name'}),
                }
</code>```

views

```<code>def show_product(request, product_id):
    url = request.META.get('HTTP_REFERER')
    product = Product.objects.get(pk=product_id)
    form = ReviewForm()
    submitted = False
    data = Product.objects.filter(pk=product_id).annotate(
            avg_rating =Avg('comments__rating'),)
    if request.method == "POST" and 'btnreview_form' in request.POST:
        form = ReviewForm(request.POST)

        if form.is_valid():
            data = form.save(commit=False)
            data.product_id = product_id
            data.user_id = request.user.id
            data.save()
            form.save()
            return redirect(url)
        else:
            print(form.errors)

    else:
        print(form.errors)
    return render(request,"main/show_product.html", {'form':form, 'submitted':submitted, 'product':product, 'venue_form':venue_form, 'data':data})
</code>```

template

```<code>    {% if user.is_authenticated %}
    <form action="{% url 'show-product' product.id%}" method="POST">
        {% csrf_token %}

        <div class="rate">
            <input type="radio" name="rating" id="rating1" value="1" required /><label for="rating1" title="1"></label>
            <input type="radio" name="rating" id="rating2" value="2" required /><label for="rating2" title="2"></label>
            <input type="radio" name="rating" id="rating3" value="3" required /><label for="rating3" title="3"></label>
            <input type="radio" name="rating" id="rating4" value="4" required /><label for="rating4" title="4"></label>
            <input type="radio" name="rating" id="rating5" value="5" required /><label for="rating5" title="5"></label>
        </div>
        {%if product.category == 1 %}
        {{ form.pairing_rum|as_crispy_field }}

        {%endif%}
        {%if product.category == 2 %}
        {{ form.pairing_gin|as_crispy_field }}

        {%endif%}
        {%if product.category == 3 %}
        {{ form.pairing_whisky|as_crispy_field }}

        {%endif%}
        {%if product.category == 8 %}
        {{ form.pairing_coffee|as_crispy_field }}

        {%endif%}

        {{ form.review|as_crispy_field }}
        {{ form.venue|as_crispy_field }}
        {% comment %} <a class="btn btn-outline-secondary btn-sm" href ="" data-toggle="modal" data-target="#AddVenueFormModal" ><font size="3px" color="#008083">Can't find the venue?</font></a> {% endcomment %}
        <input type="submit" name="btnreview_form" value="Submit Review" class="btn btn-primary custom-btn">
    </form>
    </br>
    {% else %}

    {% endif %}
</code>```

EDITED to add Traceback

The traceback indicates there is a problem at form.save(commit=False)

```<code>[23/Dec/2022 13:53:39] "GET /show_product/109 HTTP/1.1" 200 15414
Internal Server Error: /show_product/109
Traceback (most recent call last):
  File "C:\Users\CeX\Virtual\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\CeX\Virtual\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\CeX\Dev\mysite\main\views.py", line 760, in show_product
    data = form.save(commit=False)
  File "C:\Users\CeX\Virtual\lib\site-packages\django\forms\models.py", line 539, in save
    raise ValueError(
ValueError: The ReviewRating could not be created because the data didn't validate.
</code>```

New edit following Iain Shelvington's recommendation the error is the following:

Ironically, this is the code that I did deem necessary to be in the post that is causing the problem. Which is weird considering this is a pure copy/paste of the pairing_rum. 'pairing_rum` even when empty does not return any error message, but the others do.

```<code>[23/Dec/2022 14:21:50] "GET /show_product/109 HTTP/1.1" 200 15430
<ul class="errorlist"><li>pairing_coffee<ul class="errorlist"><li>Select a valid choice. 0 is not one of the available choices.</li></ul></li><li>pairing_gin<ul class="errorlist"><li>Select a valid choice. 0 is not one of the available choices.</li></ul></li><li>pairing_whisky<ul class="errorlist"><li>Select a valid choice. 0 is not one of the available choices.</li></ul></li></ul>
</code>```

Body:
I have a form and want to make some fields not required.

It's working for most, but pairing_rum field (and a few others) are causing some difficulties. For this question I removed the other fields as they are in the same format as rum_pairing.

Here is what I tried so far:

using the same format as venue ie forms.ModelChoiceField(queryset = Venue.objects.all() - but how can I filter to only get the choices contained within the field of the model?

I also tried to modify the forms __init__, but no luck (example below - sorry for the formatting, stack is not letting me putting it in a code format)

def init(self, *args, **kwargs):
super(ReviewRating, self).init(*args, **kwargs)
self.fields['pairing_rum'].required = False

Which renders the following error:
super(type, obj): obj must be an instance or subtype of type

What would be the best way to make pairing_rum field not requried?

My current code is as follows:

models

class ReviewRating(models.Model):
    user = models.ForeignKey(User,blank=True,null=True, on_delete=models.SET_NULL, related_name="usercomments")     product=models.ForeignKey(Product,related_name="comments",null=True, on_delete=models.SET_NULL)
    pairing_coffee = models.IntegerField(choices=COFFEE_PAIRING, default=0, blank=True, null=True)
    pairing_rum = models.IntegerField(choices=RUM_PAIRING, default=0, blank=True, null=True)
    pairing_gin = models.IntegerField(choices=GIN_PAIRING, default=0, blank=True, null=True)
    pairing_whisky = models.IntegerField(choices=WHISKY_PAIRING, default=0, blank=True, null=True)
    pairing_event = models.ForeignKey(CatalogueEvent, related_name="pairing_event",on_delete=models.SET_NULL,blank=True, null=True)
    pairing_venue = models.ForeignKey(Catalogue, related_name="pairing_venue",on_delete=models.SET_NULL,blank=True, null=True)
    review =models.TextField(max_length=250, blank=True)
    rating =models.IntegerField(choices=RATING, default=0)
    venue = models.ForeignKey(Venue, blank=True, null=True, related_name="venues", on_delete=models.SET_NULL)

forms

class ReviewForm(forms.ModelForm):
    venue = forms.ModelChoiceField(queryset = Venue.objects.all(),required=False)

    class Meta:
        model = ReviewRating
        fields = ['review', 'rating','venue','pairing_coffee', 'pairing_rum','pairing_gin','pairing_whisky', 'pairing_event','pairing_venue']
        widgets = {
                    'venue': forms.TextInput(attrs={'class':'form-select', 'placeholder':'Enter name'}),
                    'pairing_coffee': forms.Select(attrs={'class':'form-select', 'placeholder':'Enter name'}),
                    'pairing_rum': forms.Select(attrs={'class':'form-select', 'placeholder':'Enter name'}),
                    'pairing_gin': forms.Select(attrs={'class':'form-select', 'placeholder':'Enter name'}),
                    'pairing_whisky': forms.Select(attrs={'class':'form-select', 'placeholder':'Enter name'}),
                    'pairing_event': forms.Select(attrs={'class':'form-select', 'placeholder':'Enter name'}),
                    'pairing_venue': forms.Select(attrs={'class':'form-select', 'placeholder':'Enter name'}),
                }

views

def show_product(request, product_id):
    url = request.META.get('HTTP_REFERER')
    product = Product.objects.get(pk=product_id)
    form = ReviewForm()
    submitted = False
    data = Product.objects.filter(pk=product_id).annotate(
            avg_rating =Avg('comments__rating'),)
    if request.method == "POST" and 'btnreview_form' in request.POST:
        form = ReviewForm(request.POST)

        if form.is_valid():
            data = form.save(commit=False)
            data.product_id = product_id
            data.user_id = request.user.id
            data.save()
            form.save()
            return redirect(url)
        else:
            print(form.errors)

    else:
        print(form.errors)
    return render(request,"main/show_product.html", {'form':form, 'submitted':submitted, 'product':product, 'venue_form':venue_form, 'data':data})

template

    {% if user.is_authenticated %}
    <form action="{% url 'show-product' product.id%}" method="POST">
        {% csrf_token %}

            <input type="radio" name="rating" id="rating1" value="1" required />
            <input type="radio" name="rating" id="rating2" value="2" required />
            <input type="radio" name="rating" id="rating3" value="3" required />
            <input type="radio" name="rating" id="rating4" value="4" required />
            <input type="radio" name="rating" id="rating5" value="5" required />

        {%if product.category == 1 %}
        {{ form.pairing_rum|as_crispy_field }}

        {%endif%}
        {%if product.category == 2 %}
        {{ form.pairing_gin|as_crispy_field }}

        {%endif%}
        {%if product.category == 3 %}
        {{ form.pairing_whisky|as_crispy_field }}

        {%endif%}
        {%if product.category == 8 %}
        {{ form.pairing_coffee|as_crispy_field }}

        {%endif%}

        {{ form.review|as_crispy_field }}
        {{ form.venue|as_crispy_field }}
        {% comment %} Can't find the venue? {% endcomment %}
        <input type="submit" name="btnreview_form" value="Submit Review" class="btn btn-primary custom-btn">
    </form>

    {% else %}

    {% endif %}

EDITED to add Traceback

The traceback indicates there is a problem at form.save(commit=False)

[23/Dec/2022 13:53:39] "GET /show_product/109 HTTP/1.1" 200 15414
Internal Server Error: /show_product/109
Traceback (most recent call last):
  File "C:\Users\CeX\Virtual\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\CeX\Virtual\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\CeX\Dev\mysite\main\views.py", line 760, in show_product
    data = form.save(commit=False)
  File "C:\Users\CeX\Virtual\lib\site-packages\django\forms\models.py", line 539, in save
    raise ValueError(
ValueError: The ReviewRating could not be created because the data didn't validate.

New edit following Iain Shelvington's recommendation the error is the following:

Ironically, this is the code that I did deem necessary to be in the post that is causing the problem. Which is weird considering this is a pure copy/paste of the pairing_rum. 'pairing_rum` even when empty does not return any error message, but the others do.

[23/Dec/2022 14:21:50] "GET /show_product/109 HTTP/1.1" 200 15430

pairing_coffee

Select a valid choice. 0 is not one of the available choices.

pairing_gin

Select a valid choice. 0 is not one of the available choices.

pairing_whisky

Select a valid choice. 0 is not one of the available choices.


问:
how to make sure you have a working DCAP setup
I have installed gramine and DCAP using the fifth step:5. Install dependencies for DCAP of link https://gramine.readthedocs.io/en/stable/devel/building.html?highlight=dcap#install-dependencies-for-dcap
my questions are that:
how can I make sure that DCAP is enabled on my server?
how client can verify that his request is executed inside SGX? how can he make sure about it?</p>


问:
AWS SAM AWS::ApiGatewayV2::Stage AccessLogSetting Property validation failure
Unfortunately I cannot get AWS WebSocket logging to work. Property validation failure: [Encountered                                                                                unsupported properties in {/}: [AccessLogSetting]]. Any help highly appreciated.</p>
```<code>   Stage:
    Type: AWS::ApiGatewayV2::Stage
    Properties:
      StageName: Prod
      Description: Prod Stage
      DeploymentId: !Ref Deployment
      ApiId: !Ref TriviaWebSocket
      AccessLogSetting:
        DestinationArn: !GetAtt GwLogGroup.Arn
        Format: '{"requestTime":"$context.requestTime","requestId":"$context.requestId"}'

  GwLogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: /aws/apigateway/gw-ws-loggroup
      RetentionInDays: 7
</code>```

Body:
Unfortunately I cannot get AWS WebSocket logging to work. Property validation failure: [Encountered                                                                                unsupported properties in {/}: [AccessLogSetting]]. Any help highly appreciated.

   Stage:
    Type: AWS::ApiGatewayV2::Stage
    Properties:
      StageName: Prod
      Description: Prod Stage
      DeploymentId: !Ref Deployment
      ApiId: !Ref TriviaWebSocket
      AccessLogSetting:
        DestinationArn: !GetAtt GwLogGroup.Arn
        Format: '{"requestTime":"$context.requestTime","requestId":"$context.requestId"}'

  GwLogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: /aws/apigateway/gw-ws-loggroup
      RetentionInDays: 7


问:
How to handle those specific exceptions from repository? (Android Kotlin)
I'm new to android and I'm developing a few applications for studying.

I've been trying to improve a code that I have but I got stuck in the following problem:
I'm creating a new user, validating it with Google Firebase. I managed to create a user normally but I'm not able to handle with one exception from the register moment which is the "FirebaseAuthUserCollisionException".

I created a class to handle a most of exceptions from email/password mistakes:

```<code>class AddUser(private val repository: UserRepository) {

    @Throws(InvalidUserException::class)
    suspend operator fun invoke(user: UserModel) {
        if(user.email.isEmpty()) {
            throw InvalidUserException("Email cannot be empty")
        }
        if(!Patterns.EMAIL_ADDRESS.matcher(user.email).matches()) {
            throw InvalidUserException("Email is not valid")
        }
        if(user.password.length <= 5) {
            throw InvalidUserException("Password should contain at least 6 characters")
        }
        if(user.password.isEmpty()) {
            throw InvalidUserException("Password cannot be empty")
        }
        if(user.confirmPassword.isEmpty()) {
            throw InvalidUserException("Confirm password cannot be empty")
        }
        if(user.password != user.confirmPassword) {
            throw InvalidUserException("Passwords does not match")
        }
        repository.insert(user)
    }
}
</code>```

My repository:

```<code>class UserRepositoryImpl: UserRepository {
    private var auth: FirebaseAuth = Firebase.auth
    private var database: DatabaseReference = FirebaseDatabase.getInstance().getReference("users")

    override suspend fun insert(user: UserModel) {
        auth = FirebaseAuth.getInstance()
        auth.createUserWithEmailAndPassword(user.email, user.password).addOnCompleteListener {
            if(it.isSuccessful) {
                database.child(user.id.toString()).setValue(user)
            } else {
                //exception here
            }
        }
    }
}
</code>```

When this function is triggered, it navigates to another fragment and toasts the successful message, which is incorrect because the exception happens.

Fragment:

```<code>private fun configEventFlow() = lifecycleScope.launch {
        viewModel.eventFlow.collectLatest { event ->
            when(event) {
                is RegisterViewModel.UiEvent.ShowToast -> {
                    toast(event.message)
                }
                is RegisterViewModel.UiEvent.SaveUser -> {
                    val action = RegisterFragmentDirections.actionRegisterFragmentToMainFragment()
                    findNavController().navigate(action)
                    toast(getString(R.string.register_successfully))
                }
            }
        }
    }

private fun configUserRegistration() = with(binding) {
        fabRegister.setOnClickListener {
            val email = editRegisterEmail.text.toString()
            viewModel.onEvent(RegisterUserEvents.EnteredEmail(email))
            val password = editRegisterPassword.text.toString()
            viewModel.onEvent(RegisterUserEvents.EnteredPassword(password))
            val confirmPassword = editRegisterPasswordConfirm.text.toString()
            viewModel.onEvent(RegisterUserEvents.EnteredConfirmPassword(confirmPassword))
            viewModel.onEvent(RegisterUserEvents.SaveUser)
        }
    }
</code>```

ViewModel:

```<code>@HiltViewModel
class RegisterViewModel @Inject constructor(private val useCases: UserUseCases): ViewModel() {
    private val _email = MutableStateFlow<ResourceState<String>>(ResourceState.Empty())
    private val email: StateFlow<ResourceState<String>> = _email

    private val _password = MutableStateFlow<ResourceState<String>>(ResourceState.Empty())
    private val password: StateFlow<ResourceState<String>> = _password

    private val _confirmPassword = MutableStateFlow<ResourceState<String>>(ResourceState.Empty())
    private val confirmPassword: StateFlow<ResourceState<String>> = _confirmPassword

    private val _eventFlow = MutableSharedFlow<UiEvent>()
    val eventFlow = _eventFlow.asSharedFlow()

    fun onEvent(event: RegisterUserEvents) {
        when(event) {
            is RegisterUserEvents.EnteredEmail -> {
                _email.value = ResourceState.Success(event.value)
            }
            is RegisterUserEvents.EnteredPassword -> {
                _password.value = ResourceState.Success(event.value)
            }
            is RegisterUserEvents.EnteredConfirmPassword -> {
                _confirmPassword.value = ResourceState.Success(event.value)
            }
            is RegisterUserEvents.SaveUser -> {
                viewModelScope.launch {
                    try {
                        useCases.addUser(
                            UserModel(
                                id = System.currentTimeMillis().toInt(),
                                email = email.value.data!!,
                                password = password.value.data!!,
                                confirmPassword = confirmPassword.value.data!!
                            )
                        )
                        _eventFlow.emit(UiEvent.SaveUser)
                    } catch(e: InvalidUserException) {
                        _eventFlow.emit(UiEvent.ShowToast(message = e.message!!))
                    }
                }
            }
        }
    }

    sealed class UiEvent {
        data class ShowToast(val message: String): UiEvent()
        object SaveUser: UiEvent()
    }
}
</code>```

Is there a way that I can manage this specific exception in this pattern? Even if I catch the exception there, the action is completed and my application follows at it was registered but in the database it does not occur because of the exception. Im sure that I'll have to face it again when login to handle specific exceptions from Firebase, which I cannot create this way but I have to receive them and display to the user.

Any suggestions??
Sorry if it's missing any content, tell me and I update asap.

Thanks in advance.

Body:
I'm new to android and I'm developing a few applications for studying.

I've been trying to improve a code that I have but I got stuck in the following problem:
I'm creating a new user, validating it with Google Firebase. I managed to create a user normally but I'm not able to handle with one exception from the register moment which is the "FirebaseAuthUserCollisionException".

I created a class to handle a most of exceptions from email/password mistakes:

class AddUser(private val repository: UserRepository) {

    @Throws(InvalidUserException::class)
    suspend operator fun invoke(user: UserModel) {
        if(user.email.isEmpty()) {
            throw InvalidUserException("Email cannot be empty")
        }
        if(!Patterns.EMAIL_ADDRESS.matcher(user.email).matches()) {
            throw InvalidUserException("Email is not valid")
        }
        if(user.password.length <= 5) {
            throw InvalidUserException("Password should contain at least 6 characters")
        }
        if(user.password.isEmpty()) {
            throw InvalidUserException("Password cannot be empty")
        }
        if(user.confirmPassword.isEmpty()) {
            throw InvalidUserException("Confirm password cannot be empty")
        }
        if(user.password != user.confirmPassword) {
            throw InvalidUserException("Passwords does not match")
        }
        repository.insert(user)
    }
}

My repository:

class UserRepositoryImpl: UserRepository {
    private var auth: FirebaseAuth = Firebase.auth
    private var database: DatabaseReference = FirebaseDatabase.getInstance().getReference("users")

    override suspend fun insert(user: UserModel) {
        auth = FirebaseAuth.getInstance()
        auth.createUserWithEmailAndPassword(user.email, user.password).addOnCompleteListener {
            if(it.isSuccessful) {
                database.child(user.id.toString()).setValue(user)
            } else {
                //exception here
            }
        }
    }
}

When this function is triggered, it navigates to another fragment and toasts the successful message, which is incorrect because the exception happens.

Fragment:

private fun configEventFlow() = lifecycleScope.launch {
        viewModel.eventFlow.collectLatest { event ->
            when(event) {
                is RegisterViewModel.UiEvent.ShowToast -> {
                    toast(event.message)
                }
                is RegisterViewModel.UiEvent.SaveUser -> {
                    val action = RegisterFragmentDirections.actionRegisterFragmentToMainFragment()
                    findNavController().navigate(action)
                    toast(getString(R.string.register_successfully))
                }
            }
        }
    }

private fun configUserRegistration() = with(binding) {
        fabRegister.setOnClickListener {
            val email = editRegisterEmail.text.toString()
            viewModel.onEvent(RegisterUserEvents.EnteredEmail(email))
            val password = editRegisterPassword.text.toString()
            viewModel.onEvent(RegisterUserEvents.EnteredPassword(password))
            val confirmPassword = editRegisterPasswordConfirm.text.toString()
            viewModel.onEvent(RegisterUserEvents.EnteredConfirmPassword(confirmPassword))
            viewModel.onEvent(RegisterUserEvents.SaveUser)
        }
    }

ViewModel:

@HiltViewModel
class RegisterViewModel @Inject constructor(private val useCases: UserUseCases): ViewModel() {
    private val _email = MutableStateFlow<ResourceState<String>>(ResourceState.Empty())
    private val email: StateFlow<ResourceState<String>> = _email

    private val _password = MutableStateFlow<ResourceState<String>>(ResourceState.Empty())
    private val password: StateFlow<ResourceState<String>> = _password

    private val _confirmPassword = MutableStateFlow<ResourceState<String>>(ResourceState.Empty())
    private val confirmPassword: StateFlow<ResourceState<String>> = _confirmPassword

    private val _eventFlow = MutableSharedFlow<UiEvent>()
    val eventFlow = _eventFlow.asSharedFlow()

    fun onEvent(event: RegisterUserEvents) {
        when(event) {
            is RegisterUserEvents.EnteredEmail -> {
                _email.value = ResourceState.Success(event.value)
            }
            is RegisterUserEvents.EnteredPassword -> {
                _password.value = ResourceState.Success(event.value)
            }
            is RegisterUserEvents.EnteredConfirmPassword -> {
                _confirmPassword.value = ResourceState.Success(event.value)
            }
            is RegisterUserEvents.SaveUser -> {
                viewModelScope.launch {
                    try {
                        useCases.addUser(
                            UserModel(
                                id = System.currentTimeMillis().toInt(),
                                email = email.value.data!!,
                                password = password.value.data!!,
                                confirmPassword = confirmPassword.value.data!!
                            )
                        )
                        _eventFlow.emit(UiEvent.SaveUser)
                    } catch(e: InvalidUserException) {
                        _eventFlow.emit(UiEvent.ShowToast(message = e.message!!))
                    }
                }
            }
        }
    }

    sealed class UiEvent {
        data class ShowToast(val message: String): UiEvent()
        object SaveUser: UiEvent()
    }
}

Is there a way that I can manage this specific exception in this pattern? Even if I catch the exception there, the action is completed and my application follows at it was registered but in the database it does not occur because of the exception. Im sure that I'll have to face it again when login to handle specific exceptions from Firebase, which I cannot create this way but I have to receive them and display to the user.

Any suggestions??
Sorry if it's missing any content, tell me and I update asap.

Thanks in advance.


问:
How Can I Fix Link Error: 1104 with visual studio 2022
I know this question has been answered lots already, I have tried the solutions but they are not working for me.

My error is the following:

```<code>Erro: LNK1104   cannot open file 'C:\Users\...\source\repos\ont lang.obj'
</code>```

I am using the latest MSVC compiler and I am using Visual Studio.
I have tried going on task manager and locating tasks running it, but i couldn't find anything.

I have done Properties -> Linker -> General -> Additional Library Properties and assigned that C:\Users\...\source\repos\ont lang;%(AdditionalLibraryDirectories) but i am still getting an error. As you can see here

 General" />

This was the solution in this question but I had no luck. I compiled it about 1 minute before and it worked fine but then I got the Link Error Message 1104. I have also tried this:

but I still had no luck. As i said before, it worked one minute, all I did  to it was more code to the file and the next minute it didn't compile. I have also tried cleaning the project and rebuilding it again but still got the same issue. So does anyone know how I would go about resolving this error?

BTW: I have checked my file is actually real, here is proof:

Body:
I know this question has been answered lots already, I have tried the solutions but they are not working for me.

My error is the following:

Erro: LNK1104   cannot open file 'C:\Users\...\source\repos\ont lang.obj'

I am using the latest MSVC compiler and I am using Visual Studio.
I have tried going on task manager and locating tasks running it, but i couldn't find anything.

I have done Properties -> Linker -> General -> Additional Library Properties and assigned that C:\Users\...\source\repos\ont lang;%(AdditionalLibraryDirectories) but i am still getting an error. As you can see here

 General" />

This was the solution in this question but I had no luck. I compiled it about 1 minute before and it worked fine but then I got the Link Error Message 1104. I have also tried this:

but I still had no luck. As i said before, it worked one minute, all I did  to it was more code to the file and the next minute it didn't compile. I have also tried cleaning the project and rebuilding it again but still got the same issue. So does anyone know how I would go about resolving this error?

BTW: I have checked my file is actually real, here is proof:


问:
Userform Data entry "Update" setting wrong values when editing an entry
So I've got a userform for entering and looking up customer information, Everythign seems to currently work, except for the "Update" Button. When utilizing the update button, its changing my city and state values to my zipcode value, aswell as adjusting whatever else was changed. City and state should not be changing to my zipcode value. city and state values are populated utilizing a vlookup within a zipcodedata tab.

Below is the code for my update button:

```<code>
Private Sub UpdateButton_Click()

If Me.CustID.Value = "" Then
MsgBox "Select customer record to update!"
Exit Sub
End If
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Customer Database")
Dim Selected_Row As Long
Selected_Row = Application.WorksheetFunction.Match(CLng(Me.CustID.Value), ThisWorkbook.Worksheets("Customer Database").Range("A:A"), 0)
'Validations-----------------------------------------------------
If Me.CustomerName.Value = "" Then
MsgBox "Plese enter the customers name!", vbCritical
Exit Sub
End If
'-------
If Me.CustomerBusiness.Value = "" Then
MsgBox "Plese enter the customers business!", vbCritical
Exit Sub
End If
'-------
If Me.CustomerAddress.Value = "" Then
MsgBox "Plese enter the customers address!", vbCritical
Exit Sub
End If
'-------
If Me.CustomerPhone.Value = "" Then
MsgBox "Plese enter the customers phone number!", vbCritical
Exit Sub
End If
'----------------------------------------------------------------
sh.Range("B" & Selected_Row).Value = Me.CustomerName.Value
sh.Range("C" & Selected_Row).Value = Me.CustomerBusiness.Value
sh.Range("D" & Selected_Row).Value = Me.CustomerAddress.Value
sh.Range("E" & Selected_Row).Value = Me.City.Value
sh.Range("F" & Selected_Row).Value = Me.State.Value
sh.Range("G" & Selected_Row).Value = Me.Zipcode.Value
sh.Range("H" & Selected_Row).Value = Me.CustomerPhone.Value
sh.Range("I" & Selected_Row).Value = Me.CustomerEmail.Value
sh.Range("J" & Selected_Row).Value = Me.MachineSerial1.Value
sh.Range("K" & Selected_Row).Value = Me.MachineSerial2.Value
sh.Range("L" & Selected_Row).Value = Me.MachineSerial3.Value

'----------------------------------------------------------------
Me.CustomerName.Value = ""
Me.LCaseName.Value = ""
Me.CustomerBusiness.Value = ""
Me.CustomerAddress.Value = ""
Me.Zipcode.Value = ""
Me.City.Value = ""
Me.State.Value = ""
Me.CustomerPhone.Value = ""
Me.CustomerEmail.Value = ""
Me.MachineSerial1.Value = ""
Me.MachineSerial2.Value = ""
Me.MachineSerial3.Value = ""
Me.CustID.Value = ""
'----------------------------------------------------------------
Call Refresh
End Sub

</code>```

Here is the code for populating the City and State text boxes:

```<code>Private Sub Zipcode_Change()
Dim rng As Range
Dim a As Integer

On Error Resume Next
a = 0
Set rng = Worksheets("ZipCodeData").Range("ZipCodes")
Lastrow = Worksheets("ZipCodeData").Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To Lastrow
If Me.Zipcode = Worksheets("ZipCodeData").Cells(i, 1).Value Then
a = a + 1
End If
Next
If a >= 1 Then
Me.City.Value = Application.WorksheetFunction.VLookup(Zipcode.Value, rng, 2, 0)
Me.State.Value = Application.WorksheetFunction.VLookup(Zipcode.Value, rng, 3, 0)
End If
If a = 0 Then
Me.City.Value = ""
Me.State.Value = ""
End If
End Sub
</code>```

I've tried commenting out my "Zipcode_Change" sub, as I thought perhaps it was having issues interpreting the vlookup values when utilizing the update feature. I have a "add" button (which is identical to the update button, except the Selected_Row is a Last_Row. The "Add" button functions and works as intended, so I recopied my "Add" button code and readjusted it for the update button, and the issue persists.

Body:
So I've got a userform for entering and looking up customer information, Everythign seems to currently work, except for the "Update" Button. When utilizing the update button, its changing my city and state values to my zipcode value, aswell as adjusting whatever else was changed. City and state should not be changing to my zipcode value. city and state values are populated utilizing a vlookup within a zipcodedata tab.

Below is the code for my update button:

Private Sub UpdateButton_Click()

If Me.CustID.Value = "" Then
MsgBox "Select customer record to update!"
Exit Sub
End If
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Customer Database")
Dim Selected_Row As Long
Selected_Row = Application.WorksheetFunction.Match(CLng(Me.CustID.Value), ThisWorkbook.Worksheets("Customer Database").Range("A:A"), 0)
'Validations-----------------------------------------------------
If Me.CustomerName.Value = "" Then
MsgBox "Plese enter the customers name!", vbCritical
Exit Sub
End If
'-------
If Me.CustomerBusiness.Value = "" Then
MsgBox "Plese enter the customers business!", vbCritical
Exit Sub
End If
'-------
If Me.CustomerAddress.Value = "" Then
MsgBox "Plese enter the customers address!", vbCritical
Exit Sub
End If
'-------
If Me.CustomerPhone.Value = "" Then
MsgBox "Plese enter the customers phone number!", vbCritical
Exit Sub
End If
'----------------------------------------------------------------
sh.Range("B" & Selected_Row).Value = Me.CustomerName.Value
sh.Range("C" & Selected_Row).Value = Me.CustomerBusiness.Value
sh.Range("D" & Selected_Row).Value = Me.CustomerAddress.Value
sh.Range("E" & Selected_Row).Value = Me.City.Value
sh.Range("F" & Selected_Row).Value = Me.State.Value
sh.Range("G" & Selected_Row).Value = Me.Zipcode.Value
sh.Range("H" & Selected_Row).Value = Me.CustomerPhone.Value
sh.Range("I" & Selected_Row).Value = Me.CustomerEmail.Value
sh.Range("J" & Selected_Row).Value = Me.MachineSerial1.Value
sh.Range("K" & Selected_Row).Value = Me.MachineSerial2.Value
sh.Range("L" & Selected_Row).Value = Me.MachineSerial3.Value

'----------------------------------------------------------------
Me.CustomerName.Value = ""
Me.LCaseName.Value = ""
Me.CustomerBusiness.Value = ""
Me.CustomerAddress.Value = ""
Me.Zipcode.Value = ""
Me.City.Value = ""
Me.State.Value = ""
Me.CustomerPhone.Value = ""
Me.CustomerEmail.Value = ""
Me.MachineSerial1.Value = ""
Me.MachineSerial2.Value = ""
Me.MachineSerial3.Value = ""
Me.CustID.Value = ""
'----------------------------------------------------------------
Call Refresh
End Sub

Here is the code for populating the City and State text boxes:

Private Sub Zipcode_Change()
Dim rng As Range
Dim a As Integer

On Error Resume Next
a = 0
Set rng = Worksheets("ZipCodeData").Range("ZipCodes")
Lastrow = Worksheets("ZipCodeData").Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To Lastrow
If Me.Zipcode = Worksheets("ZipCodeData").Cells(i, 1).Value Then
a = a + 1
End If
Next
If a >= 1 Then
Me.City.Value = Application.WorksheetFunction.VLookup(Zipcode.Value, rng, 2, 0)
Me.State.Value = Application.WorksheetFunction.VLookup(Zipcode.Value, rng, 3, 0)
End If
If a = 0 Then
Me.City.Value = ""
Me.State.Value = ""
End If
End Sub

I've tried commenting out my "Zipcode_Change" sub, as I thought perhaps it was having issues interpreting the vlookup values when utilizing the update feature. I have a "add" button (which is identical to the update button, except the Selected_Row is a Last_Row. The "Add" button functions and works as intended, so I recopied my "Add" button code and readjusted it for the update button, and the issue persists.


问:
Airflow SetEncoding Latin 1
The Airflow database backend is SQL Server. I am trying to see how can I make sure that airflow sends strings as varchars to the database and not nvarchar.

The plain python equivalent of it can be seen below

When I do this

```<code>import pyodbc
cnxn = pyodbc.connect("DSN=AFdev")
crsr = cnxn.cursor()
sql = "SELECT ? AS thing"
params = ("Saugat")
result = crsr.execute(sql, params).fetchval()
</code>```

the param gets passed as nvarchar

Makes sense as the default encoding is utf-8.

When I set the encoding to Latin1

```<code>import pyodbc
cnxn = pyodbc.connect("DSN=AFdev")
cnxn.setencoding(encoding='latin1')
crsr = cnxn.cursor()
sql = "SELECT ? AS thing"
params = ("Saugat")
result = crsr.execute(sql, params).fetchval()
</code>```

I see that the param gets passed as varchar

Now, I want the same to happen for all airflow internal operations to the backend database (SQL Server, in this case)

I was hoping to use this airflow config i.e. sql_engine_encoding. However, even after adding it to airflow.config, the strings are sent to the DB from Airflow as nvarchar. what am I missing?

Title: Airflow SetEncoding Latin 1

Body:
The Airflow database backend is SQL Server. I am trying to see how can I make sure that airflow sends strings as varchars to the database and not nvarchar.

The plain python equivalent of it can be seen below

When I do this

import pyodbc
cnxn = pyodbc.connect("DSN=AFdev")
crsr = cnxn.cursor()
sql = "SELECT ? AS thing"
params = ("Saugat")
result = crsr.execute(sql, params).fetchval()

the param gets passed as nvarchar

Makes sense as the default encoding is utf-8.

When I set the encoding to Latin1

import pyodbc
cnxn = pyodbc.connect("DSN=AFdev")
cnxn.setencoding(encoding='latin1')
crsr = cnxn.cursor()
sql = "SELECT ? AS thing"
params = ("Saugat")
result = crsr.execute(sql, params).fetchval()

I see that the param gets passed as varchar

Now, I want the same to happen for all airflow internal operations to the backend database (SQL Server, in this case)

I was hoping to use this airflow config i.e. sql_engine_encoding. However, even after adding it to airflow.config, the strings are sent to the DB from Airflow as nvarchar. what am I missing?


问:
Warnings about unsupported RETURNING clause in Node SQLite3 client
I'm using a SQLite3 database for tests in Strapi with the node-sqlite3 client. When running the tests, I'm getting the following warnings:

```<code>  console.log
    node-sqlite3 does not currently support RETURNING clause
      at Logger._log (node_modules/knex/lib/logger.js:42:13)
</code>```

Initially, I thought that it is caused by an outdated SQLite version, since RETURNING support was added in SQLite 3.35. However, I've verified that the Node client version that I'm using (5.1.4) includes a newer release of SQLite:

sqlite3@^5.1.4:
  version "5.1.4"
  resolved "https://registry.yarnpkg.com/sqlite3/-/sqlite3-5.1.4.tgz#35f83d368963168b324ad2f0fffce09f3b8723a7"
  integrity sha512-i0UlWAzPlzX3B5XP2cYuhWQJsTtlMD6obOa1PgeEQ4DHEXUuyJkgv50I3isqZAP5oFc2T8OFvakmDh2W6I+YpA==
  dependencies:
    "@mapbox/node-pre-gyp" "^1.0.0"
    node-addon-api "^4.2.0"
    tar "^6.1.11"
  optionalDependencies:
    node-gyp "8.x"
```
<p>To verify the SQLite version, I've ran the following query:</p>
<pre class="lang-js prettyprint-override"><code>await strapi.db.connection.context.raw("select sqlite_version()")
</code>```

As expected, it yields {'sqlite_version()': '3.40.0'}, which should support the RETURNING clause.

For the record, my locally installed version of sqlite3 (3.38.2) also supposedly supports RETURNING, but I can also confirm it is not the source of the issue: the same warnings are also displayed when the tests are ran via Docker, and the local installation does not seem to be used either way based on the sqlite_version() result.

Are these warnings something that I should be worried about, or is it just Knex warning about a possibly unsupported feature?

Body:
I'm using a SQLite3 database for tests in Strapi with the node-sqlite3 client. When running the tests, I'm getting the following warnings:

  console.log
    node-sqlite3 does not currently support RETURNING clause
      at Logger._log (node_modules/knex/lib/logger.js:42:13)

Initially, I thought that it is caused by an outdated SQLite version, since RETURNING support was added in SQLite 3.35. However, I've verified that the Node client version that I'm using (5.1.4) includes a newer release of SQLite:

sqlite3@^5.1.4:
  version "5.1.4"
  resolved "https://registry.yarnpkg.com/sqlite3/-/sqlite3-5.1.4.tgz#35f83d368963168b324ad2f0fffce09f3b8723a7"
  integrity sha512-i0UlWAzPlzX3B5XP2cYuhWQJsTtlMD6obOa1PgeEQ4DHEXUuyJkgv50I3isqZAP5oFc2T8OFvakmDh2W6I+YpA==
  dependencies:
    "@mapbox/node-pre-gyp" "^1.0.0"
    node-addon-api "^4.2.0"
    tar "^6.1.11"
  optionalDependencies:
    node-gyp "8.x"

To verify the SQLite version, I've ran the following query:

await strapi.db.connection.context.raw("select sqlite_version()")

As expected, it yields {'sqlite_version()': '3.40.0'}, which should support the RETURNING clause.

For the record, my locally installed version of sqlite3 (3.38.2) also supposedly supports RETURNING, but I can also confirm it is not the source of the issue: the same warnings are also displayed when the tests are ran via Docker, and the local installation does not seem to be used either way based on the sqlite_version() result.

Are these warnings something that I should be worried about, or is it just Knex warning about a possibly unsupported feature?


问:
How to return value that was read from Firebase DB?
Here is my code.

```<code>fun readNameSurnameByEmail(email: String): String {

    // Сделать чтение для всех данных кроме пароля в разных функциях принимать будет email
    val database = FirebaseFirestore.getInstance()

    val myRef = database.collection("Users").document(email)

    myRef.get()
        .addOnSuccessListener { document ->
            if (document != null) {
                val fieldValue = document.get("name_surname") as String
                Log.d(TAG, "Name and surname successfully read")
            } else {
                Log.d(TAG, "Is empty")
            }
        }
        .addOnFailureListener { exception ->
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, "Error getting document: ", exception)
            }
        }

}
</code>```

I am creating val fieldValue. How can I return it if it is in SuccessListener?

And another question, is it a correct way of getting a field value by document name?

Here is updated code
Is it correct right now?

```<code>fun readNameSurnameByEmail(email: String): String {

    // Сделать чтение для всех данных кроме пароля в разных функциях принимать будет email
    val database = FirebaseFirestore.getInstance()

    val myRef = database.collection("Users").document(email)

    var fieldValue = ""

    myRef.get()
        .addOnSuccessListener { document ->
            if (document != null) {
                fieldValue = document.get("name_surname") as String
                Log.d(TAG, "Name and surname successfully read")
            } else {
                Log.d(TAG, "Is empty")
            }
        }
        .addOnFailureListener { exception ->
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, "Error getting document: ", exception)
            }
        }
    return fieldValue
}
</code>```

Body:
Here is my code.

fun readNameSurnameByEmail(email: String): String {

    // Сделать чтение для всех данных кроме пароля в разных функциях принимать будет email
    val database = FirebaseFirestore.getInstance()

    val myRef = database.collection("Users").document(email)

    myRef.get()
        .addOnSuccessListener { document ->
            if (document != null) {
                val fieldValue = document.get("name_surname") as String
                Log.d(TAG, "Name and surname successfully read")
            } else {
                Log.d(TAG, "Is empty")
            }
        }
        .addOnFailureListener { exception ->
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, "Error getting document: ", exception)
            }
        }

}

I am creating val fieldValue. How can I return it if it is in SuccessListener?

And another question, is it a correct way of getting a field value by document name?

Here is updated code
Is it correct right now?

fun readNameSurnameByEmail(email: String): String {

    // Сделать чтение для всех данных кроме пароля в разных функциях принимать будет email
    val database = FirebaseFirestore.getInstance()

    val myRef = database.collection("Users").document(email)

    var fieldValue = ""

    myRef.get()
        .addOnSuccessListener { document ->
            if (document != null) {
                fieldValue = document.get("name_surname") as String
                Log.d(TAG, "Name and surname successfully read")
            } else {
                Log.d(TAG, "Is empty")
            }
        }
        .addOnFailureListener { exception ->
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, "Error getting document: ", exception)
            }
        }
    return fieldValue
}


问:
Cannot connect to ipykernel Python 3 in Jupyter anymore
I am trying to learn more in Python. However, the fundamentals in terms of the software itself are hard to grasp for me. Let's say things got messy: I could not access all imports easily - so I decided to uninstall all Python related software to start over:

Uninstall Python, Jupyter and Anaconda

Re-install Anaconda and Python.

Installed it in C://Users/Mark/Anaconda

Added Python as PATH

But now I can not access my ipykernels anymore. It can not connect once I want to open a script I made. It asks which kernel I want to start every time. Was not the case before. It tries to connect but then says: "Disconnected".

I tried to move the ipynb files to the new root folder and open them from Path but no luck.

I tried to use cd in the Anaconda Prompt to set the root folder to C://Users/Mark/Anaconda

What is holding me from working scripts again?

I tried to move the ipynb files to the new root folder and open them from Path but no luck.

I tried to use cd in the Anaconda Prompt to set the root folder to C://Users/Mark/Anaconda


问:
Firebase function deploy failing after updating to node 16
I updated a firebase function to node 16 and I'm getting the following deploy error:

```<code>Build failed: ...ve_cv_t' is not a member of 'std'
npm ERR!              !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
npm ERR!                                       ^~~~~~~~~~~
npm ERR! /www-data-home/.cache/node-gyp/16.18.1/include/node/v8-internal.h:492:38: note: suggested alternative: 'remove_cv'
npm ERR!              !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
npm ERR!                                       ^~~~~~~~~~~
npm ERR!                                       remove_cv
npm ERR! /www-data-home/.cache/node-gyp/16.18.1/include/node/v8-internal.h:492:38: error: 'remove_cv_t' is not a member of 'std'
npm ERR! /www-data-home/.cache/node-gyp/16.18.1/include/node/v8-internal.h:492:38: note: suggested alternative: 'remove_cv'
npm ERR!              !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
npm ERR!                                       ^~~~~~~~~~~
npm ERR!                                       remove_cv
npm ERR! /www-data-home/.cache/node-gyp/16.18.1/include/node/v8-internal.h:492:50: error: template argument 2 is invalid
npm ERR!              !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
npm ERR!                                                   ^
npm ERR! /www-data-home/.cache/node-gyp/16.18.1/include/node/v8-internal.h:492:63: error: '::Perform' has not been declared
npm ERR!              !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
npm ERR!                                                                ^~~~~~~
npm ERR! /www-data-home/.cache/node-gyp/16.18.1/include/node/v8-internal.h:492:63: note: suggested alternative: 'perror'
npm ERR!              !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
npm ERR!                                                                ^~~~~~~
npm ERR!                                                                perror
npm ERR! At global scope:
npm ERR! cc1plus: warning: unrecognized command line option '-Wno-cast-function-type'
npm ERR! make: *** [Release/obj.target/sharp/src/common.o] Error 1
</code>```

I have already tried removing the cloud function and retrying deploy.

I updated firebase-admin, firebase-functions and @google-cloud/storage packages. I can run the function fine from the shell.

Body:
I updated a firebase function to node 16 and I'm getting the following deploy error:

Build failed: ...ve_cv_t' is not a member of 'std'
npm ERR!              !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
npm ERR!                                       ^~~~~~~~~~~
npm ERR! /www-data-home/.cache/node-gyp/16.18.1/include/node/v8-internal.h:492:38: note: suggested alternative: 'remove_cv'
npm ERR!              !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
npm ERR!                                       ^~~~~~~~~~~
npm ERR!                                       remove_cv
npm ERR! /www-data-home/.cache/node-gyp/16.18.1/include/node/v8-internal.h:492:38: error: 'remove_cv_t' is not a member of 'std'
npm ERR! /www-data-home/.cache/node-gyp/16.18.1/include/node/v8-internal.h:492:38: note: suggested alternative: 'remove_cv'
npm ERR!              !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
npm ERR!                                       ^~~~~~~~~~~
npm ERR!                                       remove_cv
npm ERR! /www-data-home/.cache/node-gyp/16.18.1/include/node/v8-internal.h:492:50: error: template argument 2 is invalid
npm ERR!              !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
npm ERR!                                                   ^
npm ERR! /www-data-home/.cache/node-gyp/16.18.1/include/node/v8-internal.h:492:63: error: '::Perform' has not been declared
npm ERR!              !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
npm ERR!                                                                ^~~~~~~
npm ERR! /www-data-home/.cache/node-gyp/16.18.1/include/node/v8-internal.h:492:63: note: suggested alternative: 'perror'
npm ERR!              !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
npm ERR!                                                                ^~~~~~~
npm ERR!                                                                perror
npm ERR! At global scope:
npm ERR! cc1plus: warning: unrecognized command line option '-Wno-cast-function-type'
npm ERR! make: *** [Release/obj.target/sharp/src/common.o] Error 1

I have already tried removing the cloud function and retrying deploy.

I updated firebase-admin, firebase-functions and @google-cloud/storage packages. I can run the function fine from the shell.


问:
Ansible mysql_query: How to handle if else logic or dependent queries
I'm using community.mysql.mysql_query module to run some queries against my DB using Ansible.

I'm trying to perform single transaction reads using multiple queries (SELECT statements) where every query has unique conditions (FROM and WHERE).

The issue that I'm running into is that some SELECT statements executions are dependent on others. For instance:

```<code>- name: "Read User Name"
    community.mysql.mysql_query:
        login_host: "{{login_host}}"
        login_db: "{{login_db}}"
        query:
            - >-
            SELECT username AS user_name
            FROM table1 WHERE user_id = 1
    register: user_name_reg

- name: "Set User Name"
    set_fact:
        user_name: "{{ user_name_reg['query_result'][0][0]['user_name'] }}"

- name: "Read User Last Name"
    community.mysql.mysql_query:
        login_host: "{{login_host}}"
        login_db: "{{login_db}}"
        query:
            - >-
            SELECT userLastName AS user_last_name
            FROM table2 WHERE user_name = "{{ user_name }}"
    register: user_last_name_reg
</code>```

or some logic is present, as follows:

```<code># Pseudocode

# user_name = query_result("
# SELECT username AS user_name
# FROM table1 WHERE user_id = 1")

# if not user_name:
#    user_name = query_result("
#    SELECT username AS user_name
#    FROM table2 WHERE user_special_id = 1")

- name: "Read User Name 1st"
    community.mysql.mysql_query:
        login_host: "{{login_host}}"
        login_db: "{{login_db}}"
        query:
            - >-
            SELECT username AS user_name
            FROM table1 WHERE user_id = 1
    register: user_name_reg

- name: "Set User Name"
    set_fact:
        user_name: "{{ user_name_reg['query_result'][0][0]['user_name'] }}"

- name: "Read User Name 2nd"
    community.mysql.mysql_query:
        login_host: "{{login_host}}"
        login_db: "{{login_db}}"
        query:
            - >-
            SELECT username AS user_name
            FROM table2 WHERE user_special_id = 1
    register: user_name2_reg
    when: "user_name = NULL"
</code>```

I think my examples are not transaction safe, as there is no locking mechanism between tasks.

My questions are as follow:

Is there any way to handle the above use cases using mysql_query module (as a single transaction)?

If not, would it make more sense to implement the two uses cases using SQL scripts or action modules for ansible?

Body:
I'm using community.mysql.mysql_query module to run some queries against my DB using Ansible.

I'm trying to perform single transaction reads using multiple queries (SELECT statements) where every query has unique conditions (FROM and WHERE).

The issue that I'm running into is that some SELECT statements executions are dependent on others. For instance:

- name: "Read User Name"
    community.mysql.mysql_query:
        login_host: "{{login_host}}"
        login_db: "{{login_db}}"
        query:
            - >-
            SELECT username AS user_name
            FROM table1 WHERE user_id = 1
    register: user_name_reg

- name: "Set User Name"
    set_fact:
        user_name: "{{ user_name_reg['query_result'][0][0]['user_name'] }}"

- name: "Read User Last Name"
    community.mysql.mysql_query:
        login_host: "{{login_host}}"
        login_db: "{{login_db}}"
        query:
            - >-
            SELECT userLastName AS user_last_name
            FROM table2 WHERE user_name = "{{ user_name }}"
    register: user_last_name_reg

or some logic is present, as follows:

# Pseudocode

# user_name = query_result("
# SELECT username AS user_name
# FROM table1 WHERE user_id = 1")

# if not user_name:
#    user_name = query_result("
#    SELECT username AS user_name
#    FROM table2 WHERE user_special_id = 1")

- name: "Read User Name 1st"
    community.mysql.mysql_query:
        login_host: "{{login_host}}"
        login_db: "{{login_db}}"
        query:
            - >-
            SELECT username AS user_name
            FROM table1 WHERE user_id = 1
    register: user_name_reg

- name: "Set User Name"
    set_fact:
        user_name: "{{ user_name_reg['query_result'][0][0]['user_name'] }}"

- name: "Read User Name 2nd"
    community.mysql.mysql_query:
        login_host: "{{login_host}}"
        login_db: "{{login_db}}"
        query:
            - >-
            SELECT username AS user_name
            FROM table2 WHERE user_special_id = 1
    register: user_name2_reg
    when: "user_name = NULL"

I think my examples are not transaction safe, as there is no locking mechanism between tasks.

My questions are as follow:

Is there any way to handle the above use cases using mysql_query module (as a single transaction)?

If not, would it make more sense to implement the two uses cases using SQL scripts or action modules for ansible?


问:
Is it possible to use OpenPose output of x and y coordinates to detect rotating movement?
I did some research on OpenPose and the output is x and y coordinates with confidence point. x and y coordinates are good for detecting up, down, left, and right movements. I was wondering is it possible to detect turning movements. Turning usually happens on the z axis. Is there a way to tell if body part has rotated 180 degrees with x and y coordinate.

I had few ideas like calculating the slope of the hand line. The slope tells us if the hand is tilted or not. If the slope is high or very low then the hand has rotated. Same concept for all other body parts. But I don't think that will work in all cases. Please check 2nd figure here https://cmu-perceptual-computing-lab.github.io/openpose/web/html/doc/md_doc_02_output.html to understand output of OpenPose.


问:
How to programmatically save cache in GitLabCI while running the script inside a job, instead of saving at end of the job?
Hi I am trying to save a data to GitLabCI cache programmatically on verifying that the data have met some criteria. Is this possible? Or I have to wait till end of the GitLab CI job? Issue is, this job might fail and if we are saving blindly on end of job, there is no guarantee that I am saving the required data. Appreciate if you can help.</p>


问:
How can I update cell background color based on  text color in Excel export using jquery datables?
I have a table that has most of the data text color set to green or red. I want the Excel export to reflect the same color for the background for each cell.

HTML

```<code><!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>

    <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
    <script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.html5.js"></script>
    <link href="https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css" rel="stylesheet" type="text/css" />
    <script src="https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.colVis.min.js"></script>
    <script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>

    <meta charset=utf-8 />
    <title>DataTables - JS Bin</title>
  </head>
  <body>
    <div class="container">
      <table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Order</th>
            <th>Description</th>
            <th>Deadline</th>
            <th>Status</th>
            <th>Amount</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td style="color:green">item A</td>
            <td style="color:green">2016/01/15</td>
            <td style="color:green">Done</td>
            <td style="color:green">100</td>
        </tr>
        <tr>
            <td>2</td>
            <td style="color:green">item B</td>
            <td style="color:red">0</td>
            <td style="color:red">0</td>
            <td style="color:red">0</td>
        </tr>
        <tr>
            <td>3</td>
            <td style="color:green">item C</td>
            <td style="color:green">2016/01/23</td>
            <td style="color:red">0</td>
            <td style="color:green">100</td>
        </tr>
    <tr>
            <td>4</td>
            <td style="color:green">item D</td>
            <td style="color:green">2016/10/31</td>
            <td style="color:green">Confirmed</td>
            <td  style="color:green">750</td>
        </tr>
    <tr>
            <td>5</td>
            <td style="color:green">item E</td>
            <td style="color:green">2016/02/18</td>
            <td style="color:green">Planned</td>
            <td style="color:green">200</td>
        </tr>
    </tbody>
</table>
    </div>
  </body>
</html>
</code>```
```<code>$(document).ready(function() {
  var table = $('#example').DataTable({
      dom: 'Bfrtip',
    buttons: [{
      extend: 'excelHtml5',
      customize: function ( xlsx ) {
        var sheet = xlsx.xl.worksheets['sheet1.xml'];

        var count = 0;
        var skippedHeader = false;
//         table.cells().every( function () {
//           var color = $(this).css("color");
//         } );
        $('row', sheet).each( function () {
          var col_count = 0
          console.log('row count: ' + count)
          var outerThis = $(this);
          if (skippedHeader) {
          $('col', sheet).each( function () {
            var color = $('tbody tr:eq('+parseInt(count)+') td:eq('+parseInt(col_count)+')').css('color');
            console.log(count + ', ' + col_count)
            console.log(color)
            if (color === "rgb(255, 0, 0)") {
              $(this).attr( 's', '35' );
            }
            else if (color === "rgb(0, 128, 0)") {
              $(this).attr( 's', '40' );
            }
            col_count++
          })

            count++;
          }
          else {
            skippedHeader = true;
          }
        });
      }
    }]
  });
});
</code>```

Here is a LiveTables link as well: http://live.datatables.net/sememigi/3/edit

I was originally thinking that table.cells().every() would be a better approach but was having trouble getting the color of each td. In my current approach above, I'm getting the text color of each td but am having trouble getting the cell to show up with the background color. I'm still pretty new to jquery/datatables, so any guidance would be appreciated. Thanks!

Title: How can I update cell background color based on <td> text color in Excel export using jquery datables?

Body:
I have a table that has most of the data text color set to green or red. I want the Excel export to reflect the same color for the background for each cell.

HTML

<!DOCTYPE html>

    <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />

    <link href="https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css" rel="stylesheet" type="text/css" />

    <meta charset=utf-8 />
    <title>DataTables - JS Bin</title>

            Order
            Description
            Deadline
            Status
            Amount

            1
            item A
            2016/01/15
            Done
            100

            2
            item B
            0
            0
            0

            3
            item C
            2016/01/23
            0
            100

            4
            item D
            2016/10/31
            Confirmed
            750

            5
            item E
            2016/02/18
            Planned
            200

$(document).ready(function() {
  var table = $('#example').DataTable({
      dom: 'Bfrtip',
    buttons: [{
      extend: 'excelHtml5',
      customize: function ( xlsx ) {
        var sheet = xlsx.xl.worksheets['sheet1.xml'];

        var count = 0;
        var skippedHeader = false;
//         table.cells().every( function () {
//           var color = $(this).css("color");
//         } );
        $('row', sheet).each( function () {
          var col_count = 0
          console.log('row count: ' + count)
          var outerThis = $(this);
          if (skippedHeader) {
          $('col', sheet).each( function () {
            var color = $('tbody tr:eq('+parseInt(count)+') td:eq('+parseInt(col_count)+')').css('color');
            console.log(count + ', ' + col_count)
            console.log(color)
            if (color === "rgb(255, 0, 0)") {
              $(this).attr( 's', '35' );
            }
            else if (color === "rgb(0, 128, 0)") {
              $(this).attr( 's', '40' );
            }
            col_count++
          })

            count++;
          }
          else {
            skippedHeader = true;
          }
        });
      }
    }]
  });
});

Here is a LiveTables link as well: http://live.datatables.net/sememigi/3/edit

I was originally thinking that table.cells().every() would be a better approach but was having trouble getting the color of each td. In my current approach above, I'm getting the text color of each td but am having trouble getting the cell to show up with the background color. I'm still pretty new to jquery/datatables, so any guidance would be appreciated. Thanks!


问:
Can we get certain record as a top most record in elastic search paginated response java
I have a requirement where i need to to fetch all the users using elastic search for the landing page using pagination where in topmost/first record should be from current logged in user.

I am able to get the paginated response for all the users using match all query but i am not able to get the current user record as top most record in paginated response.

is it possible to achieve this using elastic search query, my elastic search version is 7.6.0

here is my code

```<code>    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    BoolQueryBuilder builder = QueryBuilders.boolQuery();
    long totalHits;
    builder.must(QueryBuilders.matchAllQuery());
    builder.must(QueryBuilders.existsQuery(book.squadMemberMongoId.keyword)); // squad member must be present

    sourceBuilder.from(from);
    sourceBuilder.size(size);
    sourceBuilder.trackTotalHits(true);
    sourceBuilder.trackTotalHitsUpTo();
    sourceBuilder.sort((SortBuilders.fieldSort("book.eaLastName.keyword").order(SortOrder.ASC)));
    sourceBuilder.query(builder);
    searchRequest.source(sourceBuilder);
// client is instance of RestHighLevelClient
   response=client.search(searchRequest, RequestOptions.DEFAULT);

   SearchHit[] hits = searchResponse.getHits().getHits();
</code>```

is there any way where i can make above query to return current logged in user / specific record in top of the response list (current logged user can be identified by squadMemberMongoId field in data)

Sample Data:

```<code>{
  "submissionId": "232323237",
  "revision": 2,
  "author": {
  "country": "xyz",
  "email": "john.doe@informa.com",
  "name": "john doe"
},
"book": {
 "eaLastName" : "xyzea"
 "squad": "John",
 "squadMemberMongoId": 12345678
}
....
</code>```

}

submissionId is the index key here

expected response:

If i have multiple different submissions with different submission ids and different squadMemberMongoId under book , when i make a query i want record with specific squadMemberMongoId to be on top of the response  then followed by other records with different id's, entire response set has to be paginated

Body:
I have a requirement where i need to to fetch all the users using elastic search for the landing page using pagination where in topmost/first record should be from current logged in user.

I am able to get the paginated response for all the users using match all query but i am not able to get the current user record as top most record in paginated response.

is it possible to achieve this using elastic search query, my elastic search version is 7.6.0

here is my code

    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    BoolQueryBuilder builder = QueryBuilders.boolQuery();
    long totalHits;
    builder.must(QueryBuilders.matchAllQuery());
    builder.must(QueryBuilders.existsQuery(book.squadMemberMongoId.keyword)); // squad member must be present

    sourceBuilder.from(from);
    sourceBuilder.size(size);
    sourceBuilder.trackTotalHits(true);
    sourceBuilder.trackTotalHitsUpTo();
    sourceBuilder.sort((SortBuilders.fieldSort("book.eaLastName.keyword").order(SortOrder.ASC)));
    sourceBuilder.query(builder);
    searchRequest.source(sourceBuilder);
// client is instance of RestHighLevelClient
   response=client.search(searchRequest, RequestOptions.DEFAULT);

   SearchHit[] hits = searchResponse.getHits().getHits();

is there any way where i can make above query to return current logged in user / specific record in top of the response list (current logged user can be identified by squadMemberMongoId field in data)

Sample Data:

{
  "submissionId": "232323237",
  "revision": 2,
  "author": {
  "country": "xyz",
  "email": "john.doe@informa.com",
  "name": "john doe"
},
"book": {
 "eaLastName" : "xyzea"
 "squad": "John",
 "squadMemberMongoId": 12345678
}
....

}

submissionId is the index key here

expected response:

If i have multiple different submissions with different submission ids and different squadMemberMongoId under book , when i make a query i want record with specific squadMemberMongoId to be on top of the response  then followed by other records with different id's, entire response set has to be paginated


问:
Is there some idling rule for Room?
How to write an idle rule for Room? How to understand that the database is busy?
It would be great to do it without adding code to the production code.</p>

Title: Is there some idling rule for Room?


问:
How can I convert SKCanvas created from SKBitmap into SKPicture for debugging?
I'm using SkiaSharp to generate images, and it's very hard to debug the image generation code without visual trace. I discovered there's skia debugger and it can help a lot.

I have SKCanvas created from SKBitmap, and I would like to get SKPicture from it so I can serialize it in order to load it into skia debugger.

I wasn't able to find the API to do it.

How can I do it? What approach should I take to get SKPicture from SKBitmap to see the trace of what skia does?


问:
How to achieve grouping in kendo grid with dynamic columns - asp.net core kendo
I am using the Kendo asp.net core to render the kendo grid. I cannot find options to group,aggregate when dynamic columns are used to render the grid. Is there a solution that can be used by using asp.net core kendo?</p>


问:
Load R data objects' attributes without loading object from file?
I am aware that this question was already posted before, but since it was asked more than eight years ago I was wondering if there is solution now. The suggested answers in that post do not provide a satisfactory solution to the problem: Load attributes of an object without  loading the file into memory.

Basically, it would be great to load object's attributes without having to load the file. In case user-written attributes can't be loaded, it would be great to at least be able to load basic attributes such as length or names. The fst::metadata_fst() does something similar, but the problem is that it only saves data.frames, so it does not work with other type of objects like lists.

Thanks.


问:
AWS GO SDK returns "AuthFailure: AWS was not able to validate the provided access credentials"
I am developing a simple automation tool using a Go Fiber HTTP server to start and stop AWS instances using the Go SDK v1.44.156.

The service listens to an endpoint at /csm/aws/:region/:instance_id/powerOn.

My code works well when I send requests from Postman. When I send requests using the Go HTTP client, AWS returns the following error:

AuthFailure: AWS was not able to validate the provided access credentials

The Postman request that works fine:

```<code>2022/12/23 16:26:12 Request came :#0000000100000003 - 127.0.0.1:7000 <-> 127.0.0.1:34976 - POST http://127.0.0.1:7000/csm/aws/us-east-1/i-0f9c5fe6b5c7b0a87/powerOn
Params: map[instance_id:i-0f9c5fe6b5c7b0a87 region:us-east-1]
Request: POST /csm/aws/us-east-1/i-0f9c5fe6b5c7b0a87/powerOn HTTP/1.1
User-Agent: PostmanRuntime/7.30.0
Host: 127.0.0.1:7000
Content-Type: application/json
Content-Length: 136
Accept: */*
Postman-Token: e27b899f-5125-497a-b154-61cd3214cd74
Accept-Encoding: gzip, deflate, br
Connection: keep-alive

{"aws_access_key_id":"my-id","aws_secret_access_key":"my-key","account":"","region":""}
</code>```

The Go request which returns the error:

```<code>2022/12/23 16:22:02 Request came :#0000000200000002 - 127.0.0.1:7000 <-> 127.0.0.1:34278 - POST http://127.0.0.1:7000/csm/aws/us-east-1/i-0f9c5fe6b5c7b0a87/powerOn
Params: map[instance_id:i-0f9c5fe6b5c7b0a87 region:us-east-1]
Request: POST /csm/aws/us-east-1/i-0f9c5fe6b5c7b0a87/powerOn HTTP/1.1
User-Agent: Go-http-client/1.1
Host: 127.0.0.1:7000
Content-Type: application/json
Content-Length: 136
Accept-Encoding: gzip

{"aws_access_key_id":"my-id","aws_secret_access_key":"my-key","account":"","region":""}
</code>```

I searched on the web and I found information about this error message. It seems like it can be due to the time of the PC so I set my computer's time to automatic, but I see the same error.

My code was working a few days ago.

Body:
I am developing a simple automation tool using a Go Fiber HTTP server to start and stop AWS instances using the Go SDK v1.44.156.

The service listens to an endpoint at /csm/aws/:region/:instance_id/powerOn.

My code works well when I send requests from Postman. When I send requests using the Go HTTP client, AWS returns the following error:

AuthFailure: AWS was not able to validate the provided access credentials

The Postman request that works fine:

2022/12/23 16:26:12 Request came :#0000000100000003 - 127.0.0.1:7000 <-> 127.0.0.1:34976 - POST http://127.0.0.1:7000/csm/aws/us-east-1/i-0f9c5fe6b5c7b0a87/powerOn
Params: map[instance_id:i-0f9c5fe6b5c7b0a87 region:us-east-1]
Request: POST /csm/aws/us-east-1/i-0f9c5fe6b5c7b0a87/powerOn HTTP/1.1
User-Agent: PostmanRuntime/7.30.0
Host: 127.0.0.1:7000
Content-Type: application/json
Content-Length: 136
Accept: */*
Postman-Token: e27b899f-5125-497a-b154-61cd3214cd74
Accept-Encoding: gzip, deflate, br
Connection: keep-alive

{"aws_access_key_id":"my-id","aws_secret_access_key":"my-key","account":"","region":""}

The Go request which returns the error:

2022/12/23 16:22:02 Request came :#0000000200000002 - 127.0.0.1:7000 <-> 127.0.0.1:34278 - POST http://127.0.0.1:7000/csm/aws/us-east-1/i-0f9c5fe6b5c7b0a87/powerOn
Params: map[instance_id:i-0f9c5fe6b5c7b0a87 region:us-east-1]
Request: POST /csm/aws/us-east-1/i-0f9c5fe6b5c7b0a87/powerOn HTTP/1.1
User-Agent: Go-http-client/1.1
Host: 127.0.0.1:7000
Content-Type: application/json
Content-Length: 136
Accept-Encoding: gzip

{"aws_access_key_id":"my-id","aws_secret_access_key":"my-key","account":"","region":""}

I searched on the web and I found information about this error message. It seems like it can be due to the time of the PC so I set my computer's time to automatic, but I see the same error.

My code was working a few days ago.


问:
Not being able to edit my Many-To-Many entity in AWS AppSync
When creating a Many-to-Many relationship using GraphQL for the schema, I have been unable to alter the entity created. The @manyToMany annotation enables the syntax to produce a table named "OrderUsers". But the problem lies in my inability to alter the "OrderUsers" entity. After different attempts at changing the table, I have been unable to figure out how to change it. The only attributes that are taken into the "OrderUsers" table are the id from both the User as well as Order table, which also creates only two GSIs. Also, this is using the v2 docs.

```<code>type User @model {
  id: ID!
  fName: String!
  lName: String!
  phoneNumber: String!
  email: String!
  DOB: String!
  orders: [Order] @manyToMany(relationName: "OrderUsers")
  ordersByDate: [Order] @hasMany(indexName: "byOrderByDate", fields: ["id"])
  ordersByStatusDate: [Order] @hasMany(indexName: "byOrderStatusByDate", fields: ["id"])
}

type Order @model {
  id: ID!
  userId: ID! @index(name: "byOrderStatusByDate", sortKeyFields: ["status", "date"]) @index(name: "byOrderByDate", sortKeyFields: ["date"])
  status: String!
  amount: Int
  date: String!
  users: [User] @manyToMany(relationName: "OrderUsers")  # Test to see if I can tinker w/ the 'OrderUsers' tbl
  productId: ID! @index(name: "byProductOrder", sortKeyFields: ["id"])
  clubId: ID! @index(name: "byClub", sortKeyFields: ["id"])
}
</code>```

After reviewing the AWS Amplify as well as AppSync docs, attempting to add GSIs to the 'OrderUsers' table, switch the partition key used from the 'User' entity to a composite partition key for the 'OrderUsers' table, and adding other attributes to the 'OrderUsers' table, everything gets wiped as I try to push/pull it. Since the syntax isn't stored in the schema.graphql file, I have been stuck. My expectation was that it would save into the schema and update the resolvers used for the mutation(s) & queries, but that has not been the case.

Any and all help would be appreciated,

Thank you & Happy holidays

Body:
When creating a Many-to-Many relationship using GraphQL for the schema, I have been unable to alter the entity created. The @manyToMany annotation enables the syntax to produce a table named "OrderUsers". But the problem lies in my inability to alter the "OrderUsers" entity. After different attempts at changing the table, I have been unable to figure out how to change it. The only attributes that are taken into the "OrderUsers" table are the id from both the User as well as Order table, which also creates only two GSIs. Also, this is using the v2 docs.

type User @model {
  id: ID!
  fName: String!
  lName: String!
  phoneNumber: String!
  email: String!
  DOB: String!
  orders: [Order] @manyToMany(relationName: "OrderUsers")
  ordersByDate: [Order] @hasMany(indexName: "byOrderByDate", fields: ["id"])
  ordersByStatusDate: [Order] @hasMany(indexName: "byOrderStatusByDate", fields: ["id"])
}

type Order @model {
  id: ID!
  userId: ID! @index(name: "byOrderStatusByDate", sortKeyFields: ["status", "date"]) @index(name: "byOrderByDate", sortKeyFields: ["date"])
  status: String!
  amount: Int
  date: String!
  users: [User] @manyToMany(relationName: "OrderUsers")  # Test to see if I can tinker w/ the 'OrderUsers' tbl
  productId: ID! @index(name: "byProductOrder", sortKeyFields: ["id"])
  clubId: ID! @index(name: "byClub", sortKeyFields: ["id"])
}

After reviewing the AWS Amplify as well as AppSync docs, attempting to add GSIs to the 'OrderUsers' table, switch the partition key used from the 'User' entity to a composite partition key for the 'OrderUsers' table, and adding other attributes to the 'OrderUsers' table, everything gets wiped as I try to push/pull it. Since the syntax isn't stored in the schema.graphql file, I have been stuck. My expectation was that it would save into the schema and update the resolvers used for the mutation(s) & queries, but that has not been the case.

Any and all help would be appreciated,

Thank you & Happy holidays


问:
Accessing Elastic 5.5 in vagrant guest from host through a private network
A bit of context. I need to install an ancient version of Elastic namely the 5.5.

I did so by provisioning a VirtualBox'ed generic/centos7 with vagrant. Everything works pretty well.

I can ssh into the guest and see my single node Elastic cluster running and being happy with a curl -X GET "localhost:9200/_cat/health?v&pretty".

Now, when I get back to the host (Win10 with WSL2 enabled) and try curl -X GET "192.168.99.100:9200/_cat/health?v&pretty" I'm getting this message:

```<code>curl: (28) Failed to connect to 192.168.99.100 port 9200 after 21004 ms: Timed out
</code>```

vagrant version: 2.3.4
virtualbox version : 7.0.4

An excerpt from my Vagrantfile:

```<code>Vagrant.configure("2") do |config|
  config.vm.box = "generic/centos7"

  if Vagrant.has_plugin?("vagrant-vbguest")
    config.vbguest.installer_options = { running_kernel_modules: ["vboxguest"] }
    config.vbguest.auto_update = true
  end

  config.vm.network "private_network", ip: "192.168.99.100"

  config.vm.synced_folder "./provision", "/vagrant/provision"
  config.vm.synced_folder "../../indices/legacy55", "/vagrant/indices"
end
</code>```

When I open the network connections list on my Windows host, I have 3 Virtualbox host-only adapters which seems weird. I can't update/remove/re-create them for some reasons that are not technical (not being full adm of this computer).

```<code>VirtualBox Host-Only Network :
   IPv4. . . . . . . . . . . . . .: 192.168.56.1

VirtualBox Host-Only Network #2 :
   IPv4. . . . . . . . . . . . . .: 192.168.54.1

VirtualBox Host-Only Network #3 :
   IPv4. . . . . . . . . . . . . .: 192.168.99.1
</code>```

I tried to set up vagrant's private network using IP from the range of all three virtual adapters. Not to avail. I tried to set up forwarded ports (guest 9200, 9300 to host 9201, 9301), not to avail either.

I tried to change elastic network setting binding elastic listener to 0.0.0.0 didn't work either.

I ran out of ideas.

Anyway, I can work with that cluster from within the guest using sync'ed files but I'd like to get access to it from the host but I still can't and don't understand what's wrong with my overall set up.

Any guidance would be appreciated.

---------- EDIT 28/12/2022 -------------
Actually, what I noticed was a glitch due to the asynchronous nature of Elasticsearch initialization procedure.
I issued the curl commands before ES bound its main process to the network address and started to listen on port 9200.
I started to realize this when I watched ES logging in real time.

I came up with a not-so-elegant solution for automatic provisioning with Vagrant:

```<code># >1 minute elapses between startup and binding to the network ifaces
echo Waiting for Elasticsearch service to start listening on port 9200
sleep 10
result=1
max_retries=15
retries=0
while [ $result -ne 0 ] && [ $retries -lt $max_retries ];
do
    if [ -f /run/elasticsearch/elasticsearch.pid ];
    then
        pid=$(cat /run/elasticsearch/elasticsearch.pid)
        sudo netstat -nlpt | grep 9200 | grep "$pid" 1>/dev/null 2>&1
        result=$?
  fi
  sleep 5
  ((retries++))
done

if [ $result -ne 0 ];
then
    echo Elasticsearch seems to have failed to start. Exiting.
    exit 1
fi

echo "Elasticsearch up & running"
curl -S -s -XGET "http://localhost:9200/_cluster/health?wait_for_status=yellow&timeout=50s&pretty"
</code>```

Body:
A bit of context. I need to install an ancient version of Elastic namely the 5.5.

I did so by provisioning a VirtualBox'ed generic/centos7 with vagrant. Everything works pretty well.

I can ssh into the guest and see my single node Elastic cluster running and being happy with a curl -X GET "localhost:9200/_cat/health?v&pretty".

Now, when I get back to the host (Win10 with WSL2 enabled) and try curl -X GET "192.168.99.100:9200/_cat/health?v&pretty" I'm getting this message:

curl: (28) Failed to connect to 192.168.99.100 port 9200 after 21004 ms: Timed out

vagrant version: 2.3.4
virtualbox version : 7.0.4

An excerpt from my Vagrantfile:

Vagrant.configure("2") do |config|
  config.vm.box = "generic/centos7"

  if Vagrant.has_plugin?("vagrant-vbguest")
    config.vbguest.installer_options = { running_kernel_modules: ["vboxguest"] }
    config.vbguest.auto_update = true
  end

  config.vm.network "private_network", ip: "192.168.99.100"

  config.vm.synced_folder "./provision", "/vagrant/provision"
  config.vm.synced_folder "../../indices/legacy55", "/vagrant/indices"
end

When I open the network connections list on my Windows host, I have 3 Virtualbox host-only adapters which seems weird. I can't update/remove/re-create them for some reasons that are not technical (not being full adm of this computer).

VirtualBox Host-Only Network :
   IPv4. . . . . . . . . . . . . .: 192.168.56.1

VirtualBox Host-Only Network #2 :
   IPv4. . . . . . . . . . . . . .: 192.168.54.1

VirtualBox Host-Only Network #3 :
   IPv4. . . . . . . . . . . . . .: 192.168.99.1

I tried to set up vagrant's private network using IP from the range of all three virtual adapters. Not to avail. I tried to set up forwarded ports (guest 9200, 9300 to host 9201, 9301), not to avail either.

I tried to change elastic network setting binding elastic listener to 0.0.0.0 didn't work either.

I ran out of ideas.

Anyway, I can work with that cluster from within the guest using sync'ed files but I'd like to get access to it from the host but I still can't and don't understand what's wrong with my overall set up.

Any guidance would be appreciated.

---------- EDIT 28/12/2022 -------------
Actually, what I noticed was a glitch due to the asynchronous nature of Elasticsearch initialization procedure.
I issued the curl commands before ES bound its main process to the network address and started to listen on port 9200.
I started to realize this when I watched ES logging in real time.

I came up with a not-so-elegant solution for automatic provisioning with Vagrant:

# >1 minute elapses between startup and binding to the network ifaces
echo Waiting for Elasticsearch service to start listening on port 9200
sleep 10
result=1
max_retries=15
retries=0
while [ $result -ne 0 ] && [ $retries -lt $max_retries ];
do
    if [ -f /run/elasticsearch/elasticsearch.pid ];
    then
        pid=$(cat /run/elasticsearch/elasticsearch.pid)
        sudo netstat -nlpt | grep 9200 | grep "$pid" 1>/dev/null 2>&1
        result=$?
  fi
  sleep 5
  ((retries++))
done

if [ $result -ne 0 ];
then
    echo Elasticsearch seems to have failed to start. Exiting.
    exit 1
fi

echo "Elasticsearch up & running"
curl -S -s -XGET "http://localhost:9200/_cluster/health?wait_for_status=yellow&timeout=50s&pretty"


问:
Error in my ShinyApp on R: Non numeric matrix extent
Every time I try to run the shiny app on R I get this error. How to fix it?

I found out that the error is regarding samples <- matrix(sample(1:n),ncol=K)
But I don't understand why.

This is the code of my server:

server <- function(input, output) {
  output$distPlot <- renderPlot({
    r=input$r
    n=input$n
    K=input$k
    sim=input$sim
    p=input$p
    noi=input$noi

    lsEigen0 <- replicate(1, matrix(rep(0, sim*p),
                          nrow=sim, ncol = p), simplify=FALSE)

    lsmethod0 <- replicate(1, matrix(rep(0, sim*p),
                          nrow=sim, ncol = p), simplify=FALSE)

    choose0 <- replicate(1, rep(0, p), simplify=FALSE)

    for (i in 1:sim) {
      samples <- matrix(sample(1:n), ncol=K)

      #df <- rmvnorm(n = n, mean = rep(0, p), sigma = diag(p))
      #data0 <- dataset(df,r,noi)

      #for (da in 1:1) {
       # lsEigen0[[da]][i,] <- svd(data0[[da]])$d

        #lsmethod0[[da]][i,] <- method(data0[[da]], samples)

        #min_err0 <- which.min(lsmethod0[[da]][i,])
        #choose0[[da]][min_err0] <- choose0[[da]][min_err0] +1

      #}
    }

    #par(mfrow=c(1,2))

    #plot1 = plot(1:p, colMeans(lsEigen0[[1]]),
      xlab="kth Eigenvalue", ylab="Value",
      main="Scree plot data set ", type = "b", pch = 19,
       lty = 1, col = 1)

    #plot2 = plot(1:p, colMeans(lsmethod0[[1]]), xlab="Rank r",
                  ylab="Value", main= "Error data set ",
                  type = "b", pch = 19, lty = 1, col = 1)

    })
}
# Run the application
shinyApp(ui = ui, server = server)
```

The code runs but in the shiny app I get the error

I have tried to fix it by myself but I don't get it.

Body:
Every time I try to run the shiny app on R I get this error. How to fix it?

I found out that the error is regarding samples <- matrix(sample(1:n),ncol=K)
But I don't understand why.

This is the code of my server:

server <- function(input, output) {
  output$distPlot <- renderPlot({
    r=input$r
    n=input$n
    K=input$k
    sim=input$sim
    p=input$p
    noi=input$noi

    lsEigen0 <- replicate(1, matrix(rep(0, sim*p),
                          nrow=sim, ncol = p), simplify=FALSE)

    lsmethod0 <- replicate(1, matrix(rep(0, sim*p),
                          nrow=sim, ncol = p), simplify=FALSE)

    choose0 <- replicate(1, rep(0, p), simplify=FALSE)

    for (i in 1:sim) {
      samples <- matrix(sample(1:n), ncol=K)

      #df <- rmvnorm(n = n, mean = rep(0, p), sigma = diag(p))
      #data0 <- dataset(df,r,noi)

      #for (da in 1:1) {
       # lsEigen0[[da]][i,] <- svd(data0[[da]])$d

        #lsmethod0[[da]][i,] <- method(data0[[da]], samples)

        #min_err0 <- which.min(lsmethod0[[da]][i,])
        #choose0[[da]][min_err0] <- choose0[[da]][min_err0] +1

      #}
    }

    #par(mfrow=c(1,2))

    #plot1 = plot(1:p, colMeans(lsEigen0[[1]]),
      xlab="kth Eigenvalue", ylab="Value",
      main="Scree plot data set ", type = "b", pch = 19,
       lty = 1, col = 1)

    #plot2 = plot(1:p, colMeans(lsmethod0[[1]]), xlab="Rank r",
                  ylab="Value", main= "Error data set ",
                  type = "b", pch = 19, lty = 1, col = 1)

    })
}
# Run the application
shinyApp(ui = ui, server = server)

The code runs but in the shiny app I get the error

I have tried to fix it by myself but I don't get it.