问:
Header image customizer sections doesn't appear, and custom colors don't remain when I hit publish on my custom WordPress theme
I have read https://developer.wordpress.org/themes/functionality/custom-backgrounds/ and https://www.cssigniter.com/how-to-create-a-custom-color-scheme-for-your-wordpress-theme-using-the-customizer/ and tried to implement both on my WordPress theme. The functionality for my header stopped working when I added custom color support. Custom color defaults appear when I click customize on my theme, but they do not remain when I click publish.

My functions.php file:
https://pastebin.com/4viw4Hdd

The header support:

```<code>    // Add theme support for custom-header.

    $args = array(
        'flex-width'    => true,
        'width'         => 980,
        'flex-height'   => true,
        'height'        => 200,
        'default-image' => get_template_directory_uri() . '/images/mountains2.jpeg',
    );
    add_theme_support( 'custom-header', $args );

    register_nav_menus( array(
        'primary' => __('Primary Menu', 'mytheme')
    ));

    function wpb_custom_new_menu() {
        register_nav_menu('my-custom-menu',__( 'My Custom Menu' ));
    }
    add_action( 'init', 'wpb_custom_new_menu' );
}
</code>```

The support for custom colors:

```<code>function theme_customize_register( $wp_customize ) {
    // Primary color
    $wp_customize->add_setting( 'primary_color', array(
      'default'   => '#e69138',
      'transport' => 'refresh',
    ) );

    $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'primary_color', array(
      'section' => 'colors',
      'label'   => esc_html__( 'Primary Color', 'theme' ),
    ) ) );

        // BG color
    $wp_customize->add_setting( 'secondary_color', array(
      'default'   => '#5b5b5b',
      'transport' => 'refresh',
    ) );

    $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'secondary_color', array(
      'section' => 'colors',
      'label'   => esc_html__( 'Secondary Color', 'theme' ),
    ) ) );

    // Accent color
    $wp_customize->add_setting( 'accent_color', array(
      'default'   => '#B9D801',
      'transport' => 'refresh',
    ) );

    $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'accent_color', array(
      'section' => 'colors',
      'label'   => esc_html__( 'Accent Color', 'theme' ),
    ) ) );
  }

  add_action( 'customize_register', 'theme_customize_register' );

// Modify our styles registration like so:

function theme_enqueue_styles() {
  wp_enqueue_style( 'theme-styles', get_stylesheet_uri() ); // This is where you enqueue your theme's main stylesheet
  $custom_css = theme_get_customizer_css();
  wp_add_inline_style( 'theme-styles', $custom_css );
}

add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );

  function theme_get_customizer_css() {
    ob_start();

    $primary_color = get_theme_mod( 'primary_color', '' );
    if ( ! empty( $primary_color ) ) {
      ?>
      #primary_color {
        background-color: <?php echo $primary_color; ?>;
      }
      <?php
    }

    $secondary_color = get_theme_mod( 'secondary_color', '' );
    if ( ! empty( $secondary_color ) ) {
      ?>
      #secondary_color {
        background-color: <?php echo $secondary_color; ?>;
      }
      <?php
    }

    $accent_color = get_theme_mod( 'accent_color', '' );
    if ( ! empty( $accent_color ) ) {
      ?>
      #accent_color {
        background-color: <?php echo $accent_color; ?>;
      }
      <?php
    }

    $css = ob_get_clean();
    return $css;
  }
</code>```

My stylesheet:
https://pastebin.com/JbK0keSK

My footer:
https://pastebin.com/y7zsgNUE

My header:
https://pastebin.com/FCCz666A

```<code>
    <div style="background-image: url(<?php header_image(); ?>";>
    <div style="background: linear-gradient(to top,  rgba(10,10,10,0.4) 0%,rgba(255,255,58,0) 100%);">

        <br>
        <br>
        <br>
        <br>
        <?php
            $site_title = get_bloginfo( 'site_title' );
        ?>
        <h2 >
            <center>
                <b>
                    <a style="white-space: nowrap; color: white; font-size:6.5vw; text-decoration: none;" href="<?php echo $site_url; ?>"><?php echo $site_title;?></a>
                </b>
            </center>
        </h2>
        <br>
                        <nav>
                            <?php
                                wp_nav_menu(
                                    array(
                                        'theme_location' => 'header-menu',
                                        'menu_class'     => 'primary-menu'
                                        )
                                );
                            ?>
                        </nav>

    </div>
    </div>
</code>```

I tried removing the custom colors with no success getting my header to work again. I tried rebuilding the website from a working backup, and the header stopped working again. I tried googling, reading more WordPress enqueue articles, and looked for similar problems on stack exchange, and still couldn't get it working. I'm learning as I go, so I probably mixed something up with the CSS or functions file.

Body:
I have read https://developer.wordpress.org/themes/functionality/custom-backgrounds/ and https://www.cssigniter.com/how-to-create-a-custom-color-scheme-for-your-wordpress-theme-using-the-customizer/ and tried to implement both on my WordPress theme. The functionality for my header stopped working when I added custom color support. Custom color defaults appear when I click customize on my theme, but they do not remain when I click publish.

My functions.php file:
https://pastebin.com/4viw4Hdd

The header support:

    // Add theme support for custom-header.

    $args = array(
        'flex-width'    => true,
        'width'         => 980,
        'flex-height'   => true,
        'height'        => 200,
        'default-image' => get_template_directory_uri() . '/images/mountains2.jpeg',
    );
    add_theme_support( 'custom-header', $args );

    register_nav_menus( array(
        'primary' => __('Primary Menu', 'mytheme')
    ));

    function wpb_custom_new_menu() {
        register_nav_menu('my-custom-menu',__( 'My Custom Menu' ));
    }
    add_action( 'init', 'wpb_custom_new_menu' );
}

The support for custom colors:

function theme_customize_register( $wp_customize ) {
    // Primary color
    $wp_customize->add_setting( 'primary_color', array(
      'default'   => '#e69138',
      'transport' => 'refresh',
    ) );

    $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'primary_color', array(
      'section' => 'colors',
      'label'   => esc_html__( 'Primary Color', 'theme' ),
    ) ) );

        // BG color
    $wp_customize->add_setting( 'secondary_color', array(
      'default'   => '#5b5b5b',
      'transport' => 'refresh',
    ) );

    $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'secondary_color', array(
      'section' => 'colors',
      'label'   => esc_html__( 'Secondary Color', 'theme' ),
    ) ) );

    // Accent color
    $wp_customize->add_setting( 'accent_color', array(
      'default'   => '#B9D801',
      'transport' => 'refresh',
    ) );

    $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'accent_color', array(
      'section' => 'colors',
      'label'   => esc_html__( 'Accent Color', 'theme' ),
    ) ) );
  }

  add_action( 'customize_register', 'theme_customize_register' );

// Modify our styles registration like so:

function theme_enqueue_styles() {
  wp_enqueue_style( 'theme-styles', get_stylesheet_uri() ); // This is where you enqueue your theme's main stylesheet
  $custom_css = theme_get_customizer_css();
  wp_add_inline_style( 'theme-styles', $custom_css );
}

add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );

  function theme_get_customizer_css() {
    ob_start();

    $primary_color = get_theme_mod( 'primary_color', '' );
    if ( ! empty( $primary_color ) ) {
      ?>
      #primary_color {
        background-color: <?php echo $primary_color; ?>;
      }
      <?php
    }

    $secondary_color = get_theme_mod( 'secondary_color', '' );
    if ( ! empty( $secondary_color ) ) {
      ?>
      #secondary_color {
        background-color: <?php echo $secondary_color; ?>;
      }
      <?php
    }

    $accent_color = get_theme_mod( 'accent_color', '' );
    if ( ! empty( $accent_color ) ) {
      ?>
      #accent_color {
        background-color: <?php echo $accent_color; ?>;
      }
      <?php
    }

    $css = ob_get_clean();
    return $css;
  }

My stylesheet:
https://pastebin.com/JbK0keSK

My footer:
https://pastebin.com/y7zsgNUE

My header:
https://pastebin.com/FCCz666A

    <div style="background-image: url(<?php header_image(); ?>";>

        <?php
            $site_title = get_bloginfo( 'site_title' );
        ?>

                    <a style="white-space: nowrap; color: white; font-size:6.5vw; text-decoration: none;" href="<?php echo $site_url; ?>"><?php echo $site_title;?>

                            <?php
                                wp_nav_menu(
                                    array(
                                        'theme_location' => 'header-menu',
                                        'menu_class'     => 'primary-menu'
                                        )
                                );
                            ?>

I tried removing the custom colors with no success getting my header to work again. I tried rebuilding the website from a working backup, and the header stopped working again. I tried googling, reading more WordPress enqueue articles, and looked for similar problems on stack exchange, and still couldn't get it working. I'm learning as I go, so I probably mixed something up with the CSS or functions file.


来源: stackexchange

问:
Can a SqlUserDefinedAggregate be a derived class?
I'm attempting to write some bitwise aggregate functions for a project I'm working on. What I have below is a working implementation for an aggregate where the operator is bitwise-or.

using Microsoft.SqlServer.Server;
using System;
using System.Collections;
using System.Data.SqlTypes;
using System.IO;

namespace BitwiseAggregates
{
    [Serializable]
    [SqlUserDefinedAggregate(
        Format.UserDefined,
        MaxByteSize = 8000,
        IsInvariantToNulls = false,
        IsInvariantToDuplicates = true,
        IsInvariantToOrder = true
    )]
    public class BitwiseOrAggregate : IBinarySerialize
    {
        private BitArray Accumulator { get; set; }
        private bool IsFirstValue { get; set; }
        private bool IsNull { get; set; }

        public void Init()
        {
            IsFirstValue = true;
            IsNull = false;
        }
        public void Accumulate(SqlBinary Values)
        {
            if (Values.IsNull == false && this.IsNull == false)
            {
                if (this.IsFirstValue == true)
                {
                    this.Accumulator = FromSqlBinary(Values);
                    this.IsFirstValue = false;
                }
                else
                {
                    BitArray tempBA = FromSqlBinary(Values);
                    this.Accumulator = this.Accumulator.Or(tempBA);
                }
            }
            else
            {
                IsNull = true;
            }
        }
        public void Merge(BitwiseOrAggregate that)
        {
            if (this.Accumulator.Length != that.Accumulator.Length)
            {
                throw new InvalidOperationException("All values must be the same length");
            }

            if (that.IsNull)
            {
                this.IsNull = true;
            }
            else
            {
                this.Accumulator = this.Accumulator.Or(that.Accumulator);
            }
        }
        public SqlBinary Terminate()
        {
            if (IsNull == true)
            {
                return SqlBinary.Null;
            }
            else
            {
                return new SqlBinary(FromBitArray(Accumulator));
            }
        }

        // Methods for IBinarySerialize
        public void Read(BinaryReader r)
        {
            IsFirstValue = r.ReadBoolean();
            IsNull = r.ReadBoolean();

            if (IsNull == false)
            {
                int bytesToRead = r.ReadInt32();

                byte[] ba = r.ReadBytes(bytesToRead);

                Accumulator = new BitArray(ba);
            }
        }
        public void Write(BinaryWriter w)
        {
            w.Write(IsFirstValue);
            w.Write(IsNull);

            if (IsNull == false)
            {
                byte[] ba = FromBitArray(Accumulator);

                int bytesToWrite = ba.Length;
                w.Write(bytesToWrite);

                w.Write(ba);
            }
        }

        // Helper methods
        protected BitArray FromSqlBinary(SqlBinary bytes)
        {
            return new BitArray((byte[])bytes);
        }
        protected byte[] FromBitArray(BitArray ba)
        {
            int returnLength = ba.Length / 8;
            byte[] retVal = new byte[returnLength];

            ba.CopyTo(retVal, 0);
            return retVal;
        }
    }
}
```
<p>In looking to implement the next aggregate (using bitwise-and), I evaluated all of the methods and all but <code>Accumulate</code> and <code>Merge</code> will be the same. In an attempt to not repeat myself, I changed my code to this:</p>
<pre class="lang-cs prettyprint-override"><code>using Microsoft.SqlServer.Server;
using System;
using System.Collections;
using System.Data.SqlTypes;
using System.IO;

namespace BitwiseAggregates
{
    [Serializable]
    [SqlUserDefinedAggregate(
        Format.UserDefined,
        MaxByteSize = 8000,
        IsInvariantToNulls = false,
        IsInvariantToDuplicates = true,
        IsInvariantToOrder = true
    )]
    public class BitwiseOrAggregate : BitwiseAggregate
    {
        public void Accumulate(SqlBinary Values)
        {
            if (Values.IsNull == false && this.IsNull == false)
            {
                if (this.IsFirstValue == true)
                {
                    this.Accumulator = FromSqlBinary(Values);
                    this.IsFirstValue = false;
                }
                else
                {
                    BitArray tempBA = FromSqlBinary(Values);
                    this.Accumulator = this.Accumulator.Or(tempBA);
                }
            }
            else
            {
                IsNull = true;
            }
        }
        public void Merge(BitwiseOrAggregate that)
        {
            if (this.Accumulator.Length != that.Accumulator.Length)
            {
                throw new InvalidOperationException("All values must be the same length");
            }

            if (that.IsNull)
            {
                this.IsNull = true;
            }
            else
            {
                this.Accumulator = this.Accumulator.Or(that.Accumulator);
            }
        }
    }

    public class BitwiseAggregate : IBinarySerialize
    {
        protected BitArray Accumulator { get; set; }
        protected bool IsFirstValue { get; set; }
        protected bool IsNull { get; set; }
        public void Init()
        {
            IsFirstValue = true;
            IsNull = false;
        }

        public SqlBinary Terminate()
        {
            if (IsNull == true)
            {
                return SqlBinary.Null;
            }
            else
            {
                return new SqlBinary(FromBitArray(Accumulator));
            }
        }

        // Methods for IBinarySerialize
        public void Read(BinaryReader r)
        {
            IsFirstValue = r.ReadBoolean();
            IsNull = r.ReadBoolean();

            if (IsNull == false)
            {
                int bytesToRead = r.ReadInt32();

                byte[] ba = r.ReadBytes(bytesToRead);

                Accumulator = new BitArray(ba);
            }
        }
        public void Write(BinaryWriter w)
        {
            w.Write(IsFirstValue);
            w.Write(IsNull);

            if (IsNull == false)
            {
                byte[] ba = FromBitArray(Accumulator);

                int bytesToWrite = ba.Length;
                w.Write(bytesToWrite);

                w.Write(ba);
            }
        }

        // Helper methods
        protected BitArray FromSqlBinary(SqlBinary bytes)
        {
            return new BitArray((byte[])bytes);
        }
        protected byte[] FromBitArray(BitArray ba)
        {
            int returnLength = ba.Length / 8;
            byte[] retVal = new byte[returnLength];

            ba.CopyTo(retVal, 0);
            return retVal;
        }
    }
}
</code>```

But it doesn't work. Through a little experimentation, it seems that neither Init() nor Terminate() are making it into the SqlUserDefinedAggregate. What am I missing?

ContentLicense: CC BY-SA 4.0

Body:
I'm attempting to write some bitwise aggregate functions for a project I'm working on. What I have below is a working implementation for an aggregate where the operator is bitwise-or.

using Microsoft.SqlServer.Server;
using System;
using System.Collections;
using System.Data.SqlTypes;
using System.IO;

namespace BitwiseAggregates
{
    [Serializable]
    [SqlUserDefinedAggregate(
        Format.UserDefined,
        MaxByteSize = 8000,
        IsInvariantToNulls = false,
        IsInvariantToDuplicates = true,
        IsInvariantToOrder = true
    )]
    public class BitwiseOrAggregate : IBinarySerialize
    {
        private BitArray Accumulator { get; set; }
        private bool IsFirstValue { get; set; }
        private bool IsNull { get; set; }

        public void Init()
        {
            IsFirstValue = true;
            IsNull = false;
        }
        public void Accumulate(SqlBinary Values)
        {
            if (Values.IsNull == false && this.IsNull == false)
            {
                if (this.IsFirstValue == true)
                {
                    this.Accumulator = FromSqlBinary(Values);
                    this.IsFirstValue = false;
                }
                else
                {
                    BitArray tempBA = FromSqlBinary(Values);
                    this.Accumulator = this.Accumulator.Or(tempBA);
                }
            }
            else
            {
                IsNull = true;
            }
        }
        public void Merge(BitwiseOrAggregate that)
        {
            if (this.Accumulator.Length != that.Accumulator.Length)
            {
                throw new InvalidOperationException("All values must be the same length");
            }

            if (that.IsNull)
            {
                this.IsNull = true;
            }
            else
            {
                this.Accumulator = this.Accumulator.Or(that.Accumulator);
            }
        }
        public SqlBinary Terminate()
        {
            if (IsNull == true)
            {
                return SqlBinary.Null;
            }
            else
            {
                return new SqlBinary(FromBitArray(Accumulator));
            }
        }

        // Methods for IBinarySerialize
        public void Read(BinaryReader r)
        {
            IsFirstValue = r.ReadBoolean();
            IsNull = r.ReadBoolean();

            if (IsNull == false)
            {
                int bytesToRead = r.ReadInt32();

                byte[] ba = r.ReadBytes(bytesToRead);

                Accumulator = new BitArray(ba);
            }
        }
        public void Write(BinaryWriter w)
        {
            w.Write(IsFirstValue);
            w.Write(IsNull);

            if (IsNull == false)
            {
                byte[] ba = FromBitArray(Accumulator);

                int bytesToWrite = ba.Length;
                w.Write(bytesToWrite);

                w.Write(ba);
            }
        }

        // Helper methods
        protected BitArray FromSqlBinary(SqlBinary bytes)
        {
            return new BitArray((byte[])bytes);
        }
        protected byte[] FromBitArray(BitArray ba)
        {
            int returnLength = ba.Length / 8;
            byte[] retVal = new byte[returnLength];

            ba.CopyTo(retVal, 0);
            return retVal;
        }
    }
}

In looking to implement the next aggregate (using bitwise-and), I evaluated all of the methods and all but Accumulate and Merge will be the same. In an attempt to not repeat myself, I changed my code to this:

using Microsoft.SqlServer.Server;
using System;
using System.Collections;
using System.Data.SqlTypes;
using System.IO;

namespace BitwiseAggregates
{
    [Serializable]
    [SqlUserDefinedAggregate(
        Format.UserDefined,
        MaxByteSize = 8000,
        IsInvariantToNulls = false,
        IsInvariantToDuplicates = true,
        IsInvariantToOrder = true
    )]
    public class BitwiseOrAggregate : BitwiseAggregate
    {
        public void Accumulate(SqlBinary Values)
        {
            if (Values.IsNull == false && this.IsNull == false)
            {
                if (this.IsFirstValue == true)
                {
                    this.Accumulator = FromSqlBinary(Values);
                    this.IsFirstValue = false;
                }
                else
                {
                    BitArray tempBA = FromSqlBinary(Values);
                    this.Accumulator = this.Accumulator.Or(tempBA);
                }
            }
            else
            {
                IsNull = true;
            }
        }
        public void Merge(BitwiseOrAggregate that)
        {
            if (this.Accumulator.Length != that.Accumulator.Length)
            {
                throw new InvalidOperationException("All values must be the same length");
            }

            if (that.IsNull)
            {
                this.IsNull = true;
            }
            else
            {
                this.Accumulator = this.Accumulator.Or(that.Accumulator);
            }
        }
    }

    public class BitwiseAggregate : IBinarySerialize
    {
        protected BitArray Accumulator { get; set; }
        protected bool IsFirstValue { get; set; }
        protected bool IsNull { get; set; }
        public void Init()
        {
            IsFirstValue = true;
            IsNull = false;
        }

        public SqlBinary Terminate()
        {
            if (IsNull == true)
            {
                return SqlBinary.Null;
            }
            else
            {
                return new SqlBinary(FromBitArray(Accumulator));
            }
        }

        // Methods for IBinarySerialize
        public void Read(BinaryReader r)
        {
            IsFirstValue = r.ReadBoolean();
            IsNull = r.ReadBoolean();

            if (IsNull == false)
            {
                int bytesToRead = r.ReadInt32();

                byte[] ba = r.ReadBytes(bytesToRead);

                Accumulator = new BitArray(ba);
            }
        }
        public void Write(BinaryWriter w)
        {
            w.Write(IsFirstValue);
            w.Write(IsNull);

            if (IsNull == false)
            {
                byte[] ba = FromBitArray(Accumulator);

                int bytesToWrite = ba.Length;
                w.Write(bytesToWrite);

                w.Write(ba);
            }
        }

        // Helper methods
        protected BitArray FromSqlBinary(SqlBinary bytes)
        {
            return new BitArray((byte[])bytes);
        }
        protected byte[] FromBitArray(BitArray ba)
        {
            int returnLength = ba.Length / 8;
            byte[] retVal = new byte[returnLength];

            ba.CopyTo(retVal, 0);
            return retVal;
        }
    }
}

But it doesn't work. Through a little experimentation, it seems that neither Init() nor Terminate() are making it into the SqlUserDefinedAggregate. What am I missing?


问:
How to do free hosting of a website which using NewsAPI.org Api (restricted for hosting)
I made my first website have great frontend and I'm using NewsAPI.org api for fetch news data.
But it's restricted for hosting and i want to host my site to show my project to others.

When i host the site and go for that particular domain page works correctly with all information for 2 sec after that blank white pages shows up


问:
How to condense similar iterations in groovy?
I have the following code

```<code>println "statement 1 {$list_one.size}"
list_one.each { println "item: one" + it }

println "statement 2 {$list_two.size}"
list_two.each { println "item: two" + it }

println "statement 3 {$list_three.size}"
list_three.each { println "item: three. and other info" + it }

println "statement 4 {$list_four.size}"
list_four.each { println "item: four" + it }
</code>```

I would have more of these, and having them print like this one by one is not ideal. Their behavior is the same. It would be best if I could just make one iterator and make a generic function to handle this, but as you can see sometimes it has to print a different statement. What would be the best way to condense this?

I've tried the following approach.

```<code>def hashmap = [list_one: ["statement 1", "item: one"], list_two: ["statement 2", "item: two"], list_three: ["statement 3", "item: three. and other info"]]

hashmap.each { list, statement
    println statement[0] + list.size
    list.each {
        println statement[1] + it
    }
}
</code>```

But now I'm just using a hashmap with list as key and value, which is not so much an elegant way to condense this. What would be the best way to approach this?

Body:
I have the following code

println "statement 1 {$list_one.size}"
list_one.each { println "item: one" + it }

println "statement 2 {$list_two.size}"
list_two.each { println "item: two" + it }

println "statement 3 {$list_three.size}"
list_three.each { println "item: three. and other info" + it }

println "statement 4 {$list_four.size}"
list_four.each { println "item: four" + it }

I would have more of these, and having them print like this one by one is not ideal. Their behavior is the same. It would be best if I could just make one iterator and make a generic function to handle this, but as you can see sometimes it has to print a different statement. What would be the best way to condense this?

I've tried the following approach.

def hashmap = [list_one: ["statement 1", "item: one"], list_two: ["statement 2", "item: two"], list_three: ["statement 3", "item: three. and other info"]]

hashmap.each { list, statement
    println statement[0] + list.size
    list.each {
        println statement[1] + it
    }
}

But now I'm just using a hashmap with list as key and value, which is not so much an elegant way to condense this. What would be the best way to approach this?


问:
Clean up duplicate large @ApiResponses for every mapping in spring boot controller?
I have the same @ApiResponses before every mapping in my spring boot controller.

```<code>@ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Get file by path", content = {
            @Content(mediaType = "application/json", schema = @Schema(implementation = FormDataResponseDTO.GetFileResponseDTO.class)) }),
@ApiResponse(responseCode = "400", description = "Missing required parameter", content = {
            @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDTO.class)) }),
@ApiResponse(responseCode = "401", description = "You are not authorized", content = {
            @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDTO.class)) }),
@ApiResponse(responseCode = "403", description = "Forbidden", content = {
            @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDTO.class)) }),
@ApiResponse(responseCode = "404", description = "Not Found", content = {
            @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDTO.class)) }),
@ApiResponse(responseCode = "406", description = "Not acceptable", content = {
            @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDTO.class)) }),
@ApiResponse(responseCode = "500", description = "Internal Server Error", content = {
            @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDTO.class)) }) })
</code>```

Is there any way I can store this in an object/variable and reuse it rather than having to mention this above every mapping ?

Body:
I have the same @ApiResponses before every mapping in my spring boot controller.

@ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Get file by path", content = {
            @Content(mediaType = "application/json", schema = @Schema(implementation = FormDataResponseDTO.GetFileResponseDTO.class)) }),
@ApiResponse(responseCode = "400", description = "Missing required parameter", content = {
            @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDTO.class)) }),
@ApiResponse(responseCode = "401", description = "You are not authorized", content = {
            @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDTO.class)) }),
@ApiResponse(responseCode = "403", description = "Forbidden", content = {
            @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDTO.class)) }),
@ApiResponse(responseCode = "404", description = "Not Found", content = {
            @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDTO.class)) }),
@ApiResponse(responseCode = "406", description = "Not acceptable", content = {
            @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDTO.class)) }),
@ApiResponse(responseCode = "500", description = "Internal Server Error", content = {
            @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDTO.class)) }) })

Is there any way I can store this in an object/variable and reuse it rather than having to mention this above every mapping ?


问:
JavaScript heap out of memory
When I "npm run build" on a vps server with Ubuntu 20.04 64bit
It Show "FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory" It is my memory of vps server not enough?

Screenshot

How do I solve this?

Title: JavaScript heap out of memory


问:
How to access the muliple database in a same time with JDBC not in JPA
I just created a sample project in Spring Boot using CRUD operation & JDBC. Now, I want to get the data from two different databases at the same time

I need to get two table values for the use of the conditional statement. but there is one problem two tables are in two different databases in MySQL. How do I access the different databases and use them in the same API call?


问:
How to limit Slurm job CPU usage for users?
So, we have slurm accounting enabled, and I tried to limit CPUs for user via the command,

sacctmgr modify user where name=username set GrpTRES=cpu=2

But when I try to submit a job, that requests more CPUs, it still works a gives me an output, pasting the sample job here, incase that's not accurately using the resources,

```<code>#!/bin/bash
#SBATCH --ntasks=2
#SBATCH --cpus-per-task=3
sleep 5
echo "Running on $(hostname)"
</code>```

The job details, also, show it utilizes more,

```<code>UserId=username(10172) GroupId=username(15173) MCS_label=N/A
   Priority=4294901746 Nice=0 Account=dev QOS=normal
   JobState=CONFIGURING Reason=None Dependency=(null)
   Requeue=1 Restarts=0 BatchFlag=1 Reboot=0 ExitCode=0:0
   RunTime=00:02:30 TimeLimit=UNLIMITED TimeMin=N/A
   SubmitTime=2022-12-30T00:09:03 EligibleTime=2022-12-30T00:09:03
   AccrueTime=2022-12-30T00:09:03
   StartTime=2022-12-30T00:09:03 EndTime=Unknown Deadline=N/A
   SuspendTime=None SecsPreSuspend=0 LastSchedEval=2022-12-30T00:09:03 Scheduler=Main
   Partition=default-queue AllocNode:Sid=ip-10-125-240-24:19524
   ReqNodeList=(null) ExcNodeList=(null)
   NodeList=default-queue-dy-r6i2xlarge-1
   BatchHost=default-queue-dy-r6i2xlarge-1
   NumNodes=1 NumCPUs=6 NumTasks=2 CPUs/Task=3 ReqB:S:C:T=0:0:*:*
   TRES=cpu=6,node=1,billing=6
   Socks/Node=* NtasksPerN:B:S:C=0:0:*:* CoreSpec=*
   MinCPUsNode=3 MinMemoryNode=0 MinTmpDiskNode=0
   Features=(null) DelayBoot=00:00:00
   OverSubscribe=OK Contiguous=0 Licenses=(null) Network=(null)
   Command=/shared-storage/home/username/tres-test.sh
   WorkDir=/shared-storage/home/username
   StdErr=/shared-storage/home/username/slurm-13.out
   StdIn=/dev/null
   StdOut=/shared-storage/home/username/slurm-13.out
   Power=
</code>```

So, what am I missing?

Or is there a better way to restrict CPUs for all users in the system?

This user is created in slurm, but just curious, if I want to have the same restriction on all the users, should all of them be created in slurm, this way?

sacctmgr create user name=username account=account_name

Body:
So, we have slurm accounting enabled, and I tried to limit CPUs for user via the command,

sacctmgr modify user where name=username set GrpTRES=cpu=2

But when I try to submit a job, that requests more CPUs, it still works a gives me an output, pasting the sample job here, incase that's not accurately using the resources,

#!/bin/bash
#SBATCH --ntasks=2
#SBATCH --cpus-per-task=3
sleep 5
echo "Running on $(hostname)"

The job details, also, show it utilizes more,

UserId=username(10172) GroupId=username(15173) MCS_label=N/A
   Priority=4294901746 Nice=0 Account=dev QOS=normal
   JobState=CONFIGURING Reason=None Dependency=(null)
   Requeue=1 Restarts=0 BatchFlag=1 Reboot=0 ExitCode=0:0
   RunTime=00:02:30 TimeLimit=UNLIMITED TimeMin=N/A
   SubmitTime=2022-12-30T00:09:03 EligibleTime=2022-12-30T00:09:03
   AccrueTime=2022-12-30T00:09:03
   StartTime=2022-12-30T00:09:03 EndTime=Unknown Deadline=N/A
   SuspendTime=None SecsPreSuspend=0 LastSchedEval=2022-12-30T00:09:03 Scheduler=Main
   Partition=default-queue AllocNode:Sid=ip-10-125-240-24:19524
   ReqNodeList=(null) ExcNodeList=(null)
   NodeList=default-queue-dy-r6i2xlarge-1
   BatchHost=default-queue-dy-r6i2xlarge-1
   NumNodes=1 NumCPUs=6 NumTasks=2 CPUs/Task=3 ReqB:S:C:T=0:0:*:*
   TRES=cpu=6,node=1,billing=6
   Socks/Node=* NtasksPerN:B:S:C=0:0:*:* CoreSpec=*
   MinCPUsNode=3 MinMemoryNode=0 MinTmpDiskNode=0
   Features=(null) DelayBoot=00:00:00
   OverSubscribe=OK Contiguous=0 Licenses=(null) Network=(null)
   Command=/shared-storage/home/username/tres-test.sh
   WorkDir=/shared-storage/home/username
   StdErr=/shared-storage/home/username/slurm-13.out
   StdIn=/dev/null
   StdOut=/shared-storage/home/username/slurm-13.out
   Power=

So, what am I missing?

Or is there a better way to restrict CPUs for all users in the system?

This user is created in slurm, but just curious, if I want to have the same restriction on all the users, should all of them be created in slurm, this way?

sacctmgr create user name=username account=account_name


问:
How to use fetcher with @pancakeswap-libs/sdk in node.js
I am developing pancakeswap trading script but faced getReserves() error.
So I am using @pancakeswap-libs/sdk npm package.
when I use Fetcher.fetchPairData(weth, token, provider), occur this error.
So I checked on pancakeswap interface but exist liquidity.

```<code>    const weth = await Fetcher.fetchTokenData(chainId, wbnbAddr, provider)
    console.log(weth)
    const token = await Fetcher.fetchTokenData(chainId, tokenAddr, provider);
    console.log(token)
    const pair = await Fetcher.fetchPairData(weth, token, provider);
</code>```

Exception in fetchPairData() : call revert exception in method getReserves()

Body:
I am developing pancakeswap trading script but faced getReserves() error.
So I am using @pancakeswap-libs/sdk npm package.
when I use Fetcher.fetchPairData(weth, token, provider), occur this error.
So I checked on pancakeswap interface but exist liquidity.

    const weth = await Fetcher.fetchTokenData(chainId, wbnbAddr, provider)
    console.log(weth)
    const token = await Fetcher.fetchTokenData(chainId, tokenAddr, provider);
    console.log(token)
    const pair = await Fetcher.fetchPairData(weth, token, provider);

Exception in fetchPairData() : call revert exception in method getReserves()


问:
Is there any lead to read credit card number and expiry date through nfc using ionic?
I am trying to build an application in ionic where Card details can be entered using nfc.

I tried using ionic-nfc. I did got hexadecimal value where as I was expecting Card details.


问:
How to make Laravel (Sail) handle requests asynchronously
I have been having this issue on multiple devices, with both Sail and artisan serve:

I have a basic controller like this:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    function test($id) {
        if ($id == 1) {
            sleep(45);
        }

        return 'Hello World';
    }
}
</code>```

with this in my web.php route file:

```<code>Route::controller(Controller::class)->group(function () {
    Route::get('/test/{id}', 'test');
});
</code>```

Then, in Chrome I will go to localhost/test/1 and immediately go to localhost/test/2 in Firefox. In chrome, the tab will sit and wait for 45 seconds before loading as expected. However, Firefox will also wait until the Chrome script finishes before it loads. If you visit localhost/test/2 without visiting the other first, it loads instantly as expected.

What is going on? Why is one script blocking all others, and how do I fix it?

Body:
I have been having this issue on multiple devices, with both Sail and artisan serve:

I have a basic controller like this:

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    function test($id) {
        if ($id == 1) {
            sleep(45);
        }

        return 'Hello World';
    }
}

with this in my web.php route file:

Route::controller(Controller::class)->group(function () {
    Route::get('/test/{id}', 'test');
});

Then, in Chrome I will go to localhost/test/1 and immediately go to localhost/test/2 in Firefox. In chrome, the tab will sit and wait for 45 seconds before loading as expected. However, Firefox will also wait until the Chrome script finishes before it loads. If you visit localhost/test/2 without visiting the other first, it loads instantly as expected.

What is going on? Why is one script blocking all others, and how do I fix it?


问:
Expected type 'Canvas', got 'int' instead
```<code>from tkinter import *

window = Tk()
window.title('Pomodoro timer')
window.config(padx=100, pady=50)
canvas = Canvas(width=200, height=224)
tomato_img = PhotoImage(file="C:/vscode/tomato.png")
canvas.create_image(102, 112, image=tomato_img)
Canvas.create_text(102, 112, text='00:00')
canvas.pack()

window.mainloop()
</code>```

This is the code that I'm working on

when I'm trying to add two integers for x and y co-ordinates to the Canvas.create_text function, it gives me this error

```<code>Traceback (most recent call last):
  File "C:\pycharm and thonny\pythonProject1\main.py", line 26, in <module>
    Canvas.create_text(102, 112, text='00:00')
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2810, in create_text
    return self._create('text', args, kw)
AttributeError: 'int' object has no attribute '_create'
</code>```

Body:
from tkinter import *

window = Tk()
window.title('Pomodoro timer')
window.config(padx=100, pady=50)
canvas = Canvas(width=200, height=224)
tomato_img = PhotoImage(file="C:/vscode/tomato.png")
canvas.create_image(102, 112, image=tomato_img)
Canvas.create_text(102, 112, text='00:00')
canvas.pack()

window.mainloop()

This is the code that I'm working on

when I'm trying to add two integers for x and y co-ordinates to the Canvas.create_text function, it gives me this error

Traceback (most recent call last):
  File "C:\pycharm and thonny\pythonProject1\main.py", line 26, in <module>
    Canvas.create_text(102, 112, text='00:00')
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2810, in create_text
    return self._create('text', args, kw)
AttributeError: 'int' object has no attribute '_create'


问:
Can't able to load the api monkeydev in java script
I am trying to make a chat bot using java script by using the django framework just to ;load the content, but i am getting the console error :

```<code>Access to XMLHttpRequest at 'https://api.monkedev.com/fun/chat?msg=hi' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

GET https://api.monkedev.com/fun/chat?msg=hi net::ERR_FAILED 200

Uncaught (in promise) D {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
</code>```

here is my html:

ChatBot

AI ChatBot

         Send

here is the cdn for axios:

https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.2/axios.min.js

here is my javascript code:

```<code>function init() {
    let res_elm = document.createElement("div");
    res_elm.innerHTML="Hello Myself AI, How can I help you?" ;
    res_elm.setAttribute("class","left");

    document.getElementById('msg').appendChild(res_elm);
}

document.getElementById('reply').addEventListener("click", async (e) => {
    e.preventDefault();

    var req = document.getElementById('msg_send').value ;

    if (req == undefined || req== "") {

    }
    else{

        var res = "";
        await axios.get(`https://api.monkedev.com/fun/chat?msg=${req}`).then(data => {
            res = JSON.stringify(data.data.response)
        })

        let data_req = document.createElement('div');
        let data_res = document.createElement('div');

        let container1 = document.createElement('div');
        let container2 = document.createElement('div');

        container1.setAttribute("class","msgCon1");
        container2.setAttribute("class","msgCon2");

        data_req.innerHTML = req ;
        data_res.innerHTML = res ;

        data_req.setAttribute("class","right");
        data_res.setAttribute("class","left");

        let message = document.getElementById('msg');

        message.appendChild(container1);
        message.appendChild(container2);

        container1.appendChild(data_req);
        container2.appendChild(data_res);

        document.getElementById('msg_send').value = "";

    function scroll() {
        var scrollMsg = document.getElementById('msg')
        scrollMsg.scrollTop = scrollMsg.scrollHeight ;
    }
    scroll();

    }
});
</code>```

Body:
I am trying to make a chat bot using java script by using the django framework just to ;load the content, but i am getting the console error :

Access to XMLHttpRequest at 'https://api.monkedev.com/fun/chat?msg=hi' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

GET https://api.monkedev.com/fun/chat?msg=hi net::ERR_FAILED 200

Uncaught (in promise) D {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}

here is my html:

ChatBot

AI ChatBot

         Send

here is the cdn for axios:

https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.2/axios.min.js

here is my javascript code:

function init() {
    let res_elm = document.createElement("div");
    res_elm.innerHTML="Hello Myself AI, How can I help you?" ;
    res_elm.setAttribute("class","left");

    document.getElementById('msg').appendChild(res_elm);
}

document.getElementById('reply').addEventListener("click", async (e) => {
    e.preventDefault();

    var req = document.getElementById('msg_send').value ;

    if (req == undefined || req== "") {

    }
    else{

        var res = "";
        await axios.get(`https://api.monkedev.com/fun/chat?msg=${req}`).then(data => {
            res = JSON.stringify(data.data.response)
        })

        let data_req = document.createElement('div');
        let data_res = document.createElement('div');

        let container1 = document.createElement('div');
        let container2 = document.createElement('div');

        container1.setAttribute("class","msgCon1");
        container2.setAttribute("class","msgCon2");

        data_req.innerHTML = req ;
        data_res.innerHTML = res ;

        data_req.setAttribute("class","right");
        data_res.setAttribute("class","left");

        let message = document.getElementById('msg');

        message.appendChild(container1);
        message.appendChild(container2);

        container1.appendChild(data_req);
        container2.appendChild(data_res);

        document.getElementById('msg_send').value = "";

    function scroll() {
        var scrollMsg = document.getElementById('msg')
        scrollMsg.scrollTop = scrollMsg.scrollHeight ;
    }
    scroll();

    }
});


问:
java.io.IOException: Could not connect to BlobServer at address localhost/127.0.0.1:46385
flink version: 1.15.3 and jdk versioin: 1.8

conf/flink-conf.yaml file here:

```<code>jobmanager.rpc.address: test1
jobmanager.rpc.port: 6123
jobmanager.bind-host: test1
taskmanager.bind-host: test1
taskmanager.host: test1
taskmanager.numberOfTaskSlots: 2
parallelism.default: 2
</code>```

start a local cluster:

```<code>./bin/start-cluster.sh
</code>```

Starting the SQL Client CLI by calling:

```<code>./bin/sql-client.sh embedded
</code>```

then enter the simple query below and press Enter to execute it.

```<code>SET 'sql-client.execution.result-mode' = 'tableau';
SET 'execution.runtime-mode' = 'batch';

SELECT
  name,
  COUNT(*) AS cnt
FROM
  (VALUES ('Bob'), ('Alice'), ('Greg'), ('Bob')) AS NameTable(name)
GROUP BY name;
</code>```

I got error:

```<code>[ERROR] Could not execute SQL statement. Reason:
org.apache.flink.runtime.rest.util.RestClientException: [org.apache.flink.runtime.rest.handler.RestHandlerException: Could not upload job files.
    at org.apache.flink.runtime.rest.handler.job.JobSubmitHandler.lambda$uploadJobGraphFiles$4(JobSubmitHandler.java:201)
    at java.util.concurrent.CompletableFuture.biApply(CompletableFuture.java:1105)
    at java.util.concurrent.CompletableFuture$BiApply.tryFire(CompletableFuture.java:1070)
    at java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:474)
    at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1595)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.flink.util.FlinkException: Could not upload job files.
    at org.apache.flink.runtime.client.ClientUtils.uploadJobGraphFiles(ClientUtils.java:86)
    at org.apache.flink.runtime.rest.handler.job.JobSubmitHandler.lambda$uploadJobGraphFiles$4(JobSubmitHandler.java:195)
    ... 11 more
Caused by: java.io.IOException: Could not connect to BlobServer at address localhost/127.0.0.1:35138
    at org.apache.flink.runtime.blob.BlobClient.<init>(BlobClient.java:103)
    at org.apache.flink.runtime.rest.handler.job.JobSubmitHandler.lambda$null$3(JobSubmitHandler.java:199)
    at org.apache.flink.runtime.client.ClientUtils.uploadJobGraphFiles(ClientUtils.java:82)
    ... 12 more
Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:606)
    at org.apache.flink.runtime.blob.BlobClient.<init>(BlobClient.java:97)
    ... 14 more
]
</code>```

why ?

Body:
flink version: 1.15.3 and jdk versioin: 1.8

conf/flink-conf.yaml file here:

jobmanager.rpc.address: test1
jobmanager.rpc.port: 6123
jobmanager.bind-host: test1
taskmanager.bind-host: test1
taskmanager.host: test1
taskmanager.numberOfTaskSlots: 2
parallelism.default: 2

start a local cluster:

./bin/start-cluster.sh

Starting the SQL Client CLI by calling:

./bin/sql-client.sh embedded

then enter the simple query below and press Enter to execute it.

SET 'sql-client.execution.result-mode' = 'tableau';
SET 'execution.runtime-mode' = 'batch';

SELECT
  name,
  COUNT(*) AS cnt
FROM
  (VALUES ('Bob'), ('Alice'), ('Greg'), ('Bob')) AS NameTable(name)
GROUP BY name;

I got error:

[ERROR] Could not execute SQL statement. Reason:
org.apache.flink.runtime.rest.util.RestClientException: [org.apache.flink.runtime.rest.handler.RestHandlerException: Could not upload job files.
    at org.apache.flink.runtime.rest.handler.job.JobSubmitHandler.lambda$uploadJobGraphFiles$4(JobSubmitHandler.java:201)
    at java.util.concurrent.CompletableFuture.biApply(CompletableFuture.java:1105)
    at java.util.concurrent.CompletableFuture$BiApply.tryFire(CompletableFuture.java:1070)
    at java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:474)
    at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1595)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.flink.util.FlinkException: Could not upload job files.
    at org.apache.flink.runtime.client.ClientUtils.uploadJobGraphFiles(ClientUtils.java:86)
    at org.apache.flink.runtime.rest.handler.job.JobSubmitHandler.lambda$uploadJobGraphFiles$4(JobSubmitHandler.java:195)
    ... 11 more
Caused by: java.io.IOException: Could not connect to BlobServer at address localhost/127.0.0.1:35138
    at org.apache.flink.runtime.blob.BlobClient.<init>(BlobClient.java:103)
    at org.apache.flink.runtime.rest.handler.job.JobSubmitHandler.lambda$null$3(JobSubmitHandler.java:199)
    at org.apache.flink.runtime.client.ClientUtils.uploadJobGraphFiles(ClientUtils.java:82)
    ... 12 more
Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:606)
    at org.apache.flink.runtime.blob.BlobClient.<init>(BlobClient.java:97)
    ... 14 more
]

why ?


问:
bq show command giving `BigQuery error in show operation: Not found:`
As per the Google Cloud BQ Documentation, bq show --job=true myproject:US.bquijob_123x456_123y123z123c command should return the status of a BQ Job. But in my case I am getting the following error :-

```<code>BigQuery error in show operation: Not found: Job my-project:US.bqjob_r4bc4365eb9z97aa8_000001855ca75006_1
</code>```

What could be the reason behind this error ? Also, I checked that I do have all the necessary permissions namely :-

roles/bigquery.admin
roles/bigquery.user
roles/bigquery.jobUser

Thanks!

Body:
As per the Google Cloud BQ Documentation, bq show --job=true myproject:US.bquijob_123x456_123y123z123c command should return the status of a BQ Job. But in my case I am getting the following error :-

BigQuery error in show operation: Not found: Job my-project:US.bqjob_r4bc4365eb9z97aa8_000001855ca75006_1

What could be the reason behind this error ? Also, I checked that I do have all the necessary permissions namely :-

roles/bigquery.admin
roles/bigquery.user
roles/bigquery.jobUser

Thanks!


问:
Functions aren't printing messages but program completely runs?
Hello I am currently working on updating a project from when I first was learning to code. With that being said I am starting to implement classes withing the program when I have run into a bit of a Issue not like a physical Python Error but my Class Functions just don't seem to perform properly.

WebSite.py

```<code>class WebSite:
  def __init__(self, url, id):
      self.__url = url
      self.__id = id

  def getURL(self):
      return self.__url

  def getId(self):
      return self.__id
</code>```

GunSite.py

```<code>> class GunSite(WebSite):

      def __init__(self, url):

    self.__url = url

    self.__id = {

        'shotgun' : 'shotguns',

        'handgun' : 'handguns',

            'rifle' :  'rifles',

        'tactical' : 'tactical'

         }

         self.__lcount = 0

         self.__gun_listings = []

         super().__init__(self.__url, self.__id)

    def setKeyValue(self, key, value):

        self.__id[key] = value

    def getKeys(self):

        for id in self.__get():

            print(id)

    def __get(self):

            for id in self.__id:

                yield self.__id[id]

    def getKey(self, key):

        return self.__id[key]

    def __addListing(self, listing):

        self.__gun_listings.append(listing)

        print(f"Added New Listing {self.__gun_listings(self.__lcount)} to Listings List")

        self.__lcount = self.__lcount + 1

def gatherListings(self, url):

        html_url = requests.get(url).text

        soup = BeautifulSoup(html_url, "lxml")

        listings = soup.find_all('div', class_='col-6 col-md-4 outer-tiles product-impression')

        for listing in listings:

            print("Gathering Listing name, price, etc..")

            name = listing.find('span', class_='first-line d-lg-none').text

            price = listing.find('span', class_='sales').text

            desc = listing.find('div', class_='pdp-link')

            desc_url = desc.a['href']

            print("Gathered Listing Data!")

            print("Creating new GunListing Object...")

            gun_listing = GunListing(name, price, desc, desc_url)

            print("Object Created successfully!")

            print("Adding Listing Object to List of Listings...")

            self.__addListing(gun_listing)

            print("Finished Successfully!

def getListings(self):
            print("Displaying Data for all Listings")

            for glisting in self.__gun_listings:
                name = glisting.getName()
                price = glisting.getPrice()
                desc = glisting.getDesc()
                desc_url = glisting.getDescURL()

                print(f"-----------------------------------------------------------")
                print(f"Listing Name: {name}")
                print(f"Listing Price: {price}")
                print(f"Desc: {desc}")
                print(f"For more info about this handgun, Visit {desc_url}")
                print(f"-----------------------------------------------------------")

</code>```

Listing.py

```<code>class Listing:

    def __inti__(self, name, price, desc, desc_url):

        self.__name = name

        self.__price = price

        self.__desc = desc

        self.__desc_url = desc_url

    def getName(self):

        return self.__name

    def getPrice(self):

        return self.__price

    def getDesc(self):

        return self.__desc

    def getDescURL(self):

        return self.__desc_url

</code>```

GunListing.py

```<code>
from Listing import Listing

class GunListing(Listing):

    def __init__(self, name, price, desc, desc_url):

        self.__name = name

        self.__price = price

        self.__desc = desc

        self.__desc_url = desc_url

        super().__init__(self.__name, self.__price, self.__desc, self.__desc_url)

</code>```

I expected the program to run through and complete everything in every function that I have created and called. But it isn't running anything in my functions just the code on the outside of the functions.

CODE IM RUNNING

```<code>gun_site = GunSite('https://www.cheaperthandirt.com/')

print(f"Gathering Listings for Website {gun_site.getURL()}")

gun_site.gatherListings(gun_site.getURL() + gun_site.getKey('shotgun') + '/')

print(f"Finished Successfully Gathering Listings for {gun_site.getURL()}")

print(f"Collecting All of the Listings from {gun_site.getURL()}")

gun_site.getListings()

print(f"Successfully Collected and Displayed Listings form {gun_site.getURL()}")

</code>```

Body:
Hello I am currently working on updating a project from when I first was learning to code. With that being said I am starting to implement classes withing the program when I have run into a bit of a Issue not like a physical Python Error but my Class Functions just don't seem to perform properly.

WebSite.py

class WebSite:
  def __init__(self, url, id):
      self.__url = url
      self.__id = id

  def getURL(self):
      return self.__url

  def getId(self):
      return self.__id

GunSite.py

> class GunSite(WebSite):

      def __init__(self, url):

    self.__url = url

    self.__id = {

        'shotgun' : 'shotguns',

        'handgun' : 'handguns',

            'rifle' :  'rifles',

        'tactical' : 'tactical'

         }

         self.__lcount = 0

         self.__gun_listings = []

         super().__init__(self.__url, self.__id)

    def setKeyValue(self, key, value):

        self.__id[key] = value

    def getKeys(self):

        for id in self.__get():

            print(id)

    def __get(self):

            for id in self.__id:

                yield self.__id[id]

    def getKey(self, key):

        return self.__id[key]

    def __addListing(self, listing):

        self.__gun_listings.append(listing)

        print(f"Added New Listing {self.__gun_listings(self.__lcount)} to Listings List")

        self.__lcount = self.__lcount + 1

def gatherListings(self, url):

        html_url = requests.get(url).text

        soup = BeautifulSoup(html_url, "lxml")

        listings = soup.find_all('div', class_='col-6 col-md-4 outer-tiles product-impression')

        for listing in listings:

            print("Gathering Listing name, price, etc..")

            name = listing.find('span', class_='first-line d-lg-none').text

            price = listing.find('span', class_='sales').text

            desc = listing.find('div', class_='pdp-link')

            desc_url = desc.a['href']

            print("Gathered Listing Data!")

            print("Creating new GunListing Object...")

            gun_listing = GunListing(name, price, desc, desc_url)

            print("Object Created successfully!")

            print("Adding Listing Object to List of Listings...")

            self.__addListing(gun_listing)

            print("Finished Successfully!

def getListings(self):
            print("Displaying Data for all Listings")

            for glisting in self.__gun_listings:
                name = glisting.getName()
                price = glisting.getPrice()
                desc = glisting.getDesc()
                desc_url = glisting.getDescURL()

                print(f"-----------------------------------------------------------")
                print(f"Listing Name: {name}")
                print(f"Listing Price: {price}")
                print(f"Desc: {desc}")
                print(f"For more info about this handgun, Visit {desc_url}")
                print(f"-----------------------------------------------------------")

Listing.py

class Listing:

    def __inti__(self, name, price, desc, desc_url):

        self.__name = name

        self.__price = price

        self.__desc = desc

        self.__desc_url = desc_url

    def getName(self):

        return self.__name

    def getPrice(self):

        return self.__price

    def getDesc(self):

        return self.__desc

    def getDescURL(self):

        return self.__desc_url

GunListing.py

from Listing import Listing

class GunListing(Listing):

    def __init__(self, name, price, desc, desc_url):

        self.__name = name

        self.__price = price

        self.__desc = desc

        self.__desc_url = desc_url

        super().__init__(self.__name, self.__price, self.__desc, self.__desc_url)

I expected the program to run through and complete everything in every function that I have created and called. But it isn't running anything in my functions just the code on the outside of the functions.

CODE IM RUNNING

gun_site = GunSite('https://www.cheaperthandirt.com/')

print(f"Gathering Listings for Website {gun_site.getURL()}")

gun_site.gatherListings(gun_site.getURL() + gun_site.getKey('shotgun') + '/')

print(f"Finished Successfully Gathering Listings for {gun_site.getURL()}")

print(f"Collecting All of the Listings from {gun_site.getURL()}")

gun_site.getListings()

print(f"Successfully Collected and Displayed Listings form {gun_site.getURL()}")


问:
How to configure JVM for Memory Analyzer on CentoS
I am currently trying to run MemoryAnalyzer (by Eclipse) on my CentOS desktop. When I try to run it it complains that the JVM is incompatible and it needs version 11 or greater.
On my centOS desktop I do have JDK 11 at the path /usr/java/jdk11 . How can I make Memory Analyzer use it?</p>


问:
getting 400 badrequest while passing multipart file in request in Junit
when I am trying to write the junit for my controller class, I am getting 400 bad request.

In console , i can see below error:

logException Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present

this is my Junit

@Test
void testExcelFile() throws Exception {

    FileInputStream inputFile = new FileInputStream("path of the file");
    MockMultipartFile file = new MockMultipartFile("file", "myexcelFile.xlsx", "multipart/form-data", inputFile);

    Mockito.when(service.upload((MultipartFile) file)).thenReturn("received");

    RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/uploadData",file)
            .param("file",file.getName()).contentType(MediaType.MULTIPART_FORM_DATA);
    MvcResult result =
    mockMvc.perform(requestBuilder).andExpect(status().isAccepted()).andReturn();
    assertEquals(HttpStatus.ACCEPTED.value(), result.getResponse().getStatus());
}
```
<p>This is my controller class</p>
<pre class="lang-java prettyprint-override"><code>@PostMapping("/uploadData")
public ResponseEntity<String> save(@RequestParam(required = true)  MultipartFile file) {
    if(ExcelHelper.checkExcelFormat(file)) {
        return new ResponseEntity<>(service.upload(file),HttpStatus.ACCEPTED);
    }
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Please upload excel file only");
}
</code>```

Please help what I am doing wrong. Thanks in advance.

Body:
when I am trying to write the junit for my controller class, I am getting 400 bad request.

In console , i can see below error:

logException Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present

this is my Junit

@Test
void testExcelFile() throws Exception {

    FileInputStream inputFile = new FileInputStream("path of the file");
    MockMultipartFile file = new MockMultipartFile("file", "myexcelFile.xlsx", "multipart/form-data", inputFile);

    Mockito.when(service.upload((MultipartFile) file)).thenReturn("received");

    RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/uploadData",file)
            .param("file",file.getName()).contentType(MediaType.MULTIPART_FORM_DATA);
    MvcResult result =
    mockMvc.perform(requestBuilder).andExpect(status().isAccepted()).andReturn();
    assertEquals(HttpStatus.ACCEPTED.value(), result.getResponse().getStatus());
}

This is my controller class

@PostMapping("/uploadData")
public ResponseEntity<String> save(@RequestParam(required = true)  MultipartFile file) {
    if(ExcelHelper.checkExcelFormat(file)) {
        return new ResponseEntity<>(service.upload(file),HttpStatus.ACCEPTED);
    }
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Please upload excel file only");
}

Please help what I am doing wrong. Thanks in advance.


问:
Pandas Data frame: Fastest way to shift columns based on a condition
I am trying to find the fastest way to shift a column based on a condition on another column.
For example:

Assuming the given input is :

Expected Output is :

Any help is greatly appreciated.

I have tried to run through each unique name using a for loop. performed the shift(-1) on the data frame and append data to a new data frame. Code example below. But there are over 1M rows and this takes lot of time to compute.
Assuming df2 being our sorted dataframe.

```<code>df3 = pd.DataFrame()
for i in df2['Name'].unique():
    if df3.size == 0:
        df3=df2.loc[df2['name']==i]
        df3['final'] = df3['value'].shift(-1)
        df3.fillna('Exit', inplace=True)
    else:
        df4=df2.loc[df2['name']==i]
        df4['final'] = df4['value'].shift(-1)
        df4.fillna('Exit', inplace=True)
        df3 = df3.append(df4, ignore_index = True)
</code>```

Body:
I am trying to find the fastest way to shift a column based on a condition on another column.
For example:

Assuming the given input is :

Expected Output is :

Any help is greatly appreciated.

I have tried to run through each unique name using a for loop. performed the shift(-1) on the data frame and append data to a new data frame. Code example below. But there are over 1M rows and this takes lot of time to compute.
Assuming df2 being our sorted dataframe.

df3 = pd.DataFrame()
for i in df2['Name'].unique():
    if df3.size == 0:
        df3=df2.loc[df2['name']==i]
        df3['final'] = df3['value'].shift(-1)
        df3.fillna('Exit', inplace=True)
    else:
        df4=df2.loc[df2['name']==i]
        df4['final'] = df4['value'].shift(-1)
        df4.fillna('Exit', inplace=True)
        df3 = df3.append(df4, ignore_index = True)


问:
Ironsource Real Ads Not Showing
I am working on a game in unity and trying to integrate ironsource in the game for ads,
after initializing with test app key test app seen in android

```<code>IronSource.Agent.init(appKeyTest);
</code>```

But after initializing with real app key ads are not working in android

```<code>IronSource.Agent.init(appKey);
</code>```

*Also added the respective appKeys in ironsource developer setting in unity editor. *

**One more thing our game is already uploaded on playstore just changing its ads network. **

Solution on integrating ironsource with real appkeys

Title: Ironsource Real Ads Not Showing

Body:
I am working on a game in unity and trying to integrate ironsource in the game for ads,
after initializing with test app key test app seen in android

IronSource.Agent.init(appKeyTest);

But after initializing with real app key ads are not working in android

IronSource.Agent.init(appKey);

*Also added the respective appKeys in ironsource developer setting in unity editor. *

**One more thing our game is already uploaded on playstore just changing its ads network. **

Solution on integrating ironsource with real appkeys


问:
Query for timestampz field with index 3 times slowly then without
I have integration_event table with ~300k db entries in postgres.
Indexes added for:

pk,
committed_date_time (timestamptz) - btree,

response_body(text) + response_business_description(varchar 5000) + response_business_code(varchar100) + response_headers(text) - gin (gin_trgm_ops).

This EF core generated query completed in 10 seconds:

```<code>SELECT i.committed_date_time AS "CommittedDateTime", i.external_object_id AS "ExternalObjectId", i.external_system AS "ExternalSystem", i.id AS "Id", i.internal_object_id AS "InternalObjectId", i.is_successful_request AS "IsSuccessfulRequest", i.object_type AS "ObjectType", i.request_direction AS "RequestDirection", i.request_http_method AS "RequestHttpMethod", i.request_url AS "RequestUrl", i.response_business_code AS "ResponseBusinessCode", i.response_business_description AS "ResponseBusinessDescription", i.response_http_code AS "ResponseHttpCode", i.task_id AS "TaskId"
FROM events.integration_event AS i
WHERE (i.committed_date_time >= '2021-12-14 03:00:00.000 +0300') AND (((((('00294961' = '') OR
(strpos(lower(i.response_body), '00294961') > 0)) OR (('00294961' = '') OR
(strpos(lower(i.response_business_code), '00294961') > 0))) OR (('00294961' = '') OR
(strpos(lower(i.response_business_description), '00294961') > 0))) OR (('00294961' = '') OR
(strpos(lower(i.response_headers), '00294961') > 0)))
ORDER BY i.committed_date_time DESC
LIMIT 10 OFFSET 0
</code>```

In execution plan I see only committed_date_time index using.
If I delete this index, no one used and query completed in ~3 seconds.
If I delete multicolumn index nothing changes.

Explain without any indexes:

QUERY PLAN

Limit  (cost=64058.96..64060.13 rows=10 width=276) (actual time=2810.118..2815.614 rows=0 loops=1)

Output: committed_date_time, external_object_id, external_system, id, internal_object_id, is_successful_request, object_type, request_direction, request_http_method, request_url, response_business_code, response_business_description, response_http_code, task_id

Buffers: shared hit=113016 read=92539 dirtied=239 written=68

->  Gather Merge  (cost=64058.96..79140.58 rows=129262 width=276) (actual time=2810.117..2815.612 rows=0 loops=1)

Output: committed_date_time, external_object_id, external_system, id, internal_object_id, is_successful_request, object_type, request_direction, request_http_method, request_url, response_business_code, response_business_description, response_http_code, task_id

Workers Planned: 2

Workers Launched: 2

Buffers: shared hit=113016 read=92539 dirtied=239 written=68

->  Sort  (cost=63058.94..63220.52 rows=64631 width=276) (actual time=2794.379..2794.380 rows=0 loops=3)

Output: committed_date_time, external_object_id, external_system, id, internal_object_id, is_successful_request, object_type, request_direction, request_http_method, request_url, response_business_code, response_business_description, response_http_code, task_id

Sort Key: i.committed_date_time DESC

Sort Method: quicksort  Memory: 25kB

Buffers: shared hit=113016 read=92539 dirtied=239 written=68

Worker 0:  actual time=2786.424..2786.425 rows=0 loops=1

Sort Method: quicksort  Memory: 25kB

Buffers: shared hit=36144 read=30162 dirtied=52 written=13

Worker 1:  actual time=2786.908..2786.909 rows=0 loops=1

Sort Method: quicksort  Memory: 25kB

Buffers: shared hit=36415 read=29682 dirtied=77 written=19

->  Parallel Seq Scan on events.integration_event i  (cost=0.00..61662.29 rows=64631 width=276) (actual time=2794.338..2794.338 rows=0 loops=3)

Output: committed_date_time, external_object_id, external_system, id, internal_object_id, is_successful_request, object_type, request_direction, request_http_method, request_url, response_business_code, response_business_description, response_http_code, task_id

Filter: ((i.committed_date_time >= '2021-12-14 03:00:00+03'::timestamp with time zone) AND ((strpos(lower(i.response_body), '00294961'::text) > 0) OR (strpos(lower((i.response_business_code)::text), '00294961'::text) > 0) OR (strpos(lower((i.response_business_description)::text), '00294961'::text) > 0) OR (strpos(lower(i.response_headers), '00294961'::text) > 0)))

Rows Removed by Filter: 64464

Buffers: shared hit=112940 read=92539 dirtied=239 written=68

Worker 0:  actual time=2786.353..2786.354 rows=0 loops=1

Buffers: shared hit=36106 read=30162 dirtied=52 written=13

Worker 1:  actual time=2786.858..2786.858 rows=0 loops=1

Buffers: shared hit=36377 read=29682 dirtied=77 written=19

Planning Time: 0.070 ms

Execution Time: 2815.637 ms

query plan without indexes

With Indexes

QUERY PLAN

Limit  (cost=0.42..15.67 rows=10 width=276) (actual time=7687.437..7687.438 rows=0 loops=1)

Output: committed_date_time, external_object_id, external_system, id, internal_object_id, is_successful_request, object_type, request_direction, request_http_method, request_url, response_business_code, response_business_description, response_http_code, task_id

Buffers: shared hit=168221 read=152857

->  Index Scan Backward using ix_commited_date_time on events.integration_event i  (cost=0.42..236678.30 rows=155194 width=276) (actual time=7687.436..7687.436 rows=0 loops=1)

Output: committed_date_time, external_object_id, external_system, id, internal_object_id, is_successful_request, object_type, request_direction, request_http_method, request_url, response_business_code, response_business_description, response_http_code, task_id

Index Cond: (i.committed_date_time >= '2021-12-14 03:00:00+03'::timestamp with time zone)

Filter: ((strpos(lower(i.response_body), '00294961'::text) > 0) OR (strpos(lower((i.response_business_code)::text), '00294961'::text) > 0) OR (strpos(lower((i.response_business_description)::text), '00294961'::text) > 0) OR (strpos(lower(i.response_headers), '00294961'::text) > 0))

Rows Removed by Filter: 193323

Buffers: shared hit=168221 read=152857

Planning:

Buffers: shared hit=1 read=3

Planning Time: 0.142 ms

Execution Time: 7687.460 ms

query plan with indexes

First question - why its slowly?

Second - why multicolumn index not used?

Third - is there any way to multicolumn gin index includes timestamptz column?

I try another index types for committed_date_time, gin index only for response_body(largest text)

Body:
I have integration_event table with ~300k db entries in postgres.
Indexes added for:

pk,
committed_date_time (timestamptz) - btree,

response_body(text) + response_business_description(varchar 5000) + response_business_code(varchar100) + response_headers(text) - gin (gin_trgm_ops).

This EF core generated query completed in 10 seconds:

SELECT i.committed_date_time AS "CommittedDateTime", i.external_object_id AS "ExternalObjectId", i.external_system AS "ExternalSystem", i.id AS "Id", i.internal_object_id AS "InternalObjectId", i.is_successful_request AS "IsSuccessfulRequest", i.object_type AS "ObjectType", i.request_direction AS "RequestDirection", i.request_http_method AS "RequestHttpMethod", i.request_url AS "RequestUrl", i.response_business_code AS "ResponseBusinessCode", i.response_business_description AS "ResponseBusinessDescription", i.response_http_code AS "ResponseHttpCode", i.task_id AS "TaskId"
FROM events.integration_event AS i
WHERE (i.committed_date_time >= '2021-12-14 03:00:00.000 +0300') AND (((((('00294961' = '') OR
(strpos(lower(i.response_body), '00294961') > 0)) OR (('00294961' = '') OR
(strpos(lower(i.response_business_code), '00294961') > 0))) OR (('00294961' = '') OR
(strpos(lower(i.response_business_description), '00294961') > 0))) OR (('00294961' = '') OR
(strpos(lower(i.response_headers), '00294961') > 0)))
ORDER BY i.committed_date_time DESC
LIMIT 10 OFFSET 0

In execution plan I see only committed_date_time index using.
If I delete this index, no one used and query completed in ~3 seconds.
If I delete multicolumn index nothing changes.

Explain without any indexes:

QUERY PLAN

Limit  (cost=64058.96..64060.13 rows=10 width=276) (actual time=2810.118..2815.614 rows=0 loops=1)

Output: committed_date_time, external_object_id, external_system, id, internal_object_id, is_successful_request, object_type, request_direction, request_http_method, request_url, response_business_code, response_business_description, response_http_code, task_id

Buffers: shared hit=113016 read=92539 dirtied=239 written=68

->  Gather Merge  (cost=64058.96..79140.58 rows=129262 width=276) (actual time=2810.117..2815.612 rows=0 loops=1)

Output: committed_date_time, external_object_id, external_system, id, internal_object_id, is_successful_request, object_type, request_direction, request_http_method, request_url, response_business_code, response_business_description, response_http_code, task_id

Workers Planned: 2

Workers Launched: 2

Buffers: shared hit=113016 read=92539 dirtied=239 written=68

->  Sort  (cost=63058.94..63220.52 rows=64631 width=276) (actual time=2794.379..2794.380 rows=0 loops=3)

Output: committed_date_time, external_object_id, external_system, id, internal_object_id, is_successful_request, object_type, request_direction, request_http_method, request_url, response_business_code, response_business_description, response_http_code, task_id

Sort Key: i.committed_date_time DESC

Sort Method: quicksort  Memory: 25kB

Buffers: shared hit=113016 read=92539 dirtied=239 written=68

Worker 0:  actual time=2786.424..2786.425 rows=0 loops=1

Sort Method: quicksort  Memory: 25kB

Buffers: shared hit=36144 read=30162 dirtied=52 written=13

Worker 1:  actual time=2786.908..2786.909 rows=0 loops=1

Sort Method: quicksort  Memory: 25kB

Buffers: shared hit=36415 read=29682 dirtied=77 written=19

->  Parallel Seq Scan on events.integration_event i  (cost=0.00..61662.29 rows=64631 width=276) (actual time=2794.338..2794.338 rows=0 loops=3)

Output: committed_date_time, external_object_id, external_system, id, internal_object_id, is_successful_request, object_type, request_direction, request_http_method, request_url, response_business_code, response_business_description, response_http_code, task_id

Filter: ((i.committed_date_time >= '2021-12-14 03:00:00+03'::timestamp with time zone) AND ((strpos(lower(i.response_body), '00294961'::text) > 0) OR (strpos(lower((i.response_business_code)::text), '00294961'::text) > 0) OR (strpos(lower((i.response_business_description)::text), '00294961'::text) > 0) OR (strpos(lower(i.response_headers), '00294961'::text) > 0)))

Rows Removed by Filter: 64464

Buffers: shared hit=112940 read=92539 dirtied=239 written=68

Worker 0:  actual time=2786.353..2786.354 rows=0 loops=1

Buffers: shared hit=36106 read=30162 dirtied=52 written=13

Worker 1:  actual time=2786.858..2786.858 rows=0 loops=1

Buffers: shared hit=36377 read=29682 dirtied=77 written=19

Planning Time: 0.070 ms

Execution Time: 2815.637 ms

query plan without indexes

With Indexes

QUERY PLAN

Limit  (cost=0.42..15.67 rows=10 width=276) (actual time=7687.437..7687.438 rows=0 loops=1)

Output: committed_date_time, external_object_id, external_system, id, internal_object_id, is_successful_request, object_type, request_direction, request_http_method, request_url, response_business_code, response_business_description, response_http_code, task_id

Buffers: shared hit=168221 read=152857

->  Index Scan Backward using ix_commited_date_time on events.integration_event i  (cost=0.42..236678.30 rows=155194 width=276) (actual time=7687.436..7687.436 rows=0 loops=1)

Output: committed_date_time, external_object_id, external_system, id, internal_object_id, is_successful_request, object_type, request_direction, request_http_method, request_url, response_business_code, response_business_description, response_http_code, task_id

Index Cond: (i.committed_date_time >= '2021-12-14 03:00:00+03'::timestamp with time zone)

Filter: ((strpos(lower(i.response_body), '00294961'::text) > 0) OR (strpos(lower((i.response_business_code)::text), '00294961'::text) > 0) OR (strpos(lower((i.response_business_description)::text), '00294961'::text) > 0) OR (strpos(lower(i.response_headers), '00294961'::text) > 0))

Rows Removed by Filter: 193323

Buffers: shared hit=168221 read=152857

Planning:

Buffers: shared hit=1 read=3

Planning Time: 0.142 ms

Execution Time: 7687.460 ms

query plan with indexes

First question - why its slowly?

Second - why multicolumn index not used?

Third - is there any way to multicolumn gin index includes timestamptz column?

I try another index types for committed_date_time, gin index only for response_body(largest text)


问:
PineScript Version 5: Seeking different time frames for price ticker and indicators
In PineScript Version 5, I would like to have the price constantly updated on each tick but have all the buy/sell conditions that are based of indicators run on a changable time frame, say 3 month period.
Why? Because trades cannot be executed on the same bar (as far as I can tell). So I'd want to have the highest resolution possible, like the 1 second ticker update on price for example but use the 3-month resolution to calculate MACD, RSI, etc.

Outcome I'm seeking, maybe some PineScript Version 5 examples or documentation

Code needs to have RSI, MACD, etc would be 3-month and trigger buy/sell events and price could update with each tick so that if the price hits a target/stop loss it is executed on the 1 second bar and not a higher resolution where you might get worse prices.


问:
How to have same http interceptor across multiple angular projects?
I have 5 different projects having same http interceptor code.
Each time there is a change in the interceptor code, that has to be done at 5 different places.

Is there any way, by which this code can be made as generic code.


问:
Drag and select the object in fabric.js
I need to drag and select the object in fabric.js just by dragging and selecting a small portion of it. Setting 'selectionFullyContained: false' helps us to select it. But if we drag anywhere within the borders select the object.It is the default behaviour of fabric.js.

I need to select the object only when the drag and selection is made exactly on the object.

Dragging the mouse anywhere within the borders select the object
I need to select the object only when the drag and selection is made exactly on the object(that is the black lined borders)

Please note that we can select and drag exactly the object by setting perPixelFindTarget to true.But I need to select the object using mousedrag

Title: Drag and select the object in fabric.js


问:
Read TLS enable emails using IMAP library in Python
I am getting  below error while read mail using python script. I am using outlook as email server.

The same code is working for my personal email but not for may company email address.

I verified that tow-factor authentication is not enabled

Mail_read.py

```<code>import imaplib
import email
import ssl
from getpass import getpass
import html2text

imap_server="outlook.office365.com"

email_addrss="name@companyname.com"
password =  getpass()

# Login to Outlook email
imap = imaplib.IMAP4_SSL(imap_server,port=993)

imap.login(email_addrss,password)

imap.close()
</code>```

Error

```<code>    imap.login(email_addrss,password)
  File "/usr/lib/python3.10/imaplib.py", line 612, in login
    raise self.error(dat[-1])
imaplib.IMAP4.error: b'LOGIN failed.'
</code>```

Also, I verify that using SMTP protocol I can able to sent mail.

sent_mail_smtp.py (Working)

```<code>import smtplib

mailserver = smtplib.SMTP('smtp.office365.com',587)
mailserver.ehlo()
mailserver.starttls()
mailserver.login('name@companyname.com', 'Password')

mailserver.sendmail("dname@companyname.com","receiver email","email body")
mailserver.quit()
</code>```

I verify that there are email and password is correct

It's working for SMTP library

Please help me to solve this issue

Thanks

Body:
I am getting  below error while read mail using python script. I am using outlook as email server.

The same code is working for my personal email but not for may company email address.

I verified that tow-factor authentication is not enabled

Mail_read.py

import imaplib
import email
import ssl
from getpass import getpass
import html2text

imap_server="outlook.office365.com"

email_addrss="name@companyname.com"
password =  getpass()

# Login to Outlook email
imap = imaplib.IMAP4_SSL(imap_server,port=993)

imap.login(email_addrss,password)

imap.close()

Error

    imap.login(email_addrss,password)
  File "/usr/lib/python3.10/imaplib.py", line 612, in login
    raise self.error(dat[-1])
imaplib.IMAP4.error: b'LOGIN failed.'

Also, I verify that using SMTP protocol I can able to sent mail.

sent_mail_smtp.py (Working)

import smtplib

mailserver = smtplib.SMTP('smtp.office365.com',587)
mailserver.ehlo()
mailserver.starttls()
mailserver.login('name@companyname.com', 'Password')

mailserver.sendmail("dname@companyname.com","receiver email","email body")
mailserver.quit()

I verify that there are email and password is correct

It's working for SMTP library

Please help me to solve this issue

Thanks


问:
Login fails with innocent looking code in a sourced script on openSUSE
I have a number of bash scripts that load during login, to provide helpful functions that other scripts I run rely on.

I have recently moved to OpenSUSE Tumbleweed from MacOS, and Linux will not login with this code present in one of my sourced scripts.

```<code>while (( $# >= 1 )); do
    case ${1} in
        'ERR')      ___NOERR___=0;   ___hsUtilitiesForceReload__=1;;
        'EXIT')     ___NOEXIT___=0;  ___hsUtilitiesForceReload__=1;;
        'INT')      ___NOINT___=0;   ___hsUtilitiesForceReload__=1;;
        'WINCH')    ___NOWINCH___=0; ___hsUtilitiesForceReload__=1;;
        'FORCE')                     ___hsUtilitiesForceReload__=1;;
        'QUIET')    ___QUIET___=1;;
        *)          printf "Command line parameter not understood: \"%s\"" "${1}";;
    esac
    shift
done
</code>```

With this commented out, the login is successful, but with it in place, login fails and I get returned to the login screen.

If I test this apart from login, it seems to be fine. I have tested it by entering

```<code>set -eu
source [...path...]/utilities.sh
set +eu
</code>```

and the script loads without error.

Can anybody guess what may be going on?
TIA

Body:
I have a number of bash scripts that load during login, to provide helpful functions that other scripts I run rely on.

I have recently moved to OpenSUSE Tumbleweed from MacOS, and Linux will not login with this code present in one of my sourced scripts.

while (( $# >= 1 )); do
    case ${1} in
        'ERR')      ___NOERR___=0;   ___hsUtilitiesForceReload__=1;;
        'EXIT')     ___NOEXIT___=0;  ___hsUtilitiesForceReload__=1;;
        'INT')      ___NOINT___=0;   ___hsUtilitiesForceReload__=1;;
        'WINCH')    ___NOWINCH___=0; ___hsUtilitiesForceReload__=1;;
        'FORCE')                     ___hsUtilitiesForceReload__=1;;
        'QUIET')    ___QUIET___=1;;
        *)          printf "Command line parameter not understood: \"%s\"" "${1}";;
    esac
    shift
done

With this commented out, the login is successful, but with it in place, login fails and I get returned to the login screen.

If I test this apart from login, it seems to be fine. I have tested it by entering

set -eu
source [...path...]/utilities.sh
set +eu

and the script loads without error.

Can anybody guess what may be going on?
TIA


问:
Repeat users input using PySimpleGUI
I am looking to make a program that listens to what the user inputs and than it will repeat the same thing. Repeating should be easy, but what I find hard to do is to store the user input inside a list so than I can do the same thing one by one. One of the other things I don't know how to do is the timing, I also want the timing to be the same as the user input, The way I think this can be done is using another list just for the timings but im not sure thats a good idea or not, can anyone help me?</p>

Title: Repeat users input using PySimpleGUI


问:
Total profit and loss calculation from option trading with options events with the Robinhood API data
I'm writing an Chrome extension to calculate total profit and loss from Robinhood trading history.

Found out that total profit/loss calculation for options trading is more complicated than what I expected when counting options events such as expiration, exercise, and assignment.

I tried to think through all possible scenarios and came up with the formula that I think it will work but wanted to get some other eyes on it to see if I'm missing anything or doing it completely wrong.

```<code>// Option trading Profit / Loss occurrence

// Buy to open call options > Betting on Bullish
//    - TotalPL = (selling/expried premium * quantity) - (buying premium * quantity)
//    - Exercise (underlying_price * (quantity * 100)) - (strike_price * (quantity * 100))

// Sell to open call options > Betting on Bearish
//    - TotalPL = (buying premium * quantity) - (selling/expried premium * quantity)
//    - Assignment (strike_price * (quantity * 100)) - (underlying_price * (quantity * 100))
//
//    Example: Sell 2 of SPY $200 2023/01/06 call options at $10 premium (with the 200 shares of SPY as a collateral)
//    Senario 1) selling options before expiration
//      TotalPL = ($10 * 2) - (current premium at the time of selling * 2)
//    Senario 2) option expired in the money
//      TotalPL = ($10 * 2) - (0 * 2) >> current premium at the time of selling is $0. You keep all the credit. It is the same as senario 1.
//    Senario 3) option expired out of the money. SPY ended at $250 on 2023/01/06
//      TotalPL = ($200 * 200) - ($250 * 200)

// Buy to open put options > Betting on Bearish
//    - TotalPL = (selling/expried premium * quantity) - (buying premium * quantity)
//    - Exercise (strike_price * (quantity * 100)) - (underlying_price * (quantity * 100))

// Sell to open put options > Betting on Bullish
//    - TotalPL = (buying premium * quantity) - (selling/expried premium * quantity)
//    - Assignment (underlying_price * (quantity * 100)) - (strike_price * (quantity * 100))
</code>```

Body:
I'm writing an Chrome extension to calculate total profit and loss from Robinhood trading history.

Found out that total profit/loss calculation for options trading is more complicated than what I expected when counting options events such as expiration, exercise, and assignment.

I tried to think through all possible scenarios and came up with the formula that I think it will work but wanted to get some other eyes on it to see if I'm missing anything or doing it completely wrong.

// Option trading Profit / Loss occurrence

// Buy to open call options > Betting on Bullish
//    - TotalPL = (selling/expried premium * quantity) - (buying premium * quantity)
//    - Exercise (underlying_price * (quantity * 100)) - (strike_price * (quantity * 100))

// Sell to open call options > Betting on Bearish
//    - TotalPL = (buying premium * quantity) - (selling/expried premium * quantity)
//    - Assignment (strike_price * (quantity * 100)) - (underlying_price * (quantity * 100))
//
//    Example: Sell 2 of SPY $200 2023/01/06 call options at $10 premium (with the 200 shares of SPY as a collateral)
//    Senario 1) selling options before expiration
//      TotalPL = ($10 * 2) - (current premium at the time of selling * 2)
//    Senario 2) option expired in the money
//      TotalPL = ($10 * 2) - (0 * 2) >> current premium at the time of selling is $0. You keep all the credit. It is the same as senario 1.
//    Senario 3) option expired out of the money. SPY ended at $250 on 2023/01/06
//      TotalPL = ($200 * 200) - ($250 * 200)

// Buy to open put options > Betting on Bearish
//    - TotalPL = (selling/expried premium * quantity) - (buying premium * quantity)
//    - Exercise (strike_price * (quantity * 100)) - (underlying_price * (quantity * 100))

// Sell to open put options > Betting on Bullish
//    - TotalPL = (buying premium * quantity) - (selling/expried premium * quantity)
//    - Assignment (underlying_price * (quantity * 100)) - (strike_price * (quantity * 100))


问:
Elastic Beanstalk EC2 give private static ip
I have a Elastic Beanstalk running in a VPC which has access to a 3rd party VPN. The VPN firewall gives access only a single private IP. but every time during a re-deployment the ebs private IP changes in the EC2 instance. is there a way to set a private static ip to ebs ec2 instance</p>


问:
Need suggestion on best EventLoopGroup configuration for particular case
I was going through multiple docs and examples about the correct configuration of EventLoopGroup but couldn't decide what's best for my use case.

I am using Netty 4.1.86.Final on linux.

Use case:

We have a web server that accepts 50-100k connections (both http :80 and https :443) and handles 20-30k requests per second. It's server-to-server communication, where multiple servers maintain connections for a short duration (keep-alive few minutes to an hour) and then recycle (close and open a new connection) the connection. Every request typically takes 50-100ms to process. The processing involves parsing JSON payload and running some complex business logic and some async network call to internal servers as well (cache, db etc.).

Question:

What I understood so far is that there are a couple of options that I can try -

use same EventLoopGroup for boss and worker and use separate EventExecutorGroup in pipeline for my business logic like: pipeline.addLast(handlerExecutorGroup, "handler", new MyHttpEndServer());

use different EventLoopGroup for boss and worker (.group(ioThreadExecutors, workerThreadExecutors)) and use a very high number of threads for the worker EventLoopGroup (cpu * 8)

use 3 different EventLoopGroup for boss, worker and handler (cpu * 8 thread).

use same EventLoopGroup for boss and worker and use SO_REUSEPORT and bind multiple threads to the same port so that instead of 1 I/O thread per port, now we will have more I/O thread per port to accept the connection along with using separate handlerExecutorGroup in pipeline for my business logic same as option 1.

```<code>.group(ioThreadExecutors)
.option(UnixChannelOption.SO_REUSEPORT, true)

for (int i = 0; i < channelThreadCount; i++) {
       ChannelFuture f = httpServer.bind(port).sync();
       channelFutureSet.add(f);
}
</code>```

which among these seems a better option for my use case? Or if there is some other better approach that I should try.

Note: I did the load test with all 4 options, but didn't notice much difference.

Body:
I was going through multiple docs and examples about the correct configuration of EventLoopGroup but couldn't decide what's best for my use case.

I am using Netty 4.1.86.Final on linux.

Use case:

We have a web server that accepts 50-100k connections (both http :80 and https :443) and handles 20-30k requests per second. It's server-to-server communication, where multiple servers maintain connections for a short duration (keep-alive few minutes to an hour) and then recycle (close and open a new connection) the connection. Every request typically takes 50-100ms to process. The processing involves parsing JSON payload and running some complex business logic and some async network call to internal servers as well (cache, db etc.).

Question:

What I understood so far is that there are a couple of options that I can try -

use same EventLoopGroup for boss and worker and use separate EventExecutorGroup in pipeline for my business logic like: pipeline.addLast(handlerExecutorGroup, "handler", new MyHttpEndServer());

use different EventLoopGroup for boss and worker (.group(ioThreadExecutors, workerThreadExecutors)) and use a very high number of threads for the worker EventLoopGroup (cpu * 8)

use 3 different EventLoopGroup for boss, worker and handler (cpu * 8 thread).

use same EventLoopGroup for boss and worker and use SO_REUSEPORT and bind multiple threads to the same port so that instead of 1 I/O thread per port, now we will have more I/O thread per port to accept the connection along with using separate handlerExecutorGroup in pipeline for my business logic same as option 1.

.group(ioThreadExecutors)
.option(UnixChannelOption.SO_REUSEPORT, true)

for (int i = 0; i < channelThreadCount; i++) {
       ChannelFuture f = httpServer.bind(port).sync();
       channelFutureSet.add(f);
}

which among these seems a better option for my use case? Or if there is some other better approach that I should try.

Note: I did the load test with all 4 options, but didn't notice much difference.