问:
Hierarchical Query with clause "START WITH" not work when use IN subquery as condition when using JdbcTemplate
I have query to find any member of team that below the group that lead by one upper level group of target employee, and test at DBeaver using query like below

```<code>WITH HIERARCHICAL_TB AS (
   SELECT
      LEVEL as "XLEVEL"
      , t.EMP_ID as "EMP_ID"
      , t.NAME
      , t.JOB_POS_ID as "JOB_CD"
      , t.TEAM_ID
      , t.TEAM_PARENT_ID
      , 'TEAM_TREE' as "FOUND_AT"
      , PRIOR t.EMP_ID as "PRIOR_EMP_ID
      , PRIOR t.TEAM_ID as "PRIOR_TEAM_ID
      , PRIOR t.TEAM_PARENT_ID as "PRIOR_TEAM_PARENT_ID
   FROM
      TB_EMPLOYEE t
      START WITH
         t.TEAM_PARENT_ID IN (
            SELECT
               b.TEAM_PARENT_ID
            FROM
               TB_EMPLOYEE b
            WHERE
               b.EMP_ID IN (:TARGET_EMP)
         )
      CONNECT BY NOCYCLE
         PRIOR TEAM_ID = TEAM_PARENT_ID
         AND PRIOR EMP_ID <> EMP_ID
   )
SELECT
   count(*)
FROM
   SELECT
      ht.XLEVEL
      , ht.EMP_ID
      , ht.NAME
      , ht.JOB_CD
      , ht.PRIOR_EMP_ID as "LEAD_EMP_ID"
   FROM
      HIERARCHICAL_TB ht
   WHERE
      ht.NAME like (':SEARCH' || '%')

</code>```

this query work fine when run at DBeaver with correct amount number as result but...
when I use same query in code that using JdbcTemplate the result is zero.

but when I replace subquery with the static value like this

```<code> WITH HIERARCHICAL_TB AS (
   SELECT
      LEVEL as "XLEVEL"
      , t.EMP_ID as "EMP_ID"
      , t.NAME
      , t.JOB_POS_ID as "JOB_CD"
      , t.TEAM_ID
      , t.TEAM_PARENT_ID
      , 'TEAM_TREE' as "FOUND_AT"
      , PRIOR t.EMP_ID as "PRIOR_EMP_ID
      , PRIOR t.TEAM_ID as "PRIOR_TEAM_ID
      , PRIOR t.TEAM_PARENT_ID as "PRIOR_TEAM_PARENT_ID
   FROM
      TB_EMPLOYEE t
      START WITH
         t.TEAM_PARENT_ID IN ('123456','345678')
      CONNECT BY NOCYCLE
         PRIOR TEAM_ID = TEAM_PARENT_ID
         AND PRIOR EMP_ID <> EMP_ID
   )
SELECT
   count(*)
FROM
   SELECT
      ht.XLEVEL
      , ht.EMP_ID
      , ht.NAME
      , ht.JOB_CD
      , ht.PRIOR_EMP_ID as "LEAD_EMP_ID"
   FROM
      HIERARCHICAL_TB ht
   WHERE
      ht.NAME like (':SEARCH' || '%')
</code>```

the second query got same result from DBerver and JdbcTemplate.

the problem is: why the first example query got difference result between DBeaver and  JdbcTemplate because the real query is more complex than these examples and I would like to use statement that can proof result from query tool before put it in to the code.

I use ojdbc8.jar as jdbc driver, it same as I use at DBeaver (v6.3.0)
and my project using spring-boot-starter-jdbc:2.2.2.RELEASE

答:
the problem is this query (as @AlexPoole make an observation)

```<code>SELECT
   b.TEAM_PARENT_ID
FROM
   TB_EMPLOYEE b
WHERE
   b.EMP_ID IN (:TARGET_EMP)
</code>```

the cause of problem is b.EMP_ID in table TB_EMPLOYEE contain white space, and got no result at JdbcTemplate but at DBeaver have result (I still don't understand why DBeaver got result), so I fix the query by turn b.EMP_ID IN (:TARGET_EMP) to be trim(b.EMP_ID IN (:TARGET_EMP).

Thank you for all help.

Body:
I have query to find any member of team that below the group that lead by one upper level group of target employee, and test at DBeaver using query like below

WITH HIERARCHICAL_TB AS (
   SELECT
      LEVEL as "XLEVEL"
      , t.EMP_ID as "EMP_ID"
      , t.NAME
      , t.JOB_POS_ID as "JOB_CD"
      , t.TEAM_ID
      , t.TEAM_PARENT_ID
      , 'TEAM_TREE' as "FOUND_AT"
      , PRIOR t.EMP_ID as "PRIOR_EMP_ID
      , PRIOR t.TEAM_ID as "PRIOR_TEAM_ID
      , PRIOR t.TEAM_PARENT_ID as "PRIOR_TEAM_PARENT_ID
   FROM
      TB_EMPLOYEE t
      START WITH
         t.TEAM_PARENT_ID IN (
            SELECT
               b.TEAM_PARENT_ID
            FROM
               TB_EMPLOYEE b
            WHERE
               b.EMP_ID IN (:TARGET_EMP)
         )
      CONNECT BY NOCYCLE
         PRIOR TEAM_ID = TEAM_PARENT_ID
         AND PRIOR EMP_ID <> EMP_ID
   )
SELECT
   count(*)
FROM
   SELECT
      ht.XLEVEL
      , ht.EMP_ID
      , ht.NAME
      , ht.JOB_CD
      , ht.PRIOR_EMP_ID as "LEAD_EMP_ID"
   FROM
      HIERARCHICAL_TB ht
   WHERE
      ht.NAME like (':SEARCH' || '%')

this query work fine when run at DBeaver with correct amount number as result but...
when I use same query in code that using JdbcTemplate the result is zero.

but when I replace subquery with the static value like this

 WITH HIERARCHICAL_TB AS (
   SELECT
      LEVEL as "XLEVEL"
      , t.EMP_ID as "EMP_ID"
      , t.NAME
      , t.JOB_POS_ID as "JOB_CD"
      , t.TEAM_ID
      , t.TEAM_PARENT_ID
      , 'TEAM_TREE' as "FOUND_AT"
      , PRIOR t.EMP_ID as "PRIOR_EMP_ID
      , PRIOR t.TEAM_ID as "PRIOR_TEAM_ID
      , PRIOR t.TEAM_PARENT_ID as "PRIOR_TEAM_PARENT_ID
   FROM
      TB_EMPLOYEE t
      START WITH
         t.TEAM_PARENT_ID IN ('123456','345678')
      CONNECT BY NOCYCLE
         PRIOR TEAM_ID = TEAM_PARENT_ID
         AND PRIOR EMP_ID <> EMP_ID
   )
SELECT
   count(*)
FROM
   SELECT
      ht.XLEVEL
      , ht.EMP_ID
      , ht.NAME
      , ht.JOB_CD
      , ht.PRIOR_EMP_ID as "LEAD_EMP_ID"
   FROM
      HIERARCHICAL_TB ht
   WHERE
      ht.NAME like (':SEARCH' || '%')

the second query got same result from DBerver and JdbcTemplate.

the problem is: why the first example query got difference result between DBeaver and  JdbcTemplate because the real query is more complex than these examples and I would like to use statement that can proof result from query tool before put it in to the code.

I use ojdbc8.jar as jdbc driver, it same as I use at DBeaver (v6.3.0)
and my project using spring-boot-starter-jdbc:2.2.2.RELEASE

Body:
the problem is this query (as @AlexPoole make an observation)

SELECT
   b.TEAM_PARENT_ID
FROM
   TB_EMPLOYEE b
WHERE
   b.EMP_ID IN (:TARGET_EMP)

the cause of problem is b.EMP_ID in table TB_EMPLOYEE contain white space, and got no result at JdbcTemplate but at DBeaver have result (I still don't understand why DBeaver got result), so I fix the query by turn b.EMP_ID IN (:TARGET_EMP) to be trim(b.EMP_ID IN (:TARGET_EMP).

Thank you for all help.


来源: stackexchange

问:
SocketException: OS Error: Connection refused, errno = 111 in flutter using django backend
I m building a flutter app with django rest-framework. The registration api is working fine in Postman but after some successful registration from the flutter app it is showing the above error. The request is been sent on https address.

Removed csrf. Nothing happens.

Request:

```<code>var data = {'email':signupemailidcontroller.text,
            'password1':passwordcontroller.text,
            'password2':confirmpasswordcontroller.text,
           };
        //http request here
        await http.post(websitesignupurl,
                        headers: headers,
                        body: json.encode(data))
          .then((onResponse){
            print(onResponse.body);
          }).catchError((onerror){
            print(onerror.toString());
        });
</code>```

Output in Console:

SocketException: OS Error: Connection refused, errno = 111

I Expect the response of this request to be a Json object containing the user and token.

答:
I know that the question is too old, But I will answer this because this may be helpful to someone who has this problem.

Without more details, I can't give a specific solution. But with following conditions  can give a specific solution

I imagine that the API host was in local computer

I imagine that you use your emulator for running the app

The URL you tried with postman maybe something like this http://127.0.0.1:[port number]/register or http://localhost:[port number]/register. But this may not work with an emulator because it doesn't have access to that URL. To get access to the local host of your you need to find out the host address.

Follow these steps to get your host address.

Click on the three dots(More) in the android emulator

Setting -> Proxy

You can change your host address if you like by selecting `Manual proxy configuration

Then you can see your host name with the port number. Then replace your URL with those like http://10.0.0.2:5000/register.

ContentLicense: CC BY-SA 4.0

Body:
I m building a flutter app with django rest-framework. The registration api is working fine in Postman but after some successful registration from the flutter app it is showing the above error. The request is been sent on https address.

Removed csrf. Nothing happens.

Request:

var data = {'email':signupemailidcontroller.text,
            'password1':passwordcontroller.text,
            'password2':confirmpasswordcontroller.text,
           };
        //http request here
        await http.post(websitesignupurl,
                        headers: headers,
                        body: json.encode(data))
          .then((onResponse){
            print(onResponse.body);
          }).catchError((onerror){
            print(onerror.toString());
        });

Output in Console:

SocketException: OS Error: Connection refused, errno = 111

I Expect the response of this request to be a Json object containing the user and token.


问:
PL/pgSQL: finding all groups person belongs to (also indirectly)
Simple intro:

I have a database with users and groups.
Every user might be a member of one or more groups.
Every group might have one or more parent groups.

Schema:

```<code>CREATE TABLE users(
  username VARCHAR(64) NOT NULL PRIMARY KEY,
  password VARCHAR(64) NOT NULL,
  enabled BOOLEAN NOT NULL);

CREATE TABLE groups (
  id bigserial NOT NULL PRIMARY KEY,
  group_name VARCHAR(64) NOT NULL);

CREATE TABLE groups_inheritance (
  group_id bigint NOT NULL,
  parent_group_id bigint NOT NULL,
  CONSTRAINT fk_group_inheritance_group FOREIGN KEY(group_id) REFERENCES groups(id),
  CONSTRAINT fk_group_inheritance_group_2 FOREIGN KEY(parent_group_id) REFERENCES groups(id),
  CONSTRAINT unique_uk_groups_inheritance UNIQUE(group_id, parent_group_id));

CREATE TABLE group_members (
  id bigint PRIMARY KEY,
  username VARCHAR(64) NOT NULL,
  group_id bigint NOT NULL,
  CONSTRAINT fk_group_members_username FOREIGN KEY(username) REFERENCES users(username),
  CONSTRAINT fk_group_members_group FOREIGN KEY(group_id) REFERENCES groups(id));
</code>```

I'm looking for a PL/pgSQL function which finds all groups (their names) particular user belongs to.

Example:

group name: People,
group parent: null

group name: Students,
group parent: People

group name: Football_players,
group parent: People

group name: Basketball_players,
group parent: People

user name: Maciej,
groups : Students, Football_players

f("Maciej") = {"Students", "People", "Football_players"}

He belongs to "People" just because he belongs to "Students" or "Football_players". He is not a direct member of "People" group.

Thanks in advance!

答:
If you have just one level of inheritance (as in example), then you could use such query:

```<code>WITH group_ids AS
(
    SELECT group_id
    FROM group_members
    WHERE username LIKE 'Maciej'
)
SELECT group_name
FROM
    (SELECT group_id FROM group_ids
        UNION
    SELECT DISTINCT parent_group_id
    FROM groups_inheritance INNER JOIN group_ids USING(group_id)) g
INNER JOIN groups ON id = group_id;
</code>```

Result:

```<code>    group_name
------------------
 People
 Students
 Football_players
(3 rows)
</code>```

PL/pgSQL function:

```<code>DROP FUNCTION IF EXISTS f(varchar(64));
CREATE FUNCTION f(username varchar(64))
RETURNS text[] AS $$
DECLARE
    gId bigint;
    pgId bigint;
    gName text;
    result text[] = '{}';
BEGIN
    FOR gId IN SELECT group_id FROM group_members WHERE username LIKE username
    LOOP
        SELECT INTO gName group_name FROM groupS WHERE id = gId;
        result := result || gName;
        FOR pgId IN SELECT parent_group_id FROM groups_inheritance WHERE group_id = gId
        LOOP
            SELECT INTO gName group_name FROM groups WHERE id = pgId;
            IF NOT (result @> ARRAY[gName]) THEN
                result := result || gName;
            END IF;
        END LOOP;
    END LOOP;
    RETURN result;
END $$
LANGUAGE 'plpgsql';
</code>```

Result:

```<code>SELECT f('Maciej');
                 f
------------------------------------
 {Students,People,Football_players}
(1 row)
</code>```

However for nested parent groups I think that recursion should be suitable.

EDIT:

Here is recursion-based variant for nested parent groups:

```<code>CREATE OR REPLACE FUNCTION f_recursive(gIdParam bigint, resultArrayParam bigint[])
RETURNS bigint[] AS $$
DECLARE
    pgId bigint;
    resultArray bigint[];
BEGIN
    FOR pgId IN SELECT parent_group_id FROM groups_inheritance WHERE group_id = gIdParam
    LOOP
        IF NOT (resultArrayParam @> ARRAY[pgId]) THEN
            resultArray := resultArray || pgId;
            resultArray := resultArray || f_recursive(pgId, resultArray);
        END IF;
    END LOOP;
    RETURN resultArray;
END $$
LANGUAGE 'plpgsql';

CREATE OR REPLACE FUNCTION f(usernameParam varchar(64))
RETURNS text[] AS $$
DECLARE
    gId bigint;
    resultArray bigint[];
BEGIN
    FOR gId IN SELECT group_id FROM group_members WHERE username LIKE usernameParam
    LOOP
        resultArray := resultArray || gId;
        resultArray := resultArray || f_recursive(gId, resultArray);
    END LOOP;
    RETURN array_agg(group_name)
            FROM groups INNER JOIN (SELECT unnest(resultArray)) u ON unnest = id;
END $$
LANGUAGE 'plpgsql';
</code>```

Example insert:

```<code>INSERT INTO groups (id, group_name) VALUES
    (1, 'People'), (2, 'Workers'), (3, 'Programmers'),
    (4, 'AI-Programmers'), (5, 'Administators'), (6, 'Managers');

INSERT INTO groups_inheritance (group_id, parent_group_id) VALUES
    (2, 1), (3, 2), (4, 3), (5, 2), (6, 2);

INSERT INTO users (username, password, enabled) VALUES
    ('Maciej', '12345', true);

INSERT INTO group_members (id, username, group_id) VALUES
    (1, 'Maciej', 4), (2, 'Maciej', 5);
</code>```

Result:

```<code>SELECT f('Maciej');
                             f
-----------------------------------------------------------
 {AI-Programmers,Programmers,Workers,People,Administators}
(1 row)
</code>```

Another way is to use WITH query along with RECURSIVE modifier as @araqnid shown.

ContentLicense: CC BY-SA 3.0

Body:
Simple intro:

I have a database with users and groups.
Every user might be a member of one or more groups.
Every group might have one or more parent groups.

Schema:

CREATE TABLE users(
  username VARCHAR(64) NOT NULL PRIMARY KEY,
  password VARCHAR(64) NOT NULL,
  enabled BOOLEAN NOT NULL);

CREATE TABLE groups (
  id bigserial NOT NULL PRIMARY KEY,
  group_name VARCHAR(64) NOT NULL);

CREATE TABLE groups_inheritance (
  group_id bigint NOT NULL,
  parent_group_id bigint NOT NULL,
  CONSTRAINT fk_group_inheritance_group FOREIGN KEY(group_id) REFERENCES groups(id),
  CONSTRAINT fk_group_inheritance_group_2 FOREIGN KEY(parent_group_id) REFERENCES groups(id),
  CONSTRAINT unique_uk_groups_inheritance UNIQUE(group_id, parent_group_id));

CREATE TABLE group_members (
  id bigint PRIMARY KEY,
  username VARCHAR(64) NOT NULL,
  group_id bigint NOT NULL,
  CONSTRAINT fk_group_members_username FOREIGN KEY(username) REFERENCES users(username),
  CONSTRAINT fk_group_members_group FOREIGN KEY(group_id) REFERENCES groups(id));

I'm looking for a PL/pgSQL function which finds all groups (their names) particular user belongs to.

Example:

group name: People,
group parent: null

group name: Students,
group parent: People

group name: Football_players,
group parent: People

group name: Basketball_players,
group parent: People

user name: Maciej,
groups : Students, Football_players

f("Maciej") = {"Students", "People", "Football_players"}

He belongs to "People" just because he belongs to "Students" or "Football_players". He is not a direct member of "People" group.

Thanks in advance!

Body:
If you have just one level of inheritance (as in example), then you could use such query:

WITH group_ids AS
(
    SELECT group_id
    FROM group_members
    WHERE username LIKE 'Maciej'
)
SELECT group_name
FROM
    (SELECT group_id FROM group_ids
        UNION
    SELECT DISTINCT parent_group_id
    FROM groups_inheritance INNER JOIN group_ids USING(group_id)) g
INNER JOIN groups ON id = group_id;

Result:

    group_name
------------------
 People
 Students
 Football_players
(3 rows)

PL/pgSQL function:

DROP FUNCTION IF EXISTS f(varchar(64));
CREATE FUNCTION f(username varchar(64))
RETURNS text[] AS $$
DECLARE
    gId bigint;
    pgId bigint;
    gName text;
    result text[] = '{}';
BEGIN
    FOR gId IN SELECT group_id FROM group_members WHERE username LIKE username
    LOOP
        SELECT INTO gName group_name FROM groupS WHERE id = gId;
        result := result || gName;
        FOR pgId IN SELECT parent_group_id FROM groups_inheritance WHERE group_id = gId
        LOOP
            SELECT INTO gName group_name FROM groups WHERE id = pgId;
            IF NOT (result @> ARRAY[gName]) THEN
                result := result || gName;
            END IF;
        END LOOP;
    END LOOP;
    RETURN result;
END $$
LANGUAGE 'plpgsql';

Result:

SELECT f('Maciej');
                 f
------------------------------------
 {Students,People,Football_players}
(1 row)

However for nested parent groups I think that recursion should be suitable.

EDIT:

Here is recursion-based variant for nested parent groups:

CREATE OR REPLACE FUNCTION f_recursive(gIdParam bigint, resultArrayParam bigint[])
RETURNS bigint[] AS $$
DECLARE
    pgId bigint;
    resultArray bigint[];
BEGIN
    FOR pgId IN SELECT parent_group_id FROM groups_inheritance WHERE group_id = gIdParam
    LOOP
        IF NOT (resultArrayParam @> ARRAY[pgId]) THEN
            resultArray := resultArray || pgId;
            resultArray := resultArray || f_recursive(pgId, resultArray);
        END IF;
    END LOOP;
    RETURN resultArray;
END $$
LANGUAGE 'plpgsql';

CREATE OR REPLACE FUNCTION f(usernameParam varchar(64))
RETURNS text[] AS $$
DECLARE
    gId bigint;
    resultArray bigint[];
BEGIN
    FOR gId IN SELECT group_id FROM group_members WHERE username LIKE usernameParam
    LOOP
        resultArray := resultArray || gId;
        resultArray := resultArray || f_recursive(gId, resultArray);
    END LOOP;
    RETURN array_agg(group_name)
            FROM groups INNER JOIN (SELECT unnest(resultArray)) u ON unnest = id;
END $$
LANGUAGE 'plpgsql';

Example insert:

INSERT INTO groups (id, group_name) VALUES
    (1, 'People'), (2, 'Workers'), (3, 'Programmers'),
    (4, 'AI-Programmers'), (5, 'Administators'), (6, 'Managers');

INSERT INTO groups_inheritance (group_id, parent_group_id) VALUES
    (2, 1), (3, 2), (4, 3), (5, 2), (6, 2);

INSERT INTO users (username, password, enabled) VALUES
    ('Maciej', '12345', true);

INSERT INTO group_members (id, username, group_id) VALUES
    (1, 'Maciej', 4), (2, 'Maciej', 5);

Result:

SELECT f('Maciej');
                             f
-----------------------------------------------------------
 {AI-Programmers,Programmers,Workers,People,Administators}
(1 row)

Another way is to use WITH query along with RECURSIVE modifier as @araqnid shown.


问:
Live data search using ajax. How to display another query when input is empty
I am trying to create a live search using ajax, jquery, php and mysql.
The user enter some inputs, it send the search to form_livesearch.php. I got that part worked. Else if the input is empty, then display other query. (I need help with this part)

```<code>                 <div id="container" class="col-md-12">
                    <div class="row">
                      <h2>Quick Search</h2>
                      <input class='form-control' type="text" id='live_search' placeholder='Search our inventory'>

                      <br>
                      <br>

                      <h2 class="" id="searchresult">
                      </h2>
                    </div>
                  </div>

    $(document).ready(function(){

       $("#live_search").keyup(function(){

            var input = $(this).val();

            if(input != ""){

                $.ajax({

                    url:"form_livesearch.php",
                    method:"POST",
                    data:{input:input},

                    success:function(data){

                        $("#searchresult").html(data);
                        $("#searchresult").css("display","block");

                    }

                });

            } else {

                 // If the input field is empty
                 // How display another php query here?

            }

       });

   });
</code>```

Here is the php and mysql I am trying to display when the input field is empty.

```<code>    <?php

    $query = "SELECT * FROM `my_db` . `my_table` WHERE s_category = 'policy' ORDER BY id ASC";

    $result = mysqli_query($db,$query);

    if(!$result){

        die("Query Failed " . mysqli_error($db));

    }

    if(mysqli_num_rows($result) > 0){
    ?>

       <h3>Policies</h3>
            <ul>

               <?php

                    while($row = mysqli_fetch_assoc($result)){

                        $id = $row['id'];
                        $s_url = $row['s_url'];
                        $s_name = $row['s_name'];
                        $s_category = $row['s_category'];

                        ?>

                            <li><a href="<?php echo $s_url ?>"><?php echo $s_name?></a> <img src="https://www.xxxxxxx.xxx/xxxx/images/pdf.gif" alt="PDF"></li>

                        <?php
                    }
               ?>

            </ul>

       <?php

    }

?>
</code>```

form_livesearch.php:

```<code>if(isset($_POST['input'])){

$input = $_POST['input'];

    //to prevent from mysqli injection
    // x'='x
    $input = stripcslashes($input);
    $input = mysqli_real_escape_string($db, $input);

    $input = str_replace('%', ' @', $input);
    $input = str_replace("'", ' @', $input);

    $query = "SELECT * FROM `my_db` . `my_table` WHERE s_name LIKE '%{$input}%' ORDER BY id ASC";

    $result = mysqli_query($db,$query);

    if(mysqli_num_rows($result) > 0){?>

       <table class="table table-bordered table-striped mt-4">
<!--
           <thead>
               <tr>
                   <th>id</th>
                   <th>name</th>
               </tr>
           </thead>
-->
           <tbody>
               <?php

                while($row = mysqli_fetch_assoc($result)){

                    $id = $row['id'];
                    $s_url = $row['s_url'];
                    $s_name = $row['s_name'];
                    $s_category = $row['s_category'];

                    ?>

                    <tr>
                        <td style="font-size: 14px;"><a href="<?php echo $s_url; ?>"><?php echo $s_name;?></a> <img src="https://www.xxxxx.xxxx/xxxxx/images/pdf.gif" alt="PDF"></td>
                    </tr>

                    <?php
                }

            ?>
       </tbody>
   </table>

   <?php

}else{

    echo "<h6 class='text-danger text-center mt-3'>No data Found</h6>";
}

}

?>
</code>```

答:
You should handle this stuff in the PHP file. and by the way, the input can not be empty as you put the ajax in keyup event.
it just happened when the user use the backspace to delete what he search.

So the form_livesearch.php PHP file should be something like this.

```<code><?php

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

$output = "";
if(isset($_POST['input'])){

    $input = $_POST['input'];
    if(!empty($input)){

        $input = str_replace('%', ' @', $input);
        $input = str_replace("'", ' @', $input);

        $input = "%$input%"; // prepare the $input variable
        $query = "SELECT * FROM `my_db` . `my_table` WHERE s_name LIKE ? ORDER BY id ASC";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("s", $input); // here we can use only a variable
        $stmt->execute();

    }else{
        $query = "SELECT * FROM `my_db` . `my_table` WHERE s_category = 'policy' ORDER BY id ASC";
        $stmt = $conn->prepare($query);
        $stmt->execute();
    }

    $result = $stmt->get_result(); // get the mysqli result

    if($result->num_rows > 0){

        if(empty($input))
            $output = '<table class="table table-bordered table-striped mt-4"><tbody>';
        else
            $output = '<h3>Policies</h3><ul>';

                while($row = $result->fetch_assoc()){

                    $id = $row['id'];
                    $s_url = $row['s_url'];
                    $s_name = $row['s_name'];
                    $s_category = $row['s_category'];

                    if(empty($input))
                        $output .= '
                            <tr>
                                <td style="font-size: 14px;"><a href="' . $s_url . '">' . $s_name .'</a> <img src="https://www.xxxxx.xxxx/xxxxx/images/pdf.gif" alt="PDF"></td>
                            </tr>';
                    else
                        $output .= '<li><a href="' . $s_url . '">' . $s_name . '</a> <img src="https://www.xxxxxxx.xxx/xxxx/images/pdf.gif" alt="PDF"></li>';

                }

        if(empty($input))
            $output .= '</tbody></table>';
        else
            $output .= '</ul>';

        echo $output;

    }else{

        echo "<h6 class='text-danger text-center mt-3'>No data Found</h6>";
    }

}

?>
</code>```

You can use a separate file to handle 2 types but as they are all about products it's better to have one file.

It's a good practice to return the data and let the frontend build the HTML output but if you want to build HTML in the PHP file, it's better to wrap them in a string.

Also, use the prepare statement of MySQLi to prevent SQL injection. take a look at this example for more information.

And the html file should be something like this:

```<code><div id="container" class="col-md-12">
    <div class="row">
      <h2>Quick Search</h2>
      <input class='form-control' type="text" id='live_search' placeholder='Search our inventory'>

      <br>
      <br>

      <h2 class="" id="searchresult">
      </h2>
    </div>
  </div>

<script type="text/javascript">
    $(document).ready(function(){
    // will execute once the page load
       getData();
       $("#live_search").keyup(function(){

            let input = $(this).val();
            getData(input);

       });
   });

function getData(input = ''){

    $.ajax({

        url:"form_livesearch.php",
        method:"POST",
        data:{input:input},

        success:function(data){

            $("#searchresult").html(data);
            $("#searchresult").css("display","block");

        }

    });

}
</script>
</code>```

Body:
I am trying to create a live search using ajax, jquery, php and mysql.
The user enter some inputs, it send the search to form_livesearch.php. I got that part worked. Else if the input is empty, then display other query. (I need help with this part)

Quick Search

                      <input class='form-control' type="text" id='live_search' placeholder='Search our inventory'>

    $(document).ready(function(){

       $("#live_search").keyup(function(){

            var input = $(this).val();

            if(input != ""){

                $.ajax({

                    url:"form_livesearch.php",
                    method:"POST",
                    data:{input:input},

                    success:function(data){

                        $("#searchresult").html(data);
                        $("#searchresult").css("display","block");

                    }

                });

            } else {

                 // If the input field is empty
                 // How display another php query here?

            }

       });

   });

Here is the php and mysql I am trying to display when the input field is empty.

    <?php

    $query = "SELECT * FROM `my_db` . `my_table` WHERE s_category = 'policy' ORDER BY id ASC";

    $result = mysqli_query($db,$query);

    if(!$result){

        die("Query Failed " . mysqli_error($db));

    }

    if(mysqli_num_rows($result) > 0){
    ?>

Policies

               <?php

                    while($row = mysqli_fetch_assoc($result)){

                        $id = $row['id'];
                        $s_url = $row['s_url'];
                        $s_name = $row['s_name'];
                        $s_category = $row['s_category'];

                        ?>

<a href="<?php echo $s_url ?>"><?php echo $s_name?>

                        <?php
                    }
               ?>

       <?php

    }

?>

form_livesearch.php:

if(isset($_POST['input'])){

$input = $_POST['input'];

    //to prevent from mysqli injection
    // x'='x
    $input = stripcslashes($input);
    $input = mysqli_real_escape_string($db, $input);

    $input = str_replace('%', ' @', $input);
    $input = str_replace("'", ' @', $input);

    $query = "SELECT * FROM `my_db` . `my_table` WHERE s_name LIKE '%{$input}%' ORDER BY id ASC";

    $result = mysqli_query($db,$query);

    if(mysqli_num_rows($result) > 0){?>

               <?php

                while($row = mysqli_fetch_assoc($result)){

                    $id = $row['id'];
                    $s_url = $row['s_url'];
                    $s_name = $row['s_name'];
                    $s_category = $row['s_category'];

                    ?>

                        <a href="<?php echo $s_url; ?>"><?php echo $s_name;?>

                    <?php
                }

            ?>

   <?php

}else{

    echo "
No data Found
";
}

}

?>

Body:
You should handle this stuff in the PHP file. and by the way, the input can not be empty as you put the ajax in keyup event.
it just happened when the user use the backspace to delete what he search.

So the form_livesearch.php PHP file should be something like this.

<?php

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

$output = "";
if(isset($_POST['input'])){

    $input = $_POST['input'];
    if(!empty($input)){

        $input = str_replace('%', ' @', $input);
        $input = str_replace("'", ' @', $input);

        $input = "%$input%"; // prepare the $input variable
        $query = "SELECT * FROM `my_db` . `my_table` WHERE s_name LIKE ? ORDER BY id ASC";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("s", $input); // here we can use only a variable
        $stmt->execute();

    }else{
        $query = "SELECT * FROM `my_db` . `my_table` WHERE s_category = 'policy' ORDER BY id ASC";
        $stmt = $conn->prepare($query);
        $stmt->execute();
    }

    $result = $stmt->get_result(); // get the mysqli result

    if($result->num_rows > 0){

        if(empty($input))
            $output = '<table class="table table-bordered table-striped mt-4"><tbody>';
        else
            $output = '<h3>Policies</h3><ul>';

                while($row = $result->fetch_assoc()){

                    $id = $row['id'];
                    $s_url = $row['s_url'];
                    $s_name = $row['s_name'];
                    $s_category = $row['s_category'];

                    if(empty($input))
                        $output .= '
                            <tr>
                                <td style="font-size: 14px;"><a href="' . $s_url . '">' . $s_name .'</a> <img src="https://www.xxxxx.xxxx/xxxxx/images/pdf.gif" alt="PDF"></td>
                            </tr>';
                    else
                        $output .= '<li><a href="' . $s_url . '">' . $s_name . '</a> <img src="https://www.xxxxxxx.xxx/xxxx/images/pdf.gif" alt="PDF"></li>';

                }

        if(empty($input))
            $output .= '</tbody></table>';
        else
            $output .= '</ul>';

        echo $output;

    }else{

        echo "<h6 class='text-danger text-center mt-3'>No data Found</h6>";
    }

}

?>

You can use a separate file to handle 2 types but as they are all about products it's better to have one file.

It's a good practice to return the data and let the frontend build the HTML output but if you want to build HTML in the PHP file, it's better to wrap them in a string.

Also, use the prepare statement of MySQLi to prevent SQL injection. take a look at this example for more information.

And the html file should be something like this:

<div id="container" class="col-md-12">
    <div class="row">
      <h2>Quick Search</h2>
      <input class='form-control' type="text" id='live_search' placeholder='Search our inventory'>

      <br>
      <br>

      <h2 class="" id="searchresult">
      </h2>
    </div>
  </div>

<script type="text/javascript">
    $(document).ready(function(){
    // will execute once the page load
       getData();
       $("#live_search").keyup(function(){

            let input = $(this).val();
            getData(input);

       });
   });

function getData(input = ''){

    $.ajax({

        url:"form_livesearch.php",
        method:"POST",
        data:{input:input},

        success:function(data){

            $("#searchresult").html(data);
            $("#searchresult").css("display","block");

        }

    });

}
</script>


问:
antlr alias not working in other directories
I am trying to get started with antlr4.

I followed the installation tutorial from their website step by step including writing the following command:

```<code>alias antlr4='java -Xmx500M -cp "/usr/local/lib/antlr-4.9.2-complete.jar:$CLASSPATH" org.antlr.v4.Tool'
</code>```

I created two Hello.g4 files, one in usr/local/lib and one in my Desktop. When I run

```<code>antlr4 Hello.g4
</code>```

in lib, it works just fine. However, when I run it in the Desktop, I get

```<code>antlr4: command not found
</code>```

答: The alias is valid only in the current session. You may need to write the first command to ~/.bashrc (depending on your system).</p>

Body:
I am trying to get started with antlr4.

I followed the installation tutorial from their website step by step including writing the following command:

alias antlr4='java -Xmx500M -cp "/usr/local/lib/antlr-4.9.2-complete.jar:$CLASSPATH" org.antlr.v4.Tool'

I created two Hello.g4 files, one in usr/local/lib and one in my Desktop. When I run

antlr4 Hello.g4

in lib, it works just fine. However, when I run it in the Desktop, I get

antlr4: command not found


问:
Serverless framework/Cloudformation: deploying Kinesis trigger with DLQ
I'm trying to deploy a lambda on AWS with Serverless which has a Kinesis data stream as a trigger. I'm also wanting to define that any failed messages raised by the lambda are sent to a Dead Letter queue.

I couldn't find an example of how to do this in the Serverless documentation, but I found what I thought was how to do it at https://betterdev.blog/aws-lambda-kinesis-trigger-pitfalls/.

I have created a Serverless file where the lambda target looks like this:

```<code>my_lambda:
    handler: src/lambdas/my_lambda.lambda_handler
    name: my_lambda
    memorySize: 256
    timeout: 28
    package:
        patterns:
          - 'src/lambdas/my_lambda.py'
    role: MyLambdaRole # Defined in a separate file.
    events:
        - stream:
            type: kinesis
            arn: ${self:custom.MY_KINESIS_DATA_STREAM_ARN} # ARN of Kinesis data stream.
            batchSize: 100
            maximumRetryAttempts: 10
            startingPosition: LATEST
            enabled: false
            destinations:
                onFailure:
                    type: sqs
                    arn: ${self:custom.MY_DLQ_ARN} # ARN of SQS DLQ.
    environment:
        ....
    tags:
        ....
</code>```

When I try and deploy, I get this error:

```<code>TypeError: Cannot read property 'replace' of undefined
  at Object.normalizeNameToAlphaNumericOnly (/usr/local/lib/node_modules/serverless/lib/plugins/aws/lib/naming.js:32:36)
  at Object.getStreamLogicalId (/usr/local/lib/node_modules/serverless/lib/plugins/aws/lib/naming.js:372:14)
  at functionObj.events.forEach (/usr/local/lib/node_modules/serverless/lib/plugins/aws/package/compile/events/stream.js:184:58)
  at Array.forEach (<anonymous>)
  at serverless.service.getAllFunctions.forEach (/usr/local/lib/node_modules/serverless/lib/plugins/aws/package/compile/events/stream.js:143:28)
  at Array.forEach (<anonymous>)
  at AwsCompileStreamEvents.compileStreamEvents (/usr/local/lib/node_modules/serverless/lib/plugins/aws/package/compile/events/stream.js:93:47)
  at PluginManager.invoke (/usr/local/lib/node_modules/serverless/lib/classes/PluginManager.js:579:20)
</code>```

The message isn't helpful in identifying what the issue is. Could anyone suggest what the problem might be, please?

Thank you in advance for any assistance.

答: Fixed: my Kinesis data stream ARN was incorrect.</p>

Body:
I'm trying to deploy a lambda on AWS with Serverless which has a Kinesis data stream as a trigger. I'm also wanting to define that any failed messages raised by the lambda are sent to a Dead Letter queue.

I couldn't find an example of how to do this in the Serverless documentation, but I found what I thought was how to do it at https://betterdev.blog/aws-lambda-kinesis-trigger-pitfalls/.

I have created a Serverless file where the lambda target looks like this:

my_lambda:
    handler: src/lambdas/my_lambda.lambda_handler
    name: my_lambda
    memorySize: 256
    timeout: 28
    package:
        patterns:
          - 'src/lambdas/my_lambda.py'
    role: MyLambdaRole # Defined in a separate file.
    events:
        - stream:
            type: kinesis
            arn: ${self:custom.MY_KINESIS_DATA_STREAM_ARN} # ARN of Kinesis data stream.
            batchSize: 100
            maximumRetryAttempts: 10
            startingPosition: LATEST
            enabled: false
            destinations:
                onFailure:
                    type: sqs
                    arn: ${self:custom.MY_DLQ_ARN} # ARN of SQS DLQ.
    environment:
        ....
    tags:
        ....

When I try and deploy, I get this error:

TypeError: Cannot read property 'replace' of undefined
  at Object.normalizeNameToAlphaNumericOnly (/usr/local/lib/node_modules/serverless/lib/plugins/aws/lib/naming.js:32:36)
  at Object.getStreamLogicalId (/usr/local/lib/node_modules/serverless/lib/plugins/aws/lib/naming.js:372:14)
  at functionObj.events.forEach (/usr/local/lib/node_modules/serverless/lib/plugins/aws/package/compile/events/stream.js:184:58)
  at Array.forEach (<anonymous>)
  at serverless.service.getAllFunctions.forEach (/usr/local/lib/node_modules/serverless/lib/plugins/aws/package/compile/events/stream.js:143:28)
  at Array.forEach (<anonymous>)
  at AwsCompileStreamEvents.compileStreamEvents (/usr/local/lib/node_modules/serverless/lib/plugins/aws/package/compile/events/stream.js:93:47)
  at PluginManager.invoke (/usr/local/lib/node_modules/serverless/lib/classes/PluginManager.js:579:20)

The message isn't helpful in identifying what the issue is. Could anyone suggest what the problem might be, please?

Thank you in advance for any assistance.


问:
Angular5:HTML input file selection event not firing upon selecting the same file
In my angular5 File upload is a trigger onchange event, but when I select the same file twice it's not selected.

My problem similar to this HTML input file selection event not firing upon selecting the same file

```<code><input type="file" class="upload-file" onclick="this.value=null"  (change)="handleFileInput($event.target.files,'doc')">
</code>```

but its not working

答:
```<code><input #fileInput type="file" id="fileid" (click)="fileInput.value = null" value="" (change)="handleFileInput($event)" >
</code>```

every time you click on file input it will clear its value so even if you select the same file (change) will fire.

Body:
In my angular5 File upload is a trigger onchange event, but when I select the same file twice it's not selected.

My problem similar to this HTML input file selection event not firing upon selecting the same file

<input type="file" class="upload-file" onclick="this.value=null"  (change)="handleFileInput($event.target.files,'doc')">

but its not working

Body:
<input #fileInput type="file" id="fileid" (click)="fileInput.value = null" value="" (change)="handleFileInput($event)" >

every time you click on file input it will clear its value so even if you select the same file (change) will fire.


问:
Examples of compiled programming languages with modern features for the real world [please vote for reopen]
Apart from C, C++, Delphi, VB, can you put an example of a relatively "modern" COMPILED* programming language* supporting things like OO, collections, GUI libraries?
Please do not mention experimental or academic only languages, I'm looking for something used in the real world, for PCs 80x86, and I don't mind about the OS.

Thanks!

*UPDATED: Compiled to native code.

*DISCLAIMER:

For language understand language implementation.

For compiled to native code understand not interpreted.

答:
Haskell.

Source: http://www.realworldhaskell.org/


问:
moving from GoogleMobileAds.framework to xcframework error
I changed my framework references from MobileAds.framework to xcframework following the instructions(manual) at https://developers.google.com/admob/ios/quick-start.

But for some reason I get the error as shown below. I cleared the cache. Even tried adding a new simulator. It still says the same. Can someone please help?
I am on Mac OS Catalina and Xcode 12.4. Cannot upgrade my OS or Xcode anymore.I am also unable to run the app on any of my devices. This app has been running fine, it was time to do minor UI color changes so nothing else has changed in the code.

Failed to load Info.plist from bundle at path /Users/User1/Library/Developer/CoreSimulator/Devices/8AF69E5B-FD16-4C80-B9F5-DE4A4A0B78BA/data/Library/Caches/com.apple.mobile.installd.staging/temp.8rg85u/extracted/Myapp.app/Frameworks/GoogleMobileAds.framework; Extra info about Info.plist: Couldn't stat /Users/User1/Library/Developer/CoreSimulator/Devices/8AF69E5B-FD16-4C80-B9F5-DE4A4A0B78BA/data/Library/Caches/com.apple.mobile.installd.staging/temp.8rg85u/extracted/Myapp.app/Frameworks/GoogleMobileAds.framework/Info.plist: No such file or directory

答: Finally found the solution. Target->Frameworks->All Google admob related frameworks had "Embed and sign" selected, made them "Do not embed" and the app is running.</p>


问:
FileNotFoundError in Python Visul Studio
I get this when I try to run my python project code

with open("config.json", "r") as f:
```
<p>Exception raised:</p>
<pre class="lang-py prettyprint-override"><code>FileNotFoundError: [Errno 2] No such file or directory: 'config.json'
</code>```

what is a solution for this?

here is a screenshot of the code and everything.

答:
As shown in the screenshot of the IDE, you should exactly point out where the .json file. Now the json file and python code are not located in the same folder.

FYI, there are two types of path, absolute path and relative path. Please see https://www.kite.com/python/answers/how-to-find-the-absolute-and-relative-path-of-a-file-in-pythonhttps://www.kite.com/python/answers/how-to-find-the-absolute-and-relative-path-of-a-file-in-python

with open("/file program/config.json", "r") as f
    content = f.read()
    # do something
```

Or, just move out the config.json file to the folder, which the python code is located.

Body:
I get this when I try to run my python project code

with open("config.json", "r") as f:

Exception raised:

FileNotFoundError: [Errno 2] No such file or directory: 'config.json'

what is a solution for this?

here is a screenshot of the code and everything.

Body:
As shown in the screenshot of the IDE, you should exactly point out where the .json file. Now the json file and python code are not located in the same folder.

FYI, there are two types of path, absolute path and relative path. Please see https://www.kite.com/python/answers/how-to-find-the-absolute-and-relative-path-of-a-file-in-pythonhttps://www.kite.com/python/answers/how-to-find-the-absolute-and-relative-path-of-a-file-in-python

with open("/file program/config.json", "r") as f
    content = f.read()
    # do something

Or, just move out the config.json file to the folder, which the python code is located.


问:
How to redirect if slug contains certain word?
I'd like to redirect if my slug contains /product-category/. So for example...

www.mysite.com/product-category/ ---> redirect to www.mysite.com/shop

Is this possible?

答:
Add this in functions.php

```<code>function curPageURL() {

$pageURL = 'http';

if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}

$pageURL .= "://";

if ($_SERVER["SERVER_PORT"] != "80") {

    $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];

} else {

    $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];

}

return $pageURL;  }
</code>```

Then add the following in header.php

```<code>$url = curPageURL();
$url_array = explode("/", $url);
if(in_array("product-category",$url_array))
{ header("Location:www.mysite.com/shop"); }
</code>```

Body:
Add this in functions.php

function curPageURL() {

$pageURL = 'http';

if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}

$pageURL .= "://";

if ($_SERVER["SERVER_PORT"] != "80") {

    $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];

} else {

    $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];

}

return $pageURL;  }

Then add the following in header.php

$url = curPageURL();
$url_array = explode("/", $url);
if(in_array("product-category",$url_array))
{ header("Location:www.mysite.com/shop"); }


问:
Can IIS supporting ASP.NET and WAMP supporting PHP coexist on the same server?
Can IIS supporting ASP.NET and WAMP supporting PHP coexist on the same server?

We already have a WAMP stack setup on a Windows Server 2003 box to support some internal PHP applications, and I want to also setup CI Factory on that box which will try to configure IIS to support it's ASP.NET based dashboard.  I want to make sure that there isn't a big chance of fubarring the WAMP stack that is already there.  Will it be smart enough to handle *.PHP through Apache and *.aspx through IIS ?

Edit: Is there a way to get this to work on the same port?

答: Yes.  Both will run under IIS in a Windows server.</p>

OwnerDisplayName: aaronls

LastEditorDisplayName: aaronls

OwnerDisplayName: schooner

ContentLicense: CC BY-SA 2.5


问:
How to draw with CSS canvas a slideshow frame?
I have 2 slideshows which should look like this. The user will upload the photos via a Wordpress gallery so I can't cut them up to make them transparent (plus I don't really know how). I've already posted a question here on how I may achieve this and one user was kind enough to tell me that I have 2 options: webkit mask and canvas; canvas being the recommended option because of better browser support.

For the past hour I've been searching on the Internet on how to draw with canvas but I've had no luck...

Could you please direct me to a tutorial that's easy to follow or give me some pointers?

Thank you!!

答:
Definetely MDN's docs are better adopted to that activity, however if you want to get some valuable pieces of advice you can go and visit this website http://www.canvascolour.co.uk/
Ask them your question they may be able to give you the right solution.

;)


问:
How to change permission of a kvm-qemu serial console output log
I have a virtual machine with this config to redirect serial console log to another file:

```<code><devices>
   ...
   <console type="pty">
       <target type="sclp"/>
       <log file="/home/nptusk/serial-console.log" append="on"/>
   </console>
</devices>
</code>```

For automation reasons I want the log to have the permission other than root:root. What can I do to achieve this without using chown afterwards, in other words the log file when generated already has my desired user and group.

答: Kvm deamon is running on root.Otherwise it changes its uid,there is no way to change owner.But you can change its permssion to 665 or 664 so that you can access it,or change its ACL for more security</p>

Body:
I have a virtual machine with this config to redirect serial console log to another file:

<devices>
   ...
   <console type="pty">
       <target type="sclp"/>
       <log file="/home/nptusk/serial-console.log" append="on"/>
   </console>
</devices>

For automation reasons I want the log to have the permission other than root:root. What can I do to achieve this without using chown afterwards, in other words the log file when generated already has my desired user and group.


问:
SQL insert from select, but set some values by hand
Let's say that I have table with A LOT of columns. I have one column with primary key that has autoincrement set to 1. I want to insert a new row and in this new row I have following requirements:

The row must have generated ID

All non-specified columns have to be copied from row with id='9999'

I have to be able to set some values of columns by hand (for example columns name and age

I have tried:

```<code>Insert Into demo_table
  Select * From demo_table Where id='9999';
</code>```

However, I get this error:

An explicit value for the identity column in table 'demo_table' can only be specified when a column list is used and IDENTITY_INSERT is ON.

What do I need:

I want to duplicate a row -> let the id be set by database (I have PK and autoincrement configured) -> set some columns by hand -> have other column's values duplicated, without specifying column names (as I have a lot of columns and their names could change in future.)

Form of solution:

I would prefer if I was able to achive this using only one query. If necessary, I have stored procedures available.

My question:

Is this even possible? How could I achive such query/procedure?

答:
For anyone interested, how I've solved this problem:

After I've read your comments (thanks btw) and some threads online, I've realized why I cannot do what I asked. However, I've come seen solution to similar problem somewhere, where they wanted to select * except one specific column, they solved it like this:

copied the entire table

selected from there.

I've come up with similar solution to my problem

```<code>-- check data, remove after testing
select * from demo_table order by ID desc;

-- create table with one column I want to duplicate
select * into Temp_demo_table from demo_table where ID=9999;

-- drop id, so it does not get included in the inter-table insert
alter table Temp_demo_table
    drop column ID;

-- update columns that I need to modify, doesn't have to have WHERE clause, becuase there's only one row there
update Temp_demo_table set MyCustomProperty='abc', name=NULL, age=NULL

-- insert the desired and edited row
insert into demo_table
    select * from Temp_demo_table;

-- drop the temp table
drop table Temp_demo_table;

-- check data, remove after testing
select * from demo_table order by ID desc;
</code>```

I realize how inefficient this is, however the function (on my api) executing this command will not be called so often (max 100 times per day). I believe that this query could be optimized, however I do not have sufficient knowledge to do it at this moment (100% going to put it in my TODO :D).

Edit-1:

Just found out that you can write queries in oracle db like this:

(select * from demo_table) - (select name, age from demo_table)
```

I currentlly don't know if I can apply this to sql server, however as soon as I have an access to mssql, I'll try it out and keep this answear updated!

Body:
Let's say that I have table with A LOT of columns. I have one column with primary key that has autoincrement set to 1. I want to insert a new row and in this new row I have following requirements:

The row must have generated ID

All non-specified columns have to be copied from row with id='9999'

I have to be able to set some values of columns by hand (for example columns name and age

I have tried:

Insert Into demo_table
  Select * From demo_table Where id='9999';

However, I get this error:

An explicit value for the identity column in table 'demo_table' can only be specified when a column list is used and IDENTITY_INSERT is ON.

What do I need:

I want to duplicate a row -> let the id be set by database (I have PK and autoincrement configured) -> set some columns by hand -> have other column's values duplicated, without specifying column names (as I have a lot of columns and their names could change in future.)

Form of solution:

I would prefer if I was able to achive this using only one query. If necessary, I have stored procedures available.

My question:

Is this even possible? How could I achive such query/procedure?

Body:
For anyone interested, how I've solved this problem:

After I've read your comments (thanks btw) and some threads online, I've realized why I cannot do what I asked. However, I've come seen solution to similar problem somewhere, where they wanted to select * except one specific column, they solved it like this:

copied the entire table

selected from there.

I've come up with similar solution to my problem

-- check data, remove after testing
select * from demo_table order by ID desc;

-- create table with one column I want to duplicate
select * into Temp_demo_table from demo_table where ID=9999;

-- drop id, so it does not get included in the inter-table insert
alter table Temp_demo_table
    drop column ID;

-- update columns that I need to modify, doesn't have to have WHERE clause, becuase there's only one row there
update Temp_demo_table set MyCustomProperty='abc', name=NULL, age=NULL

-- insert the desired and edited row
insert into demo_table
    select * from Temp_demo_table;

-- drop the temp table
drop table Temp_demo_table;

-- check data, remove after testing
select * from demo_table order by ID desc;

I realize how inefficient this is, however the function (on my api) executing this command will not be called so often (max 100 times per day). I believe that this query could be optimized, however I do not have sufficient knowledge to do it at this moment (100% going to put it in my TODO :D).

Edit-1:

Just found out that you can write queries in oracle db like this:

(select * from demo_table) - (select name, age from demo_table)

I currentlly don't know if I can apply this to sql server, however as soon as I have an access to mssql, I'll try it out and keep this answear updated!


问:
Re-format table, placing multiple column headers as rows
I have a table of fishing catches, showing number of fish and total kg, for all the fishing days. Current format of the data is showing as below

In the other reference table is a list of all the official fish species with codes and names.

How can I re-format the first table so the rows are repeated for each day showing a certain species with the corresponding total catches and kgs in a row. So instead of the species kg and n having their different columns, I would have them in rows while there is only one n and kg column.  I am thinking of looping through the list of all species and based on the numbers it will duplicate the rows in a way with the right values of n and kg of the species in the rows. This is the final format I need. My database is SQL Server.

答:
You may use a union query here:

SELECT Day, 'Albacore' AS Species, ALB_n AS n, ALB_kg AS kg FROM yourTable
UNION ALL
SELECT Day, 'Big eye tuna', BET_n, BET_kg FROM yourTable
UNION ALL
SELECT Day, 'Sword fish', SWO_n, SWO_kg FROM yourTable
ORDER BY Day, Species;
```


问:
Unable to import Pandas on Replit.com - Python
I'm unable to import pandas with import pandas as pd on replit.
I've already installed the package with pip install pandas and it can be seen in packages. I've successfully imported it to other projects on replit. Every time I try importing it into my code on this project, it gives me the following error:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import pandas as pd
  File "/home/runner/thing/venv/lib/python3.8/site-packages/pandas/__init__.py", line 16, in <module>
    raise ImportError(
ImportError: Unable to import required dependencies:
numpy:

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the numpy C-extensions failed. This error can happen for
many reasons, often due to issues with your setup or how NumPy was
installed.

We have compiled some common reasons and troubleshooting tips at:

    https://numpy.org/devdocs/user/troubleshooting-importerror.html

Please note and check the following:

  * The Python version is: Python3.8 from "/home/runner/thing/venv/bin/python"
  * The NumPy version is: "1.22.2"

and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.

Original error was: libz.so.1: cannot open shared object file: No such file or directory
```

答:
You don't need to use pip to install packages on repl.it -- and in fact, you shouldn't! Using Nix derivations not only works better (as you're using their OS distro the way it's designed), but also keeps their storage costs low, by allowing packages to be used from a read-only, hash-addressed, shared store.

Binaries built for other distributions might assume that there will be libraries in /lib, /usr/lib, or the like, but that's not how NixOS works: Libraries will be in a path like /nix/store/<hash>-<packagename>-<version>/lib, and those paths get embedded into the executables that use those libraries.

The easiest thing to do here is to create a new bash repl, but to add a Python interpreter to it. (I suggest this instead of using a Python repl because the way they have their Python REPLs set up adds a bunch of extra tools that need to be reconfigured; a bash repl keeps it simple).

Create a new bash repl.

Click on the three-dots menu.

Select "Show Hidden Files".

Open the file named replit.nix

Edit the file by adding a Python interpreter with pandas, as follows:

{ pkgs }: {
    deps = [
        pkgs.bashInteractive
        (pkgs.python38.withPackages (p: [p.pandas]))
    ];
}
```
...changing that to taste (as long as they're getting software from a channel that has binaries for Python 3.9 or 3.10, for example, you can change python38 to python39 or python310).

Click the "run" button

In the new shell that opens, run python, and see that you can import pandas without trouble.

If, after you add a Python file to your repl, you can also change the .replit hidden file to make it run that file automatically on startup. Note that on NixOS, you should use #!/usr/bin/env python as your shebang, as PATH lookups are essential.

Body:
You don't need to use pip to install packages on repl.it -- and in fact, you shouldn't! Using Nix derivations not only works better (as you're using their OS distro the way it's designed), but also keeps their storage costs low, by allowing packages to be used from a read-only, hash-addressed, shared store.

Binaries built for other distributions might assume that there will be libraries in /lib, /usr/lib, or the like, but that's not how NixOS works: Libraries will be in a path like /nix/store/<hash>-<packagename>-<version>/lib, and those paths get embedded into the executables that use those libraries.

The easiest thing to do here is to create a new bash repl, but to add a Python interpreter to it. (I suggest this instead of using a Python repl because the way they have their Python REPLs set up adds a bunch of extra tools that need to be reconfigured; a bash repl keeps it simple).

Create a new bash repl.

Click on the three-dots menu.

Select "Show Hidden Files".

Open the file named replit.nix

Edit the file by adding a Python interpreter with pandas, as follows:

{ pkgs }: {
    deps = [
        pkgs.bashInteractive
        (pkgs.python38.withPackages (p: [p.pandas]))
    ];
}

...changing that to taste (as long as they're getting software from a channel that has binaries for Python 3.9 or 3.10, for example, you can change python38 to python39 or python310).

Click the "run" button

In the new shell that opens, run python, and see that you can import pandas without trouble.

If, after you add a Python file to your repl, you can also change the .replit hidden file to make it run that file automatically on startup. Note that on NixOS, you should use #!/usr/bin/env python as your shebang, as PATH lookups are essential.


问:
Flutter StreamBuilder to monitor for Firebase Auth state
When I have a logged user, my wrapper check for additional data and once find it will open the HomeScreen of my application.

However, the Stream Builder does not return the SignIn screen even if user successfully logout.

As I can see the Home page is built in a different tree (but how to build it in the main tree?), don't know if this should interfere.

Main code:

```<code>void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (kIsWeb) {
    await Firebase.initializeApp(),
    );
  } else {
    await Firebase.initializeApp();
  }
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        Provider<AuthService>(
          create: (_) => AuthService(),
        ),
      ],
      child: GestureDetector(
        onTap: () {
          FocusScopeNode currentFocus = FocusScope.of(context);
          if (!currentFocus.hasPrimaryFocus) {
            FocusScope.of(context).requestFocus(FocusNode());
          }
        },
        child: MaterialApp(
          theme: ThemeData(
            primaryColor: appColor,
            primaryColorLight: appColor,
            primaryColorDark: appColor,
          ),
          debugShowCheckedModeBanner: false,
          title: 'WhyBye',
          //todo: Queste righe saranno necessarie quando avremo anche la versione WEB
          // home: ResponsiveLayout(
          //     webScreenLayout: WebScreenLayout(),
          //     mobileScreenLayout: MobileScreenLayout()),
          //todo.

          initialRoute: '/wrapper',
          routes: {
            '/wrapper': (context) => const Wrapper(),
            '/signInScreen': (context) => const SignInScreen(),
            '/signUpScreen': (context) => const SignUpScreen(),
            '/registrationScreen': (context) => const RegistrationScreen(),
            '/homeScreen': (context) => const HomeScreen(),
            '/recoverPasswordScreen': (context) =>
                const RecoverPasswordScreen(),
          },
        ),
      ),
    );
  }
}
</code>```

My Wrapper code:

```<code>class Wrapper extends StatelessWidget {
  const Wrapper({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final authService = Provider.of<AuthService>(context);
    return StreamBuilder<User?>(
      stream: authService.user,
      builder: (_, AsyncSnapshot<User?> snapshot) {
        if (snapshot.connectionState == ConnectionState.active) {
          final User? user = snapshot.data;
          //return user == null ? const SignInScreen() : const HomeScreen();
          if (user == null) {
            return const SignInScreen();
          } else {
            WidgetsBinding.instance
                ?.addPostFrameCallback((_) => asyncMethod(context));
            return const Scaffold(
              body: Center(
                child: CircularProgressIndicator(
                  color: appBarColor,
                ),
              ),
            );
          }
        } else {
          return const Scaffold(
            body: Center(
              child: CircularProgressIndicator(
                color: appBarColor,
              ),
            ),
          );
        }
      },
    );
  }
}

void asyncMethod(BuildContext context) async {
  final FirebaseMethods _firebase = FirebaseMethods();
  bool isTrue = await _firebase.isRegistrationUserCompleted(_firebase.getUID());
  if (!isTrue) {
    Variables.isCustomUserPic = false;
    Variables.isSocialUserPic = false;
    await _firebase.loadDefaultUserPicUrl();
    //& qui devo andare alla registrazione utente.
    if (Variables.isSignUp) {
      Navigator.of(context).pushReplacement(
        MaterialPageRoute(builder: (context) => const RegistrationScreen()),
      );
    } else {
      Navigator.of(context).push(
        MaterialPageRoute(builder: (context) => const RegistrationScreen()),
      );
    }
    //Navigator.pop(context);
  } else {
    Navigator.of(context).push(
      MaterialPageRoute(builder: (context) => const HomeScreen()),
    );
    //Navigator.pop(context);
  }
}
</code>```

And my very simple Home Screen:

```<code>class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return const IHome();
  }
}

class IHome extends StatelessWidget {
  const IHome({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Center(
        child: ElevatedButton(
          child: const Text('LogOut'),
          onPressed: () async {
            bool isTrue = await AuthMethods().signOut();
            if (isTrue) {
              //Navigator.pop(context);
            }
            //Navigator.pop(context);
          },
        ),
      ),
    );
  }
}
</code>```

here the widget tree when a user is logged in and the wrapper loads the Home Screen.

As you can see I need to check other data before to switch to Home Screen, it's a post-account data that I need.

However when a user is logged in I open the Home Page directly from the Wrapper, but the Logout is not recognised (I checked the logout works well).

Here the widget tree when the wrapper chose the SignIn screen (because the user is not logged in).

As I should understand I probably need to avoid to use Navigator to open HomeScreen, but I don't know how to do.

Many thanks for support.

答:
There could be a couple of reasons why you don't get rerouted when the authStatechange:

could be a major issue with how your provider and state notifiers are created and are being used.

I suggest you listen for authStateChange in your Wrapper Widget instead, here is a brief example:

```<code>@override
Widget build(BuildContext context) {
  return MaterialApp(
      title: 'Your App Name',
      home: _getLandingPage()
  );
}

Widget _getLandingPage() {
  return StreamBuilder<FirebaseUser>(
    stream: FirebaseAuth.instance.onAuthStateChanged,
    builder: (BuildContext context, snapshot) {
      if (snapshot.hasData) {
         return MainPage();
      } else {
        return LoginPage();
      }
    },
  );
}
</code>```

OR

```<code>FirebaseAuth.instance
  .userChanges()
  .listen((User? user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      print('User is signed in!');
    }
  });
</code>```

You can find more info here

Body:
When I have a logged user, my wrapper check for additional data and once find it will open the HomeScreen of my application.

However, the Stream Builder does not return the SignIn screen even if user successfully logout.

As I can see the Home page is built in a different tree (but how to build it in the main tree?), don't know if this should interfere.

Main code:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (kIsWeb) {
    await Firebase.initializeApp(),
    );
  } else {
    await Firebase.initializeApp();
  }
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        Provider<AuthService>(
          create: (_) => AuthService(),
        ),
      ],
      child: GestureDetector(
        onTap: () {
          FocusScopeNode currentFocus = FocusScope.of(context);
          if (!currentFocus.hasPrimaryFocus) {
            FocusScope.of(context).requestFocus(FocusNode());
          }
        },
        child: MaterialApp(
          theme: ThemeData(
            primaryColor: appColor,
            primaryColorLight: appColor,
            primaryColorDark: appColor,
          ),
          debugShowCheckedModeBanner: false,
          title: 'WhyBye',
          //todo: Queste righe saranno necessarie quando avremo anche la versione WEB
          // home: ResponsiveLayout(
          //     webScreenLayout: WebScreenLayout(),
          //     mobileScreenLayout: MobileScreenLayout()),
          //todo.

          initialRoute: '/wrapper',
          routes: {
            '/wrapper': (context) => const Wrapper(),
            '/signInScreen': (context) => const SignInScreen(),
            '/signUpScreen': (context) => const SignUpScreen(),
            '/registrationScreen': (context) => const RegistrationScreen(),
            '/homeScreen': (context) => const HomeScreen(),
            '/recoverPasswordScreen': (context) =>
                const RecoverPasswordScreen(),
          },
        ),
      ),
    );
  }
}

My Wrapper code:

class Wrapper extends StatelessWidget {
  const Wrapper({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final authService = Provider.of<AuthService>(context);
    return StreamBuilder<User?>(
      stream: authService.user,
      builder: (_, AsyncSnapshot<User?> snapshot) {
        if (snapshot.connectionState == ConnectionState.active) {
          final User? user = snapshot.data;
          //return user == null ? const SignInScreen() : const HomeScreen();
          if (user == null) {
            return const SignInScreen();
          } else {
            WidgetsBinding.instance
                ?.addPostFrameCallback((_) => asyncMethod(context));
            return const Scaffold(
              body: Center(
                child: CircularProgressIndicator(
                  color: appBarColor,
                ),
              ),
            );
          }
        } else {
          return const Scaffold(
            body: Center(
              child: CircularProgressIndicator(
                color: appBarColor,
              ),
            ),
          );
        }
      },
    );
  }
}

void asyncMethod(BuildContext context) async {
  final FirebaseMethods _firebase = FirebaseMethods();
  bool isTrue = await _firebase.isRegistrationUserCompleted(_firebase.getUID());
  if (!isTrue) {
    Variables.isCustomUserPic = false;
    Variables.isSocialUserPic = false;
    await _firebase.loadDefaultUserPicUrl();
    //& qui devo andare alla registrazione utente.
    if (Variables.isSignUp) {
      Navigator.of(context).pushReplacement(
        MaterialPageRoute(builder: (context) => const RegistrationScreen()),
      );
    } else {
      Navigator.of(context).push(
        MaterialPageRoute(builder: (context) => const RegistrationScreen()),
      );
    }
    //Navigator.pop(context);
  } else {
    Navigator.of(context).push(
      MaterialPageRoute(builder: (context) => const HomeScreen()),
    );
    //Navigator.pop(context);
  }
}

And my very simple Home Screen:

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return const IHome();
  }
}

class IHome extends StatelessWidget {
  const IHome({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Center(
        child: ElevatedButton(
          child: const Text('LogOut'),
          onPressed: () async {
            bool isTrue = await AuthMethods().signOut();
            if (isTrue) {
              //Navigator.pop(context);
            }
            //Navigator.pop(context);
          },
        ),
      ),
    );
  }
}

here the widget tree when a user is logged in and the wrapper loads the Home Screen.

As you can see I need to check other data before to switch to Home Screen, it's a post-account data that I need.

However when a user is logged in I open the Home Page directly from the Wrapper, but the Logout is not recognised (I checked the logout works well).

Here the widget tree when the wrapper chose the SignIn screen (because the user is not logged in).

As I should understand I probably need to avoid to use Navigator to open HomeScreen, but I don't know how to do.

Many thanks for support.

Body:
There could be a couple of reasons why you don't get rerouted when the authStatechange:

could be a major issue with how your provider and state notifiers are created and are being used.

I suggest you listen for authStateChange in your Wrapper Widget instead, here is a brief example:

@override
Widget build(BuildContext context) {
  return MaterialApp(
      title: 'Your App Name',
      home: _getLandingPage()
  );
}

Widget _getLandingPage() {
  return StreamBuilder<FirebaseUser>(
    stream: FirebaseAuth.instance.onAuthStateChanged,
    builder: (BuildContext context, snapshot) {
      if (snapshot.hasData) {
         return MainPage();
      } else {
        return LoginPage();
      }
    },
  );
}

OR

FirebaseAuth.instance
  .userChanges()
  .listen((User? user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      print('User is signed in!');
    }
  });

You can find more info here


问:
How do I make multiple Rxjs http calls sequentially and access all results in subscribe?
I have 3 http requests

```<code>let a: Observable<string> = this.dataService.getData1();
let b: Observable<number> = this.dataService.getData2();
let c: Observable<boolean> = this.dataService.getData3();
</code>```

I want to call getData1, getData2, and getData3 sequentially (one after the other) and return all data in a single subscribe.

```<code>{
    //What do I put here?
}.subscribe(data => {
    //I have the result of all 3 data (string,number, and boolean)
}, error => {
    //If one data fails, it throws an error
});
</code>```

答:
With concat and reduce or toArray, you can get all results in one emission in subscribe()

```<code>concat(
  a,
  b,
  c
).pipe(reduce((acc, curr) => [curr, ...acc], []))
  .subscribe(console.log);

concat(
  a,
  b,
  c
).pipe(toArray())
  .subscribe(console.log);
</code>```

Body:
I have 3 http requests

let a: Observable<string> = this.dataService.getData1();
let b: Observable<number> = this.dataService.getData2();
let c: Observable<boolean> = this.dataService.getData3();

I want to call getData1, getData2, and getData3 sequentially (one after the other) and return all data in a single subscribe.

{
    //What do I put here?
}.subscribe(data => {
    //I have the result of all 3 data (string,number, and boolean)
}, error => {
    //If one data fails, it throws an error
});

Body:
With concat and reduce or toArray, you can get all results in one emission in subscribe()

concat(
  a,
  b,
  c
).pipe(reduce((acc, curr) => [curr, ...acc], []))
  .subscribe(console.log);

concat(
  a,
  b,
  c
).pipe(toArray())
  .subscribe(console.log);


问:
Android Text Views overflowing and blocking each other out
I am having issues with 2 text views next to each other in a constraint layout. One is a title and one is a dummy "description" and the description ends up displaying off the right edge of the screen and also pushing the title off the left edge of the screen. What am I getting wrong with the layout, the description text needs to do more linebreaks to give the title and itself space to fit within the screen.

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
    android:id="@+id/fillerContent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:text="TextView"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toEndOf="@+id/label"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"/>

<TextView
    android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:text="TextView"
    android:textSize="20sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/fillerContent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"/>
</code>```

edit 1: This view is an item in a recyclerlist.

答:
You're using wrap_contents in a chained ConstraintLayout. Judging by the layout, only the label needs to be at actual width, and fillerContent must take whatever space it can get horizontally. So, you can change the width like this:

```<code><TextView
    android:id="@+id/fillerContent"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:text="TextView"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toEndOf="@+id/label"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"/>
</code>```

Set the filler layout_width to 0dp, and it should work.

Body:
I am having issues with 2 text views next to each other in a constraint layout. One is a title and one is a dummy "description" and the description ends up displaying off the right edge of the screen and also pushing the title off the left edge of the screen. What am I getting wrong with the layout, the description text needs to do more linebreaks to give the title and itself space to fit within the screen.

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
    android:id="@+id/fillerContent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:text="TextView"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toEndOf="@+id/label"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"/>

<TextView
    android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:text="TextView"
    android:textSize="20sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/fillerContent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"/>

edit 1: This view is an item in a recyclerlist.

Body:
You're using wrap_contents in a chained ConstraintLayout. Judging by the layout, only the label needs to be at actual width, and fillerContent must take whatever space it can get horizontally. So, you can change the width like this:

<TextView
    android:id="@+id/fillerContent"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:text="TextView"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toEndOf="@+id/label"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"/>

Set the filler layout_width to 0dp, and it should work.


问:
How to capture the Batch script error during a run in Github Actions workflow
When Batch script is run as a job from workflow it exits with errorlevel, but the overall job status gives success, instead of failure. How can I capture the error and get workflow status as failed.

Attaching snippets of the Github Action workflow yaml file

```<code>- name: Setup Release directory
  id: Release_directory
  run: .\\Compile_testsuite.bat

- name: Check on failures
  if: (${{ success() }} || ${{ failure() }}) && (${{ steps.Release_directory.outcome }} == 'failure')
  run: echo ${{steps.Release_directory.outcome}} #exit 1
</code>```

Attaching the code snippet of the Batch script

```<code>@echo off
rem Get Current Path
set defaultPath=%CD%
set defaultPath=%defaultPath: =%

set /p version=<Version.txt
set ReleasePath=%defaultPath%\Release_%version%

set runPath=%ReleasePath%\run
set workloadsPath=%ReleasePath%\workloads
set commonPath=%workloadsPath%\common
set resultsPath=%ReleasePath%\results
echo %defaultPath%

if not exist %ReleasePath% mkdir %ReleasePath%
if not exist %runPath% mkdir %runPath%
if not exist %workloadsPath% mkdir %workloadsPath%
if not exist %resultsPath% mkdir %resultsPath%
if not exist %commonPath% mkdir %commonPath%

set Identifier=false

rem Iterate over directory
for /D %%w in (*) do (
    SETLOCAL ENABLEDELAYEDEXPANSION
        set workloadPath=%defaultPath%\%%~nxw

        for /f "tokens=1 delims=_" %%a in ("%%~nxw") DO (
            set var=%%a

            if "!var!" == "Excel" ( set "Identifier=true")
            if "!var!" == "Word" ( set "Identifier=true")
            if "!var!" == "Outlook" ( set "Identifier=true")
            if "!var!" == "Powerpoint" ( set "Identifier=true")
        )

        if "!Identifier!" == "true" (
            REM Print Workload path
            echo !workloadPath!
            cd !workloadPath!
            nuget install !workloadPath!\%%~nxw\packages.config -o !workloadPath!\packages\
            echo !workloadPath!\%%~nxw.sln
            msbuild !workloadPath!\%%~nxw.sln /t:Rebuild /p:Configuration=Release /p:Platform="Any CPU"
            rem echo "ERROR_LEVEL" !errorlevel!
            if not !errorlevel! == 0 ( exit /B !errorlevel!)
            set exePath=!workloadPath!\%%~nxw\bin\Release\Executable

            if not exist !workloadsPath!\%%~nxw\bin mkdir !workloadsPath!\%%~nxw\bin
            if not exist !workloadsPath!\%%~nxw\input mkdir !workloadsPath!\%%~nxw\input
            copy !exePath! !workloadsPath!\%%~nxw\bin
            copy !workloadPath!\%%~nxw\bin\Release\input !workloadsPath!\%%~nxw\input

            cd %defaultPath%
        )
</code>```

Output from the Workflow run in Github Actions

I'm trying to run build a vs code solution using "msbuild". If the build is not successful, Batch script should terminate. So I have added if condition to check status of msbuild.
When I run the workflow, I'm trying to check the build of the solution, if build is successful, I need to run the application using next task.

答: I have directed the output to a new file, and checked for failure keyword in the file. If any error occurred, I will terminate the run in workflow.</p>

Body:
When Batch script is run as a job from workflow it exits with errorlevel, but the overall job status gives success, instead of failure. How can I capture the error and get workflow status as failed.

Attaching snippets of the Github Action workflow yaml file

- name: Setup Release directory
  id: Release_directory
  run: .\\Compile_testsuite.bat

- name: Check on failures
  if: (${{ success() }} || ${{ failure() }}) && (${{ steps.Release_directory.outcome }} == 'failure')
  run: echo ${{steps.Release_directory.outcome}} #exit 1

Attaching the code snippet of the Batch script

@echo off
rem Get Current Path
set defaultPath=%CD%
set defaultPath=%defaultPath: =%

set /p version=<Version.txt
set ReleasePath=%defaultPath%\Release_%version%

set runPath=%ReleasePath%\run
set workloadsPath=%ReleasePath%\workloads
set commonPath=%workloadsPath%\common
set resultsPath=%ReleasePath%\results
echo %defaultPath%

if not exist %ReleasePath% mkdir %ReleasePath%
if not exist %runPath% mkdir %runPath%
if not exist %workloadsPath% mkdir %workloadsPath%
if not exist %resultsPath% mkdir %resultsPath%
if not exist %commonPath% mkdir %commonPath%

set Identifier=false

rem Iterate over directory
for /D %%w in (*) do (
    SETLOCAL ENABLEDELAYEDEXPANSION
        set workloadPath=%defaultPath%\%%~nxw

        for /f "tokens=1 delims=_" %%a in ("%%~nxw") DO (
            set var=%%a

            if "!var!" == "Excel" ( set "Identifier=true")
            if "!var!" == "Word" ( set "Identifier=true")
            if "!var!" == "Outlook" ( set "Identifier=true")
            if "!var!" == "Powerpoint" ( set "Identifier=true")
        )

        if "!Identifier!" == "true" (
            REM Print Workload path
            echo !workloadPath!
            cd !workloadPath!
            nuget install !workloadPath!\%%~nxw\packages.config -o !workloadPath!\packages\
            echo !workloadPath!\%%~nxw.sln
            msbuild !workloadPath!\%%~nxw.sln /t:Rebuild /p:Configuration=Release /p:Platform="Any CPU"
            rem echo "ERROR_LEVEL" !errorlevel!
            if not !errorlevel! == 0 ( exit /B !errorlevel!)
            set exePath=!workloadPath!\%%~nxw\bin\Release\Executable

            if not exist !workloadsPath!\%%~nxw\bin mkdir !workloadsPath!\%%~nxw\bin
            if not exist !workloadsPath!\%%~nxw\input mkdir !workloadsPath!\%%~nxw\input
            copy !exePath! !workloadsPath!\%%~nxw\bin
            copy !workloadPath!\%%~nxw\bin\Release\input !workloadsPath!\%%~nxw\input

            cd %defaultPath%
        )

Output from the Workflow run in Github Actions

I'm trying to run build a vs code solution using "msbuild". If the build is not successful, Batch script should terminate. So I have added if condition to check status of msbuild.
When I run the workflow, I'm trying to check the build of the solution, if build is successful, I need to run the application using next task.


问:
ValidationException: Parameter ScheduleExpression is not valid
My cron syntax is

cron(25 8 10 2 4 2022)

And I wish to run the job exactly once on Thursday February 10 at 8:25 am. But getting the above error when trying to run.

答:
You can schedule lambda event using following syntax:

# NOTE: This will execute on UTC mode only
cron(Minutes Hours Day-of-month Month Day-of-week Year)
```
<p>So your cron expression should look like:</p>
<pre class="lang-sh prettyprint-override"><code>cron(25 08 10 02 ? 2022)
</code>```

For more information, here is the official AWS Guide

Body:
You can schedule lambda event using following syntax:

# NOTE: This will execute on UTC mode only
cron(Minutes Hours Day-of-month Month Day-of-week Year)

So your cron expression should look like:

cron(25 08 10 02 ? 2022)

For more information, here is the official AWS Guide


问:
There can be only one auto column
How do I correct the error from MySQL 'you can only have one auto increment column'.</p>

```<code>CREATE TABLE book (
   id INT AUTO_INCREMENT NOT NULL,
   accepted_terms BIT(1) NOT NULL,
   accepted_privacy BIT(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

答:
This happens with you because in the case that you didn't create a primary key, SEQUELIZE will automatically generate a primary key with a default name id. Which causes a duplication because you already created one and SEQUELIZE created one too.
But when you defined id as a primary key. SEQUELIZE didn't create the default id primary key.

Title: There can be only one auto column

Body:
How do I correct the error from MySQL 'you can only have one auto increment column'.

CREATE TABLE book (
   id INT AUTO_INCREMENT NOT NULL,
   accepted_terms BIT(1) NOT NULL,
   accepted_privacy BIT(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


问:
App Icon errors using application loader
I am trying to upload a beta of my Xamarin application and I receive the following list of errors when using the application loader:

I created my icons using this and the asset catalog accepted them.

Has anyone had a similar experience or have any insight into this issue?

Thanks!

答:
Follow the below,

Right click on Assets.xcassets and select Reveal in Finder.

Take 'Back up' your App Icons from the folder.

From Visual Studio, Delete current AppIcon set in the Assets.xcassets

Add new AppIcon set in the Assets.xcassets

Upload the same required icons according to your app platform type from your back up folder.

Select the new AppIcon set in the info.plist

Try Build, Archive, Sign and upload to TestFlight


问:
Python 3.8 - Unable to update dictionary
Hello I have this below dictionary that I want to update

```<code>{
   "Version":"2012-10-17",
   "Statement":[
      {
         "Effect":"Allow",
         "Principal":{
            "Federated":"arn:aws:iam::111111111111:saml-provider/Test"
         },
         "Action":"sts:AssumeRoleWithSAML",
         "Condition":{
            "StringEquals":{
               "SAML:aud":"https://signin.aws.amazon.com/saml"
            }
         }
      }
   ]
}
</code>```

Want to update it to

```<code>{
   "Version":"2012-10-17",
   "Statement":[
      {
         "Effect":"Allow",
         "Principal":{
            "Federated":[
            "arn:aws:iam::111111111111:saml-provider/Test",
            "arn:aws:iam::111111111111:saml-provider/Test2"
            ]
         },
         "Action":"sts:AssumeRoleWithSAML",
         "Condition":{
            "StringEquals":{
               "SAML:aud":"https://signin.aws.amazon.com/saml"
            }
         }
      }
   ]
}
</code>```

i.e. add "arn:aws:iam::111111111111:saml-provider/Test2" to "Federated" and also make it a list. Below is my code

```<code>    new_arn = "arn:aws:iam::111111111111:saml-provider/Test2"
    my_dict = {
   "Version":"2012-10-17",
   "Statement":[
      {
             "Effect":"Allow",
             "Principal":{
                "Federated":[
                "arn:aws:iam::111111111111:saml-provider/Test",
                ]
             },
             "Action":"sts:AssumeRoleWithSAML",
             "Condition":{
                "StringEquals":{
                   "SAML:aud":"https://signin.aws.amazon.com/saml"
                }
             }
          }
       ]
    }
    for b in my_dict['Statement']:
        updated_arn = f"['{b['Principal']['Federated']}', {new_arn}]"
        b['Principal']['Federated']: updated_arn

    print(my_dict)
</code>```

I am bit new to python and I am not sure what am I doing wrong the dict is not getting updated. Can someone please provide some guidance on what I may be doing wrong

答:
As folks commented, you're constructing a string that looks like a list here:

    for b in my_dict['Statement']:
        updated_arn = f"['{b['Principal']['Federated']}', {new_arn}]"
        b['Principal']['Federated']: updated_arn
```
<p>You can create a real list instead:</p>
<pre class="lang-py prettyprint-override"><code>    for b in my_dict['Statement']:
        updated_arn = [b['Principal']['Federated'], new_arn]
        b['Principal']['Federated'] = updated_arn
        # note it's `=` not `:` here
</code>```

Edit:
If Federated is sometimes a string, and sometimes already a list, you'll need to check its type and act accordingly:

    for b in my_dict['Statement']:
        federated = b['Principal']['Federated']
        if isinstance(federated, list):
            federated.append(new_arn)
            # (which updates the list within the dict, no need to assign back to the dict)
        else:
            b['Principal']['Federated'] = [federated, new_arn]
```

Body:
Hello I have this below dictionary that I want to update

{
   "Version":"2012-10-17",
   "Statement":[
      {
         "Effect":"Allow",
         "Principal":{
            "Federated":"arn:aws:iam::111111111111:saml-provider/Test"
         },
         "Action":"sts:AssumeRoleWithSAML",
         "Condition":{
            "StringEquals":{
               "SAML:aud":"https://signin.aws.amazon.com/saml"
            }
         }
      }
   ]
}

Want to update it to

{
   "Version":"2012-10-17",
   "Statement":[
      {
         "Effect":"Allow",
         "Principal":{
            "Federated":[
            "arn:aws:iam::111111111111:saml-provider/Test",
            "arn:aws:iam::111111111111:saml-provider/Test2"
            ]
         },
         "Action":"sts:AssumeRoleWithSAML",
         "Condition":{
            "StringEquals":{
               "SAML:aud":"https://signin.aws.amazon.com/saml"
            }
         }
      }
   ]
}

i.e. add "arn:aws:iam::111111111111:saml-provider/Test2" to "Federated" and also make it a list. Below is my code

    new_arn = "arn:aws:iam::111111111111:saml-provider/Test2"
    my_dict = {
   "Version":"2012-10-17",
   "Statement":[
      {
             "Effect":"Allow",
             "Principal":{
                "Federated":[
                "arn:aws:iam::111111111111:saml-provider/Test",
                ]
             },
             "Action":"sts:AssumeRoleWithSAML",
             "Condition":{
                "StringEquals":{
                   "SAML:aud":"https://signin.aws.amazon.com/saml"
                }
             }
          }
       ]
    }
    for b in my_dict['Statement']:
        updated_arn = f"['{b['Principal']['Federated']}', {new_arn}]"
        b['Principal']['Federated']: updated_arn

    print(my_dict)

I am bit new to python and I am not sure what am I doing wrong the dict is not getting updated. Can someone please provide some guidance on what I may be doing wrong

Body:
As folks commented, you're constructing a string that looks like a list here:

    for b in my_dict['Statement']:
        updated_arn = f"['{b['Principal']['Federated']}', {new_arn}]"
        b['Principal']['Federated']: updated_arn

You can create a real list instead:

    for b in my_dict['Statement']:
        updated_arn = [b['Principal']['Federated'], new_arn]
        b['Principal']['Federated'] = updated_arn
        # note it's `=` not `:` here

Edit:
If Federated is sometimes a string, and sometimes already a list, you'll need to check its type and act accordingly:

    for b in my_dict['Statement']:
        federated = b['Principal']['Federated']
        if isinstance(federated, list):
            federated.append(new_arn)
            # (which updates the list within the dict, no need to assign back to the dict)
        else:
            b['Principal']['Federated'] = [federated, new_arn]