问:
Flexbox: Header, centered body and sticky footer overflow
Update This has been solved thanks to LGSon's comment below Updated codepen

I am trying to setup a layout much like the Holy grail. The difference here is that I am looking for a dynamically sized "Content" section to be vertically and horizontally centered.

I have been able to get this working (for large displays) with flexbox: Codepen here

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  text-align: center;
}

.header {
  height: 60px;
  line-height: 60px;
  width: 100%;
  background: rgba(255, 0, 0, 0.5);
}

.content {
  height: calc(100% - 120px);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 255, 0, 0.5);
}
.content p {
  width: 50%;
}

.footer {
  height: 60px;
  line-height: 60px;
  width: 100%;
  background: rgba(0, 0, 255, 0.5);
}

.header, .footer {
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
    Header
</div>

<div class="content">
    <h1>I am the content</h1>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

<div class="footer">
    Footer
</div></code>```

The problem is that if the "Content" section is too large, or the view is too small, the overflow wont kick in until the div is more than 100% vertical not (100% height - the header and footer heights)

I am trying to make it so that when there is overlap, that the whole page will scroll and not only have a scrollbar within the "Content section".

答:
After using position: fixed; on the header and footer, my syggestion is to:

remove the opaque background colours, and replace them with non opaque ones that look exactly the same (this I have already done)

remove the background colour for the article, and give the html, body the background-color instead

use background-color instead of background in this case:

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  background-color: #7FFF7F;
  text-align: center;

}

.header {
  position: fixed;
  top: 0px;
  height: 60px;
  line-height: 60px;
  width: 100%;
  background-color: #FF7F7F;
}

.content {
  overflow: scroll;
  padding: 60px 0 60px 0;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
      -ms-flex-direction: column;
          flex-direction: column;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
}

.content p {
  width: 50%;
}

.footer {
  position: fixed;
  bottom: 0px;
  height: 60px;
  line-height: 60px;
  width: 100%;
  background-color: #7F7FFF;
}

.header,
.footer {
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
    Header
</div>

<div class="content">
    <h1>I am the content</h1>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

<div class="footer">
    Footer
</div></code>```

CodePen

Body:
Update This has been solved thanks to LGSon's comment below Updated codepen

I am trying to setup a layout much like the Holy grail. The difference here is that I am looking for a dynamically sized "Content" section to be vertically and horizontally centered.

I have been able to get this working (for large displays) with flexbox: Codepen here

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  text-align: center;
}

.header {
  height: 60px;
  line-height: 60px;
  width: 100%;
  background: rgba(255, 0, 0, 0.5);
}

.content {
  height: calc(100% - 120px);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 255, 0, 0.5);
}
.content p {
  width: 50%;
}

.footer {
  height: 60px;
  line-height: 60px;
  width: 100%;
  background: rgba(0, 0, 255, 0.5);
}

.header, .footer {
  font-weight: bold;
}

    Header

I am the content

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

    Footer

The problem is that if the "Content" section is too large, or the view is too small, the overflow wont kick in until the div is more than 100% vertical not (100% height - the header and footer heights)

I am trying to make it so that when there is overlap, that the whole page will scroll and not only have a scrollbar within the "Content section".

Body:
After using position: fixed; on the header and footer, my syggestion is to:

remove the opaque background colours, and replace them with non opaque ones that look exactly the same (this I have already done)

remove the background colour for the article, and give the html, body the background-color instead

use background-color instead of background in this case:

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  background-color: #7FFF7F;
  text-align: center;

}

.header {
  position: fixed;
  top: 0px;
  height: 60px;
  line-height: 60px;
  width: 100%;
  background-color: #FF7F7F;
}

.content {
  overflow: scroll;
  padding: 60px 0 60px 0;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
      -ms-flex-direction: column;
          flex-direction: column;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
}

.content p {
  width: 50%;
}

.footer {
  position: fixed;
  bottom: 0px;
  height: 60px;
  line-height: 60px;
  width: 100%;
  background-color: #7F7FFF;
}

.header,
.footer {
  font-weight: bold;
}

<div class="header">
    Header
</div>

<div class="content">
    <h1>I am the content</h1>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

<div class="footer">
    Footer
</div>

CodePen


来源: stackexchange

问:
Program throws 'Access-Control-Allow-Origin' header in JavaScript? Works in Postman, not through browser
Solved

I have been working on this program since 07:00. This has been driving me crazy. I have written multiple full stack web apps and have not had this problem.

Basically I have a form in html that allows a user to input data. Whenever the submit button is clicked, it sends that data to a collection in mongoDB. I have tested this in postman and it works. However, when I run the program through a webbrowser, I get this error:

XMLHttpRequest cannot load http://localhost:8080/articles/addArticle. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404.

I tried installing CORS and configuring the endpoint

I tried going into the javascript file and changing the

This is my JavaScript file

```<code>alert('JS is linked to page!');

function Article(id = 1, title = "", authors="", content = "", genre = "", date = 1497484623) {
    console.log("JavaScript file loaded successfully");
    var self = this;
    self.Id = id;
    self.Title = title;
    self.Authors = authors;
    self.Content = content;
    self.Genre = genre;
    self.Date = date;
    self.Save = function() {
        var settings = {
            url: 'http://localhost:8080/articles/addArticle',
            method: 'POST',
            dataType: "json",
              beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json");
            }
        };
        var myData = {
            "Id" : self.Id,
            "Title": self.Title,
            "Authors": self.Authors,
            "Content": self.Content,
            "Genre": self.Genre,
            "Date": self.Date
        };
        settings.data = myData;

        $.ajax(settings).done(function(article) {
         var myArticle = new Article(article.Id, article.Title, article.Authors,
                article.Content, article.Genre, article.Date);
        });
    };
}

function addArticle(Article) {
    alert('addArticle Activated');
    var settings = {
        url: 'http://localhost:8080/articles/addArticle',
        method: 'POST',
        dataType: "json",
          beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json");
            }
    };
    var myData = {
        "Title": Article.Title,
        "Authors" : Article.Authors,
        "Content": Article.Content,
        "Genre" : Article.Genre,
        "Date": Article.Date
    };
    settings.data = myData;

    $.ajax(settings).done(function(Article) {
        var myArticle = new Article(article.Id, article.Title, article.Authors, article.Content,
            article.Genre, article.Date);
        console.log("Article Created");
    });
}

$(document).ready(function() {

    $(document).on("submit", "#add-article", function(e) {
        e.preventDefault();
            alert('submit Activated');
        var title, authors, genre, content;
        title = $("#Title").val();
        director = $("#Authors").val();
        rating = $("#Genre").val();
        notes = $("#Content").val();
        var myArticle = new Article(0, title, authors, genre, content, 1497484623);
        alert(myArticle.Title);
        addArticle(myArticle);
        $("#add-article")[0].reset();
        $("#title").focus();

    });

});

/*function CreateSuccessRow(Article) {
    var successDataRow = `<tr id="Article-${Article.Id}"><td>${Article.Title}</td>
                <td>${Article.Authors}</td>
                <td>${Article.Genre}</td>
</code>```

Due to popular demand, this is the server-side code:

```<code>package com.stereoscopics.app.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.stereoscopics.app.models.Article;
import com.stereoscopics.app.repo.ArticleRepo;

@RestController
@RequestMapping("/articles")
public class ArticleController {

private ArticleRepo articleRepo;

@Autowired
public ArticleController(ArticleRepo articleRepo) {
    this.articleRepo = articleRepo;
}

@RequestMapping(value = "/findall", method = RequestMethod.GET)
@ResponseBody
public List<Article> findall() {
    return articleRepo.findAll();
}

@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle) {
    articleRepo.save(newArticle);
    return newArticle;
}
</code>```

}

I have no idea how to fix this. Please help.

UPDATE

This still isn't working. I've updated the code as per some suggestions and I'm either doing it wrong or it's incorrect. The changes are shown below:

```<code>  @RestController
  @RequestMapping("/articles")
  public class ArticleController {

private ArticleRepo articleRepo;

@Autowired
public ArticleController(ArticleRepo articleRepo) {
    this.articleRepo = articleRepo;
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");
}

@RequestMapping(value = "/findall", method = RequestMethod.GET)
@ResponseBody
public List<Article> findall() {
    return articleRepo.findAll();
}

@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle, final
HttpServletResponse response) {
    response.addHeader("Access-Control-Allow-Origin", "*");
    articleRepo.save(newArticle);
    return newArticle;
  }
}
</code>```

THIS IS NOT SOLVED YET

答:
I accidentally marked this as solved, when it clearly is not.

By including the port number in the Javascript url, the server threw an error because it mistook the request as originating from somewhere it wasn't supposed to come from. When I remove the port number, it doesn't know which port to hit. It should be hitting 8080 by default, but I'm getting another error.

To date, nobody has solved this problem. I've built apps without having this come up before and everyone I've asked at work seems to think I should just use spring forms. I'd ideally like to actually solve the problem instead of just finding work arounds.

ContentLicense: CC BY-SA 3.0

Body:
Solved

I have been working on this program since 07:00. This has been driving me crazy. I have written multiple full stack web apps and have not had this problem.

Basically I have a form in html that allows a user to input data. Whenever the submit button is clicked, it sends that data to a collection in mongoDB. I have tested this in postman and it works. However, when I run the program through a webbrowser, I get this error:

XMLHttpRequest cannot load http://localhost:8080/articles/addArticle. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404.

I tried installing CORS and configuring the endpoint

I tried going into the javascript file and changing the

This is my JavaScript file

alert('JS is linked to page!');

function Article(id = 1, title = "", authors="", content = "", genre = "", date = 1497484623) {
    console.log("JavaScript file loaded successfully");
    var self = this;
    self.Id = id;
    self.Title = title;
    self.Authors = authors;
    self.Content = content;
    self.Genre = genre;
    self.Date = date;
    self.Save = function() {
        var settings = {
            url: 'http://localhost:8080/articles/addArticle',
            method: 'POST',
            dataType: "json",
              beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json");
            }
        };
        var myData = {
            "Id" : self.Id,
            "Title": self.Title,
            "Authors": self.Authors,
            "Content": self.Content,
            "Genre": self.Genre,
            "Date": self.Date
        };
        settings.data = myData;

        $.ajax(settings).done(function(article) {
         var myArticle = new Article(article.Id, article.Title, article.Authors,
                article.Content, article.Genre, article.Date);
        });
    };
}

function addArticle(Article) {
    alert('addArticle Activated');
    var settings = {
        url: 'http://localhost:8080/articles/addArticle',
        method: 'POST',
        dataType: "json",
          beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json");
            }
    };
    var myData = {
        "Title": Article.Title,
        "Authors" : Article.Authors,
        "Content": Article.Content,
        "Genre" : Article.Genre,
        "Date": Article.Date
    };
    settings.data = myData;

    $.ajax(settings).done(function(Article) {
        var myArticle = new Article(article.Id, article.Title, article.Authors, article.Content,
            article.Genre, article.Date);
        console.log("Article Created");
    });
}

$(document).ready(function() {

    $(document).on("submit", "#add-article", function(e) {
        e.preventDefault();
            alert('submit Activated');
        var title, authors, genre, content;
        title = $("#Title").val();
        director = $("#Authors").val();
        rating = $("#Genre").val();
        notes = $("#Content").val();
        var myArticle = new Article(0, title, authors, genre, content, 1497484623);
        alert(myArticle.Title);
        addArticle(myArticle);
        $("#add-article")[0].reset();
        $("#title").focus();

    });

});

/*function CreateSuccessRow(Article) {
    var successDataRow = `
${Article.Title}
                ${Article.Authors}
                ${Article.Genre}

Due to popular demand, this is the server-side code:

package com.stereoscopics.app.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.stereoscopics.app.models.Article;
import com.stereoscopics.app.repo.ArticleRepo;

@RestController
@RequestMapping("/articles")
public class ArticleController {

private ArticleRepo articleRepo;

@Autowired
public ArticleController(ArticleRepo articleRepo) {
    this.articleRepo = articleRepo;
}

@RequestMapping(value = "/findall", method = RequestMethod.GET)
@ResponseBody
public List
 findall() {
    return articleRepo.findAll();
}

@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle) {
    articleRepo.save(newArticle);
    return newArticle;
}

}

I have no idea how to fix this. Please help.

UPDATE

This still isn't working. I've updated the code as per some suggestions and I'm either doing it wrong or it's incorrect. The changes are shown below:

  @RestController
  @RequestMapping("/articles")
  public class ArticleController {

private ArticleRepo articleRepo;

@Autowired
public ArticleController(ArticleRepo articleRepo) {
    this.articleRepo = articleRepo;
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");
}

@RequestMapping(value = "/findall", method = RequestMethod.GET)
@ResponseBody
public List
 findall() {
    return articleRepo.findAll();
}

@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle, final
HttpServletResponse response) {
    response.addHeader("Access-Control-Allow-Origin", "*");
    articleRepo.save(newArticle);
    return newArticle;
  }
}

THIS IS NOT SOLVED YET


问:
Undefined reference to 'Class::StaticStructMember'
This code is meant to help in profiling game code - and I can't seem to get my head around why it isn't working. I'm getting the following error message: undefined reference to `ProfileSample::profileSamples', and another for each of the points at which I've used its members.

```<code>#ifndef PROFILER_HPP_
#define PROFILER_HPP_

#define MAXIMUM_PROFILE_SAMPLES 16

class ProfileSample {
private:
    int sampleIndex, parentIndex;
    static int previousSampleIndex;

    inline float getTime(void) {
        return ((float)SDL_GetTicks()) / 1000.0f;
    }

    static struct profileSamples {
        float start, duration;
        char *name;
    } profileSamples[MAXIMUM_PROFILE_SAMPLES];
public:
    ProfileSample(const char *name) {
        sampleIndex = 0;
        while(profileSamples[sampleIndex].name != NULL)
            sampleIndex ++;

        parentIndex = (sampleIndex > 1) ? previousSampleIndex : -1;
        previousSampleIndex = sampleIndex;
        profileSamples[sampleIndex].name = (char *)name;
        profileSamples[sampleIndex].start = getTime();
    }

    ~ProfileSample(void) {
        float end = getTime();
        profileSamples[sampleIndex].duration = (end - profileSamples[sampleIndex].start);
        if(parentIndex >= 0)
            profileSamples[parentIndex].start -= profileSamples[sampleIndex].duration;
        if(sampleIndex == 0)
            output();
    }

    static void output(void) {
        for(int i = 1; i < MAXIMUM_PROFILE_SAMPLES; i ++) {
            printf("\nName: %s"
                    "\nDuration: %f"
                    "\nOverall percentage: %f",
                    profileSamples[i].name,
                    profileSamples[i].duration,
                    (profileSamples[0].duration / 100) * profileSamples[i].duration);
        }
    }
};

#endif /* PROFILER_HPP_ */
</code>```

Can anybody explain what I'm missing here? Go easy, I've only just left C for C++

答:
```<code> static struct profileSamples {
        float start, duration;
        char *name;
    } profileSamples[MAXIMUM_PROFILE_SAMPLES];
</code>```

You have just declared this static structure.
You haven't actually initialised it.

If you add

```<code>    struct ProfileSample::profileSamples  ProfileSample::profileSamples[16] = {};
int ProfileSample::previousSampleIndex = 1;
</code>```

After the class declaration it will actually fix the issue.

You can think about it as a 2nd step, which is filling the memory with actual data. The first is just describing that some memory will be used and what interpretation data will have.

Hope that this, combined with issue marked in comments will help you understand what is going on.

Body:
This code is meant to help in profiling game code - and I can't seem to get my head around why it isn't working. I'm getting the following error message: undefined reference to `ProfileSample::profileSamples', and another for each of the points at which I've used its members.

#ifndef PROFILER_HPP_
#define PROFILER_HPP_

#define MAXIMUM_PROFILE_SAMPLES 16

class ProfileSample {
private:
    int sampleIndex, parentIndex;
    static int previousSampleIndex;

    inline float getTime(void) {
        return ((float)SDL_GetTicks()) / 1000.0f;
    }

    static struct profileSamples {
        float start, duration;
        char *name;
    } profileSamples[MAXIMUM_PROFILE_SAMPLES];
public:
    ProfileSample(const char *name) {
        sampleIndex = 0;
        while(profileSamples[sampleIndex].name != NULL)
            sampleIndex ++;

        parentIndex = (sampleIndex > 1) ? previousSampleIndex : -1;
        previousSampleIndex = sampleIndex;
        profileSamples[sampleIndex].name = (char *)name;
        profileSamples[sampleIndex].start = getTime();
    }

    ~ProfileSample(void) {
        float end = getTime();
        profileSamples[sampleIndex].duration = (end - profileSamples[sampleIndex].start);
        if(parentIndex >= 0)
            profileSamples[parentIndex].start -= profileSamples[sampleIndex].duration;
        if(sampleIndex == 0)
            output();
    }

    static void output(void) {
        for(int i = 1; i < MAXIMUM_PROFILE_SAMPLES; i ++) {
            printf("\nName: %s"
                    "\nDuration: %f"
                    "\nOverall percentage: %f",
                    profileSamples[i].name,
                    profileSamples[i].duration,
                    (profileSamples[0].duration / 100) * profileSamples[i].duration);
        }
    }
};

#endif /* PROFILER_HPP_ */

Can anybody explain what I'm missing here? Go easy, I've only just left C for C++

Body:
 static struct profileSamples {
        float start, duration;
        char *name;
    } profileSamples[MAXIMUM_PROFILE_SAMPLES];

You have just declared this static structure.
You haven't actually initialised it.

If you add

    struct ProfileSample::profileSamples  ProfileSample::profileSamples[16] = {};
int ProfileSample::previousSampleIndex = 1;

After the class declaration it will actually fix the issue.

You can think about it as a 2nd step, which is filling the memory with actual data. The first is just describing that some memory will be used and what interpretation data will have.

Hope that this, combined with issue marked in comments will help you understand what is going on.


问:
How do I change the code convention in Eclipse
I like to use curly brackets in this fashion

```<code>void hello()
{
    code();
}
</code>```

When I press Ctrl + Shift + F in Eclipse it changes everything to

```<code>void hello(){
    code();
}
</code>```

答:
In Eclipse, go to
Windows -> Preference -> Java -> Formatter.
In Active Profile drop down box, select any profile, click Edit on right of it.
In Profile Dialog box opened, you can change a lot of things like Indentation, New Line, Braces, White Spaces etc.
Alternatively, if your profile is altogether different than standard one, Create a new active profile and then edit it accordingly.

:)

Body:
I like to use curly brackets in this fashion

void hello()
{
    code();
}

When I press Ctrl + Shift + F in Eclipse it changes everything to

void hello(){
    code();
}

ContentLicense: CC BY-SA 2.5


问:
Can the compiler exploit empty base optimisation if the class contains a member of the base class?
Consider

```<code>struct base {};
struct child : base {};
</code>```

It's well-known that sizeof(child) can be 1 by application of the empty base optimisation.

Now however, consider

```<code>struct base {};
struct child : base {base b;};
</code>```

Can the compiler apply the empty base optimisation now, or must sizeof(child) be at least 2?

Reference: http://en.cppreference.com/w/cpp/language/ebo

答:
The rule is that sub-objects of the same type cannot be at the same address. You have 2 X sub-objects here, hence each one must be at a different address.

Objects of the same type cannot share the same address because the identity of an object in C++ is its address. If multiples objects of the same type share the same address they are indistinguishable. And this is why the minimum complete object size is 1, so that each object in an array has a distinct address. See "§ The C++ object model [intro.object]":

An object is a region of storage.

...

Objects can contain other objects, called subobjects. A subobject can be a member subobject (9.2), a base class subobject (Clause 10), or an array element. An object that is not a subobject of any other object is
  called a complete object.

...

Unless it is a bit-field (9.6), a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class subobjects may have zero size.

...

Unless an object is a bit-field or a base class subobject of zero size, the address of that object is the address of the first byte it occupies. Two objects that are not bit-fields may have the same address if one is a subobject of the other, or if at least one is a base class subobject of zero size and they are of different types; otherwise, they shall have distinct addresses.

This is why, for example, boost::noncopyable can increase a class size if one inherits it more than once unwittingly indirectly through empty base classes. E.g. in:

```<code>struct A : boost::noncopyable {};
struct B : boost::noncopyable {};
struct C : boost::noncopyable {};
struct D : A, B, C {};
</code>```

sizeof(D) == 3 because there are three distinct boost::noncopyable sub-subjects. If derivation from boost::noncopyable is dropped, then sizeof(D) == 1.

Body:
Consider

struct base {};
struct child : base {};

It's well-known that sizeof(child) can be 1 by application of the empty base optimisation.

Now however, consider

struct base {};
struct child : base {base b;};

Can the compiler apply the empty base optimisation now, or must sizeof(child) be at least 2?

Reference: http://en.cppreference.com/w/cpp/language/ebo

Body:
The rule is that sub-objects of the same type cannot be at the same address. You have 2 X sub-objects here, hence each one must be at a different address.

Objects of the same type cannot share the same address because the identity of an object in C++ is its address. If multiples objects of the same type share the same address they are indistinguishable. And this is why the minimum complete object size is 1, so that each object in an array has a distinct address. See "§ The C++ object model [intro.object]":

An object is a region of storage.

...

Objects can contain other objects, called subobjects. A subobject can be a member subobject (9.2), a base class subobject (Clause 10), or an array element. An object that is not a subobject of any other object is
  called a complete object.

...

Unless it is a bit-field (9.6), a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class subobjects may have zero size.

...

Unless an object is a bit-field or a base class subobject of zero size, the address of that object is the address of the first byte it occupies. Two objects that are not bit-fields may have the same address if one is a subobject of the other, or if at least one is a base class subobject of zero size and they are of different types; otherwise, they shall have distinct addresses.

This is why, for example, boost::noncopyable can increase a class size if one inherits it more than once unwittingly indirectly through empty base classes. E.g. in:

struct A : boost::noncopyable {};
struct B : boost::noncopyable {};
struct C : boost::noncopyable {};
struct D : A, B, C {};

sizeof(D) == 3 because there are three distinct boost::noncopyable sub-subjects. If derivation from boost::noncopyable is dropped, then sizeof(D) == 1.


问:
No return after executing passwd command using ssh in script
I have one script which reads hosts IP from /etc/hosts file, do ssh and update the passwords there for the given user. However, the script is closed after setting password for the first host and not able to set password for rest of the hosts. Please find below files-

/etc/hosts file-

172.x.x.x  host1

    172.x.x.x  host2

    172.x.x.x  host3

Script I am using is as-

```<code>key=$1
user=$2
password=$3
filename='/etc/hosts'
while IFS= read -r line; do
   IFS=' ' read -r -a array <<< $line
   ssh -i $key centos@${array[0]} "echo "$password" | sudo passwd $user --stdin"
done <$filename
</code>```

Script is simple. but it is getting closed after setting password for host1 from file. Does anyone has any idea, what I am missing?

答:
Using awk would help overcome any issues:

```<code>awk -v key=$1 -v usa=$2 -v pass=$3 '{system("ssh -i "key" centos@"$1" \"echo "pass" | sudo passwd "usa" --stdin\"")}' $filename
</code>```

Assign you passed parameters as awk variables with -v and then use these to construct the ssh command to be executed with awk's system function

Body:
I have one script which reads hosts IP from /etc/hosts file, do ssh and update the passwords there for the given user. However, the script is closed after setting password for the first host and not able to set password for rest of the hosts. Please find below files-

/etc/hosts file-

172.x.x.x  host1

    172.x.x.x  host2

    172.x.x.x  host3

Script I am using is as-

key=$1
user=$2
password=$3
filename='/etc/hosts'
while IFS= read -r line; do
   IFS=' ' read -r -a array <<< $line
   ssh -i $key centos@${array[0]} "echo "$password" | sudo passwd $user --stdin"
done <$filename

Script is simple. but it is getting closed after setting password for host1 from file. Does anyone has any idea, what I am missing?

Body:
Using awk would help overcome any issues:

awk -v key=$1 -v usa=$2 -v pass=$3 '{system("ssh -i "key" centos@"$1" \"echo "pass" | sudo passwd "usa" --stdin\"")}' $filename

Assign you passed parameters as awk variables with -v and then use these to construct the ssh command to be executed with awk's system function


问:
Python: for loops: using an index from a list and another index from another list
I would like to loop as something like:

```<code>for j in range(1,4) and for k in ['one', 'two', 'three']:
               print(str(j) + ' is written ' + k)
</code>```

I tried with and but it didn't work. How does someone get this effect?

And what would happen in the case that the two lists have different lengths? How could I still iterate through both of them?

答:
You can use zip

```<code>for j, k in zip(range(1,4), ['one', 'two', 'three']):
    print('{} is written {}'.format(j, k))

1 is written one
2 is written two
3 is written three
</code>```

If one is longer than the other, you could consider using itertools.zip_longest

Body:
I would like to loop as something like:

for j in range(1,4) and for k in ['one', 'two', 'three']:
               print(str(j) + ' is written ' + k)

I tried with and but it didn't work. How does someone get this effect?

And what would happen in the case that the two lists have different lengths? How could I still iterate through both of them?

Body:
You can use zip

for j, k in zip(range(1,4), ['one', 'two', 'three']):
    print('{} is written {}'.format(j, k))

1 is written one
2 is written two
3 is written three

If one is longer than the other, you could consider using itertools.zip_longest


问:
Case sensitive sybase query: Invalid column name
Details:

2 databases: sybase version 15 and sybase version 16

1 table each (identical): AuthRole with columns id, rolename and description

Tried both jTDS and jconn drivers

Query:

```<code>SELECT t1.roleName FROM AuthRole t1;
</code>```

Results:

Sybase 15: rows returned successfully. 'roleName' could be upper, lower or a mix of case, i.e. not case sensitive

Sybase 16: Invalid column name 'roleName'. It will only work with 'rolename' which is the exact case of the column. Anyone know why this would happen and how to resolve it?

答:
If on ASE 15 both queries work - with "rolename" and "roleName" - that means the the sort order in this database is case insensitive.

If on ASE 16 "rolename" is different than "roleName" - that means the the sort order in this database is case sensitive.

You can check this by querying:

```<code>if "a" = "A" print "Case insensitive" else print "Case sensitive"
</code>```

This setting is set and static for the whole server (and for all the databases that the server contains), but can be changed. Of course changing the sort order is a time consuming process, as it requires to rebuild all indexes based on character types.

You can check the server sortorder setting:

```<code>exec sp_configure 'sortorder id'
</code>```

The information about sort order should be visible in the ASE errorlog when the database server starts:

```<code>00:0002:00000:00002:2017/07/04 16:49:26.35 server  ASE's default unicode sort order is 'binary'.
00:0002:00000:00002:2017/07/04 16:49:26.35 server  ASE's default sort order is:
00:0002:00000:00002:2017/07/04 16:49:26.35 server   'bin_iso_1' (ID = 50)
00:0002:00000:00002:2017/07/04 16:49:26.35 server  on top of default character set:
00:0002:00000:00002:2017/07/04 16:49:26.35 server   'iso_1' (ID = 1).
</code>```

In my example the sort order is binary - which is case sensitive.

Information how to change the sort order for the server is in the ASE manual. Basicaly to change the sort order you need to:

add the new sort order using the charset program,

change the config parameter 'sortorder id'

reboot the ASE server (the server boots, rebuilds the disk devices and then it shuts down)

reboot the ASE server again

indexes that are build on character types are marked as invalid and need to be rebuild

Body:
Details:

2 databases: sybase version 15 and sybase version 16

1 table each (identical): AuthRole with columns id, rolename and description

Tried both jTDS and jconn drivers

Query:

SELECT t1.roleName FROM AuthRole t1;

Results:

Sybase 15: rows returned successfully. 'roleName' could be upper, lower or a mix of case, i.e. not case sensitive

Sybase 16: Invalid column name 'roleName'. It will only work with 'rolename' which is the exact case of the column. Anyone know why this would happen and how to resolve it?

Body:
If on ASE 15 both queries work - with "rolename" and "roleName" - that means the the sort order in this database is case insensitive.

If on ASE 16 "rolename" is different than "roleName" - that means the the sort order in this database is case sensitive.

You can check this by querying:

if "a" = "A" print "Case insensitive" else print "Case sensitive"

This setting is set and static for the whole server (and for all the databases that the server contains), but can be changed. Of course changing the sort order is a time consuming process, as it requires to rebuild all indexes based on character types.

You can check the server sortorder setting:

exec sp_configure 'sortorder id'

The information about sort order should be visible in the ASE errorlog when the database server starts:

00:0002:00000:00002:2017/07/04 16:49:26.35 server  ASE's default unicode sort order is 'binary'.
00:0002:00000:00002:2017/07/04 16:49:26.35 server  ASE's default sort order is:
00:0002:00000:00002:2017/07/04 16:49:26.35 server   'bin_iso_1' (ID = 50)
00:0002:00000:00002:2017/07/04 16:49:26.35 server  on top of default character set:
00:0002:00000:00002:2017/07/04 16:49:26.35 server   'iso_1' (ID = 1).

In my example the sort order is binary - which is case sensitive.

Information how to change the sort order for the server is in the ASE manual. Basicaly to change the sort order you need to:

add the new sort order using the charset program,

change the config parameter 'sortorder id'

reboot the ASE server (the server boots, rebuilds the disk devices and then it shuts down)

reboot the ASE server again

indexes that are build on character types are marked as invalid and need to be rebuild


问:
Drawing on a qwidget while playing videos
I have a class A that inherits from a class that inherits from QWidget. My class contains a media player and a QVideoWidget. I want my object A to draw a small rectangle for a few milliseconds every time a new video from the play list starts playing, on the part of the widget that isn't the video widget.
So, I've connected my slot

```<code>connect(player, &QMediaPlayer::currentMediaChanged,this,&videoDisplay::drawRect);
</code>```

but I can't manage to get the drawRect function right. Tried using QPainter but it gave me errors

```<code>QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1
</code>```

any advice?

Thanks

答:
Painting in Qt should generally only be performed as the result of an update request.

Rather than try to draw directly you could use a flag or similar to signify a new item has started from the playlist...

```<code>bool m_new_video;
</code>```

Then just use a lambda as the slot and have it set the flag and request an update...

```<code>connect(player, &QMediaPlayer::currentMediaChanged,
        [this]()
        {
          m_new_video = true;
          update();
        });
</code>```

Your videoDisplay::paintEvent implementation can then draw whatever it has to based on the value of m_new_video.

Body:
I have a class A that inherits from a class that inherits from QWidget. My class contains a media player and a QVideoWidget. I want my object A to draw a small rectangle for a few milliseconds every time a new video from the play list starts playing, on the part of the widget that isn't the video widget.
So, I've connected my slot

connect(player, &QMediaPlayer::currentMediaChanged,this,&videoDisplay::drawRect);

but I can't manage to get the drawRect function right. Tried using QPainter but it gave me errors

QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1

any advice?

Thanks

Body:
Painting in Qt should generally only be performed as the result of an update request.

Rather than try to draw directly you could use a flag or similar to signify a new item has started from the playlist...

bool m_new_video;

Then just use a lambda as the slot and have it set the flag and request an update...

connect(player, &QMediaPlayer::currentMediaChanged,
        [this]()
        {
          m_new_video = true;
          update();
        });

Your videoDisplay::paintEvent implementation can then draw whatever it has to based on the value of m_new_video.


问:
scala timing problems with add stuff to a seq
I've got a question that concerns scoping in scala. I have a function like this:

```<code>def getElements(id: Int): Seq[Element] = {
    var test = ""
    dto.getElementIds(id).map {
      elementIds => {
        test += " hello "
        elementIds.foreach(elementId => dto.getElement(elementId).map {
          case Some(element) => test += " hi "
                println("ThirdPrint: " + test)
        })
        println("SecondPrint: " + test)
      }
    }
    println("FirstPrint: " + test)
}
</code>```

Lets say "elementsIds" has a lenght of 2.
The console says:
FirstPrint:
SecondPrint: hello
ThirdPrint: hello hi
ThirdPrint: hello hi hi
Why is scala doing that? I would assume that third print is executed first. By the time I get to the "FirstPrint" the "hi"'s are gone. Why is the last line of code executed first?
I'm working with slick and Futures, does this have something to do with it? Thanks!

UPDATE

Thanks, works fine.
Is it possible to return a seq instead? Like this:

```<code> def getElements(id: Int): Future[Seq[Element]] = {
    var mySequence: Seq[Element] = Seq()
    val elementsIds: Future[Seq[Int]] = dto.getElementIds(id)
    var test = ""
    val elementsF = elementsIds.flatMap {
      elementIds => {
        test += " hello "
        val idsAsElements: Seq[Future[Element]] = elementIds.map(elementId => dto.getElement(elementId).collect {
          case Some(element) => mySequence = mySequence :+ element
        })
        val idsAsElementsF: Future[Seq[Element]] = Future.sequence(idsAsElements)
        idsAsElementsF.onComplete(_ => println("SecondPrint: " + test))
        idsAsElementsF
      }
    }
    elementsF.onComplete(_ => println("FirstPrint: " + test))
    elementsF
  }
</code>```

Is it possible to return "mySequence" whenever idsAsElements is "onComplete"?

答:
Yes, that's not a good solution. You should avoid blocking in your code, except, maybe at the highest possible level (main method). Also, mutable state is bad, especially, when combined with concurrency (futures).

Your function should return a Future. Something like this will work (I am not sure if I guess the intent of your code correctly - your function was declared to return Seq[Element], but written to return a Unit ... I assume, that what you really wanted to return was the result of getElement calls for every id):

```<code>def getElements(id: Int): Future[Seq[Element]] = dto
   .getElementIds(id)
   .map { ids => ids.map(dto.getElement) }
   .flatMap(Future.sequence)
   .map(_.flatten)
</code>```

I removed your printouts, because wasn't sure what was the purpose they serve (since the calls to dto.getElement are also happening in parallel, it is not obvious where and in which order you want those strings printed).

You could simulate your "expected output", by adding another transformation at the end for example:

```<code>  .andThen { case Success(results) =>
     val str = results.foldLeft("hello") { case (a,b) =>
        println("ThirdPrint: " + a + " hi")
        a + " hi"
     }
     println("SecondPrint: " + str)
     println("FirstPrint: " + str
  }
</code>```

Body:
I've got a question that concerns scoping in scala. I have a function like this:

def getElements(id: Int): Seq[Element] = {
    var test = ""
    dto.getElementIds(id).map {
      elementIds => {
        test += " hello "
        elementIds.foreach(elementId => dto.getElement(elementId).map {
          case Some(element) => test += " hi "
                println("ThirdPrint: " + test)
        })
        println("SecondPrint: " + test)
      }
    }
    println("FirstPrint: " + test)
}

Lets say "elementsIds" has a lenght of 2.
The console says:
FirstPrint:
SecondPrint: hello
ThirdPrint: hello hi
ThirdPrint: hello hi hi
Why is scala doing that? I would assume that third print is executed first. By the time I get to the "FirstPrint" the "hi"'s are gone. Why is the last line of code executed first?
I'm working with slick and Futures, does this have something to do with it? Thanks!

UPDATE

Thanks, works fine.
Is it possible to return a seq instead? Like this:

 def getElements(id: Int): Future[Seq[Element]] = {
    var mySequence: Seq[Element] = Seq()
    val elementsIds: Future[Seq[Int]] = dto.getElementIds(id)
    var test = ""
    val elementsF = elementsIds.flatMap {
      elementIds => {
        test += " hello "
        val idsAsElements: Seq[Future[Element]] = elementIds.map(elementId => dto.getElement(elementId).collect {
          case Some(element) => mySequence = mySequence :+ element
        })
        val idsAsElementsF: Future[Seq[Element]] = Future.sequence(idsAsElements)
        idsAsElementsF.onComplete(_ => println("SecondPrint: " + test))
        idsAsElementsF
      }
    }
    elementsF.onComplete(_ => println("FirstPrint: " + test))
    elementsF
  }

Is it possible to return "mySequence" whenever idsAsElements is "onComplete"?

Body:
Yes, that's not a good solution. You should avoid blocking in your code, except, maybe at the highest possible level (main method). Also, mutable state is bad, especially, when combined with concurrency (futures).

Your function should return a Future. Something like this will work (I am not sure if I guess the intent of your code correctly - your function was declared to return Seq[Element], but written to return a Unit ... I assume, that what you really wanted to return was the result of getElement calls for every id):

def getElements(id: Int): Future[Seq[Element]] = dto
   .getElementIds(id)
   .map { ids => ids.map(dto.getElement) }
   .flatMap(Future.sequence)
   .map(_.flatten)

I removed your printouts, because wasn't sure what was the purpose they serve (since the calls to dto.getElement are also happening in parallel, it is not obvious where and in which order you want those strings printed).

You could simulate your "expected output", by adding another transformation at the end for example:

  .andThen { case Success(results) =>
     val str = results.foldLeft("hello") { case (a,b) =>
        println("ThirdPrint: " + a + " hi")
        a + " hi"
     }
     println("SecondPrint: " + str)
     println("FirstPrint: " + str
  }


问:
How to align a Switch to the right? [Android]
I have a layout with switches. I want the text to be on the left and the actual switch to be on the right.
How can i do it? I know it's possible because they are like this in the phone settings.

Current situation:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="15dp"
android:dividerPadding="5dp"
android:orientation="vertical"
android:padding="15dp"
android:scrollbars="vertical"
android:showDividers="middle" >

<Switch
     android:paddingBottom="15dp"
    android:id="@+id/switch_gprs"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="false"
    android:gravity="center_vertical|fill|end"
    android:text="@string/gprs" />

<View
android:paddingTop="15dp"
 android:paddingBottom="15dp"
android:layout_height="1dp"
android:layout_width="match_parent"
android:background="@color/holo_black" />

<Switch
    android:paddingTop="15dp"
     android:paddingBottom="15dp"
    android:id="@+id/switch_voicemail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/voicemail" />

<RelativeLayout
    android:paddingTop="15dp"
     android:paddingBottom="15dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/number" />

    <TextView
        android:id="@+id/voicemail_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="TextView" />

</RelativeLayout>

<RelativeLayout
    android:paddingTop="15dp"
     android:paddingBottom="15dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/email" />

    <TextView
        android:id="@+id/voicemail_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="TextView" />

</RelativeLayout>

<TextView
    android:paddingTop="15dp"
    android:paddingBottom="15dp"
    android:id="@+id/textView4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/voicemail_download" />

 <View
android:paddingTop="15dp"
 android:paddingBottom="15dp"
android:layout_height="1dp"
android:layout_width="match_parent"
android:background="@color/holo_black" />

<Switch
    android:paddingTop="15dp"
     android:paddingBottom="15dp"
    android:id="@+id/switch1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/redirect" />

<RelativeLayout
    android:paddingTop="15dp"
     android:paddingBottom="15dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/sim_number" />

    <TextView
        android:id="@+id/redirect_sim"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="TextView" />

</RelativeLayout>

<RelativeLayout
    android:paddingTop="15dp"
     android:paddingBottom="15dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/redirect_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/redirect_number" />

</RelativeLayout>
</code>```

答:
Use linear layout and put spacing between TextView and Switch. Something like this:</p>

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/mexican"
        android:id="@+id/textView" />
    <Space
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1" >
    </Space>
    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/switch1"
        android:gravity="center"
       />

</LinearLayout>
</code>```

Body:
I have a layout with switches. I want the text to be on the left and the actual switch to be on the right.
How can i do it? I know it's possible because they are like this in the phone settings.

Current situation:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="15dp"
android:dividerPadding="5dp"
android:orientation="vertical"
android:padding="15dp"
android:scrollbars="vertical"
android:showDividers="middle" >

<Switch
     android:paddingBottom="15dp"
    android:id="@+id/switch_gprs"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="false"
    android:gravity="center_vertical|fill|end"
    android:text="@string/gprs" />

<View
android:paddingTop="15dp"
 android:paddingBottom="15dp"
android:layout_height="1dp"
android:layout_width="match_parent"
android:background="@color/holo_black" />

<Switch
    android:paddingTop="15dp"
     android:paddingBottom="15dp"
    android:id="@+id/switch_voicemail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/voicemail" />

<RelativeLayout
    android:paddingTop="15dp"
     android:paddingBottom="15dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/number" />

    <TextView
        android:id="@+id/voicemail_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="TextView" />

</RelativeLayout>

<RelativeLayout
    android:paddingTop="15dp"
     android:paddingBottom="15dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/email" />

    <TextView
        android:id="@+id/voicemail_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="TextView" />

</RelativeLayout>

<TextView
    android:paddingTop="15dp"
    android:paddingBottom="15dp"
    android:id="@+id/textView4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/voicemail_download" />

 <View
android:paddingTop="15dp"
 android:paddingBottom="15dp"
android:layout_height="1dp"
android:layout_width="match_parent"
android:background="@color/holo_black" />

<Switch
    android:paddingTop="15dp"
     android:paddingBottom="15dp"
    android:id="@+id/switch1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/redirect" />

<RelativeLayout
    android:paddingTop="15dp"
     android:paddingBottom="15dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/sim_number" />

    <TextView
        android:id="@+id/redirect_sim"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="TextView" />

</RelativeLayout>

<RelativeLayout
    android:paddingTop="15dp"
     android:paddingBottom="15dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/redirect_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/redirect_number" />

</RelativeLayout>

Body:
Use linear layout and put spacing between TextView and Switch. Something like this:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/mexican"
        android:id="@+id/textView" />
    <Space
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1" >
    </Space>
    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/switch1"
        android:gravity="center"
       />

</LinearLayout>


问:
Search word from text file
I have maybe pretty easy question because I'm new but I did not find any answer for it from google. Idea is search some words from the text file.

Here is the code:

```<code>private void button6_Click(object sender, EventArgs e)
{
    DialogResult result = openFileDialog2.ShowDialog();
    if (result == DialogResult.OK)
    {
        string file = openFileDialog2.FileName;
        try
        {
            string text = File.ReadAllText(file);
        }
        catch (IOException)
        {
        }
    }
}

private void button5_Click(object sender, EventArgs e)
{
    //Search from selected .txt file like: ("a"), ("b"), ("c")
}
</code>```

My English is bad so hopefully you get it and thanks for even trying to help me :)!

答:
It's pretty easy. You didn't take the time to search.

```<code>if(text.Contains("THE WORD YOU ARE SEARCHING FOR"))
{
    ///TAKE ACTION
}
</code>```

Another Idea is to Split the text files into words If the text file is not huge and iterate through words. this can help you to find the previous and next words to the searched one.

Title: Search word from text file

Body:
I have maybe pretty easy question because I'm new but I did not find any answer for it from google. Idea is search some words from the text file.

Here is the code:

private void button6_Click(object sender, EventArgs e)
{
    DialogResult result = openFileDialog2.ShowDialog();
    if (result == DialogResult.OK)
    {
        string file = openFileDialog2.FileName;
        try
        {
            string text = File.ReadAllText(file);
        }
        catch (IOException)
        {
        }
    }
}

private void button5_Click(object sender, EventArgs e)
{
    //Search from selected .txt file like: ("a"), ("b"), ("c")
}

My English is bad so hopefully you get it and thanks for even trying to help me :)!

Body:
It's pretty easy. You didn't take the time to search.

if(text.Contains("THE WORD YOU ARE SEARCHING FOR"))
{
    ///TAKE ACTION
}

Another Idea is to Split the text files into words If the text file is not huge and iterate through words. this can help you to find the previous and next words to the searched one.


问:
How to edit default page in wordpress?(index page)
How to edit default page in WordPress site?(index page).
I am inspecting the current page, and find that the code is in index page.
But there is no way to find where is the file located.
The site hosted on hostinger. Then I am trying to edit other pages other than default page? Is there is a way to find the index page?</p>

答:
If you would like only edit some part of the code you can use this url

your_address/wp-admin/theme-editor.php

or in your dashboard as admin user:
Appearance -> Editor


问:
If...Else Statement always diverts to "else".
I am trying to run a "presence check" on a radio group, to determine what happens if 1 of 2 radiobuttons are selected in the group (if statement), if the other of the 2 radiobuttons is selected instead (else if statement) or if neither are selected (else statement). The code for this is as follows:

```<code>if (rdbAM.isSelected()) {
        strTime = rdbAM.getText().toString();
    } else if(rdbPM.isSelected()){
        strTime = rdbPM.getText().toString();
    } else {
        AlertDialog.Builder WrongDateFormat = new AlertDialog.Builder(this);
        WrongDateFormat.setMessage("Please Select AM or PM");
        WrongDateFormat.setNeutralButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        AlertDialog alertWrongDateFormat = WrongDateFormat.create();
        alertWrongDateFormat.show();
        return;
    }
</code>```

So basically, what this should do is either, set the variable called "strTime" to whatever the text of the selected radiobutton in the radiogroup is, or display an error message if neither are selected. It is instead always displaying this error message, regardless of whether either radiobutton is selected or not:

(As you can see above, the "AM" radiobutton is selected, but error is still being displayed).

Any suggestions as to why this may be would be appreciated. Please note that I am relatively new to Android development, so if it is clearly something obvious then I apologise, but I have been trying to get my head round this for several days now! If you would like to see any further code, please let me know and I'll be happy to provide it, but am trying to keep it as private as possible, so didn't want to post everything in the initial post if not necessary. Thanks in advance.

答: Instead of using isSelected() go for isChecked().

Body:
I am trying to run a "presence check" on a radio group, to determine what happens if 1 of 2 radiobuttons are selected in the group (if statement), if the other of the 2 radiobuttons is selected instead (else if statement) or if neither are selected (else statement). The code for this is as follows:

if (rdbAM.isSelected()) {
        strTime = rdbAM.getText().toString();
    } else if(rdbPM.isSelected()){
        strTime = rdbPM.getText().toString();
    } else {
        AlertDialog.Builder WrongDateFormat = new AlertDialog.Builder(this);
        WrongDateFormat.setMessage("Please Select AM or PM");
        WrongDateFormat.setNeutralButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        AlertDialog alertWrongDateFormat = WrongDateFormat.create();
        alertWrongDateFormat.show();
        return;
    }

So basically, what this should do is either, set the variable called "strTime" to whatever the text of the selected radiobutton in the radiogroup is, or display an error message if neither are selected. It is instead always displaying this error message, regardless of whether either radiobutton is selected or not:

(As you can see above, the "AM" radiobutton is selected, but error is still being displayed).

Any suggestions as to why this may be would be appreciated. Please note that I am relatively new to Android development, so if it is clearly something obvious then I apologise, but I have been trying to get my head round this for several days now! If you would like to see any further code, please let me know and I'll be happy to provide it, but am trying to keep it as private as possible, so didn't want to post everything in the initial post if not necessary. Thanks in advance.


问:
How to create an array of non-const C strings on the stack without repetitive code in C++03?
I'm writing a unit test for a module that takes an array of mutable C strings in C++03 with getopt. The function argument is char*const[]. I want to create the arguments on the stack inside the function. My current solution is:

```<code>char args_stor[][1024] = {
    "parser",
    "-o",
    "SomeValue"
};
char* args[] = {
    args_stor[0],
    args_stor[1],
    args_stor[2]
};
</code>```

How can I avoid the repetitive part, and if possible, transform it into one statement?

The function declaration is:

```<code>int getopt(int argc, char* const argv[], const char *optstring);
</code>```

Use case is therefore:

```<code>getopt(3, args, ":o:");
</code>```

答:
I would do something like that (I added a parse function to verify the functionality):

```<code>#include <stdio.h>

int parse(int argc, char* argv[], const char *optstring)
{
    printf("optstring = %s\n", optstring);
    printf("argv's:\n");
    for (int i = 0; i < argc; ++i)
        printf("\t%s\n", argv[i]);
    return 0;
}

int main(void)
{
    char args_arr[][1024] = {
            "Hello",
            "how",
            "are",
            "you?"
        };
    char *args[sizeof args_arr / sizeof *args_arr];
    for (size_t i = 0; i < sizeof args / sizeof *args; ++i)
        args[i] = args_arr[i];

    parse(sizeof args / sizeof *args, args, ":o:");
    return 0;
}
</code>```

If you want to add something, you only have to add it to the args_arr declaration. The args array will change accordingly

Body:
I'm writing a unit test for a module that takes an array of mutable C strings in C++03 with getopt. The function argument is char*const[]. I want to create the arguments on the stack inside the function. My current solution is:

char args_stor[][1024] = {
    "parser",
    "-o",
    "SomeValue"
};
char* args[] = {
    args_stor[0],
    args_stor[1],
    args_stor[2]
};

How can I avoid the repetitive part, and if possible, transform it into one statement?

The function declaration is:

int getopt(int argc, char* const argv[], const char *optstring);

Use case is therefore:

getopt(3, args, ":o:");

Body:
I would do something like that (I added a parse function to verify the functionality):

#include <stdio.h>

int parse(int argc, char* argv[], const char *optstring)
{
    printf("optstring = %s\n", optstring);
    printf("argv's:\n");
    for (int i = 0; i < argc; ++i)
        printf("\t%s\n", argv[i]);
    return 0;
}

int main(void)
{
    char args_arr[][1024] = {
            "Hello",
            "how",
            "are",
            "you?"
        };
    char *args[sizeof args_arr / sizeof *args_arr];
    for (size_t i = 0; i < sizeof args / sizeof *args; ++i)
        args[i] = args_arr[i];

    parse(sizeof args / sizeof *args, args, ":o:");
    return 0;
}

If you want to add something, you only have to add it to the args_arr declaration. The args array will change accordingly


答:
You have multiple possiblities to check if a text exists.

With IndexOf you can find the statrt index of a string.

With Contains you can check if a string is in another string

With StartsWith/EndsWith you can check if a string starts/ends with another string.

Just don't forget that text value needs to be in the class context to be visible in another method.

```<code>public class MyClass
{
    private string LoadedText { get; } = string.Empty;

    private void button6_Click(object sender, EventArgs e)
    {
        DialogResult result = openFileDialog2.ShowDialog();
        if (result == DialogResult.OK)
        {
            string file = openFileDialog2.FileName;
            try
            {
                LoadedText = File.ReadAllText(file);
            }
            catch (IOException)
            {
                //TODO: error handling
            }
        }
    }

    private void button5_Click(object sender, EventArgs e)
    {
        // use `LoadedText`
        //Search from selected .txt file like: ("a"), ("b"), ("c")
    }
}
</code>```

Title: Search word from text file

Body:
You have multiple possiblities to check if a text exists.

With IndexOf you can find the statrt index of a string.

With Contains you can check if a string is in another string

With StartsWith/EndsWith you can check if a string starts/ends with another string.

Just don't forget that text value needs to be in the class context to be visible in another method.

public class MyClass
{
    private string LoadedText { get; } = string.Empty;

    private void button6_Click(object sender, EventArgs e)
    {
        DialogResult result = openFileDialog2.ShowDialog();
        if (result == DialogResult.OK)
        {
            string file = openFileDialog2.FileName;
            try
            {
                LoadedText = File.ReadAllText(file);
            }
            catch (IOException)
            {
                //TODO: error handling
            }
        }
    }

    private void button5_Click(object sender, EventArgs e)
    {
        // use `LoadedText`
        //Search from selected .txt file like: ("a"), ("b"), ("c")
    }
}


问:
Lucene: Filtering for documents NOT containing a Term
I have an index whose documents have two fields (actually more like 800 fields but the other fields won't concern us here):

The contents field contains the analyzed/tokenized text of the document. The query string is searched for in this field.

The category field contains the single category identifier of the document. There are about 2500 different categories, and a document may occur in several of them (i.e. a document may have multiple category entries. The results are filtered by this field.

The index contains about 20 mio. documents and is 5 GB in size.

The index is queried with a user-provided query string, plus an optional set of a few categories the user is not interested in. The question is: how can I remove those documents matching not only the query string but also the unwanted categories.

I could use a BooleanQuery with a MUST_NOT clause, i.e. something like this:

```<code>BooleanQuery q = new BooleanQuery();
q.add(contentQuery, BooleanClause.MUST);
for (String unwanted: unwantedCategories) {
    q.add(new TermsQuery(new Term("category", unwanted), BooleanClause.MUST_NOT);
}
</code>```

Is there a way to do this with Lucene filters? Performance is an issue here, and there will only be a few, recurring, variants of unwantedCategories, so a CachingWrapperFilter would probably help a lot. Also, due to the way the Lucene queries are generated in the existing code base, it is difficult to fit this in, whereas an extra Filter could be introduced easily.

In other words, How do I create a Filter based on what terms must _not_ occur in a document?

答:
You can use a QueryWrapperFilter to turn an arbitrary query into a filter. And you can use a CachingWrapperFilter to cache any filter. So something like:</p>

```<code>BooleanQuery bq = new BooleanQuery();
// set up bq
Filter myFilter = new CachingWrapperFilter (
                     new QueryWrapperFilter (bq)
                  );
</code>```

Body:
I have an index whose documents have two fields (actually more like 800 fields but the other fields won't concern us here):

The contents field contains the analyzed/tokenized text of the document. The query string is searched for in this field.

The category field contains the single category identifier of the document. There are about 2500 different categories, and a document may occur in several of them (i.e. a document may have multiple category entries. The results are filtered by this field.

The index contains about 20 mio. documents and is 5 GB in size.

The index is queried with a user-provided query string, plus an optional set of a few categories the user is not interested in. The question is: how can I remove those documents matching not only the query string but also the unwanted categories.

I could use a BooleanQuery with a MUST_NOT clause, i.e. something like this:

BooleanQuery q = new BooleanQuery();
q.add(contentQuery, BooleanClause.MUST);
for (String unwanted: unwantedCategories) {
    q.add(new TermsQuery(new Term("category", unwanted), BooleanClause.MUST_NOT);
}

Is there a way to do this with Lucene filters? Performance is an issue here, and there will only be a few, recurring, variants of unwantedCategories, so a CachingWrapperFilter would probably help a lot. Also, due to the way the Lucene queries are generated in the existing code base, it is difficult to fit this in, whereas an extra Filter could be introduced easily.

In other words, How do I create a Filter based on what terms must _not_ occur in a document?

Body:
You can use a QueryWrapperFilter to turn an arbitrary query into a filter. And you can use a CachingWrapperFilter to cache any filter. So something like:

BooleanQuery bq = new BooleanQuery();
// set up bq
Filter myFilter = new CachingWrapperFilter (
                     new QueryWrapperFilter (bq)
                  );


问:
How to Write HTML Content in PDF file using PDFBox
I want to write HTML content in PDF using PDFBox using JAVA. How can I write it ? Is there any method by which I can add HTML Content ? There are different add methods but not able to add HTML content.</p>

答: There is no html rendering support yet in pdfbox as of 2.0.6. But heard about few commitments on this feature in their future releases.</p>


问:
SEARCH THROUGH ROW FOR SPECIFIC VALUE IN ORACLE
I want to search in Table row with 32 columns, in each of one for specific value and count appearance , is it possible to query entire row without typing every column name in oracle ???</p>

答:
Tested on EMP table, should be available with Oracle DB installation(I guess).

Creates a sql text for searching across all fields.

Assumes you have access to DBA_TAB_COLUMNS, if not try USER_TAB_COLUMNS, if you own the table

%KING% is the search term.

SQL string has a limit of 4000 characters.

OWNER of these tables can be different, since you might have the table in a different schema

Below can be run on SQL Plus or the SQL client of your choice :)

```<code>VARIABLE cur REFCURSOR;

DECLARE
    v_chr VARCHAR2(4000);
    v_chr_tablename VARCHAR2(30) := 'EMP';
    v_chr_searchterm VARCHAR2(100) := 'KING';
BEGIN

    SELECT 'SELECT * FROM ' ||  v_chr_tablename || ' where '
        || RTRIM ( XMLAGG (XMLELEMENT (E, 'TO_CHAR('
        ||column_name
        || ')', ' || ').EXTRACT ( '//text()')
    ORDER BY column_name).getStringVal (), ' || ')
        ||' like ''%' || v_chr_searchterm || '%'''
    INTO v_chr
    FROM DBA_TAB_COLUMNS
    WHERE table_name = v_chr_tablename
    AND owner        = 'APPS';

    OPEN :cur FOR v_chr;

END;
/
print cur;
</code>```

Body:
Tested on EMP table, should be available with Oracle DB installation(I guess).

Creates a sql text for searching across all fields.

Assumes you have access to DBA_TAB_COLUMNS, if not try USER_TAB_COLUMNS, if you own the table

%KING% is the search term.

SQL string has a limit of 4000 characters.

OWNER of these tables can be different, since you might have the table in a different schema

Below can be run on SQL Plus or the SQL client of your choice :)

VARIABLE cur REFCURSOR;

DECLARE
    v_chr VARCHAR2(4000);
    v_chr_tablename VARCHAR2(30) := 'EMP';
    v_chr_searchterm VARCHAR2(100) := 'KING';
BEGIN

    SELECT 'SELECT * FROM ' ||  v_chr_tablename || ' where '
        || RTRIM ( XMLAGG (XMLELEMENT (E, 'TO_CHAR('
        ||column_name
        || ')', ' || ').EXTRACT ( '//text()')
    ORDER BY column_name).getStringVal (), ' || ')
        ||' like ''%' || v_chr_searchterm || '%'''
    INTO v_chr
    FROM DBA_TAB_COLUMNS
    WHERE table_name = v_chr_tablename
    AND owner        = 'APPS';

    OPEN :cur FOR v_chr;

END;
/
print cur;


问:
how to replace two same keys array and make none set keys empty
Let say we have 2 flowing arrays

```<code>$arr1= array('a' => "XL");
$arr2= array('a' => "XLd",'b'=>"CDW");
</code>```

i need to assign $arr1 to $arr2  and make other keys empty whith a builtin function not foreach.

It should looks as bellow:

```<code>array(2) { ['a']=> string(2) "XL" ['b']=> string(0) ""}
</code>```

thanks

答:
This seems fun enough :)

```<code><?php
$arr1= array('a' => "XL");
$arr2= array('a' => "XLd",'b'=>"CDW");

array_walk(
    $arr2,
    function (&$val ,$key) use ($arr1){
        if (isset($arr1[$key])) {
            $val = $arr1[$key];
        } else {
            $val = '';
        }
    }
);

print_r($arr2);
//Array
//(
//[a] => XL
//[b] =>
//)
</code>```

See it here: https://3v4l.org/B7G5p

Body:
Let say we have 2 flowing arrays

$arr1= array('a' => "XL");
$arr2= array('a' => "XLd",'b'=>"CDW");

i need to assign $arr1 to $arr2  and make other keys empty whith a builtin function not foreach.

It should looks as bellow:

array(2) { ['a']=> string(2) "XL" ['b']=> string(0) ""}

thanks

Body:
This seems fun enough :)

<?php
$arr1= array('a' => "XL");
$arr2= array('a' => "XLd",'b'=>"CDW");

array_walk(
    $arr2,
    function (&$val ,$key) use ($arr1){
        if (isset($arr1[$key])) {
            $val = $arr1[$key];
        } else {
            $val = '';
        }
    }
);

print_r($arr2);
//Array
//(
//[a] => XL
//[b] =>
//)

See it here: https://3v4l.org/B7G5p


问:
Asp.net MVC routing for old aspx Url
We used to have some webforms setup that allowed us to edit jobs.  External applications would access them using a URL like this:

```<code>http://server/EditJob.aspx?JobID=1235
</code>```

having replaced the webforms with MVC the new URL is

```<code>http://server/MVC/Jobs/Edit/1235
</code>```

I would like calls to the former Url  to be routed to the new URl as changing the clients is not possible.  How can I achieve this?

I tried:

```<code>public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute(name: "Job Link", url: "EditJob.aspx?JobID ={JobID}", defaults: new { area = "MVC", controller = "Jobs", action = "Edit" });

        routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new { area = "MVC", controller = "Jobs", action = "Index", id = UrlParameter.Optional });
    }
</code>```

But this gives a (System.ArgumentException: 'The route URL cannot start with a '/' or '~' character and it cannot contain a '?' character.'

So,  can I do this using routing or should I recreate the old webforms as redirections to the new pages.

thanks

Update

Thanks to all you clever people I have discovered the wonderful world of IIS URL rewriting which seems to do exactly what I need.

I now have this rule inplace which is close to what I want:

```<code>   <rewrite>
  <rules>
    <rule name="Jobs page redirect" stopProcessing="true">
      <match url="EditJob.aspx" />
      <conditions>
        <add input="{QUERY_STRING}" pattern="JobID=(\d+)" />
      </conditions>
      <action type="Redirect" redirectType="" url="MVC/Jobs/Edit/{C:1}" appendQueryString="false" />
    </rule>
  </rules>
</rewrite>
</code>```

But this redirects to:

```<code> /MVC/Jobs/Edit/1235?JobID=1235
</code>```

It would seem appendQueryString="false" doesn't work or am I missing something ?

答:
I would do this using the IIS rewrite module if you can. That way you keep any logic for your old URLs out of the new app, and if you need to tweak the rules, you can just tweak the web.config file instead having to recompile the site.

If your server doesn't already have the module installed, you can get it from the links on this page: https://learn.microsoft.com/en-us/iis/extensions/url-rewrite-module/using-the-url-rewrite-module (you can also use the IIS Web Platform Installer).

You should be ablate create a regular expression rule to redirect the old URLs to the new one. You can easily add rules for any other legacy URLs as well if need be :)

Title: Asp.net MVC routing for old aspx Url

Body:
We used to have some webforms setup that allowed us to edit jobs.  External applications would access them using a URL like this:

http://server/EditJob.aspx?JobID=1235

having replaced the webforms with MVC the new URL is

http://server/MVC/Jobs/Edit/1235

I would like calls to the former Url  to be routed to the new URl as changing the clients is not possible.  How can I achieve this?

I tried:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute(name: "Job Link", url: "EditJob.aspx?JobID ={JobID}", defaults: new { area = "MVC", controller = "Jobs", action = "Edit" });

        routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new { area = "MVC", controller = "Jobs", action = "Index", id = UrlParameter.Optional });
    }

But this gives a (System.ArgumentException: 'The route URL cannot start with a '/' or '~' character and it cannot contain a '?' character.'

So,  can I do this using routing or should I recreate the old webforms as redirections to the new pages.

thanks

Update

Thanks to all you clever people I have discovered the wonderful world of IIS URL rewriting which seems to do exactly what I need.

I now have this rule inplace which is close to what I want:

   <rewrite>
  <rules>
    <rule name="Jobs page redirect" stopProcessing="true">
      <match url="EditJob.aspx" />
      <conditions>
        <add input="{QUERY_STRING}" pattern="JobID=(\d+)" />
      </conditions>
      <action type="Redirect" redirectType="" url="MVC/Jobs/Edit/{C:1}" appendQueryString="false" />
    </rule>
  </rules>
</rewrite>

But this redirects to:

 /MVC/Jobs/Edit/1235?JobID=1235

It would seem appendQueryString="false" doesn't work or am I missing something ?


问:
Migrating to PHP7.x, Deprecated functions
So here's the problem, the script I purchase is written on PHP 5.x, and I'm using xampp with PHP7.x installed for development. Now I want to migrate my script to PHP7.x. Now I know this was asked a million times already but do you mind if you could take a look at my code and give your thoughts about it, or simply share your knowledge. I would deeply appreciate it.

Here is the code for my config.php

```<code><?php
// mySQL information
$server = 'localhost';                   // MySql server
$username = 'admin';                      // MySql Username
$password = 'admin' ;                         // MySql Password
$database = 'arcade';                  // MySql Database

// The following should not be edited

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

  $con = mysql_connect($server, $username, $password);
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db($database, $con);

// Get settings
if (!isset($install)) {
    $sql = mysql_query("SELECT * FROM ava_settings");
    while ($get_setting = mysql_fetch_array($sql)) {
        $setting[$get_setting['name']] = $get_setting['value'];
    }
}
?>
</code>```

The deprecated functions are:

mysql_connect()

     mysql_error()

     mysql_fetch_array()

     mysql_query()

     mysql_select_db()

Now, I don't want to use the PDO approach, I want to use mysqli instead. Am I suppose to just replace the mysql_* into mysqli_*? So it will become like these? I don't want to hide/surpress the deprecate warnings.

mysqli_connect()

     mysqli_error()

     mysqli_fetch_array()

     mysqli_query()

     mysqli_select_db()

答:
Look at difference between mysqli and mysql: </p>

```<code>$mysqli = mysqli_connect("example.com", "user", "password", "database");
$res = mysqli_query($mysqli, "SELECT ...");
$row = mysqli_fetch_assoc($res);
echo $row['_msg'];

$mysql = mysql_connect("example.com", "user", "password");
mysql_select_db("test");
$res = mysql_query("SELECT ...", $mysql);
$row = mysql_fetch_assoc($res);
echo $row['_msg'];
</code>```

Body:
So here's the problem, the script I purchase is written on PHP 5.x, and I'm using xampp with PHP7.x installed for development. Now I want to migrate my script to PHP7.x. Now I know this was asked a million times already but do you mind if you could take a look at my code and give your thoughts about it, or simply share your knowledge. I would deeply appreciate it.

Here is the code for my config.php

<?php
// mySQL information
$server = 'localhost';                   // MySql server
$username = 'admin';                      // MySql Username
$password = 'admin' ;                         // MySql Password
$database = 'arcade';                  // MySql Database

// The following should not be edited

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

  $con = mysql_connect($server, $username, $password);
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db($database, $con);

// Get settings
if (!isset($install)) {
    $sql = mysql_query("SELECT * FROM ava_settings");
    while ($get_setting = mysql_fetch_array($sql)) {
        $setting[$get_setting['name']] = $get_setting['value'];
    }
}
?>

The deprecated functions are:

mysql_connect()

     mysql_error()

     mysql_fetch_array()

     mysql_query()

     mysql_select_db()

Now, I don't want to use the PDO approach, I want to use mysqli instead. Am I suppose to just replace the mysql_* into mysqli_*? So it will become like these? I don't want to hide/surpress the deprecate warnings.

mysqli_connect()

     mysqli_error()

     mysqli_fetch_array()

     mysqli_query()

     mysqli_select_db()

Body:
Look at difference between mysqli and mysql:

$mysqli = mysqli_connect("example.com", "user", "password", "database");
$res = mysqli_query($mysqli, "SELECT ...");
$row = mysqli_fetch_assoc($res);
echo $row['_msg'];

$mysql = mysql_connect("example.com", "user", "password");
mysql_select_db("test");
$res = mysql_query("SELECT ...", $mysql);
$row = mysql_fetch_assoc($res);
echo $row['_msg'];


问:
Postgres plpgsql with PERFORM data-modifying CTE queries
I tried to simulate my problem in the code example below. In the code below, I am doing a delete from test2 in a procedure. This works great:

However, in my case, this delete is part of a rather complex CTE with several updates and inserts (there are no selects so I add a dummy select 1 as main query). Let's simulate this as this:

```<code>with my_cte as(delete from test2) select 1
</code>```

Now, as we know, we have to use the perform keyword to execute this:

```<code>perform (with my_cte as(delete from test2) select 1);
</code>```

I am getting the following error:

```<code>ERROR: WITH clause containing a data-modifying statement must be at the top level
</code>```

Is this a limitation of plpgsql?

(Please note that this is just an example to explain my problem. I know the queries do not really make any sense.)

```<code>create table test
(
    key int primary key
);

create table test2
(
    key int primary key
);

create function test() returns trigger as
$$
begin
    raise notice 'hello there';
    -- this does work
    delete from test2;
    -- this doesn't work
    perform (with my_cte as(delete from test2) select 1);
    return new;
end;
$$
language plpgsql;

create trigger test after insert on test for each row execute procedure test();

insert into test(key) select 1;
</code>```

答:
You can use CTE for combining several DELETE, INSERT, UPDATE returning queries. And you dont need perform for it, eg:

```<code>t=# begin; do $$ begin with d as (delete from s133 returning *) insert into s133 select * from d; raise info '%',(select count(1) from s133);
end; $$; commit;
BEGIN
Time: 0.135 ms
INFO:  4
DO
Time: 0.469 ms
COMMIT
Time: 0.887 ms
t=# select count(1) from s133;
 count
-------
     4
(1 row)
</code>```

here I delete four rows and in CTE insert them back

Body:
I tried to simulate my problem in the code example below. In the code below, I am doing a delete from test2 in a procedure. This works great:

However, in my case, this delete is part of a rather complex CTE with several updates and inserts (there are no selects so I add a dummy select 1 as main query). Let's simulate this as this:

with my_cte as(delete from test2) select 1

Now, as we know, we have to use the perform keyword to execute this:

perform (with my_cte as(delete from test2) select 1);

I am getting the following error:

ERROR: WITH clause containing a data-modifying statement must be at the top level

Is this a limitation of plpgsql?

(Please note that this is just an example to explain my problem. I know the queries do not really make any sense.)

create table test
(
    key int primary key
);

create table test2
(
    key int primary key
);

create function test() returns trigger as
$$
begin
    raise notice 'hello there';
    -- this does work
    delete from test2;
    -- this doesn't work
    perform (with my_cte as(delete from test2) select 1);
    return new;
end;
$$
language plpgsql;

create trigger test after insert on test for each row execute procedure test();

insert into test(key) select 1;

Body:
You can use CTE for combining several DELETE, INSERT, UPDATE returning queries. And you dont need perform for it, eg:

t=# begin; do $$ begin with d as (delete from s133 returning *) insert into s133 select * from d; raise info '%',(select count(1) from s133);
end; $$; commit;
BEGIN
Time: 0.135 ms
INFO:  4
DO
Time: 0.469 ms
COMMIT
Time: 0.887 ms
t=# select count(1) from s133;
 count
-------
     4
(1 row)

here I delete four rows and in CTE insert them back


问:
Network send problem
I try to send data over the network, but the server I've programmed doesen't get the data.
This code worked befor:

```<code>void MainWindow::send()
{
 QByteArray qbarr;
 QDataStream qdstrm(&qbarr, QIODevice::WriteOnly);
 int iCount = qlist->count();
 QProgressDialog qprogrsdSend(QString("Sending..."), QString("Cancel"), 0, iCount, this);

 qdstrm.setVersion(QDataStream::Qt_4_6);

 qprogrsdSend.setWindowModality(Qt::WindowModal);

 for(int i = 0; i < iCount; i++)
 {
  if(qprogrsdSend.wasCanceled())
   break;

  qdstrm << (quint16)0;
  qdstrm << (*qlist)[i].data();
  qdstrm.device()->seek(0);
  qdstrm << (quint16)(qbarr.size() - sizeof(quint16));

  qprogrsdSend.setValue(i);

  qtcpsoClient->write(qbarr);
  qtcpsoClient->flush();
  qtcpsoClient->waitForBytesWritten();

  qbarr.clear();
 }

 qlblStatus2->setText("File is send.");
}
</code>```

But it Takes to many time to send each elemt from qlist. Now I tried to modify the methode, so that first all elements from qlist has been saved in qbarr. And than I send the File. This is the code that doesnt work:

```<code>void MainWindow::send()
{
 QByteArray qbarr;
 QDataStream qdstrm(&qbarr, QIODevice::WriteOnly);
 int iCount = qlist->count();
 QProgressDialog qprogrsdSend(QString("Sending..."), QString("Cancel"), 0, iCount, this);

 qdstrm.setVersion(QDataStream::Qt_4_6);

 qprogrsdSend.setWindowModality(Qt::WindowModal);

 qdstrm << (quint16)0;

 for(int i = 0; i < iCount; i++)
 {
  if(qprogrsdSend.wasCanceled())
   break;

  qdstrm << (*qlist)[i].data();

  qprogrsdSend.setValue(i);
 }

 qdstrm.device()->seek(0);
 qdstrm << (quint16)(qbarr.size() - sizeof(quint16));

 qtcpsoClient->write(qbarr);
 qtcpsoClient->flush();
 qtcpsoClient->waitForBytesWritten();

 qbarr.clear();

 qlblStatus2->setText("File is send.");
}
</code>```

And here is the methode I use to read the data:

```<code>void QServerThread::onReadyRead(void)
{
 if(read == false)
 {
  read = true;
  emit reading(true);
 }

 while(!qtcpsoClient->atEnd())
 {
  QDataStream qdstrmIn(qtcpsoClient);
  QDataStream qdstrmOut(qfile);
  QByteArray qbarrData;
  quint16 qui16BlockSize = 0;
  int iVersion = qdstrmIn.version();

  qdstrmIn.setVersion(iVersion);
  qdstrmOut.setVersion(iVersion);

  if(qtcpsoClient->bytesAvailable() < (int)sizeof(quint16))
   break;

  qdstrmIn >> qui16BlockSize;

  if(qtcpsoClient->bytesAvailable() < qui16BlockSize)
   break;

  qdstrmIn >> qbarrData;

  qdstrmOut << qbarrData.data();

  qfile->flush();
 }

 read = false;
 emit reading(false);
}
</code>```

I hope somebody can help me.
Thanks

Paul

答:
Couldn't the problem be in your server? I suppose you connect your onReadyRead to readyRead singal of the socket. That signal is emitted once per a chunk of data received. So if you send all your data at once, it is possible the signal gets emitted only once. I suppose qtcpsoClient is the socket. Now, I can see this happening:

You ask bytesAvailable() < somesize before that much data arrived yet. In that case you read a size, but break out right after that and on next read you already lost your size information and read garbage.

This might not be a problem before as you send multiple short messages, and every message managed to fully arrive before you asked for the data size. The bug was still there though.

On a sidenote. In your original client code - why did you flush() and waitForBytesWritten() after every write? This may be the reason why it was so slow.

[edit: corrected based on Sergey Tachenov's comment]

Title: Network send problem

Body:
I try to send data over the network, but the server I've programmed doesen't get the data.
This code worked befor:

void MainWindow::send()
{
 QByteArray qbarr;
 QDataStream qdstrm(&qbarr, QIODevice::WriteOnly);
 int iCount = qlist->count();
 QProgressDialog qprogrsdSend(QString("Sending..."), QString("Cancel"), 0, iCount, this);

 qdstrm.setVersion(QDataStream::Qt_4_6);

 qprogrsdSend.setWindowModality(Qt::WindowModal);

 for(int i = 0; i < iCount; i++)
 {
  if(qprogrsdSend.wasCanceled())
   break;

  qdstrm << (quint16)0;
  qdstrm << (*qlist)[i].data();
  qdstrm.device()->seek(0);
  qdstrm << (quint16)(qbarr.size() - sizeof(quint16));

  qprogrsdSend.setValue(i);

  qtcpsoClient->write(qbarr);
  qtcpsoClient->flush();
  qtcpsoClient->waitForBytesWritten();

  qbarr.clear();
 }

 qlblStatus2->setText("File is send.");
}

But it Takes to many time to send each elemt from qlist. Now I tried to modify the methode, so that first all elements from qlist has been saved in qbarr. And than I send the File. This is the code that doesnt work:

void MainWindow::send()
{
 QByteArray qbarr;
 QDataStream qdstrm(&qbarr, QIODevice::WriteOnly);
 int iCount = qlist->count();
 QProgressDialog qprogrsdSend(QString("Sending..."), QString("Cancel"), 0, iCount, this);

 qdstrm.setVersion(QDataStream::Qt_4_6);

 qprogrsdSend.setWindowModality(Qt::WindowModal);

 qdstrm << (quint16)0;

 for(int i = 0; i < iCount; i++)
 {
  if(qprogrsdSend.wasCanceled())
   break;

  qdstrm << (*qlist)[i].data();

  qprogrsdSend.setValue(i);
 }

 qdstrm.device()->seek(0);
 qdstrm << (quint16)(qbarr.size() - sizeof(quint16));

 qtcpsoClient->write(qbarr);
 qtcpsoClient->flush();
 qtcpsoClient->waitForBytesWritten();

 qbarr.clear();

 qlblStatus2->setText("File is send.");
}

And here is the methode I use to read the data:

void QServerThread::onReadyRead(void)
{
 if(read == false)
 {
  read = true;
  emit reading(true);
 }

 while(!qtcpsoClient->atEnd())
 {
  QDataStream qdstrmIn(qtcpsoClient);
  QDataStream qdstrmOut(qfile);
  QByteArray qbarrData;
  quint16 qui16BlockSize = 0;
  int iVersion = qdstrmIn.version();

  qdstrmIn.setVersion(iVersion);
  qdstrmOut.setVersion(iVersion);

  if(qtcpsoClient->bytesAvailable() < (int)sizeof(quint16))
   break;

  qdstrmIn >> qui16BlockSize;

  if(qtcpsoClient->bytesAvailable() < qui16BlockSize)
   break;

  qdstrmIn >> qbarrData;

  qdstrmOut << qbarrData.data();

  qfile->flush();
 }

 read = false;
 emit reading(false);
}

I hope somebody can help me.
Thanks

Paul