问:
How to create elasticsearch aggregation using Java API on scala
I am new to programming and I want to get the sum of power used in a month from a data stored in elasticsearch, I've used sense and got the value but still finding it hard using Java API in scala. This is what I did

```<code>POST /myIndext/myType/_search?search_type=dfs_query_then_fetch
{
"aggs": {
"duration": {
"date_histogram": {
"field": "Day",
"interval": "month",
"format": "yyyy-MM-dd"},
"aggs": {
"Power_total": {
"sum": {
"field": "myField"
}
}
}
}
}
}
</code>```

RESULT WAS

```<code>( "aggregations": {
      "duration": {
         "buckets": [
            {
               "key_as_string": "2017-01-01",
               "key": 1480550400000,
               "doc_count": 619,
               "myField": {
                  "value": 5218.066633789334
               }
            }
</code>```

Then scala code is this

```<code>    val matchquery = QueryBuilders.matchQuery("ID", configurate)

    val queryK = QueryBuilders.matchQuery("ID", configurate)

    val filterA = QueryBuilders.rangeQuery("Day").gte("2017-01-02T00:00:05.383+0100").lte("2017-01-13T00:00:05.383+0100")
    val query = QueryBuilders.filteredQuery(queryK, filteAr)
    val agg = AggregationBuilders.dateHistogram("duration")
      .field("Day")
      .interval(DateHistogramInterval.MONTH)
      .minDocCount(0)
      .extendedBounds(new DateTime("2017-01-01T00:00:05.383+0100"), new DateTime("2017-01-13T00:00:05.383+0100"))
            .subAggregation(AggregationBuilders.sum("power_total").field("myField"))

    val result: SearchResponse = client
      .prepareSearch("myIndex")
      .setTypes("myType")
      .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
      .setQuery(query)
      .addAggregation(agg)
      .addSort("Day", SortOrder.DESC)
      .setSize(815)
      .addField("myField")
      .execute()
      .actionGet()

    val results = result.getHits.getHits
        println("Current results: " + results.length)
        for (hit <- results) {
          println("------------------------------")
          val response = hit.getSource
          println(response)
        }
    client.close()
</code>```

RESULT WAS

```<code>current result = 0
</code>```

Please let me know why am not getting value for "myField" like I got using sense.

I have tried doing it severally and still get same errors, could it be that I don't parse the query response the right way?

答: Everything was correct the only pitfall was that I was querying a date time not stored stored in my database. so instead of "2017-01-01", I was inserting this "2017-01-02"</p>

Body:
I am new to programming and I want to get the sum of power used in a month from a data stored in elasticsearch, I've used sense and got the value but still finding it hard using Java API in scala. This is what I did

POST /myIndext/myType/_search?search_type=dfs_query_then_fetch
{
"aggs": {
"duration": {
"date_histogram": {
"field": "Day",
"interval": "month",
"format": "yyyy-MM-dd"},
"aggs": {
"Power_total": {
"sum": {
"field": "myField"
}
}
}
}
}
}

RESULT WAS

( "aggregations": {
      "duration": {
         "buckets": [
            {
               "key_as_string": "2017-01-01",
               "key": 1480550400000,
               "doc_count": 619,
               "myField": {
                  "value": 5218.066633789334
               }
            }

Then scala code is this

    val matchquery = QueryBuilders.matchQuery("ID", configurate)

    val queryK = QueryBuilders.matchQuery("ID", configurate)

    val filterA = QueryBuilders.rangeQuery("Day").gte("2017-01-02T00:00:05.383+0100").lte("2017-01-13T00:00:05.383+0100")
    val query = QueryBuilders.filteredQuery(queryK, filteAr)
    val agg = AggregationBuilders.dateHistogram("duration")
      .field("Day")
      .interval(DateHistogramInterval.MONTH)
      .minDocCount(0)
      .extendedBounds(new DateTime("2017-01-01T00:00:05.383+0100"), new DateTime("2017-01-13T00:00:05.383+0100"))
            .subAggregation(AggregationBuilders.sum("power_total").field("myField"))

    val result: SearchResponse = client
      .prepareSearch("myIndex")
      .setTypes("myType")
      .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
      .setQuery(query)
      .addAggregation(agg)
      .addSort("Day", SortOrder.DESC)
      .setSize(815)
      .addField("myField")
      .execute()
      .actionGet()

    val results = result.getHits.getHits
        println("Current results: " + results.length)
        for (hit <- results) {
          println("------------------------------")
          val response = hit.getSource
          println(response)
        }
    client.close()

RESULT WAS

current result = 0

Please let me know why am not getting value for "myField" like I got using sense.

I have tried doing it severally and still get same errors, could it be that I don't parse the query response the right way?


来源: stackexchange

问:
Perform lookup and update within a single Django query
I have two models: MetaModel and RelatedModel. I want to include the result of a RelatedModel lookup within a MetaModel query, and I'd like to do this within a single DB call.

I've tried to define a 'subquery' QuerySet for use in the main query, but that hasn't worked - it's still making two queries to complete the operation.

Note: I can't use a traditional ForeignKey relationship because the profile_id field is not unique. Uniqueness is a combination of profile_id and channel. This is an aggregation table and profile_id is not guaranteed to be unique across multiple third-party channels.

Any suggestions?

Models:

```<code>class Channel(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(
        max_length=25,
    )

class MetaModel(models.Model):
    profile_id = fields.IntegerField()
    channel = fields.ForeignKey(Channel))
    metadata = fields.TextField()

class RelatedModel(models.Model):
    related_id = fields.IntegerField()
    profile_id = fields.IntegerField()
    channel = fields.ForeignKey(Channel))
</code>```

Dummy data

```<code>channel = Channel("Web site A")
channel.save()

sample_meta = MetaModel(profile_id=1234, channel=channel)
sample_related = RelatedModel(profile_id=1234, related_id=5678, channel=channel)
</code>```

Query:

```<code># Create a queryset to filter down to the single record we need the `profile_id` for
# I've limited to the only field we need via a `values` operation
related_qs = RelatedAccount.objects.filter(
    related_id=5678,
    channel=channel
).values_list("profile_id", flat=True)

# I'm doing an update_or_create as there is other data to store, not included for brevity
obj, created = MetaModel.objects.update_or_create(
    profile_id=related_qs.first(),  # <<< This var is the dynamic part of the query
    channel=channel,
    defaults={"metadata": "Metadata is added to a new or existing record."}
)
</code>```

答:
Regarding your note on uniqueness, you can use unique_together option in Django as described here in the documentation.

```<code>class MetaModel(models.Model):
    profile_id = fields.ForeignKey(RelatedModel)
    channel = fields.ForeignKey(Channel)
    metadata = fields.TextField()

    class Meta:
        unique_together = ('profile_id', 'channel')
</code>```

Then you can change your query accordingly and should solve your problem.

ContentLicense: CC BY-SA 3.0

Body:
I have two models: MetaModel and RelatedModel. I want to include the result of a RelatedModel lookup within a MetaModel query, and I'd like to do this within a single DB call.

I've tried to define a 'subquery' QuerySet for use in the main query, but that hasn't worked - it's still making two queries to complete the operation.

Note: I can't use a traditional ForeignKey relationship because the profile_id field is not unique. Uniqueness is a combination of profile_id and channel. This is an aggregation table and profile_id is not guaranteed to be unique across multiple third-party channels.

Any suggestions?

Models:

class Channel(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(
        max_length=25,
    )

class MetaModel(models.Model):
    profile_id = fields.IntegerField()
    channel = fields.ForeignKey(Channel))
    metadata = fields.TextField()

class RelatedModel(models.Model):
    related_id = fields.IntegerField()
    profile_id = fields.IntegerField()
    channel = fields.ForeignKey(Channel))

Dummy data

channel = Channel("Web site A")
channel.save()

sample_meta = MetaModel(profile_id=1234, channel=channel)
sample_related = RelatedModel(profile_id=1234, related_id=5678, channel=channel)

Query:

# Create a queryset to filter down to the single record we need the `profile_id` for
# I've limited to the only field we need via a `values` operation
related_qs = RelatedAccount.objects.filter(
    related_id=5678,
    channel=channel
).values_list("profile_id", flat=True)

# I'm doing an update_or_create as there is other data to store, not included for brevity
obj, created = MetaModel.objects.update_or_create(
    profile_id=related_qs.first(),  # <<< This var is the dynamic part of the query
    channel=channel,
    defaults={"metadata": "Metadata is added to a new or existing record."}
)

Body:
Regarding your note on uniqueness, you can use unique_together option in Django as described here in the documentation.

class MetaModel(models.Model):
    profile_id = fields.ForeignKey(RelatedModel)
    channel = fields.ForeignKey(Channel)
    metadata = fields.TextField()

    class Meta:
        unique_together = ('profile_id', 'channel')

Then you can change your query accordingly and should solve your problem.


问:
TypeScript: Sometimes don't show the latest data when delete user
I'm working on chrome browser. I have a table list users, and want to CRUD on that. Try to delete user, sometimes data reload is OK, but sometimes it's not change (need to press f5, the page will show latest data)
In ts file:

```<code> deleteUser(user: User) {
    if(user){
      this.userService.deleteUser(user);
      this.ngOnInit();
    }
  }

 ngOnInit() { //when component loading get all users and set the users[]
    this.getAllUsers();
  }

 getAllUsers() {
    this.userService.getUsers().then(user =>
        this.users = user
       );

  }
</code>```

service

```<code>deleteUser(user: User): Promise<void> {
        const url = `${this.userUrl}/${user.id}`;
        return this.http.delete(url, { headers: this.headers })
          .toPromise()
          .then(() => null)
          .catch(this.handleError);
      }

 getUsers(): Promise<User[]> {
        return this.http.get(this.userUrl)
          .toPromise()
          .then(response => response.json().content as User[])
          .catch(this.handleError)
      }
</code>```

html

```<code><button  type="button" class="btn btn-warning" (click)="deleteUser(user)">Delete</button>
</code>```

Please advice me. Many thanks.

答:
Instead of

```<code>this.userService.deleteUser(user);
this.ngOnInit();
</code>```

should be something like

```<code>this.userService.deleteUser(user).then(res => this.ngOnInit());
</code>```

Body:
I'm working on chrome browser. I have a table list users, and want to CRUD on that. Try to delete user, sometimes data reload is OK, but sometimes it's not change (need to press f5, the page will show latest data)
In ts file:

 deleteUser(user: User) {
    if(user){
      this.userService.deleteUser(user);
      this.ngOnInit();
    }
  }

 ngOnInit() { //when component loading get all users and set the users[]
    this.getAllUsers();
  }

 getAllUsers() {
    this.userService.getUsers().then(user =>
        this.users = user
       );

  }

service

deleteUser(user: User): Promise<void> {
        const url = `${this.userUrl}/${user.id}`;
        return this.http.delete(url, { headers: this.headers })
          .toPromise()
          .then(() => null)
          .catch(this.handleError);
      }

 getUsers(): Promise<User[]> {
        return this.http.get(this.userUrl)
          .toPromise()
          .then(response => response.json().content as User[])
          .catch(this.handleError)
      }

html

<button  type="button" class="btn btn-warning" (click)="deleteUser(user)">Delete</button>

Please advice me. Many thanks.

Body:
Instead of

this.userService.deleteUser(user);
this.ngOnInit();

should be something like

this.userService.deleteUser(user).then(res => this.ngOnInit());


问:
Attribute Routing doesn't work
I'm creating a rest api in visual studio express 2013.

I have 2 controllers: one for orders and one for clients.

I've already created the following:

/api/clients GET information about all clients

/api/clients/1 GET information about client with id = 1

/api/orders/10 GET information about order with id = 10

Now, I want to create this:

/api/clients/1/orders - GET information about all orders of client with id 1

I've read about attribute routing, but I can't make it work.

OrdersController.cs

```<code>[EnableCors(origins: "*", headers: "*", methods: "*")]
public class OrdersController : ApiController
{
    public Order Get(string id)
    {
        // ...
    }

    [Route("clients/{id}/orders")]
    public List<Order> GetByClient(string id)
    {
        // ...
    }
}
</code>```

WebApiConfig.cs

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Enable CORS
        config.EnableCors();

        //config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
</code>```

RouteConfig.cs

```<code>public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

Like this, all of the other requests work properly, but when I try to access /api/clients/1/orders, I get the error HTTP Error 404.0 - Not Found. The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

But as soon as I uncomment config.MapHttpAttributeRoutes();, I'm no longer able to access any of the requests - they all return this:

```<code><Error>
    <Message>An error has occurred.</Message>
<ExceptionMessage>
    The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
    at System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() at System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) at System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)
</StackTrace>
</Error>
</code>```

What am I doing wrong here?

答:
With routing attribute [Route("clients/{id}/orders")], you should access action GetByClient() not by /api/clients/1/orders url, but with /clients/1/orders. To have an original url just fix the routing:

```<code>[Route("api/clients/{id}/orders")]
public List<Order> GetByClient(string id)
</code>```

Title: Attribute Routing doesn't work

Body:
I'm creating a rest api in visual studio express 2013.

I have 2 controllers: one for orders and one for clients.

I've already created the following:

/api/clients GET information about all clients

/api/clients/1 GET information about client with id = 1

/api/orders/10 GET information about order with id = 10

Now, I want to create this:

/api/clients/1/orders - GET information about all orders of client with id 1

I've read about attribute routing, but I can't make it work.

OrdersController.cs

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class OrdersController : ApiController
{
    public Order Get(string id)
    {
        // ...
    }

    [Route("clients/{id}/orders")]
    public List<Order> GetByClient(string id)
    {
        // ...
    }
}

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Enable CORS
        config.EnableCors();

        //config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

RouteConfig.cs

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

Like this, all of the other requests work properly, but when I try to access /api/clients/1/orders, I get the error HTTP Error 404.0 - Not Found. The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

But as soon as I uncomment config.MapHttpAttributeRoutes();, I'm no longer able to access any of the requests - they all return this:

<Error>
    <Message>An error has occurred.</Message>
<ExceptionMessage>
    The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
    at System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() at System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) at System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)
</StackTrace>
</Error>

What am I doing wrong here?

Body:
With routing attribute [Route("clients/{id}/orders")], you should access action GetByClient() not by /api/clients/1/orders url, but with /clients/1/orders. To have an original url just fix the routing:

[Route("api/clients/{id}/orders")]
public List<Order> GetByClient(string id)


问:
CSS "underline" text part
How can I "underline" text to get the same effect like you can see under "TEST"?

I tried to encapsulate TEST in a span and adding an absolute :after with position: absolute, but I think it's not the correct way and haven't been able to obtain the expected result.

Here's the HTML

    ALL THIS TEXT IS

    A TEST

```

答:
You said you tried with :after . That's the right solution. See snippet below.
You can change the values

.striked {
  position: relative
}

h1 {
  text-align: center;
}

.striked:after {
  height: 50%;
  width: 150%;
  left: -25%;
  background: red;
  content: "";
  position: absolute;
  bottom: 0;
  z-index: -1
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="white hero-text">
    <span class="thin">ALL THIS TEXT IS</span>
    <br>
    <span class="bold striked">A TEST</span>
</h1></code>```

Title: CSS "underline" text part

Body:
You said you tried with :after . That's the right solution. See snippet below.
You can change the values

.striked {
  position: relative
}

h1 {
  text-align: center;
}

.striked:after {
  height: 50%;
  width: 150%;
  left: -25%;
  background: red;
  content: "";
  position: absolute;
  bottom: 0;
  z-index: -1
}

<h1 class="white hero-text">
    <span class="thin">ALL THIS TEXT IS</span>
    <br>
    <span class="bold striked">A TEST</span>
</h1>


问:
You are using the runtime-only build of Vue where the template compiler is not available
I'm trying to compile my Vue.js app with webpack but I get this warning in the browser.

You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

What does this mean? How do I resolve the error?

答:
This is because the version of vue without the template compiler (needed) is included by default. To override this default, add this to your webpack.config.js:

```<code>// webpack.config.js
{
    resolve: {
        alias: {
            vue: 'vue/dist/vue.js'
        },
    },
}
</code>```

Source: https://github.com/vuejs-templates/webpack/issues/215

Body:
This is because the version of vue without the template compiler (needed) is included by default. To override this default, add this to your webpack.config.js:

// webpack.config.js
{
    resolve: {
        alias: {
            vue: 'vue/dist/vue.js'
        },
    },
}

Source: https://github.com/vuejs-templates/webpack/issues/215


问:
Export TexCoord json in meshlab
I am new to to the 3d world, i wonder why in the "Export Mesh as" screen in meshlab i cannot export with "TexCoord" my mesh, i cannot select the checkbox, it shows only "Color" and "Normal" options under the "Vert" option.

I've imported the mesh from a 3d scanned .OBJ and .MTL, it renders ok but i cannot export with "TexCoord" that i need in my resulting JSON file to render in a gl view in another application.

There's any operations can i do on my mesh to get the things work? In another example JSON export i see in the JSON the texcoord_buffer property that i need to show properly the texture.

答: found. you have to go in filters > texture > per vertex texture function</p>

Title: Export TexCoord json in meshlab


答:
Use pseudo selector :before as you mentioned and add span tag to only that section where you want that border bottom styling as in above image.

span{
  display:inline-block;
  position:relative;
}
span:before{
  content:"";
  width:100%;
  height:10px;
  background:yellow;
  position:absolute;
  bottom:3px;
  z-index:-1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="white hero-text">
    ALL THIS TEXT IS
    <br>
    <span>A TEST</span>
</h1></code>```

Title: CSS "underline" text part

Body:
How can I "underline" text to get the same effect like you can see under "TEST"?

I tried to encapsulate TEST in a span and adding an absolute :after with position: absolute, but I think it's not the correct way and haven't been able to obtain the expected result.

Here's the HTML

    ALL THIS TEXT IS

    A TEST

Body:
Use pseudo selector :before as you mentioned and add span tag to only that section where you want that border bottom styling as in above image.

span{
  display:inline-block;
  position:relative;
}
span:before{
  content:"";
  width:100%;
  height:10px;
  background:yellow;
  position:absolute;
  bottom:3px;
  z-index:-1;
}

<h1 class="white hero-text">
    ALL THIS TEXT IS
    <br>
    <span>A TEST</span>
</h1>


问:
Reading a column file of x y z into table in Lua
Been trying to find my way through Lua, so I have a file containing N lines of numbers, 3 per line, it is actually x,y,z coordinates. I could make it a CSV file and use some Lua CSV parser, but I guess it's better if I learn how to do this regardless.

So what would be the best way to deal with this? So far I am able to read each line into a table line by the code snippet below, but 1) I don't know if this is a string or number table, 2) if I print tbllinesx[1], it prints the whole line of three numbers. I would like to be able to have tbllines[1][1], tbllines[1][2] and tbllines[1][3] corresponding to the first 3 number of 1st line of my file.

```<code>local file = io.open("locations.txt")
local tbllinesx = {}
local i = 0
if file then
for line in file:lines() do
 i = i + 1
 tbllinesx[i] = line
end
file:close()
else
error('file not found')
end
</code>```

答:
Assuming you only have valid lines in your data file (locations.txt) all you need is change the line:

```<code>tbllinesx[i] = line
</code>```

to:

```<code>tbllinesx[i] = { line:match '(%d+)%s+(%d+)%s+(%d+)' }
</code>```

This will put each of the three space-delimited numbers into its own spot in a table for each line separately.

Edit: The repeated %d+ part of the pattern will need to be adjusted according to your actual input. %d+ assumes plain integers, you need something more involved for possible minus sign (%-?%d+) and for possible dot (%-?%d-%.?%d+), and so on.  Of course the easy way would be to grab everything that is not space (%S+) as a potential number.

Body:
Been trying to find my way through Lua, so I have a file containing N lines of numbers, 3 per line, it is actually x,y,z coordinates. I could make it a CSV file and use some Lua CSV parser, but I guess it's better if I learn how to do this regardless.

So what would be the best way to deal with this? So far I am able to read each line into a table line by the code snippet below, but 1) I don't know if this is a string or number table, 2) if I print tbllinesx[1], it prints the whole line of three numbers. I would like to be able to have tbllines[1][1], tbllines[1][2] and tbllines[1][3] corresponding to the first 3 number of 1st line of my file.

local file = io.open("locations.txt")
local tbllinesx = {}
local i = 0
if file then
for line in file:lines() do
 i = i + 1
 tbllinesx[i] = line
end
file:close()
else
error('file not found')
end

Body:
Assuming you only have valid lines in your data file (locations.txt) all you need is change the line:

tbllinesx[i] = line

to:

tbllinesx[i] = { line:match '(%d+)%s+(%d+)%s+(%d+)' }

This will put each of the three space-delimited numbers into its own spot in a table for each line separately.

Edit: The repeated %d+ part of the pattern will need to be adjusted according to your actual input. %d+ assumes plain integers, you need something more involved for possible minus sign (%-?%d+) and for possible dot (%-?%d-%.?%d+), and so on.  Of course the easy way would be to grab everything that is not space (%S+) as a potential number.


问:
How to align subplots borders when one has label and not the other?
In the below example, how can I have ax2 (bottom) taking the full space on the left?

By "taking full space" I mean extending the plot area to the left limit of the figure, ie. using also the whitespace left below the label title and ticks from ax1.

import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
def example_plot(ax, fontsize=12):
    ax.plot([1, 2])
    ax.locator_params(nbins=3)
    ax.set_xlabel('x-label', fontsize=fontsize)
    ax.set_ylabel('y-label', fontsize=fontsize)
    ax.set_title('Title', fontsize=fontsize)

def example_plot_noY(ax, fontsize=12):
    ax.plot([1, 2])
    ax.locator_params(nbins=3)
    ax.set_xlabel('x-label', fontsize=fontsize)
    ax.set_yticks([])
    ax.set_title('Title', fontsize=fontsize)

plt.close('all')
fig = plt.figure()

gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])

example_plot(ax1)
example_plot_noY(ax2)

gs1.tight_layout(fig)

plt.show()
```

答:
See GridSpec with Varying Cell Sizes.
You can add another column in the gridspec which takes up the space of the labels of the upper plot. If you afterwards call tight layout, you do not need to care about its width, it can be 0 size,

```<code>gs1 = gridspec.GridSpec(2, 2, width_ratios=[0, 1])
ax1 = fig.add_subplot(gs1[0,1])
ax2 = fig.add_subplot(gs1[1,0:])
# ...
fig.tight_layout()
</code>```

Body:
See GridSpec with Varying Cell Sizes.
You can add another column in the gridspec which takes up the space of the labels of the upper plot. If you afterwards call tight layout, you do not need to care about its width, it can be 0 size,

gs1 = gridspec.GridSpec(2, 2, width_ratios=[0, 1])
ax1 = fig.add_subplot(gs1[0,1])
ax2 = fig.add_subplot(gs1[1,0:])
# ...
fig.tight_layout()


问:
Django model TextField not rendering
I've been trying to render the contents of a TextField onto my HTML page, but it's the only thing that just refuses to render. Could it be a problem with the inheritance of that model?

Here is my model:

```<code>class Section(models.Model):
    order_id = models.IntegerField()
    SECTION_TYPE_CHOICES = (('reg', 'regular'),
                        ('not', 'note'),
                        )
    section_type = models.CharField(
        max_length=5,
        choices=SECTION_TYPE_CHOICES,
        default='reg',
    )

class TextSection(Section):
    contents = models.TextField(blank=True, max_length=5000)

class Post(models.Model):
    post_id = models.IntegerField(unique=True)
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    slug = models.CharField(unique=True, max_length=20)
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)
    belongs_to = models.ForeignKey('Story')
    order_id = models.IntegerField()
    contents = models.ManyToManyField(Section, blank=True)
</code>```

and the template

```<code>{% extends 'stories/base.html' %}

{% block title %}
    {{ post.belongs_to.title }} | {{ post.title }}
{% endblock %}

{% block content %}
    <!-- Story Information -->
    <div>
        <h1>{{ post.title }}</h1>
        <p>by {{ post.author }} on {{  post.published_date }}</p>
    </div>
    <!-- Post Contents -->
    <div>
        {% for section in post.contents.all %}
            <div>
<!--------- Part that does not render --------->
                <p>{{ section.contents|safe }}</p>
<!--------- Part that does not render --------->
                {{ section.order_id }}

            </div>
        {% endfor %}
    </div>

{% endblock %}
</code>```

It always renders the section.order_id but never renders the section.contents

Thanks in advance for any advice.

EDIT: Ended up removing polymorphism and just expanding my Section model to include various contents.

答: Post.contents points to the Section model, not TextSection; Section itself doesn't have a contents field. If you need this, you should point your many-to-many field directly to TextSection.

Title: Django model TextField not rendering

Body:
I've been trying to render the contents of a TextField onto my HTML page, but it's the only thing that just refuses to render. Could it be a problem with the inheritance of that model?

Here is my model:

class Section(models.Model):
    order_id = models.IntegerField()
    SECTION_TYPE_CHOICES = (('reg', 'regular'),
                        ('not', 'note'),
                        )
    section_type = models.CharField(
        max_length=5,
        choices=SECTION_TYPE_CHOICES,
        default='reg',
    )

class TextSection(Section):
    contents = models.TextField(blank=True, max_length=5000)

class Post(models.Model):
    post_id = models.IntegerField(unique=True)
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    slug = models.CharField(unique=True, max_length=20)
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)
    belongs_to = models.ForeignKey('Story')
    order_id = models.IntegerField()
    contents = models.ManyToManyField(Section, blank=True)

and the template

{% extends 'stories/base.html' %}

{% block title %}
    {{ post.belongs_to.title }} | {{ post.title }}
{% endblock %}

{% block content %}

{{ post.title }}

by {{ post.author }} on {{  post.published_date }}

        {% for section in post.contents.all %}

{{ section.contents|safe }}

                {{ section.order_id }}

        {% endfor %}

{% endblock %}

It always renders the section.order_id but never renders the section.contents

Thanks in advance for any advice.

EDIT: Ended up removing polymorphism and just expanding my Section model to include various contents.


问:
I am trying to remove all special characters from a string and the below works fine except it is removing the space between words
Here I am trying to remove all special characters from a string and this working fine except it is removing the spaces between the words as well.I need the spaces in between the words.</p>

```<code>NSCharacterSet *charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];

    dataString = [[dataString componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""];
</code>```

答:
You can use a NSMutableCharacterSet like in this example:</p>

```<code>NSMutableCharacterSet * charactersToRemove = [NSMutableCharacterSet alphanumericCharacterSet];
[charactersToRemove addCharactersInString:@" "];

NSCharacterSet *newCharactersToRemove = [charactersToRemove invertedSet];
</code>```

Body:
Here I am trying to remove all special characters from a string and this working fine except it is removing the spaces between the words as well.I need the spaces in between the words.

NSCharacterSet *charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];

    dataString = [[dataString componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""];

Body:
You can use a NSMutableCharacterSet like in this example:

NSMutableCharacterSet * charactersToRemove = [NSMutableCharacterSet alphanumericCharacterSet];
[charactersToRemove addCharactersInString:@" "];

NSCharacterSet *newCharactersToRemove = [charactersToRemove invertedSet];


问:
Bash: check if one decimal number is greater than another decimal number
I have a case like this:

```<code>string1="some_string"
string2="some_string"
int1="0.87"
int2="${var}"
</code>```

$var is the output of some other script, and it has the form 0.994343123 or 0.3454657 or whatever (starts with 0. and the biggest value is around 0.9972343)

Now, I don't know how bash works, but usually string 0.87 is never less than or equal to 0.9999999, they are just different.

I would need something like this (pseudocode):

```<code>if (string1 equals string2 and int1 is less than int2):
    do something;
else
    do something else.
</code>```

What i would expect is 0.87687 is greater than 0.87 (correct?? i was never good at math...)

Can anyone help me with the code for that if??

Thanks in advance!

答:
If the values are between 0 and 1, string comparison will work</p>

```<code>s1=..; s2=..
v1="0.876"; v2="0.87"
[[ $s1 = $s2 && $v1 > $v2 ]] && echo yes || echo no
</code>```

Body:
I have a case like this:

string1="some_string"
string2="some_string"
int1="0.87"
int2="${var}"

$var is the output of some other script, and it has the form 0.994343123 or 0.3454657 or whatever (starts with 0. and the biggest value is around 0.9972343)

Now, I don't know how bash works, but usually string 0.87 is never less than or equal to 0.9999999, they are just different.

I would need something like this (pseudocode):

if (string1 equals string2 and int1 is less than int2):
    do something;
else
    do something else.

What i would expect is 0.87687 is greater than 0.87 (correct?? i was never good at math...)

Can anyone help me with the code for that if??

Thanks in advance!

Body:
If the values are between 0 and 1, string comparison will work

s1=..; s2=..
v1="0.876"; v2="0.87"
[[ $s1 = $s2 && $v1 > $v2 ]] && echo yes || echo no


问:
Difference in methods for converting std string to char*
I know there are a ton questions on how to convert a std::string to a char* and through my research, I have adopted a few different options.  However, the only one that seems to work for me is const_cast from the c_str() method.

So I am using that for now, but would like to know more information as to why the other methods do not work.  What am I missing in my understanding as to why this isn't working as intended which seems to work for many others.

```<code>#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    char* test = "Hello World";
    string testStr(test);

    vector<char> testVec2(testStr.begin(), testStr.end());
    // testVec2[0] = 'F';
    char* test2 = reinterpret_cast<char*>(testVec2.data());

    vector<char> testVec3(testStr.begin(), testStr.end());
    // testVec3[0] = 'G';
    char* test3 = &testVec3[0];

    // The only one that works
    char* test4 = const_cast<char*>(testStr.c_str());

    cout << "char* test: " << test << " [" << strlen(test) << "]" << endl;
    cout << "str test: " << testStr << " [" << testStr.length() << "]" <<     endl;
    cout << "=== conv testing === " << endl;
    cout << "char* test2: " << test2 << " [" << strlen(test2) << "]" <<     endl;
    cout << "char* test3: " << test3 << " [" << strlen(test3) << "]" << endl;
    cout << "char* test4: " << test4 << " [" << strlen(test4) << "]" << endl;

    cin.get();
    return 0;
}
</code>```

I know the pitfalls of using const_cast but it works for my situation at the moment.  I simply take the string from the user, pass it to a C API and do nothing else with it (no worries of it being modified).

Here is a sample of the output
https://imgur.com/a/2S1HD

So what am I doing wrong and is there a better way to do this?

UPDATE
Thanks to everyone for the extremely fast answers.  It seems that my underlying confusion was the assumption of the null terminating character not being in the new buffer that I was assigning to the char* variable.  Hence why my output was showing random characters after the string (that should have been my clue but it has been so long since I've done C/C++)

I also should have tagged this C++17 originally (since fixed) as that is what I am aiming for.  I did not have that enabled in my console app in Visual Studio which made the solution by Passer By below work.  That is the method I will use going forward.

Bottom line, changing my target to C++17 this works as expected

```<code>char* test = "Hello World";
string testStr(test);
vector<char> testVec2(testStr.begin(), testStr.end());
char* test2 = testStr.data();
</code>```

答:
In C++17, the simplest way to fetch a char* from a std::string is simply

```<code>std::string str = "Why is this only available since C++17?";
some_c_function(str.data());
</code>```

As to why other methods don't work, refer to bolov's answer

Body:
I know there are a ton questions on how to convert a std::string to a char* and through my research, I have adopted a few different options.  However, the only one that seems to work for me is const_cast from the c_str() method.

So I am using that for now, but would like to know more information as to why the other methods do not work.  What am I missing in my understanding as to why this isn't working as intended which seems to work for many others.

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    char* test = "Hello World";
    string testStr(test);

    vector<char> testVec2(testStr.begin(), testStr.end());
    // testVec2[0] = 'F';
    char* test2 = reinterpret_cast<char*>(testVec2.data());

    vector<char> testVec3(testStr.begin(), testStr.end());
    // testVec3[0] = 'G';
    char* test3 = &testVec3[0];

    // The only one that works
    char* test4 = const_cast<char*>(testStr.c_str());

    cout << "char* test: " << test << " [" << strlen(test) << "]" << endl;
    cout << "str test: " << testStr << " [" << testStr.length() << "]" <<     endl;
    cout << "=== conv testing === " << endl;
    cout << "char* test2: " << test2 << " [" << strlen(test2) << "]" <<     endl;
    cout << "char* test3: " << test3 << " [" << strlen(test3) << "]" << endl;
    cout << "char* test4: " << test4 << " [" << strlen(test4) << "]" << endl;

    cin.get();
    return 0;
}

I know the pitfalls of using const_cast but it works for my situation at the moment.  I simply take the string from the user, pass it to a C API and do nothing else with it (no worries of it being modified).

Here is a sample of the output
https://imgur.com/a/2S1HD

So what am I doing wrong and is there a better way to do this?

UPDATE
Thanks to everyone for the extremely fast answers.  It seems that my underlying confusion was the assumption of the null terminating character not being in the new buffer that I was assigning to the char* variable.  Hence why my output was showing random characters after the string (that should have been my clue but it has been so long since I've done C/C++)

I also should have tagged this C++17 originally (since fixed) as that is what I am aiming for.  I did not have that enabled in my console app in Visual Studio which made the solution by Passer By below work.  That is the method I will use going forward.

Bottom line, changing my target to C++17 this works as expected

char* test = "Hello World";
string testStr(test);
vector<char> testVec2(testStr.begin(), testStr.end());
char* test2 = testStr.data();

Body:
In C++17, the simplest way to fetch a char* from a std::string is simply

std::string str = "Why is this only available since C++17?";
some_c_function(str.data());

As to why other methods don't work, refer to bolov's answer


问:
In the class context how to create a new object by new self and new parent?
I'm using PHP 7.1.11

In the PHP manual I come across the following sentence :

In the class context, it is possible to create a new object by new
  self and new parent.

I didn't understand what this sentence actually mean? Also, there is not a single working demonstrative example has been given in the manual. So, I'm not at all able to understand the meaning of this sentence.

If someone could explain the meaning along-with the appropriate, suitable, working, demonstrative code-example each for new self and new parent it would be of great help to me.

答:
It simply means that you can use the keyword self as a shortcut to refer to the class you're in, and the keyword parent to refer to the class you extended.

```<code>class Foo
{

    public static function thing()
    {
        // do something
    }

    public function method()
    {
        $foo = new self(); // Creates an instance of Foo
        self::thing();     // Statically calls method thing in class Foo
    }

}

class Bar extends Foo
{
    public function method()
    {
        $bar = new self();   // Creates an instance of Bar
        $bar = new self;     // Same thing, without optional parens
        $foo = new parent(); // Creates an instance of Foo
        parent::thing();     // Statically calls method thing in class Foo
    }
}
</code>```

Body:
It simply means that you can use the keyword self as a shortcut to refer to the class you're in, and the keyword parent to refer to the class you extended.

class Foo
{

    public static function thing()
    {
        // do something
    }

    public function method()
    {
        $foo = new self(); // Creates an instance of Foo
        self::thing();     // Statically calls method thing in class Foo
    }

}

class Bar extends Foo
{
    public function method()
    {
        $bar = new self();   // Creates an instance of Bar
        $bar = new self;     // Same thing, without optional parens
        $foo = new parent(); // Creates an instance of Foo
        parent::thing();     // Statically calls method thing in class Foo
    }
}


问:
RecyclerView Multiple View Type
I've a list of following model:

```<code>name
categoryName
</code>```

Now, I've to build a recyclerview that groups all the entities with the same categoryName:

```<code>categoryName1
    name1
    name2
    name3
categoryName2
    name4
categoryName3
    name5
    name6
</code>```

So I have two different row type (different styles). The list is ordered. I don't necessary need the code, but, what's the algorithm to use for the adapter? Can I solve this with only one cycle?

I'd like to avoid adding view to a vertical LinearLayout from code.

答:
You must override method public int getItemViewType(int position) of RecyclerView, and handle it in public void onCreateViewHolder(ViewGroup parent, int viewType)

Example:

```<code>enum Type{Name,Category}

@Override
public int getItemViewType(int position) {
   if (position == POSITION_CATEGORY_1 || position == POSITION_CATEGORY_2) {
      return Type.Category;
   } else {
      return Type.Name;}
   }
}
</code>```

End bind:

```<code>@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if(viewType == Type.Category.ordinal()){
        return new CategoryItemView(...);
    }else {
        return new CommonItemView(...);
    }
}
</code>```

Title: RecyclerView Multiple View Type

Body:
I've a list of following model:

name
categoryName

Now, I've to build a recyclerview that groups all the entities with the same categoryName:

categoryName1
    name1
    name2
    name3
categoryName2
    name4
categoryName3
    name5
    name6

So I have two different row type (different styles). The list is ordered. I don't necessary need the code, but, what's the algorithm to use for the adapter? Can I solve this with only one cycle?

I'd like to avoid adding view to a vertical LinearLayout from code.

Body:
You must override method public int getItemViewType(int position) of RecyclerView, and handle it in public void onCreateViewHolder(ViewGroup parent, int viewType)

Example:

enum Type{Name,Category}

@Override
public int getItemViewType(int position) {
   if (position == POSITION_CATEGORY_1 || position == POSITION_CATEGORY_2) {
      return Type.Category;
   } else {
      return Type.Name;}
   }
}

End bind:

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if(viewType == Type.Category.ordinal()){
        return new CategoryItemView(...);
    }else {
        return new CommonItemView(...);
    }
}


问:
python - write row by row tuples inside a list
My issue is to write what is in my file, row by row in my function.

Here's my code:

```<code>def read_operators_file(file_name):
"""Read a file with operators into a collection.

Requires: file_name, str with the name of a text file with a list of operators.
Ensures: list, with the operators in the file; each operators is a tuple with the various element
concerning that operator, in the order provided in the file.
"""
inputFile1 = open("operators14h55.txt",'r+')
import constants
for i in range(constants.HEADER_TOTAL_LINES):  # read some lines to skip the header
    inputFile1.readline()
operators = []
for line in inputFile1:
    name, language, domain, last_hour, total_minutes = line.strip().split(', ')
    operators.append((name, language, domain, last_hour, total_minutes))
inputFile1.close()
return operators
</code>```

that return's all in a row, and I want each tuple in a single row.

```<code>[('Henry Miller', 'english', 'laptops', 'premium', 3), ('FranÃ§ois Greenwich', 'spanish', 'cameras', 'premium', 6), ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]
</code>```

I want something similar to this:

```<code>[('Henry Miller', 'english', 'laptops', 'premium', 3),
 ('FranÃ§ois Greenwich', 'spanish', 'cameras', 'premium', 6),
 ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]
</code>```

答:
```<code>for i in range(constants.HEADER_TOTAL_LINES):  # read some lines to skip the header
    inputFile1.readline()
</code>```

I also dont understand why you have those two lines? Unless I've mistaken, if anyone cares to explain :) But those line can be made redundant completely.

Body:
My issue is to write what is in my file, row by row in my function.

Here's my code:

def read_operators_file(file_name):
"""Read a file with operators into a collection.

Requires: file_name, str with the name of a text file with a list of operators.
Ensures: list, with the operators in the file; each operators is a tuple with the various element
concerning that operator, in the order provided in the file.
"""
inputFile1 = open("operators14h55.txt",'r+')
import constants
for i in range(constants.HEADER_TOTAL_LINES):  # read some lines to skip the header
    inputFile1.readline()
operators = []
for line in inputFile1:
    name, language, domain, last_hour, total_minutes = line.strip().split(', ')
    operators.append((name, language, domain, last_hour, total_minutes))
inputFile1.close()
return operators

that return's all in a row, and I want each tuple in a single row.

[('Henry Miller', 'english', 'laptops', 'premium', 3), ('FranÃ§ois Greenwich', 'spanish', 'cameras', 'premium', 6), ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]

I want something similar to this:

[('Henry Miller', 'english', 'laptops', 'premium', 3),
 ('FranÃ§ois Greenwich', 'spanish', 'cameras', 'premium', 6),
 ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]

Body:
for i in range(constants.HEADER_TOTAL_LINES):  # read some lines to skip the header
    inputFile1.readline()

I also dont understand why you have those two lines? Unless I've mistaken, if anyone cares to explain :) But those line can be made redundant completely.


问:
Nanomsg multicast bandwidth issue
Can I have pure multicasting in pub/sub protocol of the nanomsg.
As there can be N  subscribers interested in a particular data for a single publisher, the same subscribed data is flowing in N different streams.If my bandwidth for a single stream is 10MB then the total bandwidth required for N streams is 10*N,thus there is a increase in the bandwidth .Can we reduce this bandwidth as we do in the multicasting?? Can anyone help me regarding this issue?? </p>

答:
As far as I understand the PUB/SUB pattern, the data will be sent to all subscribers one by one. If a subscriber is not ready to take it, the data is dropped. I believe that the data in PUB/SUB is sent sequentially.

However, you can have better control how data is sent if you use PUSH/PULL pattern.
You can have N PULLers and one PUSHer. The PUSHer will send the data to all PULLers one by one. The difference is that you can control timing and you can wait for slower PULLers.

If you do not like multiple transmissions the only other mechanism which I can think of is a shared memory. One sender and multiple takers. That scenario applies only for a single computer though.

So, the answer is No.  You cannot have pure multi-casting in nanomsg pub/sub protocol. If you need a pure multicast you have to look at the other protocols.
Maybe incoming nng could provide it over UDP.

If multicast is a must you have to check other protocols see for example
NACK-Oriented Reliable Multicast (NORM).

Title: Nanomsg multicast bandwidth issue


问:
newbie question memory and code optimisation
this is what i write

```<code>domaine *detailsDomaine = [search_result objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"%@",[detailsDomaine valueForKey:@"nom"]];
</code>```

Is it possible to not assign a variable (detailsDomaine)to reach the same result ?
Do i have to release detailsDomaine variable after that ?

I'm not using it anywhere else in the rest of the code...

答:
first of all You do not need to release it ... </p>

<p>you can write it also in a single statement like </p>

```<code>cell.textLabel.text = [NSString stringWithFormat:@"%@",[[search_result objectAtIndex:indexPath.row] valueForKey:@"nom"]];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
this is what i write

domaine *detailsDomaine = [search_result objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"%@",[detailsDomaine valueForKey:@"nom"]];

Is it possible to not assign a variable (detailsDomaine)to reach the same result ?
Do i have to release detailsDomaine variable after that ?

I'm not using it anywhere else in the rest of the code...

Body:
first of all You do not need to release it ...

you can write it also in a single statement like

cell.textLabel.text = [NSString stringWithFormat:@"%@",[[search_result objectAtIndex:indexPath.row] valueForKey:@"nom"]];


问:
How to connect to an headless service in Kubernetes from outside?
I created an headless service:

```<code>apiVersion: v1
kind: Service
metadata:
  name: myapp-service-headless
spec:
  ports:
    - port: 80
  selector:
    app: myapp
  clusterIP: None
</code>```

From Kubernetes dashboard I can see its Internal endpoints:

```<code>myapp-service-headless:80 TCP
myapp-service-headless:0 TCP
</code>```

In this application, I also set internal endpoint to:

```<code>http://myapp-service-headless
</code>```

But from outside, how can I access its IP to connect API?

For example, my Kubernetes' IP is 192.168.99.100, then connect to 192.168.99.100 is okay?

Now the service status from Kubernetes dashboard

Services

Service Details

答:
There is two option to expose the service outside, you can use the ingress controller to connect to the server.

The simple method is change your service type to NodePort, then you should be able access server using NodeIP and service external port number.

here is the more info.

https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport

ContentLicense: CC BY-SA 4.0

Body:
I created an headless service:

apiVersion: v1
kind: Service
metadata:
  name: myapp-service-headless
spec:
  ports:
    - port: 80
  selector:
    app: myapp
  clusterIP: None

From Kubernetes dashboard I can see its Internal endpoints:

myapp-service-headless:80 TCP
myapp-service-headless:0 TCP

In this application, I also set internal endpoint to:

http://myapp-service-headless

But from outside, how can I access its IP to connect API?

For example, my Kubernetes' IP is 192.168.99.100, then connect to 192.168.99.100 is okay?

Now the service status from Kubernetes dashboard

Services

Service Details


问:
Error 55000 `object_not_in_prerequisite_state` when trying to refresh a materialized view
I'm trying to run REFRESH MATERIALIZED VIEW CONCURRENTLY recipe_search;, but PostgreSQL gives me this error: ERROR 55000 (object_not_in_prerequisite_state): cannot refresh materialized view "public.recipe_search" concurrently.

The materialized view in question looks like this in psql:

```<code># \d recipe_search

   Materialized view "public.recipe_search"
  Column  |          Type          | Modifiers
----------+------------------------+-----------
 id       | integer                |
 title    | character varying(255) |
 document | tsvector               |
Indexes:
    "recipe_search_document_index" gin (document)
    "recipe_search_title_trgm_index" gin (title gin_trgm_ops)
</code>```

Why can't I refresh this concurrently?

答:
The materialized view needs a unique index

A materialized view cannot be refreshed CONCURRENTLY unless it has at least one unique index, as described in the docs:

CONCURRENTLY

... This option is only allowed if there is at least one UNIQUE index on the materialized view which uses only column names and includes all rows; that is, it must not index on any expressions nor include a WHERE clause.

https://www.postgresql.org/docs/9.6/static/sql-refreshmaterializedview.html

Body:
I'm trying to run REFRESH MATERIALIZED VIEW CONCURRENTLY recipe_search;, but PostgreSQL gives me this error: ERROR 55000 (object_not_in_prerequisite_state): cannot refresh materialized view "public.recipe_search" concurrently.

The materialized view in question looks like this in psql:

# \d recipe_search

   Materialized view "public.recipe_search"
  Column  |          Type          | Modifiers
----------+------------------------+-----------
 id       | integer                |
 title    | character varying(255) |
 document | tsvector               |
Indexes:
    "recipe_search_document_index" gin (document)
    "recipe_search_title_trgm_index" gin (title gin_trgm_ops)

Why can't I refresh this concurrently?


问:
How to pass a dynamic value in angular2-counto
I'm using the following library:

https://github.com/izupet/angular2-counto

I'm getting an error when I pass a dynamic value.

So in my component app.component.html:

If I use interpolation:

```<code><div counto [step]="30" [countTo]="'{{value}}'" [countFrom]="0 [duration]="4" (countoChange)="counto = $event" (countoEnd)="onCountoEnd()">{{counto | currency:'EUR':true:'1.2-2'}}</div>
</code>```

I get an error related with the double braces syntax:

```<code>[countTo]="'{{value}}'"
</code>```

Otherwise, without them it works:

```<code> [countTo]="10"
</code>```

Here for [countTo] attribute passing the value from component.

For app.component.ts

```<code>export class AppComponent {

  value=10;

}
</code>```

答:
In angular, the use of [] is for when the value is a binding expression (your case).

So, for example, an input:

```<code><input value="data"> // value is `data`, a string
<input [value]="data"> // value is a property of the current component's class called `data`, can be an object, array, number, string, etc.
</code>```

That's why you need to use just the name of the property in order to pass it as value of a tag's attribute surrounded by [].

Therefore, using [countTo]="value" will work just fine if the value property in your class is defined and accepted by the library that you are using.

Body:
I'm using the following library:

https://github.com/izupet/angular2-counto

I'm getting an error when I pass a dynamic value.

So in my component app.component.html:

If I use interpolation:

{{counto | currency:'EUR':true:'1.2-2'}}

I get an error related with the double braces syntax:

[countTo]="'{{value}}'"

Otherwise, without them it works:

 [countTo]="10"

Here for [countTo] attribute passing the value from component.

For app.component.ts

export class AppComponent {

  value=10;

}

Body:
In angular, the use of [] is for when the value is a binding expression (your case).

So, for example, an input:

<input value="data"> // value is `data`, a string
<input [value]="data"> // value is a property of the current component's class called `data`, can be an object, array, number, string, etc.

That's why you need to use just the name of the property in order to pass it as value of a tag's attribute surrounded by [].

Therefore, using [countTo]="value" will work just fine if the value property in your class is defined and accepted by the library that you are using.


问:
ExpressJS - Call an outer function in router.get and render its data
I need to call functions in order to render mysql queries data to my views instead of having the query functions inside the router.get

How can I call a function() inside router.get so I can render its query output through EJS or any other templating engine?

index.js

```<code>function fdb(mypar) {
    obj = {}
    con.query(mypar, (err, rows) => {
        if (err) throw err
        obj = rows[0]
        console.log(obj)
        //rows data fetching OK using stored procedure get_all_1 when route '/' is called
    })
}

/* GET home page. */
router.get('/', function(req, res, next) {
    fdb('CALL get_all_1')
    console.log(obj) // {}

    to_render = { print: obj }
    console.log(to_render) // { print: {} }

    res.render('index', to_render);
    //it obviously cannot render anything
    //GET / 500
});
</code>```

index.ejs

```<code><% print.forEach(function (qdata) { %>
    <tr>
        <td>
            <%= qdata.name %>
        </td>
        <td>
            <%= qdata.location %>
        </td>
    </tr>
<% }) %>
</code>```

I understannd somehow that obj gets out of scope when I try to call it through fdb() function inside the router.get but can't figure out how to manipulate that scope.

答:
```<code>function fdb(mypar) {
  return new Promise((resolve) => {
    obj = {}
    con.query(mypar, (err, rows) => {
      if (err) throw err
      obj = rows[0]
      console.log(obj)
      resolve(obj);
    })
  });
}

/* GET home page. */
router.get('/', async function(req, res, next) {
  let obj = await fdb('CALL get_all_1')
  console.log(obj)

  to_render = { print: obj }
  console.log(to_render)

  res.render('index', to_render);
});
</code>```

Body:
I need to call functions in order to render mysql queries data to my views instead of having the query functions inside the router.get

How can I call a function() inside router.get so I can render its query output through EJS or any other templating engine?

index.js

function fdb(mypar) {
    obj = {}
    con.query(mypar, (err, rows) => {
        if (err) throw err
        obj = rows[0]
        console.log(obj)
        //rows data fetching OK using stored procedure get_all_1 when route '/' is called
    })
}

/* GET home page. */
router.get('/', function(req, res, next) {
    fdb('CALL get_all_1')
    console.log(obj) // {}

    to_render = { print: obj }
    console.log(to_render) // { print: {} }

    res.render('index', to_render);
    //it obviously cannot render anything
    //GET / 500
});

index.ejs

<% print.forEach(function (qdata) { %>

            <%= qdata.name %>

            <%= qdata.location %>

<% }) %>

I understannd somehow that obj gets out of scope when I try to call it through fdb() function inside the router.get but can't figure out how to manipulate that scope.


问:
how to serialize class to database instead of file system c#
we can easily serialize class to flat file but if i want to serialize class to database then how could i do it and if it is possible then how can i deserialize data from db to class.
please give a sample code in c#.

thanks

答:
Serialize an object into XML. Try and let a dataset read from that XML blob.
Create an DB create statement for each table/row in the dataset.</p>


问:
Cordova android mapped to which android API
When using Cordova I want to build for Android API version 23.

When I do cordova platform add android then when I build the app by doing cordova build android. It builds for API 25 by default.

How do I go about setting the correct api version. Also mention what is to be installed in the Android-sdk.

Thanks

答:
How do I go about setting the correct api version

In your config.xml, use a <preference> to set it:

```<code><preference name="android-targetSdkVersion" value="23" />
</code>```

Also mention what is to be installed in the Android-sdk

The API 23 platform SDK needs to be installed.
See the Cordova Android platform guide for more details.

Body:
How do I go about setting the correct api version

In your config.xml, use a <preference> to set it:

<preference name="android-targetSdkVersion" value="23" />

Also mention what is to be installed in the Android-sdk

The API 23 platform SDK needs to be installed.
See the Cordova Android platform guide for more details.


问:
SSIS Conditional split results in deadlock error
I have a conditional split in an SSIS job that inserts or updates based on the CDC operation.  The deletes dont actually delete, they just mark the row deleted (so it is also an update statement).

This is what it looks like:

And the error message associated with the red x is

"Transaction (Process ID 67) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.".

I tried to put an additional input arrow in there, so it only runs one update at a time, but it won't let me.

答:
I suspect FactWaybillTrans is has table lock checked in the destination. That's usually what you want when loading large amounts of data. However, since you also want to update the same thing, that is going to conflict with the lock and thus, you get a deadlock. Even without checking table lock, the default lock could escalate to a full lock.

I would look to stage my updates to a table (stage.CDCWaybillUpdates) and then have an Execute SQL Task fire after the Data Flow. Much cleaner and no opportunity for deadlocks.

You might be able to fake it but it'd be totally unreliable. Add a Sort Operation between the NumRowsUpdated and Update. That might be able to induce enough drag so that the OLE DB Destination finishes and releases its lock before the update begins firing. If it doesn't slow it down enough, then sort the same data in the opposite direction. Terrible, hackish approach but sometimes you have to do the dumb.


问:
How to fix ‘Path Manipulation’ issue from Fortify scan report for tthe following code sample
I have path Manipulation problem. The following code is placed in Page_load method of ASPx page.

```<code>String rName = Request.QueryString["reportName"];
string path = "C:\\hari" + rName;
if (File.Exists(path))
{
    File.Delete(path);
}
</code>```

But Fortify scan report for the above sample code shows ‘Path Manipulation’  issue as high
Need help to modify above code so that it can pass fortify scan

答: I think the problem is that someone could spoof a request with reportName = "..\\Windows\\Something important" which is clearly a security flaw. You need to change your code so that it doesn't read a partial filename from the request query string.

Body:
I have path Manipulation problem. The following code is placed in Page_load method of ASPx page.

String rName = Request.QueryString["reportName"];
string path = "C:\\hari" + rName;
if (File.Exists(path))
{
    File.Delete(path);
}

But Fortify scan report for the above sample code shows ‘Path Manipulation’  issue as high
Need help to modify above code so that it can pass fortify scan


问:
SendInput on c++ doesn't take Ctrl and Shift in account
I'm trying to send a  CTRL+SHIFT+END key stroke to a control, in a C++ application written with Embarcadero. I'm using the code below:

```<code>tagINPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.wScan = 0;
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;

// Appui sur Ctrl
ip.ki.wVk = VK_CONTROL;
ip.ki.dwFlags = 0;
SendInput(1, &ip, sizeof(INPUT));

// Appui sur Shift
ip.ki.wVk = VK_SHIFT;
ip.ki.dwFlags = 0;
SendInput(1, &ip, sizeof(INPUT));

// Appui sur End
ip.ki.wVk = VK_END;
ip.ki.dwFlags = 0;
SendInput(1, &ip, sizeof(INPUT));

Application->ProcessMessages();

// Relacher End
ip.ki.wVk = VK_END;
ip.ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(1, &ip, sizeof(INPUT));

// Relacher Shift
ip.ki.wVk = VK_SHIFT;
ip.ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(1, &ip, sizeof(INPUT));

// Relacher Ctrl
ip.ki.wVk = VK_CONTROL;
ip.ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(1, &ip, sizeof(INPUT));
</code>```

However, it appears to be working like if there was no action on the CTRL and SHIFT keys.

What am I missing ?

答:
The problem is, that the VK_END key is an extended key. So you should declare this in the flags:

```<code>eip.ki.dwFlags = 0;
ip.ki.wVk = VK_END;
ip.ki.dwFlags = 0;
ip.ki.dwFlags = ip.ki.dwFlags | 1;
SendInput(1, &ip, sizeof(INPUT));

Application->ProcessMessages();

// Relacher End
ip.ki.wVk = VK_END;
ip.ki.dwFlags = KEYEVENTF_KEYUP;
ip.ki.dwFlags = ip.ki.dwFlags | 1;
SendInput(1, &ip, sizeof(INPUT));
</code>```

Note that I used 1 for setting the flag as I don't know if you have a constant defined in your C++, but assume there is a constant someplace.

Body:
I'm trying to send a  CTRL+SHIFT+END key stroke to a control, in a C++ application written with Embarcadero. I'm using the code below:

tagINPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.wScan = 0;
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;

// Appui sur Ctrl
ip.ki.wVk = VK_CONTROL;
ip.ki.dwFlags = 0;
SendInput(1, &ip, sizeof(INPUT));

// Appui sur Shift
ip.ki.wVk = VK_SHIFT;
ip.ki.dwFlags = 0;
SendInput(1, &ip, sizeof(INPUT));

// Appui sur End
ip.ki.wVk = VK_END;
ip.ki.dwFlags = 0;
SendInput(1, &ip, sizeof(INPUT));

Application->ProcessMessages();

// Relacher End
ip.ki.wVk = VK_END;
ip.ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(1, &ip, sizeof(INPUT));

// Relacher Shift
ip.ki.wVk = VK_SHIFT;
ip.ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(1, &ip, sizeof(INPUT));

// Relacher Ctrl
ip.ki.wVk = VK_CONTROL;
ip.ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(1, &ip, sizeof(INPUT));

However, it appears to be working like if there was no action on the CTRL and SHIFT keys.

What am I missing ?

Body:
The problem is, that the VK_END key is an extended key. So you should declare this in the flags:

eip.ki.dwFlags = 0;
ip.ki.wVk = VK_END;
ip.ki.dwFlags = 0;
ip.ki.dwFlags = ip.ki.dwFlags | 1;
SendInput(1, &ip, sizeof(INPUT));

Application->ProcessMessages();

// Relacher End
ip.ki.wVk = VK_END;
ip.ki.dwFlags = KEYEVENTF_KEYUP;
ip.ki.dwFlags = ip.ki.dwFlags | 1;
SendInput(1, &ip, sizeof(INPUT));

Note that I used 1 for setting the flag as I don't know if you have a constant defined in your C++, but assume there is a constant someplace.


问:
how to swap records having unique constraint in hibernate
I have 2 tables user and userinfo. userinfo table contains user_id(id of user table) column which has UNIQUE constraint.
now i have 2users(primaryUser and secondaryUser) which has records in user and userInfo tables.

The primaryInfo object contains primaryUserId and secondaryInfo object contains secondaryUserId

I want to swap the userinfo data of primaryUser to secondaryUser and viceversa. I am doing like this

```<code>primaryInfo.setUserId(secondaryUser.getId());
secondaryInfo.setUserId(primaryUser.getId());

session.update(primaryInfo);
session.update(secondaryInfo);
</code>```

but when commiting the transaction it is giving error like
ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper:147 ERROR: duplicate key value violates unique constraint "user_infos_unique_user"
  Detail: Key (ui_user_id)=(52560087) already exists.

can you please tell how to do this.. Thanks

答:
You can use the DEFERRABLE and INITIALLY DEFERRED properties on the constraint and update both records in a single transaction.   DEFERRED means the constraint will not be evaluated until the transaction is commited -- at which time it should be valid again.

However: I have not figured out how to use Hibernate annotations to specify the DEFERRED properties, so you will have to use LiquiBase to maintain the database schema (not a bad idea anyway.)  (Or use "raw" SQL which is not so good an idea.)

See this question for more about the annotations (alas I cannot use LiquiBase on the project I ask about there.)

Body:
I have 2 tables user and userinfo. userinfo table contains user_id(id of user table) column which has UNIQUE constraint.
now i have 2users(primaryUser and secondaryUser) which has records in user and userInfo tables.

The primaryInfo object contains primaryUserId and secondaryInfo object contains secondaryUserId

I want to swap the userinfo data of primaryUser to secondaryUser and viceversa. I am doing like this

primaryInfo.setUserId(secondaryUser.getId());
secondaryInfo.setUserId(primaryUser.getId());

session.update(primaryInfo);
session.update(secondaryInfo);

but when commiting the transaction it is giving error like
ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper:147 ERROR: duplicate key value violates unique constraint "user_infos_unique_user"
  Detail: Key (ui_user_id)=(52560087) already exists.

can you please tell how to do this.. Thanks


问:
capture image from camera and send it directly to server
I'm trying to write a small code that allows me to send picture directly after taking it from the camera, I mean when I take picture from the camera, this picture will be sent directly to the server without to store in my phone or in the sdcard, So I made this Code but I dont know if it is correct, because Actually it shows me much message error but I don't know where is the problem or if someone can tell me where can I find similar code,</p>

```<code>// Upload Direct From Camera
camButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent_gallery = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        intent_gallery.putExtra( MediaStore.EXTRA_OUTPUT, SERVER_URL + "uploadFromCamera.php" );
        startActivityForResult(intent_gallery, SELECT_IMAGE);
    }
});
...

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_IMAGE) {
            Uri selectedImageUri       = data.getData();
            String selectedImagePath   = getPath( selectedImageUri );
            String url                 = SERVER_URL + "uploadFromCamera.php";

            if ( selectedImagePath != null ) {
                //Send to server
            }
        }
    }
}

public String getPath(Uri uri) {
    String result = null;
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    if(cursor.moveToFirst()){;
       int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
       result = cursor.getString(column_index);
    }
    cursor.close();
    return result;
}
</code>```

答:
I did this tutorial, hope it helps, I use Retrofit to send it to server

```<code>    private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            ex.printStackTrace();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(MainActivity.this,
                    "com.example.cedancp.uploadimage",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, MainActivity.RC_CAPTURE_IMAGE);
        }
    }
}

private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
        imageFileName,  /* prefix */
        ".jpg",         /* suffix */
        storageDir      /* directory */
);

currentImagePath = image.getPath(); //Save current image path to send later to server
return image;
</code>```

}

```<code>    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
            case RC_CAPTURE_IMAGE:
                Log.i(TAG, "RESULT CODE " + resultCode);
                if (resultCode == RESULT_OK) {
                    if(currentImagePath.length() > 0)
                    sendImageToServer(currentImagePath);
                }else{
                    currentImagePath = "";
                    Toast.makeText(MainActivity.this,"Error capturing image",Toast.LENGTH_SHORT).show();
                }
                break;
 default:
            super.onActivityResult(requestCode, resultCode, data);
            break;
    }
}

private void sendImageToServer(String imagePath, final boolean camera){
    final File image = new File(imagePath);
    if(image != null) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), image);
        MultipartBody.Part body = MultipartBody.Part.createFormData("image", image.getName(), requestFile);
        Call<JsonObject> call = api.uploadImage(body);
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                if(response.code() == 200){
                    Toast.makeText(MainActivity.this,"Image Uploaded!",Toast.LENGTH_SHORT).show();
                    if(camera){ //Delete image if it was taken from camera
                        image.delete();
                    }
                }
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {

            }
        });
    }
}
</code>```

Disclosure: This link is to my own blog.

Tutorial upload image to server

Body:
I'm trying to write a small code that allows me to send picture directly after taking it from the camera, I mean when I take picture from the camera, this picture will be sent directly to the server without to store in my phone or in the sdcard, So I made this Code but I dont know if it is correct, because Actually it shows me much message error but I don't know where is the problem or if someone can tell me where can I find similar code,

// Upload Direct From Camera
camButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent_gallery = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        intent_gallery.putExtra( MediaStore.EXTRA_OUTPUT, SERVER_URL + "uploadFromCamera.php" );
        startActivityForResult(intent_gallery, SELECT_IMAGE);
    }
});
...

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_IMAGE) {
            Uri selectedImageUri       = data.getData();
            String selectedImagePath   = getPath( selectedImageUri );
            String url                 = SERVER_URL + "uploadFromCamera.php";

            if ( selectedImagePath != null ) {
                //Send to server
            }
        }
    }
}

public String getPath(Uri uri) {
    String result = null;
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    if(cursor.moveToFirst()){;
       int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
       result = cursor.getString(column_index);
    }
    cursor.close();
    return result;
}

Body:
I did this tutorial, hope it helps, I use Retrofit to send it to server

    private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            ex.printStackTrace();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(MainActivity.this,
                    "com.example.cedancp.uploadimage",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, MainActivity.RC_CAPTURE_IMAGE);
        }
    }
}

private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
        imageFileName,  /* prefix */
        ".jpg",         /* suffix */
        storageDir      /* directory */
);

currentImagePath = image.getPath(); //Save current image path to send later to server
return image;

}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
            case RC_CAPTURE_IMAGE:
                Log.i(TAG, "RESULT CODE " + resultCode);
                if (resultCode == RESULT_OK) {
                    if(currentImagePath.length() > 0)
                    sendImageToServer(currentImagePath);
                }else{
                    currentImagePath = "";
                    Toast.makeText(MainActivity.this,"Error capturing image",Toast.LENGTH_SHORT).show();
                }
                break;
 default:
            super.onActivityResult(requestCode, resultCode, data);
            break;
    }
}

private void sendImageToServer(String imagePath, final boolean camera){
    final File image = new File(imagePath);
    if(image != null) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), image);
        MultipartBody.Part body = MultipartBody.Part.createFormData("image", image.getName(), requestFile);
        Call<JsonObject> call = api.uploadImage(body);
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                if(response.code() == 200){
                    Toast.makeText(MainActivity.this,"Image Uploaded!",Toast.LENGTH_SHORT).show();
                    if(camera){ //Delete image if it was taken from camera
                        image.delete();
                    }
                }
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {

            }
        });
    }
}

Disclosure: This link is to my own blog.

Tutorial upload image to server


问:
Share custom ribbon with multiple add-ins (manifests)
I'm not sure if this is a bug or by design but I have two different add-ins (different manifest files) that I'm developing but I want them to use the same custom ribbon. Currently, it doesn't seem possible.

Expected:

The user should be able to do the following:

Add the first add-in called "A1" (side-loaded or through store)

The Custom ribbon should appear with the name "Awesome Stuff" which has a group of various command buttons that are specific to addin A1.

The user should return a few weeks later and now wants to use add-in "A2" so insert this add-in (via side-loading or office store).

Office would then recognize that the manifest for A2 contains the same ID/Name for the custom ribbon and add the command buttons for A2 into the same custom ribbon created by A1. They would be side-by-side under different Groups.

Observing:

It appears to me that the second add-in will create another tab with the same name and thus two separate manifest cannot share the same Custom Ribbon.

Screenshots of what I'm seeing

Environment

I'm using the latest Office Insiders of Excel (16.8 build 171111). I tested in Excel Online and same result.

Question

Is this by design or potentially a bug?

Is there something wrong or missing from my manifest?

I'm guessing the standard excel ribbons (main, insert, etc...) do not have this problem?

Why not use a single manifest?

Assuming the above is by design...The second add-in is additive features on top of the first manifest. All the users will be using the features of the first add-in but only certain users will be using the second add-in. If we including it in a single manifest it will confuse users that do not need it so ideally we would like them separate.

答:
This isn't possible currently. I recommend visiting the UserVoice and adding this as a suggestion.

That said, there are some interesting concerns this would raise. It would open up the possibility for other add-ins to accidentally (or maliciously) break your add-in's commands/tab by inserting their own commands/tab with the same id.

A better option, based on the scenario you outlined, would be to support altering the ribbon at run time (there is an existing UserVoice that speaks to this). It sounds like the ability to add or enable/disable commands to the ribbon at run-time would allow you to provide everything in a single add-in.


问:
zend framework join 3 tables
I have 3 tables (order, product, order_item). In order i have the date. In order_item i have product_id and order_id. I need to select all products with orders, what created in the current month. It is my select:

```<code>$select = $this->select()
    ->setIntegrityCheck(false)
    ->from(array('o' => 'order'))
    ->join(array('oi' => 'order_item'), 'o.id = oi.order_id', array('quantity'))
        ->joinLeft(array('p' => 'product'), 'p.id = oi.product_id', array('id', 'pbv', 'name'))
        ->where('MONTH(o.date) = MONTH(CURDATE())');
</code>```

But when i haven't orders result is empty. And i should always have all products. Sorry for my english. Thanks.

答:
It was very hard. The right SQL:</p>

```<code>USE lyf;
SELECT
  *
FROM
  `order` AS o
  LEFT JOIN order_item AS oi ON oi.order_id = o.id
  RIGHT JOIN product AS p ON oi.product_id = p.id
WHERE
  IF(o.`date` IS NOT NULL, MONTH(o.`date`) = MONTH(NOW()), 1) = 1
</code>```

Title: zend framework join 3 tables

Body:
I have 3 tables (order, product, order_item). In order i have the date. In order_item i have product_id and order_id. I need to select all products with orders, what created in the current month. It is my select:

$select = $this->select()
    ->setIntegrityCheck(false)
    ->from(array('o' => 'order'))
    ->join(array('oi' => 'order_item'), 'o.id = oi.order_id', array('quantity'))
        ->joinLeft(array('p' => 'product'), 'p.id = oi.product_id', array('id', 'pbv', 'name'))
        ->where('MONTH(o.date) = MONTH(CURDATE())');

But when i haven't orders result is empty. And i should always have all products. Sorry for my english. Thanks.

Body:
It was very hard. The right SQL:

USE lyf;
SELECT
  *
FROM
  `order` AS o
  LEFT JOIN order_item AS oi ON oi.order_id = o.id
  RIGHT JOIN product AS p ON oi.product_id = p.id
WHERE
  IF(o.`date` IS NOT NULL, MONTH(o.`date`) = MONTH(NOW()), 1) = 1


问:
Bash: check if one decimal number is greater than another decimal number
I have a case like this:

```<code>string1="some_string"
string2="some_string"
int1="0.87"
int2="${var}"
</code>```

$var is the output of some other script, and it has the form 0.994343123 or 0.3454657 or whatever (starts with 0. and the biggest value is around 0.9972343)

Now, I don't know how bash works, but usually string 0.87 is never less than or equal to 0.9999999, they are just different.

I would need something like this (pseudocode):

```<code>if (string1 equals string2 and int1 is less than int2):
    do something;
else
    do something else.
</code>```

What i would expect is 0.87687 is greater than 0.87 (correct?? i was never good at math...)

Can anyone help me with the code for that if??

Thanks in advance!

答:
```<code>a=0.86
b=0.865
if ((`echo $a '<' $b|bc`)); then echo 'a<b'; fi
</code>```

(You can replace the last line by

```<code>if (($(echo $a '<' $b|bc))); then echo 'a<b'; fi
</code>```

but imho it is less readable)

Body:
I have a case like this:

string1="some_string"
string2="some_string"
int1="0.87"
int2="${var}"

$var is the output of some other script, and it has the form 0.994343123 or 0.3454657 or whatever (starts with 0. and the biggest value is around 0.9972343)

Now, I don't know how bash works, but usually string 0.87 is never less than or equal to 0.9999999, they are just different.

I would need something like this (pseudocode):

if (string1 equals string2 and int1 is less than int2):
    do something;
else
    do something else.

What i would expect is 0.87687 is greater than 0.87 (correct?? i was never good at math...)

Can anyone help me with the code for that if??

Thanks in advance!

Body:
a=0.86
b=0.865
if ((`echo $a '<' $b|bc`)); then echo 'a<b'; fi

(You can replace the last line by

if (($(echo $a '<' $b|bc))); then echo 'a<b'; fi

but imho it is less readable)


问:
Swift 3 better way to write this if-statement
I am comparing values in a GKNoise field and then setting tiles into a tileMap based on the level of noise

This if-statement is comparing the values by rounding up to the nearest tenth, is there a better way to write it?

```<code>if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -1.0 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.9 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.8 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.7 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.6 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.5 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.4 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.3 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.2 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.1 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.0 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.1 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.2 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.3 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.4 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.5 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.6 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.7 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.8 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.9 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 1.0 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
</code>```

It seems a little drawn out and not very efficient.

答:
Just for fun:

No if / switch statement needed at all

```<code>let noise = MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) + 1
let index = Int(round(noise * 10)) / 5
let tileGroup = [tileGroup4,tileGroup3,tileGroup2,tileGroup1,tileGroup1]
tileMap.setTileGroup(tileGroup[index], forColumn: columns, row: rows)
</code>```

Body:
I am comparing values in a GKNoise field and then setting tiles into a tileMap based on the level of noise

This if-statement is comparing the values by rounding up to the nearest tenth, is there a better way to write it?

if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -1.0 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.9 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.8 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.7 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.6 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.5 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.4 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.3 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.2 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.1 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.0 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.1 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.2 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.3 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.4 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.5 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.6 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.7 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.8 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.9 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 1.0 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}

It seems a little drawn out and not very efficient.

Body:
Just for fun:

No if / switch statement needed at all

let noise = MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) + 1
let index = Int(round(noise * 10)) / 5
let tileGroup = [tileGroup4,tileGroup3,tileGroup2,tileGroup1,tileGroup1]
tileMap.setTileGroup(tileGroup[index], forColumn: columns, row: rows)


问:
finding the average of array then finding the number above the average to print
```<code>import java.util.Scanner;
public class ProjectFour {
    public static void main(String args[]) {
int[] firstArray = {1,2,3,2,1,6,3,4,5};
System.out.println("this is the average of array : "+analyzeNumbers(firstArray));
System.out.println("These are the numbers above the average : "+aboveAvg(firstArray));
    }
    //finding the average
    public static int analyzeNumbers(int[] firstArray){
    int avg;
    avg=sumArray(firstArray);
    avg=avg/firstArray.length;
    return avg;
    }
    //suming the array method
    public static int sumArray(int[] firstArray){
    int sum = 0;
    for(int x=0;x<firstArray.length;x++){
        sum+=firstArray[x];
    }
    return sum;
}

**this is where im running into problems im kinda stumpted**
</code>```

<p>// this is my method i cant figure out trying to take the average and find all the numbers in the array above the average and printing them.</p>

```<code> public static int aboveAvg(int[] firstArray){
    int[] aboveAvg;
    aboveAvg = new int[0];
    int x;
    for(x=analyzeNumbers(firstArray);x<firstArray.length;x++){
        aboveAvg+=firstArray[x];
    }
    return aboveAvg;
    }
    }
</code>```

答:
Try using a for loop.</p>

```<code>int sum = 0;
    for(int i = 0; i < firstArray; i++) {
int getSum = firstArray.get(i);
sum + getSum;
    }
int average = sum / firstArray.length;

int[] aboveAverage;
for(int c = 0; c < firstArray; c++) {
if(firstArray.get(c) > average) {
aboveAverage.add(firstArray.get(c));
}
}
</code>```

Body:
import java.util.Scanner;
public class ProjectFour {
    public static void main(String args[]) {
int[] firstArray = {1,2,3,2,1,6,3,4,5};
System.out.println("this is the average of array : "+analyzeNumbers(firstArray));
System.out.println("These are the numbers above the average : "+aboveAvg(firstArray));
    }
    //finding the average
    public static int analyzeNumbers(int[] firstArray){
    int avg;
    avg=sumArray(firstArray);
    avg=avg/firstArray.length;
    return avg;
    }
    //suming the array method
    public static int sumArray(int[] firstArray){
    int sum = 0;
    for(int x=0;x<firstArray.length;x++){
        sum+=firstArray[x];
    }
    return sum;
}

**this is where im running into problems im kinda stumpted**

// this is my method i cant figure out trying to take the average and find all the numbers in the array above the average and printing them.

 public static int aboveAvg(int[] firstArray){
    int[] aboveAvg;
    aboveAvg = new int[0];
    int x;
    for(x=analyzeNumbers(firstArray);x<firstArray.length;x++){
        aboveAvg+=firstArray[x];
    }
    return aboveAvg;
    }
    }

Body:
Try using a for loop.

int sum = 0;
    for(int i = 0; i < firstArray; i++) {
int getSum = firstArray.get(i);
sum + getSum;
    }
int average = sum / firstArray.length;

int[] aboveAverage;
for(int c = 0; c < firstArray; c++) {
if(firstArray.get(c) > average) {
aboveAverage.add(firstArray.get(c));
}
}