问:
SecurityError: Failed to establish secure connection to 'EOF occurred in violation of protocol (_ssl.c:841)'
I am attempting to connect to Neo4j but I keep getting this error. I tried

```<code>from neo4j.v1 import GraphDatabase
driver = GraphDatabase.driver(uri="bolt://localhost:7687", auth=("neo4j", "12345"))
</code>```

but I get this error when I try to connect

SecurityError: Failed to establish secure connection to 'EOF occurred in violation of protocol (_ssl.c:841)'

I can connect to the browser when I type http://localhost:7474/browser/

Here is the full error log:

--------------------------------------------------------------------------- SSLEOFError                               Traceback (most recent call
  last)
  ~\AppData\Roaming\Python\Python36\site-packages\neobolt\direct.py in
  _secure(s, host, ssl_context, **config)
      853         try:
  --> 854             s = ssl_context.wrap_socket(s, server_hostname=host if HAS_SNI and host else None)
      855         except SSLError as cause:

c:\program files\python36\lib\ssl.py in wrap_socket(self, sock,
  server_side, do_handshake_on_connect, suppress_ragged_eofs,
  server_hostname, session)
      406                          server_hostname=server_hostname,
  --> 407                          _context=self, _session=session)
      408

c:\program files\python36\lib\ssl.py in init(self, sock, keyfile,
  certfile, server_side, cert_reqs, ssl_version, ca_certs,
  do_handshake_on_connect, family, type, proto, fileno,
  suppress_ragged_eofs, npn_protocols, ciphers, server_hostname,
  _context, _session)
      813                         raise ValueError("do_handshake_on_connect should not be specified for
  non-blocking sockets")
  --> 814                     self.do_handshake()
      815

c:\program files\python36\lib\ssl.py in do_handshake(self, block)

  1067                 self.settimeout(None)
  -> 1068             self._sslobj.do_handshake()    1069         finally:

c:\program files\python36\lib\ssl.py in do_handshake(self)
      688         """Start the SSL/TLS handshake."""
  --> 689         self._sslobj.do_handshake()
      690         if self.context.check_hostname:

SSLEOFError: EOF occurred in violation of protocol (_ssl.c:841)

The above exception was the direct cause of the following exception:

SecurityError                             Traceback (most recent call
  last)  in
        1
  ----> 2 driver = GraphDatabase.driver(uri="bolt://localhost:7687", auth=("neo4j", "12345"))

~\AppData\Roaming\Python\Python36\site-packages\neo4j__init__.py in
  driver(cls, uri, **config)
      118         :class:.Driver subclass instance directly.
      119         """
  --> 120         return Driver(uri, **config)
      121
      122

~\AppData\Roaming\Python\Python36\site-packages\neo4j__init__.py in
  new(cls, uri, **config)
      159         for subclass in Driver.subclasses():
      160             if parsed_scheme in subclass.uri_schemes:
  --> 161                 return subclass(uri, **config)
      162         raise ValueError("URI scheme %r not supported" % parsed.scheme)
      163

~\AppData\Roaming\Python\Python36\site-packages\neo4j__init__.py in
  new(cls, uri, **config)
      233
      234         pool = ConnectionPool(connector, instance.address, **config)
  --> 235         pool.release(pool.acquire())
      236         instance._pool = pool
      237         instance._max_retry_time = config.get("max_retry_time", default_config["max_retry_time"])

~\AppData\Roaming\Python\Python36\site-packages\neobolt\direct.py in
  acquire(self, access_mode)
      713
      714     def acquire(self, access_mode=None):
  --> 715         return self.acquire_direct(self.address)
      716
      717

~\AppData\Roaming\Python\Python36\site-packages\neobolt\direct.py in
  acquire_direct(self, address)
      606                 if can_create_new_connection:
      607                     try:
  --> 608                         connection = self.connector(address, error_handler=self.connection_error_handler)
      609                     except ServiceUnavailable:
      610                         self.remove(address)

~\AppData\Roaming\Python\Python36\site-packages\neo4j__init__.py in
  connector(address, **kwargs)
      230
      231         def connector(address, **kwargs):
  --> 232             return connect(address, **dict(config, **kwargs))
      233
      234         pool = ConnectionPool(connector, instance.address, **config)

~\AppData\Roaming\Python\Python36\site-packages\neobolt\direct.py in
  connect(address, **config)
      970         raise ServiceUnavailable("Failed to resolve addresses for %s" % address)
      971     else:
  --> 972         raise last_error

~\AppData\Roaming\Python\Python36\site-packages\neobolt\direct.py in
  connect(address, **config)
      961             host = address[0]
      962             s = _connect(resolved_address, **config)
  --> 963             s, der_encoded_server_certificate = _secure(s, host, security_plan.ssl_context, **config)
      964             connection = _handshake(s, address, der_encoded_server_certificate, **config)
      965         except Exception as error:

~\AppData\Roaming\Python\Python36\site-packages\neobolt\direct.py in
  _secure(s, host, ssl_context, **config)
      857             error = SecurityError("Failed to establish secure connection to {!r}".format(cause.args[1]))
      858             error.cause = cause
  --> 859             raise error
      860         else:
      861             # Check that the server provides a certificate

SecurityError: Failed to establish secure connection to 'EOF occurred
  in violation of protocol (_ssl.c:841)'

答:
I had the same problem with the Object Graph Mapper Neomodel (connecting to neo4j v4). Adding the second line solved it:</p>

```<code>config.DATABASE_URL = 'bolt://neo4j:password123@localhost:7687'
config.ENCRYPTED_CONNECTION = False
</code>```

Body:
I am attempting to connect to Neo4j but I keep getting this error. I tried

from neo4j.v1 import GraphDatabase
driver = GraphDatabase.driver(uri="bolt://localhost:7687", auth=("neo4j", "12345"))

but I get this error when I try to connect

SecurityError: Failed to establish secure connection to 'EOF occurred in violation of protocol (_ssl.c:841)'

I can connect to the browser when I type http://localhost:7474/browser/

Here is the full error log:

--------------------------------------------------------------------------- SSLEOFError                               Traceback (most recent call
  last)
  ~\AppData\Roaming\Python\Python36\site-packages\neobolt\direct.py in
  _secure(s, host, ssl_context, **config)
      853         try:
  --> 854             s = ssl_context.wrap_socket(s, server_hostname=host if HAS_SNI and host else None)
      855         except SSLError as cause:

c:\program files\python36\lib\ssl.py in wrap_socket(self, sock,
  server_side, do_handshake_on_connect, suppress_ragged_eofs,
  server_hostname, session)
      406                          server_hostname=server_hostname,
  --> 407                          _context=self, _session=session)
      408

c:\program files\python36\lib\ssl.py in init(self, sock, keyfile,
  certfile, server_side, cert_reqs, ssl_version, ca_certs,
  do_handshake_on_connect, family, type, proto, fileno,
  suppress_ragged_eofs, npn_protocols, ciphers, server_hostname,
  _context, _session)
      813                         raise ValueError("do_handshake_on_connect should not be specified for
  non-blocking sockets")
  --> 814                     self.do_handshake()
      815

c:\program files\python36\lib\ssl.py in do_handshake(self, block)

  1067                 self.settimeout(None)
  -> 1068             self._sslobj.do_handshake()    1069         finally:

c:\program files\python36\lib\ssl.py in do_handshake(self)
      688         """Start the SSL/TLS handshake."""
  --> 689         self._sslobj.do_handshake()
      690         if self.context.check_hostname:

SSLEOFError: EOF occurred in violation of protocol (_ssl.c:841)

The above exception was the direct cause of the following exception:

SecurityError                             Traceback (most recent call
  last)  in
        1
  ----> 2 driver = GraphDatabase.driver(uri="bolt://localhost:7687", auth=("neo4j", "12345"))

~\AppData\Roaming\Python\Python36\site-packages\neo4j__init__.py in
  driver(cls, uri, **config)
      118         :class:.Driver subclass instance directly.
      119         """
  --> 120         return Driver(uri, **config)
      121
      122

~\AppData\Roaming\Python\Python36\site-packages\neo4j__init__.py in
  new(cls, uri, **config)
      159         for subclass in Driver.subclasses():
      160             if parsed_scheme in subclass.uri_schemes:
  --> 161                 return subclass(uri, **config)
      162         raise ValueError("URI scheme %r not supported" % parsed.scheme)
      163

~\AppData\Roaming\Python\Python36\site-packages\neo4j__init__.py in
  new(cls, uri, **config)
      233
      234         pool = ConnectionPool(connector, instance.address, **config)
  --> 235         pool.release(pool.acquire())
      236         instance._pool = pool
      237         instance._max_retry_time = config.get("max_retry_time", default_config["max_retry_time"])

~\AppData\Roaming\Python\Python36\site-packages\neobolt\direct.py in
  acquire(self, access_mode)
      713
      714     def acquire(self, access_mode=None):
  --> 715         return self.acquire_direct(self.address)
      716
      717

~\AppData\Roaming\Python\Python36\site-packages\neobolt\direct.py in
  acquire_direct(self, address)
      606                 if can_create_new_connection:
      607                     try:
  --> 608                         connection = self.connector(address, error_handler=self.connection_error_handler)
      609                     except ServiceUnavailable:
      610                         self.remove(address)

~\AppData\Roaming\Python\Python36\site-packages\neo4j__init__.py in
  connector(address, **kwargs)
      230
      231         def connector(address, **kwargs):
  --> 232             return connect(address, **dict(config, **kwargs))
      233
      234         pool = ConnectionPool(connector, instance.address, **config)

~\AppData\Roaming\Python\Python36\site-packages\neobolt\direct.py in
  connect(address, **config)
      970         raise ServiceUnavailable("Failed to resolve addresses for %s" % address)
      971     else:
  --> 972         raise last_error

~\AppData\Roaming\Python\Python36\site-packages\neobolt\direct.py in
  connect(address, **config)
      961             host = address[0]
      962             s = _connect(resolved_address, **config)
  --> 963             s, der_encoded_server_certificate = _secure(s, host, security_plan.ssl_context, **config)
      964             connection = _handshake(s, address, der_encoded_server_certificate, **config)
      965         except Exception as error:

~\AppData\Roaming\Python\Python36\site-packages\neobolt\direct.py in
  _secure(s, host, ssl_context, **config)
      857             error = SecurityError("Failed to establish secure connection to {!r}".format(cause.args[1]))
      858             error.cause = cause
  --> 859             raise error
      860         else:
      861             # Check that the server provides a certificate

SecurityError: Failed to establish secure connection to 'EOF occurred
  in violation of protocol (_ssl.c:841)'

Body:
I had the same problem with the Object Graph Mapper Neomodel (connecting to neo4j v4). Adding the second line solved it:

config.DATABASE_URL = 'bolt://neo4j:password123@localhost:7687'
config.ENCRYPTED_CONNECTION = False


来源: stackexchange

问:
css gradient background on  that stretches to 100% width and height
So I'd like to have a gradient that fills 100% of the background of a webpage. For browsers that can't handle it, a solid color is fine.

here is my current css:

```<code>html {
height: 100%;
}
body {
height: 100%;
margin: 0;
padding: 0;
background-repeat: no-repeat;
background: #afb1b4; /* Old browsers */
background: -moz-linear-gradient(top, #afb1b4 0%, #696a6d 100%) no-repeat; /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#afb1b4), color-stop(100%,#696a6d)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #afb1b4 0%,#696a6d 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #afb1b4 0%,#696a6d 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #afb1b4 0%,#696a6d 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#AFB1B4', endColorstr='#696A6D',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #afb1b4 0%,#696a6d 100%); /* W3C */
}
</code>```

It seemed to work out while the page had little content, but as I've filled out the page with more content, navigation, etcetera, there is now some white at the bottom. maybe 100px or so. Am I doing this wrong? Do I need to be offsetting some padding somewhere?

答: Get rid of your height: 100% declarations. It seems like setting the height to 100% just sets it to 100% of the viewport, not actually 100% of the page itself.

ContentLicense: CC BY-SA 3.0

Title: css gradient background on <body> that stretches to 100% width and height

Body:
So I'd like to have a gradient that fills 100% of the background of a webpage. For browsers that can't handle it, a solid color is fine.

here is my current css:

html {
height: 100%;
}
body {
height: 100%;
margin: 0;
padding: 0;
background-repeat: no-repeat;
background: #afb1b4; /* Old browsers */
background: -moz-linear-gradient(top, #afb1b4 0%, #696a6d 100%) no-repeat; /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#afb1b4), color-stop(100%,#696a6d)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #afb1b4 0%,#696a6d 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #afb1b4 0%,#696a6d 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #afb1b4 0%,#696a6d 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#AFB1B4', endColorstr='#696A6D',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #afb1b4 0%,#696a6d 100%); /* W3C */
}

It seemed to work out while the page had little content, but as I've filled out the page with more content, navigation, etcetera, there is now some white at the bottom. maybe 100px or so. Am I doing this wrong? Do I need to be offsetting some padding somewhere?


问:
How to parse a complicated nested JSON string in C#?
I have an ugly JSON string that is getting returned from an API that looks like this (this is the result of Console.Write on the string):

```<code>{"d":"\"\\\"\\\\\\\"[{\\\\\\\\\\\\\\\"foo\\\\\\\\\\\\\\\":15,\\\\\\\\\\\\\\\"bar\\\\\\\\\\\\\\\":null}]\\\\\\\"\\\"\\n\""}
</code>```

I am trying to parse this into a C# object in the simplest way possible, so I can access properties like foo and bar. But I am having a difficult time doing this.

I have tried parsing it a number of ways, including:

```<code>// code to get the response string
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
var serializedData = "{data: 'data'}";
var responseString = client.UploadString(url, "POST", serializedData);

// parse the response string
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
</code>```

This allows me to access the value of d, which is the actual string I need to parse. I then tried to parse that separately using JArray.Parse(obj["d"]), but I get an error saying that obj["d"] is not an array.

Unfortunately, I have no access to the API itself so can't modify how it's serializing the data it's returning.

Any suggestions?

答:
The problem is that the value of "d" is a string representing a string representing a string ... representing an array. You could call it JSON serialization "inception".

The way to deal with this is to deserialize the value corresponding number of times. If you're sure that the value is never going to be an actual string, you could do it like this, without having to know how many times the value was serialized:

```<code>var myObject = JObject.Parse(s);
var d = myObject["d"];
while(d.Type == JTokenType.String)
    d = JToken.Parse(d.ToObject<string>());
myObject["d"] = d;
</code>```

After this procedure myObject represents this data:

```<code>{
  "d": [
    {
      "foo": 15,
      "bar": null
    }
  ]
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an ugly JSON string that is getting returned from an API that looks like this (this is the result of Console.Write on the string):

{"d":"\"\\\"\\\\\\\"[{\\\\\\\\\\\\\\\"foo\\\\\\\\\\\\\\\":15,\\\\\\\\\\\\\\\"bar\\\\\\\\\\\\\\\":null}]\\\\\\\"\\\"\\n\""}

I am trying to parse this into a C# object in the simplest way possible, so I can access properties like foo and bar. But I am having a difficult time doing this.

I have tried parsing it a number of ways, including:

// code to get the response string
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
var serializedData = "{data: 'data'}";
var responseString = client.UploadString(url, "POST", serializedData);

// parse the response string
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);

This allows me to access the value of d, which is the actual string I need to parse. I then tried to parse that separately using JArray.Parse(obj["d"]), but I get an error saying that obj["d"] is not an array.

Unfortunately, I have no access to the API itself so can't modify how it's serializing the data it's returning.

Any suggestions?

Body:
The problem is that the value of "d" is a string representing a string representing a string ... representing an array. You could call it JSON serialization "inception".

The way to deal with this is to deserialize the value corresponding number of times. If you're sure that the value is never going to be an actual string, you could do it like this, without having to know how many times the value was serialized:

var myObject = JObject.Parse(s);
var d = myObject["d"];
while(d.Type == JTokenType.String)
    d = JToken.Parse(d.ToObject<string>());
myObject["d"] = d;

After this procedure myObject represents this data:

{
  "d": [
    {
      "foo": 15,
      "bar": null
    }
  ]
}


问:
Preview Laravel Mail before sending
I want to edit my mail and change everything, if I want, as shown here.

Ive imported my file and created a test route to view the page:

```<code>use Illuminate\Mail\Markdown;

Route::get('/mail/html', function () {
    $markdown = new Markdown(view(), config('mail.markdown'));
    return $markdown->render('vendor.mail.html.message'); // or ..markdown.message
});
</code>```

However, Im having variable errors for @slot. How to view my change/see what the mail looks like before sending? Another package for that?

Thanks

答:
To preview your email in browser please add below code to route

```<code>Route::get('preview-notification', function () {
 $markdown = new \Illuminate\Mail\Markdown(view(), config('mail.markdown'));
 $data = "Your data to be use in blade file";
 return $markdown->render("path-of-your-templete-blade-file", $data]);
});
</code>```

and you will be access your templete using

```<code>http://your-application-url/preview-notification
</code>```

Title: Preview Laravel Mail before sending

Body:
I want to edit my mail and change everything, if I want, as shown here.

Ive imported my file and created a test route to view the page:

use Illuminate\Mail\Markdown;

Route::get('/mail/html', function () {
    $markdown = new Markdown(view(), config('mail.markdown'));
    return $markdown->render('vendor.mail.html.message'); // or ..markdown.message
});

However, Im having variable errors for @slot. How to view my change/see what the mail looks like before sending? Another package for that?

Thanks

Body:
To preview your email in browser please add below code to route

Route::get('preview-notification', function () {
 $markdown = new \Illuminate\Mail\Markdown(view(), config('mail.markdown'));
 $data = "Your data to be use in blade file";
 return $markdown->render("path-of-your-templete-blade-file", $data]);
});

and you will be access your templete using

http://your-application-url/preview-notification


问:
Let a bool method return other integer
```<code>class I {
public:
    virtual bool F() = 0;
};

class A :public I {
public:
    virtual bool F() {
        int i = 2;
        return i;
    }
};

void test() {
    A a;
    int i=a.F();
    std::cout << i;
}
</code>```

class I is a protocol which is not easy to change.

Want to pass more information than true/false, so want to use the uint8_t property of bool in C++.

But the compiler (VS2019/VS2017) add instructions to convert integer to 0 or 1 at the end of the bool method before return. No converstion on the caller side (only a movzx eax, al instruction) which is good.

Is there a method like a compilation flag or some embedded assembly code at the end of the bool method to let the bool method return an integer other than 0/1?

答:
Simple disclaimer is that this answer is in NO WAY good for production usage. It uses a behaviour which is generally undefined.

You can use reinterpret_cast to convert your return value to boolean without actually triggering a bool constructor (hence not changing the actual value to 0/1).

```<code>class A :public I {
public:
    virtual bool F() {
        int i = 2;
        return *reinterpret_cast<bool *>(&i);;
    }
};
</code>```

Title: Let a bool method return other integer

Body:
class I {
public:
    virtual bool F() = 0;
};

class A :public I {
public:
    virtual bool F() {
        int i = 2;
        return i;
    }
};

void test() {
    A a;
    int i=a.F();
    std::cout << i;
}

class I is a protocol which is not easy to change.

Want to pass more information than true/false, so want to use the uint8_t property of bool in C++.

But the compiler (VS2019/VS2017) add instructions to convert integer to 0 or 1 at the end of the bool method before return. No converstion on the caller side (only a movzx eax, al instruction) which is good.

Is there a method like a compilation flag or some embedded assembly code at the end of the bool method to let the bool method return an integer other than 0/1?

Body:
Simple disclaimer is that this answer is in NO WAY good for production usage. It uses a behaviour which is generally undefined.

You can use reinterpret_cast to convert your return value to boolean without actually triggering a bool constructor (hence not changing the actual value to 0/1).

class A :public I {
public:
    virtual bool F() {
        int i = 2;
        return *reinterpret_cast<bool *>(&i);;
    }
};


问:
Browser back button is not working while applying page transition effect in jQuery
I am using page transition for my website. When goto other pages transition effect applies. While doing this browser back button is not working. I have pasted the jQuery code used for transition effect.</p>

```<code><script>
    $(document).ready(function() {
            $("a").click(function() {
              $link = $(this).attr("href");
              $("body").fadeOut(500);
              setTimeout(function() {
                window.location.replace($link);
              }, 500);
              return false;
            });
     });
</script>
</code>```

答:
Hope this help you.</p>

```<code>$(document).ready(function() {
        $("a").click(function() {
          $link = $(this).attr("href");
          $("body").fadeOut(500);
          setTimeout(function() {
              console.log($link);
            window.location = $link;
          }, 500);
          return false;
        });
 });
</code>```

Body:
Hope this help you.

$(document).ready(function() {
        $("a").click(function() {
          $link = $(this).attr("href");
          $("body").fadeOut(500);
          setTimeout(function() {
              console.log($link);
            window.location = $link;
          }, 500);
          return false;
        });
 });


问:
C# how to trigg a key event in a tabcontrol specific tab?
I have an tabControl1 in my form with three TabPages named TabPage1, TabPage2 and TabPage3.

When TabPage 2 has focus I need to raise an key event (arrow keys for navigation).
This event should not be raised in the other TabPages.

Anybody know how?

答:
A C# version of msarchet's answer:

```<code>using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualBasic;

public class Form1
{

    // give a variable as a TabPage here so we know which one is selected(in focus)
    private TabPage selectedPage = TabPage1;

    // If a key is pressed when the tab control has focus, it checks to see if it is the right tab page
    // and then show a message box(for demonstration)
    private void TabControl1_KeyDown(System.Object sender, System.Windows.Forms.KeyEventArgs e)
    {
        // The IF Not is to basically catch any odd happening that might occur if a key stroke gets passed with
        // no selected tab page
        if (!selectedPage == null)
        {
            // If the tabpage is TabPage2
            if (selectedPage.Name == "TabPage2")
                MessageBox.Show("Key Pressed");
        }
    }

    // This handles the actual chaning of the tab pages
    private void TabControl1_Selected(System.Object sender, System.Windows.Forms.TabControlEventArgs e)
    {
        selectedPage = TabControl1.SelectedTab;
    }
}
</code>```

I hope this helps you :)

ContentLicense: CC BY-SA 2.5

Body:
A C# version of msarchet's answer:

using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualBasic;

public class Form1
{

    // give a variable as a TabPage here so we know which one is selected(in focus)
    private TabPage selectedPage = TabPage1;

    // If a key is pressed when the tab control has focus, it checks to see if it is the right tab page
    // and then show a message box(for demonstration)
    private void TabControl1_KeyDown(System.Object sender, System.Windows.Forms.KeyEventArgs e)
    {
        // The IF Not is to basically catch any odd happening that might occur if a key stroke gets passed with
        // no selected tab page
        if (!selectedPage == null)
        {
            // If the tabpage is TabPage2
            if (selectedPage.Name == "TabPage2")
                MessageBox.Show("Key Pressed");
        }
    }

    // This handles the actual chaning of the tab pages
    private void TabControl1_Selected(System.Object sender, System.Windows.Forms.TabControlEventArgs e)
    {
        selectedPage = TabControl1.SelectedTab;
    }
}

I hope this helps you :)


问:
Multiple if and for loop in list comprehension
I am facing issue while converting my below code in list comprehension

```<code>A = {
  "name": ['sahil', 'pankaj', 'honey'],
  'test': 'data'
}

Mylist = []
for k, v in A.items():
    if isinstance(v, list):
        for i in v:
            Mylist.append(i)
    else:
        Mylist.append(v)
</code>```

I tried this code via list comprehension but failed to get the result

```<code>Mylist = [i
  for k, v in A.items() if isinstance(v, list) for i in v
  else i = v
]
</code>```

I am facing issue syntax error.

答:
You could use the keys() method of the dict structure to get the values into a list. Hope this helps too

```<code>  A = {
    "name": ['sahil', 'pankaj', 'honey'],
    "test": 'data'
  }

 Mylist = []
 for k in A.keys():
    if k == "name":
       Mylist.extend(A[k]) #using extend as we already have a list present in the value for the dict, this just concatenates into one main list
    else:
       Mylist.append(A[k])
 print(Mylist)
</code>```

OR just using a list comprehension:

```<code>   A = {
    "name": ['sahil', 'pankaj', 'honey'],
    "test": 'data'
   }
   Mylist = [v for (k,v) in A.items() if k == "name"] #only returns values for k equal to "name"

   print(Mylist)
</code>```

Body:
I am facing issue while converting my below code in list comprehension

A = {
  "name": ['sahil', 'pankaj', 'honey'],
  'test': 'data'
}

Mylist = []
for k, v in A.items():
    if isinstance(v, list):
        for i in v:
            Mylist.append(i)
    else:
        Mylist.append(v)

I tried this code via list comprehension but failed to get the result

Mylist = [i
  for k, v in A.items() if isinstance(v, list) for i in v
  else i = v
]

I am facing issue syntax error.

Body:
You could use the keys() method of the dict structure to get the values into a list. Hope this helps too

  A = {
    "name": ['sahil', 'pankaj', 'honey'],
    "test": 'data'
  }

 Mylist = []
 for k in A.keys():
    if k == "name":
       Mylist.extend(A[k]) #using extend as we already have a list present in the value for the dict, this just concatenates into one main list
    else:
       Mylist.append(A[k])
 print(Mylist)

OR just using a list comprehension:

   A = {
    "name": ['sahil', 'pankaj', 'honey'],
    "test": 'data'
   }
   Mylist = [v for (k,v) in A.items() if k == "name"] #only returns values for k equal to "name"

   print(Mylist)


问:
the closest Sunday before given date with JavaScript
I need to know the date for last Sunday for given date in php & javascript

Let's have a function give_me_last_Sunday

```<code>give_me_last_Sunday('20110517') is 20110515
give_me_last_Sunday('20110604') is 20110529
</code>```

The full backup is done on Sundays = weekly. If I want to restore daily backup I need full (weekly) and daily backup. I need to copy backup files before restoring to temp directory so I restoring daily backup I need to know what weekly backup file I need to copy along the daily file.

My thought was to get Julian representation (or something similar) for the given date and then subtract 1 and check if it is Sunday ... Not sure if this is the best idea and how to convert given date into something I can subtract.

答:
Based on Thomas' effort, and provided the input string is exactly the format you specified, then:

```<code>function lastSunday(d) {
  var d = d.replace(/(^\d{4})(\d{2})(\d{2}$)/,'$1/$2/$3');
  d = new Date(d);
  d.setDate(d.getDate() - d.getDay());
  return d;
}
</code>```

Edit

If I were to write that now, I'd not depend on the Date object parsing the string but do it myself:

```<code>function lastSunday(s) {
  var d = new Date(s.substring(0,4), s.substring(4,6) - 1, s.substring(6));
  d.setDate(d.getDate() - d.getDay());
  return d;
}
</code>```

While the format yyyy/mm/dd is parsed correctly by all browsers I've tested, I think it's more robust to stick to basic methods. Particularly when they are likely more efficient.

Body:
I need to know the date for last Sunday for given date in php & javascript

Let's have a function give_me_last_Sunday

give_me_last_Sunday('20110517') is 20110515
give_me_last_Sunday('20110604') is 20110529

The full backup is done on Sundays = weekly. If I want to restore daily backup I need full (weekly) and daily backup. I need to copy backup files before restoring to temp directory so I restoring daily backup I need to know what weekly backup file I need to copy along the daily file.

My thought was to get Julian representation (or something similar) for the given date and then subtract 1 and check if it is Sunday ... Not sure if this is the best idea and how to convert given date into something I can subtract.

Body:
Based on Thomas' effort, and provided the input string is exactly the format you specified, then:

function lastSunday(d) {
  var d = d.replace(/(^\d{4})(\d{2})(\d{2}$)/,'$1/$2/$3');
  d = new Date(d);
  d.setDate(d.getDate() - d.getDay());
  return d;
}

Edit

If I were to write that now, I'd not depend on the Date object parsing the string but do it myself:

function lastSunday(s) {
  var d = new Date(s.substring(0,4), s.substring(4,6) - 1, s.substring(6));
  d.setDate(d.getDate() - d.getDay());
  return d;
}

While the format yyyy/mm/dd is parsed correctly by all browsers I've tested, I think it's more robust to stick to basic methods. Particularly when they are likely more efficient.


问:
Chrome - disable all styles from specific .css file
When inspecting a web site, is it possible to disable a particular .css file? I can do it in FireFox but can't find the option in Chrome.</p>

答:
```<code><script>

var stylesheet0 = document.styleSheets[0];
var stylesheet1 = document.styleSheets[1];
var stylesheet2 = document.styleSheets[2];

stylesheet0.disabled = true;
stylesheet1.disabled = true;
stylesheet2.disabled = true;

</script>
</code>```


问:
How do I increase the brightness of an image in java?
What I'm trying to do is use for loops to increase the brightness of an image. I'm trying to use for loops to find each pixel and change the brightness by a certain amount. I want to create an array and save the image in that array and then it will print out the new image in the same folder. Also in my code I've made a reflection method which takes each pixel and reflects the image vertically. To run the program the user will have to type the image name and the name of the output file in CMD. Here's my entire code:</p>

```<code>import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;

public class ImageProcessor {
    public static void main(String[] args){

    if(args.length < 3){
        System.out.println("Not enough arguments");
        System.exit(-1);
        }
        String function = args[0];
        if (function.equals("-reflectV"))
      {
      String inputFileName = args[1];
      String outputFileName = args[2];

       int [][] imageArr = readGrayscaleImage(inputFileName);
       int [][] reflectedArr = reflectV(imageArr);

       writeGrayscaleImage(outputFileName, reflectedArr);
      }
      else if (function.equals("-ascii")){
      String inputFileName = args[1];
      String outputFileName = args[2];

      int [][] imageArr = readGrayscaleImage(inputFileName);
      int [][] reflectedArr = reflectV(imageArr);
      try{
      PrintStream output = new PrintStream(new File("output.txt"));
      }
      catch (java.io.FileNotFoundException ex) {
      System.out.println("Error: File Not Found");
      System.exit(-1);
      }
      }

     else if (function.equals("-adjustBrightness")){
        String amount = args[1];
        int a = Integer.parseInt(amount);
        System.out.print(a)
 }

     public static int[][] reflectV(int[][] arr){
        int[][] reflected = new int[arr.length][arr[0].length];
        for(int i=0; i< arr.length; i++){
            for(int j=0; j<arr[i].length;j++){
                reflected[i][j] = arr[i][arr[i].length-1-j];
            }
        }

        return reflected;
    }

    public static int[][] readGrayscaleImage(String filename) {
        int [][] result = null; //create the array
        try {
            File imageFile = new File(filename);    //create the file
            BufferedImage image = ImageIO.read(imageFile);
            int height = image.getHeight();
            int width  = image.getWidth();
            result = new int[height][width];        //read each pixel value
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    int rgb = image.getRGB(x, y);
                    result[y][x] = rgb & 0xff;
                }
            }
        }
        catch (IOException ioe) {
            System.err.println("Problems reading file named " + filename);
            System.exit(-1);
        }
        return result;  //once we're done filling it, return the new array
    }

    public static void writeGrayscaleImage(String filename, int[][] array) {
        int width = array[0].length;
        int height = array.length;

        try {
            BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);    //create the image

            //set all its pixel values based on values in the input array
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    int rgb = array[y][x];
                    rgb |= rgb << 8;
                    rgb |= rgb << 16;
                    image.setRGB(x, y, rgb);
                }
            }

            //write the image to a file
            File imageFile = new File(filename);
            ImageIO.write(image, "jpg", imageFile);
        }
        catch (IOException ioe) {
            System.err.println("Problems writing file named " + filename);
            System.exit(-1);
        }
    }
}
</code>```

答:
I hope this code will help!</p>

```<code>import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.awt.Color;

public class Brighter
{
     public static void main(String args[])
     {
          BufferedImage img=null;
          try
          {
             img=ImageIO.read(new File("file_path")); // read image
             for(int i=0;i<img.getHeight();i++)
             {
                for(int j=0;j<img.getWidth();j++)
                {
                    int  color =  image.getRGB(j,i);
                    int  alpha = (color & 0x00ff0000) >> 24;
                    int  red   = (color & 0x00ff0000) >> 16;
                    int  green = (color & 0x0000ff00) >> 8;
                    int  blue  =  color & 0x000000ff;
                    Color c=new Color(red, green, blue);
                    c=c.brighter();
                    red=c.getRed();
                    green=c.getGreen();
                    blue=c.getBlue();
                    color=(alpha<<24) | (red<<16) | (green<<8) & (blue);
                    img.setRGB(j,i,color);
                }
             }
             ImageIO.write(img,"jpg",new File("output.jpg"));
          }catch(IOException e){}
     }
}
</code>```

Body:
What I'm trying to do is use for loops to increase the brightness of an image. I'm trying to use for loops to find each pixel and change the brightness by a certain amount. I want to create an array and save the image in that array and then it will print out the new image in the same folder. Also in my code I've made a reflection method which takes each pixel and reflects the image vertically. To run the program the user will have to type the image name and the name of the output file in CMD. Here's my entire code:

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;

public class ImageProcessor {
    public static void main(String[] args){

    if(args.length < 3){
        System.out.println("Not enough arguments");
        System.exit(-1);
        }
        String function = args[0];
        if (function.equals("-reflectV"))
      {
      String inputFileName = args[1];
      String outputFileName = args[2];

       int [][] imageArr = readGrayscaleImage(inputFileName);
       int [][] reflectedArr = reflectV(imageArr);

       writeGrayscaleImage(outputFileName, reflectedArr);
      }
      else if (function.equals("-ascii")){
      String inputFileName = args[1];
      String outputFileName = args[2];

      int [][] imageArr = readGrayscaleImage(inputFileName);
      int [][] reflectedArr = reflectV(imageArr);
      try{
      PrintStream output = new PrintStream(new File("output.txt"));
      }
      catch (java.io.FileNotFoundException ex) {
      System.out.println("Error: File Not Found");
      System.exit(-1);
      }
      }

     else if (function.equals("-adjustBrightness")){
        String amount = args[1];
        int a = Integer.parseInt(amount);
        System.out.print(a)
 }

     public static int[][] reflectV(int[][] arr){
        int[][] reflected = new int[arr.length][arr[0].length];
        for(int i=0; i< arr.length; i++){
            for(int j=0; j<arr[i].length;j++){
                reflected[i][j] = arr[i][arr[i].length-1-j];
            }
        }

        return reflected;
    }

    public static int[][] readGrayscaleImage(String filename) {
        int [][] result = null; //create the array
        try {
            File imageFile = new File(filename);    //create the file
            BufferedImage image = ImageIO.read(imageFile);
            int height = image.getHeight();
            int width  = image.getWidth();
            result = new int[height][width];        //read each pixel value
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    int rgb = image.getRGB(x, y);
                    result[y][x] = rgb & 0xff;
                }
            }
        }
        catch (IOException ioe) {
            System.err.println("Problems reading file named " + filename);
            System.exit(-1);
        }
        return result;  //once we're done filling it, return the new array
    }

    public static void writeGrayscaleImage(String filename, int[][] array) {
        int width = array[0].length;
        int height = array.length;

        try {
            BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);    //create the image

            //set all its pixel values based on values in the input array
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    int rgb = array[y][x];
                    rgb |= rgb << 8;
                    rgb |= rgb << 16;
                    image.setRGB(x, y, rgb);
                }
            }

            //write the image to a file
            File imageFile = new File(filename);
            ImageIO.write(image, "jpg", imageFile);
        }
        catch (IOException ioe) {
            System.err.println("Problems writing file named " + filename);
            System.exit(-1);
        }
    }
}

Body:
I hope this code will help!

import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.awt.Color;

public class Brighter
{
     public static void main(String args[])
     {
          BufferedImage img=null;
          try
          {
             img=ImageIO.read(new File("file_path")); // read image
             for(int i=0;i<img.getHeight();i++)
             {
                for(int j=0;j<img.getWidth();j++)
                {
                    int  color =  image.getRGB(j,i);
                    int  alpha = (color & 0x00ff0000) >> 24;
                    int  red   = (color & 0x00ff0000) >> 16;
                    int  green = (color & 0x0000ff00) >> 8;
                    int  blue  =  color & 0x000000ff;
                    Color c=new Color(red, green, blue);
                    c=c.brighter();
                    red=c.getRed();
                    green=c.getGreen();
                    blue=c.getBlue();
                    color=(alpha<<24) | (red<<16) | (green<<8) & (blue);
                    img.setRGB(j,i,color);
                }
             }
             ImageIO.write(img,"jpg",new File("output.jpg"));
          }catch(IOException e){}
     }
}


问:
SELECT all (but one column as null)
in mysql, is it possible to get all columns and data from a table, but select the ID column as NULL?

Something like

```<code>SELECT *, id AS (SELECT '') FROM my_table WHERE 1
</code>```

I want to pull in the ID column, so it doesn't mess up the column count for a later data load, but I want to eliminate the column's value so it doesn't cause key conflicts.

Thanks!

答:
Since it sounds like this is preparatory to a data dump anyway, use a temp table</p>

```<code>CREATE TEMP TABLE t000 AS SELECT * FROM my_table; -- or INSERT INTO
UPDATE t000 SET id = NULL;
</code>```

Title: SELECT all (but one column as null)

Body:
in mysql, is it possible to get all columns and data from a table, but select the ID column as NULL?

Something like

SELECT *, id AS (SELECT '') FROM my_table WHERE 1

I want to pull in the ID column, so it doesn't mess up the column count for a later data load, but I want to eliminate the column's value so it doesn't cause key conflicts.

Thanks!

Body:
Since it sounds like this is preparatory to a data dump anyway, use a temp table

CREATE TEMP TABLE t000 AS SELECT * FROM my_table; -- or INSERT INTO
UPDATE t000 SET id = NULL;


问:
How to apply multiple conditional statements in selenium webdriver python
I am fairly new to Selenium, I am trying to find a Contact info element in a page, and click it if it exists. Many times, what happens is, the element is in all caps such as CONTACT, sometimes Contact and sometimes contact. So I've stored these cases in a variable and I'm using find_element_by_partial_link_text to find the right element and click on it. I'm using exception handling (try and except) and if loop to check each condition. This is my code:

```<code>from selenium import webdriver
import time
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException

browser = webdriver.Chrome()
browser.implicitly_wait(30)
browser.maximize_window()

ab = 'Contact'
bc = 'CONTACT'
cd = 'contact'

browser.get('https://www.dominos.co.in/store-location/pune')

try:
    if browser.find_element_by_partial_link_text(ab).is_displayed():
        browser.find_element_by_partial_link_text(ab).click()

    elif browser.find_element_by_partial_link_text(bc).is_displayed():
        browser.find_element_by_partial_link_text(bc).click()

    elif browser.find_element_by_partial_link_text(cd).is_displayed():
        browser.find_element_by_partial_link_text(cd).click()

except NoSuchElementException:
    print("No such element found")
    browser.close()
</code>```

So if Contact element is present in any webpage, this code is able to click on it, but if other two elements are present, it goes directly into except and prints No such element found. If you guys could help me tackle this scenario, I would really appreciate it :)

答:
Try using  translate() functions  in xpath ,these functions helps you to deal with case sensitivity.

Hope this helps.

Body:
I am fairly new to Selenium, I am trying to find a Contact info element in a page, and click it if it exists. Many times, what happens is, the element is in all caps such as CONTACT, sometimes Contact and sometimes contact. So I've stored these cases in a variable and I'm using find_element_by_partial_link_text to find the right element and click on it. I'm using exception handling (try and except) and if loop to check each condition. This is my code:

from selenium import webdriver
import time
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException

browser = webdriver.Chrome()
browser.implicitly_wait(30)
browser.maximize_window()

ab = 'Contact'
bc = 'CONTACT'
cd = 'contact'

browser.get('https://www.dominos.co.in/store-location/pune')

try:
    if browser.find_element_by_partial_link_text(ab).is_displayed():
        browser.find_element_by_partial_link_text(ab).click()

    elif browser.find_element_by_partial_link_text(bc).is_displayed():
        browser.find_element_by_partial_link_text(bc).click()

    elif browser.find_element_by_partial_link_text(cd).is_displayed():
        browser.find_element_by_partial_link_text(cd).click()

except NoSuchElementException:
    print("No such element found")
    browser.close()

So if Contact element is present in any webpage, this code is able to click on it, but if other two elements are present, it goes directly into except and prints No such element found. If you guys could help me tackle this scenario, I would really appreciate it :)


问:
Gensim LDA Coherence Score Nan
I created a Gensim LDA Model as shown in this tutorial: https://www.machinelearningplus.com/nlp/topic-modeling-gensim-python/

```<code>lda_model = gensim.models.LdaMulticore(data_df['bow_corpus'], num_topics=10, id2word=dictionary, random_state=100, chunksize=100, passes=10, per_word_topics=True)
</code>```

And it generates 10 topics with a log_perplexity of:

lda_model.log_perplexity(data_df['bow_corpus']) = -5.325966117835991

But when I run the coherence model on it to calculate coherence score, like so:

```<code>coherence_model_lda = CoherenceModel(model=lda_model, texts=data_df['bow_corpus'].tolist(), dictionary=dictionary, coherence='c_v')
with np.errstate(invalid='ignore'):
    lda_score = coherence_model_lda.get_coherence()
</code>```

My LDA-Score is nan. What am I doing wrong here?

答:
Solved!
Coherence Model requires the original text, instead of the training corpus fed to LDA_Model - so when i ran this:

```<code>coherence_model_lda = CoherenceModel(model=lda_model, texts=data_df['corpus'].tolist(), dictionary=dictionary, coherence='c_v')
with np.errstate(invalid='ignore'):
    lda_score = coherence_model_lda.get_coherence()
</code>```

I got a coherence score of: 0.462

Hope this helps someone else making the same mistake. Thanks!

Title: Gensim LDA Coherence Score Nan

Body:
I created a Gensim LDA Model as shown in this tutorial: https://www.machinelearningplus.com/nlp/topic-modeling-gensim-python/

lda_model = gensim.models.LdaMulticore(data_df['bow_corpus'], num_topics=10, id2word=dictionary, random_state=100, chunksize=100, passes=10, per_word_topics=True)

And it generates 10 topics with a log_perplexity of:

lda_model.log_perplexity(data_df['bow_corpus']) = -5.325966117835991

But when I run the coherence model on it to calculate coherence score, like so:

coherence_model_lda = CoherenceModel(model=lda_model, texts=data_df['bow_corpus'].tolist(), dictionary=dictionary, coherence='c_v')
with np.errstate(invalid='ignore'):
    lda_score = coherence_model_lda.get_coherence()

My LDA-Score is nan. What am I doing wrong here?

Body:
Solved!
Coherence Model requires the original text, instead of the training corpus fed to LDA_Model - so when i ran this:

coherence_model_lda = CoherenceModel(model=lda_model, texts=data_df['corpus'].tolist(), dictionary=dictionary, coherence='c_v')
with np.errstate(invalid='ignore'):
    lda_score = coherence_model_lda.get_coherence()

I got a coherence score of: 0.462

Hope this helps someone else making the same mistake. Thanks!


答:
Use xpath with translate() to ignore the case of the text in the html. You can also use find_elements to avoid the try except:

```<code>elements = browser.find_elements_by_xpath('//a[translate(text(),"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz") = "contact"]')
if elements and elements[0].is_displayed():
    elements[0].click()
</code>```

Title: How to apply multiple conditional statements in selenium webdriver python

Body:
Use xpath with translate() to ignore the case of the text in the html. You can also use find_elements to avoid the try except:

elements = browser.find_elements_by_xpath('//a[translate(text(),"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz") = "contact"]')
if elements and elements[0].is_displayed():
    elements[0].click()


问:
jquery or js select the first class of an element
I have 3 anchors with 3 divs
The anchors are like that:

```<code><a class="home sharedClass">home</a>

<a class="about sharedClass">about</a>

<a class="contact sharedClass">contact</a>
</code>```

When I click one of them I get the contents of the corresponding div which its id is the same as the first class (home, about or contact)

I have a little jQuery code that has to select the right class But the result is an alert telling the name of theClass:

```<code>$('a.sharedClass').click(function(){

    var theClass = $(this).attr('class[0]');

    alert(theClass)

});
</code>```

The problem is that this function returns "undefined". How to fix this?

Thanks.

答:
Get the class attribute first.

```<code>var theClass= $(this).attr('class');
</code>```

You'll have to break (explode/split) it

```<code>var split = theClass.split(' '); // this returns an array
</code>```

Finally you could access the first class

```<code>var firstClass = split[0];
</code>```

Body:
I have 3 anchors with 3 divs
The anchors are like that:

home

about

contact

When I click one of them I get the contents of the corresponding div which its id is the same as the first class (home, about or contact)

I have a little jQuery code that has to select the right class But the result is an alert telling the name of theClass:

$('a.sharedClass').click(function(){

    var theClass = $(this).attr('class[0]');

    alert(theClass)

});

The problem is that this function returns "undefined". How to fix this?

Thanks.

Body:
Get the class attribute first.

var theClass= $(this).attr('class');

You'll have to break (explode/split) it

var split = theClass.split(' '); // this returns an array

Finally you could access the first class

var firstClass = split[0];


问:
Reactjs how to import constant array from another JavaScript file
In my app, I have a huge constant array of string defined in allCurrency.js file as follows. The real array is much longer than the given array. I import it in my App.js file as import currecyData from './allCurrency'. There is no syntax error. I can't access it in App.js. Just a warning  import currecyData from './allCurrency'. How do I access in App.js. I don't want to bring the whole constant array in App.js. It will work, but it will be ugly.

```<code>const currecyData = [
    "AED",
    "ARS",
    "AUD",
    "BGN",
    "BRL",
    "BSD",
    "CAD",
    "CHF",
    "CLP",
    "CNY",
    "COP",
    "CZK",
    "DKK",
    "DOP",
    "EGP",
    "EUR",
    "FJD",
    "GBP"]
</code>```

答:
Either do an

```<code>export const currecyData = [
    "AED",
    "ARS",
    "AUD",
    "BGN",
    "BRL",
    "BSD",
    "CAD",
    "CHF",
    "CLP",
    "CNY",
    "COP",
    "CZK",
    "DKK",
    "DOP",
    "EGP",
    "EUR",
    "FJD",
    "GBP"]
</code>```

And import it as

```<code>import {currecyData} from './allCurrency'
</code>```

or add a default export in your allCurrency.js as obiwankenoobi commented:

```<code>export default currecyData;
</code>```

Body:
In my app, I have a huge constant array of string defined in allCurrency.js file as follows. The real array is much longer than the given array. I import it in my App.js file as import currecyData from './allCurrency'. There is no syntax error. I can't access it in App.js. Just a warning  import currecyData from './allCurrency'. How do I access in App.js. I don't want to bring the whole constant array in App.js. It will work, but it will be ugly.

const currecyData = [
    "AED",
    "ARS",
    "AUD",
    "BGN",
    "BRL",
    "BSD",
    "CAD",
    "CHF",
    "CLP",
    "CNY",
    "COP",
    "CZK",
    "DKK",
    "DOP",
    "EGP",
    "EUR",
    "FJD",
    "GBP"]

Body:
Either do an

export const currecyData = [
    "AED",
    "ARS",
    "AUD",
    "BGN",
    "BRL",
    "BSD",
    "CAD",
    "CHF",
    "CLP",
    "CNY",
    "COP",
    "CZK",
    "DKK",
    "DOP",
    "EGP",
    "EUR",
    "FJD",
    "GBP"]

And import it as

import {currecyData} from './allCurrency'

or add a default export in your allCurrency.js as obiwankenoobi commented:

export default currecyData;


问:
DotNet Core 3.1 - Multiple projects with shared src, obj and bin
I have the following folder structure (following the feature-oriented organization):

```<code>Solution
  bin
  obj
  src
    Module1
      Shared.cs
    Module2
      Shared.cs
    Module3
      Shared.cs
    Server
      Program.cs
      Startup.cs
    Database
      Program.cs
  Solution.sln
  Server.csproj
  Database.csproj
</code>```

For the Server project I am using Microsoft.NET.Sdk and Microsoft.NET.Sdk.Web for the Database.

Here is the actual Server.csproj:

```<code><Project>
    <PropertyGroup>
        <TargetFramework>NetCoreApp3.1</TargetFramework>
        <Configuration Condition=" '$(Configuration)' == '' ">Development</Configuration>
        <EnvironmentName>$(Configuration)</EnvironmentName>
        <BaseOutputPath>bin/$(MSBuildProjectName)</BaseOutputPath>
        <OutputPath>$(BaseOutputPath)/$(Configuration)</OutputPath>
        <BaseIntermediateOutputPath>obj/$(MSBuildProjectName)</BaseIntermediateOutputPath>
        <IntermediateOutputPath>$(BaseIntermediateOutputPath)/$(Configuration)</IntermediateOutputPath>
        <AppendTargetFrameworkToOutputPath>False</AppendTargetFrameworkToOutputPath>
        <AppendRuntimeIdentifierToOutputPath>False</AppendRuntimeIdentifierToOutputPath>
        <EnableDefaultContentItems>False</EnableDefaultContentItems>
        <Nullable>Enable</Nullable>
        <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
        <RootNamespace>OeMis.Server</RootNamespace>
        <StartupObject>OeMis.Server.ServerEntry</StartupObject>
    </PropertyGroup>

    <ItemGroup>
        <Content Include="Configuration.$(Configuration).json" ExcludeFromSingleFile="True" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest"/>
        <PackageReference Include="Dapper" Version="2.0.30"/>
        <PackageReference Include="HotChocolate" Version="11.0.0-preview.95"/>
        <PackageReference Include="HotChocolate.AspNetCore" Version="11.0.0-preview.95"/>
        <PackageReference Include="HotChocolate.AspNetCore.Authorization" Version="11.0.0-preview.95"/>
        <PackageReference Include="HotChocolate.AspNetCore.Playground" Version="11.0.0-preview.95"/>
        <PackageReference Include="Microsoft.Data.SqlClient" Version="2.0.0-preview1.20021.1"/>
    </ItemGroup>

    <Import Sdk="Microsoft.NET.Sdk.Web" Project="Sdk.props"/>
    <Import Sdk="Microsoft.NET.Sdk.Web" Project="Sdk.targets"/>
</Project>
</code>```

And here is the Database.csproj:

```<code><Project>
    <PropertyGroup>
        <TargetFramework>NetCoreApp3.1</TargetFramework>
        <Configuration Condition=" '$(Configuration)' == '' ">Development</Configuration>
        <EnvironmentName>$(Configuration)</EnvironmentName>
        <OutputType>Exe</OutputType>
        <BaseOutputPath>bin/$(MSBuildProjectName)</BaseOutputPath>
        <OutputPath>$(BaseOutputPath)/$(Configuration)</OutputPath>
        <BaseIntermediateOutputPath>obj/$(MSBuildProjectName)</BaseIntermediateOutputPath>
        <IntermediateOutputPath>$(BaseIntermediateOutputPath)/$(Configuration)</IntermediateOutputPath>
        <AppendTargetFrameworkToOutputPath>False</AppendTargetFrameworkToOutputPath>
        <AppendRuntimeIdentifierToOutputPath>False</AppendRuntimeIdentifierToOutputPath>
        <EnableDefaultContentItems>False</EnableDefaultContentItems>
        <Nullable>Enable</Nullable>
        <RootNamespace>OeMis.Database</RootNamespace>
        <StartupObject>OeMis.Database.DatabaseEntry</StartupObject>
    </PropertyGroup>

    <ItemGroup>
        <Content Include="Configuration.$(Configuration).json" ExcludeFromSingleFile="True" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest"/>
        <PackageReference Include="Dapper" Version="2.0.30"/>
        <PackageReference Include="Microsoft.Data.SqlClient" Version="2.0.0-preview1.20021.1"/>
        <PackageReference Include="Bogus" Version="29.0.1"/>
    </ItemGroup>

    <Import Sdk="Microsoft.NET.Sdk" Project="Sdk.props"/>
    <Import Sdk="Microsoft.NET.Sdk" Project="Sdk.targets"/>
</Project>
</code>```

I always get errors in src/Server/Program.cs as if Database.csproj is trying to handle it. The errors have to do with missing references classes in Microsoft.NET.Sdk.Web.

The full project can be found on GitHub

答:
This actually makes sense. You are trying to build the same source files with different dependencies.

My advise is to extract the common/shared items from both and add the to a new project called shared (preferable in .Net standard) and reference the libraries in both your projects.

Creating a class library for .net core guide here

TL;DL;

Create a Solution and Client App.

Create a Class Library Project.

Add Class Library Functionality.

Settings.

Build.

Add Class Library Reference.

Import Namespace.

Call Functions.

Body:
I have the following folder structure (following the feature-oriented organization):

Solution
  bin
  obj
  src
    Module1
      Shared.cs
    Module2
      Shared.cs
    Module3
      Shared.cs
    Server
      Program.cs
      Startup.cs
    Database
      Program.cs
  Solution.sln
  Server.csproj
  Database.csproj

For the Server project I am using Microsoft.NET.Sdk and Microsoft.NET.Sdk.Web for the Database.

Here is the actual Server.csproj:

<Project>
    <PropertyGroup>
        <TargetFramework>NetCoreApp3.1</TargetFramework>
        <Configuration Condition=" '$(Configuration)' == '' ">Development</Configuration>
        <EnvironmentName>$(Configuration)</EnvironmentName>
        <BaseOutputPath>bin/$(MSBuildProjectName)</BaseOutputPath>
        <OutputPath>$(BaseOutputPath)/$(Configuration)</OutputPath>
        <BaseIntermediateOutputPath>obj/$(MSBuildProjectName)</BaseIntermediateOutputPath>
        <IntermediateOutputPath>$(BaseIntermediateOutputPath)/$(Configuration)</IntermediateOutputPath>
        <AppendTargetFrameworkToOutputPath>False</AppendTargetFrameworkToOutputPath>
        <AppendRuntimeIdentifierToOutputPath>False</AppendRuntimeIdentifierToOutputPath>
        <EnableDefaultContentItems>False</EnableDefaultContentItems>
        <Nullable>Enable</Nullable>
        <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
        <RootNamespace>OeMis.Server</RootNamespace>
        <StartupObject>OeMis.Server.ServerEntry</StartupObject>
    </PropertyGroup>

    <ItemGroup>
        <Content Include="Configuration.$(Configuration).json" ExcludeFromSingleFile="True" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest"/>
        <PackageReference Include="Dapper" Version="2.0.30"/>
        <PackageReference Include="HotChocolate" Version="11.0.0-preview.95"/>
        <PackageReference Include="HotChocolate.AspNetCore" Version="11.0.0-preview.95"/>
        <PackageReference Include="HotChocolate.AspNetCore.Authorization" Version="11.0.0-preview.95"/>
        <PackageReference Include="HotChocolate.AspNetCore.Playground" Version="11.0.0-preview.95"/>
        <PackageReference Include="Microsoft.Data.SqlClient" Version="2.0.0-preview1.20021.1"/>
    </ItemGroup>

    <Import Sdk="Microsoft.NET.Sdk.Web" Project="Sdk.props"/>
    <Import Sdk="Microsoft.NET.Sdk.Web" Project="Sdk.targets"/>
</Project>

And here is the Database.csproj:

<Project>
    <PropertyGroup>
        <TargetFramework>NetCoreApp3.1</TargetFramework>
        <Configuration Condition=" '$(Configuration)' == '' ">Development</Configuration>
        <EnvironmentName>$(Configuration)</EnvironmentName>
        <OutputType>Exe</OutputType>
        <BaseOutputPath>bin/$(MSBuildProjectName)</BaseOutputPath>
        <OutputPath>$(BaseOutputPath)/$(Configuration)</OutputPath>
        <BaseIntermediateOutputPath>obj/$(MSBuildProjectName)</BaseIntermediateOutputPath>
        <IntermediateOutputPath>$(BaseIntermediateOutputPath)/$(Configuration)</IntermediateOutputPath>
        <AppendTargetFrameworkToOutputPath>False</AppendTargetFrameworkToOutputPath>
        <AppendRuntimeIdentifierToOutputPath>False</AppendRuntimeIdentifierToOutputPath>
        <EnableDefaultContentItems>False</EnableDefaultContentItems>
        <Nullable>Enable</Nullable>
        <RootNamespace>OeMis.Database</RootNamespace>
        <StartupObject>OeMis.Database.DatabaseEntry</StartupObject>
    </PropertyGroup>

    <ItemGroup>
        <Content Include="Configuration.$(Configuration).json" ExcludeFromSingleFile="True" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest"/>
        <PackageReference Include="Dapper" Version="2.0.30"/>
        <PackageReference Include="Microsoft.Data.SqlClient" Version="2.0.0-preview1.20021.1"/>
        <PackageReference Include="Bogus" Version="29.0.1"/>
    </ItemGroup>

    <Import Sdk="Microsoft.NET.Sdk" Project="Sdk.props"/>
    <Import Sdk="Microsoft.NET.Sdk" Project="Sdk.targets"/>
</Project>

I always get errors in src/Server/Program.cs as if Database.csproj is trying to handle it. The errors have to do with missing references classes in Microsoft.NET.Sdk.Web.

The full project can be found on GitHub


问:
Why Ionic 5 content padding is not working?
When upgraded to Ionic 5, the padding attribute is not working anymore as in Ionic 4:

```<code><ion-content color="primary" padding></ion-content>
</code>```

Any fixes?

答:
Story in Ionic v4:

Use of attributes got deprecated in Ionic v4 and if you would have noticed in developers console, Ionic 4 was throwing warnings of using these attributes to style.

Story in Ionic v5:

In Ionic v5, these attributes got removed permanently and got replaced with CSS classes. So even if those attributes there in your code, no effect will be there.

As per the Breaking Changes https://github.com/ionic-team/ionic/blob/v5.0.0/BREAKING.md#css:

We originally added CSS utility attributes for styling components because it was a quick and easy way to wrap text or add padding to an element. Once we added support for multiple frameworks as part of our "Ionic for everyone" approach, we quickly determined there were problems with using CSS attributes with frameworks that use JSX and Typescript. In order to solve this we added CSS classes. Rather than support CSS attributes in certain frameworks and classes in others, we decided to remove the CSS attributes and support what works in all of them, classes, for consistency. In addition to this, changing to classes prefixed with ion avoids conflict with native attributes and user's CSS. In the latest version of Ionic 4, there are deprecation warnings printed in the console to show what the new classes are, and the documentation has been updated since support for classes was added to remove all references to attributes

Solution:

You need to replace all your attributes to CSS classes. For example:

Before

<ion-header text-center></ion-header>
<ion-content padding></ion-content>
```

<p><strong>After</strong></p>

<pre class="lang-html prettyprint-override"><code><ion-header class="ion-text-center"></ion-header>
<ion-content class="ion-padding"></ion-content>
</code>```

For your case, replace

<ion-content color="primary" padding></ion-content>
```

<p>to </p>

<pre class="lang-html prettyprint-override"><code><ion-content color="primary" class="ion-padding"></ion-content>
</code>```

Body:
When upgraded to Ionic 5, the padding attribute is not working anymore as in Ionic 4:

<ion-content color="primary" padding></ion-content>

Any fixes?

Body:
Story in Ionic v4:

Use of attributes got deprecated in Ionic v4 and if you would have noticed in developers console, Ionic 4 was throwing warnings of using these attributes to style.

Story in Ionic v5:

In Ionic v5, these attributes got removed permanently and got replaced with CSS classes. So even if those attributes there in your code, no effect will be there.

As per the Breaking Changes https://github.com/ionic-team/ionic/blob/v5.0.0/BREAKING.md#css:

We originally added CSS utility attributes for styling components because it was a quick and easy way to wrap text or add padding to an element. Once we added support for multiple frameworks as part of our "Ionic for everyone" approach, we quickly determined there were problems with using CSS attributes with frameworks that use JSX and Typescript. In order to solve this we added CSS classes. Rather than support CSS attributes in certain frameworks and classes in others, we decided to remove the CSS attributes and support what works in all of them, classes, for consistency. In addition to this, changing to classes prefixed with ion avoids conflict with native attributes and user's CSS. In the latest version of Ionic 4, there are deprecation warnings printed in the console to show what the new classes are, and the documentation has been updated since support for classes was added to remove all references to attributes

Solution:

You need to replace all your attributes to CSS classes. For example:

Before

<ion-header text-center></ion-header>
<ion-content padding></ion-content>

After

<ion-header class="ion-text-center"></ion-header>
<ion-content class="ion-padding"></ion-content>

For your case, replace

<ion-content color="primary" padding></ion-content>

to

<ion-content color="primary" class="ion-padding"></ion-content>


问:
React Native App Atom IDE error not allowing to create config folder
I keep getting this error message when I try to create a "config" folder for my Firebase API code inside Atom and even in Visual Studio Code.

Error: EACCES: permission denied, mkdir '/Users//Documents/ReactNativeProjects/react-firebase-app/config'

I've been trying to fix this error the entire day and I'm struggling to find a solution.

someone, please help me.

I'm on MacOs: 10.15.3

答:
I found the answer hours later, had to reset permissions inside the app folder.

https://support.apple.com/en-us/HT203538


问:
How to sort a python list of lists by both the values of a nested list and with a condition of reverse=True for only first value of the nested list?
I am trying to sort this list by both the values of the nested list, but I want only alphabets positions in reverse order and the numbers in ascending order.

```<code>sample_list = [
  ['y', 4],
  ['x', 2],
  ['y', 1],
  ['z', 2],
  ['x', 5],
  ['y', 2]]

sorted_list = sorted(sample_list, key=lambda nested: (nested[0], nested[1]), reverse=True)
</code>```

Output:

```<code>[['z', 2],
 ['y', 4],
 ['y', 2],
 ['y', 1],
 ['x', 5],
 ['x', 2]]
</code>```

Expected Output:

```<code>[['z', 2],
 ['y', 1],
 ['y', 2],
 ['y', 4],
 ['x', 2],
 ['x', 5]]
</code>```

答:
The answer from "abc" is a good one for your example data, but in general if you want to sort by multiple keys in different orders, you may not be able to negate some of them (e.g. if the values are all strings rather than numbers).  In such a case you can sort multiple times to control the order of each sort key:

```<code>sorted_1 = sorted(sample_list, key=lambda nested: nested[1])
sorted_0_1 = sorted(sorted_1, key=lambda nested: nested[0], reverse=True)
</code>```

This sort of thing is explained in the official documentation: https://docs.python.org/3/howto/sorting.html

This might take more time than a single sorted() invocation, but it will work on any sortable data, not only that which can be negated.

Body:
I am trying to sort this list by both the values of the nested list, but I want only alphabets positions in reverse order and the numbers in ascending order.

sample_list = [
  ['y', 4],
  ['x', 2],
  ['y', 1],
  ['z', 2],
  ['x', 5],
  ['y', 2]]

sorted_list = sorted(sample_list, key=lambda nested: (nested[0], nested[1]), reverse=True)

Output:

[['z', 2],
 ['y', 4],
 ['y', 2],
 ['y', 1],
 ['x', 5],
 ['x', 2]]

Expected Output:

[['z', 2],
 ['y', 1],
 ['y', 2],
 ['y', 4],
 ['x', 2],
 ['x', 5]]

Body:
The answer from "abc" is a good one for your example data, but in general if you want to sort by multiple keys in different orders, you may not be able to negate some of them (e.g. if the values are all strings rather than numbers).  In such a case you can sort multiple times to control the order of each sort key:

sorted_1 = sorted(sample_list, key=lambda nested: nested[1])
sorted_0_1 = sorted(sorted_1, key=lambda nested: nested[0], reverse=True)

This sort of thing is explained in the official documentation: https://docs.python.org/3/howto/sorting.html

This might take more time than a single sorted() invocation, but it will work on any sortable data, not only that which can be negated.


答:
```<code>    const currecyData = [
"AED",
"ARS",
"AUD",
"BGN",
"BRL",
"BSD",
"CAD",
"CHF",
"CLP",
"CNY",
"COP",
"CZK",
"DKK",
"DOP",
"EGP",
"EUR",
"FJD",
"GBP"];export default currecyData;
</code>```

You have to export the entity to import it.

Title: Reactjs how to import constant array from another JavaScript file

Body:
    const currecyData = [
"AED",
"ARS",
"AUD",
"BGN",
"BRL",
"BSD",
"CAD",
"CHF",
"CLP",
"CNY",
"COP",
"CZK",
"DKK",
"DOP",
"EGP",
"EUR",
"FJD",
"GBP"];export default currecyData;

You have to export the entity to import it.


问:
Using functions from global namespace in a namespace
I am using a library that is under a namespace, let's call it Hello.

namespace Hello {

template<class T>
void World(std::ostream& os, const T& t) {
    os << t;
}

}
```

<p>The <code>class T</code> is something like <code>std::array<int,10></code> and I also write an ostream overload function for it. However, calling <code>Hello::World(arr)</code> leads to compile errors that say the compiler cannot find the overload for <code>operator<<()</code>.</p>

<p>After some search, I come up with a solution that explains this situation.
How does the operator overload resolution work within namespaces? and Name resolution of functions inside templates instantiated with qualified types.</p>

<p>So we can simplify the situation like this.</p>

```void f(int) {}
void f(int,int) {}

namespace Hello {
    using ::f;
    void f(int,int,int) {}
    void World()
    {
        f(100);
        f(100, 200);
        f(100, 200, 300);
    }
};

int main()
{
    Hello::World();
    return 0;
}
```

Without the using ::f; line, this code fails to be compiled since the name f can hide ALL of the functions with the same name in the global namespace.

Now that this is my problems:

Since namespace Hello { .... } is in the library, I shall not modify it. That is, I cannot modify the implementation inside World(). The only solution is to put a line namespace Hello { using ::f; } somewhere in my code. Is it a good practice, or there is a more elegant solution?

In this example, can I only import f(int) and not f(int,int)?

答:
Is it a good practice, or there is a more elegant solution?

IMHO, you can use it with third party library. It is clear and expressive enough. It would be better if you could write:

void World() {
    ::f(100);           // f from global namespace
    ::f(100, 200);      // f from global namespace
    f(100, 200, 300);   // f NOT from global namespace
}
```

<p>because then it is clearly visible which function <strong>is</strong> and which <strong>is not</strong> from the global namespace but this solution does not work for you since you cannot modify implementation of <code>World</code> function.</p>

<blockquote>
  <p>Can I only import <code>f(int)</code> and not <code>f(int, int)</code>?</p>
</blockquote>

<p>Yes. You can do the following in order to import only <code>f(int)</code> function:</p>

<pre class="lang-cpp prettyprint-override"><code>void f(int) {}

namespace Hello {
    using ::f;    // only void f(int) is defined before this line
                  // therefore, it is the only overload being imported to the Hello namespace
}

void f(int,int) {}
</code>```

Demo

UPDATE

If you want to import only one overload of an operator<<, not an ordinary function, then you could wrap each overload in a separate namespace like this:

namespace XX {

struct X {
    int x;
};

std::ostream& operator<<(std::ostream& os, X const& x) {
    return os;
}

}

namespace YY {

std::ostream& operator<<(std::ostream& os, Y const& y) {
    return os;
}

struct Y {
    double y;
};

}

namespace Hello {
    using ::XX::X;
    using ::XX::operator<<;
    using ::YY::Y;
}
```

Check it out live.

Body:
I am using a library that is under a namespace, let's call it Hello.

namespace Hello {

template<class T>
void World(std::ostream& os, const T& t) {
    os << t;
}

}

The class T is something like std::array<int,10> and I also write an ostream overload function for it. However, calling Hello::World(arr) leads to compile errors that say the compiler cannot find the overload for operator<<().

After some search, I come up with a solution that explains this situation.
How does the operator overload resolution work within namespaces? and Name resolution of functions inside templates instantiated with qualified types.

So we can simplify the situation like this.

void f(int) {}
void f(int,int) {}

namespace Hello {
    using ::f;
    void f(int,int,int) {}
    void World()
    {
        f(100);
        f(100, 200);
        f(100, 200, 300);
    }
};

int main()
{
    Hello::World();
    return 0;
}

Without the using ::f; line, this code fails to be compiled since the name f can hide ALL of the functions with the same name in the global namespace.

Now that this is my problems:

Since namespace Hello { .... } is in the library, I shall not modify it. That is, I cannot modify the implementation inside World(). The only solution is to put a line namespace Hello { using ::f; } somewhere in my code. Is it a good practice, or there is a more elegant solution?

In this example, can I only import f(int) and not f(int,int)?

Body:
Is it a good practice, or there is a more elegant solution?

IMHO, you can use it with third party library. It is clear and expressive enough. It would be better if you could write:

void World() {
    ::f(100);           // f from global namespace
    ::f(100, 200);      // f from global namespace
    f(100, 200, 300);   // f NOT from global namespace
}

because then it is clearly visible which function is and which is not from the global namespace but this solution does not work for you since you cannot modify implementation of World function.

Can I only import f(int) and not f(int, int)?

Yes. You can do the following in order to import only f(int) function:

void f(int) {}

namespace Hello {
    using ::f;    // only void f(int) is defined before this line
                  // therefore, it is the only overload being imported to the Hello namespace
}

void f(int,int) {}

<a href="https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:3,endLineNumber:20,positionColumn:3,positionLineNumber:20,selectionStartColumn:3,selectionStartLineNumber:20,startColumn:3,startLineNumber:20),source:'%23include+%3Ciostream%3E%0A%23include+%3Cstring%3E%0A%0Avoid+f(int)+%7B%7D%0A%0Anamespace+Hello+%7B%0A++++using+::f%3B%0A%7D%0A%0Avoid+f(int,int)+%7B%7D%0A%0Anamespace+Hello+%7B%0A++++void+f(int,int,int)+%7B%7D%0A++++void+World()%0A++++%7B%0A++++++++f(100)%3B%0A++++++++f(100,+200)%3B%0A++++++++f(100,+200,+300)%3B%0A++++%7D%0A%7D%3B%0A%0Aint+main()+%7B%0A++++Hello::World()%3B%0A++++return+0%3B%0A%7D'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:49.85494633014216,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((g:!((h:compiler,i:(compiler:gsnapshot,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'0',intel:'0',libraryCode:'1',trim:'1'),fontScale:14,j:2,lang:c%2B%2B,libs:!(),options:'-std%3Dc%2B%2B11',selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'x86-64+gcc+(trunk)+(Editor+%231,+Compiler+%232)+C%2B%2B',t:'0')),k:50.145053669857845,l:'4',m:50,n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compiler:2,editor:1,fontScale:14,wrap:'1'),l:'5',n:'0',o:'%232+with+x86-64+gcc+(trunk)',t:'0')),header:(),l:'4',m:50,n:'0',o:'',s:0,t:'0')),k:50.145053669857845,l:'3',n:'0',o:'',t:'0')),l:'2',n:'0',o:'',t:'0')),version:4" rel="nofollow noreferrer">Demo

UPDATE

If you want to import only one overload of an operator<<, not an ordinary function, then you could wrap each overload in a separate namespace like this:

namespace XX {

struct X {
    int x;
};

std::ostream& operator<<(std::ostream& os, X const& x) {
    return os;
}

}

namespace YY {

std::ostream& operator<<(std::ostream& os, Y const& y) {
    return os;
}

struct Y {
    double y;
};

}

namespace Hello {
    using ::XX::X;
    using ::XX::operator<<;
    using ::YY::Y;
}

Check it out <a href="https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qhkAUgBMAISnTSAZ0ztkBPHUqZa6AMKpWAVwC2tEJNJb0AGTy1MAOWMAjTMRABmcwAdUCwuto9QxMzUh8/NTobO0cjFzdPRWVMVQCGAmZiAiDjU04klUjadMyCaIdnVxBeBQysnJD82tLy2PjqgEpFVANiZA4Acil3W2RDLABqcXcddVriTGYjaexxAAYAQWHR8cwpmYV5xeX3Vc31jdolzAUvZn6JgA1HqYB2WXPN%2BYNVJ7ePjYTIETWwECYAD2mAPErwAIlCLhdaugQCBfAQFkspAA2CaoLyuZhEYjTHSkiDI1HozHLSS43ykP5oWi1HEQjr/C7AiYLAi9Wh4hQI85wxEi%2BGfS7XW73PYATTlnMllLRRyxdLxBOIRJIpPJKupxzZDImiuZrI1AE8OTCAdzefzBcKtqLlRifmDFbaucD0D0nOwJpbnTD4e5oeKxVKjDc7g8ABLKVioJWA4EGPyiCao54553cjO2YDZkC5tFanUkmZ68M%2BoGFrOohVNkOurabK4xmUJpMp72bbnfX4ALVT3O5VGTRImAC988DQyGB8CDWrafSK8SazoKQQUaqMUaNSbR%2BaCGzrWPx0CHcQBb550DF5LuQA3VB4dATADqJFY6AgG13jrccXkhWtl2vRVgwgtNr1HOdYJAwc91RNADDBbcIUfccVXQzDqxmIMcJQ/d8P2MkiMQu0FzbRckM2UEJiMZhbEAq8gUTVhk1RX9iH/QCcNvAU1lbWEBi6VgQAGABWAZSFMAY1nk1BpLJGQ5AmBQej6PZhk4eSCGk5SOi6ABraoAE4ADoAA4ZO4SzuGxdx3DWHhJE4bEhGk7h5MU5TSFUgZ5IUEA1lIIylIk0g4FgGBEBQVAjC8PB2DICgIDQFK0qqYAFCuLwFAQVACFIKg0oIVwwogJxjPkpxbEyS1pIM0hspjegAHlaFYFrotILAWNEdh6sGvAFlSV8bjGzBwRSDDBkC0FlDG1g8CcbViEtPQsFawziDwIx9q6Gh6CYNgOB4fhQmEUQUDkOQhA2sLIC6fEijCgYAFpkWmWEJA0mRODapRCgCTRtAaPILG0VpKjcfJwn8OhocEZGinhuIqiaZJUjoEp6n0XJBDBlIikJspbAqbHEcUOpsmJxp6Zaam2hxrptN6fouEk6S5IUsbgvBWzsW%2B7FuAmYBkGQCYIHdWgzI5CBcEIEgpkkdx8gmPQcvSjXPA5dTZBkQz6tM0gLJktZrJ4a2ZPcbFsUs%2BzXls7gZJ8gY/NIY7rcFgbgtC8LIvN2KEogJAegILwMPIShstS9LQkwfBiUEM7GBYUbroAd21LwTq9gWApU6ThkkCZc8IBAIVF8XJel2X5eIAxFY6M3oothBFiwNxAK9n2/Yi0uguk4OIqikzzJAa3bY9tYHadl2ZLdj2vfcfyhfH0Ou75gZJC3wOd6niSumm4g/A0bggA%3D%3D%3D" rel="nofollow noreferrer">live.


问:
If two values have different data types, Java will automatically promote one of the values to the larger of the two data types?
The rule says that if two values have different data types, Java will automatically promote one of the values to the larger of the two data types?

In the code below, the value assigned to y is larger than the value of x. Therefore, taking the rule into consideration, the printed value should be "Float" but instead it printed "Double. Can you please why it prints Double instead of Float?

```<code>    Double x = 3.21;

    Float y = 4.1f;

    Object o  = (x*y);

    System.out.println( o.getClass().getSimpleName() ); // prints out Double
</code>```

答:
The values of the variables don't matter. Their types matter. double is an 8 bytes types and float is a 4 bytes type. Hence, to multiply a double and a float, you promote the variable of the smaller type (float) to the larger type (double).

If you are multiplying a Double with a Float, they will be unboxed to double and float. In order to multiply a double with a float, the float would be promoted to double, and double multiplication would take place.

Since the result is stored in an Object, the double result will be boxed to a Double.

Body:
The rule says that if two values have different data types, Java will automatically promote one of the values to the larger of the two data types?

In the code below, the value assigned to y is larger than the value of x. Therefore, taking the rule into consideration, the printed value should be "Float" but instead it printed "Double. Can you please why it prints Double instead of Float?

    Double x = 3.21;

    Float y = 4.1f;

    Object o  = (x*y);

    System.out.println( o.getClass().getSimpleName() ); // prints out Double


问:
Is Deque supported in GWT?
```<code>...
private Deque<PagePresenter> pageHistory = new ArrayDeque<PagePresenter>();
...

[ERROR] [test_app] - Line 8: No source code is available for type java.util.Deque<E>; did you forget to inherit a required module?
</code>```

do I need to implement it myself?

Thanks,
/S

答:
GWT includes a LinkedList implementation that implements part of the Dequeue interface (addFirst(), getFirst(), removeFirst(), addLast(), getLast(), removeLast()).

If you need a full Dequeue implementation you need to implement it (or at least the missing methods on LinkedList) yourself.

Title: Is Deque supported in GWT?

Body:
...
private Deque<PagePresenter> pageHistory = new ArrayDeque<PagePresenter>();
...

[ERROR] [test_app] - Line 8: No source code is available for type java.util.Deque<E>; did you forget to inherit a required module?

do I need to implement it myself?

Thanks,
/S


答:
"Larger" does not refer to the ">" value, but (in a nutshell) to the data type that can hold more information, e.g. Double is preferred over Float and Long is preferred over Int.

This is documented here: https://docs.oracle.com/javase/specs/jls/se13/html/jls-5.html#jls-5.6.2

Title: If two values have different data types, Java will automatically promote one of the values to the larger of the two data types?


问:
How to remove span tag which has no attribute in a HTML block using Javascript or ExtJs
using Javascript, I am trying to remove span tags within HTML content which has no attribute, but have not found a solution yet.

for example, if a html content is

```<code><p>
<span>
<span class="asset"> </span>
<iframe title="title" id="dynamicid" src="https://example.com/asset/externalasset.html" style="width: 100px; height: 30px;"> </iframe>
</span>
</p>
</code>```

expected result is,

```<code><p>
<span class="asset"> </span>
<iframe title="title" id="dynamicid" src="https://example.com/asset/externalasset.html" style="width: 100px; height: 30px;"> </iframe>
</p>
</code>```

答:
Try this:

This has only one problem: The span must be the last child of its parent, but for your example it might work:

The changes cannot be seen without displaying the innerHTML of the p (as I've done below on the 2nd snippet) or inspecting the result.

let spans = document.querySelectorAll("span");
for (let i = 0; i < spans.length; i++) {
  let span = spans[i], ih, p;
  if (span.hasAttributes() === false) {
    ih = span.innerHTML;
    p = span.parentNode;
    p.removeChild(span)
    p.innerHTML += ih;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
<span>
<span class="asset"> </span>
<iframe title="title" id="dynamicid" src="https://example.com/asset/externalasset.html" style="width: 100px; height: 30px;"> </iframe>
</span>
</p></code>```

Here is an example of console.loging it:

let spans = document.querySelectorAll("span"), arr = [];
for (let i = 0; i < spans.length; i++) {
  let span = spans[i], ih, p;
  if (span.hasAttributes() === false) {
    ih = span.innerHTML;
    p = span.parentNode;
    p.removeChild(span)
    p.innerHTML += ih;
    arr.push(p); //added to console.log the innerHTML of the parent
  }
}

//console.log the parents' innerHTML
for (let j = 0; j < arr.length; j++) {
  ih = arr[j].innerHTML;
  console.log(ih);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
<span>
<span class="asset"> </span>
<iframe title="title" id="dynamicid" src="https://example.com/asset/externalasset.html" style="width: 100px; height: 30px;"> </iframe>
</span>
</p></code>```

Body:
using Javascript, I am trying to remove span tags within HTML content which has no attribute, but have not found a solution yet.

for example, if a html content is

expected result is,

Body:
Try this:

This has only one problem: The span must be the last child of its parent, but for your example it might work:

The changes cannot be seen without displaying the innerHTML of the p (as I've done below on the 2nd snippet) or inspecting the result.

let spans = document.querySelectorAll("span");
for (let i = 0; i < spans.length; i++) {
  let span = spans[i], ih, p;
  if (span.hasAttributes() === false) {
    ih = span.innerHTML;
    p = span.parentNode;
    p.removeChild(span)
    p.innerHTML += ih;
  }
}

<p>
<span>
<span class="asset">&nbsp;</span>
<iframe title="title" id="dynamicid" src="https://example.com/asset/externalasset.html" style="width: 100px; height: 30px;">&nbsp;</iframe>
</span>
</p>

Here is an example of console.loging it:

let spans = document.querySelectorAll("span"), arr = [];
for (let i = 0; i < spans.length; i++) {
  let span = spans[i], ih, p;
  if (span.hasAttributes() === false) {
    ih = span.innerHTML;
    p = span.parentNode;
    p.removeChild(span)
    p.innerHTML += ih;
    arr.push(p); //added to console.log the innerHTML of the parent
  }
}

//console.log the parents' innerHTML
for (let j = 0; j < arr.length; j++) {
  ih = arr[j].innerHTML;
  console.log(ih);
}

<p>
<span>
<span class="asset">&nbsp;</span>
<iframe title="title" id="dynamicid" src="https://example.com/asset/externalasset.html" style="width: 100px; height: 30px;">&nbsp;</iframe>
</span>
</p>


问:
newtype-like operational semantics for a GADT where the type fully determines the constructor
Suppose I have a GADT like the following:

```<code>data Tag = A | B | C

data Payload (tag :: Tag) where
  PA :: Int -> Payload A
  PB :: Double -> Payload B
  PC :: Bool -> Payload C
</code>```

I want Payload to have no runtime representation on its own -- i.e. I want to have Coercible Int (Payload A), I want zero-cost pattern matching, and in general I want it to behave as if I had the following three newtype definitions instead:

```<code>newtype PayloadA = PA Int
newtype PayloadB = PB Double
newtype PayloadC = PC Bool
</code>```

Is there a way to convince GHC to give me that?

答:
This looks impossible to achieve, at least with current GHC. Assume your Payload A had the same representation of Int, and so on.

```<code>data Tag = A | B | C

data Payload (tag :: Tag) where
  PA :: Int -> Payload A
  PB :: Double -> Payload B
  PC :: Bool -> Payload C
</code>```

Then, how should we implement this?

```<code>foo :: Payload tag -> Int
foo (PA i) = i
foo (PB _) = 1
foo (PC _) = 2
</code>```

To implement foo, we somehow need to extract the tag from the Payload tag, but that is impossible if Payload tag does not store the tag in its representation.

What we could do, instead, is to separate the runtime tag representation from its payload data.

```<code>type family Payload (tag :: Tag) where
   Payload 'A = Int
   Payload 'B = Double
   Payload 'C = Bool
</code>```

Now, Payload 'A is exactly an Int. We however lose the ability to write foo, since the tag is no longer stored at runtime along the payload. We can instead write this:

```<code>-- singleton, could be auto-generated using the singletons library
data STag (tag :: Tag) where
    SA :: STag 'A
    SB :: STag 'B
    SC :: STag 'C

bar :: STag tag -> Payload tag -> Int
bar PA i = i
bar PB _ = 1
bar PC _ = 2
</code>```

Note how we essentially add the tag as an argument, since we do need it to be represented at runtime.

Body:
Suppose I have a GADT like the following:

data Tag = A | B | C

data Payload (tag :: Tag) where
  PA :: Int -> Payload A
  PB :: Double -> Payload B
  PC :: Bool -> Payload C

I want Payload to have no runtime representation on its own -- i.e. I want to have Coercible Int (Payload A), I want zero-cost pattern matching, and in general I want it to behave as if I had the following three newtype definitions instead:

newtype PayloadA = PA Int
newtype PayloadB = PB Double
newtype PayloadC = PC Bool

Is there a way to convince GHC to give me that?

Body:
This looks impossible to achieve, at least with current GHC. Assume your Payload A had the same representation of Int, and so on.

data Tag = A | B | C

data Payload (tag :: Tag) where
  PA :: Int -> Payload A
  PB :: Double -> Payload B
  PC :: Bool -> Payload C

Then, how should we implement this?

foo :: Payload tag -> Int
foo (PA i) = i
foo (PB _) = 1
foo (PC _) = 2

To implement foo, we somehow need to extract the tag from the Payload tag, but that is impossible if Payload tag does not store the tag in its representation.

What we could do, instead, is to separate the runtime tag representation from its payload data.

type family Payload (tag :: Tag) where
   Payload 'A = Int
   Payload 'B = Double
   Payload 'C = Bool

Now, Payload 'A is exactly an Int. We however lose the ability to write foo, since the tag is no longer stored at runtime along the payload. We can instead write this:

-- singleton, could be auto-generated using the singletons library
data STag (tag :: Tag) where
    SA :: STag 'A
    SB :: STag 'B
    SC :: STag 'C

bar :: STag tag -> Payload tag -> Int
bar PA i = i
bar PB _ = 1
bar PC _ = 2

Note how we essentially add the tag as an argument, since we do need it to be represented at runtime.


问:
Read a html file and display it in tkinter window
I am new on Python and I'm working on a project. When I work on GUI, I meet some difficulties.

I need to read a html file and put it on tkinter window. I have been looking for some solutions and someone recommanded tkinterhtml. I copied his example code, but something was wrong with the result. I do not know how to solve the problem. I would appreciate it if someone can help me.

```<code>from urllib.request import urlopen
from tkinter import *
import tkinterhtml as th

a = urlopen("https://www.baidu.com/?tn=78040160_14_pg&ch=8")
r = a.read()
d = r.decode()

root = Tk()
html = th.HtmlFrame(root)
html.pack()
html.set_content(d)
mainloop()
</code>```

And the result is:

```<code>Process finished with exit code -1073741819 (0xC0000005)
</code>```

答:
This seems to be a problem with your python installation. Try reinstalling python, as it works fine for me:

Also, assuming you want to render HTML, which hasn't worked in the screenshot, I don't reccomend tkinterhtml - it doesn't work very well. PyQt will work a lot better for what you want if you don't mind using it. Install PyQt5 and PyQtWebEngine with pip:

```<code>pip install PyQt5
pip install PyQtWebEngine
</code>```

and then try this example code for what you want:

```<code>import sys
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtWidgets import QApplication

app = QApplication(sys.argv)

web = QWebEngineView()
web.load(QUrl("https://www.baidu.com/?tn=78040160_14_pg&ch=8"))
web.show()

sys.exit(app.exec_())
</code>```

Which gives you this:

Body:
I am new on Python and I'm working on a project. When I work on GUI, I meet some difficulties.

I need to read a html file and put it on tkinter window. I have been looking for some solutions and someone recommanded tkinterhtml. I copied his example code, but something was wrong with the result. I do not know how to solve the problem. I would appreciate it if someone can help me.

from urllib.request import urlopen
from tkinter import *
import tkinterhtml as th

a = urlopen("https://www.baidu.com/?tn=78040160_14_pg&ch=8")
r = a.read()
d = r.decode()

root = Tk()
html = th.HtmlFrame(root)
html.pack()
html.set_content(d)
mainloop()

And the result is:

Process finished with exit code -1073741819 (0xC0000005)

Body:
This seems to be a problem with your python installation. Try reinstalling python, as it works fine for me:

Also, assuming you want to render HTML, which hasn't worked in the screenshot, I don't reccomend tkinterhtml - it doesn't work very well. PyQt will work a lot better for what you want if you don't mind using it. Install PyQt5 and PyQtWebEngine with pip:

pip install PyQt5
pip install PyQtWebEngine

and then try this example code for what you want:

import sys
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtWidgets import QApplication

app = QApplication(sys.argv)

web = QWebEngineView()
web.load(QUrl("https://www.baidu.com/?tn=78040160_14_pg&ch=8"))
web.show()

sys.exit(app.exec_())

Which gives you this:


问:
How to display error message if member doesn't have permissions? Discord.py
I'm trying to make a simple clear command & have it return an error message if the member does not have the manage messages permission. </p>

```<code>@bot.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx, amount=10):
    await ctx.channel.purge(limit=amount)
</code>```

答:
This will do the trick.

```<code>@bot.command()
async def clear(ctx, amount = 10):
    authorperms = ctx.author.permissions_in(ctx.channel)
    if authorperms.manage_messages:
        await ctx.channel.purge(limit=amount)
    else:
        await ctx.send("You don't have the permissions to do that!")
</code>```

There is probably a better way of doing this by using the Exception raised when someone without the right permissions tries to use the command, or by overwriting the on_error method but I don't know how. This should fix the problem for you until you can find a better solution.

Body:
I'm trying to make a simple clear command & have it return an error message if the member does not have the manage messages permission.

@bot.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx, amount=10):
    await ctx.channel.purge(limit=amount)

Body:
This will do the trick.

@bot.command()
async def clear(ctx, amount = 10):
    authorperms = ctx.author.permissions_in(ctx.channel)
    if authorperms.manage_messages:
        await ctx.channel.purge(limit=amount)
    else:
        await ctx.send("You don't have the permissions to do that!")

There is probably a better way of doing this by using the Exception raised when someone without the right permissions tries to use the command, or by overwriting the on_error method but I don't know how. This should fix the problem for you until you can find a better solution.