问:
Change WooCommerce Product Name Include Color When Attribute Selected
I'm looking for someone me help getting the WooCommerce variable product title to change based on color. In this specific case I would like the title to change when a color is selected, like "Product name - Black".

I follow this topic Change WooCommerce variable product title based on variation but it not work with WooCommerce version 3.9.1

and the code

```<code>add_filter( 'wp_footer','custom_product_title_script' );
function custom_product_title_script(){
    global $post;

    // Only single product pages
    if( ! is_product() ) return;

    // get an instance of the WC_Product Object
    $product = wc_get_product($post->ID);

    // Only for variable products
    if( ! $product->is_type( 'variable' ) ) return;

    // Here set your specific product attributes in this array (coma separated):
    $attributes = array('pa_color');

    // The 1st loop for variations IDs
    foreach($product->get_visible_children( ) as $variation_id ) {

        // The 2nd loop for attribute(s)/value
        foreach($product->get_available_variation( $variation_id )['attributes'] as $key => $value_id ){
            $taxonomy = str_replace( 'attribute_', '', $key ); // Get the taxonomy of the product attribute

            // Just for defined attributes
            if( in_array( $taxonomy, $attributes) ){
                // Set and structure data in an array( variation ID => product attribute => term name )
                $data[ $variation_id ][$taxonomy] = get_term_by( 'slug', $value_id, $taxonomy )->name;
            }
        }
    }

    ?>
        <script type="text/javascript">
            (function($){
                // variables initialization
                var variationsData = <?php echo json_encode($data); ?>,
                    productTitle = $('.product_title').text(),
                    color = 'pa_color';
                console.log(variationsData);

                // function that get the selected variation and change title
                function update_the_title( productTitle, variationsData, color ){
                    $.each( variationsData, function( index, value ){
                        if( index == $('input.variation_id').val() ){
                            $('.product_title').text(productTitle+' - '+value[color]);
                            console.log('TITLE UPDATED');
                            return false;
                        } else {
                            $('.product_title').text(productTitle);
                        }
                    });
                }

                // Once all loaded
                setTimeout(function(){
                    update_the_title( productTitle, variationsData, color );
                }, 300);

                // On live event: select fields
                $('select').blur( function(){
                    update_the_title( productTitle, variationsData, color );
                });
            })(jQuery);
        </script>
    <?php
}
</code>```

答:
I try new code and it work with new version 3.9.2</p>

```<code>add_filter( 'wp_footer','custom_product_title_script' );

function custom_product_title_script(){
    global $post;

    // Only single product pages
    if( ! is_product() ) return;

    // get an instance of the WC_Product Object
    $product = wc_get_product($post->ID);

    // Only for variable products
    if( ! $product->is_type( 'variable' ) ) return;

    // Here set your specific product attributes in this array (coma separated):
    $attributes = array('pa_colour');

    // The 1st loop for variations IDs
    foreach( $product->get_visible_children() as $variation_id ) {

        // The 2nd loop for attribute(s)/value
        foreach($product->get_available_variation( $variation_id )['attributes'] as $key => $value_id ){
            $taxonomy = str_replace( 'attribute_', '', $key ); // Get the taxonomy of the product attribute

            // Just for defined attributes
            if( in_array( $taxonomy, $attributes) ){
                // Set and structure data in an array( variation ID => product attribute => term name )
                $data[ $variation_id ][$taxonomy] = get_term_by( 'slug', $value_id, $taxonomy )->name;
            }
        }
    }

    ?>
        <script type="text/javascript">
            (function($){
                // variables initialization
                var variationsData = <?php echo json_encode($data); ?>,
                    productTitle = $('.product_title').text(),
                    color = 'pa_colour';
                console.log(variationsData);

                // function that get the selected variation and change title
                function update_the_title( productTitle, variationsData, color ){
                    $.each( variationsData, function( index, value ){
                        if( index == $('input.variation_id').val() ){
                            $('.product_title').text(productTitle+' - '+value[color]);
                            console.log('TITLE UPDATED');
                            return false;
                        } else {
                            $('.product_title').text(productTitle);
                        }
                    });
                }

                // Once all loaded
                setTimeout(function(){
                    update_the_title( productTitle, variationsData, color );
                }, 300);

                // On live event: select fields
                // $('select').blur( function(){
                //     update_the_title( productTitle, variationsData, color );
                // });

                $('#pa_colour').on('change', function(){
                   // update_the_title( productTitle, variationsData, color );
                    setTimeout(function(){
                      update_the_title( productTitle, variationsData, color );
                    }, 300);
                });

            })(jQuery);
        </script>
    <?php
}
</code>```

Body:
I'm looking for someone me help getting the WooCommerce variable product title to change based on color. In this specific case I would like the title to change when a color is selected, like "Product name - Black".

I follow this topic Change WooCommerce variable product title based on variation but it not work with WooCommerce version 3.9.1

and the code

add_filter( 'wp_footer','custom_product_title_script' );
function custom_product_title_script(){
    global $post;

    // Only single product pages
    if( ! is_product() ) return;

    // get an instance of the WC_Product Object
    $product = wc_get_product($post->ID);

    // Only for variable products
    if( ! $product->is_type( 'variable' ) ) return;

    // Here set your specific product attributes in this array (coma separated):
    $attributes = array('pa_color');

    // The 1st loop for variations IDs
    foreach($product->get_visible_children( ) as $variation_id ) {

        // The 2nd loop for attribute(s)/value
        foreach($product->get_available_variation( $variation_id )['attributes'] as $key => $value_id ){
            $taxonomy = str_replace( 'attribute_', '', $key ); // Get the taxonomy of the product attribute

            // Just for defined attributes
            if( in_array( $taxonomy, $attributes) ){
                // Set and structure data in an array( variation ID => product attribute => term name )
                $data[ $variation_id ][$taxonomy] = get_term_by( 'slug', $value_id, $taxonomy )->name;
            }
        }
    }

    ?>

    <?php
}

Body:
I try new code and it work with new version 3.9.2

add_filter( 'wp_footer','custom_product_title_script' );

function custom_product_title_script(){
    global $post;

    // Only single product pages
    if( ! is_product() ) return;

    // get an instance of the WC_Product Object
    $product = wc_get_product($post->ID);

    // Only for variable products
    if( ! $product->is_type( 'variable' ) ) return;

    // Here set your specific product attributes in this array (coma separated):
    $attributes = array('pa_colour');

    // The 1st loop for variations IDs
    foreach( $product->get_visible_children() as $variation_id ) {

        // The 2nd loop for attribute(s)/value
        foreach($product->get_available_variation( $variation_id )['attributes'] as $key => $value_id ){
            $taxonomy = str_replace( 'attribute_', '', $key ); // Get the taxonomy of the product attribute

            // Just for defined attributes
            if( in_array( $taxonomy, $attributes) ){
                // Set and structure data in an array( variation ID => product attribute => term name )
                $data[ $variation_id ][$taxonomy] = get_term_by( 'slug', $value_id, $taxonomy )->name;
            }
        }
    }

    ?>
        <script type="text/javascript">
            (function($){
                // variables initialization
                var variationsData = <?php echo json_encode($data); ?>,
                    productTitle = $('.product_title').text(),
                    color = 'pa_colour';
                console.log(variationsData);

                // function that get the selected variation and change title
                function update_the_title( productTitle, variationsData, color ){
                    $.each( variationsData, function( index, value ){
                        if( index == $('input.variation_id').val() ){
                            $('.product_title').text(productTitle+' - '+value[color]);
                            console.log('TITLE UPDATED');
                            return false;
                        } else {
                            $('.product_title').text(productTitle);
                        }
                    });
                }

                // Once all loaded
                setTimeout(function(){
                    update_the_title( productTitle, variationsData, color );
                }, 300);

                // On live event: select fields
                // $('select').blur( function(){
                //     update_the_title( productTitle, variationsData, color );
                // });

                $('#pa_colour').on('change', function(){
                   // update_the_title( productTitle, variationsData, color );
                    setTimeout(function(){
                      update_the_title( productTitle, variationsData, color );
                    }, 300);
                });

            })(jQuery);
        </script>
    <?php
}


来源: stackexchange

问:
How to make php while loop out of this MySQL query?
I want to make a loop so that every time the 'id' is queried, it puts the data into a separate block. Imagine it like listings on ebay. I know the foreach wont do it, but i have no idea how to do the while loop.

```<code><?php
include 'sqlconnection.php';
$conn = OpenCon();

$stmt = $conn->prepare("SELECT id from tasks where status='o'");
$stmt->execute();
$res = $stmt->get_result();
$data = $res->fetch_all(MYSQLI_ASSOC);

foreach ($data as $row)
{
     echo    "<p>" . $row['id'] . "</p>";
}
CloseCon($conn);
?>
</code>```

This is the HTML block i want to repeat:

```<code>
    <div class="listing-header">
        <div class="listing-title">
          <p>       </p>
        </div>
    </div>
</code>```

答:
You may want to look at this:

```<code>$stmt = $conn->prepare('SELECT id from tasks where status=?'); $o = 'o';
$stmt->bind_param('s', $o); $stmt->execute(); $stmt->bind_result($id); $html = '';
while($stmt->fetch()){
  $html .= '<div class="listing-header"><div class="listing-title"><p>'.$id.'</p></div></div>';
}
$stmt->close(); $conn->close();
</code>```

in HTML

```<code><?=$html?>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to make a loop so that every time the 'id' is queried, it puts the data into a separate block. Imagine it like listings on ebay. I know the foreach wont do it, but i have no idea how to do the while loop.

<?php
include 'sqlconnection.php';
$conn = OpenCon();

$stmt = $conn->prepare("SELECT id from tasks where status='o'");
$stmt->execute();
$res = $stmt->get_result();
$data = $res->fetch_all(MYSQLI_ASSOC);

foreach ($data as $row)
{
     echo    "
" . $row['id'] . "
";
}
CloseCon($conn);
?>

This is the HTML block i want to repeat:

Body:
You may want to look at this:

$stmt = $conn->prepare('SELECT id from tasks where status=?'); $o = 'o';
$stmt->bind_param('s', $o); $stmt->execute(); $stmt->bind_result($id); $html = '';
while($stmt->fetch()){
  $html .= '<div class="listing-header"><div class="listing-title"><p>'.$id.'</p></div></div>';
}
$stmt->close(); $conn->close();

in HTML

<?=$html?>


问:
Visual Studio breakpoints not being hit
I'm working with an ASP.NET MVC project that seems to be having some issues when attaching to the IIS process (w3wp.exe). I'm running the solution and IIS 8.5 on my own local machine so I wouldn't think that this has anything to do with our network. What's strange to me is that I'm able to hit the breakpoints on any other solution I debug locally.

The issue I'm having exactly is that the breakpoints turn to red, hollow circles and never get hit. Usually the fix for this is a Clean/Rebuild of the solution but this hasn't worked. I've confirmed the code is being updated by adding "throw new Exception" to a page and ensuring it shows the exception. Again, this problem is only happening with this one solution. Any other solution I run the debugger with works fine. I've also tried restarting the app pool, the website, IIS, and also my computer.

A few of the articles I read mentioned that anti-virus programs can block a remote debugger from accessing the process. However, the entire setup is contained on my local machine so it doesn't sound like that would be the issue. It does concern me a bit though because we recently hired a new IT guy that's been making a lot of changes to everyone's machine.

One other point to add that's unique about this web application is the binding in IIS. The binding is "*" in order to leverage some custom functionality related to subdomains.

In the meantime, I'll continue to look for a solution but if anybody has any ideas what may be causing this one solution to not debug properly I'd really appreciate it.

EDIT: Found a solution that suggested deleting the ASP.NET temporary files. No luck.

答:
My case is not mentioned here:

I have to run the web project on a fake domain (settup on IIS and /hosts/etc) because of the callbacks from a third party site.

I was seeing two w3wp processes in the process list of VS:

w3wp.exe    User Name: IIS APPPOOL\Default app pool

w3wp.exe    User Name: IIS APPPOOL.svc

I had to to manually attach to second one to be able to debug.

So I realised the app pool of my Fake domain in iis is not set to "Default app pool"

https://manage.accuwebhosting.com/knowledgebase/2532/How-to-change-application-pool-from-IIS.html

As soon as I changed the domain's app pool to the "Default app pool" visual studio started to debug the web app.

ContentLicense: CC BY-SA 3.0

Title: Visual Studio breakpoints not being hit


问:
Cloning repository from AWS Codecommit
I am currently using SSH Key to clone repository from AWS Codecommit to my local machine. My

```<code>ssh git-codecommit.us-east-2.amazonaws.com
</code>```

has successfully connected.

My problem is that when I run this:

```<code>git clone ssh://git-codecommit.us-east-2.amazonaws.com.amazonaws.com/v1/repos/Project
</code>```

it is cloning my project but after 100% of cloning, I keep getting this error

```<code>remote: Counting objects: 1024, done.
client_loop: send disconnect: Connection reset by peer KiB/s
fatal: the remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed
</code>```

I cannot find answers around google and hoping that someone will help me with this. What is the possible causes of these error? Thank you in advance!

答:
Thanks everyone! its working now. Increasing postbuffer did a lot of help but in my case that is not the reason why its working. You guys should check your firewall, vpn connection or your network for their security purposes.

This site might help you resolving the issue
Git Clone Fails - fatal: The remote end hung up unexpectedly. fatal: early EOF fatal: index-pack failed

Title: Cloning repository from AWS Codecommit

Body:
I am currently using SSH Key to clone repository from AWS Codecommit to my local machine. My

ssh git-codecommit.us-east-2.amazonaws.com

has successfully connected.

My problem is that when I run this:

git clone ssh://git-codecommit.us-east-2.amazonaws.com.amazonaws.com/v1/repos/Project

it is cloning my project but after 100% of cloning, I keep getting this error

remote: Counting objects: 1024, done.
client_loop: send disconnect: Connection reset by peer KiB/s
fatal: the remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed

I cannot find answers around google and hoping that someone will help me with this. What is the possible causes of these error? Thank you in advance!


问:
Shopware 6: Add custom Database Data to frontend view
Hello I have build my own custom shopware 6 Plugin. Now i want to add data from my own database table to the product page. My Subscriber works. But when I Want to add custom Database Data to Product Page. In my Subscriber for Products, I don't can use

```<code>$this->get('product_reservation.repository');
</code>```

because "get" is not working into a subscriber.

How can I solve my Problem?

答: Inject it via class __constructor function.

Body:
Hello I have build my own custom shopware 6 Plugin. Now i want to add data from my own database table to the product page. My Subscriber works. But when I Want to add custom Database Data to Product Page. In my Subscriber for Products, I don't can use

$this->get('product_reservation.repository');

because "get" is not working into a subscriber.

How can I solve my Problem?


问:
react button is called before onPress when using Hooks
I am trying to request an API request using hooks. But my problem is that my function is called before I onPress.

I have an custom API component like this:

```<code>const FetchDataPut = (URL) => {

  useEffect(() => {
      async function fetchData() {
          const res = await axios({
                    method: 'put',
                    url: URL,
                    data:{
                      name:'111',
                      email:'222',
                      password:'333',
                      id:'444',
                      phone:'555'
                    }
                  });
          const response = await res;
          console.log(response, 'completed')
      }
      fetchData()
  },[])
  return null
}
</code>```

I could see from the console.log that api request has completed. My problem is that my api component is called before I onPress the button.

This is my Button component:

```<code>const EditAccount = (props) => {

  const Desktop = () => {
    const URL = `MyURL...`
    return (
      <View>
        <Button title='edit account' onPress={FetchDataPut(URL)}/>
      </View>
    )
  }

  return(
    <div>
      <Desktop/>
    </div>
  )
}
</code>```

If I change my onPress function to an arrow function like this:
onPress={()=>FetchDataPut(URL)} component isn't called before I onPress it. But it will give me an error Invalid hook call. Hooks can only be called inside of the body of a function component

Any Idea how to my the api request when I onPress the Button ?

Any comments or advice would be really helpful. Thanks in advance! :)

答:
I think the way to go is to use a hook rather than a component:

```<code>const useFetchDataPut = () => {
    const [url, setUrl] = useState("");

    useEffect(() => {
        if (!url) return;

        async function fetchData() {
            const res = await axios({
                method: "put",
                url,
                data: {
                    name: "111",
                    email: "222",
                    password: "333",
                    id: "444",
                    phone: "555"
                }
            });
            const response = await res;
            console.log(response, "completed");
        }
        fetchData();
    }, [url]);

    return setUrl;
};
</code>```

And then call it when you press the button. Also Desktop should be defined outside of the EditAccount component.

```<code>const Desktop = () => {
    const setUrl = useFetchDataPut();

    return (
        <View>
            <Button
                title="edit account"
                onPress={() => setUrl("https://...")}
            />
        </View>
    );
};

const EditAccount = props => {
    return (
        <div>
            <Desktop />
        </div>
    );
};
</code>```

Let me know if something is not clear.

Body:
I am trying to request an API request using hooks. But my problem is that my function is called before I onPress.

I have an custom API component like this:

const FetchDataPut = (URL) => {

  useEffect(() => {
      async function fetchData() {
          const res = await axios({
                    method: 'put',
                    url: URL,
                    data:{
                      name:'111',
                      email:'222',
                      password:'333',
                      id:'444',
                      phone:'555'
                    }
                  });
          const response = await res;
          console.log(response, 'completed')
      }
      fetchData()
  },[])
  return null
}

I could see from the console.log that api request has completed. My problem is that my api component is called before I onPress the button.

This is my Button component:

const EditAccount = (props) => {

  const Desktop = () => {
    const URL = `MyURL...`
    return (
      <View>
        <Button title='edit account' onPress={FetchDataPut(URL)}/>
      </View>
    )
  }

  return(

      <Desktop/>

  )
}

If I change my onPress function to an arrow function like this:
onPress={()=>FetchDataPut(URL)} component isn't called before I onPress it. But it will give me an error Invalid hook call. Hooks can only be called inside of the body of a function component

Any Idea how to my the api request when I onPress the Button ?

Any comments or advice would be really helpful. Thanks in advance! :)

Body:
I think the way to go is to use a hook rather than a component:

const useFetchDataPut = () => {
    const [url, setUrl] = useState("");

    useEffect(() => {
        if (!url) return;

        async function fetchData() {
            const res = await axios({
                method: "put",
                url,
                data: {
                    name: "111",
                    email: "222",
                    password: "333",
                    id: "444",
                    phone: "555"
                }
            });
            const response = await res;
            console.log(response, "completed");
        }
        fetchData();
    }, [url]);

    return setUrl;
};

And then call it when you press the button. Also Desktop should be defined outside of the EditAccount component.

const Desktop = () => {
    const setUrl = useFetchDataPut();

    return (
        <View>
            <Button
                title="edit account"
                onPress={() => setUrl("https://...")}
            />
        </View>
    );
};

const EditAccount = props => {
    return (
        <div>
            <Desktop />
        </div>
    );
};

Let me know if something is not clear.


问:
merge 2 values and put in a v-data-table column (Vuetify)
Is it possible to merge to values and put into one column in v-data-table?

List.vue

```<code><template>
  <v-app>
        <v-data-table
          :items="items"
          :headers="headers"
        />
  </v-app>
</template>

<script>
export default {
  data() {
    return {
      items: [
         { first_name: "Peter", last_name: "Johnson" },
         { first_name: "Simon", last_name: "Walker" }
       ],
      headers: [
        { text: "first_name", value: "first_name" },
        { text: "last_name", value: "last_name" },
      ]
    };
  }
};
</script>
</code>```

For example I want to put Peter Johnson in Full name column of my v-data-table, While it doesn't have Full name column.

答: just add a "fullname" virtual column on the back end, Or use a computed property.</p>

Body:
Is it possible to merge to values and put into one column in v-data-table?

List.vue

<template>
  <v-app>
        <v-data-table
          :items="items"
          :headers="headers"
        />
  </v-app>
</template>

For example I want to put Peter Johnson in Full name column of my v-data-table, While it doesn't have Full name column.


问:
Change foreign key using SQL
I have a table like this:

```<code>ID    Name      Email           Referred_by
-------------------------------------------
1     John      john@foo.com    NULL
2     Sam       sam@foo.com     john@foo.com
3     Sally     sally@foo.com   sam@foo.com
..... more rows .....
</code>```

And I would like to change it to:

```<code>ID    Name      Email           Referred_by
-------------------------------------------
1     John      john@foo.com    NULL
2     Sam       sam@foo.com     1
3     Sally     sally@foo.com   2
..... more rows .....
</code>```

Can I make this change using SQL?

答:
This should do the trick:</p>

```<code>UPDATE my_table a
set    a.referred_by = (
       SELECT b.id
       FROM   my_table b
       WHERE  b.email = a.referred_by
);
</code>```

Title: Change foreign key using SQL

Body:
I have a table like this:

ID    Name      Email           Referred_by
-------------------------------------------
1     John      john@foo.com    NULL
2     Sam       sam@foo.com     john@foo.com
3     Sally     sally@foo.com   sam@foo.com
..... more rows .....

And I would like to change it to:

ID    Name      Email           Referred_by
-------------------------------------------
1     John      john@foo.com    NULL
2     Sam       sam@foo.com     1
3     Sally     sally@foo.com   2
..... more rows .....

Can I make this change using SQL?

Body:
This should do the trick:

UPDATE my_table a
set    a.referred_by = (
       SELECT b.id
       FROM   my_table b
       WHERE  b.email = a.referred_by
);


问:
PHP / MySQL: Error after delete a row ta PHP page (filtered)
I have a problem with my delete function. Before that, I will brief to you about the flow of the system

1) At dashboard_engineer.php, there's 3 select options which is team, time from and time to.

2) user need to select 3 select option and press button "Search" to display the result.

3) The result will display at dashboard_engineer2.php.

4) The result will display all data rows and each row contains one delete button.

My problem is, after I click button delete, it was successful delete but the dashboard_engineer2.php page doesn't display the result that same as point 3 above. The result empty.

What I want is that, after delete, the dashboard_engineer2.php will display the remaining data rows that already filtered before. Below is my code.

dashboard_engineer.php

```<code><?php

    $smt = $conn->prepare("SELECT * FROM ot_team INNER JOIN ot_users ON ot_team.team_id = ot_users.team_id WHERE ot_users.roles_id = 7 AND ot_users.team_id <> 1 ORDER BY ot_users.fullname ASC");
    $smt->execute();
    $data = $smt->fetchAll();

?>

<form method = 'post' action = 'dashboard_engineer2.php' >
  <td width="40%">
    <select class="form-control"  name="team" id="team" required>
      <option value="">Please select...</option>
      <?php foreach ($data as $row2): ?>
      <option value= <?php echo $row2["team_id"]; ?> ><?php echo $row2["fullname"]; ?></option>
      <?php endforeach ?>
    </select>
  </td>
  <td width="1%"></td>
  <td width="20%"><input type="text" name="from" id="from" class="form-control" placeholder="From" required></td>
  <td width="1%"></td>
  <td width="20%"><input type="text" name="to" id="to" class="form-control" placeholder="To" required></td>
  <td width="1%"></td>
  <td width="10%"><button type="submit" value="Search" class="btn btn-primary" >Send</button><td>
</form>

<script>
$(document).ready(function(){
  $.datepicker.setDefaults({
    dateFormat: 'yy-mm-dd'
  });
  $(function(){
    $("#from").datepicker().attr("autocomplete", "off");;
    $("#to").datepicker().attr("autocomplete", "off");;
  });

});
</script>
</code>```

dashboard_engineer2.php

```<code><?php

    if(isset($_POST["from"], $_POST["to"], $_POST["team"])){

        $result = '';
        $query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$_POST["team"]."' AND report_date BETWEEN '".$_POST["from"]."' AND '".$_POST["to"]."' ORDER BY ot_report.report_date DESC";
        $sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
        $sql -> execute();

        if($sql->rowCount() > 0){

        echo'

        <table class = "table-bordered" width = "100%">
        <thead>
        <tr>
        <th width = "10%"><input type="checkbox" id="checkAl"> All</th>
        <th width = "3%">id</th>
        <th width = "15%">Date</th>
        <th width = "30%">Task Name</th>
        <th width = "10%">Status</th>
        <th colspan = "2" width = "7%">Action</th>
        </tr>
        </thead>
        <tbody>';

            $i=0;

            while($row = $sql->fetch(PDO::FETCH_ASSOC)){

            $datereport = $row['report_date'];
            $datereport2 = strtotime($datereport);
            $report_date = date('d M Y', $datereport2);

            $report_id = $row["report_id"];

            echo'<tr>';
                echo '<td><input type="checkbox" id="checkItem" name="check[]" value='.$row['report_id'].'></td>';
                echo '<td>'.$report_id.'</td>';
                echo '<td>'.$report_date.'</td>';
                echo '<td>'.$row["task_name"].'</td>';
                echo '<td align="center"><strong>'.$row["report_status"].'</strong></td>';
                echo '<td align="center">';
                echo '<form action = "view_task/view_task.php" method = "post">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-primary">View</button>';
                echo '</form>';

                echo "<form action = 'delete.php' method = 'post' onClick=\"return confirm('Do you want to remove team?')\">";
                echo '<input type = "hidden" name = "from" value = "'.$_POST["from"].'">';
                echo '<input type = "hidden" name = "to" value = "'.$_POST["to"].'">';
                echo '<input type = "hidden" name = "team" value = "'.$_POST["team"].'">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-danger">Delete</button>';
                echo '</form>';

                echo '</td>';
            echo '</tr>';
            $i++;

            }
            echo '<tr>';
                echo '<td><p align="center"><button type="submit" class="btn-danger btn-sm" name="save">DELETE</button></p></td>';
            echo '</tr>';
            echo '</form>';

        }
        else
        {
            echo '
            <table class = "table-bordered" width = "100%">
            <thead>
            <tr>
            <th width = "5%">id</th>
            <th width = "12%">Date</th>
            <th width = "23%">Task Name</th>
            <th width = "10%">Status</th>
            <th width = "7%">Action</th>
            </tr>
            <tr>
            <td colspan="5">No report found</td>
            </tr>';
        }
        echo '</body></table></div></div>';

        }

?>
</code>```

delete.php

```<code>  <?php

        $report_id = $_POST['report_id'];

        $sql = "DELETE FROM ot_report WHERE report_id=:report_id";
        $query = $conn->prepare($sql);
        $query->execute(array(':report_id' => $report_id));

        header("Location: dashboard_engineer2.php");

  ?>
</code>```

Can anyone help me on how to fix this?

答:
I not PHP developer well, But I guess when you redirect on delete.php,
on dashboard_engineer2.php it does not exist $_POST["from"], $_POST["to"], $_POST["team"] params.So if will return false and code on if will not excute, please debug on it.
Solution is you should past it as get parameter when redirect .

Body:
I have a problem with my delete function. Before that, I will brief to you about the flow of the system

1) At dashboard_engineer.php, there's 3 select options which is team, time from and time to.

2) user need to select 3 select option and press button "Search" to display the result.

3) The result will display at dashboard_engineer2.php.

4) The result will display all data rows and each row contains one delete button.

My problem is, after I click button delete, it was successful delete but the dashboard_engineer2.php page doesn't display the result that same as point 3 above. The result empty.

What I want is that, after delete, the dashboard_engineer2.php will display the remaining data rows that already filtered before. Below is my code.

dashboard_engineer.php

<?php

    $smt = $conn->prepare("SELECT * FROM ot_team INNER JOIN ot_users ON ot_team.team_id = ot_users.team_id WHERE ot_users.roles_id = 7 AND ot_users.team_id <> 1 ORDER BY ot_users.fullname ASC");
    $smt->execute();
    $data = $smt->fetchAll();

?>

<form method = 'post' action = 'dashboard_engineer2.php' >

    <select class="form-control"  name="team" id="team" required>
      <option value="">Please select...</option>
      <?php foreach ($data as $row2): ?>
      <option value= <?php echo $row2["team_id"]; ?> ><?php echo $row2["fullname"]; ?></option>
      <?php endforeach ?>
    </select>

  <input type="text" name="from" id="from" class="form-control" placeholder="From" required>

  <input type="text" name="to" id="to" class="form-control" placeholder="To" required>

  <button type="submit" value="Search" class="btn btn-primary" >Send</button>
</form>

dashboard_engineer2.php

<?php

    if(isset($_POST["from"], $_POST["to"], $_POST["team"])){

        $result = '';
        $query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$_POST["team"]."' AND report_date BETWEEN '".$_POST["from"]."' AND '".$_POST["to"]."' ORDER BY ot_report.report_date DESC";
        $sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
        $sql -> execute();

        if($sql->rowCount() > 0){

        echo'

        <input type="checkbox" id="checkAl"> All
        id
        Date
        Task Name
        Status
        Action

';

            $i=0;

            while($row = $sql->fetch(PDO::FETCH_ASSOC)){

            $datereport = $row['report_date'];
            $datereport2 = strtotime($datereport);
            $report_date = date('d M Y', $datereport2);

            $report_id = $row["report_id"];

            echo'
';
                echo '<input type="checkbox" id="checkItem" name="check[]" value='.$row['report_id'].'>	';
                echo ''.$report_id.'	';
                echo ''.$report_date.'	';
                echo ''.$row["task_name"].'	';
                echo ''.$row["report_status"].'	';
                echo '';
                echo '<form action = "view_task/view_task.php" method = "post">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-primary">View</button>';
                echo '</form>';

                echo "<form action = 'delete.php' method = 'post' onClick=\"return confirm('Do you want to remove team?')\">";
                echo '<input type = "hidden" name = "from" value = "'.$_POST["from"].'">';
                echo '<input type = "hidden" name = "to" value = "'.$_POST["to"].'">';
                echo '<input type = "hidden" name = "team" value = "'.$_POST["team"].'">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-danger">Delete</button>';
                echo '</form>';

                echo '	';
            echo '
';
            $i++;

            }
            echo '
';
                echo '
<button type="submit" class="btn-danger btn-sm" name="save">DELETE</button>
	';
            echo '
';
            echo '</form>';

        }
        else
        {
            echo '

            id
            Date
            Task Name
            Status
            Action

            No report found

';
        }
        echo '

';

        }

?>

delete.php

  <?php

        $report_id = $_POST['report_id'];

        $sql = "DELETE FROM ot_report WHERE report_id=:report_id";
        $query = $conn->prepare($sql);
        $query->execute(array(':report_id' => $report_id));

        header("Location: dashboard_engineer2.php");

  ?>

Can anyone help me on how to fix this?


问:
Get unminified JS from rails assets pipeline
How can I run the rails assets pipeline from the terminal to get un-minified javascript out?

I was able to run RAILS_ENV=development bundle exec rake assets:precompile, but this appears to have generated bundles, and what I'm looking for is simply to have all coffeescript transpiled to javascript, but not minified and not bundled. We simply need to remove coffeescript from our codebase.

I've also tried the npm module decaffeinate, but this generates different results from the rails assets pipeline, and breaks all of our tests.

答:
Someone directed me to this article:
http://scottwb.com/blog/2012/06/30/compile-a-single-coffeescript-file-from-your-rails-project/ and I updated it to give me the option to run recursively on a directory, or once on a single file. I added this to lib/tasks/ and it worked like a charm. I added a test for sprockets-style directives, which start with #= require, because the CoffeeScript compiler strips out all comments, which causes everything to break. Instead, I converted all skipped files to JS manually and included the directives as //= require, and that worked.

```<code>namespace :coffee do

  def do_one(filepath)
    File.write(filepath.chomp(".coffee"), CoffeeScript.compile(File.open(filepath)))
    File.rename(filepath, filepath.chomp(".js.coffee") + ".backup")
  end

  def cs_task(path)
    Dir.glob("#{path.chomp("/")}/*.js.coffee").each do |filename|
      file = File.open(filename)

      if (file.read[/\= require/])
        puts "skip #{filename}"
      else
        puts "process #{filename}"
        do_one(filename)
      end
    end
    Dir.glob("#{path.chomp("/")}/*/").each do |child_path|
      cs_task(child_path)
    end
  end

  task :cancel, :path do |t, args|
    cs_task(args.path)
  end

  task :show, :path do |t, args|
    puts CoffeeScript.compile(File.open(args.path))
  end

  task :one_off, :path do |t, args|
    do_one(args.path)
  end
end
</code>```

Body:
Someone directed me to this article:
http://scottwb.com/blog/2012/06/30/compile-a-single-coffeescript-file-from-your-rails-project/ and I updated it to give me the option to run recursively on a directory, or once on a single file. I added this to lib/tasks/ and it worked like a charm. I added a test for sprockets-style directives, which start with #= require, because the CoffeeScript compiler strips out all comments, which causes everything to break. Instead, I converted all skipped files to JS manually and included the directives as //= require, and that worked.

namespace :coffee do

  def do_one(filepath)
    File.write(filepath.chomp(".coffee"), CoffeeScript.compile(File.open(filepath)))
    File.rename(filepath, filepath.chomp(".js.coffee") + ".backup")
  end

  def cs_task(path)
    Dir.glob("#{path.chomp("/")}/*.js.coffee").each do |filename|
      file = File.open(filename)

      if (file.read[/\= require/])
        puts "skip #{filename}"
      else
        puts "process #{filename}"
        do_one(filename)
      end
    end
    Dir.glob("#{path.chomp("/")}/*/").each do |child_path|
      cs_task(child_path)
    end
  end

  task :cancel, :path do |t, args|
    cs_task(args.path)
  end

  task :show, :path do |t, args|
    puts CoffeeScript.compile(File.open(args.path))
  end

  task :one_off, :path do |t, args|
    do_one(args.path)
  end
end


问:
Generic procedure in aws Redshift db
I am trying to develop generic procedure in AWS Redshift DB which can accept table name, schema name as input parameters and while calling the procedure I am getting:

SQL Error [500310] [42601]: Amazon Invalid operation: syntax error

My procedure is:

 CREATE OR REPLACE PROCEDURE purgingtbl(vschema IN  VARCHAR,
                                        vtable  IN VARCHAR,
                                        columnname IN VARCHAR)
AS $$
DECLARE
 Srcedate            VARCHAR(15);

BEGIN
    Raise info 'vschema = %, vtable = %,columnname = %', vschema,vtable,columnname;

select into Srcedate count(*) from 'vschema'.'vtable' where src_proc_dt < (Current_date - 90) and 'columnname' is NOT NULL;
     ---RAISE INFO 'Date in  Landingzone table greater than 90 days is = %', Srcedate;

END;
$$ LANGUAGE plpgsql;

call purgingtbl('schemaname', 'tablename');
```

Can any one help?

答:
This part looks a little strange:

select into Srcedate count(*) from 'vschema'.'vtable'
```

<p>The syntax for <code>SELECT INTO</code> is:</p>

```SELECT
[ TOP number ] [ ALL | DISTINCT ]
* | expression [ AS output_name ] [, ...]
INTO [ TEMPORARY | TEMP ] [ TABLE ] new_table
[ FROM table_reference [, ...] ]
```

<p>So, it should probably be:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT COUNT(*) INTO Srcedate FROM 'vschema'.'vtable' WHERE ...
</code>```

You can test it by running it as a normal command, outside the stored procedure.

Title: Generic procedure in aws Redshift db

Body:
I am trying to develop generic procedure in AWS Redshift DB which can accept table name, schema name as input parameters and while calling the procedure I am getting:

SQL Error [500310] [42601]: Amazon Invalid operation: syntax error

My procedure is:

 CREATE OR REPLACE PROCEDURE purgingtbl(vschema IN  VARCHAR,
                                        vtable  IN VARCHAR,
                                        columnname IN VARCHAR)
AS $$
DECLARE
 Srcedate            VARCHAR(15);

BEGIN
    Raise info 'vschema = %, vtable = %,columnname = %', vschema,vtable,columnname;

select into Srcedate count(*) from 'vschema'.'vtable' where src_proc_dt < (Current_date - 90) and 'columnname' is NOT NULL;
     ---RAISE INFO 'Date in  Landingzone table greater than 90 days is = %', Srcedate;

END;
$$ LANGUAGE plpgsql;

call purgingtbl('schemaname', 'tablename');

Can any one help?

Body:
This part looks a little strange:

select into Srcedate count(*) from 'vschema'.'vtable'

The syntax for SELECT INTO is:

SELECT
[ TOP number ] [ ALL | DISTINCT ]
* | expression [ AS output_name ] [, ...]
INTO [ TEMPORARY | TEMP ] [ TABLE ] new_table
[ FROM table_reference [, ...] ]

So, it should probably be:

SELECT COUNT(*) INTO Srcedate FROM 'vschema'.'vtable' WHERE ...

You can test it by running it as a normal command, outside the stored procedure.


问:
how to manage variable inside of json value string?
I have variable cardholder in my karate-config file.

I assigned it to the new entrID variable.

The main thing that i am building JSON as a String..

```<code> * def entrID = cardholder
 * def requestContactHistoryAdd =
   """
   {
   "RequestBody": "{ \"ENTR_ID\" : \"entrID\", \"BHVR_ID\" : \"VRU\", }"
   }
   """
</code>```

Now how can i provide it inside of my json RequestBody?

答:
i solved it also like this

```<code> * def entrID = someValueFromSomeWhere
 * def bodyValue = "{ \"ENTR_ID\":\"" + entrID + "\", \"BHVR_ID\" : \"VRU\" }"
 * def requestContactHistoryAdd =
   """
   {
   "RequestBody": "#(bodyValue)"
   }
   """
</code>```

we can also do this way

```<code> * def bodyValue = "{ \"ENTR_ID\":\"" + someValueFromSomeWhere + "\", \"BHVR_ID\" : \"VRU\" }"
 * def requestContactHistoryAdd =
  """
  {
  "RequestBody": "#(bodyValue)"
  }
  """

</code>```

Body:
I have variable cardholder in my karate-config file.

I assigned it to the new entrID variable.

The main thing that i am building JSON as a String..

 * def entrID = cardholder
 * def requestContactHistoryAdd =
   """
   {
   "RequestBody": "{ \"ENTR_ID\" : \"entrID\", \"BHVR_ID\" : \"VRU\", }"
   }
   """

Now how can i provide it inside of my json RequestBody?

Body:
i solved it also like this

 * def entrID = someValueFromSomeWhere
 * def bodyValue = "{ \"ENTR_ID\":\"" + entrID + "\", \"BHVR_ID\" : \"VRU\" }"
 * def requestContactHistoryAdd =
   """
   {
   "RequestBody": "#(bodyValue)"
   }
   """

we can also do this way

 * def bodyValue = "{ \"ENTR_ID\":\"" + someValueFromSomeWhere + "\", \"BHVR_ID\" : \"VRU\" }"
 * def requestContactHistoryAdd =
  """
  {
  "RequestBody": "#(bodyValue)"
  }
  """


问:
Can not hook into Microsoft Store Application with SetWindowsHookEx and injected DLL
I am trying to retrieve input messages. First i tried to do it globally, but the api says that Microsoft Store apps will not get injected. So i tried an application specific approach, which worked with a notepad app, but not with a Microsoft Whiteboard app, which makes me think its not really possible afterall.

Injected DLL:

```<code>// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#pragma data_seg("Shared")
#pragma data_seg()
#pragma comment(linker,"/section:Shared,rws")

#include <windows.h>
#include <stdio.h>

HHOOK tHook;

extern "C" __declspec(dllexport) int meconnect(int code, WPARAM wParam, LPARAM lParam) {
    BOOL EnableMouseInPointer = TRUE;
    if (code == HC_ACTION) {
        LPMSG data = (LPMSG)lParam;
        if (data->message == WM_KEYDOWN || data->message == WM_POINTERUPDATE) {
            MessageBoxA(NULL, "Hi", NULL, 0);
        }
    }
    return(CallNextHookEx(tHook, code, wParam, lParam));
}
</code>```

Python application code:

```<code>import ctypes
import os
from ctypes import *
from ctypes.wintypes import *

user32 = WinDLL('user32', use_last_error=True)
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

user32.EnableMouseInPointer(True)

HC_ACTION = 0
WH_MOUSE_LL = 14
WH_KEYBOARD_LL = 13
WH_GETMESSAGE = 3
WH_CALLWNDPROC = 4

def errcheck_bool(result, func, args):
    if not result:
        raise WinError(get_last_error())
    return args

user32.SetWindowsHookExA.errcheck = errcheck_bool
user32.SetWindowsHookExA.restype = HHOOK
user32.SetWindowsHookExA.argtypes = (c_int,     # _In_ idHook
                                     HOOKPROC,  # _In_ lpfn
                                     HINSTANCE, # _In_ hMod
                                     DWORD)     # _In_ dwThreadId

user32.CallNextHookEx.restype = LRESULT
user32.CallNextHookEx.argtypes = (HHOOK,  # _In_opt_ hhk
                                  c_int,  # _In_     nCode
                                  WPARAM, # _In_     wParam
                                  LPARAM) # _In_     lParam

user32.GetMessageW.argtypes = (LPMSG, # _Out_    lpMsg
                               HWND,  # _In_opt_ hWnd
                               UINT,  # _In_     wMsgFilterMin
                               UINT)  # _In_     wMsgFilterMax

user32.TranslateMessage.argtypes = (LPMSG,)
user32.DispatchMessageW.argtypes = (LPMSG,)

GetModuleHandle = ctypes.windll.kernel32.GetModuleHandleA
GetModuleHandle.restype = POINTER(c_void_p)

LoadLibrary = ctypes.windll.kernel32.LoadLibraryA
LoadLibrary.restype = HINSTANCE

GetProcAddress = ctypes.windll.kernel32.GetProcAddress
GetProcAddress.restype = HOOKPROC

user32.GetWindowThreadProcessId.restype = DWORD

def pointer_msg_loop():
    dll_name = 'Dll.dll'
    dll_abspath = os.path.abspath(os.path.join(os.path.dirname(__file__), '.', dll_name))
    print(dll_abspath)
    lib = LoadLibrary('C:\\Users\\Braun\\Documents\\Git Kraken\\ba-oliver-braun-logging-tool-code\\MessagesDll\\x64\\Debug\\HOOKDLL.dll')
    handle = GetModuleHandle('C:\\Users\\Braun\\Documents\\Git Kraken\\ba-oliver-braun-logging-tool-code\\MessagesDll\\x64\\Debug\\HOOKDLL.dll')
    print(lib)
    print(handle)
    procedure = GetProcAddress(handle, "meconnect")
    print(procedure)
    if (procedure):
        print('correct value procedure')
        white = user32.FindWindowA(None, 'Microsoft Whiteboard')
        print(white)
        threadId = user32.GetWindowThreadProcessId(white, None)

        tHook = user32.SetWindowsHookExA(WH_GETMESSAGE, procedure, lib, threadId)
        time.sleep(30)
        user32.UnhookWindowsHookEx(tHook)
        print(tHook)
        msg = MSG()
        while True:
            bRet = user32.GetMessageW(byref(msg), None, 0, 0)
            if not bRet:
                break
            if bRet == -1:
                raise WinError(get_last_error())
            user32.TranslateMessage(byref(msg))
            user32.DispatchMessageW(byref(msg))

if __name__ == '__main__':
    import time
    import datetime
    import threading
    startTime = datetime.datetime.now()
    #print(ctypes.windll.user32.GetSystemMetrics(94))
    #tmouse = threading.Thread(target=mouse_msg_loop)
    #tkeyboard = threading.Thread(target=keyboard_msg_loop)
    ttouch = threading.Thread(target=pointer_msg_loop)
    #tmouse.start()
    #tkeyboard.start()
    ttouch.start()
    while True:
        try:
            time.sleep(1)
        except KeyboardInterrupt:
       #     user32.PostThreadMessageW(tmouse.ident, WM_QUIT, 0, 0)
            break
</code>```

答:
Windows Store app development If dwThreadId is zero, then window hook DLLs are not loaded in-process for the Windows Store app
  processes and the Windows Runtime broker process unless they are
  installed by either UIAccess processes (accessibility tools). The
  notification is delivered on the installer's thread for these hooks:

WH_JOURNALPLAYBACK

WH_JOURNALRECORD

WH_KEYBOARD

WH_KEYBOARD_LL

WH_MOUSE

WH_MOUSE_LL

This behavior is similar to what happens when there is an architecture
  mismatch between the hook DLL and the target application process, for
  example, when the hook DLL is 32-bit and the application process
  64-bit.

The doc pointed out, In addition to the hooks mentioned above, other hooks cannot be applied to the Windows Store app.

Body:
I am trying to retrieve input messages. First i tried to do it globally, but the api says that Microsoft Store apps will not get injected. So i tried an application specific approach, which worked with a notepad app, but not with a Microsoft Whiteboard app, which makes me think its not really possible afterall.

Injected DLL:

// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#pragma data_seg("Shared")
#pragma data_seg()
#pragma comment(linker,"/section:Shared,rws")

#include <windows.h>
#include <stdio.h>

HHOOK tHook;

extern "C" __declspec(dllexport) int meconnect(int code, WPARAM wParam, LPARAM lParam) {
    BOOL EnableMouseInPointer = TRUE;
    if (code == HC_ACTION) {
        LPMSG data = (LPMSG)lParam;
        if (data->message == WM_KEYDOWN || data->message == WM_POINTERUPDATE) {
            MessageBoxA(NULL, "Hi", NULL, 0);
        }
    }
    return(CallNextHookEx(tHook, code, wParam, lParam));
}

Python application code:

import ctypes
import os
from ctypes import *
from ctypes.wintypes import *

user32 = WinDLL('user32', use_last_error=True)
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

user32.EnableMouseInPointer(True)

HC_ACTION = 0
WH_MOUSE_LL = 14
WH_KEYBOARD_LL = 13
WH_GETMESSAGE = 3
WH_CALLWNDPROC = 4

def errcheck_bool(result, func, args):
    if not result:
        raise WinError(get_last_error())
    return args

user32.SetWindowsHookExA.errcheck = errcheck_bool
user32.SetWindowsHookExA.restype = HHOOK
user32.SetWindowsHookExA.argtypes = (c_int,     # _In_ idHook
                                     HOOKPROC,  # _In_ lpfn
                                     HINSTANCE, # _In_ hMod
                                     DWORD)     # _In_ dwThreadId

user32.CallNextHookEx.restype = LRESULT
user32.CallNextHookEx.argtypes = (HHOOK,  # _In_opt_ hhk
                                  c_int,  # _In_     nCode
                                  WPARAM, # _In_     wParam
                                  LPARAM) # _In_     lParam

user32.GetMessageW.argtypes = (LPMSG, # _Out_    lpMsg
                               HWND,  # _In_opt_ hWnd
                               UINT,  # _In_     wMsgFilterMin
                               UINT)  # _In_     wMsgFilterMax

user32.TranslateMessage.argtypes = (LPMSG,)
user32.DispatchMessageW.argtypes = (LPMSG,)

GetModuleHandle = ctypes.windll.kernel32.GetModuleHandleA
GetModuleHandle.restype = POINTER(c_void_p)

LoadLibrary = ctypes.windll.kernel32.LoadLibraryA
LoadLibrary.restype = HINSTANCE

GetProcAddress = ctypes.windll.kernel32.GetProcAddress
GetProcAddress.restype = HOOKPROC

user32.GetWindowThreadProcessId.restype = DWORD

def pointer_msg_loop():
    dll_name = 'Dll.dll'
    dll_abspath = os.path.abspath(os.path.join(os.path.dirname(__file__), '.', dll_name))
    print(dll_abspath)
    lib = LoadLibrary('C:\\Users\\Braun\\Documents\\Git Kraken\\ba-oliver-braun-logging-tool-code\\MessagesDll\\x64\\Debug\\HOOKDLL.dll')
    handle = GetModuleHandle('C:\\Users\\Braun\\Documents\\Git Kraken\\ba-oliver-braun-logging-tool-code\\MessagesDll\\x64\\Debug\\HOOKDLL.dll')
    print(lib)
    print(handle)
    procedure = GetProcAddress(handle, "meconnect")
    print(procedure)
    if (procedure):
        print('correct value procedure')
        white = user32.FindWindowA(None, 'Microsoft Whiteboard')
        print(white)
        threadId = user32.GetWindowThreadProcessId(white, None)

        tHook = user32.SetWindowsHookExA(WH_GETMESSAGE, procedure, lib, threadId)
        time.sleep(30)
        user32.UnhookWindowsHookEx(tHook)
        print(tHook)
        msg = MSG()
        while True:
            bRet = user32.GetMessageW(byref(msg), None, 0, 0)
            if not bRet:
                break
            if bRet == -1:
                raise WinError(get_last_error())
            user32.TranslateMessage(byref(msg))
            user32.DispatchMessageW(byref(msg))

if __name__ == '__main__':
    import time
    import datetime
    import threading
    startTime = datetime.datetime.now()
    #print(ctypes.windll.user32.GetSystemMetrics(94))
    #tmouse = threading.Thread(target=mouse_msg_loop)
    #tkeyboard = threading.Thread(target=keyboard_msg_loop)
    ttouch = threading.Thread(target=pointer_msg_loop)
    #tmouse.start()
    #tkeyboard.start()
    ttouch.start()
    while True:
        try:
            time.sleep(1)
        except KeyboardInterrupt:
       #     user32.PostThreadMessageW(tmouse.ident, WM_QUIT, 0, 0)
            break


问:
What is the best way to request input from user
I want to request info from user. See example below:

```<code>Your Name: |_________|
      Age: |_________|
  Address: |_________|
</code>```

What is the best way to code the above in HTML?

It is best to implement it in div. Have left and right div for label and input

It is best to implement it in table

答: Any more I do forms in a table since I hate fighting with the differences in browsers with how they position controls with css.

Body:
I want to request info from user. See example below:

Your Name: |_________|
      Age: |_________|
  Address: |_________|

What is the best way to code the above in HTML?

It is best to implement it in div. Have left and right div for label and input

It is best to implement it in table


问:
Multiplication in F#
I can't get my answer correctly from my multiplication function

My code is:

```<code>let List = [77; 14; 89; 93; 201]
    let rec Mult =
       match n with
       | 24 -> 24
       | _-> n * n
    for i = 1 to 5 do
       printfn "Multiplication: %A" (Mult i)
</code>```

My question is how do I get I get it to call my List?

答:
```<code>let List = [24; 103; 7; 13; 445]

let rec Mult = function
    | head :: tail -> head * (Mult tail)
    | [] -> 1

let result = Mult List
printfn "%A" result
</code>```

Title: Multiplication in F#

Body:
I can't get my answer correctly from my multiplication function

My code is:

let List = [77; 14; 89; 93; 201]
    let rec Mult =
       match n with
       | 24 -> 24
       | _-> n * n
    for i = 1 to 5 do
       printfn "Multiplication: %A" (Mult i)

My question is how do I get I get it to call my List?


问:
Where is the global git config data stored?
When using git config --global to set things up, to which file will it write?

Example:

```<code>git config --global core.editor "blah"
</code>```

I can't find it at these places:

```<code>C:\Program Files\Git\etc\gitconfig

C:\myapp\.git\config
</code>```

I have not set an ENV?

My Git version: 1.6.5.1.1367.gcd48 –
on Windows 7

答:
.gitconfig file location

macOS testing OK

global

# global config
$ cd ~/.gitconfig

# view global config
$ git config --global -l
```

<h2>local</h2>

<pre class="lang-sh prettyprint-override"><code># local config
$ cd .git/config

# view local config
$ git config -l

</code>```

maybe a bonus for you：Vim or VSCode for edit git config

# open config with Vim

# global config
$ vim ~/.gitconfig

# local config
$ vim .git/config

# open config with VSCode

# global config
$ code ~/.gitconfig

# local config
$ code .git/config

```

Body:
When using git config --global to set things up, to which file will it write?

Example:

git config --global core.editor "blah"

I can't find it at these places:

C:\Program Files\Git\etc\gitconfig

C:\myapp\.git\config

I have not set an ENV?

My Git version: 1.6.5.1.1367.gcd48 –
on Windows 7

Body:
.gitconfig file location

macOS testing OK

global

# global config
$ cd ~/.gitconfig

# view global config
$ git config --global -l

local

# local config
$ cd .git/config

# view local config
$ git config -l

maybe a bonus for you：Vim or VSCode for edit git config

# open config with Vim

# global config
$ vim ~/.gitconfig

# local config
$ vim .git/config

# open config with VSCode

# global config
$ code ~/.gitconfig

# local config
$ code .git/config


问:
How do you handle adding a CORS header in a Spring Boot server with graphql-kotlin?
I am building a simple Spring Server project using the GraphQL Kotlin library created & open-sourced by Expedia. I have a backend up and running, talking to the datastore, and I'm able to fetch data by sending queries via Playground.

When I try to connect from my React frontend (using Apollo), the initial OPTIONS request gets a 404 response due to a CORS issue. I am relatively new to Spring Boot and there are a lot of potential approaches documented on SO and elsewhere.

How do I intercept the response & add the appropriate Access-Control-Allow-Origin header?

答:
Only adding the next configuration in spring boot-kotlin server work with React and Apollo: </p>

```<code>import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.web.cors.reactive.CorsUtils
import org.springframework.web.server.WebFilter
import reactor.core.publisher.Mono

@Configuration
class ReactiveConfigurations {

    companion object {
        const val ALLOWED_HEADERS = "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN"
        const val ALLOWED_METHODS = "GET, PUT, POST, DELETE, OPTIONS"
        const val ALLOWED_ORIGIN = "*"
        const val MAX_AGE = "3600"
    }

    @Bean
    fun corsFilter(): WebFilter {
        return WebFilter { ctx, chain ->
            val request = ctx.request
            if (CorsUtils.isCorsRequest(request)) {
                val response = ctx.response
                val headers = response.headers
                headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN)
                headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS)
                headers.add("Access-Control-Max-Age", MAX_AGE)
                headers.add("Access-Control-Allow-Headers", ALLOWED_HEADERS)
                if (request.method === HttpMethod.OPTIONS) {
                    response.statusCode = HttpStatus.OK
                    return@WebFilter Mono.empty<Void>()
                }
            }
            chain.filter(ctx)
        }
    }
}

</code>```

Body:
Only adding the next configuration in spring boot-kotlin server work with React and Apollo:

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.web.cors.reactive.CorsUtils
import org.springframework.web.server.WebFilter
import reactor.core.publisher.Mono

@Configuration
class ReactiveConfigurations {

    companion object {
        const val ALLOWED_HEADERS = "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN"
        const val ALLOWED_METHODS = "GET, PUT, POST, DELETE, OPTIONS"
        const val ALLOWED_ORIGIN = "*"
        const val MAX_AGE = "3600"
    }

    @Bean
    fun corsFilter(): WebFilter {
        return WebFilter { ctx, chain ->
            val request = ctx.request
            if (CorsUtils.isCorsRequest(request)) {
                val response = ctx.response
                val headers = response.headers
                headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN)
                headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS)
                headers.add("Access-Control-Max-Age", MAX_AGE)
                headers.add("Access-Control-Allow-Headers", ALLOWED_HEADERS)
                if (request.method === HttpMethod.OPTIONS) {
                    response.statusCode = HttpStatus.OK
                    return@WebFilter Mono.empty<Void>()
                }
            }
            chain.filter(ctx)
        }
    }
}


问:
How can I convert a date format MM-DD-YY HH:MI AM/PM to YYYY-MM-DD in Shell Scripting
I am currently trying to convert a date format using the below command

```<code>while IFS=$'\t' read -r -a ValArray
do
FILEDATE=${ValArray[0]}
COMPDATE=`date -d  $FILEDATE +'%Y-%m-%d'`
</code>```

I get the following error while trying to dynamically fetch a value from file and compare it with today's date

```<code>++ read -r -a ValArray
++ FILEDATE='02-11-20 2:25 AM'
+++ date -d 02-11-20 2:25 AM +%Y-%m-%d
date: extra operand `AM'
Try `date --help' for more information.
</code>```

How can I override this and get the date in YYYY-MM-DD format ?

答:
Using Parameter Expansions

POSIX shell provides parameter expansions to remove a substring from a string beginning from the left (front) or right (back) of the string:

```<code>${string#substring}     Strip shortest match of $substring from front of $string
${string##substring}    Strip longest match of $substring from front of $string
${string%substring}     Strip shortest match of $substring from back of $string
${string%%substring}    Strip longest match of $substring from back of $string
</code>```

The substring can contain normal file globbing, e.g. '*', '?', etc.

In your case (with f='02-11-20 2:25 AM'), you can remove the various substrings from the left and right to obtain the month, day, and year. You can then multiply the 2-digit year by 100 to obtain the 4-digit year as follows:

```<code>f='02-11-20 2:25 AM'
f="${f% *}"     # trim AM (to first space) from right (back)
f="${f% *}"     # trim 2:25 (to first space) from right
m="${f%%-*}"    # trim to last - from right leaving month
y="${f##*-}"    # trim to last - from left (front) leaving year
d="${f#*-}"     # trim to first - from left leaving day-year
d="${d%-*}"     # trim to first - from right leaving day
y=$((y*100))    # mulitply 2-digit year by 100
printf "%4d-%02d-%02d\n" "$y" "$m" "$d"     # output in desired format
</code>```

Using expr substr string start length

POSIX also provides the old expr .... set of string manipulation functions, though since command substitutions are involved, it will likely be slower than the built-in parameter expansions. The one relevant here is:

```<code>expr substr string start length
</code>```

To extract the length character substring from string beginning at index (1-based) start. You can retrieve the month, day and year using:

```<code>f='02-11-20 2:25 AM'
m=$(expr substr "$f" 1 2)                   # extract 2-digit substring at 1
d=$(expr substr "$f" 4 2)                   # extract 2-digit substring at 4
y=$(expr substr "$f" 7 2)                   # extract 2-digit substring at 7
y=$((y*100))                                # mulitply 2-digit year by 100
printf "%4d-%02d-%02d\n" "$y" "$m" "$d"     # output in desired format
</code>```

(note: just as when using [...] always quote your variables when using expr ...)

Using sed

You can also use the basic sed substitution with three capture groups and three backreferences to reinsert the date components in the correct order. The capture groups \(text\) capture the text between them (represented by the regular expression text) and in the replacement part of the expression the captured text can be reinserted using the numbered backreference \1 for the first capture, \2 for he second and so on, e.g.

```<code>f='02-11-20 2:25 AM'
echo "$f" | sed 's/^\(..\)-\(..\)-\(..\).*$/\300-\1-\2/'
</code>```

Example Output

Both approaches produce the same output:

```<code>2000-02-11
</code>```

Let me know if you have further questions.

Body:
I am currently trying to convert a date format using the below command

while IFS=$'\t' read -r -a ValArray
do
FILEDATE=${ValArray[0]}
COMPDATE=`date -d  $FILEDATE +'%Y-%m-%d'`

I get the following error while trying to dynamically fetch a value from file and compare it with today's date

++ read -r -a ValArray
++ FILEDATE='02-11-20 2:25 AM'
+++ date -d 02-11-20 2:25 AM +%Y-%m-%d
date: extra operand `AM'
Try `date --help' for more information.

How can I override this and get the date in YYYY-MM-DD format ?

Body:
Using Parameter Expansions

POSIX shell provides parameter expansions to remove a substring from a string beginning from the left (front) or right (back) of the string:

${string#substring}     Strip shortest match of $substring from front of $string
${string##substring}    Strip longest match of $substring from front of $string
${string%substring}     Strip shortest match of $substring from back of $string
${string%%substring}    Strip longest match of $substring from back of $string

The substring can contain normal file globbing, e.g. '*', '?', etc.

In your case (with f='02-11-20 2:25 AM'), you can remove the various substrings from the left and right to obtain the month, day, and year. You can then multiply the 2-digit year by 100 to obtain the 4-digit year as follows:

f='02-11-20 2:25 AM'
f="${f% *}"     # trim AM (to first space) from right (back)
f="${f% *}"     # trim 2:25 (to first space) from right
m="${f%%-*}"    # trim to last - from right leaving month
y="${f##*-}"    # trim to last - from left (front) leaving year
d="${f#*-}"     # trim to first - from left leaving day-year
d="${d%-*}"     # trim to first - from right leaving day
y=$((y*100))    # mulitply 2-digit year by 100
printf "%4d-%02d-%02d\n" "$y" "$m" "$d"     # output in desired format

Using expr substr string start length

POSIX also provides the old expr .... set of string manipulation functions, though since command substitutions are involved, it will likely be slower than the built-in parameter expansions. The one relevant here is:

expr substr string start length

To extract the length character substring from string beginning at index (1-based) start. You can retrieve the month, day and year using:

f='02-11-20 2:25 AM'
m=$(expr substr "$f" 1 2)                   # extract 2-digit substring at 1
d=$(expr substr "$f" 4 2)                   # extract 2-digit substring at 4
y=$(expr substr "$f" 7 2)                   # extract 2-digit substring at 7
y=$((y*100))                                # mulitply 2-digit year by 100
printf "%4d-%02d-%02d\n" "$y" "$m" "$d"     # output in desired format

(note: just as when using [...] always quote your variables when using expr ...)

Using sed

You can also use the basic sed substitution with three capture groups and three backreferences to reinsert the date components in the correct order. The capture groups \(text\) capture the text between them (represented by the regular expression text) and in the replacement part of the expression the captured text can be reinserted using the numbered backreference \1 for the first capture, \2 for he second and so on, e.g.

f='02-11-20 2:25 AM'
echo "$f" | sed 's/^\(..\)-\(..\)-\(..\).*$/\300-\1-\2/'

Example Output

Both approaches produce the same output:

2000-02-11

Let me know if you have further questions.


问:
Why do tuples not get changed whereas lists do?
Why does only the first tuple change in example II whereas both lists get changed in example I? Please consider these two programs and their respective output (I and II).

I.

```<code>L1 = [1,2,3,4]
L2 = L1
L2.append(5)
print("L1: ", L1)
print("L2: ", L2)
</code>```

Output:

```<code>L1: [1,2,3,4,5]
L2: [1,2,3,4,5]
</code>```

II.

```<code>L1=(1,2,3,4)
L2=L1
L2 += (5,)
print("L1: ", L1)
print("L2: ", L2)
</code>```

Output:

```<code>L1: (1,2,3,4)
L2: (1,2,3,4,5)
</code>```

答: Tuples are immutable, so only L2 is changing. As lists are mutable, both are changing then.</p>

OwnerDisplayName: anon

Body:
Why does only the first tuple change in example II whereas both lists get changed in example I? Please consider these two programs and their respective output (I and II).

I.

L1 = [1,2,3,4]
L2 = L1
L2.append(5)
print("L1: ", L1)
print("L2: ", L2)

Output:

L1: [1,2,3,4,5]
L2: [1,2,3,4,5]

II.

L1=(1,2,3,4)
L2=L1
L2 += (5,)
print("L1: ", L1)
print("L2: ", L2)

Output:

L1: (1,2,3,4)
L2: (1,2,3,4,5)


问:
Replace NaN in pandas DataFrame with random strings without using fillna
I have a pandas DataFrame like below

```<code>      NAME      EMAIL      HEIGHT      WEIGHT

1     jlka       NaN        170          70

2     qwer     eee@ttt      180          80

3     ioff       NaN        175          75

4     iowu     iou@add      170          60
</code>```

And I want to replace NaN in 'EMAIL' column with random strings with no duplicates, which does not necessarily contain @.

I have tried to make a def which generates random strings but NaNs were replaced with the same random string since I used 'fillna' method after all.

It seems like, and as I saw other Q$As, def in fillna works only once and replace all the NaN with the same values or strings came out from the def.

Should I try 'for' sentence to replace them one by one?

Or is there a more Pythonic way to replace them?

答:
you could try something like this:</p>

```<code>import pandas as pd
from numpy import nan
import random
import string

df = pd.DataFrame({
    'Name': ['aaa','bbb','CCC'],
    'Email': [nan,'ddd',nan]})

def processNan (x):
    return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10))

df['Email'] = df['Email'].apply(lambda x: processNan(x) if x is nan else x)
</code>```

Body:
I have a pandas DataFrame like below

      NAME      EMAIL      HEIGHT      WEIGHT

1     jlka       NaN        170          70

2     qwer     eee@ttt      180          80

3     ioff       NaN        175          75

4     iowu     iou@add      170          60

And I want to replace NaN in 'EMAIL' column with random strings with no duplicates, which does not necessarily contain @.

I have tried to make a def which generates random strings but NaNs were replaced with the same random string since I used 'fillna' method after all.

It seems like, and as I saw other Q$As, def in fillna works only once and replace all the NaN with the same values or strings came out from the def.

Should I try 'for' sentence to replace them one by one?

Or is there a more Pythonic way to replace them?

Body:
you could try something like this:

import pandas as pd
from numpy import nan
import random
import string

df = pd.DataFrame({
    'Name': ['aaa','bbb','CCC'],
    'Email': [nan,'ddd',nan]})

def processNan (x):
    return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10))

df['Email'] = df['Email'].apply(lambda x: processNan(x) if x is nan else x)


问:
Is it possible to create a unique constraint that includes the entire path of an ltree field?
I'm using the ltree extension in Postgres to manage paths for a tree. I want to ensure that the name field is unique for any given path on the tree. Can I accomplish this using a constraint or do I have to build this into the query?

```<code>  demo table
------------------------------
| name (text) | path (ltree) |
------------------------------
| a           | 1            |
------------------------------
| b           | 1.2          |
------------------------------
| b           | 1.3          |
------------------------------
| b           | 1.2.4        | <-- this should fail on insert
------------------------------
</code>```

If I have to build it into the query, does this potentially have a race condition if I use READ COMMITTED?

```<code>CREATE TABLE demo (
    name text NOT null,
    path ltree NOT null
);
CREATE INDEX path_gist_idx ON demo USING GIST (path);
INSERT INTO demo (name, path)
SELECT 'a', '1'
WHERE NOT EXISTS (
    SELECT * FROM demo WHERE name = 'a' AND (path <@ '1' OR path @> '1')
);
INSERT INTO demo (name, path)
SELECT 'b', '1.2'
WHERE NOT EXISTS (
    SELECT * FROM demo WHERE name = 'b' AND (path <@ '1.2' OR path @> '1.2')
);
INSERT INTO demo (name, path)
SELECT 'b', '1.3'
WHERE NOT EXISTS (
    SELECT * FROM demo WHERE name = 'b' AND (path <@ '1.3' OR path @> '1.3')
);
INSERT INTO demo (name, path)
SELECT 'b', '1.2.4'
WHERE NOT EXISTS (
    SELECT * FROM demo WHERE name = 'b' AND (path <@ '1.2.4' OR path @> '1.2.4')
);
SELECT * FROM demo;
</code>```

答:
There is a race condition if you use read committed.

You could in principle use an EXCLUDE constraint, except that there is no single self-commutative operator you can use. That means you would have to invent a new operator, maybe called <@>, and add it to ltree.  I think that this would be possible, but not something you would probably look forward to doing.

Could you just use serializable?

Body:
I'm using the ltree extension in Postgres to manage paths for a tree. I want to ensure that the name field is unique for any given path on the tree. Can I accomplish this using a constraint or do I have to build this into the query?

  demo table
------------------------------
| name (text) | path (ltree) |
------------------------------
| a           | 1            |
------------------------------
| b           | 1.2          |
------------------------------
| b           | 1.3          |
------------------------------
| b           | 1.2.4        | <-- this should fail on insert
------------------------------

If I have to build it into the query, does this potentially have a race condition if I use READ COMMITTED?

CREATE TABLE demo (
    name text NOT null,
    path ltree NOT null
);
CREATE INDEX path_gist_idx ON demo USING GIST (path);
INSERT INTO demo (name, path)
SELECT 'a', '1'
WHERE NOT EXISTS (
    SELECT * FROM demo WHERE name = 'a' AND (path <@ '1' OR path @> '1')
);
INSERT INTO demo (name, path)
SELECT 'b', '1.2'
WHERE NOT EXISTS (
    SELECT * FROM demo WHERE name = 'b' AND (path <@ '1.2' OR path @> '1.2')
);
INSERT INTO demo (name, path)
SELECT 'b', '1.3'
WHERE NOT EXISTS (
    SELECT * FROM demo WHERE name = 'b' AND (path <@ '1.3' OR path @> '1.3')
);
INSERT INTO demo (name, path)
SELECT 'b', '1.2.4'
WHERE NOT EXISTS (
    SELECT * FROM demo WHERE name = 'b' AND (path <@ '1.2.4' OR path @> '1.2.4')
);
SELECT * FROM demo;


问:
URL rewriting is rewriting ALL my files with two segments
This is my rule in web config

```<code><rule name="rewrite">
  <match url="^([^/]+)/([^/]+)?$" />
<action type="Rewrite" url="/review.aspx?c={R:1}&t={R:2}" appendQueryString="false" />
</rule>
</code>```

Which successfully turns review.aspx?c=value&t=value into /value/value

My problem now is, my /css/style.css now loads as review.aspx

Is there a way to stop this? Not only with CSS, but with all instances?

答:
Rewrite rule conditions makes it possible for you to limit the application of the rewrite rule, such that it only applies to those requests where the conditions have been met.

By defining a condition like the one below, you can ensure that rewriting only occurs for URLs that doesn't match an existing file.

```<code><rule name="rewrite">
  <match url="^([^/]+)/([^/]+)?$" />
  <conditions>
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
  </conditions>
  <action type="Rewrite" url="/review.aspx?c={R:1}&t={R:2}" appendQueryString="false" />
</rule>
</code>```

The way that it works is that for each request, before the rewrite occurs, the rewrite engine checks if the defined condition has been met and then skips the rewrite rule in case the condition wasn't met.

The condition we define is: The request must not refer to an actual file on disk.

The reason for this is that we only want the rewrite to applied to requests with virtual URLs like /value/value and not requests for static files like /css/style.css.

To break down exactly what the different attributes of the condition means:

input="{REQUEST_FILENAME}" tells the rewrite engine that we want to
perform a test against the REQUEST_FILENAME server variable. The
value of that variable would be something like
C:/mywebsite/value/value or C:/mywebsite/css/style.css.

matchType="IsFile" tells the engine to check if the above input matches an existing file on disk.

negate="true" tells the engine to invert the result of the check, such that the condition is met when the input does not match an existing file, instead of when it does match.

Body:
This is my rule in web config

<rule name="rewrite">
  <match url="^([^/]+)/([^/]+)?$" />
<action type="Rewrite" url="/review.aspx?c={R:1}&t={R:2}" appendQueryString="false" />
</rule>

Which successfully turns review.aspx?c=value&t=value into /value/value

My problem now is, my /css/style.css now loads as review.aspx

Is there a way to stop this? Not only with CSS, but with all instances?

Body:
Rewrite rule conditions makes it possible for you to limit the application of the rewrite rule, such that it only applies to those requests where the conditions have been met.

By defining a condition like the one below, you can ensure that rewriting only occurs for URLs that doesn't match an existing file.

<rule name="rewrite">
  <match url="^([^/]+)/([^/]+)?$" />
  <conditions>
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
  </conditions>
  <action type="Rewrite" url="/review.aspx?c={R:1}&amp;t={R:2}" appendQueryString="false" />
</rule>

The way that it works is that for each request, before the rewrite occurs, the rewrite engine checks if the defined condition has been met and then skips the rewrite rule in case the condition wasn't met.

The condition we define is: The request must not refer to an actual file on disk.

The reason for this is that we only want the rewrite to applied to requests with virtual URLs like /value/value and not requests for static files like /css/style.css.

To break down exactly what the different attributes of the condition means:

input="{REQUEST_FILENAME}" tells the rewrite engine that we want to
perform a test against the REQUEST_FILENAME server variable. The
value of that variable would be something like
C:/mywebsite/value/value or C:/mywebsite/css/style.css.

matchType="IsFile" tells the engine to check if the above input matches an existing file on disk.

negate="true" tells the engine to invert the result of the check, such that the condition is met when the input does not match an existing file, instead of when it does match.


问:
S3: Only allow files with certain pattern
I'm not sure if this is feasible. I'm looking for a way to limit the files that can be saved into an S3 bucket to a certain pattern (number.*, e.g. 2893.jpg or 18928.png). Can this be done thru IAM policy or is there another way?

Thanks

答:
There is no native way to do this. Permissions can be assigned to upload to a particular Prefix (folder), but there is no method for specifying permitted characters in a Key (filename).

You would likely want to implement a frontend that verifies filenames and allows upload via a pre-signed URL.

See: Uploading Objects Using Presigned URLs - Amazon S3


问:
Is it possible to calculate each all the numbers received on each day of the week from this list in Python? I don't understand splitting
```<code>import os
myFilePath = os.getcwd()
print(myFilePath)
calls = open('/Users/fake/Desktop/fakefolder/calls.txt')
mondayCalls = []
for adding in calls.readlines():
    mondayCalls.append(adding.strip())
calls.close()
print(mondayCalls)
</code>```

Here is the list that I generated from a txt file, I just want to add the total for all mondays, tuesdays etc. I would want to print

```<code>Monday = 29
Tuesday = 16 etc
</code>```

The list is longer but here is an example of the list that I have.

```<code>['Monday:21', 'Tuesday:6', 'Wednesday:8', 'Thursday:18', 'Friday:16', 'Saturday:4', 'Sunday:10', 'Monday:8']
</code>```

答:
Try this (explanation in code comments):</p>

```<code>list = ['Monday:21', 'Tuesday:6', 'Wednesday:8', 'Thursday:18', 'Friday:16', 'Saturday:4', 'Sunday:10', 'Monday:8']
# create a dictionary variable
days_dict = {}
# for every entry in the list
for entry in list:
    # split entry by ":" and take the first part of the entry
    day = entry.split(":")[0]
    # split entry by ":" and take the second part of the entry and convert it to an integer
    count = int(entry.split(":")[1])
    print (day)
    print (count)
    # if the day key is in the dictionary add to its count else create the key
    if day in days_dict:
        days_dict[day] += count
    else:
        days_dict[day] = count

print (days_dict)
# print Monday's count
print ('Monday Count = ' + str(days_dict['Monday']))
</code>```

Body:
import os
myFilePath = os.getcwd()
print(myFilePath)
calls = open('/Users/fake/Desktop/fakefolder/calls.txt')
mondayCalls = []
for adding in calls.readlines():
    mondayCalls.append(adding.strip())
calls.close()
print(mondayCalls)

Here is the list that I generated from a txt file, I just want to add the total for all mondays, tuesdays etc. I would want to print

Monday = 29
Tuesday = 16 etc

The list is longer but here is an example of the list that I have.

['Monday:21', 'Tuesday:6', 'Wednesday:8', 'Thursday:18', 'Friday:16', 'Saturday:4', 'Sunday:10', 'Monday:8']

Body:
Try this (explanation in code comments):

list = ['Monday:21', 'Tuesday:6', 'Wednesday:8', 'Thursday:18', 'Friday:16', 'Saturday:4', 'Sunday:10', 'Monday:8']
# create a dictionary variable
days_dict = {}
# for every entry in the list
for entry in list:
    # split entry by ":" and take the first part of the entry
    day = entry.split(":")[0]
    # split entry by ":" and take the second part of the entry and convert it to an integer
    count = int(entry.split(":")[1])
    print (day)
    print (count)
    # if the day key is in the dictionary add to its count else create the key
    if day in days_dict:
        days_dict[day] += count
    else:
        days_dict[day] = count

print (days_dict)
# print Monday's count
print ('Monday Count = ' + str(days_dict['Monday']))


问:
dompdf watermark, image, header and footer issues
i am using dompdf as a plugin in codeigniter. it generates the pdf perfectly. but some problem are eating up me for some days.

I want to put an image as header in every page of the generated pdf. i did it according to the tutorial given here.
but no progress. i tried for images of all types(jpg,png,gif) in the same folder wheresript for pdf resides. it did not work. then i tried for setting the path variable for image and css as shown at http://code.google.com/p/dompdf/wiki/Usage .but i could not get a good example or tutorial for that. if any body has ever used this please help me.

i also want to add watermark on every page. for that i am using

$pdf->page_text(110, $h - 240,  "TRIAL", Font_Metrics::get_font("verdana", "bold"),110, array(0.92, 0.92, 0.92), 0, -58);.

This works fine and generates watermark.but watermark comes over content.is there any thing to change the opacity of watermark. it is not changed by changing parameters in array.

3.at the end of every page ( except the last one) i want to put the text "continued..". for that i am using

```<code>$text = "Continued..";
  $width = Font_Metrics::get_text_width($text, $font, $size);
  $pdf->page_text($w - 16 - $width - 38, $y-15, $text, $font, $size, $color);
</code>```

it puts the text in every page(as it should). is there any way to put text in all pages except the last one?

how to set font which are not available in the lib file of dompdf?

答:
Make sure that DOMPDF_ENABLE_PHP is set to true in dompdf_config.inc.php ~line 173 in 0.6.2
Be aware that this is a potential security risk if there is any unfiltered content coming from an untrusted source to the pdf.

```<code>/**
 * Enable inline PHP
 *
 * If this setting is set to true then DOMPDF will automatically evaluate
 * inline PHP contained within <script type="text/php"> ... </script> tags.
 *
 * Enabling this for documents you do not trust (e.g. arbitrary remote html
 * pages) is a security risk.  Set this option to false if you wish to process
 * untrusted documents.
 *
 * @var bool
 */
define("DOMPDF_ENABLE_PHP", true);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
i am using dompdf as a plugin in codeigniter. it generates the pdf perfectly. but some problem are eating up me for some days.

I want to put an image as header in every page of the generated pdf. i did it according to the tutorial given here.
but no progress. i tried for images of all types(jpg,png,gif) in the same folder wheresript for pdf resides. it did not work. then i tried for setting the path variable for image and css as shown at http://code.google.com/p/dompdf/wiki/Usage .but i could not get a good example or tutorial for that. if any body has ever used this please help me.

i also want to add watermark on every page. for that i am using

$pdf->page_text(110, $h - 240,  "TRIAL", Font_Metrics::get_font("verdana", "bold"),110, array(0.92, 0.92, 0.92), 0, -58);.

This works fine and generates watermark.but watermark comes over content.is there any thing to change the opacity of watermark. it is not changed by changing parameters in array.

3.at the end of every page ( except the last one) i want to put the text "continued..". for that i am using

$text = "Continued..";
  $width = Font_Metrics::get_text_width($text, $font, $size);
  $pdf->page_text($w - 16 - $width - 38, $y-15, $text, $font, $size, $color);

it puts the text in every page(as it should). is there any way to put text in all pages except the last one?

how to set font which are not available in the lib file of dompdf?

Body:
Make sure that DOMPDF_ENABLE_PHP is set to true in dompdf_config.inc.php ~line 173 in 0.6.2
Be aware that this is a potential security risk if there is any unfiltered content coming from an untrusted source to the pdf.

/**
 * Enable inline PHP
 *
 * If this setting is set to true then DOMPDF will automatically evaluate
 * inline PHP contained within <script type="text/php"> ... </script> tags.
 *
 * Enabling this for documents you do not trust (e.g. arbitrary remote html
 * pages) is a security risk.  Set this option to false if you wish to process
 * untrusted documents.
 *
 * @var bool
 */
define("DOMPDF_ENABLE_PHP", true);


问:
Firebase Firestore returning no data from collection
I want get all docs from a collection but on my code nothing is returned like I can see on the log printing the snapshot returned. I can use Storage on my application to store documents, and I can write on Firestore documents too, so the Firebase is correct configured, but it's not reading the docs.

```<code>getUsers() {
  firebase
    .firestore()
    .collection("users")
    .get()
    .then(function(querySnapshot) {
      console.log(querySnapshot);
      querySnapshot.forEach(function(doc) {
        console.log(doc.id, " => ", doc.data());
      });
    });
}
</code>```

答:
This is working as expected.  The query you're performing is only going to get documents immediately in the users collection.  However, the screenshot her shows that there are not actually any documents in that collection.  The document IDs you see in that collection are in italics, which means there is no document there, HOWEVER, there is at least one subcollection ("data") under that document.

Firestore queries are shallow, meaning that they only consider documents immediately within the collection you're trying to query.  Documents in subcollections are not considered.  Missing doucuments that have nested subcollections are also not considered (since they are not actually documents).

If you want to be able to query documents in a collection, you must actually write a document there.  Documents in subcollections do force a parent document to exist.

Body:
I want get all docs from a collection but on my code nothing is returned like I can see on the log printing the snapshot returned. I can use Storage on my application to store documents, and I can write on Firestore documents too, so the Firebase is correct configured, but it's not reading the docs.

getUsers() {
  firebase
    .firestore()
    .collection("users")
    .get()
    .then(function(querySnapshot) {
      console.log(querySnapshot);
      querySnapshot.forEach(function(doc) {
        console.log(doc.id, " => ", doc.data());
      });
    });
}


问:
Vue: Data is not changing with Vuex getter?
I have a modal component that I was triggered when different components mutate the triggerModalState field.  I have a getter in my Vuex store called getFulfillmentModalState.  The modal is driven off of the local data field called dialog, which I have set to be the value of the getter this.$store.getters.getFulfillmentModalState.  I am checking the value of this.$store.getters.getFulfillmentModalState, and it is true after I trigger the modal, but the dialog data is still false.  What am I doing wrong here?

<template>

        <v-row justify="center">
            <v-dialog v-model="dialog" persistent max-width="290">
                <v-card>
                    <v-card-actions>
                        <v-spacer></v-spacer>
                        <v-btn color="rgba(53, 87, 151, 0.85)" text @click="changeModalState(true)">Cancel</v-btn>
                        <v-btn color="rgba(53, 87, 151, 0.85)" text @click="changeModalState(false)">Continue</v-btn>
                    </v-card-actions>
                </v-card>
            </v-dialog>
        </v-row>

</template>

```

答:
dialog isn't reactive in this case because it's declared in data(). Move dialog to computed to make it reactive:

//...
export default {
  data() {
    return {
      //dialog: /*..*/   // move to computed
    }
  },
  computed: {
    dialog() {
      return this.$store.getters.getFulfillmentModalState
    }
  }
}
```

demo

Body:
dialog isn't reactive in this case because it's declared in data(). Move dialog to computed to make it reactive:

//...
export default {
  data() {
    return {
      //dialog: /*..*/   // move to computed
    }
  },
  computed: {
    dialog() {
      return this.$store.getters.getFulfillmentModalState
    }
  }
}

demo


问:
Is it possible to make scalatest to discover within package object?
I have several test facets sharing multiple test classes, so I aggregate them into a trait to be mixin into package objects, expecting that those test classes will be discovered under the package:

(In trait)

```<code>trait AbstractPackageTests {

  val name: String

  class Suite1 extends FunSpec {

    describe(name) {

      it("test 1") {}

      it("test 2") {}
    }
  }

  class Suite2 extends FunSpec {
    describe(name) {

      it("test 3") {}

      it("test 4") {}
    }
  }
}
</code>```

(In package 1)

```<code>package com.spike.scalatest_spike

package object facet1 extends FunSpec with AbstractPackageTests {
  override val name: String = "facet 1"

  class Suite3 extends FunSpec {
    describe(name) {

      it("test 5") {}

    }
  }
}

</code>```

(In package 2)

```<code>package com.spike.scalatest_spike

package object facet2 extends AbstractPackageTests {
  override val name: String = "facet 2"
}
</code>```

Unfortunately it appears that none of these classes (Suite1, Suite2, Sutie3) can be discovered when I invoke scalatest to run all the test under com.spike.scalatest_spike, the classes seems to be ignored in class discovery.

What changes should I make on my project or/and scalatest sourcecode to make it working?

答:
If you're using SBT to invoke the testing then ensure sources are in src/test/scala or src/test/java as documented: https://www.scala-sbt.org/1.x/docs/Testing.html

If you're using a jar with the java or scala commands, it's possible your test classes are missing from the jar. The former method may be easier since it doesn't require a jar to have all your test classes.

Body:
I have several test facets sharing multiple test classes, so I aggregate them into a trait to be mixin into package objects, expecting that those test classes will be discovered under the package:

(In trait)

trait AbstractPackageTests {

  val name: String

  class Suite1 extends FunSpec {

    describe(name) {

      it("test 1") {}

      it("test 2") {}
    }
  }

  class Suite2 extends FunSpec {
    describe(name) {

      it("test 3") {}

      it("test 4") {}
    }
  }
}

(In package 1)

package com.spike.scalatest_spike

package object facet1 extends FunSpec with AbstractPackageTests {
  override val name: String = "facet 1"

  class Suite3 extends FunSpec {
    describe(name) {

      it("test 5") {}

    }
  }
}

(In package 2)

package com.spike.scalatest_spike

package object facet2 extends AbstractPackageTests {
  override val name: String = "facet 2"
}

Unfortunately it appears that none of these classes (Suite1, Suite2, Sutie3) can be discovered when I invoke scalatest to run all the test under com.spike.scalatest_spike, the classes seems to be ignored in class discovery.

What changes should I make on my project or/and scalatest sourcecode to make it working?


问:
I need to download the file to the local sandbox, but the download link is a blob link, how can I download it in iOS
When I click the button I will get a download url is "blob: http://v9.api.vip.groupnp.cn/html-docx/9d9685bc-6e8c-4a88-99f5-d9fc3edd384d". This should be able to download a word File, but I tried to use AFNetworking to download, but it failed, so how should I use object-c to download such a linked file in the iOS environment？

this is the downloadurl：  blob:http://v9.api.vip.groupnp.cn/html-docx/9d9685bc-6e8c-4a88-99f5-d9fc3edd384d

答: We found a relevant solution. Our Html5 developers transcoded this blob-containing URL using the js method to base64, so that the iOS side can process the transcoded string and finally write it locally Docx documentation</p>


问:
create a binding from a DataListView to a list consisting of a list
I want to create a two way binding from a DataListView to a list consisting of a list. How do I do that?

Based on the code below, I create a list like this:

```<code>   probe1 probe2 probe3 probe4 ...
1  12.3   4.2    6.3    12.5
2  65.2   2.5    12.4   54.6
3  54.2   64.3   21.5   22.2
. . .
</code>```

Row header is the row in Values. <372 values

Column header is row in Probes. <120 probes

Totalt max 44640 values but usually a few thousand values

And the code

```<code>public IList<Probe> Probes{get;private set;}

public class Probe
{
   public Probe(int maxValues)
   {
      Values = new double[maxValues];
   }
   public IList<double> Values{get;private set}
}
</code>```

答:
You have to flatten the list first. Create a new type like ProbeValue containing both the property Value:double and Probe:Probe. Then create a new CollectionView from the flattened result and apply a GroupDescription on the Probe property. Bind your listview against that

http://msdn.microsoft.com/en-us/library/system.windows.data.collectionview.aspx

Body:
I want to create a two way binding from a DataListView to a list consisting of a list. How do I do that?

Based on the code below, I create a list like this:

   probe1 probe2 probe3 probe4 ...
1  12.3   4.2    6.3    12.5
2  65.2   2.5    12.4   54.6
3  54.2   64.3   21.5   22.2
. . .

Row header is the row in Values. <372 values

Column header is row in Probes. <120 probes

Totalt max 44640 values but usually a few thousand values

And the code

public IList<Probe> Probes{get;private set;}

public class Probe
{
   public Probe(int maxValues)
   {
      Values = new double[maxValues];
   }
   public IList<double> Values{get;private set}
}