问:
Perl Tk: help me fix highlighting in my text editor
So i'm writing a text editor in Perl Tk and I have a subroutine for highlighting, it inserts two highlighted spaces for you to type in.

I'm having 3 problems.

I want the cursor to move to the left 1 space when the highlight subroutine is triggered. So that when one inserts a highlighting or underline style the cursor is automatically in between the two spaces and the user can type in that style instantly rather than having to use the left arrowkey. I guess my question is how do I insert a style at the cursor instead of the end of the file.

The subroutine's formatting of the text isn't saving properly to the filetype. I'm using .rtf currently.

I want to implement a drop down font selection menu that draws from a system font list but i'm unsure how.

```<code>#!/usr/local/bin/perl
#!/C:/Perl/site/lib
use Tk;
use utf8;
use vars qw/$TOP/;

# Main Window
my $mw = new MainWindow;

#Making a text area
my $txt = $mw -> Scrolled('Text', -width => 50,-scrollbars=>'e') -> pack (), -setgrid => true;

#Declare that there is a menu
my $mbar = $mw -> Menu();
$mw -> configure(-menu => $mbar);

#The Main Buttons
my $file = $mbar -> cascade(-label=>"File", -underline=>0, -tearoff => 0);
my $others = $mbar -> cascade(-label =>"Others", -underline=>0, -tearoff => 0);
my $help = $mbar -> cascade(-label =>"Help", -underline=>0, -tearoff => 0);

## File Menu ##
$file -> command(-label => "New", -underline=>0,
        -command=>sub { $txt -> delete('1.0','end');} );
$file -> checkbutton(-label =>"Open", -underline => 0,
        -command => [\&openfunction, "Open"]);
$file -> command(-label =>"Save", -underline => 0,
        -command => [\&savefunction, "Save"]);
$file -> separator();
$file -> command(-label =>"Exit", -underline => 1,
        -command => sub { exit } );

## Others Menu ##
my $insert = $others -> cascade(-label =>"Insert", -underline => 0, -tearoff => 0);

        $insert -> command(-label =>"Highlight",
    -command => [\&highlight, "Highlight"]);
    $insert -> command(-label =>"Underline",
    -command => [\&underline, "Underline"]);
        $insert -> command(-label =>"Title",
    -command => [\&bold, "Title"]);
    $insert -> command(-label =>"Stippling",
    -command => [\&stippling, "Stippling"]);

    $insert -> command(-label =>"Find & Replace",
    -command => [\&find_replace, "Find & Replace"]);
$insert -> command(-label =>"Name",
    -command => sub { $txt->insert('end',"Name : Thaddeus Roebuck Badgercock\n");});
$insert -> command(-label =>"Bullet Point", -command=>sub {
    $txt->insert('end',"⚫\t");});
$insert -> command(-label =>"Email",
    -command=> sub {$txt->insert('end',"E-Mail :\n");});
$others -> command(-label =>"Insert All", -underline => 7,
    -command => sub { $txt->insert('end',"Name : Thaddeus Roebuck Badgercock
Website :
E-Mail :");
    });

## Help ##
$help -> command(-label =>"About", -command => sub {
    $txt->delete('1.0','end');
    $txt->insert('end',
    "About
----------
This is a simple text editor written in Perl Tk. This program is licensed under the GNU Public License and is Free Software.
"); });

## Tags ##
$txt->tag(qw/configure bgstipple  -background black -borderwidth 0
        -bgstipple gray12/);
$txt->tag(qw/configure bold    -font C_bold/);
$txt->tag(qw/configure color1 -background/ => '#a0b7ce');
$txt->tag(qw/configure raised -background white -relief raised/);
$txt->tag(qw/configure sunken -background white -relief sunken/);
$txt->tag(qw/configure underline  -underline on/);

MainLoop;
sub find_replace {
    $txt->FindAndReplacePopUp;
}

sub stippling {
   $txt->insert('end', '  ', 'bgstipple');
} # end style

sub bold {
    $txt->insert('end', '  ', 'bold');
}

sub highlight {
     $txt->insert('end', '  ', 'color1');
 }

 sub raised {
     $txt->insert('end', '  ', 'raised');
 }

  sub underline {
     $txt->insert('end', '  ', 'underline'); #how do
 }

sub savefunction {
     my $fileDataToSave=$txt->get("1.0","end");
    # Trigger dialog
    $filename = $mw->getSaveFile( -title =>  "Selecting file to Save",
             -defaultextension => '.rtf', -initialdir => '.' );
    # save the file
    open(my $fh, '>', $filename) or die $!;
   print $fh $fileDataToSave;
   close $fh;
}

sub openfunction {
      # function to get file dialog box
     $filename = $mw->getOpenFile( -title => "Selecting file to Load",
     -defaultextension => '.txt', -initialdir => '.' );
     # function to load file into string e.g. if you have use File::Slurp
     open($fh, '<', $filename) or die $!;
     my $file_content = do { local $/; <$fh> };
     close $fh;
    $txt->Contents($file_content)
}

sub menuClicked {
    my ($opt) = @_;
    $mw->messageBox(-message=>"You have clicked $opt.
This function is not implemented yet.");
}

#todo:
#figure out how to package as monolithic executables for various platforms
</code>```

答:
You can insert the highlight formatting at the current cursor position using:</p>

```<code>sub highlight {
    $txt->insert('insert', '  ', 'color1');
    $txt->SetCursor( 'insert - 1 chars' ); # <-- moves the cursor back into the
                                           #     hightlight region
}
</code>```

Body:
So i'm writing a text editor in Perl Tk and I have a subroutine for highlighting, it inserts two highlighted spaces for you to type in.

I'm having 3 problems.

I want the cursor to move to the left 1 space when the highlight subroutine is triggered. So that when one inserts a highlighting or underline style the cursor is automatically in between the two spaces and the user can type in that style instantly rather than having to use the left arrowkey. I guess my question is how do I insert a style at the cursor instead of the end of the file.

The subroutine's formatting of the text isn't saving properly to the filetype. I'm using .rtf currently.

I want to implement a drop down font selection menu that draws from a system font list but i'm unsure how.

#!/usr/local/bin/perl
#!/C:/Perl/site/lib
use Tk;
use utf8;
use vars qw/$TOP/;

# Main Window
my $mw = new MainWindow;

#Making a text area
my $txt = $mw -> Scrolled('Text', -width => 50,-scrollbars=>'e') -> pack (), -setgrid => true;

#Declare that there is a menu
my $mbar = $mw -> Menu();
$mw -> configure(-menu => $mbar);

#The Main Buttons
my $file = $mbar -> cascade(-label=>"File", -underline=>0, -tearoff => 0);
my $others = $mbar -> cascade(-label =>"Others", -underline=>0, -tearoff => 0);
my $help = $mbar -> cascade(-label =>"Help", -underline=>0, -tearoff => 0);

## File Menu ##
$file -> command(-label => "New", -underline=>0,
        -command=>sub { $txt -> delete('1.0','end');} );
$file -> checkbutton(-label =>"Open", -underline => 0,
        -command => [\&openfunction, "Open"]);
$file -> command(-label =>"Save", -underline => 0,
        -command => [\&savefunction, "Save"]);
$file -> separator();
$file -> command(-label =>"Exit", -underline => 1,
        -command => sub { exit } );

## Others Menu ##
my $insert = $others -> cascade(-label =>"Insert", -underline => 0, -tearoff => 0);

        $insert -> command(-label =>"Highlight",
    -command => [\&highlight, "Highlight"]);
    $insert -> command(-label =>"Underline",
    -command => [\&underline, "Underline"]);
        $insert -> command(-label =>"Title",
    -command => [\&bold, "Title"]);
    $insert -> command(-label =>"Stippling",
    -command => [\&stippling, "Stippling"]);

    $insert -> command(-label =>"Find & Replace",
    -command => [\&find_replace, "Find & Replace"]);
$insert -> command(-label =>"Name",
    -command => sub { $txt->insert('end',"Name : Thaddeus Roebuck Badgercock\n");});
$insert -> command(-label =>"Bullet Point", -command=>sub {
    $txt->insert('end',"⚫\t");});
$insert -> command(-label =>"Email",
    -command=> sub {$txt->insert('end',"E-Mail :\n");});
$others -> command(-label =>"Insert All", -underline => 7,
    -command => sub { $txt->insert('end',"Name : Thaddeus Roebuck Badgercock
Website :
E-Mail :");
    });

## Help ##
$help -> command(-label =>"About", -command => sub {
    $txt->delete('1.0','end');
    $txt->insert('end',
    "About
----------
This is a simple text editor written in Perl Tk. This program is licensed under the GNU Public License and is Free Software.
"); });

## Tags ##
$txt->tag(qw/configure bgstipple  -background black -borderwidth 0
        -bgstipple gray12/);
$txt->tag(qw/configure bold    -font C_bold/);
$txt->tag(qw/configure color1 -background/ => '#a0b7ce');
$txt->tag(qw/configure raised -background white -relief raised/);
$txt->tag(qw/configure sunken -background white -relief sunken/);
$txt->tag(qw/configure underline  -underline on/);

MainLoop;
sub find_replace {
    $txt->FindAndReplacePopUp;
}

sub stippling {
   $txt->insert('end', '  ', 'bgstipple');
} # end style

sub bold {
    $txt->insert('end', '  ', 'bold');
}

sub highlight {
     $txt->insert('end', '  ', 'color1');
 }

 sub raised {
     $txt->insert('end', '  ', 'raised');
 }

  sub underline {
     $txt->insert('end', '  ', 'underline'); #how do
 }

sub savefunction {
     my $fileDataToSave=$txt->get("1.0","end");
    # Trigger dialog
    $filename = $mw->getSaveFile( -title =>  "Selecting file to Save",
             -defaultextension => '.rtf', -initialdir => '.' );
    # save the file
    open(my $fh, '>', $filename) or die $!;
   print $fh $fileDataToSave;
   close $fh;
}

sub openfunction {
      # function to get file dialog box
     $filename = $mw->getOpenFile( -title => "Selecting file to Load",
     -defaultextension => '.txt', -initialdir => '.' );
     # function to load file into string e.g. if you have use File::Slurp
     open($fh, '<', $filename) or die $!;
     my $file_content = do { local $/; <$fh> };
     close $fh;
    $txt->Contents($file_content)
}

sub menuClicked {
    my ($opt) = @_;
    $mw->messageBox(-message=>"You have clicked $opt.
This function is not implemented yet.");
}

#todo:
#figure out how to package as monolithic executables for various platforms

Body:
You can insert the highlight formatting at the current cursor position using:

sub highlight {
    $txt->insert('insert', '  ', 'color1');
    $txt->SetCursor( 'insert - 1 chars' ); # <-- moves the cursor back into the
                                           #     hightlight region
}


来源: stackexchange

问:
JS code executes on computer but not on mobile
I have a basic js block that works on desktop/laptop but not on tablet or phone. The code simply populates a select box based on what a user enters in a text box.  I have tested this in chrome and adblock browsers on mobile, both have js enabled and are up to date. What do I need to do to make this work on the mobile devices?  The phpPro is a js recordset populated when the page loads based on a page criteria.</p>

```<code>//PHP
$pro=$conn->query("Select idpro, producer, name, vintage, barcodecase, barcodebottle From products Where active='Y' And idclient=" . $client . " Order By producer, name, vintage")->fetchAll();
$jpro=json_encode($pro);
//End PHP

const phpPro=<?php echo $jpro; ?>;

function getpro() {
    var select = document.getElementById("spro");
    var length = select.options.length;
   for (var i = 0; i < length; i++) {select.remove(0);}

   var option = document.createElement('option');
   option.text = 'Please Select';
   option.value = '';
   select.add(option);

   var cnt=1;
   for (i=0; i<phpPro.length; i++) {
    var x = phpPro[i][1] + phpPro[i][2] + phpPro[i][3] + phpPro[i][4] + phpPro[i][5];
    x = x.toUpperCase();
    z = document.getElementById('isrch').value;
    z = z.toUpperCase();

    if (x.includes(z)===true) {
        var option = document.createElement('option');

        option.text = cnt + ". " + phpPro[i][1] + ": " + phpPro[i][2]  + " - " + phpPro[i][3];
        option.value = phpPro[i][0];
        select.add(option);
        cnt++;
      }
   }
}
</code>```

答: I changed the calling event from onkeypress to onkeydown and the problem was resolved.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a basic js block that works on desktop/laptop but not on tablet or phone. The code simply populates a select box based on what a user enters in a text box.  I have tested this in chrome and adblock browsers on mobile, both have js enabled and are up to date. What do I need to do to make this work on the mobile devices?  The phpPro is a js recordset populated when the page loads based on a page criteria.

//PHP
$pro=$conn->query("Select idpro, producer, name, vintage, barcodecase, barcodebottle From products Where active='Y' And idclient=" . $client . " Order By producer, name, vintage")->fetchAll();
$jpro=json_encode($pro);
//End PHP

const phpPro=<?php echo $jpro; ?>;

function getpro() {
    var select = document.getElementById("spro");
    var length = select.options.length;
   for (var i = 0; i < length; i++) {select.remove(0);}

   var option = document.createElement('option');
   option.text = 'Please Select';
   option.value = '';
   select.add(option);

   var cnt=1;
   for (i=0; i<phpPro.length; i++) {
    var x = phpPro[i][1] + phpPro[i][2] + phpPro[i][3] + phpPro[i][4] + phpPro[i][5];
    x = x.toUpperCase();
    z = document.getElementById('isrch').value;
    z = z.toUpperCase();

    if (x.includes(z)===true) {
        var option = document.createElement('option');

        option.text = cnt + ". " + phpPro[i][1] + ": " + phpPro[i][2]  + " - " + phpPro[i][3];
        option.value = phpPro[i][0];
        select.add(option);
        cnt++;
      }
   }
}


问:
WCF - Inspect the messages being sent/received?
I have 2 solutions:
 - Server Solution
 - Client Solution

The server registers itself to my localhost IIS: http://localhost/MyApp/

The client adds WCF Services (Service References) from the localhost application: http://localhost/MyApp/MyService.svc

When I'm running the client I want to be able to see the messages being passed back and forth. I downloaded Fiddler, but it doesn't seem to want to show me any traffic being sent unless I actually use a web browser. Am I using Fiddler wrong or is there another tool I should be using for this?

To clarify, what I'm looking to do is to see the actual messages being passed in. I don't want to do anything with them except see them visually with my own eyes.

I like the WCF Service Log Utility, but I don't think I have the correct setting on there. I can't see the actual soap message, just that a message was received.

And also to clarify further, I don't care what tool I use as long as I can easily see the messages themselves.

答:
Maybe I'm missing something, but...
Why don't you use the WCF tracing features? It's a fantastic troubleshooting tool. I've used it for services hosted in IIS/WAS also.

Enabling WCF Tracing

BTW, some people don't know it, but you can open traces from server side and client side at the same time, and the Viewer will show you the correlation between the server and client actions in a nice graph.

EDIT: whenever I had to capture TCP/IP traffic, I use WireShark. If you need to do it programatically you can use SharpPCAP, so I can take actions upon what I capture from the network. But for troubleshooting, much much better to rely on WCF Tracing.

ContentLicense: CC BY-SA 3.0


问:
UseState to update multiple properties in object array
Using destructuring, I can update multiple object properties with one function:

```<code>const [serverRequest, setServerRequest] = useState({ ID: "", RAM: "", CPU: "", appInstaller: [{}] });

return (
  <div className="App">
    <label className="label">ID</label>
    <input
      className="input"
      type="text"
      name="ID"
      value={serverRequest?.ID}
      onChange={e =>
        setServerRequest({
          ...serverRequest,
          ID: e.target.value
        })
      }
    />
    <input
      className="input"
      type="text"
      name="RAM"
      value={serverRequest?.RAM}
      onChange={e =>
        setServerRequest({
          ...serverRequest,
          RAM: e.target.value
        })
      }
    />
  </div>
);
</code>```

However, I'd like to do this on a object array. How can I do this?

Using

```<code>const [serverRequests, setServerRequests] = useState([{ ID: "", RAM: "", CPU: "", appInstaller: [{}] }]);
const [selectedServer, setSelectedServer] = useState(0);

onChange={e =>
  setServerRequests({
    ...serverRequests[selectedServer],
    ID: e.target.value
  })
}
</code>```

Will convert the array into a single object on the first change, and then remove all other properties on the second change.

答:
```<code>onChange={e =>
  setServerRequests({
    ...serverRequests[selectedServer],
    ID: e.target.value
  })
}
</code>```

This means "set serverRequests with this ID, and spread serverRequests[selectedServer] inside". So yes, it becomes one single object. to avoidthat, you need to spread your previous state before:

setServerRequests({...serverRequests, otherChange: otherValue}).

Now if you need to change jsut one object from serverRequests, you need to create a copy of it, edit the object you want to change and then spread it inside your setServerRequests. Something like :

```<code>onchange = () => {
 const state = Object.assign({}, serverRequests); // or lodash clonedeep
 const objIndexToEdit = // get index of the item you want to changes
 state[objIndexToEdit] = // your changed obj (do it as you wish, just giving an example)
 setServerRequests({...state});
}
</code>```

Body:
Using destructuring, I can update multiple object properties with one function:

const [serverRequest, setServerRequest] = useState({ ID: "", RAM: "", CPU: "", appInstaller: [{}] });

return (

    ID
    <input
      className="input"
      type="text"
      name="ID"
      value={serverRequest?.ID}
      onChange={e =>
        setServerRequest({
          ...serverRequest,
          ID: e.target.value
        })
      }
    />
    <input
      className="input"
      type="text"
      name="RAM"
      value={serverRequest?.RAM}
      onChange={e =>
        setServerRequest({
          ...serverRequest,
          RAM: e.target.value
        })
      }
    />

);

However, I'd like to do this on a object array. How can I do this?

Using

const [serverRequests, setServerRequests] = useState([{ ID: "", RAM: "", CPU: "", appInstaller: [{}] }]);
const [selectedServer, setSelectedServer] = useState(0);

onChange={e =>
  setServerRequests({
    ...serverRequests[selectedServer],
    ID: e.target.value
  })
}

Will convert the array into a single object on the first change, and then remove all other properties on the second change.

Body:
onChange={e =>
  setServerRequests({
    ...serverRequests[selectedServer],
    ID: e.target.value
  })
}

This means "set serverRequests with this ID, and spread serverRequests[selectedServer] inside". So yes, it becomes one single object. to avoidthat, you need to spread your previous state before:

setServerRequests({...serverRequests, otherChange: otherValue}).

Now if you need to change jsut one object from serverRequests, you need to create a copy of it, edit the object you want to change and then spread it inside your setServerRequests. Something like :

onchange = () => {
 const state = Object.assign({}, serverRequests); // or lodash clonedeep
 const objIndexToEdit = // get index of the item you want to changes
 state[objIndexToEdit] = // your changed obj (do it as you wish, just giving an example)
 setServerRequests({...state});
}


问:
How to auto fill address using Google autocomplete and Vue js?
I'm new to Vue js and I'm trying to use the autocomplete API to auto fill the address fields in my form, after a User starts typing and selects an address from the dropdown menu. The code from the docs uses Vanilla javascript and I want to convert this into Vue js and integrate it into my existing form.

Inside my data, I have an object called employerProfileData and I use this on my form inputs using v-model.

```<code>data() {
            return {

                employerProfileData: {
                    company_name: '',
                    phone: '',
                    number_of_employees: '1-25',
                    options: [
                        { value: '1-25', text: '1-25' },
                        { value: '25-50', text: '25-50' },
                        { value: '50-100', text: '50-100' },
                        { value: '100-250', text: '100-250' },
                        { value: '250-500', text: '250-500'},
                        { value: '500-1000', text: '500-1000'}
                    ],
                    street: '',
                    city: '',
                    country: 'Canada',
                    optionsTwo: [
                        { value: 'Canada', text: 'Canada' },
                        { value: 'United States', text: 'United States' }
                    ],
                    province_state: '',
                    zip_postal: '',
                },

                errors: {},

            };
</code>```

Right now, I'm getting the place details from the autocomplete object like this const place = autocomplete.getPlace();. Now, I can access the address_component like this place.address_components to get the values that I want to assign to my input fields, something like this.

```<code>mounted() {

            const autocomplete = new google.maps.places.Autocomplete(
                document.getElementById("autocomplete"),
                {
                    bounds: new google.maps.LatLngBounds(
                        new google.maps.LatLng(43.651070, -79.347015)
                    )
                });

            function fillInAddress() {

                // Get the place details from the autocomplete object.
                const place = autocomplete.getPlace();

                this.employerProfileData.street = place.address_components[0].short_name + place.address_components[1].long_name;
                this.employerProfileData.city = place.address_components[2].long_name;
                this.employerProfileData.country = place.address_components[5].long_name;
                this.employerProfileData.province_state = place.address_components[4].short_name;
                this.employerProfileData.zip_postal = place.address_components[6].short_name;

            }

            autocomplete.addListener("place_changed", fillInAddress);

        }
</code>```

But it seems I can't do this in the fillInAddress() function and I get this error:

```<code>TypeError: Cannot set property 'street' of undefined
</code>```

------------ UPDATED THIS WORKS: ------------

I needed to bind.(this) on fillInAddress function.
mounted() {

```<code>            const autocomplete = new google.maps.places.Autocomplete(
                document.getElementById("autocomplete"),
                {
                    bounds: new google.maps.LatLngBounds(
                        new google.maps.LatLng(43.651070, -79.347015)
                    )
                });

            function fillInAddress() {

                // Get the place details from the autocomplete object.
                const place = autocomplete.getPlace();

                this.employerProfileData.street = place.address_components[0].short_name + place.address_components[1].long_name;
                this.employerProfileData.city = place.address_components[2].long_name;
                this.employerProfileData.country = place.address_components[5].long_name;
                this.employerProfileData.province_state = place.address_components[4].short_name;
                this.employerProfileData.zip_postal = place.address_components[6].short_name;

            }

            autocomplete.addListener("place_changed", fillInAddress.bind(this));

        },
</code>```

答:
You will be probably interested in vue-google-autocomplete package.

Example usage:

<vue-google-autocomplete
  id="map"
  classname="form-control"
  placeholder="Start typing"
  v-on:placechanged="getAddressData"
/>
```

<p>It's demo is not working today due to exceeding the limit of free requests per day, but it seems legitimate.</p>

<p>If you want to do it on your own anyway, i suggest to check what <code>this</code> points to inside <code>fillInAddress</code> using the debugger. Perhaps binding context would help.</p>

<pre class="lang-js prettyprint-override"><code>autocomplete.addListener("place_changed", fillInAddress.bind(this))
</code>```

Body:
I'm new to Vue js and I'm trying to use the autocomplete API to auto fill the address fields in my form, after a User starts typing and selects an address from the dropdown menu. The code from the docs uses Vanilla javascript and I want to convert this into Vue js and integrate it into my existing form.

Inside my data, I have an object called employerProfileData and I use this on my form inputs using v-model.

data() {
            return {

                employerProfileData: {
                    company_name: '',
                    phone: '',
                    number_of_employees: '1-25',
                    options: [
                        { value: '1-25', text: '1-25' },
                        { value: '25-50', text: '25-50' },
                        { value: '50-100', text: '50-100' },
                        { value: '100-250', text: '100-250' },
                        { value: '250-500', text: '250-500'},
                        { value: '500-1000', text: '500-1000'}
                    ],
                    street: '',
                    city: '',
                    country: 'Canada',
                    optionsTwo: [
                        { value: 'Canada', text: 'Canada' },
                        { value: 'United States', text: 'United States' }
                    ],
                    province_state: '',
                    zip_postal: '',
                },

                errors: {},

            };

Right now, I'm getting the place details from the autocomplete object like this const place = autocomplete.getPlace();. Now, I can access the address_component like this place.address_components to get the values that I want to assign to my input fields, something like this.

mounted() {

            const autocomplete = new google.maps.places.Autocomplete(
                document.getElementById("autocomplete"),
                {
                    bounds: new google.maps.LatLngBounds(
                        new google.maps.LatLng(43.651070, -79.347015)
                    )
                });

            function fillInAddress() {

                // Get the place details from the autocomplete object.
                const place = autocomplete.getPlace();

                this.employerProfileData.street = place.address_components[0].short_name + place.address_components[1].long_name;
                this.employerProfileData.city = place.address_components[2].long_name;
                this.employerProfileData.country = place.address_components[5].long_name;
                this.employerProfileData.province_state = place.address_components[4].short_name;
                this.employerProfileData.zip_postal = place.address_components[6].short_name;

            }

            autocomplete.addListener("place_changed", fillInAddress);

        }

But it seems I can't do this in the fillInAddress() function and I get this error:

TypeError: Cannot set property 'street' of undefined

------------ UPDATED THIS WORKS: ------------

I needed to bind.(this) on fillInAddress function.
mounted() {

            const autocomplete = new google.maps.places.Autocomplete(
                document.getElementById("autocomplete"),
                {
                    bounds: new google.maps.LatLngBounds(
                        new google.maps.LatLng(43.651070, -79.347015)
                    )
                });

            function fillInAddress() {

                // Get the place details from the autocomplete object.
                const place = autocomplete.getPlace();

                this.employerProfileData.street = place.address_components[0].short_name + place.address_components[1].long_name;
                this.employerProfileData.city = place.address_components[2].long_name;
                this.employerProfileData.country = place.address_components[5].long_name;
                this.employerProfileData.province_state = place.address_components[4].short_name;
                this.employerProfileData.zip_postal = place.address_components[6].short_name;

            }

            autocomplete.addListener("place_changed", fillInAddress.bind(this));

        },

Body:
You will be probably interested in vue-google-autocomplete package.

Example usage:

<vue-google-autocomplete
  id="map"
  classname="form-control"
  placeholder="Start typing"
  v-on:placechanged="getAddressData"
/>

It's demo is not working today due to exceeding the limit of free requests per day, but it seems legitimate.

If you want to do it on your own anyway, i suggest to check what this points to inside fillInAddress using the debugger. Perhaps binding context would help.

autocomplete.addListener("place_changed", fillInAddress.bind(this))


问:
Dynamically Change the Key Value based on Delimiter in Perl
I'm reading from a CSV file and populating a Hash based on Key-Value Pairs.
The First Column of the record is the key, and the rest of the record is the value. However, for some file I need to make first 2 columns as Key and the rest of the record is value. I have written it as below  based on if loop by checking the number of Key Columns, but I wanted to know if there is any better way to do this?

```<code>use strict;
use warnings;

open my $fh, '<:encoding(utf8)', 'Sample.csv'
      or die "Couldn't open Sample.csv";
my %hash;
my $KeyCols=2;
    while (<$fh>) {
        chomp;
        if ($KeyCols==1) {
        next unless /^(.*?),(.*)$/;
        $hash{$1} = $2;
        }
        elsif ($KeyCols==2) {
        next unless /^(.*?),(.*?),(.*)$/;
        $hash{$1.$2} = $3;
        }
    }
</code>```

答:
Perhaps it is better to define variables at first lines of the code -- otherwise you have to jump all over the code.

You can define regex based on your $KeyCols and processing code will be same as before.

```<code>use strict;
use warnings;
use feature 'say';

my $KeyCols = 2;
my $fname   = 'Sample.csv';

my %hash;
my $re;

if( $KeyCols == 2 ) {
    $re = qr/^(.*?,.*?),(.*)$/
} else {
    $re = qr/^(.*?),(.*)$/;
}

open my $fh, '<:encoding(utf8)', $fname
      or die "Couldn't open $fname";

while (<$fh>) {
    chomp;
    next unless /$re/;
    $hash{$1} = $2;
}

close $fh;
</code>```

Body:
I'm reading from a CSV file and populating a Hash based on Key-Value Pairs.
The First Column of the record is the key, and the rest of the record is the value. However, for some file I need to make first 2 columns as Key and the rest of the record is value. I have written it as below  based on if loop by checking the number of Key Columns, but I wanted to know if there is any better way to do this?

use strict;
use warnings;

open my $fh, '<:encoding(utf8)', 'Sample.csv'
      or die "Couldn't open Sample.csv";
my %hash;
my $KeyCols=2;
    while (<$fh>) {
        chomp;
        if ($KeyCols==1) {
        next unless /^(.*?),(.*)$/;
        $hash{$1} = $2;
        }
        elsif ($KeyCols==2) {
        next unless /^(.*?),(.*?),(.*)$/;
        $hash{$1.$2} = $3;
        }
    }

Body:
Perhaps it is better to define variables at first lines of the code -- otherwise you have to jump all over the code.

You can define regex based on your $KeyCols and processing code will be same as before.

use strict;
use warnings;
use feature 'say';

my $KeyCols = 2;
my $fname   = 'Sample.csv';

my %hash;
my $re;

if( $KeyCols == 2 ) {
    $re = qr/^(.*?,.*?),(.*)$/
} else {
    $re = qr/^(.*?),(.*)$/;
}

open my $fh, '<:encoding(utf8)', $fname
      or die "Couldn't open $fname";

while (<$fh>) {
    chomp;
    next unless /$re/;
    $hash{$1} = $2;
}

close $fh;


问:
Multiline text area in angular material 2
How do I wrap text and have support for multiple line, using angular material 2 and angular.

```<code><md-input-container fxFlex="18" fxFlexOffset="1">
      <textarea [(ngModel)]="Comments" name="Comments" mdInput placeholder="Comments" ></textarea>
        <md-error>This field is required</md-error>
    </md-input-container>
</code>```

Wrapping text mean, text should be appear multi line if content is longer than width.

答:
Not the exact answer for the question but since this is the best match in google search,
to set rows for a textarea in angular apperantly we need to usecdkTextareaAutosize, cdkAutosizeMinRowsattributes .

    <mat-form-field>
      <textarea matInput placeholder="Your Message" formControlName="message" cdkTextareaAutosize
        cdkAutosizeMinRows="6"></textarea>
    </mat-form-field>

```

Body:
How do I wrap text and have support for multiple line, using angular material 2 and angular.

<md-input-container fxFlex="18" fxFlexOffset="1">
      <textarea [(ngModel)]="Comments" name="Comments" mdInput placeholder="Comments" ></textarea>
        <md-error>This field is required</md-error>
    </md-input-container>

Wrapping text mean, text should be appear multi line if content is longer than width.


问:
Using dplyr mutate function to create new variable conditionally based on current row
I am working on creating conditional averages for a large data set that involves # of flu cases seen during the week for several years. The data is organized as such:

What I want to do is create a new column that tabulates that average number of cases for that same week in previous years. For instance, for the row where Week.Number is 1 and Flu.Year is 2017, I would like the new row to give the average count for any year with Week.Number==1 & Flu.Year<2017. Normally, I would use the case_when() function to conditionally tabulate something like this. For instance, when calculating the average weekly volume I used this code:

```<code>   mutate(average = case_when(
    Flu.Year==2016 ~ mean(chcc$count[chcc$Flu.Year==2016]),
    Flu.Year==2017 ~ mean(chcc$count[chcc$Flu.Year==2017]),
    Flu.Year==2018 ~ mean(chcc$count[chcc$Flu.Year==2018]),
    Flu.Year==2019 ~ mean(chcc$count[chcc$Flu.Year==2019]),
  ),
</code>```

However, since there are four years of data * 52 weeks which is a lot of iterations to spell out the conditions for. Is there a way to elegantly code this in dplyr? The problem I keep running into is that I want to call values in counts column based on Week.Number and Flu.Year values in other rows conditioned on the current value of Week.Number and Flu.Year, and I am not sure how to accomplish that. Please let me know if there is further information / detail I can provide.

Thanks,
Steven

dat <- tibble( Flu.Year = rep(2016:2019,each = 52), Week.Number = rep(1:52,4), count = sample(1000, size=52*4, replace=TRUE) )
```

答:
It's bad-form and, in some cases, an error when you use $-indexing within dplyr verbs.
I think a better way to get that average field is to group_by(Flu.Year) and calculate it straight-up.

library(dplyr)
set.seed(42)
dat <- tibble(
  Flu.Year = sample(2016:2020, size=100, replace=TRUE),
  count = sample(1000, size=100, replace=TRUE)
)

dat %>%
  group_by(Flu.Year) %>%
  mutate(average = mean(count)) %>%
  # just to show a quick summary
  slice(1:3) %>%
  ungroup()
# # A tibble: 15 x 3
#    Flu.Year count average
#       <int> <int>   <dbl>
#  1     2016   734    578.
#  2     2016   356    578.
#  3     2016   411    578.
#  4     2017   217    436.
#  5     2017   453    436.
#  6     2017   920    436.
#  7     2018   963    558
#  8     2018   609    558
#  9     2018   536    558
# 10     2019   943    543.
# 11     2019   740    543.
# 12     2019   536    543.
# 13     2020   627    494.
# 14     2020   218    494.
# 15     2020   389    494.
```

<p>An alternative approach is to generate a summary table (just one row per year) and join it back in to the original data.</p>

<pre class="lang-r prettyprint-override"><code>dat %>%
  group_by(Flu.Year) %>%
  summarize(average = mean(count))
# # A tibble: 5 x 2
#   Flu.Year average
#      <int>   <dbl>
# 1     2016    578.
# 2     2017    436.
# 3     2018    558
# 4     2019    543.
# 5     2020    494.

dat %>%
  group_by(Flu.Year) %>%
  summarize(average = mean(count)) %>%
  full_join(dat, by = "Flu.Year")
# # A tibble: 100 x 3
#    Flu.Year average count
#       <int>   <dbl> <int>
#  1     2016    578.   734
#  2     2016    578.   356
#  3     2016    578.   411
#  4     2016    578.   720
#  5     2016    578.   851
#  6     2016    578.   822
#  7     2016    578.   465
#  8     2016    578.   679
#  9     2016    578.    30
# 10     2016    578.   180
# # ... with 90 more rows
</code>```

The result, after chat:

tibble( Flu.Year = rep(2016:2018,each = 3), Week.Number = rep(1:3,3), count = 1:9 )  %>%
  arrange(Flu.Year, Week.Number) %>%
  group_by(Week.Number) %>%
  mutate(year_week.average = lag(cumsum(count) / seq_along(count)))
# # A tibble: 9 x 4
# # Groups:   Week.Number [3]
#   Flu.Year Week.Number count year_week.average
#      <int>       <int> <int>             <dbl>
# 1     2016           1     1              NA
# 2     2016           2     2              NA
# 3     2016           3     3              NA
# 4     2017           1     4               1
# 5     2017           2     5               2
# 6     2017           3     6               3
# 7     2018           1     7               2.5
# 8     2018           2     8               3.5
# 9     2018           3     9               4.5
```

Body:
I am working on creating conditional averages for a large data set that involves # of flu cases seen during the week for several years. The data is organized as such:

What I want to do is create a new column that tabulates that average number of cases for that same week in previous years. For instance, for the row where Week.Number is 1 and Flu.Year is 2017, I would like the new row to give the average count for any year with Week.Number==1 & Flu.Year<2017. Normally, I would use the case_when() function to conditionally tabulate something like this. For instance, when calculating the average weekly volume I used this code:

   mutate(average = case_when(
    Flu.Year==2016 ~ mean(chcc$count[chcc$Flu.Year==2016]),
    Flu.Year==2017 ~ mean(chcc$count[chcc$Flu.Year==2017]),
    Flu.Year==2018 ~ mean(chcc$count[chcc$Flu.Year==2018]),
    Flu.Year==2019 ~ mean(chcc$count[chcc$Flu.Year==2019]),
  ),

However, since there are four years of data * 52 weeks which is a lot of iterations to spell out the conditions for. Is there a way to elegantly code this in dplyr? The problem I keep running into is that I want to call values in counts column based on Week.Number and Flu.Year values in other rows conditioned on the current value of Week.Number and Flu.Year, and I am not sure how to accomplish that. Please let me know if there is further information / detail I can provide.

Thanks,
Steven

dat <- tibble( Flu.Year = rep(2016:2019,each = 52), Week.Number = rep(1:52,4), count = sample(1000, size=52*4, replace=TRUE) )

Body:
It's bad-form and, in some cases, an error when you use $-indexing within dplyr verbs.
I think a better way to get that average field is to group_by(Flu.Year) and calculate it straight-up.

library(dplyr)
set.seed(42)
dat <- tibble(
  Flu.Year = sample(2016:2020, size=100, replace=TRUE),
  count = sample(1000, size=100, replace=TRUE)
)

dat %>%
  group_by(Flu.Year) %>%
  mutate(average = mean(count)) %>%
  # just to show a quick summary
  slice(1:3) %>%
  ungroup()
# # A tibble: 15 x 3
#    Flu.Year count average
#       <int> <int>   <dbl>
#  1     2016   734    578.
#  2     2016   356    578.
#  3     2016   411    578.
#  4     2017   217    436.
#  5     2017   453    436.
#  6     2017   920    436.
#  7     2018   963    558
#  8     2018   609    558
#  9     2018   536    558
# 10     2019   943    543.
# 11     2019   740    543.
# 12     2019   536    543.
# 13     2020   627    494.
# 14     2020   218    494.
# 15     2020   389    494.

An alternative approach is to generate a summary table (just one row per year) and join it back in to the original data.

dat %>%
  group_by(Flu.Year) %>%
  summarize(average = mean(count))
# # A tibble: 5 x 2
#   Flu.Year average
#      <int>   <dbl>
# 1     2016    578.
# 2     2017    436.
# 3     2018    558
# 4     2019    543.
# 5     2020    494.

dat %>%
  group_by(Flu.Year) %>%
  summarize(average = mean(count)) %>%
  full_join(dat, by = "Flu.Year")
# # A tibble: 100 x 3
#    Flu.Year average count
#       <int>   <dbl> <int>
#  1     2016    578.   734
#  2     2016    578.   356
#  3     2016    578.   411
#  4     2016    578.   720
#  5     2016    578.   851
#  6     2016    578.   822
#  7     2016    578.   465
#  8     2016    578.   679
#  9     2016    578.    30
# 10     2016    578.   180
# # ... with 90 more rows

The result, after chat:

tibble( Flu.Year = rep(2016:2018,each = 3), Week.Number = rep(1:3,3), count = 1:9 )  %>%
  arrange(Flu.Year, Week.Number) %>%
  group_by(Week.Number) %>%
  mutate(year_week.average = lag(cumsum(count) / seq_along(count)))
# # A tibble: 9 x 4
# # Groups:   Week.Number [3]
#   Flu.Year Week.Number count year_week.average
#      <int>       <int> <int>             <dbl>
# 1     2016           1     1              NA
# 2     2016           2     2              NA
# 3     2016           3     3              NA
# 4     2017           1     4               1
# 5     2017           2     5               2
# 6     2017           3     6               3
# 7     2018           1     7               2.5
# 8     2018           2     8               3.5
# 9     2018           3     9               4.5


问:
Copy specific word from a file to another file using shell script
i am new to shell scripting.
my folder structure is like below format, in that every folder one file is there  the file  name is  note.json, so i want to copy from note.json specific word like "user", i tried this for single file, it's working but showing unnecessary data and also i needed in loop format (means going to every folder doing the same) can any body help me out?

my folder structure:

drwxr-xr-x   - zeppelin hdfs          0 2020-06-01 16:20 /user/zeppelin/notebook/2FBC2M3K2
drwxr-xr-x   - zeppelin hdfs          0 2020-05-20 18:01 /user/zeppelin/notebook/2FBDEKUGP
drwxr-xr-x   - zeppelin hdfs          0 2020-05-26 20:32 /user/zeppelin/notebook/2FBDXNZRC
drwxr-xr-x   - zeppelin hdfs          0 2020-05-26 21:00 /user/zeppelin/notebook/2FBEAGZEE
drwxr-xr-x   - zeppelin hdfs          0 2020-05-25 14:18 /user/zeppelin/notebook/2FBGXSHZR
drwxr-xr-x   - zeppelin hdfs          0 2020-05-20 14:31 /user/zeppelin/notebook/2FBHCNKJP
drwxr-xr-x   - zeppelin hdfs          0 2020-06-02 17:34 /user/zeppelin/notebook/2FBJCZ212
```

<p>I tried for single folder using below command,</p>

<pre class="lang-none prettyprint-override"><code>$ cat note.json | grep "user"
"user": "Ayan.Paul",
            "data": "org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: HiveAccessControlException Permission denied: user [Ayan.Paul] does not have [USE] privilege on [snt_mmedata_upload_prd]\n\tat org.apache.hive.jdbc.Utils.verifySuccess(Utils.java:300)\n\tat org.apache.hive.jdbc.Utils.verifySuccessWithInfo(Utils.java:286)\n\tat org.apache.hive.jdbc.HiveStatement.runAsyncOnServer(HiveStatement.java:324)\n\tat org.apache.hive.jdbc.HiveStatement.execute(HiveStatement.java:265)\n\tat org.apache.commons.dbcp2.DelegatingStatement.execute(DelegatingStatement.java:291)\n\tat org.apache.commons.dbcp2.DelegatingStatement.execute(DelegatingStatement.java:291)\n\tat org.apache.zeppelin.jdbc.JDBCInterpreter.executeSql(JDBCInterpreter.java:718)\n\tat org.apache.zeppelin.jdbc.JDBCInterpreter.interpret(JDBCInterpreter.java:801)\n\tat org.apache.zeppelin.interpreter.LazyOpenInterpreter.interpret(LazyOpenInterpreter.java:103)\n\tat org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:633)\n\tat org.apache.zeppelin.scheduler.Job.run(Job.java:188)\n\tat org.apache.zeppelin.scheduler.ParallelScheduler$JobRunner.run(ParallelScheduler.java:162)\n\tat java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)\n\tat java.util.concurrent.FutureTask.run(FutureTask.java:266)\n\tat java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)\n\tat java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)\n\tat java.lang.Thread.run(Thread.java:745)\nCaused by: org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: HiveAccessControlException Permission denied: user [Ayan.Paul] does not have [USE] privilege on [snt_mmedata_upload_prd]\n\tat org.apache.hive.service.cli.operation.Operation.toSQLException(Operation.java:335)\n\tat org.apache.hive.service.cli.operation.SQLOperation.prepare(SQLOperation.java:199)\n\tat org.apache.hive.service.cli.operation.SQLOperation.runInternal(SQLOperation.java:262)\n\tat org.apache.hive.service.cli.operation.Operation.run(Operation.java:247)\n\tat org.apache.hive.service.cli.session.HiveSessionImpl.executeStatementInternal(HiveSessionImpl.java:541)\n\tat org.apache.hive.service.cli.session.HiveSessionImpl.executeStatementAsync(HiveSessionImpl.java:527)\n\tat org.apache.hive.service.cli.CLIService.executeStatementAsync(CLIService.java:315)\n\tat org.apache.hive.service.cli.thrift.ThriftCLIService.ExecuteStatement(ThriftCLIService.java:562)\n\tat org.apache.hive.service.rpc.thrift.TCLIService$Processor$ExecuteStatement.getResult(TCLIService.java:1557)\n\tat org.apache.hive.service.rpc.thrift.TCLIService$Processor$ExecuteStatement.getResult(TCLIService.java:1542)\n\tat org.apache.thrift.ProcessFunction.process(ProcessFunction.java:39)\n\tat org.apache.thrift.TBaseProcessor.process(TBaseProcessor.java:39)\n\tat org.apache.thrift.server.TServlet.doPost(TServlet.java:83)\n\tat org.apache.hive.service.cli.thrift.ThriftHttpServlet.doPost(ThriftHttpServlet.java:208)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:707)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:790)\n\tat org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:848)\n\tat org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:584)\n\tat org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:224)\n\tat org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180)\n\tat org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:512)\n\tat org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)\n\tat org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)\n\tat org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)\n\tat org.eclipse.jetty.server.handler.gzip.GzipHandler.handle(GzipHandler.java:493)\n\tat org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)\n\tat org.eclipse.jetty.server.Server.handle(Server.java:534)\n\tat org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320)\n\tat org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)\n\tat org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:283)\n\tat org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:108)\n\tat org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)\n\tat org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)\n\tat org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)\n\tat org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)\n\t... 3 more\nCaused by: java.lang.RuntimeException: org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAccessControlException:Permission denied: user [Ayan.Paul] does not have [USE] privilege on [snt_mmedata_upload_prd]\n\tat org.apache.ranger.authorization.hive.authorizer.RangerHiveAuthorizer.checkPrivileges(RangerHiveAuthorizer.java:483)\n\tat org.apache.hadoop.hive.ql.Driver.doAuthorizationV2(Driver.java:1330)\n\tat org.apache.hadoop.hive.ql.Driver.doAuthorization(Driver.java:1094)\n\tat org.apache.hadoop.hive.ql.Driver.compile(Driver.java:705)\n\tat org.apache.hadoop.hive.ql.Driver.compileInternal(Driver.java:1863)\n\tat org.apache.hadoop.hive.ql.Driver.compileAndRespond(Driver.java:1810)\n\tat org.apache.hadoop.hive.ql.Driver.compileAndRespond(Driver.java:1805)\n\tat org.apache.hadoop.hive.ql.reexec.ReExecDriver.compileAndRespond(ReExecDriver.java:126)\n\
</code>```

答:
If you know that the note.json file always has "user" at the beginning of a line, then you can grep for that.  It also sounds like you want the value of the "user" JSON field.  Try using jq to parse that.  Below is the "cheap and dirty" way of stripping out the extra characters.  (We'll stick with a loop because you're probably doing something other things for each file...)

```<code>for file in $(find . -name note.json); do
    grep "^.user" $file | cut -c 10- | tr -d '",'
done
</code>```

If you want help with using jq to parse JSON, just ask a different question showing a "note.json" file and your attempt at pasring it!

Body:
i am new to shell scripting.
my folder structure is like below format, in that every folder one file is there  the file  name is  note.json, so i want to copy from note.json specific word like "user", i tried this for single file, it's working but showing unnecessary data and also i needed in loop format (means going to every folder doing the same) can any body help me out?

my folder structure:

drwxr-xr-x   - zeppelin hdfs          0 2020-06-01 16:20 /user/zeppelin/notebook/2FBC2M3K2
drwxr-xr-x   - zeppelin hdfs          0 2020-05-20 18:01 /user/zeppelin/notebook/2FBDEKUGP
drwxr-xr-x   - zeppelin hdfs          0 2020-05-26 20:32 /user/zeppelin/notebook/2FBDXNZRC
drwxr-xr-x   - zeppelin hdfs          0 2020-05-26 21:00 /user/zeppelin/notebook/2FBEAGZEE
drwxr-xr-x   - zeppelin hdfs          0 2020-05-25 14:18 /user/zeppelin/notebook/2FBGXSHZR
drwxr-xr-x   - zeppelin hdfs          0 2020-05-20 14:31 /user/zeppelin/notebook/2FBHCNKJP
drwxr-xr-x   - zeppelin hdfs          0 2020-06-02 17:34 /user/zeppelin/notebook/2FBJCZ212

I tried for single folder using below command,

$ cat note.json | grep "user"
"user": "Ayan.Paul",
            "data": "org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: HiveAccessControlException Permission denied: user [Ayan.Paul] does not have [USE] privilege on [snt_mmedata_upload_prd]\n\tat org.apache.hive.jdbc.Utils.verifySuccess(Utils.java:300)\n\tat org.apache.hive.jdbc.Utils.verifySuccessWithInfo(Utils.java:286)\n\tat org.apache.hive.jdbc.HiveStatement.runAsyncOnServer(HiveStatement.java:324)\n\tat org.apache.hive.jdbc.HiveStatement.execute(HiveStatement.java:265)\n\tat org.apache.commons.dbcp2.DelegatingStatement.execute(DelegatingStatement.java:291)\n\tat org.apache.commons.dbcp2.DelegatingStatement.execute(DelegatingStatement.java:291)\n\tat org.apache.zeppelin.jdbc.JDBCInterpreter.executeSql(JDBCInterpreter.java:718)\n\tat org.apache.zeppelin.jdbc.JDBCInterpreter.interpret(JDBCInterpreter.java:801)\n\tat org.apache.zeppelin.interpreter.LazyOpenInterpreter.interpret(LazyOpenInterpreter.java:103)\n\tat org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:633)\n\tat org.apache.zeppelin.scheduler.Job.run(Job.java:188)\n\tat org.apache.zeppelin.scheduler.ParallelScheduler$JobRunner.run(ParallelScheduler.java:162)\n\tat java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)\n\tat java.util.concurrent.FutureTask.run(FutureTask.java:266)\n\tat java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)\n\tat java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)\n\tat java.lang.Thread.run(Thread.java:745)\nCaused by: org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: HiveAccessControlException Permission denied: user [Ayan.Paul] does not have [USE] privilege on [snt_mmedata_upload_prd]\n\tat org.apache.hive.service.cli.operation.Operation.toSQLException(Operation.java:335)\n\tat org.apache.hive.service.cli.operation.SQLOperation.prepare(SQLOperation.java:199)\n\tat org.apache.hive.service.cli.operation.SQLOperation.runInternal(SQLOperation.java:262)\n\tat org.apache.hive.service.cli.operation.Operation.run(Operation.java:247)\n\tat org.apache.hive.service.cli.session.HiveSessionImpl.executeStatementInternal(HiveSessionImpl.java:541)\n\tat org.apache.hive.service.cli.session.HiveSessionImpl.executeStatementAsync(HiveSessionImpl.java:527)\n\tat org.apache.hive.service.cli.CLIService.executeStatementAsync(CLIService.java:315)\n\tat org.apache.hive.service.cli.thrift.ThriftCLIService.ExecuteStatement(ThriftCLIService.java:562)\n\tat org.apache.hive.service.rpc.thrift.TCLIService$Processor$ExecuteStatement.getResult(TCLIService.java:1557)\n\tat org.apache.hive.service.rpc.thrift.TCLIService$Processor$ExecuteStatement.getResult(TCLIService.java:1542)\n\tat org.apache.thrift.ProcessFunction.process(ProcessFunction.java:39)\n\tat org.apache.thrift.TBaseProcessor.process(TBaseProcessor.java:39)\n\tat org.apache.thrift.server.TServlet.doPost(TServlet.java:83)\n\tat org.apache.hive.service.cli.thrift.ThriftHttpServlet.doPost(ThriftHttpServlet.java:208)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:707)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:790)\n\tat org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:848)\n\tat org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:584)\n\tat org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:224)\n\tat org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180)\n\tat org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:512)\n\tat org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)\n\tat org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)\n\tat org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)\n\tat org.eclipse.jetty.server.handler.gzip.GzipHandler.handle(GzipHandler.java:493)\n\tat org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)\n\tat org.eclipse.jetty.server.Server.handle(Server.java:534)\n\tat org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320)\n\tat org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)\n\tat org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:283)\n\tat org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:108)\n\tat org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)\n\tat org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)\n\tat org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)\n\tat org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)\n\t... 3 more\nCaused by: java.lang.RuntimeException: org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAccessControlException:Permission denied: user [Ayan.Paul] does not have [USE] privilege on [snt_mmedata_upload_prd]\n\tat org.apache.ranger.authorization.hive.authorizer.RangerHiveAuthorizer.checkPrivileges(RangerHiveAuthorizer.java:483)\n\tat org.apache.hadoop.hive.ql.Driver.doAuthorizationV2(Driver.java:1330)\n\tat org.apache.hadoop.hive.ql.Driver.doAuthorization(Driver.java:1094)\n\tat org.apache.hadoop.hive.ql.Driver.compile(Driver.java:705)\n\tat org.apache.hadoop.hive.ql.Driver.compileInternal(Driver.java:1863)\n\tat org.apache.hadoop.hive.ql.Driver.compileAndRespond(Driver.java:1810)\n\tat org.apache.hadoop.hive.ql.Driver.compileAndRespond(Driver.java:1805)\n\tat org.apache.hadoop.hive.ql.reexec.ReExecDriver.compileAndRespond(ReExecDriver.java:126)\n\

Body:
If you know that the note.json file always has "user" at the beginning of a line, then you can grep for that.  It also sounds like you want the value of the "user" JSON field.  Try using jq to parse that.  Below is the "cheap and dirty" way of stripping out the extra characters.  (We'll stick with a loop because you're probably doing something other things for each file...)

for file in $(find . -name note.json); do
    grep "^.user" $file | cut -c 10- | tr -d '",'
done

If you want help with using jq to parse JSON, just ask a different question showing a "note.json" file and your attempt at pasring it!


问:
C# remove string inside bounderies
sorry if this is duplicate or something but i was unable to find solution in c# for my problem. I have c# string that lookl like this:

string aa = "First Example (first to delete) , Second example ( Second to delete ) , Thrird Example ( Third to delete )"

From this string I want to delete everything that is inside ( SOME INPUT ) with ( and ).

Problem is that I dont know what this SOME INPUT is. I only know that it is inside ().

Thanks for any help.

答:
https://dotnetfiddle.net/Jnhszs

```<code>using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
    var text = "First Example (first to delete) , Second example ( Second to delete ) , Thrird Example ( Third to delete )";

    text = Regex.Replace(text, @"\([^)]*\)", "");
    text = Regex.Replace(text, @"\s{2,}", " ");

    Console.WriteLine(text);
    }
}
</code>```

Output: First Example , Second example , Thrird Example

Title: C# remove string inside bounderies

Body:
https://dotnetfiddle.net/Jnhszs

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
    var text = "First Example (first to delete) , Second example ( Second to delete ) , Thrird Example ( Third to delete )";

    text = Regex.Replace(text, @"\([^)]*\)", "");
    text = Regex.Replace(text, @"\s{2,}", " ");

    Console.WriteLine(text);
    }
}

Output: First Example , Second example , Thrird Example


问:
How to get progress of current epoch during tf.keras training?
I am writing a GUI application for training of various tf.keras-based models. So all the information on accuracy, loss etc. should be visible on the GUI instead of the default Keras console output.

Now I managed to get all the relevant information during model training via a custom tf.keras.callbacks.Callback class, which works fine. But I also want to get the progress of the current epoch, i.e. how much % of the current epoch has been trained so far, i.e. what Keras prints to console during training via the progress bar.

Is there any way to retrieve that information in a Keras callback as well?

答:
Ok, found the solution. It can be found in the self.params attribute of the Callback class.

For me this works:

```<code>def on_epoch_begin(self, epoch, logs=None):
    self.epoch_step = 0

def on_batch_end(self, batch, logs=None):
    self.epoch_step += 1
    progress = self.epoch_step / self.params["steps"]
</code>```

For the reords, I found this solution here in the keras-tqdm GitHub repo.

Body:
Ok, found the solution. It can be found in the self.params attribute of the Callback class.

For me this works:

def on_epoch_begin(self, epoch, logs=None):
    self.epoch_step = 0

def on_batch_end(self, batch, logs=None):
    self.epoch_step += 1
    progress = self.epoch_step / self.params["steps"]

For the reords, I found this solution here in the keras-tqdm GitHub repo.


问:
Python Version is not getting displayed in Command Prompt
I downloaded the recent version of python(3.8.3) and selected the 'ADD TO PATH' prompt during setup and it was successfully completed(I checked by running the python.exe file in the source folder) but when i type 'python' or 'python --version' to check which version I am running in the command prompt, it doesn't show anything.

Some of the posts online suggested, to add the path manually again in system variables under environment variables, I did that too but it didn't work. I also tried uninstalling and reinstalling it several times but that didn't work too.

I am running Windows 10 Home 64-bit.
Please Help.
Thank you!

Command prompt

答: On windows the python executable is py.exe, not python.exe (unless you are using a venv, which uses the latter to access).  Use py command instead, i.e. py --version.


问:
diff_match_patch: Generating side-by-side view
I'm using google-diff-match-patch with my Java app to create a diff. I use the method diff_prettyHtml for generating HTML output of the diff.

However, I would like to have two different outputs, so I can put them side-by-side to make it a bit more easy for the user to see the differences. (For example, like Eclipse does.)

Is there anything in that library I can use to achieve this? How would you do that? (I would not use a different library, if possible.)

答: Assuming you're not attempting to diff HTML, in which case I'd suggest using DaisyDiff, what you probably want to do with diff-match-patch is line differencing, which is described on a project wiki page. Basically it involves generating an array of hash codes, one for each line of the left and right, and keeping track of those hash codes relative to the lines in a map, and then running those arrays through the diffing algorithm. Then you use the diff output in conjunction with the map to rehydrate left and right highlighting as appropriate. </p>


问:
Angular9 SSR meta tags not loading inside of promises
I'm using Angular Universal and NestJS for my SSR. When I run npm run build:ssr and deploy it I get no errors, but the meta tags inside of promises are not shown when linking the website, but links for routes where I set the meta tags at the root level of ngOnInit do load the meta tags as expected when linking the website.

Code for setting meta tags.

```<code>generateTags({ title = '', description = '', image = '' }) {

 this.title.setTitle(title);
 this.meta.addTags([
   // Open Graph
   { name: 'og:url', content: `https://firestarter.fireship.io${this.router.url}` },
   { name: 'og:title', content: title },
   { name: 'og:description', content: description },
   { name: 'og:image', content: image },
   // Twitter Card
   { name: 'twitter:card', content: 'summary' },
   { name: 'twitter:site', content: '@fireship_dev' },
 ]);
}
</code>```

Eksample of code that does not load the meta tags

```<code>this.db.firestore.collection('users').doc(this.customerId).get().then((userRef) => {
  this.seo.generateTags({
    title: userRef.data().displayName,
    description: userRef.data().about,
    image: userRef.data().photoURL,
  })
})
</code>```

Example of code that does not load the meta tags

```<code>this.seo.generateTags({
  title: userRef.data().displayName,
  description: userRef.data().about,
  image: userRef.data().photoURL,
})
</code>```

Example with full component:

```<code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AngularFirestore } from '@angular/fire/firestore';
import { SeoService } from 'src/app/services/seo.service';

@Component({
  selector: 'app-profileviewer',
  templateUrl: './profileviewer.component.html',
  styleUrls: ['./profileviewer.component.css']
})
export class ProfileviewerComponent implements OnInit {

  customerId: string;

  constructor(
    private route: ActivatedRoute,
    private db: AngularFirestore,
    private seo: SeoService) { }

  ngOnInit() {
    this.customerId = this.route.snapshot.paramMap.get('id');

    this.db.firestore.collection('users').doc(this.customerId).get().then((userRef) => {
      this.seo.generateTags({
        title: userRef.data().displayName,
        description: userRef.data().about,
        image: userRef.data().photoURL,
      })
    })
  }
}
</code>```

Who can I display content from e.g firebase in my meta tags with Angular9 with NestJS?

I have made a dummy project on GitHub where I get this error. To reproduce attach firebase project in the environments file and run npm run serve:ssr (maybe npm run build:ssr if you get an error) and see in the source code in chrome that the meta tags are not rendered.

EDIT:
I have tried using resolve to fix this issue, but it still doesn't work with promises. This is the resolve script that I use:

```<code>import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Http } from '@angular/http';

@Injectable({
  providedIn: 'root'
})
export class LoadSeoService implements Resolve<any> {
  constructor (private http: Http, private db: AngularFirestore) {

  }

  resolve (route: ActivatedRouteSnapshot, rstate: RouterStateSnapshot) {
    // Works
    return "test"

    // Does not work
    // return this.db.firestore.collection("articles").doc(route.params['id'].substr(route.params['id'].length - 20)).get();
  }
}
</code>```

The code I use in my component:

```<code>this.route.data.subscribe(data => {
  console.log(data.cres)

  this.seo.generateTags({
    title: data.cres,
    description: data.cres,
    image: data.cres,
  })
});
</code>```

答:
Finally, after lot of research and debugging i found out why were you not seeing meta tags in your index.html.

Be sure your meta tags are getting added. I printed meta object in console After adding Tags. You can also check it. Print it :-
in output go under _doc>documentChild>innerHtml

In the image above in innerHTML, you can notice your meta tags.

Now why they were not part of index.html, when it was displayed is, because firebase promise will automatically get resolved when its connected to firebase and receive the data. But because its part of your. Your ssr will not generate tags. These tags will be appened later dynamically when your proise is resolved.Any thing that is being changed after page loads that won't be shown in page view source.If you want to check the updated meta tags you need to inspect element and check there.

To prove my 2nd point, here is screenshot of file in network tab of index.html.

and there is screenshot of element inspector showing that your meta tags were added successfully but on runtime.

If you will create a normal promise and inside that call your generate tags method, it will be showing in source itself, because you will resolve that promise there only. But in case of firebase, that promise is not resolved until data is fetched, hence your ssr coun't pre-render it.

To enable firebase with ssr, you can find info here :-

https://medium.com/@antonybudianto/server-side-rendering-with-react-and-firebase-functions-cd67fdb2b605

Body:
I'm using Angular Universal and NestJS for my SSR. When I run npm run build:ssr and deploy it I get no errors, but the meta tags inside of promises are not shown when linking the website, but links for routes where I set the meta tags at the root level of ngOnInit do load the meta tags as expected when linking the website.

Code for setting meta tags.

generateTags({ title = '', description = '', image = '' }) {

 this.title.setTitle(title);
 this.meta.addTags([
   // Open Graph
   { name: 'og:url', content: `https://firestarter.fireship.io${this.router.url}` },
   { name: 'og:title', content: title },
   { name: 'og:description', content: description },
   { name: 'og:image', content: image },
   // Twitter Card
   { name: 'twitter:card', content: 'summary' },
   { name: 'twitter:site', content: '@fireship_dev' },
 ]);
}

Eksample of code that does not load the meta tags

this.db.firestore.collection('users').doc(this.customerId).get().then((userRef) => {
  this.seo.generateTags({
    title: userRef.data().displayName,
    description: userRef.data().about,
    image: userRef.data().photoURL,
  })
})

Example of code that does not load the meta tags

this.seo.generateTags({
  title: userRef.data().displayName,
  description: userRef.data().about,
  image: userRef.data().photoURL,
})

Example with full component:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AngularFirestore } from '@angular/fire/firestore';
import { SeoService } from 'src/app/services/seo.service';

@Component({
  selector: 'app-profileviewer',
  templateUrl: './profileviewer.component.html',
  styleUrls: ['./profileviewer.component.css']
})
export class ProfileviewerComponent implements OnInit {

  customerId: string;

  constructor(
    private route: ActivatedRoute,
    private db: AngularFirestore,
    private seo: SeoService) { }

  ngOnInit() {
    this.customerId = this.route.snapshot.paramMap.get('id');

    this.db.firestore.collection('users').doc(this.customerId).get().then((userRef) => {
      this.seo.generateTags({
        title: userRef.data().displayName,
        description: userRef.data().about,
        image: userRef.data().photoURL,
      })
    })
  }
}

Who can I display content from e.g firebase in my meta tags with Angular9 with NestJS?

I have made a dummy project on GitHub where I get this error. To reproduce attach firebase project in the environments file and run npm run serve:ssr (maybe npm run build:ssr if you get an error) and see in the source code in chrome that the meta tags are not rendered.

EDIT:
I have tried using resolve to fix this issue, but it still doesn't work with promises. This is the resolve script that I use:

import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Http } from '@angular/http';

@Injectable({
  providedIn: 'root'
})
export class LoadSeoService implements Resolve<any> {
  constructor (private http: Http, private db: AngularFirestore) {

  }

  resolve (route: ActivatedRouteSnapshot, rstate: RouterStateSnapshot) {
    // Works
    return "test"

    // Does not work
    // return this.db.firestore.collection("articles").doc(route.params['id'].substr(route.params['id'].length - 20)).get();
  }
}

The code I use in my component:

this.route.data.subscribe(data => {
  console.log(data.cres)

  this.seo.generateTags({
    title: data.cres,
    description: data.cres,
    image: data.cres,
  })
});


问:
mongodb load document and increment counter
Maybe this sounds bit strange but i will ask it.

In my application i store posts in my collection called posts. It looks like this

```<code>{
   _id: 123,
   name: "somename",
   surname: "somesurname",
   img: "path/to/img",
   views: 0
}
</code>```

So is it possible in mongodb to increase the views everytime that document gets loaded? Or do i need an workaround?

My other solution is after i fetch all data with .find() or .aggregate() to map all the _ids and execute an update query with $in to increase everywhere the views by 1. I hope you know what i mean.

But i think its kinda in-efficient, because i need 2 querys. I was also thinking about, instead of using querys like .find(), to use update querys and return the new document with new: true. Is this possible, can somebody help me here?

答:
Yes, directly you can increment by updating the collection

```<code>db.posts.update({ _id: { $inc: { views: 1 } })
</code>```

For more, you can see the documentation https://docs.mongodb.com/manual/reference/operator/update/inc/

Body:
Maybe this sounds bit strange but i will ask it.

In my application i store posts in my collection called posts. It looks like this

{
   _id: 123,
   name: "somename",
   surname: "somesurname",
   img: "path/to/img",
   views: 0
}

So is it possible in mongodb to increase the views everytime that document gets loaded? Or do i need an workaround?

My other solution is after i fetch all data with .find() or .aggregate() to map all the _ids and execute an update query with $in to increase everywhere the views by 1. I hope you know what i mean.

But i think its kinda in-efficient, because i need 2 querys. I was also thinking about, instead of using querys like .find(), to use update querys and return the new document with new: true. Is this possible, can somebody help me here?

Body:
Yes, directly you can increment by updating the collection

db.posts.update({ _id: { $inc: { views: 1 } })

For more, you can see the documentation https://docs.mongodb.com/manual/reference/operator/update/inc/


问:
Visualstudio SQLite select Datetime
I have to do a cross platform app in Visual Studio for a school project. Now I'm having trouble with the SQLite database. I save individual drink data as follows.

```<code>public class Drink
   {
       [PrimaryKey,AutoIncrement]
       public int Id { get; set; }
       public string Name { get; set; }
       public double Volume { get; set; }
       public DateTime Drinktime { get; set; }
       public double Size { get; set; }
   }
</code>```

Among other things with a timestamp (Drinktime). So far so good, now my problem is that I want to read the drinks from the database after this time stamp.

My goal is now to write a function how I can call up all drinks between a certain point in time (DateTime Format) and now .

```<code>public List<Drink> GetAllDrinks()
       {
           lock (locker)
           {
               if (database.Table<Drink>().Count() == 0)
               {
                   return null;
               }
               else
               {
                   return database.Table<Drink>().ToList();
               }
           }
       }
</code>```

but unfortunately I don't know how I can do it and after many hours of research without success I hope that one of you can help me. I only managed to read all the drinks.

Can someone help me there?

greetins Marv00

答:
use LINQ</p>

```<code>var all = return database.Table<Drink>().ToList();

return all.Where(a => a.DrinkTime >= myDateTime).ToList();
</code>```

Title: Visualstudio SQLite select Datetime

Body:
I have to do a cross platform app in Visual Studio for a school project. Now I'm having trouble with the SQLite database. I save individual drink data as follows.

public class Drink
   {
       [PrimaryKey,AutoIncrement]
       public int Id { get; set; }
       public string Name { get; set; }
       public double Volume { get; set; }
       public DateTime Drinktime { get; set; }
       public double Size { get; set; }
   }

Among other things with a timestamp (Drinktime). So far so good, now my problem is that I want to read the drinks from the database after this time stamp.

My goal is now to write a function how I can call up all drinks between a certain point in time (DateTime Format) and now .

public List<Drink> GetAllDrinks()
       {
           lock (locker)
           {
               if (database.Table<Drink>().Count() == 0)
               {
                   return null;
               }
               else
               {
                   return database.Table<Drink>().ToList();
               }
           }
       }

but unfortunately I don't know how I can do it and after many hours of research without success I hope that one of you can help me. I only managed to read all the drinks.

Can someone help me there?

greetins Marv00

Body:
use LINQ

var all = return database.Table<Drink>().ToList();

return all.Where(a => a.DrinkTime >= myDateTime).ToList();