问:
How to Implement scrollIntoView in a horizontal view table for testimony
I'm sorry maybe the title make you confused, but it exactly what the title said I want to make a testimony card using table as based but I almost finish it but i can't do the final touch for it, let say I have a pointer so when I click the pointer the card will swipe to the next card but it seems I'm confused as how to implement it using javascript. I get a hunch that I can use array of child for it and move in based on the index but the card testimony still won't move

I read some topic, but the near to what I want is answer in here: Scroll smoothly by 100px horizontally

but I confused as how to implement it.

this is my code:

            var slideIndex = 1;
            showSlides(slideIndex);

            // Thumbnail image controls
            function currentTestimony(n) {
                showSlides(slideIndex = n);
            }

            function showSlides(n) {
                var i;
                var slides = document.getElementsByClassName("slider-item");
                var pointers = document.getElementsByClassName("pointer");
                if (n > slides.length) {
                    slideIndex = 1
                }

                if (n < 1) {
                    slideIndex = slides.length
                }

//                for (i = 0; i < slides.length; i++) {
//                    slides[i].getElementsById('testimony-3').scrollIntoView()
//                }

                for (i = 0; i < pointers.length; i++) {
                    pointers[i].className = pointers[i].className.replace(" active", "");
                }

                pointers[slideIndex-1].className += " active";
            }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css?family=Nunito&display=swap');

#dark-slider-testimonial .card{
    background-color: #f5f7fb;
    border-radius: 20px;
    width: 380px;
    height: 380px;
    margin: 0% 32px;
    padding: 20px;
    display: inline-table;
}

/*
    ===================================================================
    First Table
    ===================================================================
*/
#dark-slider-testimonial {
    border-radius: 20px;
    margin: 20px auto;
    padding: 5%;
    width: 100%;
    scroll-behavior: smooth;
}

#dark-slider-testimonial .container{
    width: 100%;
    max-width: 1200px;
    margin-left: auto;
    margin-right: auto;
    overflow-x: auto;
    scroll-snap-type: x mandatory;
}

#dark-slider-testimonial .container::-webkit-scrollbar {
    width: 0px;
    background: transparent;
}

#dark-slider-testimonial table {
    font-family: 'Nunito', sans-serif;
    width: 100%;
    font-size: 0.8em;
    color: #1d3962;
    border: none;
    border-top: none;
}

#dark-slider-testimonial tr{
    text-align: left;
}

#dark-slider-testimonial td{
    text-align: left;
    scroll-snap-align: start;
}

#dark-slider-testimonial .testimony-name{
    font-size: 1.6em;
    font-weight: bold;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-title{
    font-size: 1.4em;
    font-weight: bold;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-subtitle{
    font-size: 1.2em;
    font-weight: normal;
    color: #7E94B3;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-desc{
    font-size: 1.2em;
    font-weight: normal;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .pointer {
    cursor: pointer;
    height: 15px;
    width: 15px;
    margin: 0 2px;
    background-color: #bbb;
    border-radius: 50%;
    display: inline-block;
    transition: background-color 0.6s ease;
}

#dark-slider-testimonial .active,
#dark-slider-testimonial .pointer:hover {
    background-color: #3b73c5;
}</code>```

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

```

I feel I'm already near the answer but I can't quite know how to solved this, can someone help me to solve this problem?

答:
Is this It?

I have illustrated the code I've added and removed in your stylesheet. And the entire Javascript has also changed. But it's all straight forward.

var PositionPerIndex = {
  "1": "0",
  "2": "-20%",
  "3": "-40%",
  "4": "-60%",
  "5": "-80%"
};

document.querySelectorAll(".pointer").forEach(
  function(pointer){
    pointer.addEventListener('click',
      function(){
        document.getElementById("content").style.left = PositionPerIndex[this.getAttribute("data-index")];
      }
    );
  }
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css?family=Nunito&display=swap');

#dark-slider-testimonial .card{
    background-color: #f5f7fb;
    border-radius: 20px;
    width: 380px;
    height: 380px;
    margin: 0% 32px;
    padding: 20px;
    display: inline-table;
}

/*
    ===================================================================
    First Table
    ===================================================================
*/
#dark-slider-testimonial {
    border-radius: 20px;
    margin: 20px auto;
    padding: 5%;
    width: 100%;
    /* START Removed
        scroll-behavior: smooth;
       END
     */

    /* START Added */
    box-sizing: border-box;
    overflow: hidden;
}

#dark-slider-testimonial .container{
    width: 100%;
    max-width: 1200px;
    margin-left: auto;
    margin-right: auto;

    /* START Removed
        overflow-x: auto;
        scroll-snap-type: x mandatory;
       END
     */

    /* START Added */
    overflow: hidden;
}

#dark-slider-testimonial .container::-webkit-scrollbar {
    width: 0px;
    background: transparent;
}

#dark-slider-testimonial table {
    font-family: 'Nunito', sans-serif;
    width: 100%;
    overflow: hidden;
    font-size: 0.8em;
    color: #1d3962;
    border: none;
    border-top: none;
}

#dark-slider-testimonial tr{
    text-align: left;
    overflow: hidden;
    display: flex;
    flex-direction: row;

    /* Added this */
    width: 100%;
    position: relative;
    left: 0%;
    transition: left .5s ease;
}

#dark-slider-testimonial td{
    text-align: left;
    scroll-snap-align: start;

    /* Added this */
    flex-basis: 20%;
}

#dark-slider-testimonial .testimony-name{
    font-size: 1.6em;
    font-weight: bold;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-title{
    font-size: 1.4em;
    font-weight: bold;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-subtitle{
    font-size: 1.2em;
    font-weight: normal;
    color: #7E94B3;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-desc{
    font-size: 1.2em;
    font-weight: normal;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .pointer {
    cursor: pointer;
    height: 15px;
    width: 15px;
    margin: 0 2px;
    background-color: #bbb;
    border-radius: 50%;
    display: inline-block;
    transition: background-color 0.6s ease;
}

#dark-slider-testimonial .active,
#dark-slider-testimonial .pointer:hover {
    background-color: #3b73c5;
}</code>```

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

```

Body:
I'm sorry maybe the title make you confused, but it exactly what the title said I want to make a testimony card using table as based but I almost finish it but i can't do the final touch for it, let say I have a pointer so when I click the pointer the card will swipe to the next card but it seems I'm confused as how to implement it using javascript. I get a hunch that I can use array of child for it and move in based on the index but the card testimony still won't move

I read some topic, but the near to what I want is answer in here: Scroll smoothly by 100px horizontally

but I confused as how to implement it.

this is my code:

            var slideIndex = 1;
            showSlides(slideIndex);

            // Thumbnail image controls
            function currentTestimony(n) {
                showSlides(slideIndex = n);
            }

            function showSlides(n) {
                var i;
                var slides = document.getElementsByClassName("slider-item");
                var pointers = document.getElementsByClassName("pointer");
                if (n > slides.length) {
                    slideIndex = 1
                }

                if (n < 1) {
                    slideIndex = slides.length
                }

//                for (i = 0; i < slides.length; i++) {
//                    slides[i].getElementsById('testimony-3').scrollIntoView()
//                }

                for (i = 0; i < pointers.length; i++) {
                    pointers[i].className = pointers[i].className.replace(" active", "");
                }

                pointers[slideIndex-1].className += " active";
            }

@import url('https://fonts.googleapis.com/css?family=Nunito&display=swap');

#dark-slider-testimonial .card{
    background-color: #f5f7fb;
    border-radius: 20px;
    width: 380px;
    height: 380px;
    margin: 0% 32px;
    padding: 20px;
    display: inline-table;
}

/*
    ===================================================================
    First Table
    ===================================================================
*/
#dark-slider-testimonial {
    border-radius: 20px;
    margin: 20px auto;
    padding: 5%;
    width: 100%;
    scroll-behavior: smooth;
}

#dark-slider-testimonial .container{
    width: 100%;
    max-width: 1200px;
    margin-left: auto;
    margin-right: auto;
    overflow-x: auto;
    scroll-snap-type: x mandatory;
}

#dark-slider-testimonial .container::-webkit-scrollbar {
    width: 0px;
    background: transparent;
}

#dark-slider-testimonial table {
    font-family: 'Nunito', sans-serif;
    width: 100%;
    font-size: 0.8em;
    color: #1d3962;
    border: none;
    border-top: none;
}

#dark-slider-testimonial tr{
    text-align: left;
}

#dark-slider-testimonial td{
    text-align: left;
    scroll-snap-align: start;
}

#dark-slider-testimonial .testimony-name{
    font-size: 1.6em;
    font-weight: bold;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-title{
    font-size: 1.4em;
    font-weight: bold;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-subtitle{
    font-size: 1.2em;
    font-weight: normal;
    color: #7E94B3;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-desc{
    font-size: 1.2em;
    font-weight: normal;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .pointer {
    cursor: pointer;
    height: 15px;
    width: 15px;
    margin: 0 2px;
    background-color: #bbb;
    border-radius: 50%;
    display: inline-block;
    transition: background-color 0.6s ease;
}

#dark-slider-testimonial .active,
#dark-slider-testimonial .pointer:hover {
    background-color: #3b73c5;
}

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

I feel I'm already near the answer but I can't quite know how to solved this, can someone help me to solve this problem?

Body:
Is this It?

I have illustrated the code I've added and removed in your stylesheet. And the entire Javascript has also changed. But it's all straight forward.

var PositionPerIndex = {
  "1": "0",
  "2": "-20%",
  "3": "-40%",
  "4": "-60%",
  "5": "-80%"
};

document.querySelectorAll(".pointer").forEach(
  function(pointer){
    pointer.addEventListener('click',
      function(){
        document.getElementById("content").style.left = PositionPerIndex[this.getAttribute("data-index")];
      }
    );
  }
);

@import url('https://fonts.googleapis.com/css?family=Nunito&display=swap');

#dark-slider-testimonial .card{
    background-color: #f5f7fb;
    border-radius: 20px;
    width: 380px;
    height: 380px;
    margin: 0% 32px;
    padding: 20px;
    display: inline-table;
}

/*
    ===================================================================
    First Table
    ===================================================================
*/
#dark-slider-testimonial {
    border-radius: 20px;
    margin: 20px auto;
    padding: 5%;
    width: 100%;
    /* START Removed
        scroll-behavior: smooth;
       END
     */

    /* START Added */
    box-sizing: border-box;
    overflow: hidden;
}

#dark-slider-testimonial .container{
    width: 100%;
    max-width: 1200px;
    margin-left: auto;
    margin-right: auto;

    /* START Removed
        overflow-x: auto;
        scroll-snap-type: x mandatory;
       END
     */

    /* START Added */
    overflow: hidden;
}

#dark-slider-testimonial .container::-webkit-scrollbar {
    width: 0px;
    background: transparent;
}

#dark-slider-testimonial table {
    font-family: 'Nunito', sans-serif;
    width: 100%;
    overflow: hidden;
    font-size: 0.8em;
    color: #1d3962;
    border: none;
    border-top: none;
}

#dark-slider-testimonial tr{
    text-align: left;
    overflow: hidden;
    display: flex;
    flex-direction: row;

    /* Added this */
    width: 100%;
    position: relative;
    left: 0%;
    transition: left .5s ease;
}

#dark-slider-testimonial td{
    text-align: left;
    scroll-snap-align: start;

    /* Added this */
    flex-basis: 20%;
}

#dark-slider-testimonial .testimony-name{
    font-size: 1.6em;
    font-weight: bold;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-title{
    font-size: 1.4em;
    font-weight: bold;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-subtitle{
    font-size: 1.2em;
    font-weight: normal;
    color: #7E94B3;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-desc{
    font-size: 1.2em;
    font-weight: normal;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .pointer {
    cursor: pointer;
    height: 15px;
    width: 15px;
    margin: 0 2px;
    background-color: #bbb;
    border-radius: 50%;
    display: inline-block;
    transition: background-color 0.6s ease;
}

#dark-slider-testimonial .active,
#dark-slider-testimonial .pointer:hover {
    background-color: #3b73c5;
}

<div id="dark-slider-testimonial">
            <div>
                <div class="container">
                    <table>
                        <tr id="content">
                            <td id="testimony-1" class="slider-item">
                                <div class="card">
                                    <p class="testimony-name">
                                        name
                                    </p>
                                    <p class="testimony-subtitle">
                                        title
                                    </p>
                                    <p class="testimony-desc">
                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.
                                    </p>
                                </div>
                            </td>

                            <td id="testimony-2" class="slider-item">
                                <div class="card">
                                    <p class="testimony-name">
                                        name
                                    </p>
                                    <p class="testimony-subtitle">
                                        title
                                    </p>
                                    <p class="testimony-desc">
                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.
                                    </p>
                                </div>
                            </td>

                            <td id="testimony-3" class="slider-item">
                                <div class="card">
                                    <p class="testimony-name">
                                        name
                                    </p>
                                    <p class="testimony-subtitle">
                                        title
                                    </p>
                                    <p class="testimony-desc">
                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.
                                    </p>
                                </div>
                            </td>

                            <td id="testimony-4" class="slider-item">
                                <div class="card">
                                    <p class="testimony-name">
                                        name
                                    </p>
                                    <p class="testimony-subtitle">
                                        title
                                    </p>
                                    <p class="testimony-desc">
                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.
                                    </p>
                                </div>
                            </td>

                            <td id="testimony-5" class="slider-item">
                                <div class="card">
                                    <p class="testimony-name">
                                        name
                                    </p>
                                    <p class="testimony-subtitle">
                                        title
                                    </p>
                                    <p class="testimony-desc">
                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.
                                    </p>
                                </div>
                            </td>
                        </tr>
                    </table>
                </div>

                <!-- The pointers/circles -->
                <div style="text-align:center">
                    <span class="pointer" data-index="1"></span>
                    <span class="pointer" data-index="2"></span>
                    <span class="pointer" data-index="3"></span>
                    <span class="pointer" data-index="4"></span>
                    <span class="pointer" data-index="5"></span>
                </div>
            </div>
        </div>


来源: stackexchange

问:
Catalyst File Transfer sample code
Does anyone know how to use Catalyst File Transfer utility. I saw the site of that product but they dont have any sample code.</p>

答: Found the samples with the originally downloaded software.</p>

ContentLicense: CC BY-SA 3.0

Title: Catalyst File Transfer sample code


问:
How to drop data frame row if there is less than 4 character in sentence column?
let's say i have already tokenized sentence in my data frame like this :

```<code>+-----------------------------------------+-----------+
|                sentence                 | sentiment |
+-----------------------------------------+-----------+
| [i, like, this, app, it, s, awesome]    | positive  |
| [way, to, many, ads, pop, up, hate, it] | negative  |
| [ye]                                    | negative  |
| [p]                                     | positive  |
| [niceeeee]                              | positive  |
| [i, do, not, like, the, design]         | negative  |
| [very, useful, recommended]             | positive  |
| [ugly]                                  | negative  |
| [xxx]                                   | negative  |
| [yes]                                   | positive  |
+-----------------------------------------+-----------+
</code>```

I want to clean out unnecessary data from my data frame by removing df row if there is less than 4 character is sentence column, so the end result will be like this :

```<code>+-----------------------------------------+-----------+
|                sentence                 | sentiment |
+-----------------------------------------+-----------+
| [i, like, this, app, it, s, awesome]    | positive  |
| [way, to, many, ads, pop, up, hate, it] | negative  |
| [niceeeee]                              | positive  |
| [i, do, not, like, the, design]         | negative  |
| [very, useful, recommended]             | positive  |
| [ugly]                                  | negative  |
+-----------------------------------------+-----------+
</code>```

is there anyone who can provide the program code to solve this problem? i will really appreciate your help, it will help my thesis work, thank you for your attention

答:
You can use apply function for this

```<code>char_limit=4
df[df['sentence'].apply(lambda x : len("".join(x))>=char_limit)]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
let's say i have already tokenized sentence in my data frame like this :

+-----------------------------------------+-----------+
|                sentence                 | sentiment |
+-----------------------------------------+-----------+
| [i, like, this, app, it, s, awesome]    | positive  |
| [way, to, many, ads, pop, up, hate, it] | negative  |
| [ye]                                    | negative  |
| [p]                                     | positive  |
| [niceeeee]                              | positive  |
| [i, do, not, like, the, design]         | negative  |
| [very, useful, recommended]             | positive  |
| [ugly]                                  | negative  |
| [xxx]                                   | negative  |
| [yes]                                   | positive  |
+-----------------------------------------+-----------+

I want to clean out unnecessary data from my data frame by removing df row if there is less than 4 character is sentence column, so the end result will be like this :

+-----------------------------------------+-----------+
|                sentence                 | sentiment |
+-----------------------------------------+-----------+
| [i, like, this, app, it, s, awesome]    | positive  |
| [way, to, many, ads, pop, up, hate, it] | negative  |
| [niceeeee]                              | positive  |
| [i, do, not, like, the, design]         | negative  |
| [very, useful, recommended]             | positive  |
| [ugly]                                  | negative  |
+-----------------------------------------+-----------+

is there anyone who can provide the program code to solve this problem? i will really appreciate your help, it will help my thesis work, thank you for your attention

Body:
You can use apply function for this

char_limit=4
df[df['sentence'].apply(lambda x : len("".join(x))>=char_limit)]


问:
How to make long press touch and hold in react-native
I need to longpress to make my chat to archive.(i.e) like whatsapp we have long press and make the chat to pin in the top

How can I make the same using react-native?

答:
What input type are you using?

If you are using any of the touchable components, you can use the onLongPress. More info on it here


问:
Integrate custom task into lifecycle of multi project build
I have a multi-project build containing the two java library modules 'A' and 'B'. 'B' has an dependency to module 'A':

```<code>dependencies {
  api ':A'
}
</code>```

Now I want to write a custom plugin that provides the custom task 'myGenerator'. 'myGenerator' must run before compiling any classes (task compileJava) in module 'B' but after assembling module 'A' ('myGenerator' will implement a code generator that needs some resources of module 'A').

How shall I configure task 'myGenerator'? If I say

```<code>compileJava.dependsOn myGenerator
</code>```

and run gradle assemble within module 'B', 'myGenerator' still gets executed before assembling module 'A'.

Somehow I have to configure 'myGenerator' to have a dependency to the configuration 'api' of module 'A'. How can I do this?

答:
You only expressed one dependency from your sentence:

'myGenerator' must run before compiling any classes (task compileJava) in module 'B' but after assembling module 'A'

You need to express the other one:

```<code>myGenerator.dependsOn project(':A').jar // or the relevant assembly task of your build
</code>```

Body:
I have a multi-project build containing the two java library modules 'A' and 'B'. 'B' has an dependency to module 'A':

dependencies {
  api ':A'
}

Now I want to write a custom plugin that provides the custom task 'myGenerator'. 'myGenerator' must run before compiling any classes (task compileJava) in module 'B' but after assembling module 'A' ('myGenerator' will implement a code generator that needs some resources of module 'A').

How shall I configure task 'myGenerator'? If I say

compileJava.dependsOn myGenerator

and run gradle assemble within module 'B', 'myGenerator' still gets executed before assembling module 'A'.

Somehow I have to configure 'myGenerator' to have a dependency to the configuration 'api' of module 'A'. How can I do this?

Body:
You only expressed one dependency from your sentence:

'myGenerator' must run before compiling any classes (task compileJava) in module 'B' but after assembling module 'A'

You need to express the other one:

myGenerator.dependsOn project(':A').jar // or the relevant assembly task of your build


问:
Upload duplicate files using CMIS API
I want to upload the two file having the same name into Alfresco Repository (I am able to do it into Documentum) but I am getting below exception
Can somebody tell me how can I achieve it as it is my business use case in which the user can upload the document having the same name? Please note that the same is working as expected in the Documentum.</p>

```<code>[2/12/20 16:43:03:554 IST] 00000040 SystemErr     R org.apache.chemistry.opencmis.commons.exceptions.CmisContentAlreadyExistsException: An object with this name already exists: 01120277 File or folder Book_295_12.xlsx already exists
[2/12/20 16:43:03:555 IST] 00000040 SystemErr     R     at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.convertStatusCode(AbstractAtomPubService.java:506)
</code>```

答:
To do this you should override your contentModel.xml:

```<code><type name="cm:folder">
    <title>Folder</title>
    <parent>cm:cmobject</parent>
    <archive>true</archive>
    <properties/>
    <associations>
        <child-association name="cm:contains">
            <source>
                <mandatory>false</mandatory>
                <many>true</many>
            </source>
            <target>
                <class>sys:base</class>
                <mandatory enforced="false">false</mandatory>
                <many>true</many>
            </target>
            <duplicate>false</duplicate>
            <propagateTimestamps>true</propagateTimestamps>
        </child-association>
    </associations>
    <overrides/>
    <mandatory-aspects/>
</type>
</code>```

As you can see there is duplicate param in child-association with "false" value. You should change it to "true"

Title: Upload duplicate files using CMIS API

Body:
I want to upload the two file having the same name into Alfresco Repository (I am able to do it into Documentum) but I am getting below exception
Can somebody tell me how can I achieve it as it is my business use case in which the user can upload the document having the same name? Please note that the same is working as expected in the Documentum.

[2/12/20 16:43:03:554 IST] 00000040 SystemErr     R org.apache.chemistry.opencmis.commons.exceptions.CmisContentAlreadyExistsException: An object with this name already exists: 01120277 File or folder Book_295_12.xlsx already exists
[2/12/20 16:43:03:555 IST] 00000040 SystemErr     R     at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.convertStatusCode(AbstractAtomPubService.java:506)

Body:
To do this you should override your contentModel.xml:

<type name="cm:folder">
    <title>Folder</title>
    <parent>cm:cmobject</parent>
    <archive>true</archive>
    <properties/>
    <associations>
        <child-association name="cm:contains">
            <source>
                <mandatory>false</mandatory>
                <many>true</many>
            </source>
            <target>
                <class>sys:base</class>
                <mandatory enforced="false">false</mandatory>
                <many>true</many>
            </target>
            <duplicate>false</duplicate>
            <propagateTimestamps>true</propagateTimestamps>
        </child-association>
    </associations>
    <overrides/>
    <mandatory-aspects/>
</type>

As you can see there is duplicate param in child-association with "false" value. You should change it to "true"


问:
html,JS search field list
I'm new to JS but have good knowledge in C and HTML and want to create a search box so that when I write something, a drop-down list appears with some results. I already have the code to create the animated search field (which is not mine) and the code to create this search filter list but I don't know how to "connect" them.

Here is the JS part for the search bar filter: (To use it you just need this html code
<input type="text" id="searchInput" placeholder="Search article"/> here is the fiddle: https://jsfiddle.net/c30L5esq/)

```<code>$("#searchInput").on('keyup', function() {
  var searchValue = $(this).val().toUpperCase();
  if(searchValue.length > 0) {
    searchAndFilter(searchValue);
  } else {
    $("#articlesearch li").hide();
  }
});

function searchAndFilter(searchTerm) {
  $("#articlesearch li").each(function() {
    var currentText = $(this).text().toUpperCase();
    if (currentText.indexOf(searchTerm) >= 0) {
      $(this).show();
    } else {
        $(this).hide();
    }
  });
}

$(document).ready(function() {
  $("#articlesearch li").hide();
});
</code>```

And here it is the link for the search bar fullscreen animation :
https://codepen.io/suez/pen/obpLvy/

And what I want is that when I use this search bar animation, I can actually search through a list and it will show me results that match what I typed in a dropdown.

Thank you !

答:
```<code>$(document).ready(function() {
  var list = $("#articlesearch>li");
  list.hide();

  $(document).on('input', "#searchInput", function() {
    /* searchAndFilter($(this).val()) */
    list.hide();
    var searchTerm = ($(this).val() + '').toUpperCase();
    if (searchTerm.length > 0) {
      list.each(function() {
        var currentText = $(this).text().toUpperCase();
        if (currentText.indexOf(searchTerm) >= 0) {
          $(this).show();
        } else {
          $(this).hide();
        }
      });
    }
  });
});

</code>```

Jsfiddle: https://jsfiddle.net/ravinila/ghovnzty/13

Title: html,JS search field list

Body:
I'm new to JS but have good knowledge in C and HTML and want to create a search box so that when I write something, a drop-down list appears with some results. I already have the code to create the animated search field (which is not mine) and the code to create this search filter list but I don't know how to "connect" them.

Here is the JS part for the search bar filter: (To use it you just need this html code
<input type="text" id="searchInput" placeholder="Search article"/> here is the fiddle: https://jsfiddle.net/c30L5esq/)

$("#searchInput").on('keyup', function() {
  var searchValue = $(this).val().toUpperCase();
  if(searchValue.length > 0) {
    searchAndFilter(searchValue);
  } else {
    $("#articlesearch li").hide();
  }
});

function searchAndFilter(searchTerm) {
  $("#articlesearch li").each(function() {
    var currentText = $(this).text().toUpperCase();
    if (currentText.indexOf(searchTerm) >= 0) {
      $(this).show();
    } else {
        $(this).hide();
    }
  });
}

$(document).ready(function() {
  $("#articlesearch li").hide();
});

And here it is the link for the search bar fullscreen animation :
https://codepen.io/suez/pen/obpLvy/

And what I want is that when I use this search bar animation, I can actually search through a list and it will show me results that match what I typed in a dropdown.

Thank you !

Body:
$(document).ready(function() {
  var list = $("#articlesearch>li");
  list.hide();

  $(document).on('input', "#searchInput", function() {
    /* searchAndFilter($(this).val()) */
    list.hide();
    var searchTerm = ($(this).val() + '').toUpperCase();
    if (searchTerm.length > 0) {
      list.each(function() {
        var currentText = $(this).text().toUpperCase();
        if (currentText.indexOf(searchTerm) >= 0) {
          $(this).show();
        } else {
          $(this).hide();
        }
      });
    }
  });
});

Jsfiddle: https://jsfiddle.net/ravinila/ghovnzty/13


答:
These long presses can be handled by passing a function to the onLongPress props of any of the Touchable components.

Delay in ms, from onPressIn, before onLongPress is called.

delayLongPress

```<code><TouchableOpacity
 style={[styles.modelView]}
 onLongPress={() => {
     console.log('Long Press')
 }}
 delayLongPress={3000}>
     <Image
       style={[styles.modelSelection]}
       source={{ uri: 'image' }}
       resizeMode='contain'/>
</TouchableOpacity>
</code>```

Title: How to make long press touch and hold in react-native

Body:
I need to longpress to make my chat to archive.(i.e) like whatsapp we have long press and make the chat to pin in the top

How can I make the same using react-native?

Body:
These long presses can be handled by passing a function to the onLongPress props of any of the Touchable components.

Delay in ms, from onPressIn, before onLongPress is called.

delayLongPress

<TouchableOpacity
 style={[styles.modelView]}
 onLongPress={() => {
     console.log('Long Press')
 }}
 delayLongPress={3000}>
     <Image
       style={[styles.modelSelection]}
       source={{ uri: 'image' }}
       resizeMode='contain'/>
</TouchableOpacity>


问:
tf how to restore two variables from the same variable
I have saved a model and now I am trying to restore it in two branches, like this:

I wrote this code, and it raises ValueError: The same saveable will be restored with two names.
How do I restore two variables from the same variable?

```<code>restore_variables = {}
for varr in tf.global_variables()
    if varr.op.name in checkpoint_variables:
        restore_variables[varr.op.name.split("_red")[0]] = varr
        restore_variables[varr.op.name.split("_blue")[0]] = varr
init_saver = tf.train.Saver(restore_variables, max_to_keep=0)
</code>```

答:
Tested on TF 1.15

Basically the error is saying that it's finding multiple references to the same variable in the restore_variables dict. The fix is simple. Create a copy of your variable using tf.Variable(varr) as follows for one of the references.

I think it's safe to assume that you're not looking for multiple references to the same variable here, rather two separate variables. (I'm assuming this because, if you want to use the same variable multiple times, you can just use the single variable multiple times).

```<code>with tf.Session() as sess:
    saver.restore(sess, './vars/vars.ckpt-0')
    restore_variables = {}
    checkpoint_variables=['b']
    for varr in tf.global_variables():
        if varr.op.name in checkpoint_variables:
            restore_variables[varr.op.name.split("_red")[0]] = varr
            restore_variables[varr.op.name.split("_blue")[0]] = tf.Variable(varr)
    print(restore_variables)
    init_saver = tf.train.Saver(restore_variables, max_to_keep=0)
</code>```

Below you can find the full code to replicate the issue using a toy example. Essentially, we have two variables a and b and out of that, we are creating b_red and b_blue variables.

```<code># Saving the variables

import tensorflow as tf
import numpy as np
a = tf.placeholder(shape=[None, 3], dtype=tf.float64)
w1 = tf.Variable(np.random.normal(size=[3,2]), name='a')
out = tf.matmul(a, w1)
w2 = tf.Variable(np.random.normal(size=[2,3]), name='b')
out = tf.matmul(out, w2)

saver = tf.train.Saver([w1, w2])

with tf.Session() as sess:
  tf.global_variables_initializer().run()
  saved_path = saver.save(sess, './vars/vars.ckpt', global_step=0)
</code>```

```<code># Restoring the variables

with tf.Session() as sess:
    saver.restore(sess, './vars/vars.ckpt-0')
    restore_variables = {}
    checkpoint_variables=['b']
    for varr in tf.global_variables():
        if varr.op.name in checkpoint_variables:
            restore_variables[varr.op.name+"_red"] = varr
            # Fixing the issue: Instead of varr, do tf.Variable(varr)
            restore_variables[varr.op.name+"_blue"] = varr
    print(restore_variables)
    init_saver = tf.train.Saver(restore_variables, max_to_keep=0)
</code>```

Body:
I have saved a model and now I am trying to restore it in two branches, like this:

I wrote this code, and it raises ValueError: The same saveable will be restored with two names.
How do I restore two variables from the same variable?

restore_variables = {}
for varr in tf.global_variables()
    if varr.op.name in checkpoint_variables:
        restore_variables[varr.op.name.split("_red")[0]] = varr
        restore_variables[varr.op.name.split("_blue")[0]] = varr
init_saver = tf.train.Saver(restore_variables, max_to_keep=0)

Body:
Tested on TF 1.15

Basically the error is saying that it's finding multiple references to the same variable in the restore_variables dict. The fix is simple. Create a copy of your variable using tf.Variable(varr) as follows for one of the references.

I think it's safe to assume that you're not looking for multiple references to the same variable here, rather two separate variables. (I'm assuming this because, if you want to use the same variable multiple times, you can just use the single variable multiple times).

with tf.Session() as sess:
    saver.restore(sess, './vars/vars.ckpt-0')
    restore_variables = {}
    checkpoint_variables=['b']
    for varr in tf.global_variables():
        if varr.op.name in checkpoint_variables:
            restore_variables[varr.op.name.split("_red")[0]] = varr
            restore_variables[varr.op.name.split("_blue")[0]] = tf.Variable(varr)
    print(restore_variables)
    init_saver = tf.train.Saver(restore_variables, max_to_keep=0)

Below you can find the full code to replicate the issue using a toy example. Essentially, we have two variables a and b and out of that, we are creating b_red and b_blue variables.

# Saving the variables

import tensorflow as tf
import numpy as np
a = tf.placeholder(shape=[None, 3], dtype=tf.float64)
w1 = tf.Variable(np.random.normal(size=[3,2]), name='a')
out = tf.matmul(a, w1)
w2 = tf.Variable(np.random.normal(size=[2,3]), name='b')
out = tf.matmul(out, w2)

saver = tf.train.Saver([w1, w2])

with tf.Session() as sess:
  tf.global_variables_initializer().run()
  saved_path = saver.save(sess, './vars/vars.ckpt', global_step=0)

# Restoring the variables

with tf.Session() as sess:
    saver.restore(sess, './vars/vars.ckpt-0')
    restore_variables = {}
    checkpoint_variables=['b']
    for varr in tf.global_variables():
        if varr.op.name in checkpoint_variables:
            restore_variables[varr.op.name+"_red"] = varr
            # Fixing the issue: Instead of varr, do tf.Variable(varr)
            restore_variables[varr.op.name+"_blue"] = varr
    print(restore_variables)
    init_saver = tf.train.Saver(restore_variables, max_to_keep=0)


问:
Scraping all comments under an Instagram post
my previous questions was closed, but the suggested answer doesn't help me. Instagram comments has a very specific behaviour! I know how to programatically scroll a website down, but with the comments on Instagram is a bit different! I would appreciate if my question was not closed immediately because it really doesn't help. Woule ba grateful for help and not shutting me down! Thank you.

Here it is again:
I am trying to build a scraper that is saving the comments under an Instagram post. I manage to log in to the instagram through my code so I can access all comments under a post, but I seem to cannot scroll down enough times to view all comments in order to scrape all of them. I only get around 20 comments everytime.

Can anyone please help me? I am using selenium webdriver.

Thank you for your help in advance! Will be greatfull.

This is my function for saving the comments:

```<code>import time
from selenium.webdriver.firefox.options import Options
from selenium.webdriver import Firefox
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

class Instagram_comments():
    def __init__(self):
        self.firefox_options = Options()
        self.browser = Firefox(options=self.firefox_options)

    def get_comments(self, url):
        self.browser.get(url)
        time.sleep(3)

        while True:
        try:
            self.load_more_comments = self.browser.find_element_by_class_name(
                    'glyphsSpriteCircle_add__outline__24__grey_9')
            self.action = ActionChains(self.browser)
            self.action.move_to_element(self.load_more_comments)
            self.load_more_comments.click()
            time.sleep(4)
            self.body_elem = self.browser.find_element_by_class_name('Mr508')
            for _ in range(100):
                self.body_elem.send_keys(Keys.END)
                time.sleep(3)
        except Exception as e:
            pass

        time.sleep(5)
        self.comment = self.browser.find_elements_by_class_name('gElp9 ')
        for c in self.comment:
            self.container = c.find_element_by_class_name('C4VMK')
            self.name = self.container.find_element_by_class_name('_6lAjh').text
            self.content = self.container.find_element_by_tag_name('span').text
            self.content = self.content.replace('\n', ' ').strip().rstrip()
            self.time_of_post = self.browser.find_element_by_xpath('//a/time').get_attribute("datetime")
            self.comment_details = {'profile name': self.name, 'comment': self.content, 'time': self.time_of_post}
            print(self.comment_details)
            time.sleep(5)

    return self.comment_details
</code>```

答:
The first function returns True if an element is found

The second function is used to scroll to the bottom till the last comment and then BeautifulSoup is used to scrape all comments

```<code>def check_exists_by_xpath(self,xpath):
    try:
        self.driver.find_element_by_xpath(xpath)
    except NoSuchElementException:
        return False
    return True

def get_comments():
        while self.check_exists_by_xpath("//div/ul/li/div/button"):
            load_more_comments_element = self.driver.find_element_by_xpath("//div/ul/li/div/button")
            load_more_comments_element.click()
            sleep(1)

        sleep(2)
        soup = BeautifulSoup(self.driver.page_source,'lxml')
        comms = soup.find_all('div',attrs={'class':'C4VMK'})
        print(len(comms))
        soup_2 = BeautifulSoup(str(comms),'lxml')
        spans = soup_2.find_all('span')
        comments = [i.text.strip() for i in spans if i != '']
        print(comments)
</code>```

I hope this helps - be aware I'm also still learning.

Body:
my previous questions was closed, but the suggested answer doesn't help me. Instagram comments has a very specific behaviour! I know how to programatically scroll a website down, but with the comments on Instagram is a bit different! I would appreciate if my question was not closed immediately because it really doesn't help. Woule ba grateful for help and not shutting me down! Thank you.

Here it is again:
I am trying to build a scraper that is saving the comments under an Instagram post. I manage to log in to the instagram through my code so I can access all comments under a post, but I seem to cannot scroll down enough times to view all comments in order to scrape all of them. I only get around 20 comments everytime.

Can anyone please help me? I am using selenium webdriver.

Thank you for your help in advance! Will be greatfull.

This is my function for saving the comments:

import time
from selenium.webdriver.firefox.options import Options
from selenium.webdriver import Firefox
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

class Instagram_comments():
    def __init__(self):
        self.firefox_options = Options()
        self.browser = Firefox(options=self.firefox_options)

    def get_comments(self, url):
        self.browser.get(url)
        time.sleep(3)

        while True:
        try:
            self.load_more_comments = self.browser.find_element_by_class_name(
                    'glyphsSpriteCircle_add__outline__24__grey_9')
            self.action = ActionChains(self.browser)
            self.action.move_to_element(self.load_more_comments)
            self.load_more_comments.click()
            time.sleep(4)
            self.body_elem = self.browser.find_element_by_class_name('Mr508')
            for _ in range(100):
                self.body_elem.send_keys(Keys.END)
                time.sleep(3)
        except Exception as e:
            pass

        time.sleep(5)
        self.comment = self.browser.find_elements_by_class_name('gElp9 ')
        for c in self.comment:
            self.container = c.find_element_by_class_name('C4VMK')
            self.name = self.container.find_element_by_class_name('_6lAjh').text
            self.content = self.container.find_element_by_tag_name('span').text
            self.content = self.content.replace('\n', ' ').strip().rstrip()
            self.time_of_post = self.browser.find_element_by_xpath('//a/time').get_attribute("datetime")
            self.comment_details = {'profile name': self.name, 'comment': self.content, 'time': self.time_of_post}
            print(self.comment_details)
            time.sleep(5)

    return self.comment_details

Body:
The first function returns True if an element is found

The second function is used to scroll to the bottom till the last comment and then BeautifulSoup is used to scrape all comments

def check_exists_by_xpath(self,xpath):
    try:
        self.driver.find_element_by_xpath(xpath)
    except NoSuchElementException:
        return False
    return True

def get_comments():
        while self.check_exists_by_xpath("//div/ul/li/div/button"):
            load_more_comments_element = self.driver.find_element_by_xpath("//div/ul/li/div/button")
            load_more_comments_element.click()
            sleep(1)

        sleep(2)
        soup = BeautifulSoup(self.driver.page_source,'lxml')
        comms = soup.find_all('div',attrs={'class':'C4VMK'})
        print(len(comms))
        soup_2 = BeautifulSoup(str(comms),'lxml')
        spans = soup_2.find_all('span')
        comments = [i.text.strip() for i in spans if i != '']
        print(comments)

I hope this helps - be aware I'm also still learning.


问:
ImportError of module libscrc on Raspberry Pi 3
I'm kinda new to Rpi's and I have a problem executing a library called libscrc with python (I use python3), I need this to calculate a crc checksum for my RS485 communication. On pycharm on my PC everything works fine, but when I implement this on my RPI3 I get errors, I already managed to install the pyserial library and this works fine, but I keep getting errors when trying to run libscrc (this is the link to the library: https://pypi.org/project/libscrc/ ). This is the error:

```<code>Traceback (most recent call last):
  File "Rs_485.py", line 1, in <module>
    import libscrc
  File "/home/pi/.local/lib/python3.6/site-packages/libscrc/__init__.py", line 14, in <module>
    from ._crcx  import *
ImportError: libpython3.6m.so.1.0: cannot open shared object file: No such file or directory
</code>```

Can anyone help me? I already updated and upgraded the RPI.
When I try the following test command

pi@raspberrypi:~/codes $ python -m libscrc.testmodbus

I get:

/usr/bin/python: No module named libscrc

And I'm using python3.6 by the way

答:
The answer was found! Hope this wil help anyone out with the same problem!

Use this command!:

```<code>sudo apt-get install libpython3.6
</code>```

this did the job for me! :)

Body:
I'm kinda new to Rpi's and I have a problem executing a library called libscrc with python (I use python3), I need this to calculate a crc checksum for my RS485 communication. On pycharm on my PC everything works fine, but when I implement this on my RPI3 I get errors, I already managed to install the pyserial library and this works fine, but I keep getting errors when trying to run libscrc (this is the link to the library: https://pypi.org/project/libscrc/ ). This is the error:

Traceback (most recent call last):
  File "Rs_485.py", line 1, in <module>
    import libscrc
  File "/home/pi/.local/lib/python3.6/site-packages/libscrc/__init__.py", line 14, in <module>
    from ._crcx  import *
ImportError: libpython3.6m.so.1.0: cannot open shared object file: No such file or directory

Can anyone help me? I already updated and upgraded the RPI.
When I try the following test command

pi@raspberrypi:~/codes $ python -m libscrc.testmodbus

I get:

/usr/bin/python: No module named libscrc

And I'm using python3.6 by the way

Body:
The answer was found! Hope this wil help anyone out with the same problem!

Use this command!:

sudo apt-get install libpython3.6

this did the job for me! :)


问:
Are implicit casting and explicit casting has the same performance?
Taken example from w3school:

```<code>int myInt = 9;
double myDouble = myInt;       // Automatic casting: int to double

Console.WriteLine(myInt);      // Outputs 9
Console.WriteLine(myDouble);   // Outputs 9
</code>```

and

```<code>double myDouble = 9.78;
int myInt = (int) myDouble;    // Manual casting: double to int

Console.WriteLine(myDouble);   // Outputs 9.78
Console.WriteLine(myInt);      // Outputs 9
</code>```

does explicit casting add extra overhead, especially for large number/array of numbers? or it is same as implicit casting?

I had to ask this for academic reason, and also would like to explicitly casting my objects and interfaces everywhere to add clarity on code base.

Edit :

add animal example:

```<code>IAnimal animal = (IAnimal) dog;
IAnimal animal = dog;
</code>```

答:
does explicit casting add extra overhead, especially for large number/array of numbers? or it is same as implicit casting?

You can refer to SharpLab to see the differences under the hood in IL. As you can see, the logic is pretty same (except the types, of course, because you are using the different types)

```<code>.method public hidebysig
instance float64 AutoCast () cil managed
{
    .maxstack 8

    IL_0000: ldc.i4.s 9
    IL_0002: conv.r8
    IL_0003: ret
} // end of method C::AutoCast

.method public hidebysig
instance int32 ManualCast () cil managed
{
    .maxstack 8

    IL_0000: ldc.r8 9.78
    IL_0009: conv.i4
    IL_000a: ret
} // end of method C::ManualCast
</code>```

Or even refer to ASM code

```<code>C.AutoCast()
    L0000: sub esp, 0x8
    L0003: vzeroupper
    L0006: vmovsd xmm0, qword [0x14540488]
    L000e: vmovsd [esp], xmm0
    L0013: fld qword [esp]
    L0016: add esp, 0x8
    L0019: ret

C.ManualCast()
    L0000: mov eax, 0x9
    L0005: ret
</code>```

As you can see, cast double to int just moves value and return an integral part, int to double more complicated. As a result of that, you can see the different benchmark results.

Of course, it depends on used CLR and .NET version (there are a lot improvements in .NET Core and some hardware intrinsics were added as well). I've run it using .NET Core and CoreCLR, in .NET Framework you'll see the different results.

You can check the exact behavior on your environment with your code (at least because you've asked a question for academic reason)

Body:
Taken example from w3school:

int myInt = 9;
double myDouble = myInt;       // Automatic casting: int to double

Console.WriteLine(myInt);      // Outputs 9
Console.WriteLine(myDouble);   // Outputs 9

and

double myDouble = 9.78;
int myInt = (int) myDouble;    // Manual casting: double to int

Console.WriteLine(myDouble);   // Outputs 9.78
Console.WriteLine(myInt);      // Outputs 9

does explicit casting add extra overhead, especially for large number/array of numbers? or it is same as implicit casting?

I had to ask this for academic reason, and also would like to explicitly casting my objects and interfaces everywhere to add clarity on code base.

Edit :

add animal example:

IAnimal animal = (IAnimal) dog;
IAnimal animal = dog;

Body:
does explicit casting add extra overhead, especially for large number/array of numbers? or it is same as implicit casting?

You can refer to SharpLab to see the differences under the hood in IL. As you can see, the logic is pretty same (except the types, of course, because you are using the different types)

.method public hidebysig
instance float64 AutoCast () cil managed
{
    .maxstack 8

    IL_0000: ldc.i4.s 9
    IL_0002: conv.r8
    IL_0003: ret
} // end of method C::AutoCast

.method public hidebysig
instance int32 ManualCast () cil managed
{
    .maxstack 8

    IL_0000: ldc.r8 9.78
    IL_0009: conv.i4
    IL_000a: ret
} // end of method C::ManualCast

Or even refer to ASM code

C.AutoCast()
    L0000: sub esp, 0x8
    L0003: vzeroupper
    L0006: vmovsd xmm0, qword [0x14540488]
    L000e: vmovsd [esp], xmm0
    L0013: fld qword [esp]
    L0016: add esp, 0x8
    L0019: ret

C.ManualCast()
    L0000: mov eax, 0x9
    L0005: ret

As you can see, cast double to int just moves value and return an integral part, int to double more complicated. As a result of that, you can see the different benchmark results.

Of course, it depends on used CLR and .NET version (there are a lot improvements in .NET Core and some hardware intrinsics were added as well). I've run it using .NET Core and CoreCLR, in .NET Framework you'll see the different results.

You can check the exact behavior on your environment with your code (at least because you've asked a question for academic reason)


问:
can I set my firebase storage in different region from my Firestore and cloud function?
most of my users will be in Indonesia. I am using Firestore, Cloud Function and Firebase storage in my project. currently I am in development phase and all my data is temporarily stored in us-central 1.

when fetching data from firestore or when I trigger the cloud function, the speed of operation is still acceptable around 1-3s (my data in us-central 1 and I am in Indonesia).

but when fetching image data from Firebase storage, it feels so slow due to high latency. so that is why I want to recreate my project and choose the region as near as possible from Indonesia

but if I see from the table in here: https://cloud.google.com/about/locations#asia-pacific

the nearest cloud storage for firebase from Indonesia is in Singapore, but unfortunately firestore and cloud functions are not available yet in Singapore,

the nearest firestore and cloud function available region from Indonesia are in Hongkong.

so my questions are

how to set my firestore and cloud function in Hongkong but my Firebase Storage is Singapore ?

If I can set in two different regions like that, is there any additional cost for this ?

答:
How to set my Firestore and Cloud Function in Hongkong but my Firebase Storage is Singapore ?

As explained in the documentation:

Before you use Cloud Firestore, you must choose a location for your
database... This location setting is
your project's default Google Cloud Platform (GCP) resource location.

At the time of writing, this Cloud Firestore location is an immutable choices, i.e. it is not changeable (Creating a new project is the only way to change it).

For Cloud Storage, "your default GCP resource location is used for GCP services in your project that require a location setting, specifically, your default Cloud Storage bucket". However, with Cloud Storage, you have the possibility to create new buckets in other locations, if you are under the Blaze pricing plan.

You already got an answer, here, on how to reference to a specific bucket :-)

For Cloud Functions, you should refer to this documentation. You will read that "by default, functions run in the us-central1 region" but that it's quite easy to change the location of a Cloud Function by setting the region parameter in the function definition.

If I can set in two different regions like that, is there any additional cost for this?

Yes, you will have extra cost if your Cloud Function (which is in asia-east2 i.e. Hong Kong) interacts with your Cloud Storage (e.g. creates a file in Storage) which is in asia-southeast1, i.e. Singapore. More details in the documentation, here and here.


问:
'flask instance' does not have attribute 'record' error
I have a project where I am trying to build an api using flask and python with the following structure:

```<code>graph:
    -app.py
    -server.py
    -apis:
        -__init__.py
        -users.py
        -transaction_functions.py
        -neo4j_ops.py
</code>```

In the server.py file I am trying to add authentification to the endpoints of my api which are coded in the users.py file. My server.py file looks like this:

```<code>import json
from six.moves.urllib.request import urlopen
from functools import wraps

from flask import Flask, request, jsonify, _request_ctx_stack
from flask_cors import cross_origin
from jose import jwt

AUTH0_DOMAIN = 'mydomain.eu'
API_AUDIENCE = 'https://my_audience.com'
ALGORITHMS = ["RS256"]

APP = Flask(__name__)

# Error handler
class AuthError(Exception):
    def __init__(self, error, status_code):
        self.error = error
        self.status_code = status_code

@APP.errorhandler(AuthError)
def handle_auth_error(ex):
    #some code

# Format error response and append status code
def get_token_auth_header():
    """Obtains the Access Token from the Authorization Header
    """
    # some code
    return token

def requires_auth(f):
    """Determines if the Access Token is valid
    """
    @wraps(f)
    def decorated(*args, **kwargs):
        #some code
    return decorated

def requires_scope(required_scope):
    """Determines if the required scope is present in the Access Token
    Args:
        required_scope (str): The scope required to access the resource
    """
    #some code
</code>```

And I keep getting this error:

```<code>Traceback (most recent call last):
  File "C:\Python37\lib\site-packages\flask_restplus\api.py", line 183, in init_app
    app.record(self._deferred_blueprint_init)
AttributeError: 'Flask' object has no attribute 'record'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "app.py", line 16, in <module>
    api.init_app(app)
  File "C:\Python37\lib\site-packages\flask_restplus\api.py", line 186, in init_app
    self._init_app(app)
  File "C:\Python37\lib\site-packages\flask_restplus\api.py", line 204, in _init_app
    self._register_view(app, resource, *urls, **kwargs)
  File "C:\Python37\lib\site-packages\flask_restplus\api.py", line 282, in _register_view
    resource_func = self.output(resource.as_view(endpoint, self, *resource_class_args,
AttributeError: 'function' object has no attribute 'as_view'
</code>```

As you can see the result of this printstack is not really useful at all since none of these calls comes from any of my files.
The only file involved in that is app.py and it looks like this:

```<code>from flask import Flask
from flask_restplus import Api
from apis import api
import config
import os

app = Flask(__name__)

api.init_app(app)#traceback comes from here.
app.run(host='0.0.0.0', port=8080)

</code>```

The apis/__init__.py file looks like this:

```<code>from flask_restplus import Api, fields
from .users import api as users
from flask import Flask

api = Api(
    title='Graph Api',
    version='0.2',
)

api.add_namespace(users)

</code>```

Any idea of what the issue is?
If I import app (the flask instance) from app.py into server.py and use that flask instance created in app rather than creating a new whole flask instance in server.py somehow the error goes away, but the issue is that I would then create a circular call of dependencies, so I cant do that.

答:
You already have an app

```<code>APP = Flask(__name__)
</code>```

And your error handler at least is using that

Yet, you defined a second one

```<code>app = Flask(__name__)
</code>```

And __name__ here is app (the name of the file), which is probably what's breaking things and why the server file isn't broken

Body:
I have a project where I am trying to build an api using flask and python with the following structure:

graph:
    -app.py
    -server.py
    -apis:
        -__init__.py
        -users.py
        -transaction_functions.py
        -neo4j_ops.py

In the server.py file I am trying to add authentification to the endpoints of my api which are coded in the users.py file. My server.py file looks like this:

import json
from six.moves.urllib.request import urlopen
from functools import wraps

from flask import Flask, request, jsonify, _request_ctx_stack
from flask_cors import cross_origin
from jose import jwt

AUTH0_DOMAIN = 'mydomain.eu'
API_AUDIENCE = 'https://my_audience.com'
ALGORITHMS = ["RS256"]

APP = Flask(__name__)

# Error handler
class AuthError(Exception):
    def __init__(self, error, status_code):
        self.error = error
        self.status_code = status_code

@APP.errorhandler(AuthError)
def handle_auth_error(ex):
    #some code

# Format error response and append status code
def get_token_auth_header():
    """Obtains the Access Token from the Authorization Header
    """
    # some code
    return token

def requires_auth(f):
    """Determines if the Access Token is valid
    """
    @wraps(f)
    def decorated(*args, **kwargs):
        #some code
    return decorated

def requires_scope(required_scope):
    """Determines if the required scope is present in the Access Token
    Args:
        required_scope (str): The scope required to access the resource
    """
    #some code

And I keep getting this error:

Traceback (most recent call last):
  File "C:\Python37\lib\site-packages\flask_restplus\api.py", line 183, in init_app
    app.record(self._deferred_blueprint_init)
AttributeError: 'Flask' object has no attribute 'record'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "app.py", line 16, in <module>
    api.init_app(app)
  File "C:\Python37\lib\site-packages\flask_restplus\api.py", line 186, in init_app
    self._init_app(app)
  File "C:\Python37\lib\site-packages\flask_restplus\api.py", line 204, in _init_app
    self._register_view(app, resource, *urls, **kwargs)
  File "C:\Python37\lib\site-packages\flask_restplus\api.py", line 282, in _register_view
    resource_func = self.output(resource.as_view(endpoint, self, *resource_class_args,
AttributeError: 'function' object has no attribute 'as_view'

As you can see the result of this printstack is not really useful at all since none of these calls comes from any of my files.
The only file involved in that is app.py and it looks like this:

from flask import Flask
from flask_restplus import Api
from apis import api
import config
import os

app = Flask(__name__)

api.init_app(app)#traceback comes from here.
app.run(host='0.0.0.0', port=8080)

The apis/__init__.py file looks like this:

from flask_restplus import Api, fields
from .users import api as users
from flask import Flask

api = Api(
    title='Graph Api',
    version='0.2',
)

api.add_namespace(users)

Any idea of what the issue is?
If I import app (the flask instance) from app.py into server.py and use that flask instance created in app rather than creating a new whole flask instance in server.py somehow the error goes away, but the issue is that I would then create a circular call of dependencies, so I cant do that.

Body:
You already have an app

APP = Flask(__name__)

And your error handler at least is using that

Yet, you defined a second one

app = Flask(__name__)

And __name__ here is app (the name of the file), which is probably what's breaking things and why the server file isn't broken


问:
How to filter nodes or edges with special character in Networkx graph
I have the following NetworkX graph, G. I would like to filter only nodes having special characters for example (A/B and B/C) or edges (A/B, B/C) excluding others.

I have tried with this but it is printing all information.

```<code>G.nodes()
A,A/B, C, B/C, D
</code>```

and

```<code>G.edges()
(A,A/B),(A,C), (A/B, B/C), (C,B/C), (B/C,D)
</code>```

But I would like to get only A/B and B/C as mentioned above by excluding others.

Is there any way to do this in networkx python? Any solution is appreciated!

答:
Graph nodes and edges are list-like structures so you can iterate through them and filter nodes/edges like a list:

```<code>import networkx as nx

G = nx.DiGraph()
G.add_edges_from([
    ('A', 'A/B'),
    ('A/B', 'B/C'),
    ('A', 'C'),
    ('B/C', 'D')
])
</code>```

Filter all nodes with B symbol in them:

list(filter(lambda x: 'B' in x, G.nodes))

['B/C', 'A/B']

Filter all nodes with / symbol in them (another way to do the same thing):

[n for n in G.nodes if '/' in n]

['B/C', 'A/B']

Filter all edges with B symbol in any node of the edge:

[e for e in G.edges if 'B' in e[0] or 'B' in e[1]]

[('A', 'A/B'), ('B/C', 'D'), ('A/B', 'B/C')]

Filter all edges with / symbol in each node of the edge:

[e for e in G.edges if '/' in e[0] and '/' in e[1]]

[('A/B', 'B/C')]

Body:
I have the following NetworkX graph, G. I would like to filter only nodes having special characters for example (A/B and B/C) or edges (A/B, B/C) excluding others.

I have tried with this but it is printing all information.

G.nodes()
A,A/B, C, B/C, D

and

G.edges()
(A,A/B),(A,C), (A/B, B/C), (C,B/C), (B/C,D)

But I would like to get only A/B and B/C as mentioned above by excluding others.

Is there any way to do this in networkx python? Any solution is appreciated!

Body:
Graph nodes and edges are list-like structures so you can iterate through them and filter nodes/edges like a list:

import networkx as nx

G = nx.DiGraph()
G.add_edges_from([
    ('A', 'A/B'),
    ('A/B', 'B/C'),
    ('A', 'C'),
    ('B/C', 'D')
])

Filter all nodes with B symbol in them:

list(filter(lambda x: 'B' in x, G.nodes))

['B/C', 'A/B']

Filter all nodes with / symbol in them (another way to do the same thing):

[n for n in G.nodes if '/' in n]

['B/C', 'A/B']

Filter all edges with B symbol in any node of the edge:

[e for e in G.edges if 'B' in e[0] or 'B' in e[1]]

[('A', 'A/B'), ('B/C', 'D'), ('A/B', 'B/C')]

Filter all edges with / symbol in each node of the edge:

[e for e in G.edges if '/' in e[0] and '/' in e[1]]

[('A/B', 'B/C')]


问:
How do you access the verbose output from a Github Actions Azure functions deployment?
I am currently trying to deploy a Python Azure Function to a Function App using Github Actions.

The deployment code is as follows:-

```<code>name: Deploy Azure Function Dev
env:
    PYTHON_VERSION: "3.7"
    WORKING_DIR: ${{ github.workspace }}/data-science-data-acquisition
    FUNCTION_APP_DEV: "data-science-data-acquisition"

on:
  pull_request:
    branches: [master]
    types: [opened,reopened,edited]
    paths:
      - 'data-science-data-acquisition/**'
  push:
    branches: [master]
    paths:
      - 'data-science-data-acquisition/**'
jobs:
  build:

    runs-on: ubuntu-latest

    steps:
    - name: "Checkout"
      uses: actions/checkout@v1

    - name: Setup Python ${{ env.PYTHON_VERSION }}
      uses: actions/setup-python@v1
      with:
          python-version: ${{ env.PYTHON_VERSION }}

    - name: 'Run pip'
      shell: bash
      run: |
        # If your function app project is not located in your repository's root
        # Please change your directory for pip in pushd
        pushd ${{ env.WORKING_DIR }}
        python -m pip install --upgrade pip
        pip install -r requirements.txt --target=".python_packages/lib/python3.6/site-packages"
        popd

    - name: 'Azure Login'
      uses: azure/login@v1
      with:
        creds: ${{ secrets.AZURE_CREDENTIALS_DEV }}

    - name: 'Deploy Function App'
      uses: Azure/functions-action@v1
      id: fa
      with:
        app-name: ${{ env.FUNCTION_APP_DEV }}
        package: ${{ env.WORKING_DIR }}
</code>```

We are currently having an issue with the deployment, however the output within Github Actions is pretty limited:-

```<code>##[PublishContent]
Waiting for function app to spin up after app settings change.
Package deployment using ZIP Deploy initiated.
##[error]Failed to deploy web package to App Service.
##[warning]Error: Failed to update deployment history.
Bad Request (CODE: 400)
##[error]Execution Exception (state: PublishContent) (step: Invocation)
##[error]  When request Azure resource at PublishContent, zipDeploy : Failed to use /home/runner/work/_temp/temp_web_package_6376243339903418.zip as ZipDeploy content
##[error]    Failed to deploy web package to App Service.
Conflict (CODE: 409)
##[error]      Error: Failed to deploy web package to App Service.
Conflict (CODE: 409)
    at Kudu.<anonymous> (/home/runner/work/_actions/Azure/functions-action/v1/node_modules/azure-actions-appservice-rest/Kudu/azure-app-kudu-service.js:155:23)
    at Generator.next (<anonymous>)
    at fulfilled (/home/runner/work/_actions/Azure/functions-action/v1/node_modules/azure-actions-appservice-rest/Kudu/azure-app-kudu-service.js:5:58)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
##[error]Deployment Failed!
##[error]Node run failed with exit code 1
</code>```

When deploying directly from VSCode, there is far more verbose output which is obviously quite useful for troubleshooting a deployment: is there a way to enable/access this from the Github Actions deployment?

I've checked the documentation for Azure/functions-action and the Python specific example but can't see anything to enable this.

答: OK so it turns out the verbose output was being displayed however, only on the first run of the action; when it was re-run a different error was causing an issue and so the expected output was masked, and overwritten on the re-run.

Body:
I am currently trying to deploy a Python Azure Function to a Function App using Github Actions.

The deployment code is as follows:-

name: Deploy Azure Function Dev
env:
    PYTHON_VERSION: "3.7"
    WORKING_DIR: ${{ github.workspace }}/data-science-data-acquisition
    FUNCTION_APP_DEV: "data-science-data-acquisition"

on:
  pull_request:
    branches: [master]
    types: [opened,reopened,edited]
    paths:
      - 'data-science-data-acquisition/**'
  push:
    branches: [master]
    paths:
      - 'data-science-data-acquisition/**'
jobs:
  build:

    runs-on: ubuntu-latest

    steps:
    - name: "Checkout"
      uses: actions/checkout@v1

    - name: Setup Python ${{ env.PYTHON_VERSION }}
      uses: actions/setup-python@v1
      with:
          python-version: ${{ env.PYTHON_VERSION }}

    - name: 'Run pip'
      shell: bash
      run: |
        # If your function app project is not located in your repository's root
        # Please change your directory for pip in pushd
        pushd ${{ env.WORKING_DIR }}
        python -m pip install --upgrade pip
        pip install -r requirements.txt --target=".python_packages/lib/python3.6/site-packages"
        popd

    - name: 'Azure Login'
      uses: azure/login@v1
      with:
        creds: ${{ secrets.AZURE_CREDENTIALS_DEV }}

    - name: 'Deploy Function App'
      uses: Azure/functions-action@v1
      id: fa
      with:
        app-name: ${{ env.FUNCTION_APP_DEV }}
        package: ${{ env.WORKING_DIR }}

We are currently having an issue with the deployment, however the output within Github Actions is pretty limited:-

##[PublishContent]
Waiting for function app to spin up after app settings change.
Package deployment using ZIP Deploy initiated.
##[error]Failed to deploy web package to App Service.
##[warning]Error: Failed to update deployment history.
Bad Request (CODE: 400)
##[error]Execution Exception (state: PublishContent) (step: Invocation)
##[error]  When request Azure resource at PublishContent, zipDeploy : Failed to use /home/runner/work/_temp/temp_web_package_6376243339903418.zip as ZipDeploy content
##[error]    Failed to deploy web package to App Service.
Conflict (CODE: 409)
##[error]      Error: Failed to deploy web package to App Service.
Conflict (CODE: 409)
    at Kudu.<anonymous> (/home/runner/work/_actions/Azure/functions-action/v1/node_modules/azure-actions-appservice-rest/Kudu/azure-app-kudu-service.js:155:23)
    at Generator.next (<anonymous>)
    at fulfilled (/home/runner/work/_actions/Azure/functions-action/v1/node_modules/azure-actions-appservice-rest/Kudu/azure-app-kudu-service.js:5:58)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
##[error]Deployment Failed!
##[error]Node run failed with exit code 1

When deploying directly from VSCode, there is far more verbose output which is obviously quite useful for troubleshooting a deployment: is there a way to enable/access this from the Github Actions deployment?

I've checked the documentation for Azure/functions-action and the Python specific example but can't see anything to enable this.


问:
Persisting docker container logs in kubernetes
I’m looking for a really simple, lightweight way of persisting logs from a docker container running in kubernetes. I just want the stdout (and stderr I guess) to go to persistent disk, I don’t want anything else for analysing the logs, to send them over the internet to a third party, etc. as part of this.

Having done some reading I’ve been considering a DaemonSet with the application container, but then another container which has /var/lib/docker/containers mounted and also a persistent volume (maybe NFS) mounted too. That container would then need a way to copy logs from the default docker JSON logging driver in /var/lib/docker/containers to the persistent volume, maybe rsync running regularly.

Would that work (presumably if the rsync container goes down it's going to miss stuff because nothing's queuing, perhaps that's ok rather than trying to queue potentially huge amounts of logs), is this a sensible approach for the desired outcome? It’s only for one or two containers if that makes a difference. Thanks.

答: Fluentd supports a simple file output plugin (https://docs.fluentd.org/output/file) which you can easily aim at a PersistentVolume mount. Otherwise you would configure Fluentd (or Bit if you prefer) just like normal for Kubernetes so find your favorite guide and follow it.</p>


问:
How to separate regex values?
the user makes a selection and I want to test if the selection is valid. So e.g.

```<code> preg_match("/(test1/test2|test3)/", $value)
</code>```

The problem is that one value is test1/test2, but each test is treated as a single value.  Any idea how to change that to have test1/test2 as a single value?

Eg:

```<code>test1/test2,
test3
</code>```

答:
Best to use strpos or other string functions unless you're actually matching a pattern. But since you've asked....</p>

```<code>preg_match("/(?:test1\/test2)|(?:test3)/", $value)
</code>```

Title: How to separate regex values?

Body:
the user makes a selection and I want to test if the selection is valid. So e.g.

 preg_match("/(test1/test2|test3)/", $value)

The problem is that one value is test1/test2, but each test is treated as a single value.  Any idea how to change that to have test1/test2 as a single value?

Eg:

test1/test2,
test3

Body:
Best to use strpos or other string functions unless you're actually matching a pattern. But since you've asked....

preg_match("/(?:test1\/test2)|(?:test3)/", $value)


问:
Constructing a date with year and month
I want to construct a date from just a year and month. I'm currently running a query like this:

```<code>SELECT
    yyyy_mm_dd AS
    t.year,
    t.month,
    t.id,
    t.name,
    ...,
    ...
    ...
FROM(
    SELECT
        p.last_yyyy_mm_dd,
        p.id,
        p.name,
    FROM(
        SELECT
            t.*,
            MAX(yyyy_mm_dd) OVER (PARTITION BY last_day(yyyy_mm_dd)) as last_yyyy_mm_dd
        FROM
            table1 t
        WHERE
            yyyy_mm_dd IS NOT NULL
            AND name = 'XXX'
    ) p
    WHERE
        yyyy_mm_dd = last_yyyy_mm_dd
) p
RIGHT JOIN(
    SELECT
        YEAR(yyyy_mm_dd) as year,
        MONTH(yyyy_mm_dd) as month,
        id,
        name,
        ...,
        ...,
        ...,
    FROM
        table2
    WHERE
        yyyy_mm_dd IS NOT NULL
        AND name = 'XXX'
    GROUP BY
        1,2,3,4
    ) t
ON
    p.id = t.id
    AND YEAR(p.last_yyyy_mm_dd) = t.year
    AND MONTH(p.last_yyyy_mm_dd) = t.month
</code>```

On the top level select, I'd like to also have a date (YYYY-MM-DD) field constructed from the year and month. The day part should be the last day of the given month. I.e. for January it'll be 31.

I've looked here https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions and can see last_day which might be useful, however there doesn't seem to be a make date function like in MySQL - https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html. How can I construct a date like this in Hive?

答:
If you have normal date, you can extract yyyy-MM using substr or date_format:

```<code>select substr('2020-01-15',1,7);
OK
2020-01

select date_format('2020-01-15','yyyy-MM');
OK
2020-01
</code>```

To get last month day from normal date, you can use last_day

```<code>select last_day(concat(substr('2020-01-15',1,7),'-01'));
OK
2020-01-31
</code>```

And if you have yyyy-MM and want last month day, concat it with '-01' and apply last_day:

```<code>select last_day(concat('2020-01','-01'));
OK
2020-01-31
</code>```

Title: Constructing a date with year and month

Body:
I want to construct a date from just a year and month. I'm currently running a query like this:

SELECT
    yyyy_mm_dd AS
    t.year,
    t.month,
    t.id,
    t.name,
    ...,
    ...
    ...
FROM(
    SELECT
        p.last_yyyy_mm_dd,
        p.id,
        p.name,
    FROM(
        SELECT
            t.*,
            MAX(yyyy_mm_dd) OVER (PARTITION BY last_day(yyyy_mm_dd)) as last_yyyy_mm_dd
        FROM
            table1 t
        WHERE
            yyyy_mm_dd IS NOT NULL
            AND name = 'XXX'
    ) p
    WHERE
        yyyy_mm_dd = last_yyyy_mm_dd
) p
RIGHT JOIN(
    SELECT
        YEAR(yyyy_mm_dd) as year,
        MONTH(yyyy_mm_dd) as month,
        id,
        name,
        ...,
        ...,
        ...,
    FROM
        table2
    WHERE
        yyyy_mm_dd IS NOT NULL
        AND name = 'XXX'
    GROUP BY
        1,2,3,4
    ) t
ON
    p.id = t.id
    AND YEAR(p.last_yyyy_mm_dd) = t.year
    AND MONTH(p.last_yyyy_mm_dd) = t.month

On the top level select, I'd like to also have a date (YYYY-MM-DD) field constructed from the year and month. The day part should be the last day of the given month. I.e. for January it'll be 31.

I've looked here https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions and can see last_day which might be useful, however there doesn't seem to be a make date function like in MySQL - https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html. How can I construct a date like this in Hive?

Body:
If you have normal date, you can extract yyyy-MM using substr or date_format:

select substr('2020-01-15',1,7);
OK
2020-01

select date_format('2020-01-15','yyyy-MM');
OK
2020-01

To get last month day from normal date, you can use last_day

select last_day(concat(substr('2020-01-15',1,7),'-01'));
OK
2020-01-31

And if you have yyyy-MM and want last month day, concat it with '-01' and apply last_day:

select last_day(concat('2020-01','-01'));
OK
2020-01-31


问:
How to troubleshoot/test Admob mediation with Facebook Audience Network in Xamarin Android?

We have followed all steps mention Integrating Facebook Audience Network with Mediation

Added Xamarin.Facebook.AudienceNetwork.Android nuget package Version 5.6.0 to Xamarin Android

Downloaded .aar package from here

Created binding using guidance from here & added to Xamarin Android project

App is building successfully but no test ad from FAN

On Facebook Monétisation Manager - App Status is in review, Integrate the audience network SDK into your app is ticked (Done)

I tried to find monetisation test suite package in Xamarin but without any success.

答:
You can download mediation test suite arr file here
and create binding.

Facebook Audience Network is available on nuget, You do not need to create binding.

I have the same problem as you, if I manage to start, I will speak to you

UPDATE:

I used mediation-test-suite version 1.0.0 because I had problems with the higher version. In addition, I had to install libraries such as:

FlexboxLayoutXamarinBindingAndroid

GoogleGson

Constraint.Layout

Xamarin.Bindings.Volley

After doing this, the Mediation Test Suite works properly.


问:
Visual studio code Terminal is not opening giving error code
the terminal process terminated with exit code: 127 I keep gettin this every time I try to open the terminal in Visual studio code</p>

答:
Have you tried checking your path?

I have also seen something like this when tasks.json was all messed up.

Go through your settings at File-> Preferences-> Settings-> Features-> Terminal and see if anything looks wonky.

You will need to post your environment path and/or tasks.json if you don't discover the issue yourself to help you troubleshoot further.


问:
how to get POST data in django 1.3
Hey, I am following this tutorial to learn to make a wiki page with Django. However, it is made in django 0.96 and I use Django 1.3 so there are some things that are different. Some I already fixed myself, however this one I can't seem to make it work.

I made a form that submits data to a view.
 This is the form:

```<code><form method="post" action"/wikicamp/{{page_name}}/save/">{% csrf_token %}
    <textarea name="content" rows="20" cols="60">{{content}}</textarea><br>
    <input type="submit" value="Save Page"/>
</form>
</code>```

and the /wikicamp/{{page_name}}/save/ url redirects to the save_page view:

```<code>from django.http import HttpResponseRedirect
from django.core.context_processors import csrf

def save_page(request, page_name):
    c = {}
    c.update(csrf(request))
    content = c.POST["content"]
    try:
        page = Page.objects.get(pk=page_name)
        page.content = content
    except Page.DoesNotExist:
        page = Page(name=page_name, content=content)
    page.save()
    return HttpResponseRedirect("wikicamp/" + page_name + "/")
</code>```

However the problem is that I get this error:

```<code>Help

Reason given for failure:

    CSRF token missing or incorrect.

In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:

    The view function uses RequestContext for the template, instead of Context.
    In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
    If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.

You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.
</code>```

So I read through some of the documentation, like http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#how-to-use-it. I tried to do that however and it still gave the same error.

So: Anyone an idea how to handle form post data well with Django 1.3?

I think it has something to do with: The view function uses RequestContext for the template, instead of Context. but i don't now what it is.

btw, in my terminal which shows the http request of the localhost it says this: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.

答:
I guess you've missed the symbol '=' in the form declaration.

```<code>action"/wikicamp/{{page_name}}/save/"

action="/wikicamp/{{page_name}}/save/"
</code>```

Fortunately, it might be not a mistake.
So if it is not a solution, try some more easy example:

```<code># settings.py

TEMPLATE_DIRS = (
    # Here comes something like "C:/www/django/templates"
)

MIDDLEWARE_CLASSES = (
    ...
    'django.middleware.csrf.CsrfViewMiddleware',
    ...
)

# urls.py

urlpatterns = patterns('',
    ('^foo', foo),
)

# views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.core.context_processors import csrf

def foo(request):
    d = {}
    d.update(csrf(request))
    if 'output' in request.POST:
        d.update({'output':request.POST['output']})
    return render_to_response('foo.html',d)

# foo.html template
<html>
<h1> Foo </h1>
<form action="/foo" method = "post">
    {% csrf_token %}
    <input type="text" name="output"></input>
    <input type="submit" value="go"></input>
</form>
<p> Output: {{ output }} </p>
</html>
</code>```

Hope this will work

Title: how to get POST data in django 1.3

Body:
Hey, I am following this tutorial to learn to make a wiki page with Django. However, it is made in django 0.96 and I use Django 1.3 so there are some things that are different. Some I already fixed myself, however this one I can't seem to make it work.

I made a form that submits data to a view.
 This is the form:

<form method="post" action"/wikicamp/{{page_name}}/save/">{% csrf_token %}
    <textarea name="content" rows="20" cols="60">{{content}}</textarea>

    <input type="submit" value="Save Page"/>
</form>

and the /wikicamp/{{page_name}}/save/ url redirects to the save_page view:

from django.http import HttpResponseRedirect
from django.core.context_processors import csrf

def save_page(request, page_name):
    c = {}
    c.update(csrf(request))
    content = c.POST["content"]
    try:
        page = Page.objects.get(pk=page_name)
        page.content = content
    except Page.DoesNotExist:
        page = Page(name=page_name, content=content)
    page.save()
    return HttpResponseRedirect("wikicamp/" + page_name + "/")

However the problem is that I get this error:

Help

Reason given for failure:

    CSRF token missing or incorrect.

In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:

    The view function uses RequestContext for the template, instead of Context.
    In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
    If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.

You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.

So I read through some of the documentation, like http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#how-to-use-it. I tried to do that however and it still gave the same error.

So: Anyone an idea how to handle form post data well with Django 1.3?

I think it has something to do with: The view function uses RequestContext for the template, instead of Context. but i don't now what it is.

btw, in my terminal which shows the http request of the localhost it says this: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.

Body:
I guess you've missed the symbol '=' in the form declaration.

action"/wikicamp/{{page_name}}/save/"

action="/wikicamp/{{page_name}}/save/"

Fortunately, it might be not a mistake.
So if it is not a solution, try some more easy example:

# settings.py

TEMPLATE_DIRS = (
    # Here comes something like "C:/www/django/templates"
)

MIDDLEWARE_CLASSES = (
    ...
    'django.middleware.csrf.CsrfViewMiddleware',
    ...
)

# urls.py

urlpatterns = patterns('',
    ('^foo', foo),
)

# views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.core.context_processors import csrf

def foo(request):
    d = {}
    d.update(csrf(request))
    if 'output' in request.POST:
        d.update({'output':request.POST['output']})
    return render_to_response('foo.html',d)

# foo.html template
<html>
<h1> Foo </h1>
<form action="/foo" method = "post">
    {% csrf_token %}
    <input type="text" name="output"></input>
    <input type="submit" value="go"></input>
</form>
<p> Output: {{ output }} </p>
</html>

Hope this will work


问:
ActiveMQ converting `/` to `.` in queue names when using curl
My 5.0.8 ActiveMQ queue is named queue/andburn. Using

```<code>curl -u admin:admin -d 'body="Aardvark"' "http://localhost:8161/api/message/queue/andburn?type=queue"
</code>```

creates a new queue queue.andburn.  When I escape / like \/ I get queue\.andburn.  When I omit type=queue I don't see my message added to my existing queue.  Same when I use / to represent slashes.

Note: all escaping was done after queue in the URI, e.g.

```<code>"http://localhost:8161/api/message/queue\/andburn?type=queue"
</code>```

The ActiveMQ REST page was not helpful in addressing this.

Here is the output of curl --version

```<code>curl 7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8y zlib/1.2.5
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smtp smtps telnet tftp
Features: AsynchDNS GSS-Negotiate IPv6 Largefile NTLM NTLM_WB SSL libz
</code>```

Update: This is also happening when sending requests to ActiveMQ via a Ruby script using the RestClient gem.

答: I came across this issue today and did a minor search. I use ActiveMQ version 5.15.11. The solution that worked for me can be found here. I simply used the alternate producing syntax. Simply, http://127.0.0.1:8161/api/message?type=queue&destination=My.Queue.With/Slash (instead of giving the queue name after ../message.queue/{queue_name})</p>

Body:
My 5.0.8 ActiveMQ queue is named queue/andburn. Using

curl -u admin:admin -d 'body="Aardvark"' "http://localhost:8161/api/message/queue/andburn?type=queue"

creates a new queue queue.andburn.  When I escape / like \/ I get queue\.andburn.  When I omit type=queue I don't see my message added to my existing queue.  Same when I use / to represent slashes.

Note: all escaping was done after queue in the URI, e.g.

"http://localhost:8161/api/message/queue\/andburn?type=queue"

The ActiveMQ REST page was not helpful in addressing this.

Here is the output of curl --version

curl 7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8y zlib/1.2.5
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smtp smtps telnet tftp
Features: AsynchDNS GSS-Negotiate IPv6 Largefile NTLM NTLM_WB SSL libz

Update: This is also happening when sending requests to ActiveMQ via a Ruby script using the RestClient gem.