问:
How to avoid line wrap in a form generated with typescript?
I am working on a ReactJS project. The goal is simple: I want all three <FormItem> appear in one single line, without wrap. Instead, I obtain an output as follows:

In myComponent.tsx I have the following render() function:

```<code>render() {
  const { getFieldDecorator } = this.props.form;
  const formItemLayoutType = {
          labelCol: { span: 1, offset: 0 },
          wrapperCol: { span: 3, offset: 0 },
  };
  const myForm = {
         display: "inline",
         whiteSpace: "nowrap"
  } as React.CSSProperties;

  return (
    <Form onSubmit={this.handleSubmit} style={myForm}>
     <span>
      <FormItem
       // {...formItemLayoutType}  // originally, this was not commented out
       hasFeedback
      >
         {getFieldDecorator('select', { valuePropName: "fileType" })(
                        <Select placeholder="Select file type" style={{ width: "150px" }}>
                            <Option value="PD">Probabilty of default</Option>
                            <Option value="FX">Exchange Rate</Option>
                        </Select>
                        )}
      </FormItem>
      <FormItem>
         <Button type="primary" htmlType="submit"
                 disabled={this.disabledImportButtonChecker()}>Import</Button>
      </FormItem>
     </span>
    </Form>
  );
 }
}
</code>```

I added the  and the style={myForm}, the rest of the code is historic. I just cannot figure out why it still looks as follows rather than everything horizontally arranged.

References

Prevent <form> line break between two <form> tags  suggests to use display: inline.

https://alligator.io/css/prevent-line-break/

答:
Change the  to a
, and give it a style of display: flex;

See example (I added the style inline for simplicity, you should place it the way you do all your styles)

```<code>//** inline style for simplicity **//
<span style={{display:"flex"}}>
    <FormItem
        // {...formItemLayoutType}  // originally, this was not commented out
        hasFeedback
    >
        {getFieldDecorator('select', { valuePropName: "fileType" })(
            <Select placeholder="Select file type" style={{ width: "150px" }}>
                <Option value="PD">Probabilty of default</Option>
                <Option value="FX">Exchange Rate</Option>
            </Select>
        )}
    </FormItem>
    <FormItem>
        <Button type="primary" htmlType="submit"
            disabled={this.disabledImportButtonChecker()}>Import</Button>
    </FormItem>
</span>
</code>```

Body:
I am working on a ReactJS project. The goal is simple: I want all three <FormItem> appear in one single line, without wrap. Instead, I obtain an output as follows:

In myComponent.tsx I have the following render() function:

render() {
  const { getFieldDecorator } = this.props.form;
  const formItemLayoutType = {
          labelCol: { span: 1, offset: 0 },
          wrapperCol: { span: 3, offset: 0 },
  };
  const myForm = {
         display: "inline",
         whiteSpace: "nowrap"
  } as React.CSSProperties;

  return (
    <Form onSubmit={this.handleSubmit} style={myForm}>

      <FormItem
       // {...formItemLayoutType}  // originally, this was not commented out
       hasFeedback
      >
         {getFieldDecorator('select', { valuePropName: "fileType" })(
                        <Select placeholder="Select file type" style={{ width: "150px" }}>
                            <Option value="PD">Probabilty of default</Option>
                            <Option value="FX">Exchange Rate</Option>
                        </Select>
                        )}
      </FormItem>
      <FormItem>
         <Button type="primary" htmlType="submit"
                 disabled={this.disabledImportButtonChecker()}>Import</Button>
      </FormItem>

    </Form>
  );
 }
}

I added the  and the style={myForm}, the rest of the code is historic. I just cannot figure out why it still looks as follows rather than everything horizontally arranged.

References

Prevent <form> line break between two <form> tags  suggests to use display: inline.

https://alligator.io/css/prevent-line-break/

Body:
Change the <span> to a <div>, and give it a style of display: flex;

See example (I added the style inline for simplicity, you should place it the way you do all your styles)

//** inline style for simplicity **//
<span style={{display:"flex"}}>
    <FormItem
        // {...formItemLayoutType}  // originally, this was not commented out
        hasFeedback
    >
        {getFieldDecorator('select', { valuePropName: "fileType" })(
            <Select placeholder="Select file type" style={{ width: "150px" }}>
                <Option value="PD">Probabilty of default</Option>
                <Option value="FX">Exchange Rate</Option>
            </Select>
        )}
    </FormItem>
    <FormItem>
        <Button type="primary" htmlType="submit"
            disabled={this.disabledImportButtonChecker()}>Import</Button>
    </FormItem>
</span>


来源: stackexchange

问:
numpy Loadtxt function seems to be consuming too much memory
When I load an array using numpy.loadtxt, it seems to take too much memory.  E.g.

```<code>a = numpy.zeros(int(1e6))
</code>```

causes an increase of about 8MB in memory (using htop, or just 8bytes*1million \approx 8MB).  On the other hand, if I save and then load this array

```<code>numpy.savetxt('a.csv', a)
b = numpy.loadtxt('a.csv')
</code>```

my memory usage increases by about 100MB!  Again I observed this with htop.  This was observed while in the iPython shell, and also while stepping through code using Pdb++.

Any idea what's going on here?

After reading jozzas's answer, I realized that if I know ahead of time the array size, there is a much more memory efficient way to do things if say 'a' was an mxn array:

```<code>b = numpy.zeros((m,n))
with open('a.csv', 'r') as f:
    reader = csv.reader(f)
    for i, row in enumerate(reader):
        b[i,:] = numpy.array(row)
</code>```

答:
Here is what I ended up doing to solve this problem.  It works even if you don't know the shape ahead of time.  This performs the conversion to float first, and then combines the arrays (as opposed to @JohnLyon's answer, which combines the arrays of string then converts to float).  This used an order of magnitude less memory for me, although perhaps was a bit slower.  However, I literally did not have the requisite memory to use np.loadtxt, so if you don't have sufficient memory, then this will be better:

```<code>def numpy_loadtxt_memory_friendly(the_file, max_bytes = 1000000, **loadtxt_kwargs):
    numpy_arrs = []
    with open(the_file, 'rb') as f:
        i = 0
        while True:
            print(i)
            some_lines = f.readlines(max_bytes)
            if len(some_lines) == 0:
                break
            vec = np.loadtxt(some_lines, **loadtxt_kwargs)
            if len(vec.shape) < 2:
                vec = vec.reshape(1,-1)
            numpy_arrs.append(vec)
            i+=len(some_lines)
    return np.concatenate(numpy_arrs, axis=0)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When I load an array using numpy.loadtxt, it seems to take too much memory.  E.g.

a = numpy.zeros(int(1e6))

causes an increase of about 8MB in memory (using htop, or just 8bytes*1million \approx 8MB).  On the other hand, if I save and then load this array

numpy.savetxt('a.csv', a)
b = numpy.loadtxt('a.csv')

my memory usage increases by about 100MB!  Again I observed this with htop.  This was observed while in the iPython shell, and also while stepping through code using Pdb++.

Any idea what's going on here?

After reading jozzas's answer, I realized that if I know ahead of time the array size, there is a much more memory efficient way to do things if say 'a' was an mxn array:

b = numpy.zeros((m,n))
with open('a.csv', 'r') as f:
    reader = csv.reader(f)
    for i, row in enumerate(reader):
        b[i,:] = numpy.array(row)

Body:
Here is what I ended up doing to solve this problem.  It works even if you don't know the shape ahead of time.  This performs the conversion to float first, and then combines the arrays (as opposed to @JohnLyon's answer, which combines the arrays of string then converts to float).  This used an order of magnitude less memory for me, although perhaps was a bit slower.  However, I literally did not have the requisite memory to use np.loadtxt, so if you don't have sufficient memory, then this will be better:

def numpy_loadtxt_memory_friendly(the_file, max_bytes = 1000000, **loadtxt_kwargs):
    numpy_arrs = []
    with open(the_file, 'rb') as f:
        i = 0
        while True:
            print(i)
            some_lines = f.readlines(max_bytes)
            if len(some_lines) == 0:
                break
            vec = np.loadtxt(some_lines, **loadtxt_kwargs)
            if len(vec.shape) < 2:
                vec = vec.reshape(1,-1)
            numpy_arrs.append(vec)
            i+=len(some_lines)
    return np.concatenate(numpy_arrs, axis=0)

ContentLicense: CC BY-SA 4.0


问:
bash: ./remoteServer .o: cannot execute binary file: Exec format error
I am trying to run the c program remoteServer.c. I compiled it using a Makefile. When i try to run it with ./remoteServer.o I get the following error. I read that it could be cause of different architecture but I saw that both were x86-64. I am running ubuntu 18.04.03 on a VM. The code for the make file is after the commands. Also i used chmod 777 on both the .c and .o files.

```<code>isidoros@isidoros-VirtualBox:~/choice$ ./remoteServer.o

bash: ./remoteServer.o: cannot execute binary file: Exec format error

isidoros@isidoros-VirtualBox:~/choice$ file remoteServer.c

remoteServer.c: C source, ASCII text

isidoros@isidoros-VirtualBox:~/choice$ file remoteServer.o

remoteServer.o: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), with debug_info, not stripped

isidoros@isidoros-VirtualBox:~/choice$ uname -m

x86_64
</code>```

Makefile:

```<code>OBJS    = remoteServer.o

SOURCE  = remoteServer.c

HEADER  =

OUT = make

CC   = gcc

FLAGS    = -g -c -Wall

LFLAGS   =

all: $(OBJS)
    $(CC) -g $(OBJS) -o $(OUT) $(LFLAGS)

remoteServer.o: remoteServer.c
    $(CC) $(FLAGS) remoteServer.c

clean:
    rm -f $(OBJS) $(OUT)
</code>```

答:
Do note that gcc -c compiles source files without linking.

Then, consider that "Compilation refers to the processing of source code files (.c, .cc, or .cpp) and the creation of an 'object' file. This step doesn't create anything the user can actually run. " reference

Meanwhile: "Linking refers to the creation of a single executable file from multiple object files."

So, you probably wanted to link the program, even if it contained a single source file (from your perspective, that might depend on libraries you are including).

I also think that your makefile is trying to name the executable as "make" which might be a problem, since you are probably calling the GNU make program to compile you code.

Body:
I am trying to run the c program remoteServer.c. I compiled it using a Makefile. When i try to run it with ./remoteServer.o I get the following error. I read that it could be cause of different architecture but I saw that both were x86-64. I am running ubuntu 18.04.03 on a VM. The code for the make file is after the commands. Also i used chmod 777 on both the .c and .o files.

isidoros@isidoros-VirtualBox:~/choice$ ./remoteServer.o

bash: ./remoteServer.o: cannot execute binary file: Exec format error

isidoros@isidoros-VirtualBox:~/choice$ file remoteServer.c

remoteServer.c: C source, ASCII text

isidoros@isidoros-VirtualBox:~/choice$ file remoteServer.o

remoteServer.o: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), with debug_info, not stripped

isidoros@isidoros-VirtualBox:~/choice$ uname -m

x86_64

Makefile:

OBJS    = remoteServer.o

SOURCE  = remoteServer.c

HEADER  =

OUT = make

CC   = gcc

FLAGS    = -g -c -Wall

LFLAGS   =

all: $(OBJS)
    $(CC) -g $(OBJS) -o $(OUT) $(LFLAGS)

remoteServer.o: remoteServer.c
    $(CC) $(FLAGS) remoteServer.c

clean:
    rm -f $(OBJS) $(OUT)


问:
Vertical centering working in almost every browser, but not in IE7
It's actually two part question regarding my simple page (that will be replaced some day with real content), HTML+CSS boilerplate used there for vertical centering and IE7.

http://engitize.net/

Can anyone provide detailed explanation why the page is displayed correctly in non-IE browsers (Chrome, Fx, Opera), almost all semi-recent to recent IEs (IE5.5, IE6, IE8, IE9), but not in IE7?

I am especially interested in: it works in IE6, yet it doesn't work in IE7, because... kind of explanation.

What should be changed to make div#c properly centered vertically in IE7?

I am using specific height for div#c, but used boilerplate is height-agnostic and fix should preserve this feature.

Spoiling other browsers is not an option, unless it's IE5.5 (ok, IE6 too, but only if it is really unavoidable).

Changing <!DOCTYPE html> and turning IEs into quirks mode is also not accepted (and it's a pretty bad practice for newly developed pages).

If you don't have IE7 (just as I), you can visit http://ipinfo.info/netrenderer/ or http://browserling.com/, paste URL there and choose IE7 to see the problem yourself.

Because the page will change after accepting some answer, I'm providing snapshot of relevant HTML and CSS parts from it (with logo URL changed to be absolute).

```<code><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
html, body { height: 100%; }
body { background-color: #fff; color: #000; margin: 0px; padding: 0px; }
div { margin: 0px; padding: 0px; }
#outer { position: relative; width: 100%; height: 100%; overflow: visible; }
#outer[id] { display: table; position: static; }
#middle { position: absolute; top: 50%; width: 100%; text-align: center; } /* for explorer only*/
#middle[id] { display: table-cell; vertical-align: middle; position: static; }
#c { position: relative; top: -50%; } /* for explorer only */
#c { width: 385px; height: 120px; margin-left: auto; margin-right: auto; }
#c { background-image: url(http://engitize.net/engitize.png); background-repeat: no-repeat; background-position: center top; }
#c div { position: relative; top: 100px; width: 100%; color: #666; font-weight: bold; font-family: serif; font-size: 12px; text-align: right; }
#footer { width: 100%; text-align: center; height: 15px; padding: 5px 0 0 0; margin: -20px auto 0 auto; border: 0; background-color: #def; }
#footer div { padding: 0px 5px 0px 5px; text-align: right; font-size: 10px; font-family: sans-serif; }
a { text-decoration: none; color: #006; }
a:hover { color: #00c; }
p { margin: 0px; padding: 0px; }
</style>
</head>
<body>
<div id="outer"><div id="middle"><div id="c"><div>
because history is important!
</div></div></div></div>
<div id="footer"><div>
<p style="float:left;"><strong>Przemysław Pawełczyk</strong>'s imprint | Coming in 2012!</p>
<p style="float:right;"><a href="http://przemoc.net/">Przemoc's network</a></p>
</div></div>
</body>
</html>
</code>```

答:
It's the <!DOCTYPE>.

IE6 & 7 were a little flaky with that (that's what I've read, anyway).

If you do the following, you'll see things come around - with your code (no edits, save for a couple borders to see what's happening).

Here's what I did:

Deleted your <!DOCTYPE>

Added to your DIV {} CSS line - border:1px dotted gray

At your "outer", "middle", and "c" divs, a threw an inline border-color just to see which was which.

Hit Refresh

Then pasted <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">, and hit Refresh again. Looked fine to me. Centered vertically, horizontally.

As of April 20, 2011 W3C states <!DOCTYPE HTML> as "Not a Standard". Certainly, IE6/7 have no idea what that tag means. http://www.w3.org/QA/2002/04/valid-dtd-list.html

Body:
It's actually two part question regarding my simple page (that will be replaced some day with real content), HTML+CSS boilerplate used there for vertical centering and IE7.

http://engitize.net/

Can anyone provide detailed explanation why the page is displayed correctly in non-IE browsers (Chrome, Fx, Opera), almost all semi-recent to recent IEs (IE5.5, IE6, IE8, IE9), but not in IE7?

I am especially interested in: it works in IE6, yet it doesn't work in IE7, because... kind of explanation.

What should be changed to make div#c properly centered vertically in IE7?

I am using specific height for div#c, but used boilerplate is height-agnostic and fix should preserve this feature.

Spoiling other browsers is not an option, unless it's IE5.5 (ok, IE6 too, but only if it is really unavoidable).

Changing <!DOCTYPE html> and turning IEs into quirks mode is also not accepted (and it's a pretty bad practice for newly developed pages).

If you don't have IE7 (just as I), you can visit http://ipinfo.info/netrenderer/ or http://browserling.com/, paste URL there and choose IE7 to see the problem yourself.

Because the page will change after accepting some answer, I'm providing snapshot of relevant HTML and CSS parts from it (with logo URL changed to be absolute).

<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

because history is important!

Przemysław Pawełczyk's imprint | Coming in 2012!

Przemoc's network


问:
Combine multiple conditions with Having clause
Given this user and User's items table:

With this select below I'm able to get the candidates that have both item 3 and 4:

```<code>Select
     U.Id,
     U.[Name],
     STRING_AGG(UI.ItemId, ',') as Items
from Users U
     Left Join UserItems UI on UI.UserId = U.Id
Where (
     UI.ItemId IN (3, 4)
)
Group By U.Id, U.[Name]
Having Count(*) = 2
</code>```

But how can I get all candidates using more conditions?
For example:

UI.ItemId IN (2, 7) OR UI.ItemId IN (3,4) OR UI.ItemId = 2

Any idea on how to solve this?

答:
You can use aggregation as follows:

```<code>select
    u.id,
    u.name,
    string_agg(i.itemId, ',') items
from users u
left join userItems i on i.userId = u.id
group by u.id, u.name
having
    max(case when i.itemId = 3 then 1 end) = 1
    and max(case when i.itemId = 4 then 1 end) = 1
</code>```

You can easily expand the having clause with more combinations, like:

```<code>having
    -- users that have both items 3 and 4
    (
        max(case when i.itemId = 3 then 1 end) = 1
        and max(case when i.itemId = 4 then 1 end) = 1
    )
    -- users that have both items 2 and 7
    or (
        max(case when i.itemId = 2 then 1 end) = 1
        and max(case when i.itemId = 7 then 1 end) = 1
   )
    -- users that have items 1
   or max(case when i.itemId = 1 then 1 end) = 1
</code>```

Body:
Given this user and User's items table:

With this select below I'm able to get the candidates that have both item 3 and 4:

Select
     U.Id,
     U.[Name],
     STRING_AGG(UI.ItemId, ',') as Items
from Users U
     Left Join UserItems UI on UI.UserId = U.Id
Where (
     UI.ItemId IN (3, 4)
)
Group By U.Id, U.[Name]
Having Count(*) = 2

But how can I get all candidates using more conditions?
For example:

UI.ItemId IN (2, 7) OR UI.ItemId IN (3,4) OR UI.ItemId = 2

Any idea on how to solve this?

Body:
You can use aggregation as follows:

select
    u.id,
    u.name,
    string_agg(i.itemId, ',') items
from users u
left join userItems i on i.userId = u.id
group by u.id, u.name
having
    max(case when i.itemId = 3 then 1 end) = 1
    and max(case when i.itemId = 4 then 1 end) = 1

You can easily expand the having clause with more combinations, like:

having
    -- users that have both items 3 and 4
    (
        max(case when i.itemId = 3 then 1 end) = 1
        and max(case when i.itemId = 4 then 1 end) = 1
    )
    -- users that have both items 2 and 7
    or (
        max(case when i.itemId = 2 then 1 end) = 1
        and max(case when i.itemId = 7 then 1 end) = 1
   )
    -- users that have items 1
   or max(case when i.itemId = 1 then 1 end) = 1


答:
```<code>DECLARE @ids TABLE (id INT)
INSERT INTO @ids
VALUES (1), (3)

Select
     U.Id,
     U.[Name],
     STRING_AGG(UI.ItemId, ',') as Items
from Users U
     Left Join UserItems UI on UI.UserId = U.Id
     INNER JOIN @ids I on UI.ItemId = I.id
Group By U.Id, U.[Name]
HAVING(COUNT(*) = (SELECT COUNT(*) FROM @ids))
</code>```

Title: Combine multiple conditions with Having clause


问:
Jest tests hang due to open Sequelize connections

The Setup

I have a NodeJS project that uses:

Jest for testing.

Sequelize as an ORM.

Sequelize is instantiated when loading the models module which gets imported by a few of the files that are being tested with Jest.

The Problem

Jest tests pass but then hang with the message:

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't
  stopped in your tests. Consider running Jest with
  --detectOpenHandles to troubleshoot this issue.

Note: Adding --detectOpenHandles to the test call does not affect the output.

I do not actually invoke the sequelize object from any test paths, however some of the tested files import the models module and therefore Sequelize is instantiated.

(I will also note that this only occurs on my TravisCI environment, but I suspect this is a red herring.)

The Context

Because Jest is running tests in parallel, the models module is loaded multiple times during the entire test process.  I confirmed this with debug output saying SEQUELIZE LOADED which appears multiple times when I run the tests.

The Attempts

I did attempt to invoke sequelize.close() inside of a globalTeardown but this appears to simply open (and then close) a new sequelize connection.

Since none of the tests actually rely on a database connection, I attempted running sequelize.close() within the models module immediately before export.  This fixed the issue (though obviously is not a solution).

I have attempted to configure the test connection pools to aggressively end connections.

```<code>const sequelizeConfig = {
  ...
  pool: {
      idle: 0,
      evict: 0,
    }
}
</code>```

This did nothing.

The Requirements

I don't want to use a brute force solution such as running --forceExit via Jest when I run my tests. This feels like it is ignoring the root issue and might expose me to other kinds of mistakes down the line.

My tests are spread across dozens of files, which means needing to invoke something in an afterAllTests would require a lot of redundancy and would introduce a code smell.

The Question

How can I ensure that sequelize connections are closed after tests finish, so they don't cause Jest to hang?

答:
Jest provides a way to create universal setup before every test suite.  This means it is possible to leverage Jest's afterAll to close the sequelize connection pool without having to manually include it in every single test suite.

Example Jest config in package.json

```<code>  "jest": {
    ...
    "setupFilesAfterEnv": ["./src/test/suiteSetup.js"]
  }
</code>```

Example suiteSetup.js

```<code>import models from '../server/models'
afterAll(() => models.sequelize.close())

// Note: in my case sequelize is exposed as an attribute of my models module.
</code>```

Since the setupFilesAfterEnv is loaded before every test suite, this ensures that every Jest thread that opened a connection ultimately has that connection closed.

This doesn't violate DRY and it doesn't rely on a clunky --forceExit.

It does mean that connections will be closed that may never have been opened (which is a bit brute force) but that might be the best option.

Body:
The Setup

I have a NodeJS project that uses:

Jest for testing.

Sequelize as an ORM.

Sequelize is instantiated when loading the models module which gets imported by a few of the files that are being tested with Jest.

The Problem

Jest tests pass but then hang with the message:

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't
  stopped in your tests. Consider running Jest with
  --detectOpenHandles to troubleshoot this issue.

Note: Adding --detectOpenHandles to the test call does not affect the output.

I do not actually invoke the sequelize object from any test paths, however some of the tested files import the models module and therefore Sequelize is instantiated.

(I will also note that this only occurs on my TravisCI environment, but I suspect this is a red herring.)

The Context

Because Jest is running tests in parallel, the models module is loaded multiple times during the entire test process.  I confirmed this with debug output saying SEQUELIZE LOADED which appears multiple times when I run the tests.

The Attempts

I did attempt to invoke sequelize.close() inside of a globalTeardown but this appears to simply open (and then close) a new sequelize connection.

Since none of the tests actually rely on a database connection, I attempted running sequelize.close() within the models module immediately before export.  This fixed the issue (though obviously is not a solution).

I have attempted to configure the test connection pools to aggressively end connections.

const sequelizeConfig = {
  ...
  pool: {
      idle: 0,
      evict: 0,
    }
}

This did nothing.

The Requirements

I don't want to use a brute force solution such as running --forceExit via Jest when I run my tests. This feels like it is ignoring the root issue and might expose me to other kinds of mistakes down the line.

My tests are spread across dozens of files, which means needing to invoke something in an afterAllTests would require a lot of redundancy and would introduce a code smell.

The Question

How can I ensure that sequelize connections are closed after tests finish, so they don't cause Jest to hang?

Body:
Jest provides a way to create universal setup before every test suite.  This means it is possible to leverage Jest's afterAll to close the sequelize connection pool without having to manually include it in every single test suite.

Example Jest config in package.json

  "jest": {
    ...
    "setupFilesAfterEnv": ["./src/test/suiteSetup.js"]
  }

Example suiteSetup.js

import models from '../server/models'
afterAll(() => models.sequelize.close())

// Note: in my case sequelize is exposed as an attribute of my models module.

Since the setupFilesAfterEnv is loaded before every test suite, this ensures that every Jest thread that opened a connection ultimately has that connection closed.

This doesn't violate DRY and it doesn't rely on a clunky --forceExit.

It does mean that connections will be closed that may never have been opened (which is a bit brute force) but that might be the best option.


问:
UISearchController search bar appears but not working/triggering
In my view controller I am adding a search bar programmatically and it appears exactly the way i want but when i click on it do nothing i can't write/type anything on the search bar, And there is no error on the log. I added search bar in another view controller same way,it does works but in that particular it doesn't work. I am pushing this view controller from previous view controller so it has a navigation back button on the left (check the image) it works too.

In the view controller there is a TableView and a CollectionView i want to add the search for the table view. I was wondering if there is anything to do with having both of this in the same view controller.

Code to add search bar

```<code>- (void)viewDidLoad {
   //other stuff on view controller
   [self setSearchView];
}

-(void)setSearchView{
    //searchController is added as a property on .h file
    //and all the delegate are also added
    //@property (strong, nonatomic) UISearchController *searchController;

    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater= self;
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.searchBar.delegate = self;
    self.navigationController.toolbarHidden=YES;

    self.navigationItem.titleView=self.searchController.searchBar;

    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.definesPresentationContext = YES;
}
</code>```

I am coming to this view controller from a previous view controller and pushing this view controller when a button is clicked .And i am using nib file

Button action

```<code>- (void)ButtonClicked {
   MYNextViewController *nextViewController = [[MYNextViewController alloc] initWithNibName:@"MYNibFileName" bundle:nil];

    // I also have a tab bar on the bottom which i am hiding for that view controller when pushing
    nextViewController .hidesBottomBarWhenPushed=YES;

    [self.navigationController pushViewController:nextViewController  animated:YES];
}
</code>```

Image:

Any help will be greatly appreciated. Hope i made my self clear...

答:
For your particular case, Use this.

```<code> self.searchController.obscuresBackgroundDuringPresentation = NO;
</code>```

This will allow you to use the same tableview to interact with search result.

Body:
In my view controller I am adding a search bar programmatically and it appears exactly the way i want but when i click on it do nothing i can't write/type anything on the search bar, And there is no error on the log. I added search bar in another view controller same way,it does works but in that particular it doesn't work. I am pushing this view controller from previous view controller so it has a navigation back button on the left (check the image) it works too.

In the view controller there is a TableView and a CollectionView i want to add the search for the table view. I was wondering if there is anything to do with having both of this in the same view controller.

Code to add search bar

- (void)viewDidLoad {
   //other stuff on view controller
   [self setSearchView];
}

-(void)setSearchView{
    //searchController is added as a property on .h file
    //and all the delegate are also added
    //@property (strong, nonatomic) UISearchController *searchController;

    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater= self;
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.searchBar.delegate = self;
    self.navigationController.toolbarHidden=YES;

    self.navigationItem.titleView=self.searchController.searchBar;

    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.definesPresentationContext = YES;
}

I am coming to this view controller from a previous view controller and pushing this view controller when a button is clicked .And i am using nib file

Button action

- (void)ButtonClicked {
   MYNextViewController *nextViewController = [[MYNextViewController alloc] initWithNibName:@"MYNibFileName" bundle:nil];

    // I also have a tab bar on the bottom which i am hiding for that view controller when pushing
    nextViewController .hidesBottomBarWhenPushed=YES;

    [self.navigationController pushViewController:nextViewController  animated:YES];
}

Image:

Any help will be greatly appreciated. Hope i made my self clear...

Body:
For your particular case, Use this.

 self.searchController.obscuresBackgroundDuringPresentation = NO;

This will allow you to use the same tableview to interact with search result.


问:
liferay 7 - how to change from the default liferay logo to the company logo?
Liferay 7 GA1 is just releasead but the documentation is not complete yet. How can I change from the default liferay's logo to the company logo? I want to have a custom logo for each site of course.</p>

答:
For those using the 7.1 it's found at:

Build > Pages > Configure (cog icon) > Scroll down to bottom of page


问:
Range-based loop for linked list
I guess I am missing something in operator ++(). I want to implement Range based loop in following Linked list code. I am not sure what I am missing in it.

```<code>struct Node {
    Node() {}
    Node(int e, Node* n) : elem(e), next(n) {  }
    int elem = 0;
    Node* next = nullptr;

    Node& operator ++() {
        Node* current = this;
        if( current != nullptr ) {
            current = current->next;
            return *current;
        }
    }

    int& operator *() {
        return this->elem;
    }

    bool operator !=(Node const& rhs) const {
        return this->elem != rhs.elem;
    }

    int* begin() {
        return &this->elem;
    }

    int* end() {
        return nullptr;
    }

};

void add(Node& n, int x) {
    n.next = new Node(x, n.next);
}

int main() {

    Node head;
    add(head, 1);
    add(head, 2);
    add(head, 3);
    add(head, 4);
    add(head, 5);

    for (int x : head) {
        std::cout << x << " ";
    }
    std::cout << "2nd " << std::endl;
    std::cout << std::endl;
    for (int& x : head) {
        x = 7;
    }

    std::cout << "3rd " << std::endl;
    for (const int& x : head) {
        std::cout << x << " ";
    }
    std::cout << std::endl;

    return 0;
}
</code>```

I am not sure what to add in ++ operator. I want it in same struct instead of having separate Iterator class.

答:
The Node structure contains a single int element. This int element is totally unrelated to any other nodes int element.

What you do with begin and the increment operator ++ is treat one nodes int element as the first element of an array. That means your code will immediately go out of bounds.

To solve your iteration problem I first suggest that you abstract out the list and the nodes into different structures. Then you can easily make a wrapper structure which contains a pointer to the current node in the list iteration. This wrapper structure then need to overload the ++ operator which will the go to the next node in the list.

Somewhat graphically it could be something like

```
+------+     +--------+     +--------+     +--------+
| list | --> | node 1 | --> | node 2 | --> | node 3 | --> ...
+------+     +--------+     +--------+     +--------+
             ^
             |
             +----------+
             | iterator |
             +----------+
```

Then you increment the iterator you get this:

```
+------+     +--------+     +--------+     +--------+
| list | --> | node 1 | --> | node 2 | --> | node 3 | --> ...
+------+     +--------+     +--------+     +--------+
                            ^
                            |
                            +----------+
                            | iterator |
                            +----------+
```

And so on...

Title: Range-based loop for linked list

Body:
I guess I am missing something in operator ++(). I want to implement Range based loop in following Linked list code. I am not sure what I am missing in it.

struct Node {
    Node() {}
    Node(int e, Node* n) : elem(e), next(n) {  }
    int elem = 0;
    Node* next = nullptr;

    Node& operator ++() {
        Node* current = this;
        if( current != nullptr ) {
            current = current->next;
            return *current;
        }
    }

    int& operator *() {
        return this->elem;
    }

    bool operator !=(Node const& rhs) const {
        return this->elem != rhs.elem;
    }

    int* begin() {
        return &this->elem;
    }

    int* end() {
        return nullptr;
    }

};

void add(Node& n, int x) {
    n.next = new Node(x, n.next);
}

int main() {

    Node head;
    add(head, 1);
    add(head, 2);
    add(head, 3);
    add(head, 4);
    add(head, 5);

    for (int x : head) {
        std::cout << x << " ";
    }
    std::cout << "2nd " << std::endl;
    std::cout << std::endl;
    for (int& x : head) {
        x = 7;
    }

    std::cout << "3rd " << std::endl;
    for (const int& x : head) {
        std::cout << x << " ";
    }
    std::cout << std::endl;

    return 0;
}

I am not sure what to add in ++ operator. I want it in same struct instead of having separate Iterator class.

Body:
The Node structure contains a single int element. This int element is totally unrelated to any other nodes int element.

What you do with begin and the increment operator ++ is treat one nodes int element as the first element of an array. That means your code will immediately go out of bounds.

To solve your iteration problem I first suggest that you abstract out the list and the nodes into different structures. Then you can easily make a wrapper structure which contains a pointer to the current node in the list iteration. This wrapper structure then need to overload the ++ operator which will the go to the next node in the list.

Somewhat graphically it could be something like

+------+     +--------+     +--------+     +--------+
| list | --> | node 1 | --> | node 2 | --> | node 3 | --> ...
+------+     +--------+     +--------+     +--------+
             ^
             |
             +----------+
             | iterator |
             +----------+

Then you increment the iterator you get this:

+------+     +--------+     +--------+     +--------+
| list | --> | node 1 | --> | node 2 | --> | node 3 | --> ...
+------+     +--------+     +--------+     +--------+
                            ^
                            |
                            +----------+
                            | iterator |
                            +----------+

And so on...


问:
PySpark: java.lang.OutofMemoryError: Java heap space
I have been using PySpark with Ipython lately on my server with 24 CPUs and 32GB RAM. Its running only on one machine. In my process, I want to collect huge amount of data as is give in below code:

```<code>train_dataRDD = (train.map(lambda x:getTagsAndText(x))
.filter(lambda x:x[-1]!=[])
.flatMap(lambda (x,text,tags): [(tag,(x,text)) for tag in tags])
.groupByKey()
.mapValues(list))
</code>```

When I do

```<code>training_data =  train_dataRDD.collectAsMap()
</code>```

It gives me outOfMemory Error. Java heap Space. Also, I can not perform any operations on Spark after this error as it looses connection with Java. It gives Py4JNetworkError: Cannot connect to the java server.

It looks like heap space is small. How can I set it to bigger limits?

EDIT:

Things that I tried before running:
sc._conf.set('spark.executor.memory','32g').set('spark.driver.memory','32g').set('spark.driver.maxResultsSize','0')

I changed the spark options as per the documentation here(if you do ctrl-f and search for spark.executor.extraJavaOptions) : http://spark.apache.org/docs/1.2.1/configuration.html

It says that I can avoid OOMs by setting spark.executor.memory option. I did the same thing but it seem not be working.

答:
If you're looking for the way to set this from within the script or a jupyter notebook, you can do:

from pyspark.sql import SparkSession

spark = SparkSession.builder \
    .master('local[*]') \
    .config("spark.driver.memory", "15g") \
    .appName('my-cool-app') \
    .getOrCreate()
```

Body:
I have been using PySpark with Ipython lately on my server with 24 CPUs and 32GB RAM. Its running only on one machine. In my process, I want to collect huge amount of data as is give in below code:

train_dataRDD = (train.map(lambda x:getTagsAndText(x))
.filter(lambda x:x[-1]!=[])
.flatMap(lambda (x,text,tags): [(tag,(x,text)) for tag in tags])
.groupByKey()
.mapValues(list))

When I do

training_data =  train_dataRDD.collectAsMap()

It gives me outOfMemory Error. Java heap Space. Also, I can not perform any operations on Spark after this error as it looses connection with Java. It gives Py4JNetworkError: Cannot connect to the java server.

It looks like heap space is small. How can I set it to bigger limits?

EDIT:

Things that I tried before running:
sc._conf.set('spark.executor.memory','32g').set('spark.driver.memory','32g').set('spark.driver.maxResultsSize','0')

I changed the spark options as per the documentation here(if you do ctrl-f and search for spark.executor.extraJavaOptions) : http://spark.apache.org/docs/1.2.1/configuration.html

It says that I can avoid OOMs by setting spark.executor.memory option. I did the same thing but it seem not be working.


问:
Hosting a web service in an Android application
Is there any way to host a web service from an Android application? I will be hosting RESTful services via WCF and would like to be able to "push" data to an Android app. I understand this could be done with polling but would like to try to avoid that. I was thinking if I could host a web service from the Android app, I would be able to call it from my server. Any ideas would be appreciated.</p>

答:
You can use Cloud to Device Messaging (C2DM) to push data from a server to the device. This will eliminate the need to keep polling a webserver for updated data.

Then, use normal web access methods to access a server's data on any particular event.

Good enough? or you need more assistance?

 Just revert.


问:
Javascript Export CSV data URI is not displaying korean characters
I am using below code

 var uri = 'data:text/csv;charset=utf-8,\uFFFE' + escape(str);
```

When i click on download CSV button in UI and the above code gets triggered and csv file will be downloaded.

The problem is  When i open the csv file , i see korean characters are not displayed properly and it is displayed as "%uBC29%uAC08"

Questions

How do I display Korean characters in the CSV properly.

答:
The code is doing exactly what you programmed:

var s = "방갈";
console.log(escape(s)); // %uBC29%uAC08```
</div>
</div>
</p>

<hr>

<h2>UPDATE</h2>

<p>Consider using <code>encodeURIComponent</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var s = "방갈";
console.log(encodeURIComponent(s)); // %EB%B0%A9%EA%B0%88</code>```

That looks like UTF-8 percent encoded.

From the Docs:

escape()

Warning: Although escape() is not strictly deprecated

… Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code. …

— MDN JavaScript Reference - escape()

UPDATE #2

Consider using blobs instead of data uris:

```<code>var blob = new Blob([s], { type: "text/csv;charset=utf-8" });
var uri =  URL.createObjectURL(blob);
</code>```

Frankly data-uris are obsolete.

For more information,

MDN Web API Reference - Blob constructor

MDN Web API Reference - URL.createObjectURL

Body:
I am using below code

 var uri = 'data:text/csv;charset=utf-8,\uFFFE' + escape(str);

When i click on download CSV button in UI and the above code gets triggered and csv file will be downloaded.

The problem is  When i open the csv file , i see korean characters are not displayed properly and it is displayed as "%uBC29%uAC08"

Questions

How do I display Korean characters in the CSV properly.

Body:
The code is doing exactly what you programmed:

var s = "방갈";
console.log(escape(s)); // %uBC29%uAC08

UPDATE

Consider using encodeURIComponent:

var s = "방갈";
console.log(encodeURIComponent(s)); // %EB%B0%A9%EA%B0%88

That looks like UTF-8 percent encoded.

From the Docs:

escape()

Warning: Although escape() is not strictly deprecated

… Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code. …

— MDN JavaScript Reference - escape()

UPDATE #2

Consider using blobs instead of data uris:

var blob = new Blob([s], { type: "text/csv;charset=utf-8" });
var uri =  URL.createObjectURL(blob);

Frankly data-uris are obsolete.

For more information,

MDN Web API Reference - Blob constructor

MDN Web API Reference - URL.createObjectURL


问:
View Encapsulation Emulated, is it possible to escape emulated encapsulation within a stylesheet?
I have a situation where i am using a jQuery plugin to resize a div. When using emulated view encapsulation this element is not getting the attribute prefix for the style in my stylesheet to target. This makes sense because i am modifying the DOM without angular's knowledge (which i know is not best practice).

Element created from plugin - without attribute

Element defined in angular HTML - with attribute

I would prefer to keep using Emulated ViewEncapsulation for everything else in this component to prevent any style's leaking.

I was wondering if there is anyway for me to target a single class from my stylesheet without ViewEncapsulation? Or if anyone has any suggestions for how best to tackle this?

Thanks in advance.

答:
This is where the (deprecated) ::ng-deep comes in play:

In your templates stylesheet:

```<code>:host ::ng-deep .ui-resizable-handle {
  background-color: pink;
}
</code>```

This will target any child element with the class ui-resizable-handle from your component, regardless if it's declared in the template, a child component or dynamically added with a third party library, because this will compile to something like:

```<code>[_nghost-fav-c294] .ui-resizable-handle {
  background-color: pink;
}
</code>```

Body:
This is where the (deprecated) ::ng-deep comes in play:

In your templates stylesheet:

:host ::ng-deep .ui-resizable-handle {
  background-color: pink;
}

This will target any child element with the class ui-resizable-handle from your component, regardless if it's declared in the template, a child component or dynamically added with a third party library, because this will compile to something like:

[_nghost-fav-c294] .ui-resizable-handle {
  background-color: pink;
}


问:
Setting unique ID to a table cell created in JavaScript from a JSON file
I create table cells and rows in JavaScript and add information from JSON file in table cells. I assign a unique id to table cells in my code but I get error that the ids are undefined and when I want to use them later on the ids are "blank".

I can't understand why this happens! Note that the table gets created and everything shows as i will. Below you can see my code and other relevant information, please no jQuery, thanks!

HTML:

```<code><div id="info">
    <table id="country">
    </table>
</div>
</code>```

JavaScript:

```<code>            document.getElementById("country").innerHTML = "";
            for (var i = 0; i < jsonData.api.countries.length; i = i + 2) {
                document.getElementById("country").innerHTML += "<tr><td id = '" + jsonData.api.countries[i].code + "' > " + "<img src=" + jsonData.api.countries[i].flag + ">" + "<p>" + jsonData.api.countries[i].country + "</p>" + "</td>" +
                    "<td id = '" + jsonData.api.countries[i + 1].code + "' > " + "<img src=" + jsonData.api.countries[i + 1].flag + ">" + "<p>" + jsonData.api.countries[i + 1].country + "</p>" + "</td>"
                    +"</tr>";

                }
</code>```

The error that i get in console log:

```<code>Uncaught TypeError: Cannot read property 'code' of undefined
at XMLHttpRequest.myfunction
</code>```

Here is a picture of how the html looks like in page elements:

Sample of jsonfile:

答:
Hi here is an example using vanilla js and some custom json:

     let json = {
    "countries": [{
            "country": "Albania",
            "code": "AL",
            "flag": "https://media.api-football.com/flags/al.svg"
        },
        {
            "country": "Algeria",
            "code": "DZ",
            "flag": "https://media.api-football.com/flags/dz.svg"
        },
        {
            "country": "Honduras",
            "code": "HN",
            "flag": "https://media.api-football.com/flags/hn.svg"
        }
    ]
};
let html = ``;

json.countries.forEach((e, i) => {
    html += `<tr><td id="${e.code}" onclick="infoCountry(this)"><img src="${e.flag}"></img><p>${e.country}</p></td><tr>`;
});
document.getElementById('country').innerHTML = html;
const infoCountry = (target) => {
    let country = target.querySelectorAll('p')[0].innerText;

    alert('this country is ' + country)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="info">
  <table id="country">

  </table>
</div></code>```

Hope it helps

Body:
I create table cells and rows in JavaScript and add information from JSON file in table cells. I assign a unique id to table cells in my code but I get error that the ids are undefined and when I want to use them later on the ids are "blank".

I can't understand why this happens! Note that the table gets created and everything shows as i will. Below you can see my code and other relevant information, please no jQuery, thanks!

HTML:

JavaScript:

            document.getElementById("country").innerHTML = "";
            for (var i = 0; i < jsonData.api.countries.length; i = i + 2) {
                document.getElementById("country").innerHTML += "
 " + "" + "
" + jsonData.api.countries[i].country + "
" + "	" +
                    " " + "" + "
" + jsonData.api.countries[i + 1].country + "
" + "	"
                    +"
";

                }

The error that i get in console log:

Uncaught TypeError: Cannot read property 'code' of undefined
at XMLHttpRequest.myfunction

Here is a picture of how the html looks like in page elements:

Sample of jsonfile:

Body:
Hi here is an example using vanilla js and some custom json:

     let json = {
    "countries": [{
            "country": "Albania",
            "code": "AL",
            "flag": "https://media.api-football.com/flags/al.svg"
        },
        {
            "country": "Algeria",
            "code": "DZ",
            "flag": "https://media.api-football.com/flags/dz.svg"
        },
        {
            "country": "Honduras",
            "code": "HN",
            "flag": "https://media.api-football.com/flags/hn.svg"
        }
    ]
};
let html = ``;

json.countries.forEach((e, i) => {
    html += `<tr><td id="${e.code}" onclick="infoCountry(this)"><img src="${e.flag}"></img><p>${e.country}</p></td><tr>`;
});
document.getElementById('country').innerHTML = html;
const infoCountry = (target) => {
    let country = target.querySelectorAll('p')[0].innerText;

    alert('this country is ' + country)
}

<div id="info">
  <table id="country">

  </table>
</div>

Hope it helps


问:
Convert Java Map<Obj1, Collection<Obj2>> to Map<Obj2, Collection<Obj1>>
What would be a good practice to convert Map<Obj1, Collection<Obj2>> to Map<Obj2, Collection<Obj1>>?

I tried doing it with MultiMap.

```<code>    Map<Obj1, Collection<Obj2>> originalMap = ...;
    Multimap<Obj1, Obj2> multiMap = ArrayListMultimap.create();
    originalMap.forEach(multiMap::putAll);
    Map<Obj2, Collection<Obj1>> convertedMap = Multimaps.invertFrom(multiMap, ArrayListMultimap.create()).asMap();
</code>```

Is there a better way to do this?

答:
Your approach is correct, but could be even more straightforward if you used Multimap instead in the first place and

you don't need mutability,

you don't have nulls.

If that's the case, all you need is ImmutableMultimap#inverse():

```<code>ImmutableListMultimap<Integer, String> originalMultimap = ImmutableListMultimap.of(
        1, "foo",
        1, "bar",
        2, "baz",
        42, "foo"
);
ImmutableListMultimap<String, Integer> convertedMap = originalMultimap.inverse();
System.out.println(convertedMap);   // {foo=[1, 42], bar=[1], baz=[2]}
</code>```

I used ImmutableListMultimap instead of ImmutableMultimap because docs encourage to do so:

Warning: avoid direct usage of ImmutableMultimap as a type (as with Multimap itself). Prefer subtypes such as ImmutableSetMultimap or ImmutableListMultimap, which have well-defined equals(java.lang.Object) semantics, thus avoiding a common source of bugs and confusion.

Body:
What would be a good practice to convert Map<Obj1, Collection<Obj2>> to Map<Obj2, Collection<Obj1>>?

I tried doing it with MultiMap.

    Map<Obj1, Collection<Obj2>> originalMap = ...;
    Multimap<Obj1, Obj2> multiMap = ArrayListMultimap.create();
    originalMap.forEach(multiMap::putAll);
    Map<Obj2, Collection<Obj1>> convertedMap = Multimaps.invertFrom(multiMap, ArrayListMultimap.create()).asMap();

Is there a better way to do this?

Body:
Your approach is correct, but could be even more straightforward if you used Multimap instead in the first place and

you don't need mutability,

you don't have nulls.

If that's the case, all you need is ImmutableMultimap#inverse():

ImmutableListMultimap<Integer, String> originalMultimap = ImmutableListMultimap.of(
        1, "foo",
        1, "bar",
        2, "baz",
        42, "foo"
);
ImmutableListMultimap<String, Integer> convertedMap = originalMultimap.inverse();
System.out.println(convertedMap);   // {foo=[1, 42], bar=[1], baz=[2]}

I used ImmutableListMultimap instead of ImmutableMultimap because docs encourage to do so:

Warning: avoid direct usage of ImmutableMultimap as a type (as with Multimap itself). Prefer subtypes such as ImmutableSetMultimap or ImmutableListMultimap, which have well-defined equals(java.lang.Object) semantics, thus avoiding a common source of bugs and confusion.


问:
How to organize generated code and avoid copying format when copying and pasting text in the editor WYSIWYG?
I have observed some questions but all are based on the use of a plugin. But I have my own editor so the answers given do not solve my problem.

The issue is that in each tabulation that is given, the code is generated with a div container and, the paragraphs in br in such a way:

How to avoid the use of div y, the paragraphs in br, instead of them, use only p and in an organized way for example:

And finally

The issue I've got is that whenever you copy and paste something into the editor, it copies over the formatting from wherever you've copied it.

How can I correct these defects of my editor, here my complete code: https://jsfiddle.net/p87t0aqx/

答:
This might not be a perfect solution, as there might be a plenty of work to be done to make the WYSIWYG editor truly usable.

Original Solution:

What the solution does:

Format the HTML code on Code Toggle before displaying.

Detect Enter Key and apply
 format, otherwise apply
 format.

On Clipboard Paste, intercept the default clipboard pasting behavior and then insert plain text at current editor's cursor position.

$(function() {
  // https://stackoverflow.com/questions/26360414/javascript-how-to-correct-indentation-in-html-string
  function formatHtmlCode(str) {

    var div = document.createElement('div');
    div.innerHTML = str.trim();

    return format(div, 0).innerHTML;
  }

  function format(node, level) {
    var indentBefore = new Array(level++ + 1).join('  '),
      indentAfter = new Array(level - 1).join('  '),
      textNode;

    for (var i = 0; i < node.children.length; i++) {

      textNode = document.createTextNode('\n' + indentBefore);
      node.insertBefore(textNode, node.children[i]);

      format(node.children[i], level);

      if (node.lastElementChild == node.children[i]) {
        textNode = document.createTextNode('\n' + indentAfter);
        node.appendChild(textNode);
      }
    }

    return node;
  }

  $('#editControls a').click(function(e) {
    switch ($(this).data('role')) {
      case 'p':
        document.execCommand('formatBlock', false, $(this).data('role'));
        break;
        //Specific control for the code button.
      case 'code':
        //enable / disable code mode
        codeMode = !codeMode;
        if (codeMode) {
          // ON: show the code in text mode
          var formattedHtml = formatHtmlCode(htmlDiv.html());

          htmlDiv.css("white-space", "pre");
          htmlDiv.text(formattedHtml);
          //
          var editor = $("#editor")
          editor.addClass("black-bg-colr codeMode")
        } else {
          // OFF: reinterpret the code
          htmlDiv.css("white-space", "normal");
          htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
          var editor = $("#editor")
          editor.removeClass("black-bg-colr codeMode")
        }
        break;
      default:
        document.execCommand($(this).data('role'), false, null);
        break;
    }
  });

  //code mode control
  let codeMode = false;
  let htmlDiv = $("#editor");

  htmlDiv.on('keyup', function(e) {
    if (!e.shiftKey && e.keyCode === 13) {
      document.execCommand('formatBlock', false, 'p');
    } else if (e.shiftKey) {
      document.execCommand('formatBlock', false, 'div');
    }
  });

  htmlDiv.on("paste", function(e) {
    e.preventDefault();

    var text = (e.originalEvent || e).clipboardData.getData('text/plain');

    document.execCommand('formatBlock', false, 'div');
    document.execCommand('insertText', false, text);
  });

  //input -> NOT keyup
  htmlDiv.on("input", function(e) {
    //htmlDiv.on("keyup", function(e) {
    $(".editor-preview").val(htmlDiv.html());
    //$("#textarea").html(htmlDiv.html());
    $(".editor-preview").keyup();
    //$(".editor-preview").html(htmlDiv.html());
  });
  //$("#textarea").html(htmlDiv.html());

  $('.editor-preview').keyup(function() {
    //var value = $(this).val();
    var contentAttr = $(this).attr('class');
    if (!codeMode) {
      var value = $(this).val();
      //$( '.' + contentAttr + '' ).html(value);
      $('.' + contentAttr).html(value);
    } else {
      //$( '.' + contentAttr + '' ).html(htmlDiv.text());
      $('.' + contentAttr).html(htmlDiv.text());
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#editControls {
  overflow: auto;
  border-top: 1px solid transparent;
  border-left: 1px solid transparent;
  border-right: 1px solid transparent;
  border-color: silver;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  padding: .5em 1em .5em 1em;
  background-color: #fbfbfb;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor {
  resize: vertical;
  overflow: auto;
  border: 1px solid silver;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
  min-height: 100px;
  padding: 1em;
  background: white;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor:focus {
  outline: none !important;
  box-shadow: inset 0 0 2px silver;
}

.codeMode {
  font-family: Courier New, Source Code Pro Light, Medium, Source Code Pro ExtraLight, Menlo, Consola, Monaco Linux, Consola Regular, Fira Code Regular, DejaVu Sans Mono;
  /*font-family: inherit;*/
  /*font-family: 'Courier New';*/
  border: 0px;
  font-style: inherit;
  font-variant: inherit;
  font-weight: inherit;
  font-stretch: inherit;
  line-height: inherit;
  vertical-align: baseline;
  box-sizing: inherit;
  color: #fff;
}

.black-bg-colr {
  background-color: #000 !important;
}

.btn-group {
  position: relative;
  display: inline-block;
  font-size: 0;
  vertical-align: middle;
  white-space: nowrap;
}

.btn-group+.btn-group {
  margin-left: 5px;
}

.btn-group a {
  text-decoration: none;
}

.btn-editor {
  height: 30px;
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 0;
  font-size: 11px;
  font-weight: normal;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-image: none;
  border-radius: 4px;
  border: 1px solid transparent;
  color: #333;
  background-color: #fff;
  border-color: #ccc;
}

.btn-group>.btn-editor:first-child {
  margin-left: 0;
  -webkit-border-top-left-radius: 4px;
  -moz-border-radius-topleft: 4px;
  border-top-left-radius: 4px;
  -webkit-border-bottom-left-radius: 4px;
  -moz-border-radius-bottomleft: 4px;
  border-bottom-left-radius: 4px;
}

.btn-group>.btn-editor+.btn-editor {
  margin-left: -1px !important;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}

.btn-not-space {
  position: relative;
  float: left;
  margin-left: 0 !important;
  border-radius: inherit;
  border: 1px solid transparent;
  border-color: #ccc;
}

.btn-editor.btn-not-space:hover {
  background-color: rgba(230, 230, 230, 0.32);
}

#preview {
  padding: 1em;
  margin: 0 auto;
  width: 97%;
  border-top: 1px dotted #c8ccd0;
  border-bottom: 1px dotted #c8ccd0;
  clear: both;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>WYSIWYG</title>

        Bold
        Italic
        U
        abc

        </>

    <textarea id="textarea" name="detail" class="editor-preview" style="display: none;"></textarea>

```
</div>
</div>
</p>

<hr>

<p><strong>With Ace Editor:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() {
  var aceEditor = ace.edit("ace-editor");
  aceEditor.setTheme("ace/theme/eclipse");
  aceEditor.session.setMode("ace/mode/html");

  $('#editControls a').click(function(e) {
    switch ($(this).data('role')) {
      case 'p':
        document.execCommand('formatBlock', false, $(this).data('role'));
        break;
        //Specific control for the code button.
      case 'code':
        //enable / disable code mode
        codeMode = !codeMode;
        if (codeMode) {
          // ON: show the code in text mode
          var editor = $("#editor");
          var $aceEditor = $("#ace-editor");

          var formattedHtml = html_beautify(htmlDiv.html());

          aceEditor.setValue(formattedHtml, -1);

          editor.css("display", "none");
          $aceEditor.css("display", "block");

        } else {
          // OFF: reinterpret the code
          htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
          var editor = $("#editor");
          var $aceEditor = $("#ace-editor");

          editor.css("display", "block");
          $aceEditor.css("display", "none");

          htmlDiv.html(aceEditor.getValue().replace(/\r?\n|\r/g, ""));
        }
        break;
      default:
        document.execCommand($(this).data('role'), false, null);
        break;
    }
  });

  //code mode control
  let codeMode = false;
  let htmlDiv = $("#editor");

  htmlDiv.on('keyup', function(e) {
    if (!e.shiftKey && e.keyCode === 13) {
      document.execCommand('formatBlock', false, 'p');
    } else if (e.shiftKey) {
      document.execCommand('formatBlock', false, 'div');
    }
  });

  htmlDiv.on("paste", function(e) {
    e.preventDefault();

    var text = (e.originalEvent || e).clipboardData.getData('text/plain');

    document.execCommand('formatBlock', false, 'div');
    document.execCommand('insertText', false, text);
  });

  //input -> NOT keyup
  htmlDiv.on("input", function(e) {
    //htmlDiv.on("keyup", function(e) {
    $(".editor-preview").val(htmlDiv.html());
    //$("#textarea").html(htmlDiv.html());
    $(".editor-preview").keyup();
    //$(".editor-preview").html(htmlDiv.html());
  });
  //$("#textarea").html(htmlDiv.html());

  aceEditor.getSession().on('change', function() {
    $('.editor-preview').html(aceEditor.getValue().replace(/\r?\n|\r/g, ""));
  });

  $('.editor-preview').keyup(function() {
    //var value = $(this).val();
    var contentAttr = $(this).attr('class');
    if (!codeMode) {
      var value = $(this).val();
      //$( '.' + contentAttr + '' ).html(value);
      $('.' + contentAttr).html(value);
    } else {
      //$( '.' + contentAttr + '' ).html(htmlDiv.text());
      $('.' + contentAttr).html(htmlDiv.text());
    }
  });
});</code>```

#editControls {
  overflow: auto;
  border-top: 1px solid transparent;
  border-left: 1px solid transparent;
  border-right: 1px solid transparent;
  border-color: silver;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  padding: .5em 1em .5em 1em;
  background-color: #fbfbfb;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor {
  resize: vertical;
  overflow: auto;
  border: 1px solid silver;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
  min-height: 100px;
  padding: 1em;
  background: white;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor:focus {
  outline: none !important;
  box-shadow: inset 0 0 2px silver;
}

.codeMode {
  font-family: Courier New, Source Code Pro Light, Medium, Source Code Pro ExtraLight, Menlo, Consola, Monaco Linux, Consola Regular, Fira Code Regular, DejaVu Sans Mono;
  /*font-family: inherit;*/
  /*font-family: 'Courier New';*/
  border: 0px;
  font-style: inherit;
  font-variant: inherit;
  font-weight: inherit;
  font-stretch: inherit;
  line-height: inherit;
  vertical-align: baseline;
  box-sizing: inherit;
  color: #fff;
}

.black-bg-colr {
  background-color: #000 !important;
}

.btn-group {
  position: relative;
  display: inline-block;
  font-size: 0;
  vertical-align: middle;
  white-space: nowrap;
}

.btn-group+.btn-group {
  margin-left: 5px;
}

.btn-group a {
  text-decoration: none;
}

.btn-editor {
  height: 30px;
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 0;
  font-size: 11px;
  font-weight: normal;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-image: none;
  border-radius: 4px;
  border: 1px solid transparent;
  color: #333;
  background-color: #fff;
  border-color: #ccc;
}

.btn-group>.btn-editor:first-child {
  margin-left: 0;
  -webkit-border-top-left-radius: 4px;
  -moz-border-radius-topleft: 4px;
  border-top-left-radius: 4px;
  -webkit-border-bottom-left-radius: 4px;
  -moz-border-radius-bottomleft: 4px;
  border-bottom-left-radius: 4px;
}

.btn-group>.btn-editor+.btn-editor {
  margin-left: -1px !important;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}

.btn-not-space {
  position: relative;
  float: left;
  margin-left: 0 !important;
  border-radius: inherit;
  border: 1px solid transparent;
  border-color: #ccc;
}

.btn-editor.btn-not-space:hover {
  background-color: rgba(230, 230, 230, 0.32);
}

#preview {
  padding: 1em;
  margin: 0 auto;
  width: 97%;
  border-top: 1px dotted #c8ccd0;
  border-bottom: 1px dotted #c8ccd0;
  clear: both;
}

#ace-editor {
  resize: vertical;
  overflow: auto;
  border: 1px solid silver;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
  min-height: 100px;
  padding: 1em;
  margin: 0 auto;
  width: 100%;
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>WYSIWYG</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.7/ace.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.7/ext-beautify.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.10.3/beautify-html.min.js"></script>
</head>

<body>
  <div class="editor-wrapper">
    <div id="editControls">
      <div class="btn-group">
        <b>Bold</b>
        <em>Italic</em>
        <u><b>U</b></u>
        <strike>abc</strike>
      </div>
      <div class="btn-group">
        <code></></code>
      </div>
    </div>
    <div id="editor" contenteditable></div>
    <div id="ace-editor"></div>
    <textarea id="textarea" name="detail" class="editor-preview" style="display: none;"></textarea>
    <div id="preview" class="editor-preview"></div>
  </div>

</body>

</html></code>```

Ace Editor with
 Only:

$(function () {
    var aceEditor = ace.edit("ace-editor");
    aceEditor.setTheme("ace/theme/eclipse");
    aceEditor.session.setMode("ace/mode/html");

    $('#editControls a').click(function (e) {
        switch ($(this).data('role')) {
            case 'p':
                document.execCommand('formatBlock', false, $(this).data('role'));
                break;
            //Specific control for the code button.
            case 'code':
                //enable / disable code mode
                codeMode = !codeMode;
                if (codeMode) {
                    // ON: show the code in text mode
                    var editor = $("#editor");
                    var $aceEditor = $("#ace-editor");

                    var formattedHtml = html_beautify(htmlDiv.html());

                    aceEditor.setValue(formattedHtml, -1);

                    editor.css("display", "none");
                    $aceEditor.css("display", "block");

                } else {
                    // OFF: reinterpret the code
                    htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
                    var editor = $("#editor");
                    var $aceEditor = $("#ace-editor");

                    editor.css("display", "block");
                    $aceEditor.css("display", "none");

                    htmlDiv.html(aceEditor.getValue().replace(/\r?\n|\r/g, ""));
                }
                break;
            default:
                document.execCommand($(this).data('role'), false, null);
                break;
        }
    });

    //code mode control
    let codeMode = false;
    let htmlDiv = $("#editor");

    htmlDiv.on("paste", function (e) {
        e.preventDefault();

        var text = (e.originalEvent || e).clipboardData.getData('text/plain');

        document.execCommand('formatBlock', false, 'p');
        document.execCommand('insertText', false, text);
    });

    //input -> NOT keyup
    htmlDiv.on("input", function (e) {
        document.execCommand('formatBlock', false, 'p');
        //htmlDiv.on("keyup", function(e) {
        $(".editor-preview").val(htmlDiv.html());
        //$("#textarea").html(htmlDiv.html());
        $(".editor-preview").keyup();
        //$(".editor-preview").html(htmlDiv.html());
    });
    //$("#textarea").html(htmlDiv.html());

    aceEditor.getSession().on('change', function () {
        $('.editor-preview').html(aceEditor.getValue().replace(/\r?\n|\r/g, ""));
    });

    $('.editor-preview').keyup(function () {
        //var value = $(this).val();
        var contentAttr = $(this).attr('class');
        if (!codeMode) {
            var value = $(this).val();
            //$( '.' + contentAttr + '' ).html(value);
            $('.' + contentAttr).html(value);
        } else {
            //$( '.' + contentAttr + '' ).html(htmlDiv.text());
            $('.' + contentAttr).html(htmlDiv.text());
        }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#editControls {
  overflow: auto;
  border-top: 1px solid transparent;
  border-left: 1px solid transparent;
  border-right: 1px solid transparent;
  border-color: silver;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  padding: .5em 1em .5em 1em;
  background-color: #fbfbfb;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor {
  resize: vertical;
  overflow: auto;
  border: 1px solid silver;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
  min-height: 100px;
  padding: 1em;
  background: white;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor:focus {
  outline: none !important;
  box-shadow: inset 0 0 2px silver;
}

.codeMode {
  font-family: Courier New, Source Code Pro Light, Medium, Source Code Pro ExtraLight, Menlo, Consola, Monaco Linux, Consola Regular, Fira Code Regular, DejaVu Sans Mono;
  /*font-family: inherit;*/
  /*font-family: 'Courier New';*/
  border: 0px;
  font-style: inherit;
  font-variant: inherit;
  font-weight: inherit;
  font-stretch: inherit;
  line-height: inherit;
  vertical-align: baseline;
  box-sizing: inherit;
  color: #fff;
}

.black-bg-colr {
  background-color: #000 !important;
}

.btn-group {
  position: relative;
  display: inline-block;
  font-size: 0;
  vertical-align: middle;
  white-space: nowrap;
}

.btn-group+.btn-group {
  margin-left: 5px;
}

.btn-group a {
  text-decoration: none;
}

.btn-editor {
  height: 30px;
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 0;
  font-size: 11px;
  font-weight: normal;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-image: none;
  border-radius: 4px;
  border: 1px solid transparent;
  color: #333;
  background-color: #fff;
  border-color: #ccc;
}

.btn-group>.btn-editor:first-child {
  margin-left: 0;
  -webkit-border-top-left-radius: 4px;
  -moz-border-radius-topleft: 4px;
  border-top-left-radius: 4px;
  -webkit-border-bottom-left-radius: 4px;
  -moz-border-radius-bottomleft: 4px;
  border-bottom-left-radius: 4px;
}

.btn-group>.btn-editor+.btn-editor {
  margin-left: -1px !important;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}

.btn-not-space {
  position: relative;
  float: left;
  margin-left: 0 !important;
  border-radius: inherit;
  border: 1px solid transparent;
  border-color: #ccc;
}

.btn-editor.btn-not-space:hover {
  background-color: rgba(230, 230, 230, 0.32);
}

#preview {
  padding: 1em;
  margin: 0 auto;
  width: 97%;
  border-top: 1px dotted #c8ccd0;
  border-bottom: 1px dotted #c8ccd0;
  clear: both;
}

#ace-editor {
  resize: vertical;
  overflow: auto;
  border: 1px solid silver;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
  min-height: 100px;
  padding: 1em;
  margin: 0 auto;
  width: 100%;
  display: none;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>WYSIWYG</title>

        Bold
        Italic
        U
        abc

        </>

    <textarea id="textarea" name="detail" class="editor-preview" style="display: none;"></textarea>

```

Body:
This might not be a perfect solution, as there might be a plenty of work to be done to make the WYSIWYG editor truly usable.

Original Solution:

What the solution does:

Format the HTML code on Code Toggle before displaying.

Detect Enter Key and apply <p> format, otherwise apply <div> format.

On Clipboard Paste, intercept the default clipboard pasting behavior and then insert plain text at current editor's cursor position.

$(function() {
  // https://stackoverflow.com/questions/26360414/javascript-how-to-correct-indentation-in-html-string
  function formatHtmlCode(str) {

    var div = document.createElement('div');
    div.innerHTML = str.trim();

    return format(div, 0).innerHTML;
  }

  function format(node, level) {
    var indentBefore = new Array(level++ + 1).join('  '),
      indentAfter = new Array(level - 1).join('  '),
      textNode;

    for (var i = 0; i < node.children.length; i++) {

      textNode = document.createTextNode('\n' + indentBefore);
      node.insertBefore(textNode, node.children[i]);

      format(node.children[i], level);

      if (node.lastElementChild == node.children[i]) {
        textNode = document.createTextNode('\n' + indentAfter);
        node.appendChild(textNode);
      }
    }

    return node;
  }

  $('#editControls a').click(function(e) {
    switch ($(this).data('role')) {
      case 'p':
        document.execCommand('formatBlock', false, $(this).data('role'));
        break;
        //Specific control for the code button.
      case 'code':
        //enable / disable code mode
        codeMode = !codeMode;
        if (codeMode) {
          // ON: show the code in text mode
          var formattedHtml = formatHtmlCode(htmlDiv.html());

          htmlDiv.css("white-space", "pre");
          htmlDiv.text(formattedHtml);
          //
          var editor = $("#editor")
          editor.addClass("black-bg-colr codeMode")
        } else {
          // OFF: reinterpret the code
          htmlDiv.css("white-space", "normal");
          htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
          var editor = $("#editor")
          editor.removeClass("black-bg-colr codeMode")
        }
        break;
      default:
        document.execCommand($(this).data('role'), false, null);
        break;
    }
  });

  //code mode control
  let codeMode = false;
  let htmlDiv = $("#editor");

  htmlDiv.on('keyup', function(e) {
    if (!e.shiftKey && e.keyCode === 13) {
      document.execCommand('formatBlock', false, 'p');
    } else if (e.shiftKey) {
      document.execCommand('formatBlock', false, 'div');
    }
  });

  htmlDiv.on("paste", function(e) {
    e.preventDefault();

    var text = (e.originalEvent || e).clipboardData.getData('text/plain');

    document.execCommand('formatBlock', false, 'div');
    document.execCommand('insertText', false, text);
  });

  //input -> NOT keyup
  htmlDiv.on("input", function(e) {
    //htmlDiv.on("keyup", function(e) {
    $(".editor-preview").val(htmlDiv.html());
    //$("#textarea").html(htmlDiv.html());
    $(".editor-preview").keyup();
    //$(".editor-preview").html(htmlDiv.html());
  });
  //$("#textarea").html(htmlDiv.html());

  $('.editor-preview').keyup(function() {
    //var value = $(this).val();
    var contentAttr = $(this).attr('class');
    if (!codeMode) {
      var value = $(this).val();
      //$( '.' + contentAttr + '' ).html(value);
      $('.' + contentAttr).html(value);
    } else {
      //$( '.' + contentAttr + '' ).html(htmlDiv.text());
      $('.' + contentAttr).html(htmlDiv.text());
    }
  });
});

#editControls {
  overflow: auto;
  border-top: 1px solid transparent;
  border-left: 1px solid transparent;
  border-right: 1px solid transparent;
  border-color: silver;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  padding: .5em 1em .5em 1em;
  background-color: #fbfbfb;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor {
  resize: vertical;
  overflow: auto;
  border: 1px solid silver;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
  min-height: 100px;
  padding: 1em;
  background: white;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor:focus {
  outline: none !important;
  box-shadow: inset 0 0 2px silver;
}

.codeMode {
  font-family: Courier New, Source Code Pro Light, Medium, Source Code Pro ExtraLight, Menlo, Consola, Monaco Linux, Consola Regular, Fira Code Regular, DejaVu Sans Mono;
  /*font-family: inherit;*/
  /*font-family: 'Courier New';*/
  border: 0px;
  font-style: inherit;
  font-variant: inherit;
  font-weight: inherit;
  font-stretch: inherit;
  line-height: inherit;
  vertical-align: baseline;
  box-sizing: inherit;
  color: #fff;
}

.black-bg-colr {
  background-color: #000 !important;
}

.btn-group {
  position: relative;
  display: inline-block;
  font-size: 0;
  vertical-align: middle;
  white-space: nowrap;
}

.btn-group+.btn-group {
  margin-left: 5px;
}

.btn-group a {
  text-decoration: none;
}

.btn-editor {
  height: 30px;
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 0;
  font-size: 11px;
  font-weight: normal;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-image: none;
  border-radius: 4px;
  border: 1px solid transparent;
  color: #333;
  background-color: #fff;
  border-color: #ccc;
}

.btn-group>.btn-editor:first-child {
  margin-left: 0;
  -webkit-border-top-left-radius: 4px;
  -moz-border-radius-topleft: 4px;
  border-top-left-radius: 4px;
  -webkit-border-bottom-left-radius: 4px;
  -moz-border-radius-bottomleft: 4px;
  border-bottom-left-radius: 4px;
}

.btn-group>.btn-editor+.btn-editor {
  margin-left: -1px !important;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}

.btn-not-space {
  position: relative;
  float: left;
  margin-left: 0 !important;
  border-radius: inherit;
  border: 1px solid transparent;
  border-color: #ccc;
}

.btn-editor.btn-not-space:hover {
  background-color: rgba(230, 230, 230, 0.32);
}

#preview {
  padding: 1em;
  margin: 0 auto;
  width: 97%;
  border-top: 1px dotted #c8ccd0;
  border-bottom: 1px dotted #c8ccd0;
  clear: both;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>WYSIWYG</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
  <div class="editor-wrapper">
    <div id="editControls">
      <div class="btn-group">
        <a class="btn-editor btn-not-space" data-role="bold" data-ref="#"><b>Bold</b></a>
        <a class="btn-editor btn-not-space" data-role="italic" data-ref="#"><em>Italic</em></a>
        <a class="btn-editor btn-not-space" data-role="underline" data-ref="#"><u><b>U</b></u></a>
        <a class="btn-editor btn-not-space" data-role="strikeThrough" data-ref="#"><strike>abc</strike></a>
      </div>
      <div class="btn-group">
        <a class="btn-editor btn-not-space" data-role="code" data-ref="#"><code>&lt;/&gt;</code></a>
      </div>
    </div>
    <div id="editor" contenteditable></div>
    <textarea id="textarea" name="detail" class="editor-preview" style="display: none;"></textarea>
    <div id="preview" class="editor-preview"></div>
  </div>

</body>

</html>

With Ace Editor:

$(function() {
  var aceEditor = ace.edit("ace-editor");
  aceEditor.setTheme("ace/theme/eclipse");
  aceEditor.session.setMode("ace/mode/html");

  $('#editControls a').click(function(e) {
    switch ($(this).data('role')) {
      case 'p':
        document.execCommand('formatBlock', false, $(this).data('role'));
        break;
        //Specific control for the code button.
      case 'code':
        //enable / disable code mode
        codeMode = !codeMode;
        if (codeMode) {
          // ON: show the code in text mode
          var editor = $("#editor");
          var $aceEditor = $("#ace-editor");

          var formattedHtml = html_beautify(htmlDiv.html());

          aceEditor.setValue(formattedHtml, -1);

          editor.css("display", "none");
          $aceEditor.css("display", "block");

        } else {
          // OFF: reinterpret the code
          htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
          var editor = $("#editor");
          var $aceEditor = $("#ace-editor");

          editor.css("display", "block");
          $aceEditor.css("display", "none");

          htmlDiv.html(aceEditor.getValue().replace(/\r?\n|\r/g, ""));
        }
        break;
      default:
        document.execCommand($(this).data('role'), false, null);
        break;
    }
  });

  //code mode control
  let codeMode = false;
  let htmlDiv = $("#editor");

  htmlDiv.on('keyup', function(e) {
    if (!e.shiftKey && e.keyCode === 13) {
      document.execCommand('formatBlock', false, 'p');
    } else if (e.shiftKey) {
      document.execCommand('formatBlock', false, 'div');
    }
  });

  htmlDiv.on("paste", function(e) {
    e.preventDefault();

    var text = (e.originalEvent || e).clipboardData.getData('text/plain');

    document.execCommand('formatBlock', false, 'div');
    document.execCommand('insertText', false, text);
  });

  //input -> NOT keyup
  htmlDiv.on("input", function(e) {
    //htmlDiv.on("keyup", function(e) {
    $(".editor-preview").val(htmlDiv.html());
    //$("#textarea").html(htmlDiv.html());
    $(".editor-preview").keyup();
    //$(".editor-preview").html(htmlDiv.html());
  });
  //$("#textarea").html(htmlDiv.html());

  aceEditor.getSession().on('change', function() {
    $('.editor-preview').html(aceEditor.getValue().replace(/\r?\n|\r/g, ""));
  });

  $('.editor-preview').keyup(function() {
    //var value = $(this).val();
    var contentAttr = $(this).attr('class');
    if (!codeMode) {
      var value = $(this).val();
      //$( '.' + contentAttr + '' ).html(value);
      $('.' + contentAttr).html(value);
    } else {
      //$( '.' + contentAttr + '' ).html(htmlDiv.text());
      $('.' + contentAttr).html(htmlDiv.text());
    }
  });
});

#editControls {
  overflow: auto;
  border-top: 1px solid transparent;
  border-left: 1px solid transparent;
  border-right: 1px solid transparent;
  border-color: silver;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  padding: .5em 1em .5em 1em;
  background-color: #fbfbfb;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor {
  resize: vertical;
  overflow: auto;
  border: 1px solid silver;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
  min-height: 100px;
  padding: 1em;
  background: white;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor:focus {
  outline: none !important;
  box-shadow: inset 0 0 2px silver;
}

.codeMode {
  font-family: Courier New, Source Code Pro Light, Medium, Source Code Pro ExtraLight, Menlo, Consola, Monaco Linux, Consola Regular, Fira Code Regular, DejaVu Sans Mono;
  /*font-family: inherit;*/
  /*font-family: 'Courier New';*/
  border: 0px;
  font-style: inherit;
  font-variant: inherit;
  font-weight: inherit;
  font-stretch: inherit;
  line-height: inherit;
  vertical-align: baseline;
  box-sizing: inherit;
  color: #fff;
}

.black-bg-colr {
  background-color: #000 !important;
}

.btn-group {
  position: relative;
  display: inline-block;
  font-size: 0;
  vertical-align: middle;
  white-space: nowrap;
}

.btn-group+.btn-group {
  margin-left: 5px;
}

.btn-group a {
  text-decoration: none;
}

.btn-editor {
  height: 30px;
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 0;
  font-size: 11px;
  font-weight: normal;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-image: none;
  border-radius: 4px;
  border: 1px solid transparent;
  color: #333;
  background-color: #fff;
  border-color: #ccc;
}

.btn-group>.btn-editor:first-child {
  margin-left: 0;
  -webkit-border-top-left-radius: 4px;
  -moz-border-radius-topleft: 4px;
  border-top-left-radius: 4px;
  -webkit-border-bottom-left-radius: 4px;
  -moz-border-radius-bottomleft: 4px;
  border-bottom-left-radius: 4px;
}

.btn-group>.btn-editor+.btn-editor {
  margin-left: -1px !important;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}

.btn-not-space {
  position: relative;
  float: left;
  margin-left: 0 !important;
  border-radius: inherit;
  border: 1px solid transparent;
  border-color: #ccc;
}

.btn-editor.btn-not-space:hover {
  background-color: rgba(230, 230, 230, 0.32);
}

#preview {
  padding: 1em;
  margin: 0 auto;
  width: 97%;
  border-top: 1px dotted #c8ccd0;
  border-bottom: 1px dotted #c8ccd0;
  clear: both;
}

#ace-editor {
  resize: vertical;
  overflow: auto;
  border: 1px solid silver;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
  min-height: 100px;
  padding: 1em;
  margin: 0 auto;
  width: 100%;
  display: none;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>WYSIWYG</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.7/ace.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.7/ext-beautify.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.10.3/beautify-html.min.js"></script>
</head>

<body>
  <div class="editor-wrapper">
    <div id="editControls">
      <div class="btn-group">
        <a class="btn-editor btn-not-space" data-role="bold" data-ref="#"><b>Bold</b></a>
        <a class="btn-editor btn-not-space" data-role="italic" data-ref="#"><em>Italic</em></a>
        <a class="btn-editor btn-not-space" data-role="underline" data-ref="#"><u><b>U</b></u></a>
        <a class="btn-editor btn-not-space" data-role="strikeThrough" data-ref="#"><strike>abc</strike></a>
      </div>
      <div class="btn-group">
        <a class="btn-editor btn-not-space" data-role="code" data-ref="#"><code>&lt;/&gt;</code></a>
      </div>
    </div>
    <div id="editor" contenteditable></div>
    <div id="ace-editor"></div>
    <textarea id="textarea" name="detail" class="editor-preview" style="display: none;"></textarea>
    <div id="preview" class="editor-preview"></div>
  </div>

</body>

</html>

Ace Editor with <p> Only:

$(function () {
    var aceEditor = ace.edit("ace-editor");
    aceEditor.setTheme("ace/theme/eclipse");
    aceEditor.session.setMode("ace/mode/html");

    $('#editControls a').click(function (e) {
        switch ($(this).data('role')) {
            case 'p':
                document.execCommand('formatBlock', false, $(this).data('role'));
                break;
            //Specific control for the code button.
            case 'code':
                //enable / disable code mode
                codeMode = !codeMode;
                if (codeMode) {
                    // ON: show the code in text mode
                    var editor = $("#editor");
                    var $aceEditor = $("#ace-editor");

                    var formattedHtml = html_beautify(htmlDiv.html());

                    aceEditor.setValue(formattedHtml, -1);

                    editor.css("display", "none");
                    $aceEditor.css("display", "block");

                } else {
                    // OFF: reinterpret the code
                    htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
                    var editor = $("#editor");
                    var $aceEditor = $("#ace-editor");

                    editor.css("display", "block");
                    $aceEditor.css("display", "none");

                    htmlDiv.html(aceEditor.getValue().replace(/\r?\n|\r/g, ""));
                }
                break;
            default:
                document.execCommand($(this).data('role'), false, null);
                break;
        }
    });

    //code mode control
    let codeMode = false;
    let htmlDiv = $("#editor");

    htmlDiv.on("paste", function (e) {
        e.preventDefault();

        var text = (e.originalEvent || e).clipboardData.getData('text/plain');

        document.execCommand('formatBlock', false, 'p');
        document.execCommand('insertText', false, text);
    });

    //input -> NOT keyup
    htmlDiv.on("input", function (e) {
        document.execCommand('formatBlock', false, 'p');
        //htmlDiv.on("keyup", function(e) {
        $(".editor-preview").val(htmlDiv.html());
        //$("#textarea").html(htmlDiv.html());
        $(".editor-preview").keyup();
        //$(".editor-preview").html(htmlDiv.html());
    });
    //$("#textarea").html(htmlDiv.html());

    aceEditor.getSession().on('change', function () {
        $('.editor-preview').html(aceEditor.getValue().replace(/\r?\n|\r/g, ""));
    });

    $('.editor-preview').keyup(function () {
        //var value = $(this).val();
        var contentAttr = $(this).attr('class');
        if (!codeMode) {
            var value = $(this).val();
            //$( '.' + contentAttr + '' ).html(value);
            $('.' + contentAttr).html(value);
        } else {
            //$( '.' + contentAttr + '' ).html(htmlDiv.text());
            $('.' + contentAttr).html(htmlDiv.text());
        }
    });
});

#editControls {
  overflow: auto;
  border-top: 1px solid transparent;
  border-left: 1px solid transparent;
  border-right: 1px solid transparent;
  border-color: silver;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  padding: .5em 1em .5em 1em;
  background-color: #fbfbfb;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor {
  resize: vertical;
  overflow: auto;
  border: 1px solid silver;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
  min-height: 100px;
  padding: 1em;
  background: white;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor:focus {
  outline: none !important;
  box-shadow: inset 0 0 2px silver;
}

.codeMode {
  font-family: Courier New, Source Code Pro Light, Medium, Source Code Pro ExtraLight, Menlo, Consola, Monaco Linux, Consola Regular, Fira Code Regular, DejaVu Sans Mono;
  /*font-family: inherit;*/
  /*font-family: 'Courier New';*/
  border: 0px;
  font-style: inherit;
  font-variant: inherit;
  font-weight: inherit;
  font-stretch: inherit;
  line-height: inherit;
  vertical-align: baseline;
  box-sizing: inherit;
  color: #fff;
}

.black-bg-colr {
  background-color: #000 !important;
}

.btn-group {
  position: relative;
  display: inline-block;
  font-size: 0;
  vertical-align: middle;
  white-space: nowrap;
}

.btn-group+.btn-group {
  margin-left: 5px;
}

.btn-group a {
  text-decoration: none;
}

.btn-editor {
  height: 30px;
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 0;
  font-size: 11px;
  font-weight: normal;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-image: none;
  border-radius: 4px;
  border: 1px solid transparent;
  color: #333;
  background-color: #fff;
  border-color: #ccc;
}

.btn-group>.btn-editor:first-child {
  margin-left: 0;
  -webkit-border-top-left-radius: 4px;
  -moz-border-radius-topleft: 4px;
  border-top-left-radius: 4px;
  -webkit-border-bottom-left-radius: 4px;
  -moz-border-radius-bottomleft: 4px;
  border-bottom-left-radius: 4px;
}

.btn-group>.btn-editor+.btn-editor {
  margin-left: -1px !important;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}

.btn-not-space {
  position: relative;
  float: left;
  margin-left: 0 !important;
  border-radius: inherit;
  border: 1px solid transparent;
  border-color: #ccc;
}

.btn-editor.btn-not-space:hover {
  background-color: rgba(230, 230, 230, 0.32);
}

#preview {
  padding: 1em;
  margin: 0 auto;
  width: 97%;
  border-top: 1px dotted #c8ccd0;
  border-bottom: 1px dotted #c8ccd0;
  clear: both;
}

#ace-editor {
  resize: vertical;
  overflow: auto;
  border: 1px solid silver;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
  min-height: 100px;
  padding: 1em;
  margin: 0 auto;
  width: 100%;
  display: none;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>WYSIWYG</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.7/ace.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.7/ext-beautify.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.10.3/beautify-html.min.js"></script>
</head>

<body>
  <div class="editor-wrapper">
    <div id="editControls">
      <div class="btn-group">
        <a class="btn-editor btn-not-space" data-role="bold" data-ref="#"><b>Bold</b></a>
        <a class="btn-editor btn-not-space" data-role="italic" data-ref="#"><em>Italic</em></a>
        <a class="btn-editor btn-not-space" data-role="underline" data-ref="#"><u><b>U</b></u></a>
        <a class="btn-editor btn-not-space" data-role="strikeThrough" data-ref="#"><strike>abc</strike></a>
      </div>
      <div class="btn-group">
        <a class="btn-editor btn-not-space" data-role="code" data-ref="#"><code>&lt;/&gt;</code></a>
      </div>
    </div>
    <div id="editor" contenteditable></div>
    <div id="ace-editor"></div>
    <textarea id="textarea" name="detail" class="editor-preview" style="display: none;"></textarea>
    <div id="preview" class="editor-preview"></div>
  </div>

</body>

</html>


问:
Is it possible to include (but not importing) a stand-alone grammar in ANTLR4?
I have a grammar which describes expressions (original, right?).  I want to use this Expressions language inside of other languages.

For example, OtherLanguage.g4:

```<code>grammar OtherLanguage.g4

import Expressions;

keyPair: IDENTIFIER ':' expression;
IDENTIFIER: [a-zA-Z0-9]+
</code>```

If I use import Expressions;, then it generates a valid parser, but it doesn't generate or use ExpressionsParser.ExpressionContext, but instead generates and uses OtherLanguageParser.ExpressionContext.  This means I can't create methods that take in "ExpressionContext" and reuse them in other projects.

Is there a feature of ANTLR4 that will make this work?

In other words, I don't want to "import" the Expressions grammar, but the parser and lexer.

答: Yeah, import really means include---it is not treating the imported grammar as a separate entity for which you can use all of those parts tree objects.</p>

Body:
I have a grammar which describes expressions (original, right?).  I want to use this Expressions language inside of other languages.

For example, OtherLanguage.g4:

grammar OtherLanguage.g4

import Expressions;

keyPair: IDENTIFIER ':' expression;
IDENTIFIER: [a-zA-Z0-9]+

If I use import Expressions;, then it generates a valid parser, but it doesn't generate or use ExpressionsParser.ExpressionContext, but instead generates and uses OtherLanguageParser.ExpressionContext.  This means I can't create methods that take in "ExpressionContext" and reuse them in other projects.

Is there a feature of ANTLR4 that will make this work?

In other words, I don't want to "import" the Expressions grammar, but the parser and lexer.


问:
No python at '\python.exe'
No Python at 'C:\Users\~~~~\python.exe' error keeps coming out..
Even if I deleted my previous python and path, the file location is where I installed my previous python...

I want to use python in VS code and cmd on windows 10.

What I tried to fix it

deleted python 3.7 version and reinstalled python 3.6 version.

removed previous python 3.7 path and added python 3.6 version reinstalled to the Windows Path variable.

remove ';' on windows path variable.

put ';' on windows path variable.

delete and reinstall python on vscode Extensions

答:
If you use venv, then look in that file:
pyvenv.cfg</p>

Title: No python at '\python.exe'