问:
Material input type datetime-local shows its own placeholder and toggle button
I'm trying to render the angular material date picker. Which is not the problem (DEMO)

```<code><mat-form-field class="example-full-width">
    <input
        matInput
       [matDatepickerFilter]="myFilter"
       [matDatepicker]="picker"
       placeholder="Choose a date"
    />
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
</mat-form-field>
</code>```

But in my case I need a date-time picker. From what I found on the web, you simple add

```<code> type="datetime-local"
</code>```

to the input field. And I can confirm that this works, but it does weird things with the input field.

DEMO

Although angular material seems to support this type the picker you get however is native.

It has its own toggle button and it shows default text dd/mm/yyyy --:--. Is there a way to hide this text and toggle button?

答:
I didn't find time-picker feature in Angular Material.

Try this - https://www.npmjs.com/package/@angular-material-components/datetime-picker

Body:
I'm trying to render the angular material date picker. Which is not the problem (DEMO)

<mat-form-field class="example-full-width">
    <input
        matInput
       [matDatepickerFilter]="myFilter"
       [matDatepicker]="picker"
       placeholder="Choose a date"
    />
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

But in my case I need a date-time picker. From what I found on the web, you simple add

 type="datetime-local"

to the input field. And I can confirm that this works, but it does weird things with the input field.

DEMO

Although angular material seems to support this type the picker you get however is native.

It has its own toggle button and it shows default text dd/mm/yyyy --:--. Is there a way to hide this text and toggle button?


来源: stackexchange

问:
"Transitive type conversion" in typescript
in a typescript project which I'm currently working on, I have a class A, a class B extends A, a class C extends B and a class D extends C. I also have a method getFoo(): A.

The following type conversion doesn't work:

const foo = this.getFoo() as D;

The error I get is that the conversion may be a mistake, because neither type sufficiently overlaps the other (although D is a subclass of A).

What, funnily enough, works, is:

 const foo = this.getFoo() as C as D

Why? Is the inheritance chain somehow too long for TS? Is there any way to write this without the double cast?

Thanks in advance!

答:
I was able to resolve the question eventually.

My initial description was too simplified. In reality, it was like this:

Classes A and B were defined inside a type declaration library lorem, each as a default export from its own module. Class B extends A.

Classes C, better called my/B, and D were declared inside my own my.d.ts file. Class C actually had the same name as class B, so I had to rename it during import.

All of this was used inside my own class E, which had a method getFoo(): A.

What I initially wrote was (my.d.ts)

```<code>declare module "my/B" {
  import {B as LoremB} from "lorem/B";

  export default class B extends LoremB {
  }
}

declare module "my/D" {
  import B from "my/B";

  export default class D extends B {
    public doSomething(): void
  }
}
</code>```

and (E.ts)

```<code>(this.getFoo() as D).doSomething();
</code>```

This gave me the error message that the conversion may be a mistake because neither A or D sufficiently overlap each other and that doSomething is missing from A.

It turns out the import of lorem/B should be written as import LoremB from "lorem/B" instead. Typescript did not complain because of this, I guess because of "skipLibCheck": true? But writing the import as import LoremB from "lorem/B" solved the problem.

ContentLicense: CC BY-SA 4.0

Body:
I was able to resolve the question eventually.

My initial description was too simplified. In reality, it was like this:

Classes A and B were defined inside a type declaration library lorem, each as a default export from its own module. Class B extends A.

Classes C, better called my/B, and D were declared inside my own my.d.ts file. Class C actually had the same name as class B, so I had to rename it during import.

All of this was used inside my own class E, which had a method getFoo(): A.

What I initially wrote was (my.d.ts)

declare module "my/B" {
  import {B as LoremB} from "lorem/B";

  export default class B extends LoremB {
  }
}

declare module "my/D" {
  import B from "my/B";

  export default class D extends B {
    public doSomething(): void
  }
}

and (E.ts)

(this.getFoo() as D).doSomething();

This gave me the error message that the conversion may be a mistake because neither A or D sufficiently overlap each other and that doSomething is missing from A.

It turns out the import of lorem/B should be written as import LoremB from "lorem/B" instead. Typescript did not complain because of this, I guess because of "skipLibCheck": true? But writing the import as import LoremB from "lorem/B" solved the problem.


问:
Bootstrap Carousel not working in web browsers but working in mobile
I have corrected in many ways my bootstrap carousel working on mobile not in web browsers. Even i cleared my browser's cache. No sliding effect while clicking on indicator and even everything is in perfect order. other pc it is working.
Have a  look at my site please here

and here is my cod

$(document).ready(function() {
  $('#myCarousel').carousel({
    interval: 5000
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.ff {
  max-width: 4% !important;
}</code>```

<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" rel="stylesheet" />

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui@4.0/dist/fancybox.css" />

<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />

WEBSITE SHOWCASE

This website development company
 has actualized numerous website ideas into reality.
 Indulge yourself into our website development and
 design projects.

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  /assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

        Previous

        Next

```

答: I found solutions afte 1 day. If you close animation from windows, it will close all animation from all browsers. From Settings > Ease of Access > Show animations in Windows > ON. Here is the help I took from stackoverflow.

Body:
I have corrected in many ways my bootstrap carousel working on mobile not in web browsers. Even i cleared my browser's cache. No sliding effect while clicking on indicator and even everything is in perfect order. other pc it is working.
Have a  look at my site please here

and here is my cod

$(document).ready(function() {
  $('#myCarousel').carousel({
    interval: 5000
  });
});

.ff {
  max-width: 4% !important;
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" rel="stylesheet" />

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui@4.0/dist/fancybox.css" />

<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />

WEBSITE SHOWCASE

This website development company
 has actualized numerous website ideas into reality.
 Indulge yourself into our website development and
 design projects.

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

                  <a href="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5b.png" data-fancybox="gallery">
                                        <img src="<?php echo BASE_URL; ?>/assets/img/portfolio/website/5.png" />

        Previous

        Next


问:
Not able to add .ashx file in Visual Studio
I recently downloaded Visual Studio 2012 for web(express edition) and I am creating a simple asp .net empty web site. I am retreiving the data from mysql database by using Websockets. For that i want to add .ashx file to my solution but when i am hitting add new item it is not giving me the option to add .ashx file(handler file).

edited--
all the option i am getting for adding a new file are
Text File
html page
style sheet
xml file
xml schema
xslt file
sql file

答:
Open visual Studio Installer.

Click Modify.

click "ASP.Net and web development" so that it is checked.

In the "Installation Details" section (on the Right), you will see an "Optional" section. Make sure that ".Net Framework project and item templates" is checked.

Click "Modify"


问:
CSS - why doesn't :hover parent hide child elements
I have a navigation bar with images, like so:

```<code><ul>
  <li class="me">
    <span class="cont"><img src="dummy.png" /></span>
  </li>
  <li class="me">
    <span class="cont"><img src="dummy.png" /></span>
  </li>
</ul>
</code>```

On hovering over a list item I want to change the background color to cover the span and image like so:

```<code>.me {background-color: none;}
.me:hover {background-color: rgba(150,150,150,0.5);}
</code>```

Problem is, the image does not get covered... Is this because the background is in fact... a "background" on which child elements are sitting? If so, how could I achieve this effect with plain CSS?

EDIT - solution

this worked with my original HTML structure:

```<code><ul>
  <li>
   <a href="" class="ui-btn">
     <span class="ui-btn-inner"> /* CONTAINS IMAGE AS BACKGROUND */
        <span class="ui-btn-text">text</span>  /* GETS BACKGROUND */
        <span class="ui-icon"></span>
     </span>
   </a>
 </li>
</ul>
</code>```

"Negative logic": If I assign the background to list item, it sits behind all child elements, so I figured I needed to assign the background to an element that is a child of the element containing the img to have it appear above all items. span ui-btn-inner contains the image, so setting the :hover background on span ui-btn-text makes it appear above the image... weird, but works.

答:
Yes, it's because the background is in fact a background. The best method to achieve this in raw css would be to continue using the background:

```<code>.me
{
    background-color: none;
    background-image: url(dummy.png);
    background-repeat: no-repeat;
}
.me:hover
{
    background-color: rgba(150,150,150,0.5);
    background-image: ;
}
</code>```

You could also achieve this effect with a bit of javascript as well.

```<code><ul>
  <li class="me">
    <span class="cont"><img="dummy.png" onmouseover='this.src="sometransparent.gif";' onmouseout='this.src="dummy.png";'></span>
  </li>
  <li class="me">
    <span class="cont"><img="dummy.png"" onmouseover='this.src="sometransparent.gif";' onmouseout='this.src="dummy.png";></span>
  </li>
</ul>
</code>```

Code not tested. It might require tweaking to get it just right.

Edit: Layering concept

None of this pseudo-code is test, but I've done it before so it may just take a bit of tweaking. I don't have a copy of the original I did on hand so I'll have to wing it. The first step is to create a relative container and 2 sub containers.

```<code>.meContainer
{
    position: relative;
    width: 100px;
    height: 30px;   /* I usually specify height/width for these things */
}

.meContainerLink
{
    position: absolute;
    top: 0;
    left: 0;        /* You need to use position to get them to overlap */
    z-index: 1;     /* Provide a layer */
}

.meContainerAlpha
{
    position: absolute;
    top: -30px;     /* Move it UP 30px */
    left: 0px;
    z-index: 2;     /* Place it on top of the other layer */
    display: none;  /* Hide it */
    background-color: rgba(150,150,150,0.5);
}

.meContainerAlpha:hover
{
    display: inline; /* Show it */
}
</code>```

Then you'd need to place these in divs inside your
.

```<code><ul>
  <li class="me">
    <div class="meContainer">
        <div class="meContainerLink">
            <img="dummy.png">
        </div>
        <div class="meContainerAlpha">

        </div>
    </div>
  </li>
  <li class="me">
    <div class="meContainer">
        <div class="meContainerLink">
            <img="dummy.png">
        </div>
        <div class="meContainerAlpha">

        </div>
    </div>
  </li>
</ul>
</code>```

I don't recall ever trying this method inside embedded
 tags, so it may behave oddly at first. You may have to abandon
 and switch to a different
 structure entirely.

ContentLicense: CC BY-SA 3.0

Body:
I have a navigation bar with images, like so:

On hovering over a list item I want to change the background color to cover the span and image like so:

.me {background-color: none;}
.me:hover {background-color: rgba(150,150,150,0.5);}

Problem is, the image does not get covered... Is this because the background is in fact... a "background" on which child elements are sitting? If so, how could I achieve this effect with plain CSS?

EDIT - solution

this worked with my original HTML structure:

      /* CONTAINS IMAGE AS BACKGROUND */
        text  /* GETS BACKGROUND */

"Negative logic": If I assign the background to list item, it sits behind all child elements, so I figured I needed to assign the background to an element that is a child of the element containing the img to have it appear above all items. span ui-btn-inner contains the image, so setting the :hover background on span ui-btn-text makes it appear above the image... weird, but works.

Body:
Yes, it's because the background is in fact a background. The best method to achieve this in raw css would be to continue using the background:

.me
{
    background-color: none;
    background-image: url(dummy.png);
    background-repeat: no-repeat;
}
.me:hover
{
    background-color: rgba(150,150,150,0.5);
    background-image: ;
}

You could also achieve this effect with a bit of javascript as well.

<ul>
  <li class="me">
    <span class="cont"><img="dummy.png" onmouseover='this.src="sometransparent.gif";' onmouseout='this.src="dummy.png";'></span>
  </li>
  <li class="me">
    <span class="cont"><img="dummy.png"" onmouseover='this.src="sometransparent.gif";' onmouseout='this.src="dummy.png";></span>
  </li>
</ul>

Code not tested. It might require tweaking to get it just right.

Edit: Layering concept

None of this pseudo-code is test, but I've done it before so it may just take a bit of tweaking. I don't have a copy of the original I did on hand so I'll have to wing it. The first step is to create a relative container and 2 sub containers.

.meContainer
{
    position: relative;
    width: 100px;
    height: 30px;   /* I usually specify height/width for these things */
}

.meContainerLink
{
    position: absolute;
    top: 0;
    left: 0;        /* You need to use position to get them to overlap */
    z-index: 1;     /* Provide a layer */
}

.meContainerAlpha
{
    position: absolute;
    top: -30px;     /* Move it UP 30px */
    left: 0px;
    z-index: 2;     /* Place it on top of the other layer */
    display: none;  /* Hide it */
    background-color: rgba(150,150,150,0.5);
}

.meContainerAlpha:hover
{
    display: inline; /* Show it */
}

Then you'd need to place these in divs inside your <li>.

<ul>
  <li class="me">
    <div class="meContainer">
        <div class="meContainerLink">
            <img="dummy.png">
        </div>
        <div class="meContainerAlpha">
            &nbsp;
        </div>
    </div>
  </li>
  <li class="me">
    <div class="meContainer">
        <div class="meContainerLink">
            <img="dummy.png">
        </div>
        <div class="meContainerAlpha">
            &nbsp;
        </div>
    </div>
  </li>
</ul>

I don't recall ever trying this method inside embedded <li> tags, so it may behave oddly at first. You may have to abandon <li> and switch to a different <div> structure entirely.


问:
ElasticSearch updates are not immediate, how do you wait for ElasticSearch to finish updating it's index?
I'm attempting to improve performance on a suite that tests against ElasticSearch.

The tests take a long time because Elasticsearch does not update it's indexes immediately after updating. For instance, the following code runs without raising an assertion error.

```<code>from elasticsearch import Elasticsearch
elasticsearch = Elasticsearch('es.test')

# Asumming that this is a clean and empty elasticsearch instance
elasticsearch.update(
     index='blog',
     doc_type=,'blog'
     id=1,
     body={
        ....
    }
)

results = elasticsearch.search()
assert not results
# results are not populated
</code>```

Currently out hacked together solution to this issue is dropping a time.sleep call into the code, to give ElasticSearch some time to update it's indexes.

```<code>from time import sleep
from elasticsearch import Elasticsearch
elasticsearch = Elasticsearch('es.test')

# Asumming that this is a clean and empty elasticsearch instance
elasticsearch.update(
     index='blog',
     doc_type=,'blog'
     id=1,
     body={
        ....
    }
)

# Don't want to use sleep functions
sleep(1)

results = elasticsearch.search()
assert len(results) == 1
# results are now populated
</code>```

Obviously this isn't great, as it's rather failure prone, hypothetically if ElasticSearch takes longer than a second to update it's indexes, despite how unlikely that is, the test will fail. Also it's extremely slow when you're running 100s of tests like this.

My attempt to solve the issue has been to query the pending cluster jobs to see if there are any tasks left to be done. However this doesn't work, and this code will run without an assertion error.

```<code>from elasticsearch import Elasticsearch
elasticsearch = Elasticsearch('es.test')

# Asumming that this is a clean and empty elasticsearch instance
elasticsearch.update(
     index='blog',
     doc_type=,'blog'
     id=1,
     body={
        ....
    }
)

# Query if there are any pending tasks
while elasticsearch.cluster.pending_tasks()['tasks']:
    pass

results = elasticsearch.search()
assert not results
# results are not populated
</code>```

So basically, back to my original question, ElasticSearch updates are not
immediate, how do you wait for ElasticSearch to finish updating it's index?

答:
Elasticsearch do near real-time search. The updated/indexed document is not immediately searchable but only after the next refresh operation. The refresh is scheduled every 1 second.

To retrieve a document after updating/indexing, you should use GET api instead. By default, the get API is realtime, and is not affected by the refresh rate of the index. That means if the update/index was correctly done, you should see the modifications in the response of GET request.

If you insist on using SEARCH api to retrive a document after updating/indexing. Then from the documentation, there are 3 solutions:

Waiting for the refresh interval

Setting the ?refresh option in an index/update/delete request

Using the Refresh API to explicitly complete a refresh (POST _refresh) after an index/update request. However, please note that refreshes are resource-intensive.

Body:
I'm attempting to improve performance on a suite that tests against ElasticSearch.

The tests take a long time because Elasticsearch does not update it's indexes immediately after updating. For instance, the following code runs without raising an assertion error.

from elasticsearch import Elasticsearch
elasticsearch = Elasticsearch('es.test')

# Asumming that this is a clean and empty elasticsearch instance
elasticsearch.update(
     index='blog',
     doc_type=,'blog'
     id=1,
     body={
        ....
    }
)

results = elasticsearch.search()
assert not results
# results are not populated

Currently out hacked together solution to this issue is dropping a time.sleep call into the code, to give ElasticSearch some time to update it's indexes.

from time import sleep
from elasticsearch import Elasticsearch
elasticsearch = Elasticsearch('es.test')

# Asumming that this is a clean and empty elasticsearch instance
elasticsearch.update(
     index='blog',
     doc_type=,'blog'
     id=1,
     body={
        ....
    }
)

# Don't want to use sleep functions
sleep(1)

results = elasticsearch.search()
assert len(results) == 1
# results are now populated

Obviously this isn't great, as it's rather failure prone, hypothetically if ElasticSearch takes longer than a second to update it's indexes, despite how unlikely that is, the test will fail. Also it's extremely slow when you're running 100s of tests like this.

My attempt to solve the issue has been to query the pending cluster jobs to see if there are any tasks left to be done. However this doesn't work, and this code will run without an assertion error.

from elasticsearch import Elasticsearch
elasticsearch = Elasticsearch('es.test')

# Asumming that this is a clean and empty elasticsearch instance
elasticsearch.update(
     index='blog',
     doc_type=,'blog'
     id=1,
     body={
        ....
    }
)

# Query if there are any pending tasks
while elasticsearch.cluster.pending_tasks()['tasks']:
    pass

results = elasticsearch.search()
assert not results
# results are not populated

So basically, back to my original question, ElasticSearch updates are not
immediate, how do you wait for ElasticSearch to finish updating it's index?


问:
TypeError deleting a file with gridfs mongoose and node.js
I am developing an application that allows uploading and downloading music.
I can upload files, send them to the client... however, I have problems when it comes to deleting a bucket file...

I'am using "mongoose": "^6.2.1".

My controller, where podcastId is a ObjectId:

```<code>const connection = require('../database')
const mongoose = require('mongoose')
const Users = require('../models/Users')
const PodcastInfo = require('../models/PodcastInfo')

ctrPod.deletePodcast = async (req, res, next) => {

    try {

        const id = req.params.idPodInfo
        const info = await PodcastInfo.findById(id)
        const { userId, podcastId } = info
        const gridFsBucket = new mongoose.mongo.GridFSBucket(connection, {
        bucketName: 'podcasts',
        });

        gridFsBucket.delete(podcastId, (err) => {
            console.log(err)
        })
.
.
.

</code>```

I get this error:

```<code>TypeError: Cannot use 'in' operator to search for 'client' in undefined
    at getTopology
</code>```

The problem appears here, \node_modules\mongodb\lib\utils.js:363:23) :

```<code>function getTopology(provider) {
    if (`topology` in provider && provider.topology) {
        return provider.topology;
    }
    else if ('client' in provider.s && provider.s.client.topology) {
        return provider.s.client.topology;
    }
    else if ('db' in provider.s && provider.s.db.s.client.topology) {
        return provider.s.db.s.client.topology;
    }
    throw new error_1.MongoNotConnectedError('MongoClient must be connected to perform this operation');
}
////////////////////////
 delete(id, callback) {
        return (0, utils_1.executeLegacyOperation)((0, utils_1.getTopology)(this.s.db), _delete, [this, id, callback], {
            skipSessions: true
        });
    }
/////////////////////////////////////

</code>```

What am I doing wrong?

答:
I think the problem lies here:

```<code> const gridFsBucket = new mongoose.mongo.GridFSBucket(connection, {
        bucketName: 'podcasts',
        });
</code>```

new mongoose.mongo.GridFSBucket(db,{bucketName}) takes in a db not a connection. Try:

```<code>const gridFsBucket = new mongoose.mongo.GridFSBucket(connection.db, {
        bucketName: 'podcasts',
        });
</code>```

Body:
I am developing an application that allows uploading and downloading music.
I can upload files, send them to the client... however, I have problems when it comes to deleting a bucket file...

I'am using "mongoose": "^6.2.1".

My controller, where podcastId is a ObjectId:

const connection = require('../database')
const mongoose = require('mongoose')
const Users = require('../models/Users')
const PodcastInfo = require('../models/PodcastInfo')

ctrPod.deletePodcast = async (req, res, next) => {

    try {

        const id = req.params.idPodInfo
        const info = await PodcastInfo.findById(id)
        const { userId, podcastId } = info
        const gridFsBucket = new mongoose.mongo.GridFSBucket(connection, {
        bucketName: 'podcasts',
        });

        gridFsBucket.delete(podcastId, (err) => {
            console.log(err)
        })
.
.
.

I get this error:

TypeError: Cannot use 'in' operator to search for 'client' in undefined
    at getTopology

The problem appears here, \node_modules\mongodb\lib\utils.js:363:23) :

function getTopology(provider) {
    if (`topology` in provider && provider.topology) {
        return provider.topology;
    }
    else if ('client' in provider.s && provider.s.client.topology) {
        return provider.s.client.topology;
    }
    else if ('db' in provider.s && provider.s.db.s.client.topology) {
        return provider.s.db.s.client.topology;
    }
    throw new error_1.MongoNotConnectedError('MongoClient must be connected to perform this operation');
}
////////////////////////
 delete(id, callback) {
        return (0, utils_1.executeLegacyOperation)((0, utils_1.getTopology)(this.s.db), _delete, [this, id, callback], {
            skipSessions: true
        });
    }
/////////////////////////////////////

What am I doing wrong?

Body:
I think the problem lies here:

 const gridFsBucket = new mongoose.mongo.GridFSBucket(connection, {
        bucketName: 'podcasts',
        });

new mongoose.mongo.GridFSBucket(db,{bucketName}) takes in a db not a connection. Try:

const gridFsBucket = new mongoose.mongo.GridFSBucket(connection.db, {
        bucketName: 'podcasts',
        });


问:
Does Amazon S3 support HTTP request with basic authentication
I would like to set up an Amazon S3 account, create a bucket, upload some data, and that this data will be available using HTTP GET with basic authentication.

I know that there are several ways to get the S3 data authenticated (query string and such), but I would like to be able to provide a simple username/password scheme for authentication.

Is this possible?

答:
By now, this has become relatively straightforward on AWS. It's basically 3 things that need to be done:

Create a CloudFront function to add Basic Auth into the request.

Configure the Origin of the CloudFront distribution correctly in a few places.

Activate the CloudFront function.

That's it, no particular bells & whistles otherwise. Here's what I've done:

First, go to CloudFront, then click on Functions on the left, create a new function with a name of your choice (no region etc. necessary) and then add the following as the code of the function:

function handler(event) {
  var user = "myuser";
  var pass = "mypassword";
  var requiredAuth = "Basic " + `${user}:${pass}`.toString('base64');

  var authHeader = event.request.headers.authorization;

  if (authHeader && authHeader.value === requiredAuth) {
    return event.request;
  } else {
    return {
      statusCode: 401,
      statusDescription: "Unauthorized",
      headers: {
        "www-authenticate": { value: 'Basic realm="Application"' },
      },
    };
  }
}
```

Then you can test with directly on the UI and assuming it works and assuming you have customized username and password, publish the function.

Next, open your CloudFront distribution and do the following:

Make sure your S3 bucket in the origin is configured as a REST endpoint and not a website endpoint, i.e. it must end on .s3.amazonaws.com and not have the word website in the hostname.

Also in the Origin settings, under "S3 bucket access", select "Yes use OAI (bucket can restrict access to only CloudFront)". In the setting below click on "Create OAI" to create a new OAI (unless you have an existing one and know what you're doing). And select "Yes, update the bucket policy" to allow AWS to add the necessary permissions to your OAI.

Finally, open your Behavior of the CloudFront distribution and scroll to the bottom. Under "Function associations", for "Viewer request" select "CloudFront Function" and select your newly created CloudFront function. Save your changes.

And that should be it. With a bit of luck a matter of a couple of minutes (realistically more, I know) and especially not additional complexity once this is all set up.

ContentLicense: CC BY-SA 2.5

Body:
By now, this has become relatively straightforward on AWS. It's basically 3 things that need to be done:

Create a CloudFront function to add Basic Auth into the request.

Configure the Origin of the CloudFront distribution correctly in a few places.

Activate the CloudFront function.

That's it, no particular bells & whistles otherwise. Here's what I've done:

First, go to CloudFront, then click on Functions on the left, create a new function with a name of your choice (no region etc. necessary) and then add the following as the code of the function:

function handler(event) {
  var user = "myuser";
  var pass = "mypassword";
  var requiredAuth = "Basic " + `${user}:${pass}`.toString('base64');

  var authHeader = event.request.headers.authorization;

  if (authHeader && authHeader.value === requiredAuth) {
    return event.request;
  } else {
    return {
      statusCode: 401,
      statusDescription: "Unauthorized",
      headers: {
        "www-authenticate": { value: 'Basic realm="Application"' },
      },
    };
  }
}

Then you can test with directly on the UI and assuming it works and assuming you have customized username and password, publish the function.

Next, open your CloudFront distribution and do the following:

Make sure your S3 bucket in the origin is configured as a REST endpoint and not a website endpoint, i.e. it must end on .s3.amazonaws.com and not have the word website in the hostname.

Also in the Origin settings, under "S3 bucket access", select "Yes use OAI (bucket can restrict access to only CloudFront)". In the setting below click on "Create OAI" to create a new OAI (unless you have an existing one and know what you're doing). And select "Yes, update the bucket policy" to allow AWS to add the necessary permissions to your OAI.

Finally, open your Behavior of the CloudFront distribution and scroll to the bottom. Under "Function associations", for "Viewer request" select "CloudFront Function" and select your newly created CloudFront function. Save your changes.

And that should be it. With a bit of luck a matter of a couple of minutes (realistically more, I know) and especially not additional complexity once this is all set up.


问:
SSL error when open jupyter notebook in Microsoft Edge
I'm opening a jupyter notebook in an Ubantu with MobaXterm.
At first , everything worked well and jupyter notebook can be open normally.
Suddenly one day when I open it in Microsoft Edge by typing "jupyter notebook", it gives the following message and the web page gives the error "ERR_SSL_VERSION_OR_CIPHER_MISMATCH"

```<code>[W 21:16:49.329 NotebookApp] SSL Error on 9 ('10.21.144.80', 56849): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)
[W 21:16:50.459 NotebookApp] SSL Error on 9 ('10.21.144.80', 56850): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)
[W 21:16:50.555 NotebookApp] SSL Error on 9 ('10.21.144.80', 56851): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)
[W 21:16:50.719 NotebookApp] SSL Error on 9 ('10.21.144.80', 56852): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)
[W 21:16:55.935 NotebookApp] SSL Error on 9 ('10.21.144.80', 56854): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)

</code>```

Try again with https, it gives

```<code>[W 21:55:56.774 NotebookApp] SSL Error on 9 ('10.21.144.80', 57721): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:55:56.777 NotebookApp] SSL Error on 10 ('10.21.144.80', 57722): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:55:56.940 NotebookApp] SSL Error on 9 ('10.21.144.80', 57723): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:55:56.958 NotebookApp] SSL Error on 10 ('10.21.144.80', 57724): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:56:02.134 NotebookApp] SSL Error on 9 ('10.21.144.80', 57727): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:56:02.142 NotebookApp] SSL Error on 10 ('10.21.144.80', 57728): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:56:02.322 NotebookApp] SSL Error on 9 ('10.21.144.80', 57729): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:56:02.323 NotebookApp] SSL Error on 10 ('10.21.144.80', 57730): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)

</code>```

But surprsingly it can be open in IE browser with a warning "DLG_FLAGS_INVALID_CADLG_FLAGS_SEC_CERT_CN_INVALID"
I also tried Chrome, just the same mistake.
I also tried most solutions I can find, just nothing happened.(;o;)

What's wrong with my computer? Thanks for your solutions.

答: It may be that the tls 1.0 and 1.1 protocols have been deprecated. Upgrade your system working with tls 1.2</p>

Body:
I'm opening a jupyter notebook in an Ubantu with MobaXterm.
At first , everything worked well and jupyter notebook can be open normally.
Suddenly one day when I open it in Microsoft Edge by typing "jupyter notebook", it gives the following message and the web page gives the error "ERR_SSL_VERSION_OR_CIPHER_MISMATCH"

[W 21:16:49.329 NotebookApp] SSL Error on 9 ('10.21.144.80', 56849): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)
[W 21:16:50.459 NotebookApp] SSL Error on 9 ('10.21.144.80', 56850): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)
[W 21:16:50.555 NotebookApp] SSL Error on 9 ('10.21.144.80', 56851): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)
[W 21:16:50.719 NotebookApp] SSL Error on 9 ('10.21.144.80', 56852): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)
[W 21:16:55.935 NotebookApp] SSL Error on 9 ('10.21.144.80', 56854): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)

Try again with https, it gives

[W 21:55:56.774 NotebookApp] SSL Error on 9 ('10.21.144.80', 57721): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:55:56.777 NotebookApp] SSL Error on 10 ('10.21.144.80', 57722): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:55:56.940 NotebookApp] SSL Error on 9 ('10.21.144.80', 57723): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:55:56.958 NotebookApp] SSL Error on 10 ('10.21.144.80', 57724): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:56:02.134 NotebookApp] SSL Error on 9 ('10.21.144.80', 57727): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:56:02.142 NotebookApp] SSL Error on 10 ('10.21.144.80', 57728): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:56:02.322 NotebookApp] SSL Error on 9 ('10.21.144.80', 57729): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:56:02.323 NotebookApp] SSL Error on 10 ('10.21.144.80', 57730): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)

But surprsingly it can be open in IE browser with a warning "DLG_FLAGS_INVALID_CADLG_FLAGS_SEC_CERT_CN_INVALID"
I also tried Chrome, just the same mistake.
I also tried most solutions I can find, just nothing happened.(;o;)

What's wrong with my computer? Thanks for your solutions.


问:
NodeJs Error: Port already in use:3000 using socket.io and express
I'm making a node.js application that uses socket.io and express.

The code looks like this-

```<code>const express=require('express');
const app=express();
const http=require('http').Server(app);
app.use(express.static('public'));

const io=require('socket.io')(http,{
  cors:{origin:'*'}
});

http.listen(3000,()=>{
  console.log('listening to port 3000');
});

//when connection made
io.on('connection',(socket)=>{
  console.log('connection made!');
});
</code>```

Here,public is a folder container all the html files for the website.

Now,when I run it locally on my pc,it works fine
But when I deployed it on the glitch.com servers,i get this error:

```<code>Error: listen EADDREINUSE: address already in use :::3000
</code>```

As far as i know,3000 is the only available port in glitch and I cannot use another port.

Also,the questions on stack overflow related to this topic doesn't help me since most of the answers are related to killing the running tasks themselves and I don't have permission to do so on the server.

答: This often happens when your server is still running in error, try switching listening to 3001 and see if there is still the error</p>

Body:
I'm making a node.js application that uses socket.io and express.

The code looks like this-

const express=require('express');
const app=express();
const http=require('http').Server(app);
app.use(express.static('public'));

const io=require('socket.io')(http,{
  cors:{origin:'*'}
});

http.listen(3000,()=>{
  console.log('listening to port 3000');
});

//when connection made
io.on('connection',(socket)=>{
  console.log('connection made!');
});

Here,public is a folder container all the html files for the website.

Now,when I run it locally on my pc,it works fine
But when I deployed it on the glitch.com servers,i get this error:

Error: listen EADDREINUSE: address already in use :::3000

As far as i know,3000 is the only available port in glitch and I cannot use another port.

Also,the questions on stack overflow related to this topic doesn't help me since most of the answers are related to killing the running tasks themselves and I don't have permission to do so on the server.


问:
Why does "x and y" return "y" when "x" and "y" are integers?
So I came across the following syntax for a coding-game solution:

.
.
n and 9
```
<p>and I didn't knew how to interpret it, thus I tried</p>
<pre class="lang-py prettyprint-override"><code>2 and 3 #3
3 and 2 #2
.
</code>```

Why does x and y (seems to) equal y i.e how is this calculated/understood?

答: This is called short-circuiting in boolean expressions if the first is true(non zero considered as true) it goes to 2nd if this was or if the first was false(0 is considered false) it goes to 2nd try it or as or integers hope this clears stuff up</p>

Body:
So I came across the following syntax for a coding-game solution:

.
.
n and 9

and I didn't knew how to interpret it, thus I tried

2 and 3 #3
3 and 2 #2
.

Why does x and y (seems to) equal y i.e how is this calculated/understood?


问:
Malformed UTF-8 error on PUT request with Dropwizard Jersey Client and Jackson
I have a Dropwizard application that queries an external REST API using a Jersey client and mapping the data with Jackson. GET requests work alright (including object mapping), but PUT resquests fail with error 500 and when I check the REST API server logs, it shows the following:

```<code>2022-02-09T11:00:34 [F|app|bd4d2aec]
 bd4d2aec | JSON::GeneratorError (source sequence is illegal/malformed utf-8):
 bd4d2aec |
 bd4d2aec | lib/server/middleware/catch_json_parse_errors.rb:16:in `rescue in call'
 bd4d2aec | lib/server/middleware/catch_json_parse_errors.rb:8:in `call'
 bd4d2aec | lib/server/middleware/logging_context_session.rb:22:in `call'
 bd4d2aec | lib/server/middleware/logging_context_request.rb:11:in `call'
</code>```

The request body JSON code required is:

```<code>{"hostgroup": {"description": "Test"}}
</code>```

I tested it with regular api clients and it works. This is how I translated it into Kotlin objects:

```<code>data class UpdateHostgroupInput(val hostgroup: UpdateDescriptionInput)
data class UpdateDescriptionInput(val description: String?)
</code>```

And this is how I build my client and my request:

```<code>val client = JerseyClientBuilder(environment)
.using(configuration.APIServerConfiguration.client)
.using(environment.objectMapper).build("API-client")
.target(url)
.register(HttpAuthenticationFeature.basic(user, password))

val parameter = UpdateHostgroupInput(UpdateDescriptionInput("Test"))

client.path(endpoint).request(MediaType.APPLICATION_JSON_TYPE).put(Entity.json(parameter))
</code>```

I tried to explicitly declare UTF-8 encoding, but it seems to be default for Jackson. I also tried forgetting about the objects and directly write JSON as a UTF-8 encoded string, but the result was the same. I've discarded the API itself being malfunctioning since I was able to perform the same request from Python successfuly.

Any hint on what I'm doing wrong here? Thanks for your help.

答:
I solved the issue by disabling gzip in the Jersey client from the config file (yml):

```<code>jerseyClient:
  gzipEnabled: false
</code>```

I guess it's not compatible with the server I'm querying against.

Body:
I have a Dropwizard application that queries an external REST API using a Jersey client and mapping the data with Jackson. GET requests work alright (including object mapping), but PUT resquests fail with error 500 and when I check the REST API server logs, it shows the following:

2022-02-09T11:00:34 [F|app|bd4d2aec]
 bd4d2aec | JSON::GeneratorError (source sequence is illegal/malformed utf-8):
 bd4d2aec |
 bd4d2aec | lib/server/middleware/catch_json_parse_errors.rb:16:in `rescue in call'
 bd4d2aec | lib/server/middleware/catch_json_parse_errors.rb:8:in `call'
 bd4d2aec | lib/server/middleware/logging_context_session.rb:22:in `call'
 bd4d2aec | lib/server/middleware/logging_context_request.rb:11:in `call'

The request body JSON code required is:

{"hostgroup": {"description": "Test"}}

I tested it with regular api clients and it works. This is how I translated it into Kotlin objects:

data class UpdateHostgroupInput(val hostgroup: UpdateDescriptionInput)
data class UpdateDescriptionInput(val description: String?)

And this is how I build my client and my request:

val client = JerseyClientBuilder(environment)
.using(configuration.APIServerConfiguration.client)
.using(environment.objectMapper).build("API-client")
.target(url)
.register(HttpAuthenticationFeature.basic(user, password))

val parameter = UpdateHostgroupInput(UpdateDescriptionInput("Test"))

client.path(endpoint).request(MediaType.APPLICATION_JSON_TYPE).put(Entity.json(parameter))

I tried to explicitly declare UTF-8 encoding, but it seems to be default for Jackson. I also tried forgetting about the objects and directly write JSON as a UTF-8 encoded string, but the result was the same. I've discarded the API itself being malfunctioning since I was able to perform the same request from Python successfuly.

Any hint on what I'm doing wrong here? Thanks for your help.

Body:
I solved the issue by disabling gzip in the Jersey client from the config file (yml):

jerseyClient:
  gzipEnabled: false

I guess it's not compatible with the server I'm querying against.


问:
Can you set public / private read access for azure blobs in the same container?
The Azure documentation says that storage blob containers can be made with public or private read access (see here). This says that public access can be set to 'Container' or 'Blob', and explains the differences in the table.

However, it isn't clear if, having set the container with Blob level public access:

```<code>container.CreateIfNotExists(Azure.Storage.Blobs.Models.PublicAccessType.Blob);
</code>```

This implies that the public read access is set on a blob by blob basis, and if so, how to set it up.

However, I am not sure this is true? I have seen various other posts about copying blobs around between different public/private containers, which somewhat backs up my thinking. The client creation doesnt appear to have a public/private setting:

```<code>BlobClient blobClient = container.GetBlobClient(filename);
</code>```

... and using the above coding, then all blobs created have public access.

My problem is that I need to allow users to change the state of uploaded images/videos to public or private. I am wondering if there is a less cludgy way than moving the blobs around between private and public containers..?

答:
Your right in your assumptions, the access level is defined on the container.

To workaround your issue, I would suggest granting access to all blob's using Shared Access Signatures. That way your application logic can control access, but all downloads still happen directly from blob storage.

The correct way to do this would be proxy all request via your application logic before redirecting the user to an blob url including the shared access signature. That way you can revoke a link later.

An example flow would then look like:

User access https://example.com/images/myimage.png

Application logic determines if "images/myimage.png" should allow anonymous access or if the user should be redirect to login

If access is allowed, the application finds the correct blob in blob storage, and generates an SAS signature

The user is then redirect to "https://example.blob.core.windows.net/images/myimage.png?sastokenstuffhere

Body:
The Azure documentation says that storage blob containers can be made with public or private read access (see here). This says that public access can be set to 'Container' or 'Blob', and explains the differences in the table.

However, it isn't clear if, having set the container with Blob level public access:

container.CreateIfNotExists(Azure.Storage.Blobs.Models.PublicAccessType.Blob);

This implies that the public read access is set on a blob by blob basis, and if so, how to set it up.

However, I am not sure this is true? I have seen various other posts about copying blobs around between different public/private containers, which somewhat backs up my thinking. The client creation doesnt appear to have a public/private setting:

BlobClient blobClient = container.GetBlobClient(filename);

... and using the above coding, then all blobs created have public access.

My problem is that I need to allow users to change the state of uploaded images/videos to public or private. I am wondering if there is a less cludgy way than moving the blobs around between private and public containers..?


问:
Hide out of stock products woocommerce query
Tying to hide out of stock products from a query

```<code><?php
                $args = array(
                        'post_type' => 'product',
                        'posts_per_page' => 16,
                        'product_cat' => 'crisps',
                        'orderby' => 'rand',
                        'meta_query' => array (
                            'key' => '_stock_status',
                            'value' => 'instock'
                        )
                    );
                $loop = new WP_Query( $args );
                if ( $loop->have_posts() ) {
                    while ( $loop->have_posts() ) : $loop->the_post();
                        wc_get_template_part( 'content', 'product' );
                    endwhile;
                } else {
                    echo __( 'No products found' );
                }
                wp_reset_postdata();
                ?>
</code>```

however the out of stock products are still showing

any help

答:
Try</p>
```<code>'meta_query' => array (
        array(
            'key' => '_stock_status',
            'value' => 'instock'
        ),
    )
</code>```

Body:
Tying to hide out of stock products from a query

<?php
                $args = array(
                        'post_type' => 'product',
                        'posts_per_page' => 16,
                        'product_cat' => 'crisps',
                        'orderby' => 'rand',
                        'meta_query' => array (
                            'key' => '_stock_status',
                            'value' => 'instock'
                        )
                    );
                $loop = new WP_Query( $args );
                if ( $loop->have_posts() ) {
                    while ( $loop->have_posts() ) : $loop->the_post();
                        wc_get_template_part( 'content', 'product' );
                    endwhile;
                } else {
                    echo __( 'No products found' );
                }
                wp_reset_postdata();
                ?>

however the out of stock products are still showing

any help

Body:
Try

'meta_query' => array (
        array(
            'key' => '_stock_status',
            'value' => 'instock'
        ),
    )


问:
Resolve java.lang.StackOverflowError memory problem
I'm using a recursive function, and I'm getting this error when I execute :

```<code>Exception in thread "main" java.lang.StackOverflowError
    at java.util.HashMap$Entry.<init>(Unknown Source)
    at java.util.HashMap.addEntry(Unknown Source)
    at java.util.HashMap.put(Unknown Source)
</code>```

I debeugged the method and 100% sure it ends at some point.

So I think its related to a memory problem.

Is there any solution ?

EDIT:

```<code>public static Vector<String> _toOpen;

public static void openFiles(Vector<String> files)
{
   ...

    while(actualFile.hasNext)
    {
        if(!_toOpen.contains(word))
        {
           _toOpen.add(word);
            System.out.println("word");
        }
    }

   ...

   if(_toOpen.size() > 0)
   {
       openFiles(_toOpen);
   }
}
</code>```

At the first call I pass to OpenFiles a Vector wich contains a list of files to open, each file has a list of files to open again and so on ...

What I'm doing is preventing a file to be opened if it was dopne before.

答:
Looking at your code - is there any conditional (e.g. if for example) on your final call to openFiles(_toOpen)?

If not, then every time openFiles is called, it will call itself recursively.  No matter what the maximum size of the stack, this method will never actually return and you've effectively got an infinite loop.

And if there is some conditional beforehand, you're evidently getting into a situation where it's consistently evaluating to a true (or whatever leads to the recursive call being made).

Asides from that, it looks like you could restructure your code to avoid this.  What it is you're trying to do with _toOpen?  Why do you appear to ignore the files argument passed in (I appreciate there is elided code, and presumably the contents get copied to _toOpen, but this seems unusual to say the least).

A recursive call does not seem like it's the best way to approach this problem, unless you have some strange situation such as files that refer to other files to open.

Body:
I'm using a recursive function, and I'm getting this error when I execute :

Exception in thread "main" java.lang.StackOverflowError
    at java.util.HashMap$Entry.<init>(Unknown Source)
    at java.util.HashMap.addEntry(Unknown Source)
    at java.util.HashMap.put(Unknown Source)

I debeugged the method and 100% sure it ends at some point.

So I think its related to a memory problem.

Is there any solution ?

EDIT:

public static Vector<String> _toOpen;

public static void openFiles(Vector<String> files)
{
   ...

    while(actualFile.hasNext)
    {
        if(!_toOpen.contains(word))
        {
           _toOpen.add(word);
            System.out.println("word");
        }
    }

   ...

   if(_toOpen.size() > 0)
   {
       openFiles(_toOpen);
   }
}

At the first call I pass to OpenFiles a Vector wich contains a list of files to open, each file has a list of files to open again and so on ...

What I'm doing is preventing a file to be opened if it was dopne before.


问:
Bigquery query plan produce unknown output
I am trying to better understand BigQuery queryPlan, and try to establish data lineage at a column-level using that queryPlan.

Everything started fine, READ, COMPUTE, etc... are pretty understandable, then I crossed a JOIN step. Using a simple query that will join two tables on a single column, and output columns from both tables:

CREATE OR REPLACE TABLE wrk_dataset.t1 AS ( select 1 as t1f1 );
CREATE OR REPLACE TABLE wrk_dataset.t2 AS ( select 1 as t2f1 );

SELECT t1f1 AS t3f1,
       t1f1 AS t3f2,
       t2f1 AS t3f3,
FROM   wrk_dataset.t1
JOIN   wrk_dataset.t2
  ON   t1f1 = t2f1
```
<p>I got those steps in my queryPlan:</p>
<h2>S00: Input</h2>
```READ    $10:t2f1
        FROM wrk_dataset.t2

WRITE   $10
        TO __stage00_output
```
<h2>S02: Output</h2>
```READ    $1:t1f1
        FROM wrk_dataset.t1

READ    $10
        FROM __stage00_output

JOIN    INNER HASH JOIN EACH WITH ALL ON $1 = $10

WRITE   $20, $21
        TO __stage02_output
```
<p>So at first, everything is fine,</p>
<ul>
<li><code>$10</code> links to <code>wrk_dataset.t2.t2f1</code></li>
<li><code>$1</code> links to <code>wrk_dataset.t1.t1f1</code></li>
<li>the join is a inner hash comparing <code>$1</code> and <code>$10</code> (so <code>wrk_dataset.t1.t1f1</code> and <code>wrk_dataset.t2.t2f1</code>)</li>
</ul>
<p>And then it becomes complicated: that step outputs <code>$20</code> and <code>$21</code>, but what are they the product of? Also in my <code>SELECT</code>, I asked for 3 columns (with 2 of them being identical), so I can <em>guess</em> that <code>$20</code> is probably <code>t1f1</code> and <code>$21</code> is <code>t2f1</code> but only by looking at the <code>SELECT</code>.</p>
<p>Is it not possible to know the result of a query just by looking at its plan like other framework?</p>
<h1>EDIT</h1>
<p>So, apparently just a simple <code>READ</code> is harder to understand that I thought.</p>
<pre class="lang-sql prettyprint-override"><code>SELECT id, id FROM ( select 1 as id )
</code>```

Give me that queryPlan:

```<code>COMPUTE     $1 := 1
WRITE       $1
            TO __stage00_output
</code>```

So I guess I cannot determinate the schema of the table that will be the result of my query by looking only at the queryPlan?

答:
Its not possible by the query plan. The $variables sent to the last step TO __stage00_output contains the column data to be sent to the output. If it is repeated, it will not be sent multiple times. It will just be showed multiple times in the final output (as there no meaning to pass same information multiple times from one step to another.)

if there is no repeated columns, it can be considered a representation of output schema, but better not use it. The query plan is meant to be used to troubleshooting and identify bottlenecks on the queries by monitoring its execution time ans so on..

Body:
I am trying to better understand BigQuery queryPlan, and try to establish data lineage at a column-level using that queryPlan.

Everything started fine, READ, COMPUTE, etc... are pretty understandable, then I crossed a JOIN step. Using a simple query that will join two tables on a single column, and output columns from both tables:

CREATE OR REPLACE TABLE wrk_dataset.t1 AS ( select 1 as t1f1 );
CREATE OR REPLACE TABLE wrk_dataset.t2 AS ( select 1 as t2f1 );

SELECT t1f1 AS t3f1,
       t1f1 AS t3f2,
       t2f1 AS t3f3,
FROM   wrk_dataset.t1
JOIN   wrk_dataset.t2
  ON   t1f1 = t2f1

I got those steps in my queryPlan:

S00: Input

READ    $10:t2f1
        FROM wrk_dataset.t2

WRITE   $10
        TO __stage00_output

S02: Output

READ    $1:t1f1
        FROM wrk_dataset.t1

READ    $10
        FROM __stage00_output

JOIN    INNER HASH JOIN EACH WITH ALL ON $1 = $10

WRITE   $20, $21
        TO __stage02_output

So at first, everything is fine,

$10 links to wrk_dataset.t2.t2f1

$1 links to wrk_dataset.t1.t1f1

the join is a inner hash comparing $1 and $10 (so wrk_dataset.t1.t1f1 and wrk_dataset.t2.t2f1)

And then it becomes complicated: that step outputs $20 and $21, but what are they the product of? Also in my SELECT, I asked for 3 columns (with 2 of them being identical), so I can guess that $20 is probably t1f1 and $21 is t2f1 but only by looking at the SELECT.

Is it not possible to know the result of a query just by looking at its plan like other framework?

EDIT

So, apparently just a simple READ is harder to understand that I thought.

SELECT id, id FROM ( select 1 as id )

Give me that queryPlan:

COMPUTE     $1 := 1
WRITE       $1
            TO __stage00_output

So I guess I cannot determinate the schema of the table that will be the result of my query by looking only at the queryPlan?


问:
Loop through NSDictionary to create separate NSArrays
I have a large NSDictionary that I need to loop through and create separate NSArrays.  Here are the contents:

```<code>(
        {
        id =         {
            text = "";
        };
        sub =         {
            text = " , ";
        };
        text = "";
        "thumb_url" =         {
            text = "";
        };
        title =         {
            text = "2010-2011";
        };
        type =         {
            text = "title";
        };
    },
        {
        id =         {
            text = "76773";
        };
        sub =         {
            text = "December 13, 2010";
        };
        text = "";
        "thumb_url" =         {
            text = "http://www.puc.edu/__data/assets/image/0004/76774/varieties/thumb.jpg";
        };
        title =         {
            text = "College Days - Fall 2010";
        };
        type =         {
            text = "gallery";
        };
    },
        {
        id =         {
            text = "";
        };
        sub =         {
            text = "";
        };
        text = "";
        "thumb_url" =         {
            text = "";
        };
        title =         {
            text = "2009-2010";
        };
        type =         {
            text = "title";
        };
    },
        {
        id =         {
            text = "76302";
        };
        sub =         {
            text = "December 3, 2010";
        };
        text = "";
        "thumb_url" =         {
            text = "http://www.puc.edu/__data/assets/image/0019/76303/varieties/thumb.jpg";
        };
        title =         {
            text = "Christmas Colloquy";
        };
        type =         {
            text = "gallery";
        };
    }
)
</code>```

Each section has a type key, which I need to check.  When it finds the title key, I need to add those to an array.  Then the next sections that would use the gallery key needs to be in its own array until it finds another title key.  Then the gallery keys after that into their own array.

I am using a UITableView section titles and content.  So, the NSDictionary above should have one NSArray *titles; array, and two other arrays each containing the galleries that came after the title.

I have tried using a for loop but I just can't seem to get it right.  Any ideas would be appreciated.

答:
```<code>NSString *key;
for(key in someDictionary){
     NSLog(@"Key: %@, Value %@", key, [someDictionary objectForKey: key]);
}
</code>```

Body:
I have a large NSDictionary that I need to loop through and create separate NSArrays.  Here are the contents:

(
        {
        id =         {
            text = "";
        };
        sub =         {
            text = " , ";
        };
        text = "";
        "thumb_url" =         {
            text = "";
        };
        title =         {
            text = "2010-2011";
        };
        type =         {
            text = "title";
        };
    },
        {
        id =         {
            text = "76773";
        };
        sub =         {
            text = "December 13, 2010";
        };
        text = "";
        "thumb_url" =         {
            text = "http://www.puc.edu/__data/assets/image/0004/76774/varieties/thumb.jpg";
        };
        title =         {
            text = "College Days - Fall 2010";
        };
        type =         {
            text = "gallery";
        };
    },
        {
        id =         {
            text = "";
        };
        sub =         {
            text = "";
        };
        text = "";
        "thumb_url" =         {
            text = "";
        };
        title =         {
            text = "2009-2010";
        };
        type =         {
            text = "title";
        };
    },
        {
        id =         {
            text = "76302";
        };
        sub =         {
            text = "December 3, 2010";
        };
        text = "";
        "thumb_url" =         {
            text = "http://www.puc.edu/__data/assets/image/0019/76303/varieties/thumb.jpg";
        };
        title =         {
            text = "Christmas Colloquy";
        };
        type =         {
            text = "gallery";
        };
    }
)

Each section has a type key, which I need to check.  When it finds the title key, I need to add those to an array.  Then the next sections that would use the gallery key needs to be in its own array until it finds another title key.  Then the gallery keys after that into their own array.

I am using a UITableView section titles and content.  So, the NSDictionary above should have one NSArray *titles; array, and two other arrays each containing the galleries that came after the title.

I have tried using a for loop but I just can't seem to get it right.  Any ideas would be appreciated.


问:
Move button when clicked
How do I move the button from the div with id of two to the div with id of one when I click the button?

  <button onclick="moveMe"></button>

```
<pre class="lang-js prettyprint-override"><code>function moveMe() {
 // ??
}
</code>```

答:
We can do this using removeChild and appendChild js features. Provided an example below with working code.

const one =  document.getElementById("one");
const two =  document.getElementById("two");

const allButtons = document.getElementsByTagName("button");

for(let i = 0; i < allButtons.length; i++) {
  const btn = allButtons[i];
  btn.addEventListener("click", function(e) {
    const el = e.currentTarget;
    const newParent =  el.parentNode.id == "one" ? two : one;
    el.parentNode.removeChild(el);
    newParent.appendChild(el)
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.section {
  height: 100px;
  width: 150px;
  padding: 4px;
  margin: 5px;
  float: left;
}

#one {
  background: #CCC;
}

#two {
  background: #eee;
}

button {
  margin: 2px;
  padding: 4px;
}</code>```

Toggle button between container on click

 <button>Move me 1</button> <button>Move me 2</button>

```

Title: Move button when clicked

Body:
How do I move the button from the div with id of two to the div with id of one when I click the button?

  <button onclick="moveMe"></button>

function moveMe() {
 // ??
}

Body:
We can do this using removeChild and appendChild js features. Provided an example below with working code.

const one =  document.getElementById("one");
const two =  document.getElementById("two");

const allButtons = document.getElementsByTagName("button");

for(let i = 0; i < allButtons.length; i++) {
  const btn = allButtons[i];
  btn.addEventListener("click", function(e) {
    const el = e.currentTarget;
    const newParent =  el.parentNode.id == "one" ? two : one;
    el.parentNode.removeChild(el);
    newParent.appendChild(el)
  });
}

.section {
  height: 100px;
  width: 150px;
  padding: 4px;
  margin: 5px;
  float: left;
}

#one {
  background: #CCC;
}

#two {
  background: #eee;
}

button {
  margin: 2px;
  padding: 4px;
}

<h3>Toggle button between container on click</h3>
<div>
  <div class="section" id="one"></div>
  <div class="section" id="two"> <button>Move me 1</button> <button>Move me 2</button></div>
</div>


答:
Using data.table::rleid to get the group ids, and ordinal function from package english to convert it to ordinal.

Base R

df$period <- as.numeric(ave(df$time_tested, df$id, FUN = data.table::rleid))
df$english <- english::ordinal(df$period)
```
<h3>tidyverse</h3>
<pre class="lang-r prettyprint-override"><code>df %>%
  group_by(id) %>%
  mutate(period = data.table::rleid(time_tested),
         english = english::ordinal(period))
</code>```

output

   id time_tested period english
1   1  2022-02-05      1   first
2   1  2022-02-05      1   first
3   1  2022-02-05      1   first
4   1  2022-02-08      2  second
5   1  2022-02-08      2  second
6   1  2022-02-08      2  second
7   1  2022-02-11      3   third
8   1  2022-02-11      3   third
9   1  2022-02-11      3   third
10  2  2022-02-08      1   first
11  2  2022-02-08      1   first
12  2  2022-02-08      1   first
13  2  2022-02-10      2  second
14  2  2022-02-10      2  second
15  2  2022-02-10      2  second
16  2  2022-02-13      3   third
17  2  2022-02-13      3   third
18  2  2022-02-13      3   third
19  3  2022-02-05      1   first
20  3  2022-02-05      1   first
21  3  2022-02-05      1   first
22  3  2022-02-08      2  second
23  3  2022-02-08      2  second
24  3  2022-02-08      2  second
25  3  2022-02-11      3   third
26  3  2022-02-11      3   third
27  3  2022-02-11      3   third
```

Title: Mutate case_when in R to create a column of time periods per participant

Body:
I have tested participants at three points in time. I have the dates at which they were tested. I want to make a column which levels are first, second, and third. Each participant has three dates, so they are all different per participant. The data looks like this:

structure(list(id = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L), time_tested = c("2022-02-05", "2022-02-05", "2022-02-05",
"2022-02-08", "2022-02-08", "2022-02-08", "2022-02-11", "2022-02-11",
"2022-02-11", "2022-02-08", "2022-02-08", "2022-02-08", "2022-02-10",
"2022-02-10", "2022-02-10", "2022-02-13", "2022-02-13", "2022-02-13",
"2022-02-05", "2022-02-05", "2022-02-05", "2022-02-08", "2022-02-08",
"2022-02-08", "2022-02-11", "2022-02-11", "2022-02-11")), class = "data.frame", row.names = c(NA,
-27L))

and this is the result I want:

structure(list(id = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L), time_tested = c("2022-02-05", "2022-02-05", "2022-02-05",
"2022-02-08", "2022-02-08", "2022-02-08", "2022-02-11", "2022-02-11",
"2022-02-11", "2022-02-08", "2022-02-08", "2022-02-08", "2022-02-10",
"2022-02-10", "2022-02-10", "2022-02-13", "2022-02-13", "2022-02-13",
"2022-02-05", "2022-02-05", "2022-02-05", "2022-02-08", "2022-02-08",
"2022-02-08", "2022-02-11", "2022-02-11", "2022-02-11"), period = c("first",
"first", "first", "second", "second", "second", "third", "third",
"third", "first", "first", "first", "second", "second", "second",
"third", "third", "third", "first", "first", "first", "second",
"second", "second", "third", "third", "third")), class = "data.frame", row.names = c(NA,
-27L))

Thank you!

Body:
Using data.table::rleid to get the group ids, and ordinal function from package english to convert it to ordinal.

Base R

df$period <- as.numeric(ave(df$time_tested, df$id, FUN = data.table::rleid))
df$english <- english::ordinal(df$period)

tidyverse

df %>%
  group_by(id) %>%
  mutate(period = data.table::rleid(time_tested),
         english = english::ordinal(period))

output

   id time_tested period english
1   1  2022-02-05      1   first
2   1  2022-02-05      1   first
3   1  2022-02-05      1   first
4   1  2022-02-08      2  second
5   1  2022-02-08      2  second
6   1  2022-02-08      2  second
7   1  2022-02-11      3   third
8   1  2022-02-11      3   third
9   1  2022-02-11      3   third
10  2  2022-02-08      1   first
11  2  2022-02-08      1   first
12  2  2022-02-08      1   first
13  2  2022-02-10      2  second
14  2  2022-02-10      2  second
15  2  2022-02-10      2  second
16  2  2022-02-13      3   third
17  2  2022-02-13      3   third
18  2  2022-02-13      3   third
19  3  2022-02-05      1   first
20  3  2022-02-05      1   first
21  3  2022-02-05      1   first
22  3  2022-02-08      2  second
23  3  2022-02-08      2  second
24  3  2022-02-08      2  second
25  3  2022-02-11      3   third
26  3  2022-02-11      3   third
27  3  2022-02-11      3   third


问:
How can i use clock instead of time.sleep in kivy?
I'm trying to change an image every half second. I researched a little and found time.sleep doesnt working on kivy. So i need to use clock function but i didnt understand how should i use it. Can you help me ?

What i want for the program is to wait for half a second between photo changes

.py file

```<code>from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.screenmanager import NoTransition
from kivy.properties import StringProperty
import time

class MainPage(Screen):
    img_ico = StringProperty("./img/testico1.png")

    def test(self):
        for _ in range(0, 3):   # Changes the image 3 times
            self.ids.my_ico1.source = './img/testico2.png'
            self.ids.my_ico1.reload()
            time.sleep(0.5)     # What should i use instead of time.sleep ?
            self.ids.my_ico1.source = './img/testico1.png'
            self.ids.my_ico1.reload()
            time.sleep(0.5)     # What should i use instead of time.sleep ?

class MyApp(App):
    def build(self):
        global sm
        sm = ScreenManager(transition=NoTransition())
        sm.add_widget(MainPage(name='mainpage'))
        return sm

if __name__ == '__main__':
    MyApp().run()
</code>```

.kv file

```<code><MainPage>
    FloatLayout:
        Button:
            text:"Test Button"
            size_hint: 0.35,0.075
            pos_hint: {"x": 0.1, "top": 0.9}
            on_release:
                root.test()

        Image:
            id: my_ico1
            source: root.img_ico
            size_hint_x: 0.04
            allow_stretch: True
            pos_hint: {"x": 0.2, "top": 0.7}
</code>```

答:
You can schedule a callback function either once or within some interval using Clock.

One of different ways you can implement this here, is as follows,

First store all images at start,

Trigger a callback, say, update_image from your test method.

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.images = ['./img/testico1.png', './img/testico2.png'] # Store all images here.
        self.index = 0 # Set a index to iterate over.

    def update_image(self, dt): # Callback function.
        i = self.index%len(self.images) # You can set your desired condition here, stop the callback etc. Currently this will loop over self.images.
        self.ids.my_ico1.source = self.images[i]
        self.index += 1

    def test(self):
        Clock.schedule_interval(self.update_image, 0.5) # It will schedule the callback after every 0.5 sec.
```

Body:
I'm trying to change an image every half second. I researched a little and found time.sleep doesnt working on kivy. So i need to use clock function but i didnt understand how should i use it. Can you help me ?

What i want for the program is to wait for half a second between photo changes

.py file

from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.screenmanager import NoTransition
from kivy.properties import StringProperty
import time

class MainPage(Screen):
    img_ico = StringProperty("./img/testico1.png")

    def test(self):
        for _ in range(0, 3):   # Changes the image 3 times
            self.ids.my_ico1.source = './img/testico2.png'
            self.ids.my_ico1.reload()
            time.sleep(0.5)     # What should i use instead of time.sleep ?
            self.ids.my_ico1.source = './img/testico1.png'
            self.ids.my_ico1.reload()
            time.sleep(0.5)     # What should i use instead of time.sleep ?

class MyApp(App):
    def build(self):
        global sm
        sm = ScreenManager(transition=NoTransition())
        sm.add_widget(MainPage(name='mainpage'))
        return sm

if __name__ == '__main__':
    MyApp().run()

.kv file

<MainPage>
    FloatLayout:
        Button:
            text:"Test Button"
            size_hint: 0.35,0.075
            pos_hint: {"x": 0.1, "top": 0.9}
            on_release:
                root.test()

        Image:
            id: my_ico1
            source: root.img_ico
            size_hint_x: 0.04
            allow_stretch: True
            pos_hint: {"x": 0.2, "top": 0.7}


问:
How can I make consistent-width plots in ggplot (with legends)?
I've got a few different categories that I want to plot.  These are different categories, each with their own set of labels, but which makes sense to group together in the document.  The following gives some simple stacked bar chart examples:

```<code>df <- data.frame(x=c("a", "b", "c"),
                 y=c("happy", "sad", "ambivalent about life"))
ggplot(df, aes(x=factor(0), fill=x)) + geom_bar()
ggplot(df, aes(x=factor(0), fill=y)) + geom_bar()
</code>```

The problem is that with different labels, the legends have different widths, which means the plots have different widths, leading to things looking a bit goofy if I make a table or \subfigure elements.  How can I fix this?

Is there a way to explicitly set the width (absolute or relative) of either the plot or the legend?

答:
You could also use the patchwork-package for that:

require(ggplot2)
require(patchwork)
# data
df = data.frame(x = c("a", "b", "c"),
                y = c("happy", "sad", "ambivalent about life"))
p1 = ggplot(df, aes(x=factor(0), fill=x)) + geom_bar()
p2 = ggplot(df, aes(x=factor(0), fill=y)) + geom_bar()

# Patchwork 1: Does it automatically
p1 / p2

# Patchwork 2: Create a list
l = patchwork::align_patches(p1, p2)
```

Body:
I've got a few different categories that I want to plot.  These are different categories, each with their own set of labels, but which makes sense to group together in the document.  The following gives some simple stacked bar chart examples:

df <- data.frame(x=c("a", "b", "c"),
                 y=c("happy", "sad", "ambivalent about life"))
ggplot(df, aes(x=factor(0), fill=x)) + geom_bar()
ggplot(df, aes(x=factor(0), fill=y)) + geom_bar()

The problem is that with different labels, the legends have different widths, which means the plots have different widths, leading to things looking a bit goofy if I make a table or \subfigure elements.  How can I fix this?

Is there a way to explicitly set the width (absolute or relative) of either the plot or the legend?


问:
Paste copied shape in the center of the canvas in flex
I have to paste the copied shape on the center of the visible part of canvas.The canvas is on the panel and panel is having scrollbar and I need to position the shape , so that the center of the shape is the center of the visible canvas.I am also zooming out the canvas and should be able to paste on the center of the zoomed canvas.
Do anybody is having any idea about the above issue?</p>

答:
how you are pasting that i don't know

any way the solution seems to be like this

convert the center point of the panel to Local point of the Canvas.

during pasting.

and this link seems to be useful Local to Global & Global to Local


问:
Gravity form automatically select value
I have gravity form. I want to do that if user select options from the drop-down then I need to also want to automatically filled others 2 filelds based on what user filled in first drop-down filed.

How can i do that?

答:
If you want to go pure code, here's a basic approach:

// Update "123" to your form ID and "1" to your Drop Down field ID.
$( '#input_123_1' ).change( function() {
    var sourceValue = $( this ).val();
    switch( sourceValue ) {
        case 'First Choice':
            targetValue = 'You are first!';
            break;
        case 'Second Choice':
            targetValue = 'Second is nothing to sneeze at.';
            break;
        case 'Third Choice':
            targetValue = 'You know what they say about being third...';
            break;
    }
    // Update "123" to your form ID and "2" to your target field ID.
    $( '#input_123_2' ).val( targetValue );
} );
```

If you want to do it the easy, no-code way, checkout our plugin, Gravity Forms Populate Anything.

The simplest approach would be to create a form that would act as your data source. On this form, you would have the possible Drop Down values and the corresponding values that should be populated when a given Drop Down value is selected.

In your original form, you would use Populate Anything to:

Populate the Drop Down options from your data source form.

Populate the values that correspond with the selected Drop Down value into your other fields.

With this approach, you can handle an infinite number of values in your Drop Down and map corresponding values to any number of additional inputs without the bulky overhead of a giant JavaScript switch case.

If you still prefer the pure code approach, consider using our free Gravity Forms Custom JavaScript plugin that will output the JS alongside your form and ensure it executes at the right time.

Title: Gravity form automatically select value

Body:
If you want to go pure code, here's a basic approach:

// Update "123" to your form ID and "1" to your Drop Down field ID.
$( '#input_123_1' ).change( function() {
    var sourceValue = $( this ).val();
    switch( sourceValue ) {
        case 'First Choice':
            targetValue = 'You are first!';
            break;
        case 'Second Choice':
            targetValue = 'Second is nothing to sneeze at.';
            break;
        case 'Third Choice':
            targetValue = 'You know what they say about being third...';
            break;
    }
    // Update "123" to your form ID and "2" to your target field ID.
    $( '#input_123_2' ).val( targetValue );
} );

If you want to do it the easy, no-code way, checkout our plugin, Gravity Forms Populate Anything.

The simplest approach would be to create a form that would act as your data source. On this form, you would have the possible Drop Down values and the corresponding values that should be populated when a given Drop Down value is selected.

In your original form, you would use Populate Anything to:

Populate the Drop Down options from your data source form.

Populate the values that correspond with the selected Drop Down value into your other fields.

With this approach, you can handle an infinite number of values in your Drop Down and map corresponding values to any number of additional inputs without the bulky overhead of a giant JavaScript switch case.

If you still prefer the pure code approach, consider using our free Gravity Forms Custom JavaScript plugin that will output the JS alongside your form and ensure it executes at the right time.


问:
getting error while using sendActivityNotification graph API
I am using the below POST api.

```<code>https://graph.microsoft.com/beta/teams/xxxx-xxx-xxxx-xxxx-xxxx/sendActivityNotification
</code>```
```<code>{
    "topic": {
        "source": "text",
        "value": "Weekly Virtual Social",
        "webUrl": "{{team link}}"
    },
    "previewText": {
        "content": "It will be fun!"
    },
    "activityType": "eventCreated",
    "recipient": {
        "@odata.type": "microsoft.graph.channelMembersNotificationRecipient",
        "teamId": "xxxx-xxxx-xxxx-xxxx",
        "channelId": "19:123456qwertyui....@thread.tacv2"
    }
}
</code>```

Error:

Application with AAD App Id 'APP-ID' is
not authorized to generate custom text notifications about
'/beta/teams/xxx-xxx-xxx-xxx/Microsoft.Teams.GraphSvc.sendActivityNotification'
to the recipient. Ensure that the expected Teams app is installed in
the target scope (user, team, or chat).

Note:

I have a bot-based application, that is installed in the team in which I am sending notifications.

The app ID matches with the App id in error.

The app manifest contains webApplication info.

答:
After searching found I need to include applicatiopermission in the webApplicationInfo JSON in the manifest file as below:

```<code>"webApplicationInfo": {
    "id": "5xxxxx-xxxx-xxx-xxxx9",
    "resource": "api://5xxxxx-xxxx-xxx-xxxx9",
    "applicationPermissions": [,
      "TeamsActivity.Send.Group"
    ]
  }
</code>```

Body:
I am using the below POST api.

https://graph.microsoft.com/beta/teams/xxxx-xxx-xxxx-xxxx-xxxx/sendActivityNotification

{
    "topic": {
        "source": "text",
        "value": "Weekly Virtual Social",
        "webUrl": "{{team link}}"
    },
    "previewText": {
        "content": "It will be fun!"
    },
    "activityType": "eventCreated",
    "recipient": {
        "@odata.type": "microsoft.graph.channelMembersNotificationRecipient",
        "teamId": "xxxx-xxxx-xxxx-xxxx",
        "channelId": "19:123456qwertyui....@thread.tacv2"
    }
}

Error:

Application with AAD App Id 'APP-ID' is
not authorized to generate custom text notifications about
'/beta/teams/xxx-xxx-xxx-xxx/Microsoft.Teams.GraphSvc.sendActivityNotification'
to the recipient. Ensure that the expected Teams app is installed in
the target scope (user, team, or chat).

Note:

I have a bot-based application, that is installed in the team in which I am sending notifications.

The app ID matches with the App id in error.

The app manifest contains webApplication info.

Body:
After searching found I need to include applicatiopermission in the webApplicationInfo JSON in the manifest file as below:

"webApplicationInfo": {
    "id": "5xxxxx-xxxx-xxx-xxxx9",
    "resource": "api://5xxxxx-xxxx-xxx-xxxx9",
    "applicationPermissions": [,
      "TeamsActivity.Send.Group"
    ]
  }


问:
How to efficiently and clearly check for existence of a row in Oracle?
Assume you have some large table foo that contains a column  bar which has a relatively low number of values. For example, 10,000 rows where the bar column can contain just 'a', 'b', or 'c'.

What is the fastest and clearest way to check for the existence of a single row where the foo column contains an 'a' value, without causing Oracle to scan every row and instead short-circuit once it has located 1 matching row?

This way is fast and concise, but I don't think it is immediately clear from the use of rownum that your goal is to check existence as quickly as possible:

```<code>select count(1)
from foo
where bar = 'a' and rownum = 1;
</code>```

This way is fast and more clear/obvious to me than the use of rownum but I still don't think it is immediately obvious, imo.

```<code>select count(1)
from dual
where exists (
    select 1
    from foo
    where bar = 'a'
)
</code>```

Is there a standard, idiomatic way to check existence for a row in Oracle that is both fast and clear as to the intent of the query?

答:
Your second version is obviously wrong - you can't select from a column (as you are, in the subquery).

The first version is perfectly fine (and efficient) - the rownum = 1 condition causes short-circuiting. It may not be immediately clear what the purpose of the rownum condition is; if that is a concern, include a comment to explain it. The query will return 1 as soon as the value of interest is first found in the column. (The table is still full-scanned, of course, if the value is not present; then the query will return 0.)

If you need an even faster check, you would need an index on column bar; the query may still be the same, but the runtime will scan the index rather than the table.

Body:
Assume you have some large table foo that contains a column  bar which has a relatively low number of values. For example, 10,000 rows where the bar column can contain just 'a', 'b', or 'c'.

What is the fastest and clearest way to check for the existence of a single row where the foo column contains an 'a' value, without causing Oracle to scan every row and instead short-circuit once it has located 1 matching row?

This way is fast and concise, but I don't think it is immediately clear from the use of rownum that your goal is to check existence as quickly as possible:

select count(1)
from foo
where bar = 'a' and rownum = 1;

This way is fast and more clear/obvious to me than the use of rownum but I still don't think it is immediately obvious, imo.

select count(1)
from dual
where exists (
    select 1
    from foo
    where bar = 'a'
)

Is there a standard, idiomatic way to check existence for a row in Oracle that is both fast and clear as to the intent of the query?


答: Chain of logical operators returns the first (counting from left-most value) item that lets you know the logical value of the whole statement. So, in case of and, there are 2 options - one of the values is False, at which point you know that whole statement is False and you return that value without checking anything further on the right, or all of them are True and you return the last one, as only then you know that it will be True.

Title: Why does "x and y" return "y" when "x" and "y" are integers?

Body:
So I came across the following syntax for a coding-game solution:

.
.
n and 9

and I didn't knew how to interpret it, thus I tried

2 and 3 #3
3 and 2 #2
.

Why does x and y (seems to) equal y i.e how is this calculated/understood?


问:
OverflowError for int value bigger than 66 bit hex number
so i found this code online and if the value set is changed to a bigger value it throws me an error

```<code>import bit
import tqdm
import time
import random
from bit import *
from tqdm import tqdm
from time import sleep
t = time.ctime()
print('',t)
sleep(1)
print('\n ================= ================= ================= ================= =================')
print('\n\n RANDOM BITCOIN PREDATOR \n #64: 8000000000000000...ffffffffffffffff\n\n')
f=[]
i=0
a=4000000
print('\n Generate',str(a),'random Keys and sort....')
while i < a:
    f.clear()
    print('\n\n WAIT! ', end='\r')
    sleep(1)
    start = time.time()
    f = random.sample(range(9223372036854775808,18446744073709551615), a)
    f.sort()
    end = time.time()
    print('',str(a),'Keys DONE !!','{:5.3f}s'.format(end-start),'\n')
    sleep(1)
    print (' start scanning... ', end='\r')
    sleep(2)
    for line in tqdm(f):
        line!='\n'
        pass
        key = Key.from_int(line)
        addr = key.address

        if addr.startswith('16jY7') or addr.endswith('jyXQN'):
            print('\n\n',hex(line),'|', addr)
            sleep(1)
            print('\n continue...\n')
            sleep(1)

        if addr == "16jY7qLJnxb7CHZyqBP8qca9d51gAjyXQN":
            print('\n\n Target found!!' + hex(line) + ' \n ' + addr,'\n')
            file=open(u"16j.Target.Info.txt","a")
            file.write('\n ' + hex(line) + ' | ' + addr)
            file.close()
            sleep(2)
            wait = input("Press Enter to Exit.")
            sleep(1)
            exit()
</code>```

error that it throws if i try to add 73786976294838206464,147573952589676412927 insted of (the default) 9223372036854775808,18446744073709551615

this is the error

```<code>Traceback (most recent call last):
  File "main.py", line 22, in <module>
    f = random.sample(range(73786976294838206464,147573952589676412927), a)
  File "/usr/lib/python3.8/random.py", line 361, in sample
    n = len(population)
OverflowError: Python int too large to convert to C ssize_t
</code>```

so the question is how do i change the "f" variable to a bigger value..?? and not get

```<code>OverflowError: Python int too large to convert to C ssize_t
</code>```

答: I'm pretty sure those numbers are specific values in the module you are using and any integer bigger is not accepted in the the conversion to the C ssize_t.</p>

Body:
so i found this code online and if the value set is changed to a bigger value it throws me an error

import bit
import tqdm
import time
import random
from bit import *
from tqdm import tqdm
from time import sleep
t = time.ctime()
print('',t)
sleep(1)
print('\n ================= ================= ================= ================= =================')
print('\n\n RANDOM BITCOIN PREDATOR \n #64: 8000000000000000...ffffffffffffffff\n\n')
f=[]
i=0
a=4000000
print('\n Generate',str(a),'random Keys and sort....')
while i < a:
    f.clear()
    print('\n\n WAIT! ', end='\r')
    sleep(1)
    start = time.time()
    f = random.sample(range(9223372036854775808,18446744073709551615), a)
    f.sort()
    end = time.time()
    print('',str(a),'Keys DONE !!','{:5.3f}s'.format(end-start),'\n')
    sleep(1)
    print (' start scanning... ', end='\r')
    sleep(2)
    for line in tqdm(f):
        line!='\n'
        pass
        key = Key.from_int(line)
        addr = key.address

        if addr.startswith('16jY7') or addr.endswith('jyXQN'):
            print('\n\n',hex(line),'|', addr)
            sleep(1)
            print('\n continue...\n')
            sleep(1)

        if addr == "16jY7qLJnxb7CHZyqBP8qca9d51gAjyXQN":
            print('\n\n Target found!!' + hex(line) + ' \n ' + addr,'\n')
            file=open(u"16j.Target.Info.txt","a")
            file.write('\n ' + hex(line) + ' | ' + addr)
            file.close()
            sleep(2)
            wait = input("Press Enter to Exit.")
            sleep(1)
            exit()

error that it throws if i try to add 73786976294838206464,147573952589676412927 insted of (the default) 9223372036854775808,18446744073709551615

this is the error

Traceback (most recent call last):
  File "main.py", line 22, in <module>
    f = random.sample(range(73786976294838206464,147573952589676412927), a)
  File "/usr/lib/python3.8/random.py", line 361, in sample
    n = len(population)
OverflowError: Python int too large to convert to C ssize_t

so the question is how do i change the "f" variable to a bigger value..?? and not get

OverflowError: Python int too large to convert to C ssize_t