问:
How to send file to dropzone using ruby and selenium-webdriver?
Here is the web with file dropzone

I was trying to upload an image file like this:

```<code>filename = '6.png'
file = File.join(Dir.pwd, filename)
@driver.find_element(:id, "project_images_dropzone").send_key file
</code>```

But it does not work.
I also tried drag and drop:

```<code>filename = '6.png'
file = File.join(Dir.pwd, filename)
target = @driver.find_element(:id, "project_images_dropzone")
@driver.action.click_and_hold(file).perform
@driver.action.drag_and_drop(file,target).perform
@driver.action.release.perform
</code>```

... but this method does not work too.
Is someone know the solution of my problem?

In the code of the page hidden input I found:

```<code><input class="dz-hidden-input" multiple="multiple" accept="image/jpg, image/jpeg, image/png" style="visibility: hidden; position: absolute; top: 0px; left: 0px; height: 0px; width: 0px;" type="file">
</code>```

Again, I tried to send the file with the first method, but webdriver can't find this element:

```<code>/var/lib/gems/2.3.0/gems/selenium-webdriver-3.3.0/lib/selenium/webdriver/remote/response.rb:69:in `assert_ok': Unable to locate element: #dz\-hidden\-input (Selenium::WebDriver::Error::NoSuchElementError)
</code>```

答:
I found solution by myself. All I had to do was locate the hidden input field using xpath. It works great. Here's what it looks like:</p>

```<code>And(/^I upload an image$/) do
  filename = '6.png'
  file = File.join(Dir.pwd, filename) #Dir.pwd is the same folder where .rb file is
  @driver.find_element(:xpath, "html/body/input").send_key file #hidden input field
end
</code>```

Body:
Here is the web with file dropzone

I was trying to upload an image file like this:

filename = '6.png'
file = File.join(Dir.pwd, filename)
@driver.find_element(:id, "project_images_dropzone").send_key file

But it does not work.
I also tried drag and drop:

filename = '6.png'
file = File.join(Dir.pwd, filename)
target = @driver.find_element(:id, "project_images_dropzone")
@driver.action.click_and_hold(file).perform
@driver.action.drag_and_drop(file,target).perform
@driver.action.release.perform

... but this method does not work too.
Is someone know the solution of my problem?

In the code of the page hidden input I found:

<input class="dz-hidden-input" multiple="multiple" accept="image/jpg, image/jpeg, image/png" style="visibility: hidden; position: absolute; top: 0px; left: 0px; height: 0px; width: 0px;" type="file">

Again, I tried to send the file with the first method, but webdriver can't find this element:

/var/lib/gems/2.3.0/gems/selenium-webdriver-3.3.0/lib/selenium/webdriver/remote/response.rb:69:in `assert_ok': Unable to locate element: #dz\-hidden\-input (Selenium::WebDriver::Error::NoSuchElementError)

Body:
I found solution by myself. All I had to do was locate the hidden input field using xpath. It works great. Here's what it looks like:

And(/^I upload an image$/) do
  filename = '6.png'
  file = File.join(Dir.pwd, filename) #Dir.pwd is the same folder where .rb file is
  @driver.find_element(:xpath, "html/body/input").send_key file #hidden input field
end


来源: stackexchange

问:
Reinitialise only new appended FB button
I have an "article" page where the selected article is displayed by default and another articles are ajax-appended to the bottom after clicking on "next" button.

Every article has its own FB share button.

I can reinitialise all the buttons by FB.XFBML.parse(); command, but the existing buttons disappear for a short moment during reinitialisation.

Is there a way to reinitialise only last appended button or somehow to prevent visual disappearing of the buttons?

(Btw. this issue does not apply to twitter button, which can be reinitialised by twttr.widgets.load(); command)

答:
FB.XFBML.parse() function takes a parameter with selected DOM element. Then it will only reinitialise share buttons that are present in the DOM element:

```<code>        var buttons = newblog.find('.share-buttons')[0];
        FB.XFBML.parse(buttons);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
FB.XFBML.parse() function takes a parameter with selected DOM element. Then it will only reinitialise share buttons that are present in the DOM element:

        var buttons = newblog.find('.share-buttons')[0];
        FB.XFBML.parse(buttons);


问:
Feed RSS not updating for W3 validator
I have a problem with my feed rss actually.

I did many tests, and i have to modify my feed rss view (customize it).

Here it's my feed rss : http://agro-media.fr/?feed=email

When you are in the link, you see there is no apparent problems.

However, when you check this link in W3 validator or if you choose this feed in mailchimp, he says "THIS IS NOT A VALID RSS FEED, because there is on the top of the feed this :

```<code>link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</code>```

BUT NO WAY. I deleted it before...

I already did many things like :
- clear WP Rocket cache
- clear Varnish cache
- clear chrome cache
- Server reboot

I don't have more ideas, maybe you can help me ...

thanks a lot guys, have a good day.

答:
Your server software seems to act differently when different user-agent header is present. I tried curling your feed URL and got something in binary-like format. When I modified my user-agent like so:

```<code>curl -A "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5" www.agro-media.fr/?feed=email
</code>```

I got a correct response that starts like this

```<code><?xml version="1.0" encoding="UTF-8"?><rss version="0.92">
<channel>
    <title>Agro Media</title>
</code>```

Unfortunately, I can't help you further, although I've found the cause of your problem.

Title: Feed RSS not updating for W3 validator

Body:
I have a problem with my feed rss actually.

I did many tests, and i have to modify my feed rss view (customize it).

Here it's my feed rss : http://agro-media.fr/?feed=email

When you are in the link, you see there is no apparent problems.

However, when you check this link in W3 validator or if you choose this feed in mailchimp, he says "THIS IS NOT A VALID RSS FEED, because there is on the top of the feed this :

link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

BUT NO WAY. I deleted it before...

I already did many things like :
- clear WP Rocket cache
- clear Varnish cache
- clear chrome cache
- Server reboot

I don't have more ideas, maybe you can help me ...

thanks a lot guys, have a good day.

Body:
Your server software seems to act differently when different user-agent header is present. I tried curling your feed URL and got something in binary-like format. When I modified my user-agent like so:

curl -A "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5" www.agro-media.fr/?feed=email

I got a correct response that starts like this

<?xml version="1.0" encoding="UTF-8"?><rss version="0.92">
<channel>
    <title>Agro Media</title>

Unfortunately, I can't help you further, although I've found the cause of your problem.


问:
Is it possible to have @OneToOne relation between 2 objects but not having the child automatically persisted in Hibernate
I'm using jpa persistance annotations. I have 2 objects, Order(parent) and Transaction(child). I want to be able to fetch my oder and get its transaction. The problem is I don't want my transaction to be automatically saved when I save my order. I need to do some special processing on it before I save it.

Is there a way to tell hybernate not to persist the child object but still fetch it when I retreive the order?

I tried something like this

```<code>@OneToOne(cascade=CascadeType.REFRESH)
@JoinColumn(name = "commande_id", insertable=false, updatable=false)
</code>```

This didn't work. I keep getting this message:

object references an unsaved transient instance - save the transient instance before flushing

When I try to save the order object. The first time I save the order the transaction object contains some data but its not ready to be saved yet.

Thanks in advance

答:
You could make the relationship bidiretional and controlled by the transaction side.

Something like

```<code>class Order {
  @OneToOne(mappedBy="order", cascade={}, insertable=false, updatable=false)
  private Transaction transaction;
}

class Transaction {
  @OneToOne(name = "order_fk")
  private Order order;
}
</code>```

If you do it in this way, the the order.transaction shoud have no writing influence to the data base.
But even it it works, i belive it is a hack.

ContentLicense: CC BY-SA 2.5

Body:
I'm using jpa persistance annotations. I have 2 objects, Order(parent) and Transaction(child). I want to be able to fetch my oder and get its transaction. The problem is I don't want my transaction to be automatically saved when I save my order. I need to do some special processing on it before I save it.

Is there a way to tell hybernate not to persist the child object but still fetch it when I retreive the order?

I tried something like this

@OneToOne(cascade=CascadeType.REFRESH)
@JoinColumn(name = "commande_id", insertable=false, updatable=false)

This didn't work. I keep getting this message:

object references an unsaved transient instance - save the transient instance before flushing

When I try to save the order object. The first time I save the order the transaction object contains some data but its not ready to be saved yet.

Thanks in advance

Body:
You could make the relationship bidiretional and controlled by the transaction side.

Something like

class Order {
  @OneToOne(mappedBy="order", cascade={}, insertable=false, updatable=false)
  private Transaction transaction;
}

class Transaction {
  @OneToOne(name = "order_fk")
  private Order order;
}

If you do it in this way, the the order.transaction shoud have no writing influence to the data base.
But even it it works, i belive it is a hack.


问:
Questionning a technique for preloading images (typically used as background images for hover state)
This technique for preloading several images entails the following CSS:

```<code>#preload_area {
    background-image: url(someimage.jpg);
    background-image: url(someimage2.jpg);
    width: 0px;
    height: 0px;
    display: inline;
}
</code>```

However, will someimage.jpg actually be loaded? I would have thought it would simply be ignored hence not loaded after being overriden by the rule with someimage2.jpg in the next line.

答:
You are right, the first background-image would be ignored. However, you can use something similar since CSS3 supports multiple backgrounds:

```<code>background-image: url(someimage.jpg), url(someimage2.jpg);
</code>```

Supported by every broswer since IE8 – http://caniuse.com/#feat=multibackgrounds

Body:
This technique for preloading several images entails the following CSS:

#preload_area {
    background-image: url(someimage.jpg);
    background-image: url(someimage2.jpg);
    width: 0px;
    height: 0px;
    display: inline;
}

However, will someimage.jpg actually be loaded? I would have thought it would simply be ignored hence not loaded after being overriden by the rule with someimage2.jpg in the next line.

Body:
You are right, the first background-image would be ignored. However, you can use something similar since CSS3 supports multiple backgrounds:

background-image: url(someimage.jpg), url(someimage2.jpg);

Supported by every broswer since IE8 – http://caniuse.com/#feat=multibackgrounds


问:
Should I have multiple repositories?
Does having multiple repositories increase resource usage?

I have followed this tutorial for adding a repository service that holds a database context: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api

In the tutorial the repository is for managing a Todo item.  In my own app I have several different types of items and activities that I need a context for.  Should I create an individual repository for each?  For instance one repository for enquiries, another for user usage metrics?  Is there any overhead or penalty for doing this?

答:
Should I create an individual repository for each? For instance one repository for enquiries, another for user usage metrics? Is there any overhead or penalty for doing this?

Yes.  No.

Generally you want to have one repository per entity type because each entity type is going to more than likely require operations specific to its type beyond the cliche CRUD operations.  The aim of the repo is to eliminate duplicate data query logic that would otherwise be littered about your application.

e.g.

```<code>interface IRepo { CRUD }

protected abstract class RepoBase<T> : IRepo
{
   // CRUD implementation
}

public class PatientRepo : RepoBase<Patient>
{
    List<IPatient> GetAllTerminallyIllPatients();
}

public class MusicRepo : RepoBase<Music>
{
    List<ISong> GetAllSongsByArtist (string artist);
}
</code>```

Note how each repo in my feeble example is customised to the entity type.   If you didn't do this your single repo would quickly

become hard to find that method you're after

unmanageble with the potential for 100s of methods

lead to increased probability of source control conflict due to all code being in one file

You might want to consider splitting your repos into repos and unit of work classes because:

Repositories should not have semantics of your database.  It should
  be like a collection of objects in memory and should not methods like
  update and save. - Mosh

You can learn more from the tutorial in the link below.

Does having multiple repositories increase resource usage?

Generally no, because for any given operation, all of your interested repos would be attached to the same database context instance.  It is the context that is expensive, not the repo.

Tell me more

Repository Pattern with C# and Entity Framework, Done Right

Title: Should I have multiple repositories?

Body:
Should I create an individual repository for each? For instance one repository for enquiries, another for user usage metrics? Is there any overhead or penalty for doing this?

Yes.  No.

Generally you want to have one repository per entity type because each entity type is going to more than likely require operations specific to its type beyond the cliche CRUD operations.  The aim of the repo is to eliminate duplicate data query logic that would otherwise be littered about your application.

e.g.

interface IRepo { CRUD }

protected abstract class RepoBase<T> : IRepo
{
   // CRUD implementation
}

public class PatientRepo : RepoBase<Patient>
{
    List<IPatient> GetAllTerminallyIllPatients();
}

public class MusicRepo : RepoBase<Music>
{
    List<ISong> GetAllSongsByArtist (string artist);
}

Note how each repo in my feeble example is customised to the entity type.   If you didn't do this your single repo would quickly

become hard to find that method you're after

unmanageble with the potential for 100s of methods

lead to increased probability of source control conflict due to all code being in one file

You might want to consider splitting your repos into repos and unit of work classes because:

Repositories should not have semantics of your database.  It should
  be like a collection of objects in memory and should not methods like
  update and save. - Mosh

You can learn more from the tutorial in the link below.

Does having multiple repositories increase resource usage?

Generally no, because for any given operation, all of your interested repos would be attached to the same database context instance.  It is the context that is expensive, not the repo.

Tell me more

Repository Pattern with C# and Entity Framework, Done Right


问:
update same rows
I have a table like below:
Current

```<code>    Column1 Column2 column3
   -------------------------
    abc       cat1     1
    efg       cat1     3
    hij       cat1     2
    klm       cat2     1
    nop       car2     2
    qrs       cat2     3
</code>```

I want to update column1 where all rows matching cat1 from rows matching cat2 , considering rows will be updated for id which matches column 3 ids

Expected

```<code>Column1 Column2 column3
-------------------------
klm       cat1     1
qrs       cat1     3
nop       cat1     2
klm       cat2     1
nop       car2     2
qrs       cat2     3
</code>```

答:
```<code>Use below query :

 CREATE TABLE #Table (Column1 VARCHAR(100),Column2 VARCHAR(100), Column3
 VARCHAR(100))

 INSERT INTO #Table ( Column1  ,    Column2  , Column3  )
 SELECT 'abc','cat1',1 UNION ALL
 SELECT 'efg','cat1',3 UNION ALL
 SELECT 'hij','cat1',2 UNION ALL
 SELECT 'klm','cat2',1 UNION ALL
 SELECT 'nop','cat2',2 UNION ALL
 SELECT 'qrs','cat2',3

 UPDATE #Table SET Column1 = A.Column1
 FROM
 (
   SELECT Column1 , Column3
   FROM #Table
   WHERE Column2 = 'cat2'
 )A WHERE #Table.Column2 = 'cat1' AND  A.Column3 = #Table.Column3

 SELECT * FROM #Table
</code>```

http://rextester.com/QYHLTE44670

Title: update same rows

Body:
I have a table like below:
Current

    Column1 Column2 column3
   -------------------------
    abc       cat1     1
    efg       cat1     3
    hij       cat1     2
    klm       cat2     1
    nop       car2     2
    qrs       cat2     3

I want to update column1 where all rows matching cat1 from rows matching cat2 , considering rows will be updated for id which matches column 3 ids

Expected

Column1 Column2 column3
-------------------------
klm       cat1     1
qrs       cat1     3
nop       cat1     2
klm       cat2     1
nop       car2     2
qrs       cat2     3

Body:
Use below query :

 CREATE TABLE #Table (Column1 VARCHAR(100),Column2 VARCHAR(100), Column3
 VARCHAR(100))

 INSERT INTO #Table ( Column1  ,    Column2  , Column3  )
 SELECT 'abc','cat1',1 UNION ALL
 SELECT 'efg','cat1',3 UNION ALL
 SELECT 'hij','cat1',2 UNION ALL
 SELECT 'klm','cat2',1 UNION ALL
 SELECT 'nop','cat2',2 UNION ALL
 SELECT 'qrs','cat2',3

 UPDATE #Table SET Column1 = A.Column1
 FROM
 (
   SELECT Column1 , Column3
   FROM #Table
   WHERE Column2 = 'cat2'
 )A WHERE #Table.Column2 = 'cat1' AND  A.Column3 = #Table.Column3

 SELECT * FROM #Table

http://rextester.com/QYHLTE44670


问:
Handling a RequestBody when there are variable key-value in the request json body in spring boot
I am pretty new to java development but I have developed couple of production ready applications on PHP and Python. I am developing a REST api using spring boot framework and find it little confusion in terms to handling/parsing the request body. In the other languages I have worked on, it was much simpler.

If its in python/php, I need not define all the parameters of the request explicitly to handle the request body. But in java, I have to predefine all the request parameters in a POJO class and MAP it. So for every API endpoint I make, I will have to define all in a Java class as the data layer.

But in other languages, I dont need to map anything to an array, in php $_POST holds the data objects.

My question is

I have the following requests

```<code>1.
{
  "category": "product/invoice/event",
  "item_id": "Unique tool identifier id",
  "platforms_id": "1",
  "share_platform_settings": {
    "fb_share_type": "page/profile",
    "fb_share_name": "profilename/pagename",
    "fb_id": "fb_uid/page_id"
  }
}

2.
{
  "category": "product/invoice/event",
  "item_id": "Unique tool identifier id",
  "platforms_id": "1",
  "share_platform_settings": {
    "twitter_username": "page/profile",
    "twitter_user_access_token": "profilename/pagename"
  }
}
</code>```

I had written a class

```<code>import com.google.common.base.Objects;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
public class User {

    @Id
    @NotNull
    @Size(max = 64)
    @Column(name = "id", nullable = false, updatable = false)

    private String id;

    private String category;

    private String item_id;

    private String platforms_id;

    private String fb_share_type;

    private String fb_share_name;

    private String fb_id;

    User() {
    }

    public User(final String id, final String category,final String item_id,final String platforms_id,final String fb_share_type,final String fb_share_name,final String fb_id) {
        this.id = id;
        this.category = category;
        this.item_id = item_id;
        this.platforms_id = platforms_id;
        this.fb_share_type = fb_share_type;
        this.fb_share_name = fb_share_name;
        this.fb_id = fb_id;
    }

    public String getId() {
        return id;
    }

    public String getCategory() {
        return category;
    }

    public String getItemId() {
        return item_id;
    }

    public String getFbShareType() {
        return platforms_id;
    }

    public String getFbShareName() {
        return category;
    }

    public String getFbId() {
        return category;
    }

    public String setCategory(String category) {
        return this.category = category;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setItemId(String item_id) {
        this.item_id = item_id;
    }

    public void setFbShareType(String fb_share_type) {
        this.fb_share_type = fb_share_type;
    }

    public void setFbShareName(String fb_share_name) {
        this.fb_share_name = fb_share_name;
    }

    public void setFbId(String fb_id) {
        this.fb_id = fb_id;
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("id", id)
                .add("item_id", item_id)
                .add("fb_share_type", fb_share_type)
                .add("fb_share_name", fb_share_name)
                .add("fb_id", fb_id)
                .add("category", category)
                .toString();
    }
}
</code>```

I can map the request to the class using @RequestBody Request request,
but I have define the class Request with my request params. But my request params keeps changing, I have a different json request structure 2. What would I do in that case? What if if I have n number of different requests on the same API? Do I need to create classes for each of them? or define all the variables in this class itself? Or is there anyway, I dont need anyclass, is jackson dependency used for that?

Sorry if this a dump question, I am pretty new to java development and I really appreciate understanding a  question like this :P

答:
As you are using key/value parameters in your JSON, you will need to map it with a similar structure in the Backend so you will need to use a collection of type Map like Map<String, String> share_platform_settings in your Entity.

And your Entity will be like:

```<code>@Entity
public class User {

    @Id
    @NotNull
    @Size(max = 64)
    @Column(name = "id", nullable = false, updatable = false)
    private String id;

    private String category;
    private String item_id;
    private String platforms_id;
    private Map<String, String> share_platform_settings;

    //Constructors, getters and setters
}
</code>```

This should work for you.

Body:
I am pretty new to java development but I have developed couple of production ready applications on PHP and Python. I am developing a REST api using spring boot framework and find it little confusion in terms to handling/parsing the request body. In the other languages I have worked on, it was much simpler.

If its in python/php, I need not define all the parameters of the request explicitly to handle the request body. But in java, I have to predefine all the request parameters in a POJO class and MAP it. So for every API endpoint I make, I will have to define all in a Java class as the data layer.

But in other languages, I dont need to map anything to an array, in php $_POST holds the data objects.

My question is

I have the following requests

1.
{
  "category": "product/invoice/event",
  "item_id": "Unique tool identifier id",
  "platforms_id": "1",
  "share_platform_settings": {
    "fb_share_type": "page/profile",
    "fb_share_name": "profilename/pagename",
    "fb_id": "fb_uid/page_id"
  }
}

2.
{
  "category": "product/invoice/event",
  "item_id": "Unique tool identifier id",
  "platforms_id": "1",
  "share_platform_settings": {
    "twitter_username": "page/profile",
    "twitter_user_access_token": "profilename/pagename"
  }
}

I had written a class

import com.google.common.base.Objects;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
public class User {

    @Id
    @NotNull
    @Size(max = 64)
    @Column(name = "id", nullable = false, updatable = false)

    private String id;

    private String category;

    private String item_id;

    private String platforms_id;

    private String fb_share_type;

    private String fb_share_name;

    private String fb_id;

    User() {
    }

    public User(final String id, final String category,final String item_id,final String platforms_id,final String fb_share_type,final String fb_share_name,final String fb_id) {
        this.id = id;
        this.category = category;
        this.item_id = item_id;
        this.platforms_id = platforms_id;
        this.fb_share_type = fb_share_type;
        this.fb_share_name = fb_share_name;
        this.fb_id = fb_id;
    }

    public String getId() {
        return id;
    }

    public String getCategory() {
        return category;
    }

    public String getItemId() {
        return item_id;
    }

    public String getFbShareType() {
        return platforms_id;
    }

    public String getFbShareName() {
        return category;
    }

    public String getFbId() {
        return category;
    }

    public String setCategory(String category) {
        return this.category = category;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setItemId(String item_id) {
        this.item_id = item_id;
    }

    public void setFbShareType(String fb_share_type) {
        this.fb_share_type = fb_share_type;
    }

    public void setFbShareName(String fb_share_name) {
        this.fb_share_name = fb_share_name;
    }

    public void setFbId(String fb_id) {
        this.fb_id = fb_id;
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("id", id)
                .add("item_id", item_id)
                .add("fb_share_type", fb_share_type)
                .add("fb_share_name", fb_share_name)
                .add("fb_id", fb_id)
                .add("category", category)
                .toString();
    }
}

I can map the request to the class using @RequestBody Request request,
but I have define the class Request with my request params. But my request params keeps changing, I have a different json request structure 2. What would I do in that case? What if if I have n number of different requests on the same API? Do I need to create classes for each of them? or define all the variables in this class itself? Or is there anyway, I dont need anyclass, is jackson dependency used for that?

Sorry if this a dump question, I am pretty new to java development and I really appreciate understanding a  question like this :P

Body:
As you are using key/value parameters in your JSON, you will need to map it with a similar structure in the Backend so you will need to use a collection of type Map like Map<String, String> share_platform_settings in your Entity.

And your Entity will be like:

@Entity
public class User {

    @Id
    @NotNull
    @Size(max = 64)
    @Column(name = "id", nullable = false, updatable = false)
    private String id;

    private String category;
    private String item_id;
    private String platforms_id;
    private Map<String, String> share_platform_settings;

    //Constructors, getters and setters
}

This should work for you.


问:
Laravel Auth Middleware: Class can does not exist
I'm trying to protect a route via middleware as described in the doc

When I hit the url, I get:

```<code>ReflectionException in Container.php line 749:
Class can does not exist
</code>```

Here's the relevant part from routes.php:

```<code>Route::get('{user}/profile/edit/{type?}', [
    'as'   => 'edit',
    'uses' => 'User\UserController@edit',
    'middleware' => ['can:edit-user,user'],
]);
</code>```

AuthServiceProvider.php:

```<code>public function boot()
{
    $this->registerPolicies();

    // ... other definitions

    Gate::define('edit-user', function ($user, $subjectUser) {
        return
            $user->hasRole('manage.user') // if the user has this role, green
            ||
            ($user->isAdmin && $user->id == $subjectUser->id) // otherwise if is admin, can edit her own profile
            ;
    });
</code>```

Maybe it's because I'm not using a separate policy class for defining the gate?

答:
According to the documentation on using Middleware with Routes - you need to register the definition in app/Http/Kernel.php

If you want a middleware to run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/Kernel.php class.

The error you're seeing shows that this definition is missing. You need to add something like;

```<code>// Within App\Http\Kernel Class...

protected $routeMiddleware = [
    //...
    'can' => \Path\To\Your\Middleware::class,
];
</code>```

Body:
I'm trying to protect a route via middleware as described in the doc

When I hit the url, I get:

ReflectionException in Container.php line 749:
Class can does not exist

Here's the relevant part from routes.php:

Route::get('{user}/profile/edit/{type?}', [
    'as'   => 'edit',
    'uses' => 'User\UserController@edit',
    'middleware' => ['can:edit-user,user'],
]);

AuthServiceProvider.php:

public function boot()
{
    $this->registerPolicies();

    // ... other definitions

    Gate::define('edit-user', function ($user, $subjectUser) {
        return
            $user->hasRole('manage.user') // if the user has this role, green
            ||
            ($user->isAdmin && $user->id == $subjectUser->id) // otherwise if is admin, can edit her own profile
            ;
    });

Maybe it's because I'm not using a separate policy class for defining the gate?

Body:
According to the documentation on using Middleware with Routes - you need to register the definition in app/Http/Kernel.php

If you want a middleware to run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/Kernel.php class.

The error you're seeing shows that this definition is missing. You need to add something like;

// Within App\Http\Kernel Class...

protected $routeMiddleware = [
    //...
    'can' => \Path\To\Your\Middleware::class,
];


问:
Is it ok to have style tag and xml in svg embedded in html page?
I have generated some svgs with Adobe Illustrator and have embedded them inline in my html page. As far as I know all style tags must be in head but these svgs have their own style tags. Following is the example of one svg:

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 21.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg version="1.1" id="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 526.6 28.3" style="enable-background:new 0 0 526.6 28.3;" xml:space="preserve">
    <style type="text/css">
        .st0 {
        fill: none;
        }

        .st1 {
        enable-background: new;
        }

        .st2 {
        fill: #009444;
        }
    </style>
    <rect y="2.3" class="st0" width="526.6" height="26" />
</svg>
</code>```

The svg renders well in Firefox and Chrome. One svg appeared smaller than in other browsers in IE11 and Edge it appeared perfect. I haven't checked in Safari as I don't have mac. My question is:

Is it ok to have style tag and xml in svg embedded in html page as per w3c and browser compatibility?

P.S: In a work of mine I saw problems with inline svg in EDGE browser when appended with jquery appendTo. The svgs, set to display inline-block   overlapped each other. (The bottom case in https://anupamkhosla.github.io/marqueedirection/)

答:
This is not an HTML document, but an SVG document.

In SVG, there is no  element and

Body:
I have generated some svgs with Adobe Illustrator and have embedded them inline in my html page. As far as I know all style tags must be in head but these svgs have their own style tags. Following is the example of one svg:

<?xml version="1.0" encoding="utf-8"?>

<svg version="1.1" id="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 526.6 28.3" style="enable-background:new 0 0 526.6 28.3;" xml:space="preserve">

    <rect y="2.3" class="st0" width="526.6" height="26" />
</svg>

The svg renders well in Firefox and Chrome. One svg appeared smaller than in other browsers in IE11 and Edge it appeared perfect. I haven't checked in Safari as I don't have mac. My question is:

Is it ok to have style tag and xml in svg embedded in html page as per w3c and browser compatibility?

P.S: In a work of mine I saw problems with inline svg in EDGE browser when appended with jquery appendTo. The svgs, set to display inline-block   overlapped each other. (The bottom case in https://anupamkhosla.github.io/marqueedirection/)

Body:
This is not an HTML document, but an SVG document.

In SVG, there is no <head> element and <style> is commonly placed directly in the root elements or in a <defs> subelement.

As documented in the HTML standard, you can embed whole SVG documents in HTML, including <style>. Therefore, it is ok to place style into SVG documents within HTML ones, provided they are actually SVG, i.e. their namespace is http://www.w3.org/2000/svg.

In HTML, <style> should be put under <head> (or <noscript> in <head>), per the HTML standard.


问:
Excel IFS formula - range of number
I have a value in cell AB8 and I want to conditionally return a status depending on which value it takes between 1 and 30.

I want to save time and rather than type the scores 1-9 indivdually to turn into "EMERGING" (etc) is there a way I can put a range in?

```<code>IFS(AB8=1,"EMERGING",AB8=2,"EMERGING",AB8=3,"EMERGING",AB8=4,"EMERGING",AB8=5,"EMERGING",AB8=6,"EMERGING",AB8=7,"EMERGING",AB8=8,"EMERGING",AB8=9,"DEVELOPING",AB8=10,"DEVELOPING",AB8=11,"DEVELOPING",AB8=12,"DEVELOPING",AB8=13,"DEVELOPING",AB8=14,"DEVELOPING",AB8=15,"DEVELOPING",AB8=16,"DEVELOPING",AB8=17,"SECURING",AB8=18,"SECURING",AB8=19,"SECURING",AB8=20,"SECURING",AB8=21,"SECURING",AB8=22,"SECURING",AB8=23,"SECURING",AB8=24,"SECURING",AB8=25,"READY",AB8=26,"READY",AB8=27,"READY",AB8=28,"READY",AB8=29,"READY",AB8=30,"READY")
</code>```

答:
Try this:

```<code>=INDEX({"EMERGING","DEVELOPING","SECURING","READY"},MATCH(AB8,{0,9,17,25},1))
</code>```

Or create this table in, say, A1:B4:

```<code>0   Emerging
9   Developing
17  Securing
25  Ready
</code>```

And then the formula is just:

```<code>=INDEX($B$1:$B$4,MATCH(AB8,$A$1:$A$4,1))
</code>```

Title: Excel IFS formula - range of number

Body:
I have a value in cell AB8 and I want to conditionally return a status depending on which value it takes between 1 and 30.

I want to save time and rather than type the scores 1-9 indivdually to turn into "EMERGING" (etc) is there a way I can put a range in?

IFS(AB8=1,"EMERGING",AB8=2,"EMERGING",AB8=3,"EMERGING",AB8=4,"EMERGING",AB8=5,"EMERGING",AB8=6,"EMERGING",AB8=7,"EMERGING",AB8=8,"EMERGING",AB8=9,"DEVELOPING",AB8=10,"DEVELOPING",AB8=11,"DEVELOPING",AB8=12,"DEVELOPING",AB8=13,"DEVELOPING",AB8=14,"DEVELOPING",AB8=15,"DEVELOPING",AB8=16,"DEVELOPING",AB8=17,"SECURING",AB8=18,"SECURING",AB8=19,"SECURING",AB8=20,"SECURING",AB8=21,"SECURING",AB8=22,"SECURING",AB8=23,"SECURING",AB8=24,"SECURING",AB8=25,"READY",AB8=26,"READY",AB8=27,"READY",AB8=28,"READY",AB8=29,"READY",AB8=30,"READY")

Body:
Try this:

=INDEX({"EMERGING","DEVELOPING","SECURING","READY"},MATCH(AB8,{0,9,17,25},1))

Or create this table in, say, A1:B4:

0   Emerging
9   Developing
17  Securing
25  Ready

And then the formula is just:

=INDEX($B$1:$B$4,MATCH(AB8,$A$1:$A$4,1))


问:
Best way to multi-thread?
What is the best way to multi-thread in the C language? I want something that is very efficient and not a CPU hog. Thanks.</p>

答: If you're on a UNIX-based platform (Linux or Mac OS X) your best option is POSIX threads. They're the standard cross-platform way to multithread in a POSIX environment. They can also be used in Windows, but there are probably better (more native) solutions for that platform.</p>

OwnerDisplayName: Sasayins

Title: Best way to multi-thread?

LastEditorDisplayName: John

OwnerDisplayName: Kyle


问:
String search
What is the best way to search strings for something like forum? i seen horrible string search and typically get worse the more strings you use rather then better.

I also may implement a title search so if the way to search title that is better then a body of string i'd love to hear that too

答: Take a look at using Lucene (Java) (or Lucene.Net) for full text search.  Lucene is a text-mining API that allows you to index and search documents by title, text, author, etc.  I've used a Ruby port of Lucene (Ferret or acts_as_ferret) to index a specialized mailing list and found that it works very well.</p>

Title: String search

OwnerDisplayName: tvanfosson


问:
Why I'm getting trash on this pipe?
I'm running a full-duplex server/client code I found on Oracle's website:

When writing ./fd_client hahaha I get something like:

HAHAHA0�$0

The upper case is OK (it's what the server it's supposed to return) but, how the hell do I avoid that trailing trash?

fd_client.c

```<code>#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "fullduplex.h" /* For name of the named-pipe */

int main(int argc, char *argv[])
{
    int wrfd, rdfd, numread;
    char rdbuf[MAX_BUF_SIZE];

    /* Check if an argument was specified. */

    if (argc != 2) {
        printf("Usage : %s \n", argv[0]);
        exit (0);
    }

    /* Open the first named pipe for writing */
    wrfd = open(NP1, O_WRONLY);

    /* Open the second named pipe for reading */
    rdfd = open(NP2, O_RDONLY);

    /* Write to the pipe */
    write(wrfd, argv[1], strlen(argv[1]));

    /* Read from the pipe */
    numread = read(rdfd, rdbuf, MAX_BUF_SIZE);

    rdbuf[numread] = '0';

    printf("Full Duplex Client : Read From the  Pipe : %s\n", rdbuf);

    return 0;
}
</code>```

fd_server.c

```<code>#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "fullduplex.h" /* For name of the named-pipe */

int main(int argc, char *argv[])
{
    int rdfd, wrfd, ret_val, count, numread;
    char buf[MAX_BUF_SIZE];

    /* Create the first named - pipe */
    ret_val = mkfifo(NP1, 0666);

    if ((ret_val == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit (0);
    }

    ret_val = mkfifo(NP2, 0666);

    if ((ret_val == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit (0);
    }

    /* Open the first named pipe for reading */
    rdfd = open(NP1, O_RDONLY);

    /* Open the second named pipe for writing */
    wrfd = open(NP2, O_WRONLY);

    /* Read from the first pipe */
    numread = read(rdfd, buf, MAX_BUF_SIZE);

    buf[numread] = '0';

    printf("Full Duplex Server : Read From the pipe : %s \n", buf);

    /* Convert to the string to upper case */
    count = 0;
    while (count < numread) {
        buf[count] = toupper(buf[count]);
        count++;
    }

    /*
     * Write the converted string back to the second
     * pipe
     */
    write(wrfd, buf, strlen(buf));
}
</code>```

fullduplex.h

```<code>#define NP1     "/tmp/np1"
#define NP2     "/tmp/np2"
#define MAX_BUF_SIZE    255
</code>```

答:
This:

```<code>buf[numread] = '0';
</code>```

is wrong. You want:

```<code>buf[numread] = '\0';
</code>```

(Same with rdbuf[numread] = '0';.)

Title: Why I'm getting trash on this pipe?

Body:
I'm running a full-duplex server/client code I found on Oracle's website:

When writing ./fd_client hahaha I get something like:

HAHAHA0�$0

The upper case is OK (it's what the server it's supposed to return) but, how the hell do I avoid that trailing trash?

fd_client.c

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "fullduplex.h" /* For name of the named-pipe */

int main(int argc, char *argv[])
{
    int wrfd, rdfd, numread;
    char rdbuf[MAX_BUF_SIZE];

    /* Check if an argument was specified. */

    if (argc != 2) {
        printf("Usage : %s \n", argv[0]);
        exit (0);
    }

    /* Open the first named pipe for writing */
    wrfd = open(NP1, O_WRONLY);

    /* Open the second named pipe for reading */
    rdfd = open(NP2, O_RDONLY);

    /* Write to the pipe */
    write(wrfd, argv[1], strlen(argv[1]));

    /* Read from the pipe */
    numread = read(rdfd, rdbuf, MAX_BUF_SIZE);

    rdbuf[numread] = '0';

    printf("Full Duplex Client : Read From the  Pipe : %s\n", rdbuf);

    return 0;
}

fd_server.c

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "fullduplex.h" /* For name of the named-pipe */

int main(int argc, char *argv[])
{
    int rdfd, wrfd, ret_val, count, numread;
    char buf[MAX_BUF_SIZE];

    /* Create the first named - pipe */
    ret_val = mkfifo(NP1, 0666);

    if ((ret_val == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit (0);
    }

    ret_val = mkfifo(NP2, 0666);

    if ((ret_val == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit (0);
    }

    /* Open the first named pipe for reading */
    rdfd = open(NP1, O_RDONLY);

    /* Open the second named pipe for writing */
    wrfd = open(NP2, O_WRONLY);

    /* Read from the first pipe */
    numread = read(rdfd, buf, MAX_BUF_SIZE);

    buf[numread] = '0';

    printf("Full Duplex Server : Read From the pipe : %s \n", buf);

    /* Convert to the string to upper case */
    count = 0;
    while (count < numread) {
        buf[count] = toupper(buf[count]);
        count++;
    }

    /*
     * Write the converted string back to the second
     * pipe
     */
    write(wrfd, buf, strlen(buf));
}

fullduplex.h

#define NP1     "/tmp/np1"
#define NP2     "/tmp/np2"
#define MAX_BUF_SIZE    255

Body:
This:

buf[numread] = '0';

is wrong. You want:

buf[numread] = '\0';

(Same with rdbuf[numread] = '0';.)


问:
Label disappear when table is reloaded / scrolled
I have a UITableview with two UILabels like in the chat. When the visible UITableview is filled and when I add extra cells, my UILabels get disappeared.

There are may other UILabels which is visible. Only those 2 chat UILabels is hidden. Can anyone suggest me the possible solution?

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
ChatScreenViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChatCell" forIndexPath:indexPath];
index = indexPath.row + 1;
indexx = indexPath;

cell.ChatLabel1.layer.cornerRadius = 8;
cell.ChatLabel1.layer.masksToBounds = YES;
cell.ChatLabel2.layer.cornerRadius = 8;
cell.ChatLabel2.layer.masksToBounds = YES;

cell.ImageviewLabel1.layer.cornerRadius = 20;
cell.ImageviewLabel1.layer.masksToBounds = YES;
cell.ImageviewLabel2.layer.cornerRadius = 20;
cell.ImageviewLabel2.layer.masksToBounds = YES;
cell.ImageviewLabel2.backgroundColor = [UIColor greenColor];

if([Replychat[indexPath.row] valueForKey:@"bot"] != NULL)
{

    cell.ChatLabel1.text = [Replychat[indexPath.row] valueForKey:@"bot"];
    cell.ChatLabel2.hidden = YES;
    cell.ImageviewLabel2.hidden = YES;

    cell.TimeLabel1.text = TimeArray[indexPath.row];
}
else
{

    cell.ChatLabel2.text = [Replychat[indexPath.row] valueForKey:@"User"];
    cell.ChatLabel1.hidden = YES;
    cell.ImageviewLabel1.hidden = YES;
    cell.TimeLabel2.text = TimeArray[indexPath.row];
}

return cell;
</code>```

}

答:
try:</p>

```<code>   //....
    cell.ImageviewLabel2.backgroundColor = [UIColor greenColor];
   // because tableview reuse uitableviewcell, so you must reset hidden status for lable
    cell.ChatLabel2.hidden = NO;
    cell.ChatLabel1.hidden = NO;

   if([Replychat[indexPath.row] valueForKey:@"bot"] != NULL)
   //....
</code>```

Body:
I have a UITableview with two UILabels like in the chat. When the visible UITableview is filled and when I add extra cells, my UILabels get disappeared.

There are may other UILabels which is visible. Only those 2 chat UILabels is hidden. Can anyone suggest me the possible solution?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
ChatScreenViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChatCell" forIndexPath:indexPath];
index = indexPath.row + 1;
indexx = indexPath;

cell.ChatLabel1.layer.cornerRadius = 8;
cell.ChatLabel1.layer.masksToBounds = YES;
cell.ChatLabel2.layer.cornerRadius = 8;
cell.ChatLabel2.layer.masksToBounds = YES;

cell.ImageviewLabel1.layer.cornerRadius = 20;
cell.ImageviewLabel1.layer.masksToBounds = YES;
cell.ImageviewLabel2.layer.cornerRadius = 20;
cell.ImageviewLabel2.layer.masksToBounds = YES;
cell.ImageviewLabel2.backgroundColor = [UIColor greenColor];

if([Replychat[indexPath.row] valueForKey:@"bot"] != NULL)
{

    cell.ChatLabel1.text = [Replychat[indexPath.row] valueForKey:@"bot"];
    cell.ChatLabel2.hidden = YES;
    cell.ImageviewLabel2.hidden = YES;

    cell.TimeLabel1.text = TimeArray[indexPath.row];
}
else
{

    cell.ChatLabel2.text = [Replychat[indexPath.row] valueForKey:@"User"];
    cell.ChatLabel1.hidden = YES;
    cell.ImageviewLabel1.hidden = YES;
    cell.TimeLabel2.text = TimeArray[indexPath.row];
}

return cell;

}

Body:
try:

   //....
    cell.ImageviewLabel2.backgroundColor = [UIColor greenColor];
   // because tableview reuse uitableviewcell, so you must reset hidden status for lable
    cell.ChatLabel2.hidden = NO;
    cell.ChatLabel1.hidden = NO;

   if([Replychat[indexPath.row] valueForKey:@"bot"] != NULL)
   //....


问:
Advice on building graphQL queries in c#
I am working on a data migration project - API to API.

The destination API is graphQL, we have a number of objects to push into the destination and the shapes vary so I am looking for some advice on how best to dynamically build mutations/queries specifically in c#.

Currently we are just using templates and using find/replace routines to inject values. While this approach does work as the shapes of the data vary this becomes evermore complex and inelegant.

I am looking for any advice/pointers from anyone who have may have had a similar scenario or knows of any libraries I should look at.

答:
Update - 13/02/2018

I have since updated this monstrosity to cater for nested sub selections and GraphQl enums so if anyone is interested here it is in GitHub

Orignal answer

I've got the same requirement. Couldn't find anything out there so I've come up with this very inelegant solution. It works for my scenarios so I'll post it here for anyone else looking for a solution.

```<code> public static class GraphQlObjectParser
{
    public static string Parse(string queryType, string queryName, string[] subSelection, object @object = null, string objectTypeName = null)
    {
        var query = queryType + "{" + queryName;

        if (@object != null)
        {
            query += "(";

            if (objectTypeName != null)
            {
                query += objectTypeName + ":" + "{";
            }

            var queryData = string.Empty;
            foreach (var propertyInfo in @object.GetType().GetProperties())
            {
                var value = propertyInfo.GetValue(@object);
                if (value != null)
                {
                    var type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
                    var valueQuotes = type == typeof(string) ? "\"" : string.Empty;

                    var queryPart = char.ToLowerInvariant(propertyInfo.Name[0]) + propertyInfo.Name.Substring(1) + ":" + valueQuotes + value + valueQuotes;
                    queryData += queryData.Length > 0 ? "," + queryPart : queryPart;
                }
            }
            query += (objectTypeName != null ? queryData + "}" : queryData) + ")";
        }

        if (subSelection.Length > 0)
        {
            query += subSelection.Aggregate("{", (current, s) => current + (current.Length > 1 ? "," + s : s)) + "}";
        }

        query += "}";

        return query;
    }
}
</code>```

This works for both queries and mutations. Examples of usage are:

```<code>var query = GraphQlObjectParser.Parse("query", "users", new[] { "id", "name" });
</code>```

will give you

```<code>query{users{id,name}}
</code>```

or

```<code>var query = GraphQlObjectParser.Parse("query", "user", new[] { "id", "name" }, new User { Id = 1 });
</code>```

will give you

```<code>query{user(id:1){id,name}}
</code>```

or

```<code>var query = GraphQlObjectParser.Parse("mutation", "user", new[] { "id", "name" }, new User { Id = 1, Name = "John" }, "data");
</code>```

will give you

```<code>mutation{user(data:{id:1,name:"John"}){id,name}}
</code>```

It'll work with enums which is why I needed this solution in the first place. You can pass in a sub selection without the object or the object without an object type name. I've tried to cover as many bases as possible although I've not yet catered for sub selection of a sub selection. I'll update here if/when I code this one.

Hope it helps someone.

Body:
Update - 13/02/2018

I have since updated this monstrosity to cater for nested sub selections and GraphQl enums so if anyone is interested here it is in GitHub

Orignal answer

I've got the same requirement. Couldn't find anything out there so I've come up with this very inelegant solution. It works for my scenarios so I'll post it here for anyone else looking for a solution.

 public static class GraphQlObjectParser
{
    public static string Parse(string queryType, string queryName, string[] subSelection, object @object = null, string objectTypeName = null)
    {
        var query = queryType + "{" + queryName;

        if (@object != null)
        {
            query += "(";

            if (objectTypeName != null)
            {
                query += objectTypeName + ":" + "{";
            }

            var queryData = string.Empty;
            foreach (var propertyInfo in @object.GetType().GetProperties())
            {
                var value = propertyInfo.GetValue(@object);
                if (value != null)
                {
                    var type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
                    var valueQuotes = type == typeof(string) ? "\"" : string.Empty;

                    var queryPart = char.ToLowerInvariant(propertyInfo.Name[0]) + propertyInfo.Name.Substring(1) + ":" + valueQuotes + value + valueQuotes;
                    queryData += queryData.Length > 0 ? "," + queryPart : queryPart;
                }
            }
            query += (objectTypeName != null ? queryData + "}" : queryData) + ")";
        }

        if (subSelection.Length > 0)
        {
            query += subSelection.Aggregate("{", (current, s) => current + (current.Length > 1 ? "," + s : s)) + "}";
        }

        query += "}";

        return query;
    }
}

This works for both queries and mutations. Examples of usage are:

var query = GraphQlObjectParser.Parse("query", "users", new[] { "id", "name" });

will give you

query{users{id,name}}

or

var query = GraphQlObjectParser.Parse("query", "user", new[] { "id", "name" }, new User { Id = 1 });

will give you

query{user(id:1){id,name}}

or

var query = GraphQlObjectParser.Parse("mutation", "user", new[] { "id", "name" }, new User { Id = 1, Name = "John" }, "data");

will give you

mutation{user(data:{id:1,name:"John"}){id,name}}

It'll work with enums which is why I needed this solution in the first place. You can pass in a sub selection without the object or the object without an object type name. I've tried to cover as many bases as possible although I've not yet catered for sub selection of a sub selection. I'll update here if/when I code this one.

Hope it helps someone.


问:
PHP return array if breaking chain in singleton
I've built a singleton class with chaining methods (to be used in a template).

To make chaining work I need to return new static. It allows the next chain to be added. The problem I have is that I don't want to return the static object if there are no more chains.

Example

```<code><?php
class bread {
  public static $array;
  public static function blueprints() {
    static::$array = array('some', 'values');
    return new static;
  }
  public static function fields() {
    return static::$array;
  }
}

$blueprints = bread::blueprints();
$fields = bread::blueprints()->fields();

print_r($blueprint) // Returns object - FAIL
print_r($fields ) // Returns array - OK
</code>```

In the example above I want $blueprints to return an array, because there are no more methods chained on it.

How can that be done?

答:
The simple answer is you cannot do what you want.
Method chaining is not a special thing for Php.
For your example

```<code>bread::blueprints()->fields();
</code>```

This is not different than:

```<code>$tmp = bread::blueprints();
$tmp->fields();
</code>```

So because of the Php does not know the context where the result will be used of it cannot change the return type.
Here is another version of this question:
Check if call is method chaining

However, your class can implement ArrayAccess interface.This will allow you to treat the object like an array without casting and you get total control over how the members are used.

Body:
I've built a singleton class with chaining methods (to be used in a template).

To make chaining work I need to return new static. It allows the next chain to be added. The problem I have is that I don't want to return the static object if there are no more chains.

Example

<?php
class bread {
  public static $array;
  public static function blueprints() {
    static::$array = array('some', 'values');
    return new static;
  }
  public static function fields() {
    return static::$array;
  }
}

$blueprints = bread::blueprints();
$fields = bread::blueprints()->fields();

print_r($blueprint) // Returns object - FAIL
print_r($fields ) // Returns array - OK

In the example above I want $blueprints to return an array, because there are no more methods chained on it.

How can that be done?

Body:
The simple answer is you cannot do what you want.
Method chaining is not a special thing for Php.
For your example

bread::blueprints()->fields();

This is not different than:

$tmp = bread::blueprints();
$tmp->fields();

So because of the Php does not know the context where the result will be used of it cannot change the return type.
Here is another version of this question:
Check if call is method chaining

However, your class can implement ArrayAccess interface.This will allow you to treat the object like an array without casting and you get total control over how the members are used.


问:
Python lambda function to calculate factorial of a number
I have just started learning python. I came across lambda functions. On one of the problems, the author asked to write a one liner lambda function for factorial of a number.

This is the solution that was given:

```<code>num = 5
print (lambda b: (lambda a, b: a(a, b))(lambda a, b: b*a(a, b-1) if b > 0 else 1,b))(num)
</code>```

I cannot understand the weird syntax. What does a(a,b) mean?

Can someone explain?

Thanks

答:
It is this simple:</p>

```<code>n=input()

print reduce(lambda x,y:x*y,range(1,n+1))
</code>```

Body:
I have just started learning python. I came across lambda functions. On one of the problems, the author asked to write a one liner lambda function for factorial of a number.

This is the solution that was given:

num = 5
print (lambda b: (lambda a, b: a(a, b))(lambda a, b: b*a(a, b-1) if b > 0 else 1,b))(num)

I cannot understand the weird syntax. What does a(a,b) mean?

Can someone explain?

Thanks

Body:
It is this simple:

n=input()

print reduce(lambda x,y:x*y,range(1,n+1))


问:
Returning HTML or JSON based on header type Nodejs
My nodeJS Api needs to return HTML or Json based on the header. If the header is:

```<code>Accept = application/json
</code>```

The Api needs to return Json else my Api needs to return a HTML file.

this is the code I use on my routes:

```<code>var app = express();
app.use('/auth', require('./routes/Authenticate'));
</code>```

In the Authenticate file I catch /login, and do the login stuff. if it succeeds I redirect to /users. In the /users I check for the Accept with an if statement:

```<code>router.get('/users', function(req,res){
    if(req.get('Accept') === 'application/json'){
       res.json({ success: true, user: req.user });
    } else {
        res.render("account/profile") //redirect to the file
    }
});
</code>```

This works(from this solution) but is there a better way? Because there are like 20 endpoints and the application is growing and this will be a mess for every endpoint.

答:
you can split these actions into 2 functions. One to verify the content type and an other to doing your actions.

```<code>router.get('/users', checkIfJson, action);

function checkIfJson(req, res, next) {
    if(!(req.get('Content-Type') === 'application/json')) {
        res.render("account/profile");
        return;
    }
    next();
}

function action(req, res) {
    res.json({ success: true, user: req.user });
    return;
}
</code>```

If you write your code like that you can reuse your checkIfJson into other routes.

Body:
My nodeJS Api needs to return HTML or Json based on the header. If the header is:

Accept = application/json

The Api needs to return Json else my Api needs to return a HTML file.

this is the code I use on my routes:

var app = express();
app.use('/auth', require('./routes/Authenticate'));

In the Authenticate file I catch /login, and do the login stuff. if it succeeds I redirect to /users. In the /users I check for the Accept with an if statement:

router.get('/users', function(req,res){
    if(req.get('Accept') === 'application/json'){
       res.json({ success: true, user: req.user });
    } else {
        res.render("account/profile") //redirect to the file
    }
});

This works(from this solution) but is there a better way? Because there are like 20 endpoints and the application is growing and this will be a mess for every endpoint.

Body:
you can split these actions into 2 functions. One to verify the content type and an other to doing your actions.

router.get('/users', checkIfJson, action);

function checkIfJson(req, res, next) {
    if(!(req.get('Content-Type') === 'application/json')) {
        res.render("account/profile");
        return;
    }
    next();
}

function action(req, res) {
    res.json({ success: true, user: req.user });
    return;
}

If you write your code like that you can reuse your checkIfJson into other routes.


问:
Determine if a Word cell is merged
I need to programmatically add and remove rows from a Word 2010 table.  Unfortunately the header of the table contains merged cells, both horizontally and vertically merged.  That causes an error when using the Row.Add and Row.Delete methods.  I have tested and discovered that I can programmically remove the merged cells (Cell.Split) and then do the .Add and .Delete methods and then restore the merged cells.  The problem I'm having is identifying which cells that are merged.

```<code>-------------------------
| 1,1 | 1,2 | 1,3 | 1,4 |
-------------------------
| 2,1 | 2,2 | 2,3 | 2,4 |
-------------------------
</code>```

If cells 1,1 and 2,1 are vertically merged then accessing Table.Cell(2,1) throws an error.  Which is good.  But, if cells 1,1 and 1,2 are horizontally merged, accessing 1,2 does not throw an error but accessing 1,4 does.  Which means that I can't determine which cells are horizontally merged.

What I'm trying to do is let the design people change the look and feel of a Word document but the data in the table is populated by an SQL query that people fill in using a web app.

My question, is there a way to determine the layout of a table so that I can remove the merged cells and recreate them after adding and removing rows?

Thanks,
Aaron

答:
When dealing with tables that might contain merged cells, you always have to start with CELL(1,1) and step through the cells using CELL.NEXT (Next is a property of the CELL object)

If you do that, you can interrogate what row and column the "current" cell is. You +can not+ reference cells by row col directly in tables with merged cells or you'll get the error you mention.

Then just continue through till NEXT returns nothing.

Title: Determine if a Word cell is merged

Body:
I need to programmatically add and remove rows from a Word 2010 table.  Unfortunately the header of the table contains merged cells, both horizontally and vertically merged.  That causes an error when using the Row.Add and Row.Delete methods.  I have tested and discovered that I can programmically remove the merged cells (Cell.Split) and then do the .Add and .Delete methods and then restore the merged cells.  The problem I'm having is identifying which cells that are merged.

-------------------------
| 1,1 | 1,2 | 1,3 | 1,4 |
-------------------------
| 2,1 | 2,2 | 2,3 | 2,4 |
-------------------------

If cells 1,1 and 2,1 are vertically merged then accessing Table.Cell(2,1) throws an error.  Which is good.  But, if cells 1,1 and 1,2 are horizontally merged, accessing 1,2 does not throw an error but accessing 1,4 does.  Which means that I can't determine which cells are horizontally merged.

What I'm trying to do is let the design people change the look and feel of a Word document but the data in the table is populated by an SQL query that people fill in using a web app.

My question, is there a way to determine the layout of a table so that I can remove the merged cells and recreate them after adding and removing rows?

Thanks,
Aaron


问:
Use of variable in adding data to Values field of Pivot Chart using VBA
I have a data set which looks something like this
Dataset
However my number of days is a variable and will keep on changing.

I want to use VBA to create a Pivot Chart, the code as below:

```<code>Sheets("Initialize").Select
NoRes = Cells(6, 3).Value
Sheets("Metric Calculations").Select
ProjDur = Cells(31, 4).Value
Range(Cells(31, 61), Cells(30 + NoRes, 61 + ProjDur)).Select
Selection.Copy
Sheets("Resource Histogram Data").Select
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Range(Cells(1, 1), Cells(1 + NoRes, 1 + ProjDur)).Select
Application.CutCopyMode = False
r = 1 + NoRes
p = 1 + ProjDur
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Sheets("Resource Histogram Data").Range(Cells(1, 1), Cells(r, p)), Version:=6). _
    CreatePivotTable TableDestination:="Sheet1!R1C1", TableName:="PivotTable1", DefaultVersion:=6
Sheets("Sheet1").Select
Cells(1, 1).Select
ActiveWorkbook.ShowPivotTableFieldList = True
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$C$18")
With ActiveChart.PivotLayout.PivotTable.PivotFields("Resources")
    .Orientation = xlPageField
    .Position = 1
End With
    ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
        PivotTable.PivotFields("Day 1"), "Sum of Day 1", xlSum
    ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
        PivotTable.PivotFields("Day 2"), "Sum of Day 2", xlSum
    ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
        PivotTable.PivotFields("Day 3"), "Sum of Day 3", xlSum
ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day 4"), "Sum of Day 4", xlSum
ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day 5"), "Sum of Day 5", xlSum
ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day 6"), "Sum of Day 6", xlSum
ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day 7"), "Sum of Day 7", xlSum
ActiveChart.ShowValueFieldButtons = False
</code>```

In the last part of the code in which the AddDataField is repeated for seven time. When the number of days will vary (between 1 to 200) this ideally should be in a for loop. However doing this obviously doesnt work.

```<code>For i = 1 To ProjDur
    ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day i"), "Sum of Day i", xlSum
Next i
</code>```

How do i get this for loop function included in my code?

答:
It would be:</p>

```<code>For i = 1 To ProjDur
    ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day " & i), "Sum of Day " & i, xlSum
Next i
</code>```

Body:
I have a data set which looks something like this
Dataset
However my number of days is a variable and will keep on changing.

I want to use VBA to create a Pivot Chart, the code as below:

Sheets("Initialize").Select
NoRes = Cells(6, 3).Value
Sheets("Metric Calculations").Select
ProjDur = Cells(31, 4).Value
Range(Cells(31, 61), Cells(30 + NoRes, 61 + ProjDur)).Select
Selection.Copy
Sheets("Resource Histogram Data").Select
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Range(Cells(1, 1), Cells(1 + NoRes, 1 + ProjDur)).Select
Application.CutCopyMode = False
r = 1 + NoRes
p = 1 + ProjDur
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Sheets("Resource Histogram Data").Range(Cells(1, 1), Cells(r, p)), Version:=6). _
    CreatePivotTable TableDestination:="Sheet1!R1C1", TableName:="PivotTable1", DefaultVersion:=6
Sheets("Sheet1").Select
Cells(1, 1).Select
ActiveWorkbook.ShowPivotTableFieldList = True
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$C$18")
With ActiveChart.PivotLayout.PivotTable.PivotFields("Resources")
    .Orientation = xlPageField
    .Position = 1
End With
    ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
        PivotTable.PivotFields("Day 1"), "Sum of Day 1", xlSum
    ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
        PivotTable.PivotFields("Day 2"), "Sum of Day 2", xlSum
    ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
        PivotTable.PivotFields("Day 3"), "Sum of Day 3", xlSum
ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day 4"), "Sum of Day 4", xlSum
ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day 5"), "Sum of Day 5", xlSum
ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day 6"), "Sum of Day 6", xlSum
ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day 7"), "Sum of Day 7", xlSum
ActiveChart.ShowValueFieldButtons = False

In the last part of the code in which the AddDataField is repeated for seven time. When the number of days will vary (between 1 to 200) this ideally should be in a for loop. However doing this obviously doesnt work.

For i = 1 To ProjDur
    ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day i"), "Sum of Day i", xlSum
Next i

How do i get this for loop function included in my code?

Body:
It would be:

For i = 1 To ProjDur
    ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day " & i), "Sum of Day " & i, xlSum
Next i


问:
Sorting only a part of object/array in PHP
I've been struggling around this for a while now and can't seem to get the right algorithm.

What I want is to sort this:

```<code>$variable = '{
    "0": {
            "id": "0",
            "code": "main_colour",
            "label": "Main Colour",
            "options": [{
                "id": "825",
                "label": "White",
                "products": ["1", "2", "3"]
            }, {
                "id": "840",
                "label": "Cream",
                "products": ["3", "4", "5"]
            }],
            "position": "0"
        },
    "2": {
           "id": "0",
            "code": "size",
            "label": "Size",
            "options": [{
                "id": "825",
                "label": "S",
                "products": ["1", "2", "3"]
            }, {
                "id": "840",
                "label": "M",
                "products": ["3", "4", "5"]
            }],
            "position": "0"
        }
}';
</code>```

And the output would be

```<code>$variable = '{
        "0": {
                "id": "0",
                "code": "main_colour",
                "label": "Main Colour",
                "options": [{
                    "id": "840",
                    "label": "Cream",
                    "products": ["3", "4", "5"]
                },{
                    "id": "825",
                    "label": "White",
                    "products": ["1", "2", "3"]
                }],
                "position": "0"
            },
        "2": {
               "id": "0",
                "code": "size",
                "label": "Size",
                "options": [{
                    "id": "840",
                    "label": "M",
                    "products": ["3", "4", "5"]
                }, {
                    "id": "825",
                    "label": "S",
                    "products": ["1", "2", "3"]
                }],
                "position": "0"
            }
    }';
</code>```

So basically it should be sorted using the label inside the "options" without affecting the other fields. I've been trying usort and tried different algorithms but to no avail.

Current code that sorts only the outside "label" and not the inner label:

```<code>function optionsSort($a, $b) {
return strcmp($a['options'][0]['label'], $b['options'][0]['options']['label']);
}
usort($variable, "optionsSort"));
</code>```

答:
Here's the code:</p>

```<code>// your array
$variable = '{
    "0": {
            "id": "0",
            "code": "main_colour",
            "label": "Main Colour",
            "options": [{
                "id": "825",
                "label": "White",
                "products": ["1", "2", "3"]
            }, {
                "id": "840",
                "label": "Cream",
                "products": ["3", "4", "5"]
            }],
            "position": "0"
        },
    "2": {
           "id": "0",
            "code": "size",
            "label": "Size",
            "options": [{
                "id": "825",
                "label": "S",
                "products": ["1", "2", "3"]
            }, {
                "id": "840",
                "label": "M",
                "products": ["3", "4", "5"]
            }],
            "position": "0"
        }
}';

$a = json_decode($variable);
foreach ($a as $item) {
    // sorting function
    usort($item->options, function($a, $b) { return strcmp($a->label, $b->label); });
}
</code>```

Body:
I've been struggling around this for a while now and can't seem to get the right algorithm.

What I want is to sort this:

$variable = '{
    "0": {
            "id": "0",
            "code": "main_colour",
            "label": "Main Colour",
            "options": [{
                "id": "825",
                "label": "White",
                "products": ["1", "2", "3"]
            }, {
                "id": "840",
                "label": "Cream",
                "products": ["3", "4", "5"]
            }],
            "position": "0"
        },
    "2": {
           "id": "0",
            "code": "size",
            "label": "Size",
            "options": [{
                "id": "825",
                "label": "S",
                "products": ["1", "2", "3"]
            }, {
                "id": "840",
                "label": "M",
                "products": ["3", "4", "5"]
            }],
            "position": "0"
        }
}';

And the output would be

$variable = '{
        "0": {
                "id": "0",
                "code": "main_colour",
                "label": "Main Colour",
                "options": [{
                    "id": "840",
                    "label": "Cream",
                    "products": ["3", "4", "5"]
                },{
                    "id": "825",
                    "label": "White",
                    "products": ["1", "2", "3"]
                }],
                "position": "0"
            },
        "2": {
               "id": "0",
                "code": "size",
                "label": "Size",
                "options": [{
                    "id": "840",
                    "label": "M",
                    "products": ["3", "4", "5"]
                }, {
                    "id": "825",
                    "label": "S",
                    "products": ["1", "2", "3"]
                }],
                "position": "0"
            }
    }';

So basically it should be sorted using the label inside the "options" without affecting the other fields. I've been trying usort and tried different algorithms but to no avail.

Current code that sorts only the outside "label" and not the inner label:

function optionsSort($a, $b) {
return strcmp($a['options'][0]['label'], $b['options'][0]['options']['label']);
}
usort($variable, "optionsSort"));

Body:
Here's the code:

// your array
$variable = '{
    "0": {
            "id": "0",
            "code": "main_colour",
            "label": "Main Colour",
            "options": [{
                "id": "825",
                "label": "White",
                "products": ["1", "2", "3"]
            }, {
                "id": "840",
                "label": "Cream",
                "products": ["3", "4", "5"]
            }],
            "position": "0"
        },
    "2": {
           "id": "0",
            "code": "size",
            "label": "Size",
            "options": [{
                "id": "825",
                "label": "S",
                "products": ["1", "2", "3"]
            }, {
                "id": "840",
                "label": "M",
                "products": ["3", "4", "5"]
            }],
            "position": "0"
        }
}';

$a = json_decode($variable);
foreach ($a as $item) {
    // sorting function
    usort($item->options, function($a, $b) { return strcmp($a->label, $b->label); });
}


问:
How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?
I want to downgrade php version from 7.1.1 to 5.6 in xampp 7.1.1. But I can't find any option.

答:
Change the .htaccess code to switch to PHP 5.6:</p>

```<code>AddHandler application/x-httpd-php56 .php
</code>```

Body:
Change the .htaccess code to switch to PHP 5.6:

AddHandler application/x-httpd-php56 .php


问:
Encapsulation confusion
I'm not sure how to correctly encapsulate objects.

Example:

```<code>struct Car {
    int wheels = 0;
    int doors = 0;
};

class A{
    Car myCar;

public:
// 1st method
    Car getCar() const { return myCar; }
    void setCar(Car c) { myCar = c; }
// 2nd method
    Car &getCarReference() { return myCar; }
// 3rd method
    Car *getCarPointer() { return &myCar; }
};
</code>```

As I understand 1st method makes a copy of my structure which is fine if structure is small like shown in example. But what if structure contains 100 000 double values. Should I then use 2nd method? Or declare structure pointer, dynamically allocate memory and use 3rd method?

答:
I assume what you want is this:

Some class, A, wraps another class, Car. It should be possible to access the Car element of A, however, you can't make the Car element public since there is potential for inconsistency of the wrapper class if somebody should then change that element (if not, then simply make it public).

If so, go with a const reference:

```<code>const Car& getConstCarReference() const { return myCar; }
</code>```

This is then called like

```<code>const Car& car = instanceOfA.getConstCarReference();
</code>```

And after that, you can use any constant call on car.

Returning a pointer, by the way, is in most cases a bad idea. Essentially, whenever you think of returning a pointer, you should be able to clearly argue why returning a pointer is the best solution.

That said, I recommend to abstain from method names like "get" and "set". Make the code looking more like a clockwork instead of handling organic classes. I'd recommend you to name the method simply car, as in const Car& car() const { return m_car; }, the member variable in hungarian notation as you see (not important that you use hungarian notation, but I recommend to clearly mark member variables, at least if the class is not very small. Going with something like _car or car_ for the member also works well.)

Title: Encapsulation confusion

Body:
I'm not sure how to correctly encapsulate objects.

Example:

struct Car {
    int wheels = 0;
    int doors = 0;
};

class A{
    Car myCar;

public:
// 1st method
    Car getCar() const { return myCar; }
    void setCar(Car c) { myCar = c; }
// 2nd method
    Car &getCarReference() { return myCar; }
// 3rd method
    Car *getCarPointer() { return &myCar; }
};

As I understand 1st method makes a copy of my structure which is fine if structure is small like shown in example. But what if structure contains 100 000 double values. Should I then use 2nd method? Or declare structure pointer, dynamically allocate memory and use 3rd method?

Body:
I assume what you want is this:

Some class, A, wraps another class, Car. It should be possible to access the Car element of A, however, you can't make the Car element public since there is potential for inconsistency of the wrapper class if somebody should then change that element (if not, then simply make it public).

If so, go with a const reference:

const Car& getConstCarReference() const { return myCar; }

This is then called like

const Car& car = instanceOfA.getConstCarReference();

And after that, you can use any constant call on car.

Returning a pointer, by the way, is in most cases a bad idea. Essentially, whenever you think of returning a pointer, you should be able to clearly argue why returning a pointer is the best solution.

That said, I recommend to abstain from method names like "get" and "set". Make the code looking more like a clockwork instead of handling organic classes. I'd recommend you to name the method simply car, as in const Car& car() const { return m_car; }, the member variable in hungarian notation as you see (not important that you use hungarian notation, but I recommend to clearly mark member variables, at least if the class is not very small. Going with something like _car or car_ for the member also works well.)


问:
TFS and golang continuous Integration
I'm tracking the files of my golang app in a local TFS server integrated with git. I want to define build, test, and deploy steps but I can't find any tool for that.

How can I define a build and test step for the project that shows the test results in the Team's web site? thank you.

答:
You can use the vNext build system in TFS2017 and add Command Line task in the build definition to run the build and test just like what you do on local machine:

And then add a "Publish Test Result" task to publish the test result to TFS so that you can check the test result from the TFS Website. A limitation is that "Publish Test Result" task only support four Test Result Format for now: JUnit, NUnit, VSTest and XUnit.

Title: TFS and golang continuous Integration


问:
Why I am getting null value while parsing json object in servlet
My Json Object from postman:

```<code>{
    "sender":"hello"
}
</code>```

My servlet dopost method:

```<code>protected void doPost(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {

    Gson gs = new Gson();
    String chatId = gs.fromJson(req.getParameter("sender"), String.class);
    JSONObject obj = new JSONObject();

    JSONArray arr= new JSONArray();
    try {
        obj.put("name", chatId);
        arr.add(obj);
    }
    finally {
    }
    resp.setContentType("application/json");
    resp.setCharacterEncoding("utf-8");
    resp.getWriter().println(arr);
}
</code>```

What am I doing wrong?

答: I think JSON will come in request body. Refer Get the POST request body from HttpServletRequest to read the requestbody from HttpServletRequest.</p>

Body:
My Json Object from postman:

{
    "sender":"hello"
}

My servlet dopost method:

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {

    Gson gs = new Gson();
    String chatId = gs.fromJson(req.getParameter("sender"), String.class);
    JSONObject obj = new JSONObject();

    JSONArray arr= new JSONArray();
    try {
        obj.put("name", chatId);
        arr.add(obj);
    }
    finally {
    }
    resp.setContentType("application/json");
    resp.setCharacterEncoding("utf-8");
    resp.getWriter().println(arr);
}

What am I doing wrong?


问:
jQuery, converting from a .POST to .AJAX with a method?
I have the following:

```<code>    $.post(this.href, { _method: 'delete' }, null, "script");
</code>```

How can I convert that to a:

```<code>$.ajax({
    type: "POST",
    url: ,
    data: ,
    beforeSend: function() {
    },
    success: function() {
</code>```

I'm not use how to deal with URL or how to add the _method: 'delete' where does that go with .ajax?

thanks

答:
here's an example of a method i use in my application, note the URL and data parameters will be your this.href and _methods:"delete"</p>

```<code>function OnChangeRoom(RoomID) {
    $.ajax({
        type: "POST",
        url: "../server.asmx/GetWordFromRoomID",
        data: "{'RoomID':'" + RoomID + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {
            if (data.d.length == 0)
                $('#spanWord').html(' ');
            else
                $('#spanWord').html('Word: ' + data.d);
        }
    });
}
</code>```

Body:
I have the following:

    $.post(this.href, { _method: 'delete' }, null, "script");

How can I convert that to a:

$.ajax({
    type: "POST",
    url: ,
    data: ,
    beforeSend: function() {
    },
    success: function() {

I'm not use how to deal with URL or how to add the _method: 'delete' where does that go with .ajax?

thanks

Body:
here's an example of a method i use in my application, note the URL and data parameters will be your this.href and _methods:"delete"

function OnChangeRoom(RoomID) {
    $.ajax({
        type: "POST",
        url: "../server.asmx/GetWordFromRoomID",
        data: "{'RoomID':'" + RoomID + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {
            if (data.d.length == 0)
                $('#spanWord').html(' ');
            else
                $('#spanWord').html('Word: ' + data.d);
        }
    });
}


问:
Python find succesive numbers in array/list
I have an array like this arr = [1,2,3,10,11,15] from which I want to have the numbers left and right of each block of successive numbers, i.e. [0,4,9,12,14,16].

答:
an unpretty way of doing this:</p>

```<code>def getMissing( lst ):
    a = sorted(lst) # in case its not already sorted
    a.append( a[-1] + 10000) #insert one dummy bigger to ease iteration
    missing = []

    for i in xrange(len(a)-1):
        if a[i] - a[i-1] != 1:
            missing.append( a[i] -1)
        if a[i+1] - a[i] != 1:
            missing.append( a[i] +1)
    return missing

print getMissing([1,2,3,10,11,15])
</code>```

Body:
an unpretty way of doing this:

def getMissing( lst ):
    a = sorted(lst) # in case its not already sorted
    a.append( a[-1] + 10000) #insert one dummy bigger to ease iteration
    missing = []

    for i in xrange(len(a)-1):
        if a[i] - a[i-1] != 1:
            missing.append( a[i] -1)
        if a[i+1] - a[i] != 1:
            missing.append( a[i] +1)
    return missing

print getMissing([1,2,3,10,11,15])


问:
Add Alt text on Media Images while uploading - Umbraco
I am using Umbraco 7.5.3 and I want to add an alt text to media images while uploading or while selecting (On clicking submit) them using media picker. Is this possible?

I have added a property to Image Media Type. This way it is available for all the images I have in the CMS.

But another question I am getting stucked with. Is it good or bad to change inbuilt Umbraco data types?

Any help appreciated.

Thanks in advance!

答:
It's not currently possible to add ALT text to images whilst uploading / selecting images using the standard media picker.

To fulfil this functionality you would need to extend the data type.

Extending existing datatypes & creating new data types is encouraged, Umbraco is an open source project so you could even create a pull request on GitHub.

I would be very interested as this is a feature that I also would like to see in core.


问:
C++ array pointer
I came across a C++ program like this

```<code>#include<iostream>
using namespace std;

int main() {
    int N = 10;
    int M = 2;
    int a[] = { 2,1,4,3,6,5,8,7,10,9 };
    int(*b)[5] = (int(*)[5]) a;
    for (int i = 0; i<M; i++) {
        for (int j = 0; j<N / M; j++) {
            cout << b[i][j] << endl;
        }
    }

    system("pause");
    return 0;
}
</code>```

The above program's output is 2,1,4,3,6,5,8,7,10,9. It looks like b is an array point. So what does (int(*)[5]) a mean? Can someone help me to explain it?

答:
Here, a[] is an array of 10 integers. b is a pointer to an array of 5 elements.

```<code>int(*b)[5] = (int(*)[5]) a;
</code>```

In the above statement the address of the array a[] is type-casted to a pointer to an array of 5 elements. Then, b is accessed as a two dimensional array.

Title: C++ array pointer

Body:
I came across a C++ program like this

#include<iostream>
using namespace std;

int main() {
    int N = 10;
    int M = 2;
    int a[] = { 2,1,4,3,6,5,8,7,10,9 };
    int(*b)[5] = (int(*)[5]) a;
    for (int i = 0; i<M; i++) {
        for (int j = 0; j<N / M; j++) {
            cout << b[i][j] << endl;
        }
    }

    system("pause");
    return 0;
}

The above program's output is 2,1,4,3,6,5,8,7,10,9. It looks like b is an array point. So what does (int(*)[5]) a mean? Can someone help me to explain it?

Body:
Here, a[] is an array of 10 integers. b is a pointer to an array of 5 elements.

int(*b)[5] = (int(*)[5]) a;

In the above statement the address of the array a[] is type-casted to a pointer to an array of 5 elements. Then, b is accessed as a two dimensional array.


问:
Python loop and invalid answer
This is what I'm working just a little yes/no question.

```<code>print("Hello")
print("I love you")
answer = input("Do you love me?")
if answer in ["yes"]:
  print("Yey! I knew it! Thank You!")
if answer in ["no"]:
  print("O-ok, I understand, no worries.")

while True:
  try:
    print("Please answer me.")
    answer = input("Do you love me?")
  except ValueError:
   continue
  if answer in ["yes", "no"]:
    break
</code>```

When I enter a valid answer it print what I want but also jumps into the loop asking again, if I answer again then it breaks. I don't understand why tho.
When I enter an invalid answer it loops until it gets one right, when it gets one right it breaks but doesn't answer. Can someone please explain why?

Here is where I have been currently testing it: https://trinket.io/python/5a25117b84

答:
By the your code that's the way it is should work. Look, this part of the code respond of the first question ("Do you love me?"):

```<code>#
# First part of your code
#
print("Hello")
print("I love you")
answer = input("Do you love me?")
if answer in ["yes"]:
  print("Yey! I knew it! Thank You!")
if answer in ["no"]:
  print("O-ok, I understand, no worries.")
</code>```

after your answer you "jump" into the second part of the code ("loop asking again"):

```<code>#
# Second part of your code
#
while True:
  try:
    print("Please answer me.")
    answer = input("Do you love me?")
  except ValueError:
    continue
  if answer in ["yes", "no"]:
    break
</code>```

You need to delete/remove the second part of the your code. Part with loop/cycle:

```<code>while True:
  try:
    print("Please answer me.")
    answer = input("Do you love me?")
  except ValueError:
    continue
  if answer in ["yes", "no"]:
    break
</code>```

Or you can use a loop a good example is in the answer from Ni3_k.

Title: Python loop and invalid answer

Body:
This is what I'm working just a little yes/no question.

print("Hello")
print("I love you")
answer = input("Do you love me?")
if answer in ["yes"]:
  print("Yey! I knew it! Thank You!")
if answer in ["no"]:
  print("O-ok, I understand, no worries.")

while True:
  try:
    print("Please answer me.")
    answer = input("Do you love me?")
  except ValueError:
   continue
  if answer in ["yes", "no"]:
    break

When I enter a valid answer it print what I want but also jumps into the loop asking again, if I answer again then it breaks. I don't understand why tho.
When I enter an invalid answer it loops until it gets one right, when it gets one right it breaks but doesn't answer. Can someone please explain why?

Here is where I have been currently testing it: https://trinket.io/python/5a25117b84

Body:
By the your code that's the way it is should work. Look, this part of the code respond of the first question ("Do you love me?"):

#
# First part of your code
#
print("Hello")
print("I love you")
answer = input("Do you love me?")
if answer in ["yes"]:
  print("Yey! I knew it! Thank You!")
if answer in ["no"]:
  print("O-ok, I understand, no worries.")

after your answer you "jump" into the second part of the code ("loop asking again"):

#
# Second part of your code
#
while True:
  try:
    print("Please answer me.")
    answer = input("Do you love me?")
  except ValueError:
    continue
  if answer in ["yes", "no"]:
    break

You need to delete/remove the second part of the your code. Part with loop/cycle:

while True:
  try:
    print("Please answer me.")
    answer = input("Do you love me?")
  except ValueError:
    continue
  if answer in ["yes", "no"]:
    break

Or you can use a loop a good example is in the answer from Ni3_k.


问:
Run script and php after form submission
I have an html form like this:

```<code><form method="get" action="save.php">
<input type="email" id="email" name="email"/>
<input type="submit" name="submit" value="Submit" />
</form>
</code>```

and in save.php i have something like this:

```<code><?php
session_start();

$email = $_REQUEST['email'];
$email_content = "Thank you for your subscription";
mail($email,"Thank you",$email_content);
header("Location:thankyou.php");
?>
</code>```

Now in save.php file i need to send this e-mail but also to echo a script that runs a js function. For example

```<code><?php
    echo "<script>";
    echo "<script src='my_path_to_file/file.js'></script>";
    echo "var subscriberEmail = '" . $email . "';";
    echo "mySubscribe(subscriberEmail);";
    echo "</script>";
 ?>
</code>```

Now, if i place the echoing of the script before mail(), then i don't go to thankyou.php, mail() is not executed, i don't go to thankyou.php but script function works. If i place echoing of script after mail, then mail is sent, i go to thankyou.php but script function is not executed at all.

Any ideas to make both happen?

Thank you in advance

答: Possibly some error in mySubscribe(subscriberEmail); function. Thats is why if you put script before email and header("Location:thankyou.php");  it not sending mail and redirects you. And also if you put script before,  $email variable is not set yet</p>

Body:
I have an html form like this:

<form method="get" action="save.php">
<input type="email" id="email" name="email"/>
<input type="submit" name="submit" value="Submit" />
</form>

and in save.php i have something like this:

<?php
session_start();

$email = $_REQUEST['email'];
$email_content = "Thank you for your subscription";
mail($email,"Thank you",$email_content);
header("Location:thankyou.php");
?>

Now in save.php file i need to send this e-mail but also to echo a script that runs a js function. For example

<?php
    echo "";
    echo "var subscriberEmail = '" . $email . "';";
    echo "mySubscribe(subscriberEmail);";
    echo "</script>";
 ?>

Now, if i place the echoing of the script before mail(), then i don't go to thankyou.php, mail() is not executed, i don't go to thankyou.php but script function works. If i place echoing of script after mail, then mail is sent, i go to thankyou.php but script function is not executed at all.

Any ideas to make both happen?

Thank you in advance


问:
Requires simple explanation on Arbiter's role in a given mongoDB replica set
I came across MongoDB official site explaining on having odd number of members replica set up. I also heard of the term Arbiter from the same site, which based on my understanding, it will not be elected as primary and it does participate on election (from https://docs.mongodb.com/manual/core/replica-set-arbiter/).

There is also a post related to Arbiter in Why do we need an 'arbiter' in MongoDB replication? which then relates to CAP theorem, which further gets things more complicated.

First of all, why do we need to make the number of members odd? Also, can someone explain to me what this Arbiter is and what is its role in a given replica set in simple layman English??

Thanks in advance.

答:
In short: it is to stop the two normal nodes of the replica set getting into a split-brain situation if they lose contact with each other.

MongoDB replica sets are designed so that, if one or more members goes down or loses contact, the other members are able to keep going as long as between them they have a majority. The majority clause is important: without that, you might have a situation where the network is split in two, and the nodes on each side of the partition think that they're still carrying on the replica set, and end up with different sets of data.

So to avoid the split brain problem, the nodes of a replica set will not continue if they can't command an absolute majority. An example of this is if you have two nodes, in a replica set like this:

If they lose communication, the outcome is symmetrical:

Each one will reason the same way:

realise it has lost communication with the other

assess whether it is possible to keep the replica set going

realise that 1 node (out of 2) does not constitute a majority

revert to Secondary mode

The difference an Arbiter makes

If there is a third node, then even if the two main nodes lose contact with each other then there will still be one of them in contact with the arbiter. This allows the two main nodes to make different decisions, and keep the replica set going while avoiding the split-brain problem.

Consider the following example of a 3-node replica set:

Whichever way the network partition goes, one node will still be in contact with the arbiter; for example like this:

Node A will:

realise it can contact neither node B nor the arbiter

assess whether it is possible to keep the replica set going

realise that 1 node (out of 3) does not constitute a majority

revert to Secondary mode

Whereas node B is able to react differently:

realise it cannot contact node A, but still has contact with the arbiter

assess whether it is possible to keep the replica set going

realise that 2 nodes (out of 3) do constitute a majority

take over as Primary

This also illustrates how you should deploy an arbiter to get that benefit:

try to put the arbiter on a system independent of both the data-bearing nodes, to maximise the chance of it still being able to communicate with either throughout network problems

it doesn't need to store data, so you don't need high-spec hardware

Just 1 arbiter is enough to break the deadlock; you don't get any benefit from multiple arbiters