问:
Why does yyp not behave according to p's documentation
I was just wondering if someone could explain what goes on behind the scenes w.r.t the behaviour of yyp.

Given some text:

```<code>Text that can be copied
</code>```

typing yyp while the cursor is in the middle of a line, let's say just before can, results in:

```<code>Text that can be copied
Text that can be copied
</code>```

Which, while very useful and logical, is not what p typically does.

As p pastes after the cursor, and my cursor remains before can, I don't feel I would be wrong to expect something like:

```<code>Text that Text that can be copied can be copied
</code>```

While I agree the former is more useful – could someone explain why and how in these instances the default behaviour of p is ignored?

答:
This is explained at :help linewise-register. Vim motions either cover a sequence of characters or whole lines. Likewise, text that is yanked into a register either is comprised of characters (including newlines, but not ending with one), complete lines (always ending with a newline), or a block of text (from a <C-V> blockwise visual selection). When you paste, the "insertion point" is determined by the source register, so complete lines will be pasted on separate lines. The :reg command indicates the type for each register with c / l / b in the first column.

```<code>:reg abc
Type Name Content
c  "a   a word
l  "b   a line^J
b  "c   a block^Jof text
</code>```

I agree with you that the default behavior is useful. Sometimes, it is helpful to override that, though, e.g. to paste an incomplete text as a separate line, or to insert a full deleted line inside an existing line. Vim offers ways to insert the register contents they way you want, but you have to remember it and it's several keys to type. I needed to "cast" register contents into a certain (characterwise / linewise / blockwise) mode so often, I wrote the UnconditionalPaste plugin for it. It provides gcp, glp, etc. alternatives to the built-in paste commands that force a certain mode (and by now several more variations on this theme, like pasting with joined by commas or queried characters).

Body:
I was just wondering if someone could explain what goes on behind the scenes w.r.t the behaviour of yyp.

Given some text:

Text that can be copied

typing yyp while the cursor is in the middle of a line, let's say just before can, results in:

Text that can be copied
Text that can be copied

Which, while very useful and logical, is not what p typically does.

As p pastes after the cursor, and my cursor remains before can, I don't feel I would be wrong to expect something like:

Text that Text that can be copied can be copied

While I agree the former is more useful – could someone explain why and how in these instances the default behaviour of p is ignored?

Body:
This is explained at :help linewise-register. Vim motions either cover a sequence of characters or whole lines. Likewise, text that is yanked into a register either is comprised of characters (including newlines, but not ending with one), complete lines (always ending with a newline), or a block of text (from a <C-V> blockwise visual selection). When you paste, the "insertion point" is determined by the source register, so complete lines will be pasted on separate lines. The :reg command indicates the type for each register with c / l / b in the first column.

:reg abc
Type Name Content
c  "a   a word
l  "b   a line^J
b  "c   a block^Jof text

I agree with you that the default behavior is useful. Sometimes, it is helpful to override that, though, e.g. to paste an incomplete text as a separate line, or to insert a full deleted line inside an existing line. Vim offers ways to insert the register contents they way you want, but you have to remember it and it's several keys to type. I needed to "cast" register contents into a certain (characterwise / linewise / blockwise) mode so often, I wrote the UnconditionalPaste plugin for it. It provides gcp, glp, etc. alternatives to the built-in paste commands that force a certain mode (and by now several more variations on this theme, like pasting with joined by commas or queried characters).


来源: stackexchange

问:
postgresql - bytea v jsonb vs xml
Would be needing to store in a field either an XML or JSON or could be other types as well in the future in postgresql.  From the docs https://www.postgresql.org/docs/current/datatype.html, I understand we have xml, json, jsonb, bytea datatypes.  There's really need to query each by tag or field, just need to dump the file to store and fetch it as a whole, so I'm thinking of bytea instead.  Any significant performance on it?  Am I on the right track.

TIA

答: As both types you want to store are made of character data (and not binary data), the best choice would be text

ContentLicense: CC BY-SA 4.0

Title: postgresql - bytea v jsonb vs xml


问:
Allowing both comma or dot in currency parameter
I have this in my model:

```<code>  monetize :advance_amount_cents, allow_nil: true
  monetize :rental_amount_cents, allow_nil: true
</code>```

I use AutoNumeric to display the currency.  It sends it back to the controller like this in params:

```<code>'rental_amount' = "2050.12"
</code>```

Which returns this error from the model:

```<code>activerecord.errors.models.rental_period.attributes.rental_amount.invalid_currency
</code>```

It accepts the currency when I can get it to be sent with a comma instead of a dot as decimal.  What is the best practise here?  Ideally I would like for all attributes that are monetized to accept anything as decimal separator, comma or dot.  That's also how Monetize seems to do it:

```<code>pry(main)> Monetize.parse "2050.12"
=> #<Money fractional:205012 currency:USD>
pry(main)> Monetize.parse "2050,12"
=> #<Money fractional:205012 currency:USD>
</code>```

Which is perfect.  How can I configure my model (or the Monetize gem in general) to accept both as params (dot or comma).

答:
Hopefully this is of use to someone.

Model:

```<code>monetize :rental_amount_cents, allow_nil: true
</code>```

View:

```<code>  = f.input :rental_amount, label: 'Rental amount' do
    .input-group
      = text_field_tag :rental_amount, @rental_period.rental_amount, class: 'form-control', id: "#{@rental_period.new_record? ? '' : (@rental_period.id.to_s + '_')}rental_amount_rate_rendered"
      = f.hidden_field :rental_amount, class: 'rate-input'
      %span.input-group-addon €
</code>```

Javascript setup:

```<code>$('[id$=rate_rendered]').add('.flex-rate').autoNumeric('init', settings.money_nosign).on('keyup', function() {
  var $hid;
  $hid = $(this).parent().find('input.rate-input');
  if ($(this).autoNumeric('get') !== '') {
    return $hid.val($(this).autoNumeric('get').replace('.', ','));
  } else {
    return $hid.val(0);
  }
});
</code>```

In settings I have (only relevant part:

```<code>window.settings = {
  money_nosign: {
    aDec: ',',
    aSep: '.',
    vMin: '-999999999.99'
  }
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this in my model:

  monetize :advance_amount_cents, allow_nil: true
  monetize :rental_amount_cents, allow_nil: true

I use AutoNumeric to display the currency.  It sends it back to the controller like this in params:

'rental_amount' = "2050.12"

Which returns this error from the model:

activerecord.errors.models.rental_period.attributes.rental_amount.invalid_currency

It accepts the currency when I can get it to be sent with a comma instead of a dot as decimal.  What is the best practise here?  Ideally I would like for all attributes that are monetized to accept anything as decimal separator, comma or dot.  That's also how Monetize seems to do it:

pry(main)> Monetize.parse "2050.12"
=> #<Money fractional:205012 currency:USD>
pry(main)> Monetize.parse "2050,12"
=> #<Money fractional:205012 currency:USD>

Which is perfect.  How can I configure my model (or the Monetize gem in general) to accept both as params (dot or comma).

Body:
Hopefully this is of use to someone.

Model:

monetize :rental_amount_cents, allow_nil: true

View:

  = f.input :rental_amount, label: 'Rental amount' do
    .input-group
      = text_field_tag :rental_amount, @rental_period.rental_amount, class: 'form-control', id: "#{@rental_period.new_record? ? '' : (@rental_period.id.to_s + '_')}rental_amount_rate_rendered"
      = f.hidden_field :rental_amount, class: 'rate-input'
      %span.input-group-addon €

Javascript setup:

$('[id$=rate_rendered]').add('.flex-rate').autoNumeric('init', settings.money_nosign).on('keyup', function() {
  var $hid;
  $hid = $(this).parent().find('input.rate-input');
  if ($(this).autoNumeric('get') !== '') {
    return $hid.val($(this).autoNumeric('get').replace('.', ','));
  } else {
    return $hid.val(0);
  }
});

In settings I have (only relevant part:

window.settings = {
  money_nosign: {
    aDec: ',',
    aSep: '.',
    vMin: '-999999999.99'
  }
};


问:
Conda environment from linux to windows
I am working on an image processing / computer vision / deep learning app which requires the use of old versions for some Python packages.
I am new to the world of machine learning and software,it's been 6 months that I made a career change and I am not aware of the best practices when it comes to python projects that work for different platforms (Windows, Linux, MacOS).
So today, I am working on a linux, I did some conda installs and some pip installs and I am exporting my environment to a .yml file. How to make sure that creating a virtual environment on a Windows Machine using conda and my exported .yml file is going to work with no problems ?</p>

答:
first you create the virtual environment e.g.

```<code>pipenv shell
</code>```

then you write a batch script checking for python packages in that environment:

```<code>echo %time% Check if python packages are installed...
echo ------------------------------------------------------------------------
pip install -r [your .yml file]
echo ------------------------------------------------------------------------
</code>```

Title: Conda environment from linux to windows

Body:
first you create the virtual environment e.g.

pipenv shell

then you write a batch script checking for python packages in that environment:

echo %time% Check if python packages are installed...
echo ------------------------------------------------------------------------
pip install -r [your .yml file]
echo ------------------------------------------------------------------------


问:
How to create a mailitem?
I'm trying to send the active Excel workbook as an attachment via Outlook.

Whenever I run the code it says

Invalid use of New key word

at New Outlook.MailItem`.

```<code>Sub SendOutlook()
    'Declaring Variables
    Dim OutlookApp  As Outlook.Application
    Dim OutlookEmail  As Outlook.MailItem

    'Assigning variables to create outlook application and mailitem
    Set OutlookApp = New Outlook.Application
    Set OutlookEmail = New Outlook.MailItem

    With OutlookEmail
        'Format of the mail
        .BodyFormat = olFormatPlain
        'Body of the mail
        .Body = "Dear Someone" & vbNewLine & "How are you?"
        'To whom you want to send mail
        .To = "Someone@somewhere.com"
        'Subject of mail
        .Subject = "Write Subject Here"
        'TO add an attachment
        .Attachments.Add ActiveWorkbook.FullName
        'sends the mail
        .Send
    End With

End Sub
</code>```

答:
You cannot create a MailItem via New. It must be created using CreateItem of the the Outlook Application Object.

```<code>   Set OutlookApp = New Outlook.Application
   Set OutlookEmail = OutlookApp.CreateItem(olMailItem)
</code>```

Title: How to create a mailitem?

Body:
I'm trying to send the active Excel workbook as an attachment via Outlook.

Whenever I run the code it says

Invalid use of New key word

at New Outlook.MailItem`.

Sub SendOutlook()
    'Declaring Variables
    Dim OutlookApp  As Outlook.Application
    Dim OutlookEmail  As Outlook.MailItem

    'Assigning variables to create outlook application and mailitem
    Set OutlookApp = New Outlook.Application
    Set OutlookEmail = New Outlook.MailItem

    With OutlookEmail
        'Format of the mail
        .BodyFormat = olFormatPlain
        'Body of the mail
        .Body = "Dear Someone" & vbNewLine & "How are you?"
        'To whom you want to send mail
        .To = "Someone@somewhere.com"
        'Subject of mail
        .Subject = "Write Subject Here"
        'TO add an attachment
        .Attachments.Add ActiveWorkbook.FullName
        'sends the mail
        .Send
    End With

End Sub

Body:
You cannot create a MailItem via New. It must be created using CreateItem of the the Outlook Application Object.

   Set OutlookApp = New Outlook.Application
   Set OutlookEmail = OutlookApp.CreateItem(olMailItem)


问:
What do we need to do to fix this equation so that it works in our Python code?
Assignment and code below...

I am assisting my son with his homework. I know coding, but not Python. He has gotten this far and has asked me to jump in to assist and I am stumped. I believe that the equation for the total take-home salary is too long, but I am not sure what to do to help. The code works as is, but when we try to switch the "...will take home $" + str(emp_1.salary) + ", after taxes." with "...will take home $" + str(emp_1.apply_taxes()) + ", after taxes." for both emp_1 and emp_2 we get an error that apply_taxes is not defined. all we need to do is get the equation to work and we will be good. Any suggestions would be greatly appreciated!

Thank you!!

This is the assignment:

Include to class variables that will account for the federal tax rate (0.2) and the state tax rate (0.0314)

Using these variables, add a method to the init method that will deduct BOTH federal and state taxes from the employee salary.

Using proper concatenation, output both the first employee's salary AND what the employee's take home pay will be after taxes are deducted.

Do the same for the second employee.

This is the code that we have:

```<code>class Employee:

  fed_tax = float(.2)
  state_tax = float(.0314)

  def __init__(self, name, salary):
    self.name = name
    self.salary = salary

  def apply_taxes(self):
    self.salary = int(float(self.salary - ((self.salary * float(self.fed_tax)) + (self.salary * float(self.state_tax)))))

emp_1 = Employee("Isaac Soiffer", 50000)
emp_2 = Employee("Jack Fuller", 45000)

print("The employee, " + emp_1.name + ", salary is $" + str(emp_1.salary) + ".")
print("Employee " + emp_1.name + " will take home $" + str(emp_1.salary) + ", after taxes.")

print("The employee, " + emp_2.name + ", salary is $" + str(emp_2.salary) + ".")
print("Employee " + emp_2.name + " will take home $" + str(emp_2.salary) + ", after taxes.")
</code>```

答:
you are not calling apply taxes anywhere:
Try something like:

```<code>class Employee:

   fed_tax = 0.2
   state_tax = 0.0314

   def __init__(self, name, salary):
       self.name = name
       self.salary = salary
       self.post_taxed_salary = self.apply_taxes()

   def apply_taxes(self):
       return int(float(self.salary - ((self.salary * float(self.fed_tax)) + (self.salary * float(self.state_tax)))))

emp_1 = Employee("Isaac Soiffer", 50000)
emp_2 = Employee("Jack Fuller", 45000)
print('employee {} has salary of {} and after taxes {}'.format(emp_1.name, emp_1.salary, emp_1.post_taxed_salary))
</code>```

Returns: employee Isaac Soiffer has salary of 50000 and after taxes 38430

On a note, because saalary is an attribute, you can make post_taxed_salary a property, e.g.

```<code>class Employee:

   fed_tax = 0.2
   state_tax = 0.0314

   def __init__(self, name, salary):
       self.name = name
       self.salary = salary

   @property
   def post_taxed_salary(self):
       return int(float(self.salary - ((self.salary * float(self.fed_tax)) + (self.salary * float(self.state_tax)))))
</code>```

Should work as well

Body:
Assignment and code below...

I am assisting my son with his homework. I know coding, but not Python. He has gotten this far and has asked me to jump in to assist and I am stumped. I believe that the equation for the total take-home salary is too long, but I am not sure what to do to help. The code works as is, but when we try to switch the "...will take home $" + str(emp_1.salary) + ", after taxes." with "...will take home $" + str(emp_1.apply_taxes()) + ", after taxes." for both emp_1 and emp_2 we get an error that apply_taxes is not defined. all we need to do is get the equation to work and we will be good. Any suggestions would be greatly appreciated!

Thank you!!

This is the assignment:

Include to class variables that will account for the federal tax rate (0.2) and the state tax rate (0.0314)

Using these variables, add a method to the init method that will deduct BOTH federal and state taxes from the employee salary.

Using proper concatenation, output both the first employee's salary AND what the employee's take home pay will be after taxes are deducted.

Do the same for the second employee.

This is the code that we have:

class Employee:

  fed_tax = float(.2)
  state_tax = float(.0314)

  def __init__(self, name, salary):
    self.name = name
    self.salary = salary

  def apply_taxes(self):
    self.salary = int(float(self.salary - ((self.salary * float(self.fed_tax)) + (self.salary * float(self.state_tax)))))

emp_1 = Employee("Isaac Soiffer", 50000)
emp_2 = Employee("Jack Fuller", 45000)

print("The employee, " + emp_1.name + ", salary is $" + str(emp_1.salary) + ".")
print("Employee " + emp_1.name + " will take home $" + str(emp_1.salary) + ", after taxes.")

print("The employee, " + emp_2.name + ", salary is $" + str(emp_2.salary) + ".")
print("Employee " + emp_2.name + " will take home $" + str(emp_2.salary) + ", after taxes.")

Body:
you are not calling apply taxes anywhere:
Try something like:

class Employee:

   fed_tax = 0.2
   state_tax = 0.0314

   def __init__(self, name, salary):
       self.name = name
       self.salary = salary
       self.post_taxed_salary = self.apply_taxes()

   def apply_taxes(self):
       return int(float(self.salary - ((self.salary * float(self.fed_tax)) + (self.salary * float(self.state_tax)))))

emp_1 = Employee("Isaac Soiffer", 50000)
emp_2 = Employee("Jack Fuller", 45000)
print('employee {} has salary of {} and after taxes {}'.format(emp_1.name, emp_1.salary, emp_1.post_taxed_salary))

Returns: employee Isaac Soiffer has salary of 50000 and after taxes 38430

On a note, because saalary is an attribute, you can make post_taxed_salary a property, e.g.

class Employee:

   fed_tax = 0.2
   state_tax = 0.0314

   def __init__(self, name, salary):
       self.name = name
       self.salary = salary

   @property
   def post_taxed_salary(self):
       return int(float(self.salary - ((self.salary * float(self.fed_tax)) + (self.salary * float(self.state_tax)))))

Should work as well


问:
Is there a way to track time user spent on page using Google analytics (Angular)
I have an Angular application and I want to track time user spent on each page using google analytics. What is the best way to do it? (Or maybe there are alternatives to Google Analytics that have this functionality out of the box?)</p>

答:
As Angular is an SPA, you need to set the page manually on Google Analytics. In order to do that you have set a listener on route changes.

Something similar to this is required:

```<code> private subscribeToRouteChanges(): void {
    this.router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe((event: NavigationEnd) => this.sendPageDataToGoogleAnalytics(event.urlAfterRedirects));
  }

  public sendPageDataToGoogleAnalytics(url: string): void {
   //need a title for each page which will be shown at GA dashboards
   //you can setup your own service or static function to return a title for each route registered
    const pageTitle = this.pageTitleService.getPageTitle(url);
    if (pageTitle) {
      (window as any).ga('set', 'page', url);
      (window as any).ga('set', 'title', pageTitle);
      (window as any).ga('send', 'pageview');
    }
  }
</code>```

Body:
As Angular is an SPA, you need to set the page manually on Google Analytics. In order to do that you have set a listener on route changes.

Something similar to this is required:

 private subscribeToRouteChanges(): void {
    this.router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe((event: NavigationEnd) => this.sendPageDataToGoogleAnalytics(event.urlAfterRedirects));
  }

  public sendPageDataToGoogleAnalytics(url: string): void {
   //need a title for each page which will be shown at GA dashboards
   //you can setup your own service or static function to return a title for each route registered
    const pageTitle = this.pageTitleService.getPageTitle(url);
    if (pageTitle) {
      (window as any).ga('set', 'page', url);
      (window as any).ga('set', 'title', pageTitle);
      (window as any).ga('send', 'pageview');
    }
  }


问:
How to pivot if a column has null
```<code>source Type
a       null
a       aa
a       bb
a       cc

source null aa bb cc
a.       1.  1 1 1
</code>```

How to stop pivoting.a column which contains null

答:
Filter the null values before pivot

Check below code.

```<code>scala> df.show(false)
+------+----+
|source|type|
+------+----+
|a     |null|
|a     |aa  |
|a     |bb  |
|a     |cc  |
+------+----+

scala> df
         .filter($"type".isNotNull)
         .groupBy($"source")
         .pivot($"type")
         .agg(count($"type"))
         .show(false)

+------+---+---+---+
|source|aa |bb |cc |
+------+---+---+---+
|a     |1  |1  |1  |
+------+---+---+---+

</code>```

Title: How to pivot if a column has null

Body:
source Type
a       null
a       aa
a       bb
a       cc

source null aa bb cc
a.       1.  1 1 1

How to stop pivoting.a column which contains null

Body:
Filter the null values before pivot

Check below code.

scala> df.show(false)
+------+----+
|source|type|
+------+----+
|a     |null|
|a     |aa  |
|a     |bb  |
|a     |cc  |
+------+----+

scala> df
         .filter($"type".isNotNull)
         .groupBy($"source")
         .pivot($"type")
         .agg(count($"type"))
         .show(false)

+------+---+---+---+
|source|aa |bb |cc |
+------+---+---+---+
|a     |1  |1  |1  |
+------+---+---+---+


问:
How can I make a tkinter text widget unselectable?
I want to make my tkinter Text to be only an output and not an input. Through some research I've found that text.config(state="disabled") disables user input, but it still allows for selecting text, which I do not want.

How can I get my Text widget to be unselectable and unwritable?

答:
A read-only, unselectable text widget.

```<code>class Textarea(tkinter.Text):
  def __init__(self, master, **kw):
    super().__init__(master, **kw)
    # disable text alteration
    self.configure(state="disabled")
    # untag any selection from beginning to end
    def unselect(event):
      self.tag_remove("sel", "1.0", "end")
    # catch different ways selections could be made and unselect before copying or cutting
    good = ["<ButtonRelease-1>", "<Leave>", "<Control-c>", "<Control-C>", "<Control-x>", "<Control-X>"]
    better = good + ["<Shift-Left>", "<Shift-Up>", "<Shift-Right>", "<Shift-Down>", "<Shift-Home>", "<Shift-End>", "<Shift-Next>", "<Shift-Prior>"]
    excessive = better + ["<Shift-KP_1>", "<Shift-KP_2>", "<Shift-KP_3>", "<Shift-KP_4>", "<Shift-KP_6>", "<Shift-KP_7>", "<Shift-KP_8>", "<Shift-KP_9>"]
    for sequence in better:
      self.bind(sequence, unselect, add="+")
    # remove the appearance of selection
    self.configure(selectforeground=self.cget("foreground"), selectbackground=self.cget("background"))
    # disallow export of selection in case anything gets through
    self.configure(exportselection=False)
</code>```

Tested on python 3.8.2

Body:
A read-only, unselectable text widget.

class Textarea(tkinter.Text):
  def __init__(self, master, **kw):
    super().__init__(master, **kw)
    # disable text alteration
    self.configure(state="disabled")
    # untag any selection from beginning to end
    def unselect(event):
      self.tag_remove("sel", "1.0", "end")
    # catch different ways selections could be made and unselect before copying or cutting
    good = ["<ButtonRelease-1>", "<Leave>", "<Control-c>", "<Control-C>", "<Control-x>", "<Control-X>"]
    better = good + ["<Shift-Left>", "<Shift-Up>", "<Shift-Right>", "<Shift-Down>", "<Shift-Home>", "<Shift-End>", "<Shift-Next>", "<Shift-Prior>"]
    excessive = better + ["<Shift-KP_1>", "<Shift-KP_2>", "<Shift-KP_3>", "<Shift-KP_4>", "<Shift-KP_6>", "<Shift-KP_7>", "<Shift-KP_8>", "<Shift-KP_9>"]
    for sequence in better:
      self.bind(sequence, unselect, add="+")
    # remove the appearance of selection
    self.configure(selectforeground=self.cget("foreground"), selectbackground=self.cget("background"))
    # disallow export of selection in case anything gets through
    self.configure(exportselection=False)

Tested on python 3.8.2


问:
How to live-decrypt WPA/WPA2-PSK using tcpdump?
Here my Problem:

If I am connected to a network (so I know the WPA/WPA2-PSK), I´d like to be able to decrypt the traffic I capture from other devices in the network.
(If WEP is used, tcpdump does this automatically).

As far as I know, WPA uses something like a session key for each client in the WiFi - but I know this is possible - so I´m wondering HOW to do this. (If this is not possibile with tcpdump, how to do this "by hand"?)

Thanks for any help!

答: TamoSoft has CommView for WiFi product which does what you need. As far as I know, decrypting WPA is a tricky task, and this is what they charge for. </p>


问:
Update state from child component and return component
I'm trying to update a parent component from its child and return a component
here is what I'm doing:

```<code>const Template = () => {
    const [someVar, setSomeVar] = useState({a:"a"});
    const components = [];
    components.push(getComp(someVar, (vari) =>setSomeVar(vari), 1));
    return <div>{components}</div>;
};

const getComp = (someVar, updateVar, i) => {
    const someOtherVar = {...someVar, i: i};
    updateVar(someOtherVar);
    return <Typography key={i}> i </Typography>
};

export default Template;
</code>```

but I'm getting the following error:

```<code>Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
</code>```

I understand it's something to do with my setSomevar, but I'm boxing it, so it won't be triggered.

any thoughts?

答:
You are executing the Template() function in an infinite loop. Using the react hook the component is rerendered each time you call setSomeVar, which you do in the getComp  function automatically. Try adding your component on an event, like a clickEvent.

```<code>const Template = () => {
    const [components, addComponent] = useState([]);
    const click = (event) =>{
       const component = (<p>I'm a component!!</p>);
        addComponent([...components, component])
    }

    return <div><button onClick={click}>click me</button>
    {components.map(c => return c; )}</div>;
    };

export default Template;
</code>```

Body:
I'm trying to update a parent component from its child and return a component
here is what I'm doing:

const Template = () => {
    const [someVar, setSomeVar] = useState({a:"a"});
    const components = [];
    components.push(getComp(someVar, (vari) =>setSomeVar(vari), 1));
    return
{components}
;
};

const getComp = (someVar, updateVar, i) => {
    const someOtherVar = {...someVar, i: i};
    updateVar(someOtherVar);
    return <Typography key={i}> i </Typography>
};

export default Template;

but I'm getting the following error:

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

I understand it's something to do with my setSomevar, but I'm boxing it, so it won't be triggered.

any thoughts?

Body:
You are executing the Template() function in an infinite loop. Using the react hook the component is rerendered each time you call setSomeVar, which you do in the getComp  function automatically. Try adding your component on an event, like a clickEvent.

const Template = () => {
    const [components, addComponent] = useState([]);
    const click = (event) =>{
       const component = (<p>I'm a component!!</p>);
        addComponent([...components, component])
    }

    return <div><button onClick={click}>click me</button>
    {components.map(c => return c; )}</div>;
    };

export default Template;


问:
Document image dewarping script on Python 3.5
I'm trying to run the following script on windows: https://github.com/mzucker/page_dewarp.

It requires scipy, numpy, pillow and OpenCV.

I have no experience with python, I have downloaded WinPython (http://winpython.github.io/), which includes scipy, numpy and pillow and also installed OpenCV 3.2 for Python 3.5 following the instructions found here: https://pythonarena.wordpress.com/2016/03/07/scientific-python-on-windows/.

Now I'm trying to run the script using the command page_dewarp.py IMAGE1, as indicated by the developer, but it results in a syntax error.

Could you explain if there is something missing or wrong and, eventually, how to do to make it work properly?

Thank you!

答:
Try putting braces around the content of print statements as:

```<code>print 'abc'
</code>```

to

```<code>print('abc')
</code>```

This should solve the syntax problem. You might need to install scipy. This can be done using

```<code>pip install scipy
</code>```

Body:
Try putting braces around the content of print statements as:

print 'abc'

to

print('abc')

This should solve the syntax problem. You might need to install scipy. This can be done using

pip install scipy


问:
Can someone explain the parameter void(*pfn)(void*)?
I've come across this piece of code

```<code>inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
</code>```

I don't understand this part

```<code>void(*pfn)(void*)
</code>```

Can someone tell me what it means/is?

This is btw not listed in books for beginners so if you want to mention to read books, it's not there.

Afaik, void is datatype of a function meaning it will not return anything, however that part there...void is used on a pointer?

答:
The declaration of CreateThread says that the first parameter pfn is a pointer to a callback function that will be used by CreateThread. The callback pfn is your own function that CreateThread will call so that you can execute your code in a new thread.

You define a function

```<code>void MyThreadCallback(void* data)
{
    MyData myData = reinterpret_cast<MyData*>(data);
    ...
}
</code>```

and pass it to CreateThread as

```<code>MyData* myData = new MyData();
CreateThread(MyThreadCallback, myData, ... );
</code>```

so that CreateThread can call it in the context of the new thread.

Body:
I've come across this piece of code

inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)

I don't understand this part

void(*pfn)(void*)

Can someone tell me what it means/is?

This is btw not listed in books for beginners so if you want to mention to read books, it's not there.

Afaik, void is datatype of a function meaning it will not return anything, however that part there...void is used on a pointer?

Body:
The declaration of CreateThread says that the first parameter pfn is a pointer to a callback function that will be used by CreateThread. The callback pfn is your own function that CreateThread will call so that you can execute your code in a new thread.

You define a function

void MyThreadCallback(void* data)
{
    MyData myData = reinterpret_cast<MyData*>(data);
    ...
}

and pass it to CreateThread as

MyData* myData = new MyData();
CreateThread(MyThreadCallback, myData, ... );

so that CreateThread can call it in the context of the new thread.


问:
Check if autofilter range is completely hidden
In my Excel sheet I have a filter in Row 28 for all other rows below.

Now I want to check if all rows are hidden below Row 28. Therefore, I went with the solution from this question here:

```<code>Sub Check_filter_visibility()
If Sheet1.Range("A28:A10000").SpecialCells(xlCellTypeVisible).Count > 1 Then
Sheet1.Range("A1").Value = 1
Else
Sheet1.Range("A1").Value = 2
End If
End Sub
</code>```

All this works fine.

Now, instead of the defined range Sheet1.Range("A28:A10000") I want to include the entire AutoFilter range.

Therefore I tried to go with this function:

```<code>Sub Check_filter_visibility()
If AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Count > 1 Then
Sheet1.Range("A1").Value = 1
Else
Sheet1.Range("A1").Value = 2
End If
End Sub
</code>```

However, with this solution I get runtime error 424.

Is there any other way to make the check if all cells in the AutoFilter are hidden independent from a defined range?

答:
As already described in the comments the solution is:</p>

```<code>Sub Check_filter_visibility()
If Sheet1.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Count > 1 Then
Sheet1.Range("A1").Value = 1
Else
Sheet1.Range("A1").Value = 2
End If
End Sub
</code>```

Body:
In my Excel sheet I have a filter in Row 28 for all other rows below.

Now I want to check if all rows are hidden below Row 28. Therefore, I went with the solution from this question here:

Sub Check_filter_visibility()
If Sheet1.Range("A28:A10000").SpecialCells(xlCellTypeVisible).Count > 1 Then
Sheet1.Range("A1").Value = 1
Else
Sheet1.Range("A1").Value = 2
End If
End Sub

All this works fine.

Now, instead of the defined range Sheet1.Range("A28:A10000") I want to include the entire AutoFilter range.

Therefore I tried to go with this function:

Sub Check_filter_visibility()
If AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Count > 1 Then
Sheet1.Range("A1").Value = 1
Else
Sheet1.Range("A1").Value = 2
End If
End Sub

However, with this solution I get runtime error 424.

Is there any other way to make the check if all cells in the AutoFilter are hidden independent from a defined range?

Body:
As already described in the comments the solution is:

Sub Check_filter_visibility()
If Sheet1.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Count > 1 Then
Sheet1.Range("A1").Value = 1
Else
Sheet1.Range("A1").Value = 2
End If
End Sub


问:
Calling Python in Java?
I am wondering if it is possible to call Python functions from Java code using Jython, or is it only for calling Java code from Python?</p>

答: This gives a pretty good overview over the current options. Some of which are named in other answers. Jython is not usable until they decide to not implement Python 3. Many of the other projects are coming from the python side and want to access java. But there are a few options still, to name something which has not been named yet: gRPC</p>

Title: Calling Python in Java?


问:
Using enums as status returned status indicators in C#
Just wondering what the general consensus was about returning enums from methods indicating the status. The notion of returning codes (ints) is pretty innate in oldschool systems programming (C) but I am wondering if the methodology for indicating the status has changed.

thanks

Edit: I am aware that enums are basically int values. I'm inquiring about the sheer practice of having methods start throwing around status codes (be them enums or ints) to indicate statuses altogether. It seems like a good practice but I was wondering if there is any negative feelings about the idea.

I would always choose an enum over an int return for a status code.

答:
As an enum is basicly just an int, it'll work just fine.  You get the added bonus of intellisense.

That is assuming you want the status of your function call.  If you are looking for a system/overall status you may want to expose that as an event(s).

OwnerDisplayName: Chance

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Chance

OwnerDisplayName: Boo


问:
Why did my countdown clock stop counting?
Let me preface this with I'm pretty clueless about JavaScript..

So for example, I just want to link to a countdown that will count down until when a particular server is open.

I used https://www.w3schools.com/howto/howto_js_countdown.asp to make the countdown and modified it so that it uses the server time instead of the client time.

```<code>var serverNow =  new Date().toLocaleString("en-US", {timeZone: "Asia/Seoul"});

var tomorrowKR = new Date(serverNow);
tomorrowKR.setDate(tomorrowKR.getDate()+1)
tomorrowKR.setHours(18,0,0,0)

var countDownDateKR = tomorrowKR.getTime();
var x = setInterval(function() {
  var now = new Date(serverNow).getTime();
  var distanceKR = countDownDateKR - now;
  var hoursKR = Math.floor((distanceKR % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutesKR = Math.floor((distanceKR % (1000 * 60 * 60)) / (1000 * 60));
  var secondsKR = Math.floor((distanceKR % (1000 * 60)) / 1000);

  document.getElementById("ASIAServer").innerHTML = "The KR Server is currently CLOSED, but will open again in " + hoursKR + "h " + minutesKR + "m " + secondsKR + "s (6 PM KST)" ;
  }, 1000);
}

</code>```

The error seems to be in the line

```<code>var now = new Date(serverNow).getTime();
</code>```

if I remove the "serverNow" and just let it roll as the client time, it will count down.
Changing it to the serverNow, it displays the correct countdown time, but the actual countdown action stops.

What's going on with this?

答:
When you run new Date(serverNow) inside your setInterval, the value does not update because serverNow does not change. serverNow is a fixed string that keeps whatever value it had when the page was first loaded. For now to update with every interval, you need to get the latest server time:

```<code>now = new Date(new Date().toLocaleString("en-US", {timeZone: "Asia/Seoul"})).getTime();
</code>```

Definitely not the prettiest code in the world. You should know that working with dates and timezones in vanilla Javascript is always messy. A lot of people use Moment.js to save significant headache.

Body:
Let me preface this with I'm pretty clueless about JavaScript..

So for example, I just want to link to a countdown that will count down until when a particular server is open.

I used https://www.w3schools.com/howto/howto_js_countdown.asp to make the countdown and modified it so that it uses the server time instead of the client time.

var serverNow =  new Date().toLocaleString("en-US", {timeZone: "Asia/Seoul"});

var tomorrowKR = new Date(serverNow);
tomorrowKR.setDate(tomorrowKR.getDate()+1)
tomorrowKR.setHours(18,0,0,0)

var countDownDateKR = tomorrowKR.getTime();
var x = setInterval(function() {
  var now = new Date(serverNow).getTime();
  var distanceKR = countDownDateKR - now;
  var hoursKR = Math.floor((distanceKR % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutesKR = Math.floor((distanceKR % (1000 * 60 * 60)) / (1000 * 60));
  var secondsKR = Math.floor((distanceKR % (1000 * 60)) / 1000);

  document.getElementById("ASIAServer").innerHTML = "The KR Server is currently CLOSED, but will open again in " + hoursKR + "h " + minutesKR + "m " + secondsKR + "s (6 PM KST)" ;
  }, 1000);
}

The error seems to be in the line

var now = new Date(serverNow).getTime();

if I remove the "serverNow" and just let it roll as the client time, it will count down.
Changing it to the serverNow, it displays the correct countdown time, but the actual countdown action stops.

What's going on with this?

Body:
When you run new Date(serverNow) inside your setInterval, the value does not update because serverNow does not change. serverNow is a fixed string that keeps whatever value it had when the page was first loaded. For now to update with every interval, you need to get the latest server time:

now = new Date(new Date().toLocaleString("en-US", {timeZone: "Asia/Seoul"})).getTime();

Definitely not the prettiest code in the world. You should know that working with dates and timezones in vanilla Javascript is always messy. A lot of people use Moment.js to save significant headache.


问:
React.js: Set time limit for axios to wait for a response
I want to set a time limit for an axios request to wait for a response

For example, I fired a request from the client then I would like to set the system to wait for only 8 seconds then show a request time out

Kindly see my axios request below

```<code>executeJwtAuthenticationService(username, password) {
    return axios.post(`${API_URL_LOCAL}`, {
      username,
      password,
    });
  }
</code>```

How would I pattern it similar to this?

```<code>axios({
  method: 'post',
  url: '/user',
  timeout: 8000, // Let's say you want to wait at least 8 seconds
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
})
</code>```

答:
If you trying to implement your axios.post request with the inline version, so you just have to know, it will take configs as a separate object.

So your final code should be something like this:

axios.post(`${API_URL_LOCAL}`, {
  username,
  password,
}, {
  timeout: 8000
});
```

NOTE: For more information you can read this.

Body:
I want to set a time limit for an axios request to wait for a response

For example, I fired a request from the client then I would like to set the system to wait for only 8 seconds then show a request time out

Kindly see my axios request below

executeJwtAuthenticationService(username, password) {
    return axios.post(`${API_URL_LOCAL}`, {
      username,
      password,
    });
  }

How would I pattern it similar to this?

axios({
  method: 'post',
  url: '/user',
  timeout: 8000, // Let's say you want to wait at least 8 seconds
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
})

Body:
If you trying to implement your axios.post request with the inline version, so you just have to know, it will take configs as a separate object.

So your final code should be something like this:

axios.post(`${API_URL_LOCAL}`, {
  username,
  password,
}, {
  timeout: 8000
});

NOTE: For more information you can read this.


问:
Python function to return concatenated string from a list, where the length of the string is more than 2 characters
Newbie learning Python here, be nice!!

I have an assignment as part of my course to write simple programs, but there is one I am struggling with. For all elements in a list that have more than 2 characters, should be concatenated. The code itself is working, but it's returning the first string in the list as well as the other strings which are more than 2 characters. It's because of the way I have written the code I know, but I can't figure out a way to exclude the first string. Iteration should be utilised.

My code:

```<code>def concatenate(strings):
    start = strings[0]
    for string in strings:
        if len(string) > 2:
            start += string
    return start

print(concatenate(["a", "de", "fg", "hijk", "abc"]))
</code>```

It's correctly concatenating hijkabc, but it's also including the "a" at the beginning, so the result I'm actually getting is ahijkabc.

What do I need to do?

Thanks!

答:
Initialize the start variable with empty string.

```<code>def concatenate(strings):
    start = ''
    for string in strings:
        if len(string) > 2:
            start += string
    return start
</code>```

Body:
Newbie learning Python here, be nice!!

I have an assignment as part of my course to write simple programs, but there is one I am struggling with. For all elements in a list that have more than 2 characters, should be concatenated. The code itself is working, but it's returning the first string in the list as well as the other strings which are more than 2 characters. It's because of the way I have written the code I know, but I can't figure out a way to exclude the first string. Iteration should be utilised.

My code:

def concatenate(strings):
    start = strings[0]
    for string in strings:
        if len(string) > 2:
            start += string
    return start

print(concatenate(["a", "de", "fg", "hijk", "abc"]))

It's correctly concatenating hijkabc, but it's also including the "a" at the beginning, so the result I'm actually getting is ahijkabc.

What do I need to do?

Thanks!

Body:
Initialize the start variable with empty string.

def concatenate(strings):
    start = ''
    for string in strings:
        if len(string) > 2:
            start += string
    return start


问:
Can't run any container with an entrypoint script
I work with docker on a daily basis, but this morning, when I tried to launch some containers, it failed for every of my containers with an entrypoint script:

```<code>$ docker run postgres:11
bash: /usr/local/bin/docker-entrypoint.sh: Permission denied

$ docker run mysql:5
/bin/bash: /usr/local/bin/docker-entrypoint.sh: Permission denied

$ docker run php:7.3-apache
/bin/sh: 0: Can't open /usr/local/bin/docker-php-entrypoint
</code>```

I managed to docker run hello-world without errors.

What happens? I don't think I have changed anything important on my computer since the last time it worked... I am on Ubuntu 20.04.
Thanks for your help.

UPDATE

I still don't know what was going on. I managed to make it work again by removing docker-ce and re-installing it:

```<code>sudo apt-get remove docker-ce
sudo apt install docker-ce
docker run postgres:11
  ==> ok, worked!
</code>```

But, each time I shut down my laptop and then turn it on, I have the same problem again, docker doesn't run any container with an entrypoint.

Any ideas?

答:
Well, following the idea of @PieterBeyens, I checked apparmor, and indeed,it was denying me read access to /usr/local/bin/docker-entrypoint.sh. It also appeared that I had a mixed snap/apt installation of docker and docker-compose. It was a mess.

So, for future readers, what I did and finally worked (you may need to adapt, but you have the general idea):

```<code># Remove the docker and docker-compose snaps
sudo snap remove docker-compose
sudo snap remove docker
# Remove the packages via apt
sudo apt-get purge -y  docker-ce docker-ce-cli containerd.io
# Remove the apparmor profiles (snap ones for docker)
sudo aa-remove-unknown
# Reinstall via apt
sudo apt-get install docker-ce=5:19.03.8~3-0~ubuntu-bionic docker-ce-cli=5:19.03.8~3-0~ubuntu-bionic containerd.io
</code>```

And I also resinstalled docker-compose via curl.

Body:
I work with docker on a daily basis, but this morning, when I tried to launch some containers, it failed for every of my containers with an entrypoint script:

$ docker run postgres:11
bash: /usr/local/bin/docker-entrypoint.sh: Permission denied

$ docker run mysql:5
/bin/bash: /usr/local/bin/docker-entrypoint.sh: Permission denied

$ docker run php:7.3-apache
/bin/sh: 0: Can't open /usr/local/bin/docker-php-entrypoint

I managed to docker run hello-world without errors.

What happens? I don't think I have changed anything important on my computer since the last time it worked... I am on Ubuntu 20.04.
Thanks for your help.

UPDATE

I still don't know what was going on. I managed to make it work again by removing docker-ce and re-installing it:

sudo apt-get remove docker-ce
sudo apt install docker-ce
docker run postgres:11
  ==> ok, worked!

But, each time I shut down my laptop and then turn it on, I have the same problem again, docker doesn't run any container with an entrypoint.

Any ideas?

Body:
Well, following the idea of @PieterBeyens, I checked apparmor, and indeed,it was denying me read access to /usr/local/bin/docker-entrypoint.sh. It also appeared that I had a mixed snap/apt installation of docker and docker-compose. It was a mess.

So, for future readers, what I did and finally worked (you may need to adapt, but you have the general idea):

# Remove the docker and docker-compose snaps
sudo snap remove docker-compose
sudo snap remove docker
# Remove the packages via apt
sudo apt-get purge -y  docker-ce docker-ce-cli containerd.io
# Remove the apparmor profiles (snap ones for docker)
sudo aa-remove-unknown
# Reinstall via apt
sudo apt-get install docker-ce=5:19.03.8~3-0~ubuntu-bionic docker-ce-cli=5:19.03.8~3-0~ubuntu-bionic containerd.io

And I also resinstalled docker-compose via curl.


问:
How to prevent duplicate form submission in ASP.NET MVC 3?
I have a razor view that renders a html form and it posts to the server.
If the form values are right then it gets saved to database.
After insertion, I redirect to another view where user can make further changes.

Right now the user can hit browser back button and resubmit the form to create another record in db.

How do I prevent duplicate submission in my MVC app?

答: Create a cookie to represent that particular page when it succeeds. If it is replayed with the cookie (which the browser would now send over with every request) you know not to allow the new attempt.</p>


问:
Mongoose query array inside array of objects
So I'm using node v10, mongodb v4.2 and mongoose v5.9.

I have a UsersSchema:

const UsersSchema = new Schema({
    name: {
        type: String,
        required: true,
    },
    email: {
        type: String,
        required: true,
        lowercase: true
    },
 ...
```

<p>A CompaniesSchema:</p>

<pre class="lang-js prettyprint-override"><code>const CompaniesSchema = new Schema({
    name: {
        type: String,
        required: true,
    },
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Users',
        required: true
    },
    branches: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Branches'
    }]
    ...

})
</code>```

And a BranchesSchema:

const BranchesSchema = new Schema({
    name: {
        type: String,
        required: true,
    },
    company: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Companies',
        required: true
    }
    users: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Users',
    }]
})
```

<p>I need to query all the companies the user own, OR the companies he's been added to a branch.
I tried to do like:</p>

<pre class="lang-js prettyprint-override"><code>const id = 'MY_USER_ID'
const queryCompanies = await Companies.find({
  $or: [{ user: id }, { "branches.users": [id] }],
});
</code>```

The { user: id } part works. I'm having trouble trying to query the companies he's in based on the branches he's in. Is that even possible?

答:
With the current schema setup you have 2 options:

Split into 2 calls:

```<code>const id = 'MY_USER_ID';
let companyIds = await Branches.distinct("company", {users: id});
const queryCompanies = await Companies.find({
    $or: [{ user: id }, { _id: {$in: companyIds} }],
});

</code>```

Use $lookup

```<code>const id = 'MY_USER_ID';
const queryCompanies = await Companies.aggregate([
    {
        $lookup: {
            from: "branches",
            let: {companyId: "$_id", userId: id},
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $and: [
                                {
                                    $eq: ["$$companyId", "$company"]
                                },
                                {
                                    $setIsSubset: [["$$userId"], "$users"]
                                }
                            ]
                        }
                    }
                }
            ],
            as: "branches"
        }
    },
    {
        $match: {
            $or: [
                {
                    user: id
                },
                {
                    "branches.0": {$exists: true}
                }
            ]
        }
    }
]);
</code>```

I personally recommend option 1 as Mongo does not like lookuping, especially here where you have to do so on the entire collection.

Body:
So I'm using node v10, mongodb v4.2 and mongoose v5.9.

I have a UsersSchema:

const UsersSchema = new Schema({
    name: {
        type: String,
        required: true,
    },
    email: {
        type: String,
        required: true,
        lowercase: true
    },
 ...

A CompaniesSchema:

const CompaniesSchema = new Schema({
    name: {
        type: String,
        required: true,
    },
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Users',
        required: true
    },
    branches: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Branches'
    }]
    ...

})

And a BranchesSchema:

const BranchesSchema = new Schema({
    name: {
        type: String,
        required: true,
    },
    company: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Companies',
        required: true
    }
    users: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Users',
    }]
})

I need to query all the companies the user own, OR the companies he's been added to a branch.
I tried to do like:

const id = 'MY_USER_ID'
const queryCompanies = await Companies.find({
  $or: [{ user: id }, { "branches.users": [id] }],
});

The { user: id } part works. I'm having trouble trying to query the companies he's in based on the branches he's in. Is that even possible?

Body:
With the current schema setup you have 2 options:

Split into 2 calls:

const id = 'MY_USER_ID';
let companyIds = await Branches.distinct("company", {users: id});
const queryCompanies = await Companies.find({
    $or: [{ user: id }, { _id: {$in: companyIds} }],
});

Use $lookup

const id = 'MY_USER_ID';
const queryCompanies = await Companies.aggregate([
    {
        $lookup: {
            from: "branches",
            let: {companyId: "$_id", userId: id},
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $and: [
                                {
                                    $eq: ["$$companyId", "$company"]
                                },
                                {
                                    $setIsSubset: [["$$userId"], "$users"]
                                }
                            ]
                        }
                    }
                }
            ],
            as: "branches"
        }
    },
    {
        $match: {
            $or: [
                {
                    user: id
                },
                {
                    "branches.0": {$exists: true}
                }
            ]
        }
    }
]);

I personally recommend option 1 as Mongo does not like lookuping, especially here where you have to do so on the entire collection.


问:
Why does yyp not behave according to p's documentation
I was just wondering if someone could explain what goes on behind the scenes w.r.t the behaviour of yyp.

Given some text:

```<code>Text that can be copied
</code>```

typing yyp while the cursor is in the middle of a line, let's say just before can, results in:

```<code>Text that can be copied
Text that can be copied
</code>```

Which, while very useful and logical, is not what p typically does.

As p pastes after the cursor, and my cursor remains before can, I don't feel I would be wrong to expect something like:

```<code>Text that Text that can be copied can be copied
</code>```

While I agree the former is more useful – could someone explain why and how in these instances the default behaviour of p is ignored?

答:
In Vim a yanked text is stored within an internal variable called "a register". However the registers in Vim keep not only the text itself, but also "the type of text" (one of "char", "line" or "block", just like Visual modes).

So yy saves the text "Text that can be copied" with the type of "line". Therefore, the p command respects this and puts it on the line of its own.

You can change this with :call setreg('', @@, 'c') (keeping newline at the end but overwriting internal type) or yanking it with 0y$ etc.

Body:
I was just wondering if someone could explain what goes on behind the scenes w.r.t the behaviour of yyp.

Given some text:

Text that can be copied

typing yyp while the cursor is in the middle of a line, let's say just before can, results in:

Text that can be copied
Text that can be copied

Which, while very useful and logical, is not what p typically does.

As p pastes after the cursor, and my cursor remains before can, I don't feel I would be wrong to expect something like:

Text that Text that can be copied can be copied

While I agree the former is more useful – could someone explain why and how in these instances the default behaviour of p is ignored?


问:
Need to understand the solution to this query
We define an employee's total earnings to be their monthly  worked, and the maximum total earnings to be the maximum total earnings for any employee in the Employee table. Write a query to find the maximum total earnings for all employees as well as the total number of employees who have maximum total earnings. Then print these values as  space-separated integers.
This is link to the question for better understanding https://www.hackerrank.com/challenges/earnings-of-employees/problem

I am a beginner in SQL and couldn't understand the solution which was given

```<code>1.SELECT (months*salary) as earnings,
 2.COUNT(*) FROM Employee
3. GROUP BY earnings
4. ORDER BY earnings DESC
 5.LIMIT 1;
</code>```

I understood the first step where we are giving months*salary an Alias which is earnings
in the 2nd step we are counting the no. of employees from employee table. I didn't understand why we are using group by here, 4th and 5th step is also clear, we used order by clause in order to rank earnings from highest to lowest, and limit 1 will fetch me the highest value. But why GROUP BY?
 Ignore 1,2,3,4,5. These are just numbers I used for better clarity

答:
Step 3: GROUP BY earnings was used to GROUP TOGETHER same value earnings. If you have, for example, earnings of $3,000, and there were 3 of them, they will be grouped together. GROUP BY is also required in combination with the aggregate function COUNT(*). Otherwise, COUNT(*) will not work and return an error.

Step 4: ORDER BY earnings DESC was used to order the GROUPED EARNINGS in DESCENDING order. Meaning, from HIGHEST EARNINGS down to the LOWEST EARNINGS.

Step 5: LIMIT 1 limits the returned row count to only 1.

Hope this helps! :)

Body:
We define an employee's total earnings to be their monthly  worked, and the maximum total earnings to be the maximum total earnings for any employee in the Employee table. Write a query to find the maximum total earnings for all employees as well as the total number of employees who have maximum total earnings. Then print these values as  space-separated integers.
This is link to the question for better understanding https://www.hackerrank.com/challenges/earnings-of-employees/problem

I am a beginner in SQL and couldn't understand the solution which was given

1.SELECT (months*salary) as earnings,
 2.COUNT(*) FROM Employee
3. GROUP BY earnings
4. ORDER BY earnings DESC
 5.LIMIT 1;

I understood the first step where we are giving months*salary an Alias which is earnings
in the 2nd step we are counting the no. of employees from employee table. I didn't understand why we are using group by here, 4th and 5th step is also clear, we used order by clause in order to rank earnings from highest to lowest, and limit 1 will fetch me the highest value. But why GROUP BY?
 Ignore 1,2,3,4,5. These are just numbers I used for better clarity


问:
How to compare time after date?
So I am building a service for selling theatre tickets, when someone wants to buy a ticket the customer will see a list of all available shows.

An available show is defined as follows:

The show is not sold out

The date has not been passed

The time hase not been passed

In the backend there is a query that looks like this to filter only the upcomming shows

```<code>SELECT *
FROM shows
WHERE CURRENT_DATE() <= show.date
</code>```

This query returns the shows of today and the upcomming shows, but it does not filter the shows of today where the start time has been passed. So a customer is still able to buy tickets from a show that has allready started.

I.e: Today is 29th may 2020 and the current time is 21:00:00 the show we are looking at is today and starts at 20:00:00. In the current system it is still possible to buy tickets for this show, but the show allready has started.

Queries like this won't work:

```<code>SELECT *
FROM shows
WHERE CURRENT_DATE() <= show.date AND CURRENT_TIME() <= show.time

OR

SELECT *
FROM shows
WHERE CURRENT_DATE() <= show.date OR CURRENT_TIME() <= show.time
</code>```

These queries wont fit the criteria above because the first query will not return any  show when the time has passed

And the second query doesn't work because it will also return older shows when the time condition matches.

So does anyone have an idea how to write a query that first selects all the shows where the date mathes the codition and the check if the time matches the condition. With respect to the upcomming show.

答:
What you can do is get the tickets that have validity greater than tomorrow's date separately and get the ones of today that match the time condition. So something like this should work:</p>

```<code>SELECT *
FROM shows
WHERE DateADD(dd,1,CURRENT_DATE()) <= show.date OR (CURRENT_DATE() = show.date AND CURRENT_TIME() <= show.time)
</code>```

Title: How to compare time after date?

Body:
So I am building a service for selling theatre tickets, when someone wants to buy a ticket the customer will see a list of all available shows.

An available show is defined as follows:

The show is not sold out

The date has not been passed

The time hase not been passed

In the backend there is a query that looks like this to filter only the upcomming shows

SELECT *
FROM shows
WHERE CURRENT_DATE() <= show.date

This query returns the shows of today and the upcomming shows, but it does not filter the shows of today where the start time has been passed. So a customer is still able to buy tickets from a show that has allready started.

I.e: Today is 29th may 2020 and the current time is 21:00:00 the show we are looking at is today and starts at 20:00:00. In the current system it is still possible to buy tickets for this show, but the show allready has started.

Queries like this won't work:

SELECT *
FROM shows
WHERE CURRENT_DATE() <= show.date AND CURRENT_TIME() <= show.time

OR

SELECT *
FROM shows
WHERE CURRENT_DATE() <= show.date OR CURRENT_TIME() <= show.time

These queries wont fit the criteria above because the first query will not return any  show when the time has passed

And the second query doesn't work because it will also return older shows when the time condition matches.

So does anyone have an idea how to write a query that first selects all the shows where the date mathes the codition and the check if the time matches the condition. With respect to the upcomming show.

Body:
What you can do is get the tickets that have validity greater than tomorrow's date separately and get the ones of today that match the time condition. So something like this should work:

SELECT *
FROM shows
WHERE DateADD(dd,1,CURRENT_DATE()) <= show.date OR (CURRENT_DATE() = show.date AND CURRENT_TIME() <= show.time)


问:
Scanner object has a class attribute instead of in code initialisation
Today, I have encounter a problem with Scanner object while programming a server/client application. I have solved the problem but I don't understand why my solution solved the problem.

At first, in my application I had some memory leak warning when compiling the project (JAVA 8, eclipse)
 because I was using Scanner to ask input from the user but didn't close it. When I try to close the scanner my other class where throwing exception like java.util.NoSuchElementException. I learned that I had a similar problem to : Cannot use multiple Scanner objects in Java but between classes. When I was closing a scanner in a class the other class (thread) scanner couldn't execute.  (java.util.NoSuchElementException)

The solution I found to solve this problem was to put a Scanner function as a class function member:

```<code>public class ClientThread extends Thread {

    private Scanner scanner;

   /*some code*/

}
</code>```

When doing so I lost my memory leak warning.

Why having the scanner as a class member solved the warning ? Is it because of the class destructor ?

答:
Usually, when you create a Scanner, you need to close it once you no longer need it.

The Scanner class has several, overloaded constructors where each one takes a different type of argument. There is a constructor that takes a File argument. There is a constructor that takes a Path argument. And there is a constructor that takes a InputStream argument. In order for your Java program to accept input from the user, via the computer keyboard, you use the constructor that takes an InputStream like so:

Scanner scanner = new Scanner(System.in);
```

<p>This is because the static member <code>in</code> of class <code>java.lang.System</code> has type <code>InputStream</code>. You should think of <code>System.in</code> as encapsulating the keyboard on your computer. If you close <code>System.in</code>, it's like closing your keyboard and that is something you shouldn't do.</p>

<p>Now the Eclipse IDE is not smart enough to realize that your code is creating a <code>Scanner</code> that essentially encapsulates the computer keyboard (and therefore should not be closed). <em>Eclipse</em> only knows that any <code>Scanner</code> that you create should eventually be closed and since your code does not close the <code>Scanner</code> you created, <em>Eclipse</em> displays a warning that you haven't closed a <code>Scanner</code> that you created. In the displayed warning you are offered three suggestions on how to get rid of the warning. The first two refer to an annotation that you can add, namely</p>

```@SuppressWarnings("resource")
```

The third suggestion requires you to change the Eclipse configuration. You do this by selecting the Preferences item of the Window menu that appears at the top of the Eclipse IDE. In the Preferenes window, select Java > Compiler > Errors/Warnings and change the Resource leak setting to Ignore as shown in the following screen capture:

Note however, that this configuration setting applies to all resources, not just Scanner, so if you open a regular file in your java code and don't close it, Eclipse will not warn you.

Personally, I simply ignore the warning since I know that I should not close a Scanner created with System.in or I add an annotation.

Body:
Today, I have encounter a problem with Scanner object while programming a server/client application. I have solved the problem but I don't understand why my solution solved the problem.

At first, in my application I had some memory leak warning when compiling the project (JAVA 8, eclipse)
 because I was using Scanner to ask input from the user but didn't close it. When I try to close the scanner my other class where throwing exception like java.util.NoSuchElementException. I learned that I had a similar problem to : Cannot use multiple Scanner objects in Java but between classes. When I was closing a scanner in a class the other class (thread) scanner couldn't execute.  (java.util.NoSuchElementException)

The solution I found to solve this problem was to put a Scanner function as a class function member:

public class ClientThread extends Thread {

    private Scanner scanner;

   /*some code*/

}

When doing so I lost my memory leak warning.

Why having the scanner as a class member solved the warning ? Is it because of the class destructor ?

Body:
Usually, when you create a Scanner, you need to close it once you no longer need it.

The Scanner class has several, overloaded constructors where each one takes a different type of argument. There is a constructor that takes a File argument. There is a constructor that takes a Path argument. And there is a constructor that takes a InputStream argument. In order for your Java program to accept input from the user, via the computer keyboard, you use the constructor that takes an InputStream like so:

Scanner scanner = new Scanner(System.in);

This is because the static member in of class java.lang.System has type InputStream. You should think of System.in as encapsulating the keyboard on your computer. If you close System.in, it's like closing your keyboard and that is something you shouldn't do.

Now the Eclipse IDE is not smart enough to realize that your code is creating a Scanner that essentially encapsulates the computer keyboard (and therefore should not be closed). Eclipse only knows that any Scanner that you create should eventually be closed and since your code does not close the Scanner you created, Eclipse displays a warning that you haven't closed a Scanner that you created. In the displayed warning you are offered three suggestions on how to get rid of the warning. The first two refer to an annotation that you can add, namely

@SuppressWarnings("resource")

The third suggestion requires you to change the Eclipse configuration. You do this by selecting the Preferences item of the Window menu that appears at the top of the Eclipse IDE. In the Preferenes window, select Java > Compiler > Errors/Warnings and change the Resource leak setting to Ignore as shown in the following screen capture:

Note however, that this configuration setting applies to all resources, not just Scanner, so if you open a regular file in your java code and don't close it, Eclipse will not warn you.

Personally, I simply ignore the warning since I know that I should not close a Scanner created with System.in or I add an annotation.


问:
Bootstrap 4: fix contents bottom inside container
I have an app wrapped around a
, in which I have an editor and a few buttons, which I always want to be shown at the bottom, something like so:

  // some content....

  // this should be shown always at the bottom!

```

I have tried changing the min-height, and height properties of html, body and container to be 100% and added important to this rules, but that doesnt make my div container stretch any more downwards. When I use the "fixed-bottom" bootstrap class, the #bottom div stretches horizontally over the container boundaries, which makes the layout completely ugly.

any suggestions? :)

答:
If you are using the BS4, then there is lots of classes provided by BS, use those to achieve your output.

I have added some height to row, just to show you desired result, As we will have some content in container then you would not need any height on row.

NOTE: If you do not want to use row, just in case, then use class d-flex on container and rest will remain same.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Button

```

Body:
I have an app wrapped around a
, in which I have an editor and a few buttons, which I always want to be shown at the bottom, something like so:

  // some content....

  // this should be shown always at the bottom!

I have tried changing the min-height, and height properties of html, body and container to be 100% and added important to this rules, but that doesnt make my div container stretch any more downwards. When I use the "fixed-bottom" bootstrap class, the #bottom div stretches horizontally over the container boundaries, which makes the layout completely ugly.

any suggestions? :)

Body:
If you are using the BS4, then there is lots of classes provided by BS, use those to achieve your output.

I have added some height to row, just to show you desired result, As we will have some content in container then you would not need any height on row.

NOTE: If you do not want to use row, just in case, then use class d-flex on container and rest will remain same.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="container">
<div class="row" style="height: 200px;">
<div id="bottom" class="submit-form align-self-end">
    <div id="editor"></div>
    <div class="btn btn-grp" >Button</div>
  </div>
  </div>
  </div>


问:
How do you feed a csv with no headers into a python function - the function is returning 0
I'm trying to get data from a common api in my industry and append all the data to a csv. The below code works until I try to give it a feed csv, which only contains a list of keywords starting at row 1 (no headers).

```<code>   parameters = {"type":"phrase_organic",
                "phrase":"",
                "key": API_KEY,
                "database":"us",
                "export_column": "Dn,Ur,Fk",
                "display_limit":"10"}

keywords = pd.read_csv(r"C:\Users\stff\bulk_kw.csv", header=None)

res_df = None

for i in keywords:
    parameters["phrase"] = i  **#i is 0 for some reason**
    response = requests.get("https://api.semrush.com/", params=parameters)
    print(response.url)
    tmp_df = pd.read_csv(io.StringIO(response.text), sep=";")
    if res_df is None:
        res_df = tmp_df
    else:
        res_df = pd.concat([res_df, tmp_df])

res_df.to_csv(r"C:\Users\stff\SEMrush_call.csv")
</code>```

I've tried a lot of things e.g.

iteritems

iterrows

df.to_list()

keywords.index

unpacking the loop e.g. for i, j in keywords:

None give me what I want, which is a simple list of the values in the csv to loop through. What it's currently giving me is that i is 0.

答:
I made the following change in my for loop and it works:

```<code>for i in keywords.values:
parameters["phrase"] = i  #i is 0 for some reason
response = requests.get("https://api.semrush.com/", params=parameters)
print(response.url)
tmp_df = pd.read_csv(io.StringIO(response.text), sep=";")
if res_df is None:
    res_df = tmp_df
else:
    res_df = pd.concat([res_df, tmp_df])
</code>```

I understand that is because read_csv infers a header, in this case 0.  By adding keywords.values the program only looks at the values in the DataFrame.

Body:
I'm trying to get data from a common api in my industry and append all the data to a csv. The below code works until I try to give it a feed csv, which only contains a list of keywords starting at row 1 (no headers).

   parameters = {"type":"phrase_organic",
                "phrase":"",
                "key": API_KEY,
                "database":"us",
                "export_column": "Dn,Ur,Fk",
                "display_limit":"10"}

keywords = pd.read_csv(r"C:\Users\stff\bulk_kw.csv", header=None)

res_df = None

for i in keywords:
    parameters["phrase"] = i  **#i is 0 for some reason**
    response = requests.get("https://api.semrush.com/", params=parameters)
    print(response.url)
    tmp_df = pd.read_csv(io.StringIO(response.text), sep=";")
    if res_df is None:
        res_df = tmp_df
    else:
        res_df = pd.concat([res_df, tmp_df])

res_df.to_csv(r"C:\Users\stff\SEMrush_call.csv")

I've tried a lot of things e.g.

iteritems

iterrows

df.to_list()

keywords.index

unpacking the loop e.g. for i, j in keywords:

None give me what I want, which is a simple list of the values in the csv to loop through. What it's currently giving me is that i is 0.

Body:
I made the following change in my for loop and it works:

for i in keywords.values:
parameters["phrase"] = i  #i is 0 for some reason
response = requests.get("https://api.semrush.com/", params=parameters)
print(response.url)
tmp_df = pd.read_csv(io.StringIO(response.text), sep=";")
if res_df is None:
    res_df = tmp_df
else:
    res_df = pd.concat([res_df, tmp_df])

I understand that is because read_csv infers a header, in this case 0.  By adding keywords.values the program only looks at the values in the DataFrame.


问:
Silverlight hosted on Linux
I am interested in Silverlight development, but due to expensive Windows Server licenses , I'm strongly considering running SL on Linux. I understand that it's a client-side technology, but I also need to be able to interact with server-side code via web services. I found out that Java (i.e. C# alike) can be used on the server side, but just wondering, would I be able to take advantage of Silverlight (development would start in Silverlight 5) in its entirety if I hosted data-driven SL content on Linux Servers? What would I lose if the back end was not ASP.NET?

Note that I just want to host content on Linux servers. The users would still need Windows or Mac to run SL.

Also I am aware of the Mono team, but as far as I know their implementation is not compatible with the latest version of SL or ASP.NET.

答:
You can host/deploy Silverlight solutions on a Linux/Apache server relatively easily.  See this question for more info.

Consuming a webservice from a SL app shouldn't really matter on what language the service is written in.

Title: Silverlight hosted on Linux


问:
Splitting variable with json leads to Uncaught TypeError
I'm trying to split the content of a variable pickerValue, so that the end result only shows "eosptest2"

The console.log shows pickerValue: i:0#.w|opmain\eosptest2;

The problem is that I get an Uncaught TypeError: Cannot read property '0' of undefined at the following line:

```<code>return json[0].id.split("\\")[1];
</code>```

This is the function:

```<code>function getUserNameFromPeoplePicker(pickerValue, returnType) {

    if (checkNull(pickerValue) == "") {
        return "";
    }

    var json;

    try {
        json = JSON.parse(pickerValue);
    } catch (err) {
        return replaceSubstring(pickerValue.split("\\")[1], ";", "");
    } finally {
        switch (returnType) {
            case "label":
                console.log("json[0].label: " + json[0].label);
                return json[0].label;
                break;

            case "id":
                console.log("pickerValue: " + pickerValue);
                // console.log("Json id split: " + json[0].id.split("\\")[1]);
                return json[0].id.split("\\")[1];

            default:

                return replaceSubstring(pickerValue.split("\\")[1], ";", "");
                //return replaceSubstring(json[0].value.split("\\")[1], ";", "");
                break;
        }
    }
}
</code>```

To test it, I replaced the return statement with return "eosptest2" and it worked fine, but I don't know what exactly needs to be changed.

How can one fix this issue?

答:
You're running your switch cases under the assumption that the json variable is always defined, but if the catch() block ran, that means that your json variable will be undefined:

function example(value) {
    var json;

    try {
        json = JSON.parse(value);
    } catch (err) {
        // couldn't parse the value, so you catch an error
        console.error(err);

        return "catch";
    } finally {
        // an error got caught, this block runs regardless, and now json is undefined
        console.log(`json variable: ${json}`);
    }
}

const result = example(";");
console.log(result);```
</div>
</div>
</p>

<p>What you're also assuming is that if you have a return statement in the <code>catch()</code> block, this will stop the <code>finally</code> block from executing, but that's not true. The <code>finally</code> block will execute its code, and only then will it return some statement.</p>

<p>Also note that if you have a return statement in both the <code>catch</code> and <code>finally</code> block, the <code>finally</code> return statement will take priority over the other:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function example(value) {
    var json;

    try {
        json = JSON.parse(value);
    } catch (err) {
        // couldn't parse the value, so you catch an error
        console.error(err);

        return "catch";
    } finally {
        // but this return statement takes priority over catch
        return "finally";
    }
}

const result = example(";");
console.log(result);</code>```

Body:
I'm trying to split the content of a variable pickerValue, so that the end result only shows "eosptest2"

The console.log shows pickerValue: i:0#.w|opmain\eosptest2;

The problem is that I get an Uncaught TypeError: Cannot read property '0' of undefined at the following line:

return json[0].id.split("\\")[1];

This is the function:

function getUserNameFromPeoplePicker(pickerValue, returnType) {

    if (checkNull(pickerValue) == "") {
        return "";
    }

    var json;

    try {
        json = JSON.parse(pickerValue);
    } catch (err) {
        return replaceSubstring(pickerValue.split("\\")[1], ";", "");
    } finally {
        switch (returnType) {
            case "label":
                console.log("json[0].label: " + json[0].label);
                return json[0].label;
                break;

            case "id":
                console.log("pickerValue: " + pickerValue);
                // console.log("Json id split: " + json[0].id.split("\\")[1]);
                return json[0].id.split("\\")[1];

            default:

                return replaceSubstring(pickerValue.split("\\")[1], ";", "");
                //return replaceSubstring(json[0].value.split("\\")[1], ";", "");
                break;
        }
    }
}

To test it, I replaced the return statement with return "eosptest2" and it worked fine, but I don't know what exactly needs to be changed.

How can one fix this issue?

Body:
You're running your switch cases under the assumption that the json variable is always defined, but if the catch() block ran, that means that your json variable will be undefined:

function example(value) {
    var json;

    try {
        json = JSON.parse(value);
    } catch (err) {
        // couldn't parse the value, so you catch an error
        console.error(err);

        return "catch";
    } finally {
        // an error got caught, this block runs regardless, and now json is undefined
        console.log(`json variable: ${json}`);
    }
}

const result = example(";");
console.log(result);

What you're also assuming is that if you have a return statement in the catch() block, this will stop the finally block from executing, but that's not true. The finally block will execute its code, and only then will it return some statement.

Also note that if you have a return statement in both the catch and finally block, the finally return statement will take priority over the other:

function example(value) {
    var json;

    try {
        json = JSON.parse(value);
    } catch (err) {
        // couldn't parse the value, so you catch an error
        console.error(err);

        return "catch";
    } finally {
        // but this return statement takes priority over catch
        return "finally";
    }
}

const result = example(";");
console.log(result);


答: GROUP BY aggregate your Results. When there are multiple numbers of "earnings" with a same value is just a single one in your table.</p>

Title: Need to understand the solution to this query


问:
How can I get the months between two dates in Oracle SQL
I need to get the numbers of the months between two dates.
For example, between those dates: "03/03/2020 - 06/06/2020"
I need something like "(03,04,05,06)".</p>

答:
Try the DATEDIFF function to achieve this:

```<code>SELECT RIGHT(CONCAT('00',DATEDIFF(MONTH,'03/06/2020','06/06/2020')) ,2)
</code>```

Body:
Try the DATEDIFF function to achieve this:

SELECT RIGHT(CONCAT('00',DATEDIFF(MONTH,'03/06/2020','06/06/2020')) ,2)


问:
Overwrite Paste Event for TextFormField
I have a TextFormField. Usually you can use the selection toolbar to copy/paste/select all and so on using long tap/double tap.

I want to overwrite the Paste Event. It shouldn't simple insert the current clipboard data but open a popup with several options to insert.

Is it possible to catch and overwrite the Paste event in any way? I saw something like handlePaste() for SelectionControls, but I don't know how to add this to my TextFormField.

Thanks in advance!

答:
I search for this problem. I think there is no proper way to solve this problem. I read about the Textfield class and found two solutions for it.

if you check TextField widget you can find that it will use EditableText to show its simple Text input. EditableText has a selectionControls property. this property is used to render the selection toolbar. also, I found that material and Cupertino have different implementation of it.

1st Solution: you can create your own custom TextField that will use EditableText and pass your custom selectionControl to your widget. I think this gonna be a very hard job to do. create your own implementation of the widget, handling animations, and...

2nd Solution: You can simply copy all related files of TextField in a new file and update it as you want. for this solution, I create a repo in GitHub. you can checkout source code to understand how you can show a dialog in the paste option. and this is how the code should work.

note: I just simply update paste function of the Material implementation of selectionControls. if you want you can also update the Cupertino selectionControls too.

note: also I added documents in everywhere I change the code.

Title: Overwrite Paste Event for TextFormField


问:
ASP.NET MVC Application in Sharepoint 2007 virtual directory
I have MOSS 2007 installed at lets say http://localhost:4999/ and I want to have my custom ASP.NET MVC (1.0) application at http://localhost:4999/mvcapp/ - logic dictates that, in IIS, i should create a new application virtual directory under my MOSS site and point it at my custom MVC app.

I've done this and it works for executing my controllers etc, however, none of my /Content content is being returned! All referenced images, javascript and css aren't retrieved.

If I put this app into it's own site, or a virtual application within a non-sharepoint site, this works fine and pulls down the images, js and css as normal.

Note - I'm creating a new application in IIS, not just a virtual directory and I have no requirement for integrating with sharepoint, I just want it to have the same domain and port number.

Any ideas?

Cheers
Tony

** EDIT **
To clarify - the URL's that are being generated aren't the issue - they are correct and are being generated in the same way as they would be if this wasn't hosted under sharepoint. IE: /mvcapp/Content/Scripts/jquery.js etc.

** EDIT 2 **
More clarification - the MVC app has it's own web.config file - but it appears that when using a virtual directory withn a sharepoint site, many of the handler mappings still get pushed up to the child site (Note: This is a virtual directory configured as a seperate application not just a virtual directory).

Whilst I don't want or need SharePoint integration, I need my MVC app to come from the same domain and port to overcome some cross domain issues (a lot of MVC content is iframed into sharepoint in various ways). So sharepoint would be at http://site and my app at http://site/mvc

答:
Look at the following:

Configuring Specific Files and Subdirectories (MSDN)

Disabling Configuration Inheritance For ASP.NET Child Applications (Blog)

HTH


问:
GoogleApiClient is throwing "GoogleApiClient is not connected yet" AFTER onConnected function getting called
So I found something that is not very clear for me about GoogleApiClient.
GoogleApiClient has a function called onConnected which is run when the client is connected (for sure).

I got my own function called: startLocationListening which is eventually getting called on GoogleApiClient's onConnected function.

So my startLocationListening function couldn't run without a GoogleApiClient connection.

Code and log:

```<code>@Override
public void onConnected(Bundle bundle) {
    log("Google_Api_Client:connected.");
    initLocationRequest();
    startLocationListening(); //Exception caught inside this function
}
</code>```

...

```<code>private void startLocationListening() {
    log("Starting_location_listening:now");

    //Exception caught here below:
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
   }
</code>```

The exception is:

```<code>03-30 12:23:28.947: E/AndroidRuntime(4936):     java.lang.IllegalStateException: GoogleApiClient is not connected yet.
03-30 12:23:28.947: E/AndroidRuntime(4936):     at com.google.android.gms.internal.jx.a(Unknown Source)
03-30 12:23:28.947: E/AndroidRuntime(4936):     at com.google.android.gms.common.api.c.b(Unknown Source)
03-30 12:23:28.947: E/AndroidRuntime(4936):     at com.google.android.gms.internal.nf.requestLocationUpdates(Unknown Source)
03-30 12:23:28.947: E/AndroidRuntime(4936):     at hu.company.testproject.service.GpsService.startLocationListening(GpsService.java:169)
03-30 12:23:28.947: E/AndroidRuntime(4936):     at hu.company.testproject.service.GpsService.onConnected(GpsService.java:259)
</code>```

...

My debug log also says the onConnected function got called:

```<code>03-30 12:23:28.847: I/Locationing_GpsService(4936): Google_Api_Client:connected.
03-30 12:23:28.857: I/Locationing_GpsService(4936): initLocationRequest:initing_now
03-30 12:23:28.877: I/Locationing_GpsService(4936): initLocationRequest:interval_5000
03-30 12:23:28.897: I/Locationing_GpsService(4936): initLocationRequest:priority_100
03-30 12:23:28.917: I/Locationing_GpsService(4936): Starting_location_listening:now
</code>```

After this I got the exception.

Am I missing something here? I got a response for "connected" I ran my func, and I got the error "not connected" what's this? Plus one annoying thing is: I used this location service for weeks now and never got this error.

E D I T :

I added a more specific log output, just blown my mind, check this out:

```<code>@Override
    public void onConnected(Bundle bundle) {

        if(mGoogleApiClient.isConnected()){
            log("Google_Api_Client: It was connected on (onConnected) function, working as it should.");
        }
        else{
            log("Google_Api_Client: It was NOT connected on (onConnected) function, It is definetly bugged.");
        }

        initLocationRequest();
        startLocationListening();
    }
</code>```

log output in this case:

```<code>03-30 16:20:00.950: I/Locationing_GpsService(16608): Google_Api_Client:connected.
03-30 16:20:00.960: I/Locationing_GpsService(16608): Google_Api_Client: It was NOT connected on (onConnected) function, It is definetly bugged.
</code>```

Yes, I just got mGoogleApiClient.isConnected() == false inside onConnected() how is it possible?

E D I T:

Since nobody could answer this even with reputation bounty, I decided to report this as a bug to Google. What came next was really surprising to me.
Google's official answer for my report:

"This website is for developer issues with the AOSP Android source
  code and the developer toolset, not Google apps or services such as
  Play services, GMS or Google APIs. Unfortunately there doesn't seem to
  be an appropriate place to report bugs with Play Services. All I can
  say is that this website isn't it, sorry. Try posting on the Google
  Product Forums instead. "

Full issue report here. (I hope they won't remove it just because it's silly)

So yeah I took a look at Google Product Forums and just couldn't find any topic to post this thing, so at the moment I am puzzled and stuck.

Does anybody in planet earth could help me with this?

E D I T:

Full code in pastebin

答: Moving GoogleApiClient from onStartCommand to onCeate resolved my issue</p>

Body:
So I found something that is not very clear for me about GoogleApiClient.
GoogleApiClient has a function called onConnected which is run when the client is connected (for sure).

I got my own function called: startLocationListening which is eventually getting called on GoogleApiClient's onConnected function.

So my startLocationListening function couldn't run without a GoogleApiClient connection.

Code and log:

@Override
public void onConnected(Bundle bundle) {
    log("Google_Api_Client:connected.");
    initLocationRequest();
    startLocationListening(); //Exception caught inside this function
}

...

private void startLocationListening() {
    log("Starting_location_listening:now");

    //Exception caught here below:
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
   }

The exception is:

03-30 12:23:28.947: E/AndroidRuntime(4936):     java.lang.IllegalStateException: GoogleApiClient is not connected yet.
03-30 12:23:28.947: E/AndroidRuntime(4936):     at com.google.android.gms.internal.jx.a(Unknown Source)
03-30 12:23:28.947: E/AndroidRuntime(4936):     at com.google.android.gms.common.api.c.b(Unknown Source)
03-30 12:23:28.947: E/AndroidRuntime(4936):     at com.google.android.gms.internal.nf.requestLocationUpdates(Unknown Source)
03-30 12:23:28.947: E/AndroidRuntime(4936):     at hu.company.testproject.service.GpsService.startLocationListening(GpsService.java:169)
03-30 12:23:28.947: E/AndroidRuntime(4936):     at hu.company.testproject.service.GpsService.onConnected(GpsService.java:259)

...

My debug log also says the onConnected function got called:

03-30 12:23:28.847: I/Locationing_GpsService(4936): Google_Api_Client:connected.
03-30 12:23:28.857: I/Locationing_GpsService(4936): initLocationRequest:initing_now
03-30 12:23:28.877: I/Locationing_GpsService(4936): initLocationRequest:interval_5000
03-30 12:23:28.897: I/Locationing_GpsService(4936): initLocationRequest:priority_100
03-30 12:23:28.917: I/Locationing_GpsService(4936): Starting_location_listening:now

After this I got the exception.

Am I missing something here? I got a response for "connected" I ran my func, and I got the error "not connected" what's this? Plus one annoying thing is: I used this location service for weeks now and never got this error.

E D I T :

I added a more specific log output, just blown my mind, check this out:

@Override
    public void onConnected(Bundle bundle) {

        if(mGoogleApiClient.isConnected()){
            log("Google_Api_Client: It was connected on (onConnected) function, working as it should.");
        }
        else{
            log("Google_Api_Client: It was NOT connected on (onConnected) function, It is definetly bugged.");
        }

        initLocationRequest();
        startLocationListening();
    }

log output in this case:

03-30 16:20:00.950: I/Locationing_GpsService(16608): Google_Api_Client:connected.
03-30 16:20:00.960: I/Locationing_GpsService(16608): Google_Api_Client: It was NOT connected on (onConnected) function, It is definetly bugged.

Yes, I just got mGoogleApiClient.isConnected() == false inside onConnected() how is it possible?

E D I T:

Since nobody could answer this even with reputation bounty, I decided to report this as a bug to Google. What came next was really surprising to me.
Google's official answer for my report:

"This website is for developer issues with the AOSP Android source
  code and the developer toolset, not Google apps or services such as
  Play services, GMS or Google APIs. Unfortunately there doesn't seem to
  be an appropriate place to report bugs with Play Services. All I can
  say is that this website isn't it, sorry. Try posting on the Google
  Product Forums instead. "

Full issue report here. (I hope they won't remove it just because it's silly)

So yeah I took a look at Google Product Forums and just couldn't find any topic to post this thing, so at the moment I am puzzled and stuck.

Does anybody in planet earth could help me with this?

E D I T:

Full code in pastebin