问:
MySQL query slow querying table on primary key
So I have a table that's being used basically like a NoSQL setup. The structure is:

id bigint primary key
data mediumblob
modified timestamp

It has around 350k rows. The queries that run on it are all structured as follows:

select data from table where id=XXX;

The table engine is InnoDB. I'm noticing that sometimes queries run against this table are rather slow. Sometimes they take 3 seconds to run. The table is 3 GB on disk and I gave the innodb_buffer_pool_size 4G.

Is there anything I'm missing here? Are there any settings I can tweak to improve performance?

Edit: As requested explain output:

```<code>+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table    | type  | possible_keys | key     | key_len | ref   | rows | Extra |
+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
|  1 | SIMPLE      | cache    | const | PRIMARY       | PRIMARY | 8       | const |    1 |       |
+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
</code>```

create table:

```<code>CREATE TABLE `cache` (
  `id` bigint(20) unsigned NOT NULL DEFAULT '0',
  `data` mediumblob,
  `modified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
</code>```

答:
Things I would look for:

when are the slow queries appearing?

is it after a fresh start of the DB? then this might be just a temporary problem - queries hitting in a cold cache

is it during DB dump/load? - then change your backup policies - use replication for example, or add more disk IO (adding more disks in RAID, change disks to SSD, repartition your system on multiple disks, etc)

is it during peak read/write times? replication might also help here - write into master and load balance the reads between master and slaves

Also - is that mediumblob really necessary there?

Body:
So I have a table that's being used basically like a NoSQL setup. The structure is:

id bigint primary key
data mediumblob
modified timestamp

It has around 350k rows. The queries that run on it are all structured as follows:

select data from table where id=XXX;

The table engine is InnoDB. I'm noticing that sometimes queries run against this table are rather slow. Sometimes they take 3 seconds to run. The table is 3 GB on disk and I gave the innodb_buffer_pool_size 4G.

Is there anything I'm missing here? Are there any settings I can tweak to improve performance?

Edit: As requested explain output:

+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table    | type  | possible_keys | key     | key_len | ref   | rows | Extra |
+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
|  1 | SIMPLE      | cache    | const | PRIMARY       | PRIMARY | 8       | const |    1 |       |
+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+

create table:

CREATE TABLE `cache` (
  `id` bigint(20) unsigned NOT NULL DEFAULT '0',
  `data` mediumblob,
  `modified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8


来源: stackexchange

问:
DbFit can't connect and find fixture in SetUp page
I installed DbFit on my laptop and connected it to my local Oracle Database.
I did the initial setup:

```<code>!path lib\*.jar

!|dbfit.OracleTest|

!|Connect|localhost:1522|system|Test123!|ORCLE|

!|Query| select 'test' as x from dual|
|x|
|test|
</code>```

This worked fine (after lots of errors and using StackOverflow).

Now for a more clean look and since it's needed for every page I moved this part to the SetUp page which will be automaticly included in every page I create:

```<code>!path lib\*.jar

!|dbfit.OracleTest|

!|Connect|localhost:1522|system|Test123!|ORCLE|
</code>```

When I then try to run I get the following message:

Could not find fixture: dbfit.OracleTest. (This is for !|dbfit.OracleTest|)

Could not find fixture: Connect. (This is for !|Connect|localhost:1522|system|Test123!|ORCLE|)

Could not find fixture: Query. (This for the query select 'test' as x from dual)

Anyone has any idea? The only simulair issue I found was here:
Why cannot DbFit be imported in SuiteSetUp?

But this didn't give me any solution.

Thank you for looking at this issue and your answers!

答: I'm not 100% sure, but I expect the problem is that the !path line should be in the parent page and not on the setup. </p>

ContentLicense: CC BY-SA 4.0

Body:
I installed DbFit on my laptop and connected it to my local Oracle Database.
I did the initial setup:

!path lib\*.jar

!|dbfit.OracleTest|

!|Connect|localhost:1522|system|Test123!|ORCLE|

!|Query| select 'test' as x from dual|
|x|
|test|

This worked fine (after lots of errors and using StackOverflow).

Now for a more clean look and since it's needed for every page I moved this part to the SetUp page which will be automaticly included in every page I create:

!path lib\*.jar

!|dbfit.OracleTest|

!|Connect|localhost:1522|system|Test123!|ORCLE|

When I then try to run I get the following message:

Could not find fixture: dbfit.OracleTest. (This is for !|dbfit.OracleTest|)

Could not find fixture: Connect. (This is for !|Connect|localhost:1522|system|Test123!|ORCLE|)

Could not find fixture: Query. (This for the query select 'test' as x from dual)

Anyone has any idea? The only simulair issue I found was here:
Why cannot DbFit be imported in SuiteSetUp?

But this didn't give me any solution.

Thank you for looking at this issue and your answers!


问:
Remove consecutive uppercase words from string
I'm having a long string where I would like to remove consecutive words with uppercase (2+ in a row) and if a punctation follows the last uppercase word, that as well.
But at the same time I would like to keep single uppercase words and uppercase words that are part of a "mixed" word (see reprex).

I struggle to implement the consecutive word group in reprex.

string <- "Lorem ipsum DOLOR SIT AMET? consectetuer adipiscing elit. Morbi gravida libero NEC velit. Morbi scelerisque luctus velit. ETIAM-123 dui sem, fermentum vitae, SAGITTIS ID? malesuada in, quam. Proin mattis lacinia justo. Vestibulum facilisis auctor urna. Aliquam IN LOREM SIT amet leo accumsan"

#remove all consecutive UPPERCASE words including punctation (--> DOLOR SIT AMET?), but not single uppercase words (--> NEC) or "mixed" words with uppercase and digits (--> ETIAM-123)
#this doesn't work:
string %>%
  stringr::str_remove_all("\\b[:upper:]+\\b")
#> [1] "Lorem ipsum   ? consectetuer adipiscing elit. Morbi gravida libero  velit. Morbi scelerisque luctus velit. -123 dui sem, fermentum vitae,  ? malesuada in, quam. Proin mattis lacinia justo. Vestibulum facilisis auctor urna. Aliquam    amet leo accumsan"
```

Created on 2020-05-30 by the reprex package (v0.3.0)

Any hints are appreciated :)

答:
You may use

```<code>string <- "Lorem ipsum DOLOR SIT AMET? consectetuer adipiscing elit. Morbi gravida libero NEC velit. Morbi scelerisque luctus velit. ETIAM-123 dui sem, fermentum vitae, SAGITTIS ID? malesuada in, quam. Proin mattis lacinia justo. Vestibulum facilisis auctor urna. Aliquam IN LOREM SIT amet leo accumsan"
gsub("\\s*\\b\\p{Lu}{2,}(?:\\s+\\p{Lu}{2,})+\\b[\\p{P}\\p{S}]*", "", string, perl=TRUE)
</code>```

Output:

```<code>[1] "Lorem ipsum  consectetuer adipiscing elit. Morbi gravida libero NEC velit. Morbi scelerisque luctus velit. ETIAM-123 dui sem, fermentum vitae,  malesuada in, quam. Proin mattis lacinia justo. Vestibulum facilisis auctor urna. Aliquam  amet leo accumsan"
</code>```

See the R demo and the regex demo.

Details

\s* - 0 or more whitespaces

\b - word boundary

\p{Lu}{2,} -  two or more capital letters

(?:\s+\p{Lu}{2,})+ - 1 or more occurrences of 1+ whitespaces followed with 2 or more uppercase letters

\b - a word boundary

[\p{P}\p{S}]* - any 0 or more symbols or punctuation

Body:
I'm having a long string where I would like to remove consecutive words with uppercase (2+ in a row) and if a punctation follows the last uppercase word, that as well.
But at the same time I would like to keep single uppercase words and uppercase words that are part of a "mixed" word (see reprex).

I struggle to implement the consecutive word group in reprex.

string <- "Lorem ipsum DOLOR SIT AMET? consectetuer adipiscing elit. Morbi gravida libero NEC velit. Morbi scelerisque luctus velit. ETIAM-123 dui sem, fermentum vitae, SAGITTIS ID? malesuada in, quam. Proin mattis lacinia justo. Vestibulum facilisis auctor urna. Aliquam IN LOREM SIT amet leo accumsan"

#remove all consecutive UPPERCASE words including punctation (--> DOLOR SIT AMET?), but not single uppercase words (--> NEC) or "mixed" words with uppercase and digits (--> ETIAM-123)
#this doesn't work:
string %>%
  stringr::str_remove_all("\\b[:upper:]+\\b")
#> [1] "Lorem ipsum   ? consectetuer adipiscing elit. Morbi gravida libero  velit. Morbi scelerisque luctus velit. -123 dui sem, fermentum vitae,  ? malesuada in, quam. Proin mattis lacinia justo. Vestibulum facilisis auctor urna. Aliquam    amet leo accumsan"

Created on 2020-05-30 by the reprex package (v0.3.0)

Any hints are appreciated :)

Body:
You may use

string <- "Lorem ipsum DOLOR SIT AMET? consectetuer adipiscing elit. Morbi gravida libero NEC velit. Morbi scelerisque luctus velit. ETIAM-123 dui sem, fermentum vitae, SAGITTIS ID? malesuada in, quam. Proin mattis lacinia justo. Vestibulum facilisis auctor urna. Aliquam IN LOREM SIT amet leo accumsan"
gsub("\\s*\\b\\p{Lu}{2,}(?:\\s+\\p{Lu}{2,})+\\b[\\p{P}\\p{S}]*", "", string, perl=TRUE)

Output:

[1] "Lorem ipsum  consectetuer adipiscing elit. Morbi gravida libero NEC velit. Morbi scelerisque luctus velit. ETIAM-123 dui sem, fermentum vitae,  malesuada in, quam. Proin mattis lacinia justo. Vestibulum facilisis auctor urna. Aliquam  amet leo accumsan"

See the R demo and the regex demo.

Details

\s* - 0 or more whitespaces

\b - word boundary

\p{Lu}{2,} -  two or more capital letters

(?:\s+\p{Lu}{2,})+ - 1 or more occurrences of 1+ whitespaces followed with 2 or more uppercase letters

\b - a word boundary

[\p{P}\p{S}]* - any 0 or more symbols or punctuation


问:
Tooltip not popping up on enter event
I have written a custom tkinter widget, TooltipLabel. When the cursor enters the label, it pops up a text widget that displays text. On windows, this works. But once I tested it on macos, the tooltip would not popup, even though the method to do so is getting called

I tried using this solution, but it didn't help.

Here's the PoC:

import math
import tkinter as tk
from tkinter import ttk

class Tooltip(object):
    """This widget adds a tooltip to a given widget, that displays when the cursor hovers over it"""
    def __init__(self, widget):
        self.widget = widget
        self.tooltip = None
        self.text = None
    #end init

    def show_tooltip(self, text):
        self.text = text
        if self.tooltip or not self.text:
            return

        x, y, cx, cy = self.widget.bbox("insert")
        x = x + self.widget.winfo_rootx() + 45
        y = y + cy + self.widget.winfo_rooty() + 30

        self.tooltip = tooltip_window = tk.Toplevel(self.widget)
        tooltip_window.wm_overrideredirect(1)   # removes the default window hide/maximize/close buttons
        tooltip_window.wm_geometry("+%d+%d" % (x, y))

        self._add_tooltip_text(tooltip_window)
    #end show_tooltip

    def hide_tooltip(self):
        tooltip_window = self.tooltip
        self.tooltip = None
        if tooltip_window:
            tooltip_window.destroy()
    #end hide_tooltip

    def _add_tooltip_text(self, tooltip_window):
        tooltip = tk.Text(tooltip_window, relief=tk.SOLID, width=40, wrap=tk.WORD)
        height = math.ceil(len(self.text) / 40) + self.text.count('\n')
        tooltip.insert(tk.END, self.text)
        tooltip.config(state=tk.DISABLED, height=height)
        tooltip.pack(ipadx=1)
    #end _add_tooltip_text
#end class Tooltip

def add_tooltip(widget, text):
    tooltip = Tooltip(widget)

    def enter(event):
        print(event)
        print(event.widget)
        print("Tooltip: %s" % text)
        tooltip.show_tooltip(text)
    #end enter

    def leave(event):
        tooltip.hide_tooltip()
    #end leave

    widget.bind('<Enter>', enter)
    widget.bind('<Leave>', leave)
#end add_tooltip

class TooltipLabel(ttk.Label):
    """This widget extends ttk.Label, and displays a tooltip when the cursor hovers over it"""
    def __init__(self, parent, tooltip_dict_key, **kwargs):
        ttk.Label.__init__(self, parent, **kwargs)

        self.parent = parent
        self.tooltip_text = None

        self.fetch_tooltip_text(tooltip_dict_key)
        add_tooltip(self, self.tooltip_text)
    #end init

    def fetch_tooltip_text(self, tooltip_dict_key):
        self.tooltip_text = "Testing tooltip"
    #end fetch_tooltip_text
#end class TooltipLabel

def main():
    root = tk.Tk()
    label = TooltipLabel(root, "tooltip_dict_key", text="testing")
    label.pack()

    root.mainloop()

if __name__ == "__main__":
    main()
```

<p>I would expect the tooltip to pop up and display the text "Testing tooltip". This doesn't happen even though the event fires.</p>

<p>The output I get from the print statements:</p>

```<Enter event focus=False x=43 y=20>
.!tooltiplabel
Tooltip: Testing tooltip
```

答:
Try adding below after the line:
tooltip_window.wm_geometry("+%d+%d" % (x, y))</p>

```<code>tooltip_window.update_idletasks()
tooltip_window.lift()
</code>```

Title: Tooltip not popping up on enter event

Body:
I have written a custom tkinter widget, TooltipLabel. When the cursor enters the label, it pops up a text widget that displays text. On windows, this works. But once I tested it on macos, the tooltip would not popup, even though the method to do so is getting called

I tried using this solution, but it didn't help.

Here's the PoC:

import math
import tkinter as tk
from tkinter import ttk

class Tooltip(object):
    """This widget adds a tooltip to a given widget, that displays when the cursor hovers over it"""
    def __init__(self, widget):
        self.widget = widget
        self.tooltip = None
        self.text = None
    #end init

    def show_tooltip(self, text):
        self.text = text
        if self.tooltip or not self.text:
            return

        x, y, cx, cy = self.widget.bbox("insert")
        x = x + self.widget.winfo_rootx() + 45
        y = y + cy + self.widget.winfo_rooty() + 30

        self.tooltip = tooltip_window = tk.Toplevel(self.widget)
        tooltip_window.wm_overrideredirect(1)   # removes the default window hide/maximize/close buttons
        tooltip_window.wm_geometry("+%d+%d" % (x, y))

        self._add_tooltip_text(tooltip_window)
    #end show_tooltip

    def hide_tooltip(self):
        tooltip_window = self.tooltip
        self.tooltip = None
        if tooltip_window:
            tooltip_window.destroy()
    #end hide_tooltip

    def _add_tooltip_text(self, tooltip_window):
        tooltip = tk.Text(tooltip_window, relief=tk.SOLID, width=40, wrap=tk.WORD)
        height = math.ceil(len(self.text) / 40) + self.text.count('\n')
        tooltip.insert(tk.END, self.text)
        tooltip.config(state=tk.DISABLED, height=height)
        tooltip.pack(ipadx=1)
    #end _add_tooltip_text
#end class Tooltip

def add_tooltip(widget, text):
    tooltip = Tooltip(widget)

    def enter(event):
        print(event)
        print(event.widget)
        print("Tooltip: %s" % text)
        tooltip.show_tooltip(text)
    #end enter

    def leave(event):
        tooltip.hide_tooltip()
    #end leave

    widget.bind('<Enter>', enter)
    widget.bind('<Leave>', leave)
#end add_tooltip

class TooltipLabel(ttk.Label):
    """This widget extends ttk.Label, and displays a tooltip when the cursor hovers over it"""
    def __init__(self, parent, tooltip_dict_key, **kwargs):
        ttk.Label.__init__(self, parent, **kwargs)

        self.parent = parent
        self.tooltip_text = None

        self.fetch_tooltip_text(tooltip_dict_key)
        add_tooltip(self, self.tooltip_text)
    #end init

    def fetch_tooltip_text(self, tooltip_dict_key):
        self.tooltip_text = "Testing tooltip"
    #end fetch_tooltip_text
#end class TooltipLabel

def main():
    root = tk.Tk()
    label = TooltipLabel(root, "tooltip_dict_key", text="testing")
    label.pack()

    root.mainloop()

if __name__ == "__main__":
    main()

I would expect the tooltip to pop up and display the text "Testing tooltip". This doesn't happen even though the event fires.

The output I get from the print statements:

<Enter event focus=False x=43 y=20>
.!tooltiplabel
Tooltip: Testing tooltip

Body:
Try adding below after the line:
tooltip_window.wm_geometry("+%d+%d" % (x, y))

tooltip_window.update_idletasks()
tooltip_window.lift()


问:
How to divide a DataFrame into groups using index label and perform operation to find 3 largest in a particular column according to each index
I have a dataframe like this:

```<code>STNAME         CTYNAME           POPESTIMATE
Alabama        Autauga County     54660
Alabama        Baldwin County     183193
Alabama        Barbour County     27341
Alabama        Bibb County        22861
Alabama        Blount County      57373
.......        ...............    .....
Wyoming        Sweetwater County  43593
Wyoming        Teton County       21297
Wyoming        Uinta County       21102

.......      .............      ......
.......        .............       .....

and so on............
</code>```

Here i have to find out three most populous cities(CTYNAME) for each state and sum up them(using POPESTIMATE) for each state and we can call that as Population of each state,and from that data of population(only three most populous cities for each state) I have to find out three most populous states and print them in a list.

I have tried out this using multiple method in pandas library but nothing has worked for me.
Can some one please help me with this.

答:
Spliting df:</p>

```<code>df = df.groupby('STNAME',as_index=True)
print(df.apply(lambda s: pd.Series(s.nlargest(3).index)))
</code>```

Body:
I have a dataframe like this:

STNAME         CTYNAME           POPESTIMATE
Alabama        Autauga County     54660
Alabama        Baldwin County     183193
Alabama        Barbour County     27341
Alabama        Bibb County        22861
Alabama        Blount County      57373
.......        ...............    .....
Wyoming        Sweetwater County  43593
Wyoming        Teton County       21297
Wyoming        Uinta County       21102

.......      .............      ......
.......        .............       .....

and so on............

Here i have to find out three most populous cities(CTYNAME) for each state and sum up them(using POPESTIMATE) for each state and we can call that as Population of each state,and from that data of population(only three most populous cities for each state) I have to find out three most populous states and print them in a list.

I have tried out this using multiple method in pandas library but nothing has worked for me.
Can some one please help me with this.

Body:
Spliting df:

df = df.groupby('STNAME',as_index=True)
print(df.apply(lambda s: pd.Series(s.nlargest(3).index)))


问:
Angular - Only allow routing if routed using router.navigate() method
My requirement is to prevent the user navigation if the user changes browser URL manually from address bar. Routing should only be done through angular app(router.navigate()).

I know that we can implement route guard using canActive property.

```<code>canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

}
</code>```

But I don't know which properties of ActivatedRouteSnapshot or RouterStateSnapshot I can use to identify that the user is navigating inside the application using manual url change. Can you please help.

答:
I have recently faced this problem and I think I have solved it or at least it works for me.

```<code>canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

  const nav = this.router.getCurrentNavigation();

  if (nav.id === 1 || nav.previousNavigation !== null) {
    this.router.navigate(['/somewhere']);
  } else {
    return true;
  }
}
</code>```

The property 'id' of navigation object indicates the number within the user's browsing history within the application. So id === 1 would indicate that the user has entered by browser address first time and not by redirection via router.navigate()

If the user was already browsing the application, we have to check that there is a previous registered navigation and to be able to control from where they are browsing.

Body:
My requirement is to prevent the user navigation if the user changes browser URL manually from address bar. Routing should only be done through angular app(router.navigate()).

I know that we can implement route guard using canActive property.

canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

}

But I don't know which properties of ActivatedRouteSnapshot or RouterStateSnapshot I can use to identify that the user is navigating inside the application using manual url change. Can you please help.

Body:
I have recently faced this problem and I think I have solved it or at least it works for me.

canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

  const nav = this.router.getCurrentNavigation();

  if (nav.id === 1 || nav.previousNavigation !== null) {
    this.router.navigate(['/somewhere']);
  } else {
    return true;
  }
}

The property 'id' of navigation object indicates the number within the user's browsing history within the application. So id === 1 would indicate that the user has entered by browser address first time and not by redirection via router.navigate()

If the user was already browsing the application, we have to check that there is a previous registered navigation and to be able to control from where they are browsing.


问:
Jetty error: HTTP method GET is not supported by this URL
I am using HTTP4S and the webapp is running on jetty. The web app file is configured as:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

   <servlet>
      <servlet-name>user-svc</servlet-name>
      <servlet-class>io.databaker.UserSvcServlet</servlet-class>
      <async-supported>true</async-supported>
   </servlet>

   <servlet-mapping>
      <servlet-name>user-svc</servlet-name>
      <url-pattern>/*</url-pattern>
   </servlet-mapping>

</web-app>
```

<p>The available URI's are:</p>

```object UserSvcRoutes {

  def helloWorldRoutes[F[_]: Sync](H: HelloWorld[F]): HttpRoutes[F] = {
    val dsl = new Http4sDsl[F]{}
    import dsl._
    HttpRoutes.of[F] {
      case GET -> Root =>
        Ok("Example")
      case GET -> Root / "hello" / name =>
        for {
          greeting <- H.hello(HelloWorld.Name(name))
          resp <- Ok(greeting)
        } yield resp
    }
  }

}
```

When I call http://localhost:8080/ I've got:

What I am doing wrong?

答:
Http4sServlet was recently made abstract, with two concrete implementations provided by BlockingHttp4sServlet and AsyncHttp4sServlet.

You can get your example working by changing UserSvcServlet to extend either of these:

package io.databaker

import AppContextShift._
import cats.effect._
import java.util.concurrent.Executors
import org.http4s.server.DefaultServiceErrorHandler
import org.http4s.servlet.BlockingHttp4sServlet
import org.http4s.servlet.BlockingServletIo

class UserSvcServlet
  extends BlockingHttp4sServlet[IO](
    service = UserSvcServer.start,
    servletIo = BlockingServletIo(4096, Blocker.liftExecutorService(Executors.newCachedThreadPool())),
    serviceErrorHandler = DefaultServiceErrorHandler
  )
```

Body:
I am using HTTP4S and the webapp is running on jetty. The web app file is configured as:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

   <servlet>
      <servlet-name>user-svc</servlet-name>
      <servlet-class>io.databaker.UserSvcServlet</servlet-class>
      <async-supported>true</async-supported>
   </servlet>

   <servlet-mapping>
      <servlet-name>user-svc</servlet-name>
      <url-pattern>/*</url-pattern>
   </servlet-mapping>

</web-app>

The available URI's are:

object UserSvcRoutes {

  def helloWorldRoutes[F[_]: Sync](H: HelloWorld[F]): HttpRoutes[F] = {
    val dsl = new Http4sDsl[F]{}
    import dsl._
    HttpRoutes.of[F] {
      case GET -> Root =>
        Ok("Example")
      case GET -> Root / "hello" / name =>
        for {
          greeting <- H.hello(HelloWorld.Name(name))
          resp <- Ok(greeting)
        } yield resp
    }
  }

}

When I call http://localhost:8080/ I've got:

What I am doing wrong?


问:
what's command to list all the virtual environments in venv?
I know in conda I can use conda env list to get a list of all conda virtual environments, what's the corresponding command in python venv that can list all the virtual environments in a given venv? also, is there any way I can print/check the directory of current venv? somehow I have many projects that have same name .venv for their virtual environment and I'd like to find a way to verify which venv I'm in. Thanks

答: Virtual environments are simple a set of files in a directory on your system. You can find them the same way you would find images or documents with a certain name. For example, if you are using Linux or macOS, you could run find / | grep bin/activate in terminal. Not too sure about Windows but I suspect you can search for something similar in Windows Explorer.


问:
OpenXml Spreadsheet. Value filters, styles and unicode characters
because of small documentation i have problems with OpenXml SpreadSheetDocument in C#.

How to make top row with filter?

How to make colors to alternate?

I want to put unicode characters in my SheetData, but when i oppen the excel it gives me an error..

Change the top row color.
Can you say if there are some proper ways to do this, some more documentation than these available on msdn, or post some StyleSheet code?
Sorry for my english.
Thanks.

答:
I think that your question is really about how to create tables in a spreadsheet.  Tables are a cool feature of Open XML / Excel 2007 / 2010 that enable you to sort a range of cells by clicking on column headings.  Also they are presented with alternative color bands for rows.  There are additional features, such as ability to have a total row, and automatic expansion when you insert a row.

I've written a blog post about tables and how to create them: Exploring Table Markup in SpreadsheetML.  In addition, I've recorded a 15 minute screen-cast that explores the markup, and shows how to create an Open XML SDK program that converts ordinary cells into a table.

-Eric

ContentLicense: CC BY-SA 3.0


问:
How to configure NGINX for Vue and Django?
I was following this tutorial to create a backend and it worked.

I made simple a Django REST admin panel to upload images, it worked.

Then I created Vue frontend app, run npm run serve while in 'VScode remote' and it worked (images are fetched from Django and styled by Vue in my localhost).

The PROBLEM is it's not obvious how to make all this work in the production VPS server (i mean from Vue 'dist' folder after vue run build).
Everything I tried just gives me a 404 error or ruins the Django admin panel.

Here are my NGINX settings :

```<code>server {
server_name kruglovks.xyz www.kruglovks.xyz;
client_max_body_size 100m;

location = /favicon.ico { access_log off; log_not_found off; }

location /static {
    root /home/kirill/myprojectdir/myproject;
}

location /media {
    root /home/kirill/myprojectdir/myproject;
}

location /dist {
    try_files $uri $uri/ /index.html;
    alias /home/kirill/myprojectdir/myproject;
}

location / {
    include proxy_params;
    proxy_pass http://unix:/run/gunicorn.sock;
}
</code>```

Vue router is set to history mode.

Please, I need some info on how to make Vue work in this configuration.

P.S. Maybe there is an alternative way of using Vue alongside Django?

Thank you so much and have a nice day!

答:
You are not listening to any ports.
Notice that in location /dist you also have to change the order of operations

Try to change your default to this configuration:

```<code>server {
    listen      80;
    server_name kruglovks.xyz www.kruglovks.xyz;
    root        /var/www;
    #... configurations
    location /dist {
        alias /home/kirill/myprojectdir/myproject;
        try_files $uri $uri/ /index.html;

}
</code>```

And the vuejs application will be served in www.kruglovks.xyz/dist.

Body:
I was following this tutorial to create a backend and it worked.

I made simple a Django REST admin panel to upload images, it worked.

Then I created Vue frontend app, run npm run serve while in 'VScode remote' and it worked (images are fetched from Django and styled by Vue in my localhost).

The PROBLEM is it's not obvious how to make all this work in the production VPS server (i mean from Vue 'dist' folder after vue run build).
Everything I tried just gives me a 404 error or ruins the Django admin panel.

Here are my NGINX settings :

server {
server_name kruglovks.xyz www.kruglovks.xyz;
client_max_body_size 100m;

location = /favicon.ico { access_log off; log_not_found off; }

location /static {
    root /home/kirill/myprojectdir/myproject;
}

location /media {
    root /home/kirill/myprojectdir/myproject;
}

location /dist {
    try_files $uri $uri/ /index.html;
    alias /home/kirill/myprojectdir/myproject;
}

location / {
    include proxy_params;
    proxy_pass http://unix:/run/gunicorn.sock;
}

Vue router is set to history mode.

Please, I need some info on how to make Vue work in this configuration.

P.S. Maybe there is an alternative way of using Vue alongside Django?

Thank you so much and have a nice day!

Body:
You are not listening to any ports.
Notice that in location /dist you also have to change the order of operations

Try to change your default to this configuration:

server {
    listen      80;
    server_name kruglovks.xyz www.kruglovks.xyz;
    root        /var/www;
    #... configurations
    location /dist {
        alias /home/kirill/myprojectdir/myproject;
        try_files $uri $uri/ /index.html;

}

And the vuejs application will be served in www.kruglovks.xyz/dist.


问:
How to process inner observables?
In my Angular app is an array recordlist. This array contains other arrays of objects. What I'm trying to do now is to process a http.post (via a function) on every nested element in the recordlist array.

The this.recordlist is an Observable which works and is shown as a table in my app.

```<code>/**
 *
 */
save() {
    this.recordlist
        .pipe(
            mergeMap((response: any) => response.flat()),
            map((response: any) => {
                console.log('---', response);
                return this.skaterService.setSkaterSeasonBestTimes(response);
            })
        )
        .subscribe(
            response => {},
            error => {},
            () => {
                console.log('.....done');
            }
        );
    }

/**
 *
 */
setSkaterSeasonBestTimes(value: SkaterBesttime): Observable<any> {
    return this.restService.post('/skater/besttimes', value).pipe(
        map((response: any) => {
            console.log('+++', response);
            return new SkaterBesttime(response, true);
        })
    );
}
</code>```

The problem is now that the inner setSkaterSeasonBestTimes(...) is not processed. I hope that somebody can give me a useful hint and solution.

答:
You reversed your map and your mergeMap.

Try this :

/**
 *
 */
save() {
    this.recordlist
        .pipe(
            map((response: any) => response.flat()),
            mergeMap((response: any) => {
                console.log('---', response);
                return this.skaterService.setSkaterSeasonBestTimes(response);
            })
        )
        .subscribe(
            response => {},
            error => {},
            () => {
                console.log('.....done');
            }
        );
    }

/**
 *
 */
setSkaterSeasonBestTimes(value: SkaterBesttime): Observable<any> {
    return this.restService.post('/skater/besttimes', value).pipe(
        map((response: any) => {
            console.log('+++', response);
            return new SkaterBesttime(response, true);
        })
    );
}```

mergeMap need to return an Observable

Title: How to process inner observables?

Body:
In my Angular app is an array recordlist. This array contains other arrays of objects. What I'm trying to do now is to process a http.post (via a function) on every nested element in the recordlist array.

The this.recordlist is an Observable which works and is shown as a table in my app.

/**
 *
 */
save() {
    this.recordlist
        .pipe(
            mergeMap((response: any) => response.flat()),
            map((response: any) => {
                console.log('---', response);
                return this.skaterService.setSkaterSeasonBestTimes(response);
            })
        )
        .subscribe(
            response => {},
            error => {},
            () => {
                console.log('.....done');
            }
        );
    }

/**
 *
 */
setSkaterSeasonBestTimes(value: SkaterBesttime): Observable<any> {
    return this.restService.post('/skater/besttimes', value).pipe(
        map((response: any) => {
            console.log('+++', response);
            return new SkaterBesttime(response, true);
        })
    );
}

The problem is now that the inner setSkaterSeasonBestTimes(...) is not processed. I hope that somebody can give me a useful hint and solution.

Body:
You reversed your map and your mergeMap.

Try this :

/**
 *
 */
save() {
    this.recordlist
        .pipe(
            map((response: any) => response.flat()),
            mergeMap((response: any) => {
                console.log('---', response);
                return this.skaterService.setSkaterSeasonBestTimes(response);
            })
        )
        .subscribe(
            response => {},
            error => {},
            () => {
                console.log('.....done');
            }
        );
    }

/**
 *
 */
setSkaterSeasonBestTimes(value: SkaterBesttime): Observable<any> {
    return this.restService.post('/skater/besttimes', value).pipe(
        map((response: any) => {
            console.log('+++', response);
            return new SkaterBesttime(response, true);
        })
    );
}

mergeMap need to return an Observable


问:
select query in laravel
I have created a my application in laravel.my sql query is working fine.I'm bit struck with laravel query

```<code>select a.type from chart_table a left join color_codes b on a.type=b.type_id group by a.type
</code>```

For the above query tried as

```<code>DB::table('chart_table')
    ->leftjoin('color_codes','color_codes.type_id','=','chart_table.type')
    ->whereIn('chart_table.user_name',$filter_username_details)
    ->orderBy('color_codes.id', 'asc')
    ->groupBy('chart_table.type')
    ->pluck('chart_table.type')
    ->toArray();
</code>```

I'm getting the error as

```<code>SQLSTATE[42803]: Grouping error: 7 ERROR:  column "color_codes.id" must appear in the GROUP BY clause or be used in an aggregate function<br />
LINE 1: ...le"."type" group by "chart_table"."type" order by "color_cod..
</code>```

What I did wrong in my query

答:
for groupBy, you will have to change strict as false. It will not affect on your any SQL / Eloquent query.

and then try.

```<code>DB::table('chart_table')
    ->leftjoin('color_codes','color_codes.type_id','=','chart_table.type')
    ->whereIn('chart_table.user_name',$filter_username_details)
    ->orderBy('color_codes.id', 'asc')
    ->groupBy('chart_table.type')
    ->pluck('chart_table.type')
    ->toArray();
</code>```

I hope it will work for you.

Title: select query in laravel

Body:
I have created a my application in laravel.my sql query is working fine.I'm bit struck with laravel query

select a.type from chart_table a left join color_codes b on a.type=b.type_id group by a.type

For the above query tried as

DB::table('chart_table')
    ->leftjoin('color_codes','color_codes.type_id','=','chart_table.type')
    ->whereIn('chart_table.user_name',$filter_username_details)
    ->orderBy('color_codes.id', 'asc')
    ->groupBy('chart_table.type')
    ->pluck('chart_table.type')
    ->toArray();

I'm getting the error as

SQLSTATE[42803]: Grouping error: 7 ERROR:  column "color_codes.id" must appear in the GROUP BY clause or be used in an aggregate function

LINE 1: ...le"."type" group by "chart_table"."type" order by "color_cod..

What I did wrong in my query

Body:
for groupBy, you will have to change strict as false. It will not affect on your any SQL / Eloquent query.

and then try.

DB::table('chart_table')
    ->leftjoin('color_codes','color_codes.type_id','=','chart_table.type')
    ->whereIn('chart_table.user_name',$filter_username_details)
    ->orderBy('color_codes.id', 'asc')
    ->groupBy('chart_table.type')
    ->pluck('chart_table.type')
    ->toArray();

I hope it will work for you.


问:
bluezero remote api v-rep with python
I have some issues when I am trying to connect python to v-rep using Blue Zero based remote API. The community of v-rep didn't have enough details and I have followed their information such as:
copy and paste the py files from v-rep directory to folder project and also b0.dll file, also I have install msgpack using pip install but it didn't show it in the folder project. when I am trying to import the API as follow in spyder editor from Anaconda:

```<code>import b0RemoteApi
</code>```

it shows me the error message

```<code>Traceback (most recent call last):

  File "<ipython-input-11-42c3b157e1d8>", line 1, in <module>
    import b0RemoteApi

  File "C:path to folder project\b0RemoteApi.py", line 6, in <module>
    import b0

  File "C:path to folder project\b0.py", line 18, in <module>
    libb0 = ct.CDLL(libb0_fullpath)

  File "C:some pathes\Anaconda1\lib\ctypes\__init__.py", line 364, in __init__
    self._handle = _dlopen(self._name, mode)

OSError: [WinError 126] The specified module could not be found
</code>```

I am using windows 10 and I have worked on many suggestions but I didn't find out the solution. Any help please.

答:
I ran into a similar problem, you need to add all the dependencies(.dll files) for BlueZero.
They are already present inside the installation folder at different places.
The following dependencies you need to add:

boost (boost_date_time, boost_filesystem, boost_program_options,  boost_regex, boost_serialization, boost_thread)

libzmq

lz4

zlib

Title: bluezero remote api v-rep with python

Body:
I have some issues when I am trying to connect python to v-rep using Blue Zero based remote API. The community of v-rep didn't have enough details and I have followed their information such as:
copy and paste the py files from v-rep directory to folder project and also b0.dll file, also I have install msgpack using pip install but it didn't show it in the folder project. when I am trying to import the API as follow in spyder editor from Anaconda:

import b0RemoteApi

it shows me the error message

Traceback (most recent call last):

  File "<ipython-input-11-42c3b157e1d8>", line 1, in <module>
    import b0RemoteApi

  File "C:path to folder project\b0RemoteApi.py", line 6, in <module>
    import b0

  File "C:path to folder project\b0.py", line 18, in <module>
    libb0 = ct.CDLL(libb0_fullpath)

  File "C:some pathes\Anaconda1\lib\ctypes\__init__.py", line 364, in __init__
    self._handle = _dlopen(self._name, mode)

OSError: [WinError 126] The specified module could not be found

I am using windows 10 and I have worked on many suggestions but I didn't find out the solution. Any help please.


问:
how to get Github Pull Request Comments Thread Using github API
https://developer.github.com/v3/pulls/

I Need PR Comments like this

ex)

```<code>[
    {
        avartar : 'img_link',
        author : 'MoonSupport',
        description: 'dd\ntt',
    },
    {
        avartar : 'img_link',
        author : 'MoonSupport',
        description: 'review1',
    },
    {
        avartar : 'img_link',
        author : 'MoonSupport',
        description: 'review2',
    }
]
</code>```

Is there API that work it?

Please find it.

答:
Rest API v3

Using API v3, you can get the PR comments using

```<code>https://api.github.com/repos/OWNER/REPO_NAME/issues/NUMBER/comments
</code>```

Example for this PR : https://api.github.com/repos/mui-org/material-ui/issues/21214/comments

You can get the PR review comments using :

```<code>https://api.github.com/repos/OWNER/REPO_NAME/pulls/NUMBER/comments
</code>```

Example for this PR : https://api.github.com/repos/mui-org/material-ui/pulls/21214/comments

But this doen't include the review body text (which is at the same level as a comment in the Github Web UI). The following get the body text of the reviews :

```<code>https://api.github.com/repos/OWNER/REPO_NAME/pulls/NUMBER/reviews
</code>```

Example for this PR : https://api.github.com/repos/mui-org/material-ui/pulls/21214/reviews

GraphQL API v4

Using GraphQL API, to get both comments, reviews comments and review body text :

{
  repository(name: "material-ui", owner: "mui-org") {
    pullRequest(number: 21214) {
      reviews(first: 100) {
        nodes {
          bodyText
          createdAt
          author {
            login
          }
          comments(first: 100) {
            nodes {
              author {
                login
              }
              body
            }
          }
        }
      }
      comments(first: 100) {
        nodes {
          author {
            login
          }
          createdAt
          body
        }
        totalCount
      }
    }
  }
}
```

Body:
https://developer.github.com/v3/pulls/

I Need PR Comments like this

ex)

[
    {
        avartar : 'img_link',
        author : 'MoonSupport',
        description: 'dd\ntt',
    },
    {
        avartar : 'img_link',
        author : 'MoonSupport',
        description: 'review1',
    },
    {
        avartar : 'img_link',
        author : 'MoonSupport',
        description: 'review2',
    }
]

Is there API that work it?

Please find it.

Body:
Rest API v3

Using API v3, you can get the PR comments using

https://api.github.com/repos/OWNER/REPO_NAME/issues/NUMBER/comments

Example for this PR : https://api.github.com/repos/mui-org/material-ui/issues/21214/comments

You can get the PR review comments using :

https://api.github.com/repos/OWNER/REPO_NAME/pulls/NUMBER/comments

Example for this PR : https://api.github.com/repos/mui-org/material-ui/pulls/21214/comments

But this doen't include the review body text (which is at the same level as a comment in the Github Web UI). The following get the body text of the reviews :

https://api.github.com/repos/OWNER/REPO_NAME/pulls/NUMBER/reviews

Example for this PR : https://api.github.com/repos/mui-org/material-ui/pulls/21214/reviews

GraphQL API v4

Using GraphQL API, to get both comments, reviews comments and review body text :

{
  repository(name: "material-ui", owner: "mui-org") {
    pullRequest(number: 21214) {
      reviews(first: 100) {
        nodes {
          bodyText
          createdAt
          author {
            login
          }
          comments(first: 100) {
            nodes {
              author {
                login
              }
              body
            }
          }
        }
      }
      comments(first: 100) {
        nodes {
          author {
            login
          }
          createdAt
          body
        }
        totalCount
      }
    }
  }
}


问:
vim-go, modules and GoRename
Is there a way I can achieve GoRename to rename all occurences in my whole module?

For example, I have module with go.mod

module test

go 1.14
```

<p>and 2 packages:
file sub/sub.go</p>

<pre class="lang-golang prettyprint-override"><code>package sub

import "fmt"

func Sub() {
    fmt.Printf("Hello from sub package")
}

func CallSub() {
    Sub()
}
</code>```

and another:
main/main.go

package main

import "test/sub"

func main() {
    sub.Sub()
}
```

<p>GoRename correctly renames all references of function Sub in sub package, but not in main. Is it possible to achieve renaming in whole module? Thanks for reply.</p>

<p><em>p.s I'm using gopls in my vimrc</em></p>

```let g:go_rename_command = 'gopls'
```

答: I solved it by running PlugUpdate.</p>

Title: vim-go, modules and GoRename

Body:
Is there a way I can achieve GoRename to rename all occurences in my whole module?

For example, I have module with go.mod

module test

go 1.14

and 2 packages:
file sub/sub.go

package sub

import "fmt"

func Sub() {
    fmt.Printf("Hello from sub package")
}

func CallSub() {
    Sub()
}

and another:
main/main.go

package main

import "test/sub"

func main() {
    sub.Sub()
}

GoRename correctly renames all references of function Sub in sub package, but not in main. Is it possible to achieve renaming in whole module? Thanks for reply.

p.s I'm using gopls in my vimrc

let g:go_rename_command = 'gopls'

Body: I solved it by running PlugUpdate.


问:
Updating label during function
If you have a simple routine like the one below how do you get the label to update during the loop? When I run this it only updates at the end when the function it is in completes.

```<code>for loop in 1...10 {
    doCalculation()

    resultLabel.text = String(result)

    sleep(1)
}

function doCalculation() {

    ... perform calculation updating variable result ...

}
</code>```

I have tried this also but this doesn't fix it.

```<code>for loop in 1...10 {
    doCalculation()

    DispatchQueue.main.async {
      self.resultLabel.text = String(self.result)
    }

    sleep(1)
}
</code>```

答:
You can try Timer:

Swift’s Timer class is a flexible way to schedule work to happen in
  the future, either just once or repeatedly.

```<code>let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
    print("Timer fired!")
}
</code>```

The more detailed explanation can be found here or here.

Title: Updating label during function

Body:
If you have a simple routine like the one below how do you get the label to update during the loop? When I run this it only updates at the end when the function it is in completes.

for loop in 1...10 {
    doCalculation()

    resultLabel.text = String(result)

    sleep(1)
}

function doCalculation() {

    ... perform calculation updating variable result ...

}

I have tried this also but this doesn't fix it.

for loop in 1...10 {
    doCalculation()

    DispatchQueue.main.async {
      self.resultLabel.text = String(self.result)
    }

    sleep(1)
}

Body:
You can try Timer:

Swift’s Timer class is a flexible way to schedule work to happen in
  the future, either just once or repeatedly.

let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
    print("Timer fired!")
}

The more detailed explanation can be found here or here.


问:
How can I register given info on signup page by user to Firestore directly?
I'm building an App with a detailed Sign up page that requesting name, nationality and phone number from the new user.

I want to register all the provided information above to the newly created user ID who just signed up now.

I did google search for the method but all what I found is how to feed data to user.uid after signing in ... Ok that is very simple and easy to retrieve the user ID after signing in by Auth.auth().didChangeListner

But what I want exactly is how to feed given information from user directly to his new created ID?
Or how to get the latest created user ID without Singing in?

答:
The typical process is:

You create the user account on Firebase Authentication.

You then write the additional registration information to the database.

Something like:

```<code>Auth.auth().createUser(withEmail: email, password: password) { authResult, error in
    if let eror = error {
        print(eror.localizedDescription )
    } else {
        // user created successfully
        print(result.user.uid)
        // TODO: register their additional information in the database under their UID
    }
}
</code>```

Body:
The typical process is:

You create the user account on Firebase Authentication.

You then write the additional registration information to the database.

Something like:

Auth.auth().createUser(withEmail: email, password: password) { authResult, error in
    if let eror = error {
        print(eror.localizedDescription )
    } else {
        // user created successfully
        print(result.user.uid)
        // TODO: register their additional information in the database under their UID
    }
}


问:
Container not starting
I made a docker container of my web application.

At the end of the docker build command, I saw (which I suppose means that image was made)

```<code>Successfully tagged App:30may2020
SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.
</code>```

When I run the container, I get error

docker run  --publish 9000:9000 --detach --name App App:30may2020

```<code>docker: Error response from daemon: Conflict. The container name "/App" is already in use by container "8a641431369c418e99ccb752161f5f2848d3c8f14bb903a18b6bd4aff2966af6". You have to remove (or rename) that container to be able to reuse that name.
</code>```

Question 1 - Does build command also starts the container as I didn't start the container?
Question 2 - I did docker container ls  and docker container ps but I don't see my container running. Then why do I get the error?

答:
Question1 answer: build doesn't starts a container

Question 2 answer: ps and ls display the container which are currently running but not those containers which are stopped. Do docker ps -a Incase if you want to view stopped containers.
You are getting the error because you have already a container with the name '/App' try to run a container with a different name.
Or in case if you want to run container with same name but want to use from new build you should first stop and delete the container and you can run under a same name

Title: Container not starting

Body:
I made a docker container of my web application.

At the end of the docker build command, I saw (which I suppose means that image was made)

Successfully tagged App:30may2020
SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.

When I run the container, I get error

docker run  --publish 9000:9000 --detach --name App App:30may2020

docker: Error response from daemon: Conflict. The container name "/App" is already in use by container "8a641431369c418e99ccb752161f5f2848d3c8f14bb903a18b6bd4aff2966af6". You have to remove (or rename) that container to be able to reuse that name.

Question 1 - Does build command also starts the container as I didn't start the container?
Question 2 - I did docker container ls  and docker container ps but I don't see my container running. Then why do I get the error?


问:
remove \begin{tabular} from Stargazer .tex output
Is there a simple way to automatically remove the

```<code>\begin{tabular}{@{\extracolsep{5pt}}lc}
</code>```

and

```<code>\end{tabular}
</code>```

lines at the beginning and end of a Stargazer LaTeX output?

Indeed, I just need the inside LaTeX code and removing those lines manually from the TeX file generated by stargazer is a complete loss of time...

答:
Having the same issue, I ended up just adding some lines to my R code after having created the table with stargazer:

```<code>filename <- paste0("./my/path/", dplyr::last(list.files("./my/path/"))) # always loads the last file
lines <- readLines(filename) # read file
lines[1:4] <- ""           # I wanted to replace the first four lines
lines[length(lines)] <- "" # as well as the last line
</code>```

Hope this helps.

Body:
Is there a simple way to automatically remove the

\begin{tabular}{@{\extracolsep{5pt}}lc}

and

\end{tabular}

lines at the beginning and end of a Stargazer LaTeX output?

Indeed, I just need the inside LaTeX code and removing those lines manually from the TeX file generated by stargazer is a complete loss of time...

Body:
Having the same issue, I ended up just adding some lines to my R code after having created the table with stargazer:

filename <- paste0("./my/path/", dplyr::last(list.files("./my/path/"))) # always loads the last file
lines <- readLines(filename) # read file
lines[1:4] <- ""           # I wanted to replace the first four lines
lines[length(lines)] <- "" # as well as the last line

Hope this helps.


问:
How to load a YAML file in Python while preserving the original order
I want to laod a YAML-file to a dict.
Everything I found is outdated, since Python 3.6 changed dicts to be ordered by insertion.
What would be the proper way to do it?</p>

答:
It is possible to do that with ruamel. </p>

```<code>import ruamel.yaml

yaml = ruamel.yaml.YAML(typ='safe')
with open(path_to_file) as file:
    my_dict = yaml.load(file)
</code>```

Body:
It is possible to do that with ruamel.

import ruamel.yaml

yaml = ruamel.yaml.YAML(typ='safe')
with open(path_to_file) as file:
    my_dict = yaml.load(file)


问:
How can I make a bootstrap media list with a scroll bar?
Here is my code:

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

     <video id="selfView" class="h-100 w-100 position-absolute" controls muted>
      <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
     </video>

      TV:On
      <input type="checkbox" id="shareVideo" checked>

      Light:On
      <input type="checkbox" id="shareAudio" checked>

      Air Cond:Off
      <input type="checkbox" id="shareScreen">

      <button class="btn-sm btn btn-lg btn-success">Create a meeting</button>

        i

        f

        c

         a

         b

         c

         a

         b

         c

         a

         b

         c

         a

         b

         c

         a

         b

         c

         a

         b

         c

        2

        3

```

How can I make the bootstrap media list(i.e line 81) with a scroll bar?

I have using a "position-relative" and "position-absolute" class to make the browser show a scroll bar.

Unfortunately, it does not work.

It is because when I browse the web page with a mobile phone the media list is too long.

答:
The scrollbar can be added by using a CSS class with these 2 attributes:

overflow-y: scroll

max-height: height;

An example CSS class for scroll bar:

```<code>        .scroll-bar {
            overflow-x: scroll;
            overflow-y: scroll;
            max-height: 100px;
        }
</code>```

Here is the working example with CSS class added to the list:

```<code><html>
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
        <!-- Optional JavaScript -->
        <!-- jQuery first, then Popper.js, then Bootstrap JS -->
        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

        <style>
            .scroll-bar {
                overflow-x: scroll;
                overflow-y: scroll;
                max-height: 100px;
            }
        </style>
    </head>
    <body class="p-1">
        <div class="p-0 container-fluid">
            <div class="p-0 row h-25 no-gutters">
                <div class="p-0 col-12 col-sm-12 col-lg-12 col-xl-12">
                    <video id="selfView" class="h-100 w-100 position-absolute" controls muted>
                        <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
                    </video>
                </div>
            </div>
            <div class="p-0 row no-gutters">
                <div class="d-flex flex-row justify-content-center p-0 col-12 col-sm-12 col-lg-12 col-xl-12">
                    <div class="btn-group-toggle p-1" data-toggle="buttons">
                      <label class="btn btn-sm btn-lg btn-success">
                        TV:<span class="badge badge-success">On</span>
                        <input type="checkbox" id="shareVideo" checked>
                      </label>
                    </div>
                    <div class="btn-group-toggle p-1" data-toggle="buttons">
                      <label class="btn-sm btn btn-lg btn-success">
                        Light:<span class="badge badge-success">On</span>
                        <input type="checkbox" id="shareAudio" checked>
                      </label>
                    </div>
                    <div class="btn-group-toggle p-1" data-toggle="buttons">
                      <label class="btn-sm btn btn-lg btn-danger">
                        Air Cond:<span class="badge badge-danger">Off</span>
                        <input type="checkbox" id="shareScreen">
                      </label>
                    </div>
                    <div class="btn-group-toggle p-1">
                        <button class="btn-sm btn btn-lg btn-success">Create a meeting</button>
                    </div>
                </div>
            </div>
            <div class="p-0 row no-gutters">
                <div class="p-0 col-12 col-sm-12 col-lg-12 col-xl-12">
                    <ul class="nav nav-pills p-1 d-flex justify-content-around" id="pills-tab" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link active"
                                id="pills-info-tab" data-toggle="pill"
                                href="#pills-info" role="tab" aria-controls="pills-info" aria-selected="true">
                                i
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link"
                                id="pills-member-tab" data-toggle="pill"
                                href="#pills-member" role="tab" aria-controls="pills-member" aria-selected="false">
                                f
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link"
                                id="pills-message-tab" data-toggle="pill"
                                href="#pills-message" role="tab" aria-controls="pills-message" aria-selected="false">
                                c
                            </a>
                        </li>
                    </ul>
                    <div class="tab-content border border-success position-relative" id="pills-tabContent">

                            <div class="tab-pane fade p-0 show active" id="pills-info" role="tabpanel" aria-labelledby="pills-member-tab">
                                <ul class="list-unstyled overflow-auto h-100 scroll-bar">
                                  <li class="media">
                                    a
                                  </li>
                                  <li class="media">
                                    b
                                  </li>
                                  <li class="media">
                                    c
                                  </li>
                                  <li class="media">
                                    a
                                  </li>
                                  <li class="media">
                                    b
                                  </li>
                                  <li class="media">
                                    c
                                  </li>
                                  <li class="media">
                                    a
                                  </li>
                                  <li class="media">
                                    b
                                  </li>
                                  <li class="media">
                                    c
                                  </li>
                                  <li class="media">
                                    a
                                  </li>
                                  <li class="media">
                                    b
                                  </li>
                                  <li class="media">
                                    c
                                  </li>
                                  <li class="media">
                                    a
                                  </li>
                                  <li class="media">
                                    b
                                  </li>
                                  <li class="media">
                                    c
                                  </li>
                  <li class="media">
                                    a
                                  </li>
                                  <li class="media">
                                    b
                                  </li>
                                  <li class="media">
                                    c
                                  </li>
                                </ul>
                            </div>
                            <div class="tab-pane fade p-0" id="pills-member" role="tabpanel" aria-labelledby="pills-member-tab">
                                2
                            </div>
                            <div class="tab-pane fade p-0" id="pills-message" role="tabpanel" aria-labelledby="pills-member-tab">
                                3
                            </div>

                    </div>
                </div>
            </div>
        </div>
    </body>
</html>
</code>```

Output:

Body:
Here is my code:

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

     <video id="selfView" class="h-100 w-100 position-absolute" controls muted>
      <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
     </video>

      TV:On
      <input type="checkbox" id="shareVideo" checked>

      Light:On
      <input type="checkbox" id="shareAudio" checked>

      Air Cond:Off
      <input type="checkbox" id="shareScreen">

      <button class="btn-sm btn btn-lg btn-success">Create a meeting</button>

        i

        f

        c

         a

         b

         c

         a

         b

         c

         a

         b

         c

         a

         b

         c

         a

         b

         c

         a

         b

         c

        2

        3

How can I make the bootstrap media list(i.e line 81) with a scroll bar?

I have using a "position-relative" and "position-absolute" class to make the browser show a scroll bar.

Unfortunately, it does not work.

It is because when I browse the web page with a mobile phone the media list is too long.

Body:
The scrollbar can be added by using a CSS class with these 2 attributes:

overflow-y: scroll

max-height: height;

An example CSS class for scroll bar:

        .scroll-bar {
            overflow-x: scroll;
            overflow-y: scroll;
            max-height: 100px;
        }

Here is the working example with CSS class added to the list:

<html>
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
        <!-- Optional JavaScript -->
        <!-- jQuery first, then Popper.js, then Bootstrap JS -->
        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

        <style>
            .scroll-bar {
                overflow-x: scroll;
                overflow-y: scroll;
                max-height: 100px;
            }
        </style>
    </head>
    <body class="p-1">
        <div class="p-0 container-fluid">
            <div class="p-0 row h-25 no-gutters">
                <div class="p-0 col-12 col-sm-12 col-lg-12 col-xl-12">
                    <video id="selfView" class="h-100 w-100 position-absolute" controls muted>
                        <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
                    </video>
                </div>
            </div>
            <div class="p-0 row no-gutters">
                <div class="d-flex flex-row justify-content-center p-0 col-12 col-sm-12 col-lg-12 col-xl-12">
                    <div class="btn-group-toggle p-1" data-toggle="buttons">
                      <label class="btn btn-sm btn-lg btn-success">
                        TV:<span class="badge badge-success">On</span>
                        <input type="checkbox" id="shareVideo" checked>
                      </label>
                    </div>
                    <div class="btn-group-toggle p-1" data-toggle="buttons">
                      <label class="btn-sm btn btn-lg btn-success">
                        Light:<span class="badge badge-success">On</span>
                        <input type="checkbox" id="shareAudio" checked>
                      </label>
                    </div>
                    <div class="btn-group-toggle p-1" data-toggle="buttons">
                      <label class="btn-sm btn btn-lg btn-danger">
                        Air Cond:<span class="badge badge-danger">Off</span>
                        <input type="checkbox" id="shareScreen">
                      </label>
                    </div>
                    <div class="btn-group-toggle p-1">
                        <button class="btn-sm btn btn-lg btn-success">Create a meeting</button>
                    </div>
                </div>
            </div>
            <div class="p-0 row no-gutters">
                <div class="p-0 col-12 col-sm-12 col-lg-12 col-xl-12">
                    <ul class="nav nav-pills p-1 d-flex justify-content-around" id="pills-tab" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link active"
                                id="pills-info-tab" data-toggle="pill"
                                href="#pills-info" role="tab" aria-controls="pills-info" aria-selected="true">
                                i
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link"
                                id="pills-member-tab" data-toggle="pill"
                                href="#pills-member" role="tab" aria-controls="pills-member" aria-selected="false">
                                f
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link"
                                id="pills-message-tab" data-toggle="pill"
                                href="#pills-message" role="tab" aria-controls="pills-message" aria-selected="false">
                                c
                            </a>
                        </li>
                    </ul>
                    <div class="tab-content border border-success position-relative" id="pills-tabContent">

                            <div class="tab-pane fade p-0 show active" id="pills-info" role="tabpanel" aria-labelledby="pills-member-tab">
                                <ul class="list-unstyled overflow-auto h-100 scroll-bar">
                                  <li class="media">
                                    a
                                  </li>
                                  <li class="media">
                                    b
                                  </li>
                                  <li class="media">
                                    c
                                  </li>
                                  <li class="media">
                                    a
                                  </li>
                                  <li class="media">
                                    b
                                  </li>
                                  <li class="media">
                                    c
                                  </li>
                                  <li class="media">
                                    a
                                  </li>
                                  <li class="media">
                                    b
                                  </li>
                                  <li class="media">
                                    c
                                  </li>
                                  <li class="media">
                                    a
                                  </li>
                                  <li class="media">
                                    b
                                  </li>
                                  <li class="media">
                                    c
                                  </li>
                                  <li class="media">
                                    a
                                  </li>
                                  <li class="media">
                                    b
                                  </li>
                                  <li class="media">
                                    c
                                  </li>
                  <li class="media">
                                    a
                                  </li>
                                  <li class="media">
                                    b
                                  </li>
                                  <li class="media">
                                    c
                                  </li>
                                </ul>
                            </div>
                            <div class="tab-pane fade p-0" id="pills-member" role="tabpanel" aria-labelledby="pills-member-tab">
                                2
                            </div>
                            <div class="tab-pane fade p-0" id="pills-message" role="tabpanel" aria-labelledby="pills-member-tab">
                                3
                            </div>

                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

Output:


问:
Pattern matching object decomposition on list in Vavr
Is there any option to apply object decomposition on vavrs collections?

I.e. something like this code snippet from scala:

```<code>val x = List(1, 2, 3)

val t = x match {
  case List(a, b, c) => (a, b, c)
}
</code>```

(in this example we're converting list to tuple)

I saw some examples similar to my case here https://github.com/vavr-io/vavr/issues/1157 but it looks like the current syntax is different or it is even impossible.

答:
JMPL is simple java library, which could emulate some of the features pattern matching, using Java 8 features.
This library also support deconstruct pattern

```<code>   Figure figure = new Rectangle();

   let(figure, (int w, int h) -> {
      System.out.println("border: " + w + " " + h));
   });

   matches(figure).as(
      Rectangle.class, (int w, int h) -> System.out.println("square: " + (w * h)),
      Circle.class,    (int r)        -> System.out.println("square: " + (2 * Math.PI * r)),
      Else.class,      ()             -> System.out.println("Default square: " + 0)
   );

   foreach(listRectangles, (int w, int h) -> {
      System.out.println("square: " + (w * h));
   });
</code>```

Deconstruct classes must to have one or more extract method(s).
They must to be marked annotation @Extract. Parameters must to be
output. Since primitive and wrappers for primitive types can't to be
pass by reference we must to use wrappers such IntRef, FloatRef and etc.

```<code>   @Extract
   public void deconstruct(IntRef width, IntRef height) {
      width.set(this.width);
      height.set(this.height);
   }
</code>```

Body:
Is there any option to apply object decomposition on vavrs collections?

I.e. something like this code snippet from scala:

val x = List(1, 2, 3)

val t = x match {
  case List(a, b, c) => (a, b, c)
}

(in this example we're converting list to tuple)

I saw some examples similar to my case here https://github.com/vavr-io/vavr/issues/1157 but it looks like the current syntax is different or it is even impossible.

Body:
JMPL is simple java library, which could emulate some of the features pattern matching, using Java 8 features.
This library also support deconstruct pattern

   Figure figure = new Rectangle();

   let(figure, (int w, int h) -> {
      System.out.println("border: " + w + " " + h));
   });

   matches(figure).as(
      Rectangle.class, (int w, int h) -> System.out.println("square: " + (w * h)),
      Circle.class,    (int r)        -> System.out.println("square: " + (2 * Math.PI * r)),
      Else.class,      ()             -> System.out.println("Default square: " + 0)
   );

   foreach(listRectangles, (int w, int h) -> {
      System.out.println("square: " + (w * h));
   });

Deconstruct classes must to have one or more extract method(s).
They must to be marked annotation @Extract. Parameters must to be
output. Since primitive and wrappers for primitive types can't to be
pass by reference we must to use wrappers such IntRef, FloatRef and etc.

   @Extract
   public void deconstruct(IntRef width, IntRef height) {
      width.set(this.width);
      height.set(this.height);
   }


问:
filenotfound issues in eclipse on Mac OSX
Hi
I have a java class which is working fine in windows but not in Mac OSX snow leopard. I am using Eclipse on both operating systems. On Mac OSX its throwing file not found exception.

Basically I am trying to read a file using BufferedReader and FileReader and I put my file in \resources\

```<code>import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileContents {

    /**
     * @param args
     */
    public static void main(String[] args) {

        BufferedReader br = null;
        String line = "";
        try {
            br = new BufferedReader(new FileReader("resources\\abc"));
            while((line = br.readLine())!= null)
            {
                System.out.println("Read :::  "+line+"  From File.");
            }
        } catch (FileNotFoundException fne) {
            fne.printStackTrace();
        }catch (IOException ioe) {
            ioe.printStackTrace();
        }

    }

}
</code>```

On Mac it is giving

```<code>java.io.FileNotFoundException: resources\abc (No such file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:106)
    at java.io.FileInputStream.<init>(FileInputStream.java:66)
    at java.io.FileReader.<init>(FileReader.java:41)
    at ReadFileContents.main(ReadFileContents.java:18)
</code>```

Do I need any special configuration in my eclipse to get this working...

答: Mac uses forward slashes: "resources/abc".  (This will actually work on Windows as well.  Only the command line interpreter requires backslashes.)

Body:
Hi
I have a java class which is working fine in windows but not in Mac OSX snow leopard. I am using Eclipse on both operating systems. On Mac OSX its throwing file not found exception.

Basically I am trying to read a file using BufferedReader and FileReader and I put my file in \resources\

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileContents {

    /**
     * @param args
     */
    public static void main(String[] args) {

        BufferedReader br = null;
        String line = "";
        try {
            br = new BufferedReader(new FileReader("resources\\abc"));
            while((line = br.readLine())!= null)
            {
                System.out.println("Read :::  "+line+"  From File.");
            }
        } catch (FileNotFoundException fne) {
            fne.printStackTrace();
        }catch (IOException ioe) {
            ioe.printStackTrace();
        }

    }

}

On Mac it is giving

java.io.FileNotFoundException: resources\abc (No such file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:106)
    at java.io.FileInputStream.<init>(FileInputStream.java:66)
    at java.io.FileReader.<init>(FileReader.java:41)
    at ReadFileContents.main(ReadFileContents.java:18)

Do I need any special configuration in my eclipse to get this working...


问:
VSCode hot reload for Flutter does not work
I'm on VSCode right now working on my flutter application when hot reload just stops working, right in the middle of my development. I have absolutely no idea why this happens, I had no issue with this before at all in the past. If it helps anyone, I'm working on the second page of my app, which you get to via a route on the first page. Is this why hot reload isn't working? If it isn't can someone tell me why it doesn't work? This is really annoying and hindering progress on my app. Thanks!

Restarting my computer, and restarting the debugging. I'm on a Macbook Pro 2015 running macOS Mojave Version 10.14.2 if that helps.

There isn't really any code to show, it's not code related. It's VSCode or Flutter.

I expect the hot reload to work, but it doesn't.

答: first save your project then hot reload it.</p>


问:
Laravel Distinct query not working in my project
In my laravel project am trying to show google map locator, there are various kinds of services, each services may or may not be available in various clinics in various locations.Am trying to make a ajax call to my controller by passing service to fetch clinic and location details.

Problem is that if Clinic A have service X  & Service Y in location X, then it is fetching Clinc A details multiple times.I want to show the clinc details only once.

Following is my code

```<code>public function mapService(Request $request)
    {
        $postdata = Request::all();
        // Start XML file, create parent node
        $dom = new \DOMDocument("1.0");
        $node = $dom->createElement("markers");
        $parnode = $dom->appendChild($node);

        $services_id = isset($postdata['id'])? $postdata['id']:'';

        $apiKey = $postdata['apikey'];

        if( $services_id ) {
            $loc_services = Clinic::select('*')
                        ->join('locations', 'locations.clinicID', '=', 'clinics.clinicID')
                        ->join('location_services', 'location_services.locationID', '=', 'locations.locationID')
                        ->join('services', 'services.serviceID', '=', 'location_services.serviceID')
                        ->whereIn('services.serviceID',$services_id)
                        ->where('clinics.api_key','=',$apiKey)
                        ->distinct()
                        ->get();
        }else {
            $loc_services =Clinic::select('*')
                        ->join('locations', 'locations.clinicID', '=', 'clinics.clinicID')
                        ->where('clinics.api_key','=',$apiKey)
                        ->get();
        }

        foreach ($loc_services as $loc_service) {
            $node = $dom->createElement("marker");
            $newnode = $parnode->appendChild($node);
            $newnode->setAttribute("id", $loc_service->locationID);
            $newnode->setAttribute("locationName", $loc_service->locationName);
            $newnode->setAttribute("locationAddress1", $loc_service->locationAddress1);
            $newnode->setAttribute("locationCity", $loc_service->locationCity);
            $newnode->setAttribute("locationState", $loc_service->locationState);
            $newnode->setAttribute("locationZip", $loc_service->locationZip);
            $newnode->setAttribute("locationLat", $loc_service->locationLat);
            $newnode->setAttribute("locationLong", $loc_service->locationLong);
            $newnode->setAttribute("serviceName", $loc_service->serviceName);
            $newnode->setAttribute("clinicName", $loc_service->clinicName);
            $newnode->setAttribute("distance", $loc_service->distance);
            $newnode->setAttribute("cname", $loc_service->clinicName);
            $newnode->setAttribute("clinicFname", $loc_service->clinicFname);
            $newnode->setAttribute("clinicLname", $loc_service->clinicLname);
            $newnode->setAttribute("clinicAddress", $loc_service->clinicAddress);
            $newnode->setAttribute("clinicCity", $loc_service->clinicCity);
            $newnode->setAttribute("clinicPhone", $loc_service->clinicPhone);
            $newnode->setAttribute("clinicstate", $loc_service->clinicState);
            $newnode->setAttribute("cliniczip", $loc_service->clinicZip);
            $newnode->setAttribute("clinicemail", $loc_service->clinicEmail);
        }

        echo $dom->saveXML();
        //$view = \View::make('api.getwazemap', ['maplocservices'=>$loc_services]);

    }
</code>```

答:
you are applying 'distinct' on all your result ... this would be ineffective ..
you should apply 'distinct' only on  clinics table

try change to this:

```<code>$loc_services = Clinic::select('clinics.*').....
</code>```

... it should work

Body:
In my laravel project am trying to show google map locator, there are various kinds of services, each services may or may not be available in various clinics in various locations.Am trying to make a ajax call to my controller by passing service to fetch clinic and location details.

Problem is that if Clinic A have service X  & Service Y in location X, then it is fetching Clinc A details multiple times.I want to show the clinc details only once.

Following is my code

public function mapService(Request $request)
    {
        $postdata = Request::all();
        // Start XML file, create parent node
        $dom = new \DOMDocument("1.0");
        $node = $dom->createElement("markers");
        $parnode = $dom->appendChild($node);

        $services_id = isset($postdata['id'])? $postdata['id']:'';

        $apiKey = $postdata['apikey'];

        if( $services_id ) {
            $loc_services = Clinic::select('*')
                        ->join('locations', 'locations.clinicID', '=', 'clinics.clinicID')
                        ->join('location_services', 'location_services.locationID', '=', 'locations.locationID')
                        ->join('services', 'services.serviceID', '=', 'location_services.serviceID')
                        ->whereIn('services.serviceID',$services_id)
                        ->where('clinics.api_key','=',$apiKey)
                        ->distinct()
                        ->get();
        }else {
            $loc_services =Clinic::select('*')
                        ->join('locations', 'locations.clinicID', '=', 'clinics.clinicID')
                        ->where('clinics.api_key','=',$apiKey)
                        ->get();
        }

        foreach ($loc_services as $loc_service) {
            $node = $dom->createElement("marker");
            $newnode = $parnode->appendChild($node);
            $newnode->setAttribute("id", $loc_service->locationID);
            $newnode->setAttribute("locationName", $loc_service->locationName);
            $newnode->setAttribute("locationAddress1", $loc_service->locationAddress1);
            $newnode->setAttribute("locationCity", $loc_service->locationCity);
            $newnode->setAttribute("locationState", $loc_service->locationState);
            $newnode->setAttribute("locationZip", $loc_service->locationZip);
            $newnode->setAttribute("locationLat", $loc_service->locationLat);
            $newnode->setAttribute("locationLong", $loc_service->locationLong);
            $newnode->setAttribute("serviceName", $loc_service->serviceName);
            $newnode->setAttribute("clinicName", $loc_service->clinicName);
            $newnode->setAttribute("distance", $loc_service->distance);
            $newnode->setAttribute("cname", $loc_service->clinicName);
            $newnode->setAttribute("clinicFname", $loc_service->clinicFname);
            $newnode->setAttribute("clinicLname", $loc_service->clinicLname);
            $newnode->setAttribute("clinicAddress", $loc_service->clinicAddress);
            $newnode->setAttribute("clinicCity", $loc_service->clinicCity);
            $newnode->setAttribute("clinicPhone", $loc_service->clinicPhone);
            $newnode->setAttribute("clinicstate", $loc_service->clinicState);
            $newnode->setAttribute("cliniczip", $loc_service->clinicZip);
            $newnode->setAttribute("clinicemail", $loc_service->clinicEmail);
        }

        echo $dom->saveXML();
        //$view = \View::make('api.getwazemap', ['maplocservices'=>$loc_services]);

    }

Body:
you are applying 'distinct' on all your result ... this would be ineffective ..
you should apply 'distinct' only on  clinics table

try change to this:

$loc_services = Clinic::select('clinics.*').....

... it should work


问:
RTL passwords copy/ pasting issue
I'm developing a portal in RTL language with a password generator in php/ javascript that generates randomly passwords like

```<code>F1O=a@9@
</code>```

or

```<code>7$kf8F=og!$
</code>```

However if i paste such passwords with special chars into the RTL field they are completly wrong.

A fiddle of the issue can be found HERE.

How to overcome such an issue?
Excluding special chars in passwords is not an option as it would decrease security.

Thanks for any hint in advance.

答:
Thats how it works, if you simply want text on the right, use css instead.

RTL FIELD
<input type="text" value="">```

Title: RTL passwords copy/ pasting issue

Body:
I'm developing a portal in RTL language with a password generator in php/ javascript that generates randomly passwords like

F1O=a@9@

or

7$kf8F=og!$

However if i paste such passwords with special chars into the RTL field they are completly wrong.

A fiddle of the issue can be found HERE.

How to overcome such an issue?
Excluding special chars in passwords is not an option as it would decrease security.

Thanks for any hint in advance.

Body:
Thats how it works, if you simply want text on the right, use css instead.

<style>
  input[type="text"] {
    text-align: right
  }
</style>

<label>RTL FIELD</label>
<input type="text" value="">


问:
Error when trying to use React useref in typescript
Using React and typescript I am building a tabs component where you can scroll through tab links left to right at the top with overflow: scroll set. This works with a trackpad but I need to implement a method for mouse users so they can click and scroll much like in this codepen: https://codepen.io/thenutz/full/VwYeYEE
the code I have so far for the tab Links which sits above tab Content looks like this:

      {React.Children.map(children, (child, index) => ( //LOOPS THROUGH TAB LINKS HERE ))}

```

<p>The tabLinks div is the div that needs to be scrolled horizontally by both a trackpad and mouse(click and drag)</p>

<p>my first attempt at doing this was using react useRef to creat a ref for div with ClassName 'tabLinks' </p>

```const ref = React.useRef<HTMLDivElement>(null)
```

<p>This ref was then passed to the tabLinks div and I tried to implement the onMouseDown events as per the codepen example but ran into this error below: </p>

```Property 'offsetLeft' does not exist on type 'RefObject<HTMLDivElement>'
```

<p>Any help would be really appreciated.</p>

<p>EDIT: </p>

<p>This is what I have tried so far:</p>

<pre class="lang-js prettyprint-override"><code>const ref = React.useRef<HTMLDivElement>(null)
  let startX
  let scrollLeft

<div className='container'>
  <div className='flex-row'
    sx={{ overflow: 'scroll',
    '::-webkit-scrollbar': { display: 'none' },
    display: flex,
    flexDirection: 'row',
    flexWrap: 'no-wrap' }}>
        <div
          className='items'
          sx={{
            display: 'flex',
            flexDirection: 'row',
            flexWrap: 'no-wrap'
           }}
          ref={ref}
          onMouseDown={e => {
            isDown= true
            const offset = ref.current?.offsetLeft || 0
            startX = e.pageX - offset
            scrollLeft = ref.current?.scrollLeft
          }}
          onMouseUp={e => {
            isDown = false;
          }}
          onMouseLeave={e => {
            isDown = false
          }}
          onMouseMove={e => {
            if(!isDown) return;
            e.preventDefault();
            const x = e.pageX - (ref.current?.offsetLeft ?? 0)
            const walk = (x - startX) * 3; //scroll-fast
            ref.scrollLeft = scrollLeft - walk
            console.log(walk)
          }}
        >
      {React.Children.map(children, (child, index) => ( //LOOPS THROUGH TAB LINKS HERE ))}
    </div>
  </div>
</div>
</code>```

I now am getting this error

```<code>Uncaught TypeError: Cannot add property scrollLeft, object is not extensible
    at onMouseMove (index.tsx:102)
    at HTMLUnknownElement.callCallback (react-dom.development.js:149)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
    at invokeGuardedCallback (react-dom.development.js:256)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:270)
    at executeDispatch (react-dom.development.js:561)
    at executeDispatchesInOrder (react-dom.development.js:583)
    at executeDispatchesAndRelease (react-dom.development.js:680)
    at executeDispatchesAndReleaseTopLevel (react-dom.development.js:688)
    at forEachAccumulated (react-dom.development.js:662)
</code>```

答:
const offset = ref.current?.offsetLeft ?? 0;

And the same for:

scrollLeft = ref.current?.scrollLeft ?? 0;

This makes sure that both variables have a numeric value when the current ref is null.

You will need the null coalescing operator. If you don’t have that available then use:

const offset = ref.current?.offsetLeft || 0;
scrollLeft = ref.current?.scrollLeft || 0;

Body:
Using React and typescript I am building a tabs component where you can scroll through tab links left to right at the top with overflow: scroll set. This works with a trackpad but I need to implement a method for mouse users so they can click and scroll much like in this codepen: https://codepen.io/thenutz/full/VwYeYEE
the code I have so far for the tab Links which sits above tab Content looks like this:

      {React.Children.map(children, (child, index) => ( //LOOPS THROUGH TAB LINKS HERE ))}

The tabLinks div is the div that needs to be scrolled horizontally by both a trackpad and mouse(click and drag)

my first attempt at doing this was using react useRef to creat a ref for div with ClassName 'tabLinks'

const ref = React.useRef<HTMLDivElement>(null)

This ref was then passed to the tabLinks div and I tried to implement the onMouseDown events as per the codepen example but ran into this error below:

Property 'offsetLeft' does not exist on type 'RefObject<HTMLDivElement>'

Any help would be really appreciated.

EDIT:

This is what I have tried so far:

const ref = React.useRef<HTMLDivElement>(null)
  let startX
  let scrollLeft

 {
            isDown= true
            const offset = ref.current?.offsetLeft || 0
            startX = e.pageX - offset
            scrollLeft = ref.current?.scrollLeft
          }}
          onMouseUp={e => {
            isDown = false;
          }}
          onMouseLeave={e => {
            isDown = false
          }}
          onMouseMove={e => {
            if(!isDown) return;
            e.preventDefault();
            const x = e.pageX - (ref.current?.offsetLeft ?? 0)
            const walk = (x - startX) * 3; //scroll-fast
            ref.scrollLeft = scrollLeft - walk
            console.log(walk)
          }}
        >
      {React.Children.map(children, (child, index) => ( //LOOPS THROUGH TAB LINKS HERE ))}

I now am getting this error

Uncaught TypeError: Cannot add property scrollLeft, object is not extensible
    at onMouseMove (index.tsx:102)
    at HTMLUnknownElement.callCallback (react-dom.development.js:149)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
    at invokeGuardedCallback (react-dom.development.js:256)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:270)
    at executeDispatch (react-dom.development.js:561)
    at executeDispatchesInOrder (react-dom.development.js:583)
    at executeDispatchesAndRelease (react-dom.development.js:680)
    at executeDispatchesAndReleaseTopLevel (react-dom.development.js:688)
    at forEachAccumulated (react-dom.development.js:662)


答:
If docker ps shows nothing, then you must already have a stopped container called App. When a container stops, it remains, so that it can be started again.

As commented above docker ps -a will show all containers both running and stopped.

To remove the stopped container, use docker rm App.

It's a good idea when manually running containers, especially whilst debugging (so you're going to stop and start many times) to use the --rm flag. This will ensure that the container is removed when it's stopped.

Title: Container not starting


问:
INITIAL_STATE injection token with new createreducer function
With the new createReducer function in ngrx8 I'm trying to work out how you would use it with the INITIAL_STATE injection token from '@ngrx/store';

In the old world you could do something like:

providers: [{ provide: INITIAL_STATE, useValue: { initialState: initialState } }]

and this would hydrate the state parameter of the reducer function to be your initial state

However as the first parameter is the initial state, I'm trying to work out how you would inject the INITIAL_STATE?

Cheers

James

答:
As stated in your comment, you try to use the initial state token in a feature module - unfortunately this isn't possible. The token can only be used in the root module:

The INITIAL_STATE token is only used to set the initial state of the root module.
  You could use the OnInitEffect lifecycle or the @ngrx/store/update-reducers action to dispatch a "set action" to set the state of the feature module in a reducer.

See this Github Link for more info.