问:
The relationship could not be changed because one or more of the foreign-key properties is non-nullable?
According to the accepted answer here: The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I've already deleted all child items before updating the entity using entity.Children.Clear():

```<code>public static JsonViewData AddOrUpdate(ModelDBContext context, GENCompanyViewModel companyModel, string userName, string userId)
        {
            try
            {
                var company = new GENCompany();

                if (companyModel.Id > 0) //Update
                {
                    company = context.Companies.Find(companyModel.Id);
                    context.Entry(company).State = EntityState.Modified;

                    company.Vehicles.Clear();
                    company.Phones.Clear();
                    company.Emails.Clear();

                    company.InjectFrom(companyModel);
                    company.DateUpdated = DateTime.Now;
                }
                else //Add
                {
                    company.InjectFrom(companyModel);
                    company.CreatedById = new Guid(userId);
                    context.Companies.Add(company);

                    context.SaveChanges(userName);

                }

                if (companyModel.Vehicles.Any())
                {
                    foreach (var vehicleModel in companyModel.Vehicles)
                    {
                        var vehicle = context.Vehicles.Find(vehicleModel.Id);
                        context.Entry(vehicle).State = EntityState.Unchanged;
                        company.Vehicles.Add(vehicle);
                    }
                }

                if (companyModel.Phones.Any())
                {
                    foreach (var phoneModel in companyModel.Phones)
                    {
                        var phone = new GENCompanyPhone();
                        phone.InjectFrom(phoneModel);
                        company.Phones.Add(phone);
                    }
                }

                if (companyModel.Emails.Any())
                {
                    foreach (var emailModel in companyModel.Emails)
                    {
                        var email = new GENCompanyEmail();
                        email.InjectFrom(emailModel);
                        company.Emails.Add(email);
                    }
                }

                context.SaveChanges(userName);
                return new JsonViewData { IsSuccess = true, Message = "Added Successfully" };
            }
            catch (Exception ex)
            {
                return new JsonViewData { IsSuccess = false, Message = ex.InnerException?.InnerException?.Message ?? ex.InnerException?.Message ?? ex.Message };
            }
        }
</code>```

and I get this error:

The operation failed: The relationship could not be changed because
  one or more of the foreign-key properties is non-nullable. When a
  change is made to a relationship, the related foreign-key property is
  set to a null value. If the foreign-key does not support null values,
  a new relationship must be defined, the foreign-key property must be
  assigned another non-null value, or the unrelated object must be
  deleted.

答:
The problem occurs because you are trying to remove something from one end of a relationship but not the other and the thing on the other end is non nullable.

The easiest solution to this is to enable cascade deletes, then let EF worry about the details but if you have to handle this then what you need to do is remove all the items using as you are but also on each item set the related item to null and if this cannot be null you'll have to remove the related item too.

Body:
According to the accepted answer here: The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I've already deleted all child items before updating the entity using entity.Children.Clear():

public static JsonViewData AddOrUpdate(ModelDBContext context, GENCompanyViewModel companyModel, string userName, string userId)
        {
            try
            {
                var company = new GENCompany();

                if (companyModel.Id > 0) //Update
                {
                    company = context.Companies.Find(companyModel.Id);
                    context.Entry(company).State = EntityState.Modified;

                    company.Vehicles.Clear();
                    company.Phones.Clear();
                    company.Emails.Clear();

                    company.InjectFrom(companyModel);
                    company.DateUpdated = DateTime.Now;
                }
                else //Add
                {
                    company.InjectFrom(companyModel);
                    company.CreatedById = new Guid(userId);
                    context.Companies.Add(company);

                    context.SaveChanges(userName);

                }

                if (companyModel.Vehicles.Any())
                {
                    foreach (var vehicleModel in companyModel.Vehicles)
                    {
                        var vehicle = context.Vehicles.Find(vehicleModel.Id);
                        context.Entry(vehicle).State = EntityState.Unchanged;
                        company.Vehicles.Add(vehicle);
                    }
                }

                if (companyModel.Phones.Any())
                {
                    foreach (var phoneModel in companyModel.Phones)
                    {
                        var phone = new GENCompanyPhone();
                        phone.InjectFrom(phoneModel);
                        company.Phones.Add(phone);
                    }
                }

                if (companyModel.Emails.Any())
                {
                    foreach (var emailModel in companyModel.Emails)
                    {
                        var email = new GENCompanyEmail();
                        email.InjectFrom(emailModel);
                        company.Emails.Add(email);
                    }
                }

                context.SaveChanges(userName);
                return new JsonViewData { IsSuccess = true, Message = "Added Successfully" };
            }
            catch (Exception ex)
            {
                return new JsonViewData { IsSuccess = false, Message = ex.InnerException?.InnerException?.Message ?? ex.InnerException?.Message ?? ex.Message };
            }
        }

and I get this error:

The operation failed: The relationship could not be changed because
  one or more of the foreign-key properties is non-nullable. When a
  change is made to a relationship, the related foreign-key property is
  set to a null value. If the foreign-key does not support null values,
  a new relationship must be defined, the foreign-key property must be
  assigned another non-null value, or the unrelated object must be
  deleted.


来源: stackexchange

问:
Spring Boot - @Async is ignored
Using Spring Boot 1.5.2.RELEASE and the @Async annotation seems to be ignored.

Have setup the environment like this:

```<code>@SpringBootApplication
@EnableAsync
public class Application extends AsyncConfigurerSupport {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public Executor getAsyncExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(500);
        executor.setThreadNamePrefix("async-task-");

        executor.initialize();

        return executor;
    }

    ...
</code>```

... the async method itself:

```<code>@Service
public class MyService {

    @Async
    public Future<Long> asyncTask() throws Exception {

        Long test = 1023L;

        Thread.sleep(10000);

        return new AsyncResult<>(test);
    }
}
</code>```

... now I'm trying to use this:

```<code>@RestController
public MyController {

    @Autowired
    public MyService myService;

    @PostMapping("/test")
    public ResponseEntity<MyResponse> test() {
        return new ResponseEntity<>(
                       new MyResponse(myService
                           .asyncTask()
                           .get()),
                       HttpStatus.OK);
    }
}
</code>```

... and the controller method still hangs for 10sec instead of to be immediatelly returned.

The @Async method is called from the different object. It's neither private nor transactional one as it mentioned at the similar questions.

How to let the method to be invoked asynchronously?

答:
You should have a look at the
Future#get javadoc:

Waits if necessary for the computation to complete, and then retrieves
  its result.

You are transforming your async method to a synchronous call by calling get method.

Thus instead of calling get, just return the Future. Spring MVC supports future as return type:

A ListenableFuture or CompletableFuture/CompletionStage can
  be returned when the application wants to produce the value from a
  thread pool submission.

Example:

```<code>return myService.asyncTask().thenApply(r -> ResponseEntity.ok(new MyResponse(r)));
</code>```

ContentLicense: CC BY-SA 3.0

Title: Spring Boot - @Async is ignored

Body:
Using Spring Boot 1.5.2.RELEASE and the @Async annotation seems to be ignored.

Have setup the environment like this:

@SpringBootApplication
@EnableAsync
public class Application extends AsyncConfigurerSupport {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public Executor getAsyncExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(500);
        executor.setThreadNamePrefix("async-task-");

        executor.initialize();

        return executor;
    }

    ...

... the async method itself:

@Service
public class MyService {

    @Async
    public Future<Long> asyncTask() throws Exception {

        Long test = 1023L;

        Thread.sleep(10000);

        return new AsyncResult<>(test);
    }
}

... now I'm trying to use this:

@RestController
public MyController {

    @Autowired
    public MyService myService;

    @PostMapping("/test")
    public ResponseEntity<MyResponse> test() {
        return new ResponseEntity<>(
                       new MyResponse(myService
                           .asyncTask()
                           .get()),
                       HttpStatus.OK);
    }
}

... and the controller method still hangs for 10sec instead of to be immediatelly returned.

The @Async method is called from the different object. It's neither private nor transactional one as it mentioned at the similar questions.

How to let the method to be invoked asynchronously?

Body:
You should have a look at the
Future#get javadoc:

Waits if necessary for the computation to complete, and then retrieves
  its result.

You are transforming your async method to a synchronous call by calling get method.

Thus instead of calling get, just return the Future. Spring MVC supports future as return type:

A ListenableFuture or CompletableFuture/CompletionStage can
  be returned when the application wants to produce the value from a
  thread pool submission.

Example:

return myService.asyncTask().thenApply(r -> ResponseEntity.ok(new MyResponse(r)));


问:
iframe not disappearing
I have an iframe:

```<code>parent.document.getElementById("IFRAMENAME").style.display = "none";
</code>```

What would cause this code not to work?  If i set the width to 0px it hides it.  I debugged to make sure all the values of the frame are coming back.

I am using ie 7

答:
IFRAMENAME suggests you use the name of the IFrame. That is not right. You should use the id as specified in the id attribute.</p>

```<code><iframe name="notthisone" id="butthisone" src="whatever.htm"></iframe>
</code>```

ContentLicense: CC BY-SA 2.5

Title: iframe not disappearing

Body:
I have an iframe:

parent.document.getElementById("IFRAMENAME").style.display = "none";

What would cause this code not to work?  If i set the width to 0px it hides it.  I debugged to make sure all the values of the frame are coming back.

I am using ie 7

Body:
IFRAMENAME suggests you use the name of the IFrame. That is not right. You should use the id as specified in the id attribute.

<iframe name="notthisone" id="butthisone" src="whatever.htm"></iframe>


问:
Decoding bytes doesn't seem to decode
While trying to get the html source of an... "academic" site I have trouble with decoding. I am using the requests commands:

```<code>resp = requests.get(url)
print(resp.content)
</code>```

edit: I did try resp.text

The result is something like this:

```<code>"b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00\".
</code>```

Bytes. Cool. I tried using .decode("format") with various formats mentioned here (iso, latin, utf, cp) but I had no luck.

Here is what some of those printed:

utf-8:

```<code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
</code>```

latin-1:

```<code>"ÿØÿàJFIFÿÛC         2! !222222222222222222222222Äµ}"
</code>```

iso8859_2:

```<code>"˙Ř˙ŕJFIF˙ŰC         2!!2222222222"
</code>```

edit 2: As per this Q&A I cannot post the link, or refer to the webpage.

Even though this question is about decoding the source, it would also be great if you could point towards alternative solutions (i.e. for the others methods I tried; see below)

1) I tried using selenium but the following prevents it from getting the source: "Accessibility support is partially disabled due to compatibility issues with new Firefox features." (The problem seems to be an add-on that is required to login to the site)

Selenium code:

```<code>driver = webdriver.Firefox()
driver.get(url)
htmlSource = driver.page_source
driver.quit()
soup = BeautifulSoup(htmlSource,'lxml')
</code>```

2) Using urllib didn't work either, and it threw an HTTPError 302 infinite loop. I tried using a cookiejar but to no avail.

答:
As per https://stackoverflow.com/a/41068125/7432972:

resp.text should return Unicode text in your case.

Please do post back and let me know if this works or not as I've never had that problem personally before, possibly because I did always use request_response.text except for when feeding the response into bs4.

EDIT:

As per @Ilja_Everilä, you got an image as a response instead of the source you were looking for. I'd check what response code you receive for that request (resp.status_code), there's a chance it won't be 200, meaning the server returns some other message as a response. If that is the case, changing user-agent to something else may fix it, although it seems like the website in question doesn't want requests from the requests module, at the very least.

Or, even more likely, it has to do with that addon you mentioned that's needed for login. It's possible to add an addon to a selenium.webdriver.FirefoxProfile() through .add_extension('/path/to/addon'). Any sort of configuration for the addon, however, I could not help with.

Title: Decoding bytes doesn't seem to decode

Body:
While trying to get the html source of an... "academic" site I have trouble with decoding. I am using the requests commands:

resp = requests.get(url)
print(resp.content)

edit: I did try resp.text

The result is something like this:

"b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00\".

Bytes. Cool. I tried using .decode("format") with various formats mentioned here (iso, latin, utf, cp) but I had no luck.

Here is what some of those printed:

utf-8:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

latin-1:

"ÿØÿàJFIFÿÛC         2! !222222222222222222222222Äµ}"

iso8859_2:

"˙Ř˙ŕJFIF˙ŰC         2!!2222222222"

edit 2: As per this Q&A I cannot post the link, or refer to the webpage.

Even though this question is about decoding the source, it would also be great if you could point towards alternative solutions (i.e. for the others methods I tried; see below)

1) I tried using selenium but the following prevents it from getting the source: "Accessibility support is partially disabled due to compatibility issues with new Firefox features." (The problem seems to be an add-on that is required to login to the site)

Selenium code:

driver = webdriver.Firefox()
driver.get(url)
htmlSource = driver.page_source
driver.quit()
soup = BeautifulSoup(htmlSource,'lxml')

2) Using urllib didn't work either, and it threw an HTTPError 302 infinite loop. I tried using a cookiejar but to no avail.


问:
*.cs.aspx cannot access *.cs files in App_Code folder
This site was developed a few years ago. it was working 100%. I am re-deploying to my pc to make some changes and testing. Now it cannot find those classes in those files. I have always used 4.5 Framework. I have searched for a solution, unfortunately those have not resolved my issue. including coping it into main directory. It worked when I copied the actual code into one of the *.cs.aspx files. However there are more then 20 pages using this email file. Any advice would be welcome. I have been scratching around for days. Thx.

===================ERROR========================>
The error is as follows:The type or namespace name 'Emailer' could not be found (are you missing a using directive or an assembly reference?)

===================ERROR-DISPLAY================>
Source Error:

Heading

答:
As the message is saying you are most likely missing an Assembly reference. Look at the references of the old project (pic below) and make sure your new project has the same ones added.

If you locate any missing references you can add them by clicking on References > Add reference, and find it among the listed ones or browse to the physical path.


问:
Off canvas responsive menu - open and close issue
I'm developing an responsive menu that switches between a horizontal format for wider view ports and an off canvas menu for smaller view ports.

I completely understand that the two formats are meant to be viewed on devices with the specific view port widths, and that some may argue that people don't usually resize their browser window when viewing a website on desktop; however I need to resolve this since the client sees it as an issue.

Basically, when the browser width is diminished so that the menu is viewed in off canvas mode, and the menu is opened and closed, if the browser window width is then resized, the menu list items (in horizontal format) are hidden.

I'm assuming this is because of the 'closeNav' function which dictates that the width of 'mySidenav' is 0px. However, I've tried quite a few different solutions to this (including the window resize function, none of which have worked.

Please could anyone help me out with this.

Thanks.

function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
}

function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
}

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
    margin: 0;
    padding: 0;
}

html {
    font-size: 100%;
    }

body {
    font-family: "Lato", sans-serif;
    margin: 0;
    padding: 0;
}

li {
    float: none;
    list-style-type: none;
}

#top-bar {
    display: block;
    width:100%;
    height: 53px;
    background-color: #fff400;
}

/* icon to open the navigation menu */
.burger {
    font-size: 2.3rem;
    color: #737171;
    cursor: pointer;
    position: absolute;
    z-index:1;
    top:8px;
    right:20px;
    display: block;
}

/* navigation menu container */
.sidenav {
    width: 0;
    height: 100%;
    position: fixed;
    z-index: 2;
    top: 0;
    right: 0;
    overflow-x: hidden;
    transition: 0.5s;
}

/* navigation menu anchor links */
.sidenav a {
    text-decoration: none;
    display: block;
    transition: 0.3s
}

/* close button */
a.closebtn {
    position: absolute;
    top: 3px;
    right: 20px;
    display: block;
    z-index: 3;
    }

/* The container <div> - needed to position the dropdown content */
.dropdown {
    position: relative;
    display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
    display: none;

}

/* Dropdown Content list elements */
.dropdown-content li {
    float: none;
}

/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {display:block;}

@media screen and (max-height: 450px) {
}

@media screen and (min-width: 720px) {

li {
    float: left;
    list-style-type: none;
}

/* icon to open the navigation menu */
.burger {
    display: none;
}

/* navigation menu container */
.sidenav {
    width: 790px;
    position: fixed;
    z-index: 1;
    top: 0;
    right: 0px;
    overflow-x: visible;
}

/* navigation menu anchor links */
.sidenav a {
    display: inline-block;
    transition: 0.3s;
}

/* close button */
a.closebtn {
    display: none;
    }
}
 /* Dropdown Button
.dropbtn {
    border: none;
    cursor: pointer;
}*/

/* Links inside the dropdown
.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
} */

/* Change color of dropdown links on hover */
.dropdown-content a:hover {}

/* Show the dropdown menu on hover*/
.dropdown:hover .dropdown-content,
.dropdown:focus .dropdown-content {
    display: block;
}</code>```

            ×

Home

About Us

Portfolio

item 1

item 2

Testimonials

Contact Us

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

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
}

function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
}

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}</code>```

* {
    margin: 0;
    padding: 0;
}

html {
    font-size: 100%;
    }

body {
    font-family: "Lato", sans-serif;
    margin: 0;
    padding: 0;
}

li {
    float: none;
    list-style-type: none;
}

#top-bar {
    display: block;
    width:100%;
    height: 53px;
    background-color: #fff400;
}

/* icon to open the navigation menu */
.burger {
    font-size: 2.3rem;
    color: #737171;
    cursor: pointer;
    position: absolute;
    z-index:1;
    top:8px;
    right:20px;
    display: block;
}

/* navigation menu container */
.sidenav {
    width: 0;
    height: 100%;
    position: fixed;
    z-index: 2;
    top: 0;
    right: 0;
    overflow-x: hidden;
    transition: 0.5s;
}

/* navigation menu anchor links */
.sidenav a {
    text-decoration: none;
    display: block;
    transition: 0.3s
}

/* close button */
a.closebtn {
    position: absolute;
    top: 3px;
    right: 20px;
    display: block;
    z-index: 3;
    }

/* The container
 - needed to position the dropdown content */
.dropdown {
    position: relative;
    display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
    display: none;

}

/* Dropdown Content list elements */
.dropdown-content li {
    float: none;
}

/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {display:block;}

@media screen and (max-height: 450px) {
}

@media screen and (min-width: 720px) {

li {
    float: left;
    list-style-type: none;
}

/* icon to open the navigation menu */
.burger {
    display: none;
}

/* navigation menu container */
.sidenav {
    width: 250px;
    position: fixed;
    z-index: 1;
    top: 0;
    right: 0px;
    overflow-x: visible;
}

/* navigation menu anchor links */
.sidenav a {
    display: inline-block;
    transition: 0.3s;
}

/* close button */
a.closebtn {
    display: none;
    }
}
 /* Dropdown Button
.dropbtn {
    border: none;
    cursor: pointer;
}*/

/* Links inside the dropdown
.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
} */

/* Change color of dropdown links on hover */
.dropdown-content a:hover {}

/* Show the dropdown menu on hover*/
.dropdown:hover .dropdown-content,
.dropdown:focus .dropdown-content {
    display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" type="text/css" media="all">

<!--YELLOW TOP BAR-->
<div id="top-bar">

        <!--NAVIGATION MENU-->
        <div id="mySidenav" class="sidenav">
            ×
            <ul>
              <li>Home</li>
              <li>About Us</li>
              <li class="dropdown">Portfolio
                    <ul class="dropdown-content">
                        <li>item 1</li>
                        <li>item 2</li>
                    </ul>
              </li>
              <li>Testimonials</li>
              <li>Contact Us</li>
            </ul>
        </div>

    <!--OPEN NAV BURGER-->
    <span class="burger ion-drag" onclick="openNav()"></span>

</div></code>```

答:
You need to remove the styles that you have added when you clicked on menu bar in responsive while you resize the window. You can find the answer in this question.

jQuery $(window).resize(); equivalent event listener, that only fires on a specified axis change?

Body:
I'm developing an responsive menu that switches between a horizontal format for wider view ports and an off canvas menu for smaller view ports.

I completely understand that the two formats are meant to be viewed on devices with the specific view port widths, and that some may argue that people don't usually resize their browser window when viewing a website on desktop; however I need to resolve this since the client sees it as an issue.

Basically, when the browser width is diminished so that the menu is viewed in off canvas mode, and the menu is opened and closed, if the browser window width is then resized, the menu list items (in horizontal format) are hidden.

I'm assuming this is because of the 'closeNav' function which dictates that the width of 'mySidenav' is 0px. However, I've tried quite a few different solutions to this (including the window resize function, none of which have worked.

Please could anyone help me out with this.

Thanks.

function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
}

function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
}

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

* {
    margin: 0;
    padding: 0;
}

html {
    font-size: 100%;
    }

body {
    font-family: "Lato", sans-serif;
    margin: 0;
    padding: 0;
}

li {
    float: none;
    list-style-type: none;
}

#top-bar {
    display: block;
    width:100%;
    height: 53px;
    background-color: #fff400;
}

/* icon to open the navigation menu */
.burger {
    font-size: 2.3rem;
    color: #737171;
    cursor: pointer;
    position: absolute;
    z-index:1;
    top:8px;
    right:20px;
    display: block;
}

/* navigation menu container */
.sidenav {
    width: 0;
    height: 100%;
    position: fixed;
    z-index: 2;
    top: 0;
    right: 0;
    overflow-x: hidden;
    transition: 0.5s;
}

/* navigation menu anchor links */
.sidenav a {
    text-decoration: none;
    display: block;
    transition: 0.3s
}

/* close button */
a.closebtn {
    position: absolute;
    top: 3px;
    right: 20px;
    display: block;
    z-index: 3;
    }

/* The container
 - needed to position the dropdown content */
.dropdown {
    position: relative;
    display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
    display: none;

}

/* Dropdown Content list elements */
.dropdown-content li {
    float: none;
}

/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {display:block;}

@media screen and (max-height: 450px) {
}

@media screen and (min-width: 720px) {

li {
    float: left;
    list-style-type: none;
}

/* icon to open the navigation menu */
.burger {
    display: none;
}

/* navigation menu container */
.sidenav {
    width: 790px;
    position: fixed;
    z-index: 1;
    top: 0;
    right: 0px;
    overflow-x: visible;
}

/* navigation menu anchor links */
.sidenav a {
    display: inline-block;
    transition: 0.3s;
}

/* close button */
a.closebtn {
    display: none;
    }
}
 /* Dropdown Button
.dropbtn {
    border: none;
    cursor: pointer;
}*/

/* Links inside the dropdown
.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
} */

/* Change color of dropdown links on hover */
.dropdown-content a:hover {}

/* Show the dropdown menu on hover*/
.dropdown:hover .dropdown-content,
.dropdown:focus .dropdown-content {
    display: block;
}

            ×

Home

About Us

Portfolio

item 1

item 2

Testimonials

Contact Us

function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
}

function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
}

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

* {
    margin: 0;
    padding: 0;
}

html {
    font-size: 100%;
    }

body {
    font-family: "Lato", sans-serif;
    margin: 0;
    padding: 0;
}

li {
    float: none;
    list-style-type: none;
}

#top-bar {
    display: block;
    width:100%;
    height: 53px;
    background-color: #fff400;
}

/* icon to open the navigation menu */
.burger {
    font-size: 2.3rem;
    color: #737171;
    cursor: pointer;
    position: absolute;
    z-index:1;
    top:8px;
    right:20px;
    display: block;
}

/* navigation menu container */
.sidenav {
    width: 0;
    height: 100%;
    position: fixed;
    z-index: 2;
    top: 0;
    right: 0;
    overflow-x: hidden;
    transition: 0.5s;
}

/* navigation menu anchor links */
.sidenav a {
    text-decoration: none;
    display: block;
    transition: 0.3s
}

/* close button */
a.closebtn {
    position: absolute;
    top: 3px;
    right: 20px;
    display: block;
    z-index: 3;
    }

/* The container
 - needed to position the dropdown content */
.dropdown {
    position: relative;
    display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
    display: none;

}

/* Dropdown Content list elements */
.dropdown-content li {
    float: none;
}

/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {display:block;}

@media screen and (max-height: 450px) {
}

@media screen and (min-width: 720px) {

li {
    float: left;
    list-style-type: none;
}

/* icon to open the navigation menu */
.burger {
    display: none;
}

/* navigation menu container */
.sidenav {
    width: 250px;
    position: fixed;
    z-index: 1;
    top: 0;
    right: 0px;
    overflow-x: visible;
}

/* navigation menu anchor links */
.sidenav a {
    display: inline-block;
    transition: 0.3s;
}

/* close button */
a.closebtn {
    display: none;
    }
}
 /* Dropdown Button
.dropbtn {
    border: none;
    cursor: pointer;
}*/

/* Links inside the dropdown
.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
} */

/* Change color of dropdown links on hover */
.dropdown-content a:hover {}

/* Show the dropdown menu on hover*/
.dropdown:hover .dropdown-content,
.dropdown:focus .dropdown-content {
    display: block;
}

<link rel="stylesheet" href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" type="text/css" media="all">

            ×

Home

About Us

Portfolio

item 1

item 2

Testimonials

Contact Us


问:
table row in php are stuck
I've been trying to get te rows right in my table somehow it's stuck,
I don't know why. the first table with "rekening" should be showing all the results from the table rekening in my database which works , but the second row "creditcards" is a bit stuck.

Here is my code:

```<code>$db = mysqli_connect($host, $user, $pass,$database);
$rekening= mysqli_query($db,"SELECT * FROM Rekening");
$cc= mysqli_query($db,"SELECT * FROM Creditcard");

while ($row1 = mysqli_fetch_assoc($rekening)){

    $h.= "<tr><td>".$row1['rekeningNummer']."</td>";

    while ($row2 = mysqli_fetch_assoc($cc)){

        $rekeningID = $row2['rekening_ID'];
        $creditcard= mysqli_query($db,"SELECT * FROM creditcard WHERE Rekening_ID = '$rekeningID'");

        while ($row3 = mysqli_fetch_assoc($creditcard)){
            $h.= "<td><td>".$row3['creditcardNummer']."</td></tr>";
        }
    }
}
</code>```

and here is the picture of my page :

https://gyazo.com/1fa963573fd5d07d50e5e8231bcd487c

and here the database :
https://gyazo.com/dc71363640e0b6495e9a3504d0405365

答:
I can see that You open a new
 tag everytime You get an result, but You don't close that tag. Opening și many tags but not closing them might be one of your problems.
Instead of this

```<code>$h.= "<tr><td>".$row1['rekeningNummer']."</td>";
</code>```

You can use this

```<code>$h.= "<tr><td>".$row1['rekeningNummer']."</td></td>";
</code>```

Title: table row in php are stuck

Body:
I've been trying to get te rows right in my table somehow it's stuck,
I don't know why. the first table with "rekening" should be showing all the results from the table rekening in my database which works , but the second row "creditcards" is a bit stuck.

Here is my code:

$db = mysqli_connect($host, $user, $pass,$database);
$rekening= mysqli_query($db,"SELECT * FROM Rekening");
$cc= mysqli_query($db,"SELECT * FROM Creditcard");

while ($row1 = mysqli_fetch_assoc($rekening)){

    $h.= "
".$row1['rekeningNummer']."	";

    while ($row2 = mysqli_fetch_assoc($cc)){

        $rekeningID = $row2['rekening_ID'];
        $creditcard= mysqli_query($db,"SELECT * FROM creditcard WHERE Rekening_ID = '$rekeningID'");

        while ($row3 = mysqli_fetch_assoc($creditcard)){
            $h.= "".$row3['creditcardNummer']."
";
        }
    }
}

and here is the picture of my page :

https://gyazo.com/1fa963573fd5d07d50e5e8231bcd487c

and here the database :
https://gyazo.com/dc71363640e0b6495e9a3504d0405365

Body:
I can see that You open a new <tr> tag everytime You get an result, but You don't close that tag. Opening și many tags but not closing them might be one of your problems.
Instead of this

$h.= "<tr><td>".$row1['rekeningNummer']."</td>";

You can use this

$h.= "<tr><td>".$row1['rekeningNummer']."</td></td>";


问:
Cannot use XmlMapper (Jackson-dataformat-xml) in Spring boot, error: requiresPropertyOrdering()Z
I've used Spring Boot version 1.5.2 with Maven default pom.xml

```<code>...
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
</parent>
...
</code>```

Because Spring Boot does not have XmlMapper from Maven: jackson-dataformat-xml, so I added this dependency in pom.xml

```<code>    <dependency>
      <groupId>com.fasterxml.jackson.dataformat</groupId>
      <artifactId>jackson-dataformat-xml</artifactId>
      <version>2.8.7</version>
    </dependency>
</code>```

and check the Jackson dependencies for project, all of them have same version 2.8.7 (newest).

```<code>    mvn dependency:tree -Dincludes=com.fasterxml.jackson.core
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.10:tree (default-cli) @ demo ---
[INFO] com.example:demo:jar:0.0.1-SNAPSHOT
[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:1.5.2.RELEASE:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-databind:jar:2.8.7:compile
[INFO] +- com.fasterxml.jackson.dataformat:jackson-dataformat-xml:jar:2.8.7:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-core:jar:2.8.7:compile
[INFO] \- com.fasterxml.jackson.core:jackson-annotations:jar:2.8.7:compile
</code>```

And when I run the application, it cannot start as there is an error in Spring Boot for NoSuchMethod found.

```<code>Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.filter.OrderedHttpPutFormContentFilter]: Factory method 'httpPutFormContentFilter' threw exception; nested exception is java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonFactory.requiresPropertyOrdering()Z
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    ... 26 common frames omitted
Caused by: java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonFactory.requiresPropertyOrdering()Z
    at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:564) ~[jackson-databind-2.8.7.jar:2.8.7]
    at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:474) ~[jackson-databind-2.8.7.jar:2.8.7]
    at org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.build(Jackson2ObjectMapperBuilder.java:588) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.<init>(MappingJackson2HttpMessageConverter.java:57) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter.<init>(AllEncompassingFormHttpMessageConverter.java:61) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.HttpPutFormContentFilter.<init>(HttpPutFormContentFilter.java:63) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.boot.web.filter.OrderedHttpPutFormContentFilter.<init>(OrderedHttpPutFormContentFilter.java:29) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
</code>```

Any idea for this problem? I want to use XmlMapper from Jackson library to deserialize/serialize XML string to object and vice-versa (not from the HTTPRequest but internally).

Here is the full pom.xml for Maven https://pastebin.com/LMujJY7e

答:
I think you have run into a problem of version compatibility of dependencies.

I use spring boot 1.5.2 with jackson-dataformat-xml without any problems.

This is part of my build.gradle

```<code>ext {
    springBootVersion = '1.5.2.RELEASE'
}

compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.8.5'
</code>```

hope it helps

Body:
I've used Spring Boot version 1.5.2 with Maven default pom.xml

...
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
</parent>
...

Because Spring Boot does not have XmlMapper from Maven: jackson-dataformat-xml, so I added this dependency in pom.xml

    <dependency>
      <groupId>com.fasterxml.jackson.dataformat</groupId>
      <artifactId>jackson-dataformat-xml</artifactId>
      <version>2.8.7</version>
    </dependency>

and check the Jackson dependencies for project, all of them have same version 2.8.7 (newest).

    mvn dependency:tree -Dincludes=com.fasterxml.jackson.core
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.10:tree (default-cli) @ demo ---
[INFO] com.example:demo:jar:0.0.1-SNAPSHOT
[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:1.5.2.RELEASE:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-databind:jar:2.8.7:compile
[INFO] +- com.fasterxml.jackson.dataformat:jackson-dataformat-xml:jar:2.8.7:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-core:jar:2.8.7:compile
[INFO] \- com.fasterxml.jackson.core:jackson-annotations:jar:2.8.7:compile

And when I run the application, it cannot start as there is an error in Spring Boot for NoSuchMethod found.

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.filter.OrderedHttpPutFormContentFilter]: Factory method 'httpPutFormContentFilter' threw exception; nested exception is java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonFactory.requiresPropertyOrdering()Z
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    ... 26 common frames omitted
Caused by: java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonFactory.requiresPropertyOrdering()Z
    at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:564) ~[jackson-databind-2.8.7.jar:2.8.7]
    at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:474) ~[jackson-databind-2.8.7.jar:2.8.7]
    at org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.build(Jackson2ObjectMapperBuilder.java:588) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.<init>(MappingJackson2HttpMessageConverter.java:57) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter.<init>(AllEncompassingFormHttpMessageConverter.java:61) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.HttpPutFormContentFilter.<init>(HttpPutFormContentFilter.java:63) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.boot.web.filter.OrderedHttpPutFormContentFilter.<init>(OrderedHttpPutFormContentFilter.java:29) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]

Any idea for this problem? I want to use XmlMapper from Jackson library to deserialize/serialize XML string to object and vice-versa (not from the HTTPRequest but internally).

Here is the full pom.xml for Maven https://pastebin.com/LMujJY7e

Body:
I think you have run into a problem of version compatibility of dependencies.

I use spring boot 1.5.2 with jackson-dataformat-xml without any problems.

This is part of my build.gradle

ext {
    springBootVersion = '1.5.2.RELEASE'
}

compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.8.5'

hope it helps

ContentLicense: CC BY-SA 4.0


问:
Protecting Sections of Source Code
I'm writing a Java class that connects to a server and reads messages in a given queue.

I would like to protect the username and password, which, right now, appear as plain text in the source code.

What I'm wondering, is, what is a good way to do this?  If I encrypt the username and password in a text file, won't I need to store the key, in plain text, in any source code that accesses this file?  And then anyone else who decides to use my class will be able to gain access to these fields.

There is no prompt where someone can enter the key, either, as this class will autonomously be used by the system.

EDIT:  this will become a java lib file.  But those can easily be decompiled and thus are basically the original class files anyway, right?  And the people this is being protected from are fellow developers of other systems who will gain access to this lib file.

My End Goal: is to have the username and password strings not appear as plain text anywhere, and for them to be as difficult as possible to crack.

答:
It is not possible to do this. Even if you encrypt the login/password and store it somewhere (may it be your class or an external file) you'd still need to save the encryption key somewhere in plain text. This is actually just marginally better than saving username/password in plain text, in fact I would avoid doing so as it creates a false sense of security.

So I'd suggest that your class takes username/password as a parameter and that the system which is using your class will have to care about protecting the credentials. It could do so by asking an end user to enter the credentials or store them into an external file which is only readable to the operating system user that your process is running as.

Edit: You might also think about using mechanisms such as OAuth which use tokens instead of passwords. Tokens have a limited life time and are tied to a certain purpose so they pose a good alternative to access credentials. So your end users could get an access token with their,say, Windows credentials, which is then used inside your class to call the protected service.

Title: Protecting Sections of Source Code


问:
Spacial data for region mapping
I have some data in the UK and I need to introduce a map of all 9 regions of England. I tried using library(maps) but the plots I get do not have any regional information and I just end up with the whole of the United Kingdom.

Ideally i am looking for a result like this
https://upload.wikimedia.org/wikipedia/commons/thumb/b/b4/English_regions_2009.svg/370px-English_regions_2009.svg.png

(I cant actually attach pictures due to the lack of reputation points,apologies!)

My data has a column for regions with character values:

```<code>         EastMid
         EastEng
         London
         NorthEast
         NorthWest
         SouthEast
         SouthWest
         WestMid
         Yorkshire
</code>```

I would then go on to map by color regions with different attributes

How would I go on about this?

答:
First, as Andrew wrote you need to find and download shapefiles with necessary regions. Such split as you need is usually called historical regions or standard statistical regions. You might want to check this site: http://www.natureonthemap.naturalengland.org.uk/

Second, you read shapefile and merge with referendum data. Make sure that region names at the referendum file are exactly the same as in geospatial file (I use file downloaded from the site mentioned above, if you download another shapefile the names probably will be different):

```<code>library(rgdal)
library(tmap)
geoEN = readOGR(".", "maghistengland")
</code>```

In this case region names are stored in NAME (in another shapefile attribute name can be different). You can check what information consists of geospatial file by:

```<code>ogrInfo(".", "maghistengland")
</code>```

For the purpose of the example I am creating fake figures of voting results.

```<code>votes = as.data.frame(
    cbind(
    c("EAST MIDLANDS",
    "EAST OF ENGLAND",
    "LONDON",
    "NORTH EAST",
    "NORTH WEST",
    "SOUTH EAST",
    "WEST MIDLANDS",
    "YORKSHIRE AND THE HUMBER",
    "SOUTH WEST"),
    c(60, 65, 55, 50, 45, 40, 35, 30, 30),
    c(40, 35, 45, 50, 55, 60, 65, 70, 70)
  ), stringsAsFactors = FALSE)

names(votes) = c("Regions", "Yes", "No")

votes$Yes = as.numeric(votes$Yes)
votes$No = as.numeric(votes$No)
votes$Result = colnames(votes)[max.col(votes[,2:3])+1]
</code>```

Now we can merge both files:

```<code>mapEN = append_data(geoEN, votes, key.shp = "NAME", key.data = "Regions")
</code>```

Third, create necessary charts. Here are three examples. You can play with number of groups (n = 2, 3, 4..), colors etc.

```<code>tm_shape(mapEN) +
    tm_fill("Yes", title = "This is a title", palette = "Blues", n=4) +
    tm_borders(alpha=.5)

tm_shape(mapEN) +
    tm_fill("No", title = "This is a title", palette = "Reds", n=5) +
    tm_borders(alpha=.5)

tm_shape(mapEN) +
    tm_fill("Result", palette = c("Red", "Blue")) +
    tm_borders(alpha=.5)
</code>```

OwnerDisplayName: anon

LastEditorDisplayName: anon

Title: Spacial data for region mapping

Body:
I have some data in the UK and I need to introduce a map of all 9 regions of England. I tried using library(maps) but the plots I get do not have any regional information and I just end up with the whole of the United Kingdom.

Ideally i am looking for a result like this
https://upload.wikimedia.org/wikipedia/commons/thumb/b/b4/English_regions_2009.svg/370px-English_regions_2009.svg.png

(I cant actually attach pictures due to the lack of reputation points,apologies!)

My data has a column for regions with character values:

         EastMid
         EastEng
         London
         NorthEast
         NorthWest
         SouthEast
         SouthWest
         WestMid
         Yorkshire

I would then go on to map by color regions with different attributes

How would I go on about this?

Body:
First, as Andrew wrote you need to find and download shapefiles with necessary regions. Such split as you need is usually called historical regions or standard statistical regions. You might want to check this site: http://www.natureonthemap.naturalengland.org.uk/

Second, you read shapefile and merge with referendum data. Make sure that region names at the referendum file are exactly the same as in geospatial file (I use file downloaded from the site mentioned above, if you download another shapefile the names probably will be different):

library(rgdal)
library(tmap)
geoEN = readOGR(".", "maghistengland")

In this case region names are stored in NAME (in another shapefile attribute name can be different). You can check what information consists of geospatial file by:

ogrInfo(".", "maghistengland")

For the purpose of the example I am creating fake figures of voting results.

votes = as.data.frame(
    cbind(
    c("EAST MIDLANDS",
    "EAST OF ENGLAND",
    "LONDON",
    "NORTH EAST",
    "NORTH WEST",
    "SOUTH EAST",
    "WEST MIDLANDS",
    "YORKSHIRE AND THE HUMBER",
    "SOUTH WEST"),
    c(60, 65, 55, 50, 45, 40, 35, 30, 30),
    c(40, 35, 45, 50, 55, 60, 65, 70, 70)
  ), stringsAsFactors = FALSE)

names(votes) = c("Regions", "Yes", "No")

votes$Yes = as.numeric(votes$Yes)
votes$No = as.numeric(votes$No)
votes$Result = colnames(votes)[max.col(votes[,2:3])+1]

Now we can merge both files:

mapEN = append_data(geoEN, votes, key.shp = "NAME", key.data = "Regions")

Third, create necessary charts. Here are three examples. You can play with number of groups (n = 2, 3, 4..), colors etc.

tm_shape(mapEN) +
    tm_fill("Yes", title = "This is a title", palette = "Blues", n=4) +
    tm_borders(alpha=.5)

tm_shape(mapEN) +
    tm_fill("No", title = "This is a title", palette = "Reds", n=5) +
    tm_borders(alpha=.5)

tm_shape(mapEN) +
    tm_fill("Result", palette = c("Red", "Blue")) +
    tm_borders(alpha=.5)


问:
Python close a while
Hello i have made this simple program but i have a problem. All the program works good but at the end after i answer the final question "Do you want to make another operation? yes or no" and i choose no, the window of the input don't close. (this probably mean that i don't have closed properly the while loop). How i can close the while correctly ? </p>

<p>CODE : </p>

```<code>def multiplication(b, c):

   a=b*c

   return a

def division(b, c):

   a=b/c

   return a

def main():

    Menu = input("""Choose one operation :

    1.Multiplication
    2.Division

    -------------------->""")

   if Menu=="1":

       b=float(input("Insert a number"))
       c=float(input("Insert a number"))

       print("Result :",multiplication(b, c))

   elif Menu=="2":

       b=float(input("Insert a number"))
       c=float(input("Insert a number"))

       print("Result :",division(b, c))

 main()

 while True:

    while True:

        cont=input("Do you want to make another operation? yes or no")

        if cont=="yes":

            main()

        else:

            print ("Close")
            break
</code>```

答:
You have to while Loop. Remove the outer one and it'll work.
Also unhindent the inner while loop

Title: Python close a while

Body:
Hello i have made this simple program but i have a problem. All the program works good but at the end after i answer the final question "Do you want to make another operation? yes or no" and i choose no, the window of the input don't close. (this probably mean that i don't have closed properly the while loop). How i can close the while correctly ?

CODE :

def multiplication(b, c):

   a=b*c

   return a

def division(b, c):

   a=b/c

   return a

def main():

    Menu = input("""Choose one operation :

    1.Multiplication
    2.Division

    -------------------->""")

   if Menu=="1":

       b=float(input("Insert a number"))
       c=float(input("Insert a number"))

       print("Result :",multiplication(b, c))

   elif Menu=="2":

       b=float(input("Insert a number"))
       c=float(input("Insert a number"))

       print("Result :",division(b, c))

 main()

 while True:

    while True:

        cont=input("Do you want to make another operation? yes or no")

        if cont=="yes":

            main()

        else:

            print ("Close")
            break


问:
Drupal - clean database
Is there a way to clear or clean the database of all the unnessecary entries that was added by amodules that have since been uninstalled. Ive created my site but have added alot of modules to ploay around with, I have no removed all of those I dont use, but just wondering if there is a way top clear the database etc.. to ensure nothing unused was left behind ?

thanks

答: If you have your own content that you would want to keep AND you have used the uninstall feature for all the modules that you have installed, then the only route is to manually check. if you don't have much content you could export it and replace the db with a clean one, then put your content back into it.</p>

Title: Drupal - clean database


问:
Haskell: "Couldn't match expected type IO () with IO ThreadId"
I'm new to concurrency in Haskell and I'm trying to get a result where a new MVar is made in the main thread, is passed over empty to the userThread thread, which takes a character input from the user, then puts that value in an MVar and has the main thread print it.

Here is what I have so far

```<code>module Main where

import Control.Concurrent
import Control.Monad
import System.IO
import System.Random
import Text.Printf

data Msg = C Char | Time

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  hSetBuffering stdin NoBuffering
  hSetEcho stdin False

  -- shared resources
  chan <- newEmptyMVar
  forkIO $ userThread chan
  --r <- takeMVar chan
  --show(r)

userThread :: MVar Msg -> IO ()
userThread chan = forever $ do
  x <- getChar
  putMVar chan (C x)
</code>```

Right now, I'm stuck on trying to put the entered char into the MVar, I've pasted the error below

```<code>assignment1.hs:20:3: error:
    * Couldn't match type `ThreadId' with `()'
      Expected type: IO ()
        Actual type: IO ThreadId
    * In a stmt of a 'do' block: forkIO $ userThread chan
      In the expression:
        do { hSetBuffering stdout NoBuffering;
             hSetBuffering stdin NoBuffering;
             hSetEcho stdin False;
             chan <- newEmptyMVar;
             .... }
      In an equation for `main':
          main
            = do { hSetBuffering stdout NoBuffering;
                   hSetBuffering stdin NoBuffering;
                   hSetEcho stdin False;
                   .... }
Failed, modules loaded: none.
</code>```

Any pointers in the right direction would be a great help!
Thanks everyone

答:
Since you're going to get this error over and over as you learn haskell, I wanted to unpack it for you:

```<code>assignment1.hs:20:3: error:
</code>```

GHC is giving you the file, line number and column number: file:line:col

```<code>    * Couldn't match type `ThreadId' with `()'
      Expected type: IO ()
        Actual type: IO ThreadId
</code>```

Expected type refers to the type GHC is expecting for an expression, based on the context e.g. a type signature you provided, or the way you use a value returned from that expression. Actual type is the... actual type of the expression, e.g. a literal 'c' has type Char, map fst [('c', undefined)] has actual type [Char], etc.

```<code>    * In a stmt of a 'do' block: forkIO $ userThread chan
</code>```

This ^ is the problem statement. forkIO returns a ThreadId (which you can see from its type signature). The tricky part here then, I suppose, is to know why the typechecker was expecting a type IO () (because of your type signature, and the fact that the value returned in the last statement of your do block will be the type returned, as chi mentions).

It's useful to have ghci open to help you answer questions like these as you're developing:

```<code>Prelude> import Control.Concurrent
Prelude Control.Concurrent> :t forkIO
forkIO :: IO () -> IO ThreadId
Prelude Control.Concurrent> :t ()
() :: ()
Prelude Control.Concurrent> :t repeat ()
repeat () :: [()]
</code>```

The rest is more context which you probably don't need if you have the file in front of you:

```<code>      In the expression:
        do { hSetBuffering stdout NoBuffering;
             hSetBuffering stdin NoBuffering;
             hSetEcho stdin False;
             chan <- newEmptyMVar;
             .... }
      In an equation for `main':
          main
            = do { hSetBuffering stdout NoBuffering;
                   hSetBuffering stdin NoBuffering;
                   hSetEcho stdin False;
                   .... }
Failed, modules loaded: none.
</code>```

Body:
I'm new to concurrency in Haskell and I'm trying to get a result where a new MVar is made in the main thread, is passed over empty to the userThread thread, which takes a character input from the user, then puts that value in an MVar and has the main thread print it.

Here is what I have so far

module Main where

import Control.Concurrent
import Control.Monad
import System.IO
import System.Random
import Text.Printf

data Msg = C Char | Time

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  hSetBuffering stdin NoBuffering
  hSetEcho stdin False

  -- shared resources
  chan <- newEmptyMVar
  forkIO $ userThread chan
  --r <- takeMVar chan
  --show(r)

userThread :: MVar Msg -> IO ()
userThread chan = forever $ do
  x <- getChar
  putMVar chan (C x)

Right now, I'm stuck on trying to put the entered char into the MVar, I've pasted the error below

assignment1.hs:20:3: error:
    * Couldn't match type `ThreadId' with `()'
      Expected type: IO ()
        Actual type: IO ThreadId
    * In a stmt of a 'do' block: forkIO $ userThread chan
      In the expression:
        do { hSetBuffering stdout NoBuffering;
             hSetBuffering stdin NoBuffering;
             hSetEcho stdin False;
             chan <- newEmptyMVar;
             .... }
      In an equation for `main':
          main
            = do { hSetBuffering stdout NoBuffering;
                   hSetBuffering stdin NoBuffering;
                   hSetEcho stdin False;
                   .... }
Failed, modules loaded: none.

Any pointers in the right direction would be a great help!
Thanks everyone

Body:
Since you're going to get this error over and over as you learn haskell, I wanted to unpack it for you:

assignment1.hs:20:3: error:

GHC is giving you the file, line number and column number: file:line:col

    * Couldn't match type `ThreadId' with `()'
      Expected type: IO ()
        Actual type: IO ThreadId

Expected type refers to the type GHC is expecting for an expression, based on the context e.g. a type signature you provided, or the way you use a value returned from that expression. Actual type is the... actual type of the expression, e.g. a literal 'c' has type Char, map fst [('c', undefined)] has actual type [Char], etc.

    * In a stmt of a 'do' block: forkIO $ userThread chan

This ^ is the problem statement. forkIO returns a ThreadId (which you can see from its type signature). The tricky part here then, I suppose, is to know why the typechecker was expecting a type IO () (because of your type signature, and the fact that the value returned in the last statement of your do block will be the type returned, as chi mentions).

It's useful to have ghci open to help you answer questions like these as you're developing:

Prelude> import Control.Concurrent
Prelude Control.Concurrent> :t forkIO
forkIO :: IO () -> IO ThreadId
Prelude Control.Concurrent> :t ()
() :: ()
Prelude Control.Concurrent> :t repeat ()
repeat () :: [()]

The rest is more context which you probably don't need if you have the file in front of you:

      In the expression:
        do { hSetBuffering stdout NoBuffering;
             hSetBuffering stdin NoBuffering;
             hSetEcho stdin False;
             chan <- newEmptyMVar;
             .... }
      In an equation for `main':
          main
            = do { hSetBuffering stdout NoBuffering;
                   hSetBuffering stdin NoBuffering;
                   hSetEcho stdin False;
                   .... }
Failed, modules loaded: none.