问:
CSS - Keep divs in columns aligned
I tried searching for what I was looking for, but I kept on finding things for css on internal divs.

Anyway, what I am trying to do is have two columns of divs be aligned with oneanother, with the right column always being aligned to the top of  the left column. This is where I am drawing a blank, I can't seem to figure out how to do that.

The size of the left column is dynamic, so I can't use the :height property to keep things in order.

Here is what I am trying to do:

答:
I wanted to create a grid, but simple tables and nested divs forced me to lay out rows at a time. This made it hard to stack columns for a responsive design.

Here's a code pen that uses flexboxes to create grids. The first one lets you specify rows at a time, while the second one lets you specify columns at a time.

https://codepen.io/chaimleib/pen/zPPGgj

HTML:

```<code><h2>By row</h2>
<div class="table table3cols">
  <div class="table-cell"><h3>Eddard Stark</h3></div>
  <div class="table-cell">Sword named Ice</div>
  <div class="table-cell">No direwolf</div>

  <div class="table-cell"><h3>Jon Snow</h3></div>
  <div class="table-cell">Sword named Longclaw</div>
  <div class="table-cell">Direwolf: Ghost</div>

  <div class="table-cell"><h3>Arya Stark</h3></div>
  <div class="table-cell">Sword named Needle</div>
  <div class="table-cell">Direwolf: Nymeria</div>
</div>

<h2>By column</h2>

<div class="table table3cols">
  <div style="order:1;" class="table-cell"><h3>Eddard Stark</h3></div>
  <div style="order:2;" class="table-cell">Sword named Ice</div>
  <div style="order:3;" class="table-cell">No direwolf</div>

  <div style="order:1;" class="table-cell"><h3>Jon Snow</h3></div>
  <div style="order:2;" class="table-cell">Sword named Longclaw</div>
  <div style="order:3;" class="table-cell">Direwolf: Ghost</div>

  <div style="order:1;" class="table-cell"><h3>Arya Stark</h3></div>
  <div style="order:2;" class="table-cell">Sword named Needle</div>
  <div style="order:3;" class="table-cell">Direwolf: Nymeria</div>
</div>
</code>```

LESS:

```<code>/* Variables
================================== */
@bw: 3px;  // border width

/* Tables
================================== */
.table {
  display: flex;
  flex-wrap: wrap;
  margin: 0 0 3em 0;
  padding: 0;
}
.table-cell {
  box-sizing: border-box;
  flex-grow: 1;
  width: 100%;  // Default to full width
  padding: 0.8em 1.2em;
  overflow: hidden; // Or flex might break
  list-style: none;
  border: solid @bw white; // margins would overflow row and cause early wrapping
  background: fade(slategrey,20%);
  > h1, > h2, > h3, > h4, > h5, > h6 { margin: 0; }
}

/* Table column sizing
================================== */
.table2cols > .table-cell  { width: 50%; }
.table3cols > .table-cell  { width: 33.33%; }
.table4cols > .table-cell  { width: 25%; }

/* Page styling
================================== */

body {
  border: 1px solid grey;
  margin: 0 auto;
  max-width: 800px;
  padding: 2em;
}
h1, h2, h3, h4, h5, h6 { margin-top: 0; }
</code>```

Credit for the technique goes to Davide Rizzo, whose article also shows spiffy ways to make the design responsive.

Title: CSS - Keep divs in columns aligned

Body:
I wanted to create a grid, but simple tables and nested divs forced me to lay out rows at a time. This made it hard to stack columns for a responsive design.

Here's a code pen that uses flexboxes to create grids. The first one lets you specify rows at a time, while the second one lets you specify columns at a time.

https://codepen.io/chaimleib/pen/zPPGgj

HTML:

<h2>By row</h2>
<div class="table table3cols">
  <div class="table-cell"><h3>Eddard Stark</h3></div>
  <div class="table-cell">Sword named Ice</div>
  <div class="table-cell">No direwolf</div>

  <div class="table-cell"><h3>Jon Snow</h3></div>
  <div class="table-cell">Sword named Longclaw</div>
  <div class="table-cell">Direwolf: Ghost</div>

  <div class="table-cell"><h3>Arya Stark</h3></div>
  <div class="table-cell">Sword named Needle</div>
  <div class="table-cell">Direwolf: Nymeria</div>
</div>

<h2>By column</h2>

<div class="table table3cols">
  <div style="order:1;" class="table-cell"><h3>Eddard Stark</h3></div>
  <div style="order:2;" class="table-cell">Sword named Ice</div>
  <div style="order:3;" class="table-cell">No direwolf</div>

  <div style="order:1;" class="table-cell"><h3>Jon Snow</h3></div>
  <div style="order:2;" class="table-cell">Sword named Longclaw</div>
  <div style="order:3;" class="table-cell">Direwolf: Ghost</div>

  <div style="order:1;" class="table-cell"><h3>Arya Stark</h3></div>
  <div style="order:2;" class="table-cell">Sword named Needle</div>
  <div style="order:3;" class="table-cell">Direwolf: Nymeria</div>
</div>

LESS:

/* Variables
================================== */
@bw: 3px;  // border width

/* Tables
================================== */
.table {
  display: flex;
  flex-wrap: wrap;
  margin: 0 0 3em 0;
  padding: 0;
}
.table-cell {
  box-sizing: border-box;
  flex-grow: 1;
  width: 100%;  // Default to full width
  padding: 0.8em 1.2em;
  overflow: hidden; // Or flex might break
  list-style: none;
  border: solid @bw white; // margins would overflow row and cause early wrapping
  background: fade(slategrey,20%);
  > h1, > h2, > h3, > h4, > h5, > h6 { margin: 0; }
}

/* Table column sizing
================================== */
.table2cols > .table-cell  { width: 50%; }
.table3cols > .table-cell  { width: 33.33%; }
.table4cols > .table-cell  { width: 25%; }

/* Page styling
================================== */

body {
  border: 1px solid grey;
  margin: 0 auto;
  max-width: 800px;
  padding: 2em;
}
h1, h2, h3, h4, h5, h6 { margin-top: 0; }

Credit for the technique goes to Davide Rizzo, whose article also shows spiffy ways to make the design responsive.


来源: stackexchange

问:
refer to Gradle task which is defined later in build
Our build has some generic logic to create tasks from configuration data. There are also several Gradle files on whose execution order I do not want to depend.

Now I need to add a task dependency to a task without knowing if that task will be defined before my part of the build script runs (at configuration time) or after my part.

[Edit: as @canillas writes I can say myTask.dependsOn "otherTask" and "lazily" depend on yet undefined "otherTask", but I need it the other way around.]

Since I can't write tasks["otherTask"].dependsOn myNewTask before "otherTask" is defined, I made the following helper function:

void safelyDoWithTask(String taskName, Closure func) {
    def task = tasks.findByName(taskName)
    if (task != null) {
        func(task)
    } else {
        project.tasks.whenTaskAdded { task_ ->
            if (taskName.equals(task_.getName())) {
                func(task_)
            }
        }
    }
}

safelyDoWithTask('otherTask', { it.dependsOn myNewTask })
```

Now I wonder if there is more canonical way to achieve this?

答:
Consider the following:

```<code>// section 1
def dynamicDependencies = [:]

dynamicDependencies['otherTask'] = 'myNewTask'

// section 2
afterEvaluate { project ->
    // taskA dependsOn taskB
    dynamicDependencies.each { taskA, taskB ->
        def task = project.tasks.findByName(taskA)
        if (task) { task.dependsOn "${taskB}" }
    }
}

// section 3
task myNewTask() {
    doLast {
        println 'myNewTask !'
    }
}

task otherTask() {
    doLast {
        println 'otherTask !'
    }
}
</code>```

The gist is:

section 1 defines our dependency info in a custom map

section 2 uses the afterEvaluate hook to process the map

because the above is decoupled from the task definitions, we can simply put them in section 3 (or wherever)

ContentLicense: CC BY-SA 3.0

Body:
Our build has some generic logic to create tasks from configuration data. There are also several Gradle files on whose execution order I do not want to depend.

Now I need to add a task dependency to a task without knowing if that task will be defined before my part of the build script runs (at configuration time) or after my part.

[Edit: as @canillas writes I can say myTask.dependsOn "otherTask" and "lazily" depend on yet undefined "otherTask", but I need it the other way around.]

Since I can't write tasks["otherTask"].dependsOn myNewTask before "otherTask" is defined, I made the following helper function:

void safelyDoWithTask(String taskName, Closure func) {
    def task = tasks.findByName(taskName)
    if (task != null) {
        func(task)
    } else {
        project.tasks.whenTaskAdded { task_ ->
            if (taskName.equals(task_.getName())) {
                func(task_)
            }
        }
    }
}

safelyDoWithTask('otherTask', { it.dependsOn myNewTask })

Now I wonder if there is more canonical way to achieve this?

Body:
Consider the following:

// section 1
def dynamicDependencies = [:]

dynamicDependencies['otherTask'] = 'myNewTask'

// section 2
afterEvaluate { project ->
    // taskA dependsOn taskB
    dynamicDependencies.each { taskA, taskB ->
        def task = project.tasks.findByName(taskA)
        if (task) { task.dependsOn "${taskB}" }
    }
}

// section 3
task myNewTask() {
    doLast {
        println 'myNewTask !'
    }
}

task otherTask() {
    doLast {
        println 'otherTask !'
    }
}

The gist is:

section 1 defines our dependency info in a custom map

section 2 uses the afterEvaluate hook to process the map

because the above is decoupled from the task definitions, we can simply put them in section 3 (or wherever)


问:
Windows Critical Section strange behaviour
I have two shared global variables

```<code>int a = 0;
int b = 0;
</code>```

and two threads

```<code>// thread 1
for (int i = 0; i < 10; ++i) {
    EnterCriticalSection(&sect);
    a++;
    b++;
    std::cout << a " " << b << std::endl;
    LeaveCriticalSection(&sect);
}

// thread2
for (int i = 0; i < 10; ++i) {
    EnterCriticalSection(&sect);
    a--;
    b--;
    std::cout << a " " << b << std::endl;
    LeaveCriticalSection(&sect);
}
</code>```

The code always prints the following output

1 1

2 2

3 3

4 4

5 5

6 6

7 7

8 8

9 9

10 10

9 9

8 8

7 7

6 6

5 5

4 4

3 3

2 2

1 1

0 0

That is quite strange, looks like threads are working sequentally.. What's the problem with that?

Thanks.

答:
Each thread has a specific time slice during which it executes before being preempted. In your example, the time slice seems to be longer than the time required to complete the loop.

However, you can actively yield control by calling Sleep(0) after leaving the critical section inside the loop.

ContentLicense: CC BY-SA 2.5

Body:
I have two shared global variables

int a = 0;
int b = 0;

and two threads

// thread 1
for (int i = 0; i < 10; ++i) {
    EnterCriticalSection(&sect);
    a++;
    b++;
    std::cout << a " " << b << std::endl;
    LeaveCriticalSection(&sect);
}

// thread2
for (int i = 0; i < 10; ++i) {
    EnterCriticalSection(&sect);
    a--;
    b--;
    std::cout << a " " << b << std::endl;
    LeaveCriticalSection(&sect);
}

The code always prints the following output

1 1

2 2

3 3

4 4

5 5

6 6

7 7

8 8

9 9

10 10

9 9

8 8

7 7

6 6

5 5

4 4

3 3

2 2

1 1

0 0

That is quite strange, looks like threads are working sequentally.. What's the problem with that?

Thanks.


问:
MongoDB agregation and comparing
I need to write mongodb query that will agregate items by quantinty (orders collestion). After agregation, or with agregation, it should identify items that can't be supplied in stock collection, and return name of the person who made this order

code of orders insert

```<code>db.orders.insertMany([
{client:  {firstName: "John",lastName: "Smith" },orderedItems: [{ name: "itemA", qty: 5},{ name: "itemS", qty: 3}]},
{client:  {firstName: "Jan",lastName: "Nowak" },orderedItems: [{ name: "itemA", qty: 56},{ name: "itemS", qty: 53}]},
{client:  {firstName: "Klara",lastName: "Bolączka" },orderedItems: [{ name: "itemA", qty: 35},{ name: "itemS", qty: 23}]},
{client:  {firstName: "Brajan",lastName: "Kowalski" },orderedItems: [{ name: "itemA", qty: 95},{ name: "itemS", qty: 13}]}
]);
</code>```

code of stocks insert

```<code>db.stock.insertMany([
{ item: "itemA", qty: 40},
{ item: "itemS", qty: 113}
]);
</code>```

Right now i got some mongoDB code, that just agregates orders

```<code>db.orders.aggregate([
{$unwind: "$orderedItems"},
{$group: { _id: "$orderedItems.name", total:{$sum: "$orderedItems.qty"}}}
]);
</code>```

I tried to use lookup, but probably I'm doing something wrong.

Could I get some sugestions, please?

答:
How would you like something like this:</p>

```<code>db.orders.aggregate([
{
    $unwind: "$orderedItems" // flatten the "orderedItems" array
},
{
    $group: {
        "_id": "$orderedItems.name", // group by orderItems.name
        "total": {
            $sum: "$orderedItems.qty" // calculate total quantity
        },
        "users": {
            $addToSet: "$client" // create an array of clients who have ordered each item
        }
    }
}, {
    $lookup: { // retrieve the stock information
       from: "stock",
       localField: "_id",
       foreignField: "item",
       as: "stock"
    }
}, {
    $unwind: "$stock" // flatten the result array - should always return only one document, given your data model
}, {
    $addFields: { // add a new field...
        "difference": { // ...called "difference"...
            $subtract: [ "$stock.qty", "$total" ] // ...in which we store the difference between the stock qty and the ordered qty
        }
    }
}, {
    $match: { // only return documents...
        "difference": { // ...where the value for "difference"...
            $lt: 0 // ...is less than zero
        }
    }
}])
</code>```

Title: MongoDB agregation and comparing

Body:
I need to write mongodb query that will agregate items by quantinty (orders collestion). After agregation, or with agregation, it should identify items that can't be supplied in stock collection, and return name of the person who made this order

code of orders insert

db.orders.insertMany([
{client:  {firstName: "John",lastName: "Smith" },orderedItems: [{ name: "itemA", qty: 5},{ name: "itemS", qty: 3}]},
{client:  {firstName: "Jan",lastName: "Nowak" },orderedItems: [{ name: "itemA", qty: 56},{ name: "itemS", qty: 53}]},
{client:  {firstName: "Klara",lastName: "Bolączka" },orderedItems: [{ name: "itemA", qty: 35},{ name: "itemS", qty: 23}]},
{client:  {firstName: "Brajan",lastName: "Kowalski" },orderedItems: [{ name: "itemA", qty: 95},{ name: "itemS", qty: 13}]}
]);

code of stocks insert

db.stock.insertMany([
{ item: "itemA", qty: 40},
{ item: "itemS", qty: 113}
]);

Right now i got some mongoDB code, that just agregates orders

db.orders.aggregate([
{$unwind: "$orderedItems"},
{$group: { _id: "$orderedItems.name", total:{$sum: "$orderedItems.qty"}}}
]);

I tried to use lookup, but probably I'm doing something wrong.

Could I get some sugestions, please?

Body:
How would you like something like this:

db.orders.aggregate([
{
    $unwind: "$orderedItems" // flatten the "orderedItems" array
},
{
    $group: {
        "_id": "$orderedItems.name", // group by orderItems.name
        "total": {
            $sum: "$orderedItems.qty" // calculate total quantity
        },
        "users": {
            $addToSet: "$client" // create an array of clients who have ordered each item
        }
    }
}, {
    $lookup: { // retrieve the stock information
       from: "stock",
       localField: "_id",
       foreignField: "item",
       as: "stock"
    }
}, {
    $unwind: "$stock" // flatten the result array - should always return only one document, given your data model
}, {
    $addFields: { // add a new field...
        "difference": { // ...called "difference"...
            $subtract: [ "$stock.qty", "$total" ] // ...in which we store the difference between the stock qty and the ordered qty
        }
    }
}, {
    $match: { // only return documents...
        "difference": { // ...where the value for "difference"...
            $lt: 0 // ...is less than zero
        }
    }
}])


问:
How to ignore javascript timezone to send a datetime to server
I am building a web app with c# and angular to store event schedule. The user will input a date time which is in UTC and I want to save that time in db exactly as inputted. And then show exactly same time when a user will view this information. And this should not depend on user's timezone, and I am telling the user that time is in UTC.

But the problem is browser send time information with timezone info when ajax post to server and server saves a different time (by converting its own timezone) in db as the server is in a different timezone.

How to prevent this?

答:
I am not sure how you are formatting. But I think you could use momentjs in case you don't want to use any custom solution. The following code should work

moment(your_date_time).format('YYYY-MM-DD HH:mm:ss')

in case your_date_time has time zone, then the following should work

moment().utc().format('YYYY-MM-DD HH:mm:ss')


问:
changing type in getter - sequelize with graphql
I'm trying to stringify an array as I save it to my mysql database, and parse it when I retrieve it, but I'm getting "String cannot represent an array". Is changing the type in a getter possible with sequelize and if so how would it be done?</p>

```<code>choices: {
  type:Sequelize.TEXT,
  get(){
    var val = this.getDataValue('choices');
    return val ? JSON.parse(val):null;
  },
  set(val){
    if(val && typeof(val)!=='string'){
      val = JSON.stringify(val);
    }
    this.setDataValue('choices',val);
  }
},
</code>```

答:
This was not a problem with sequelize or mysql. This was a problem with my GraphQL mutation where I had to override a type

```<code>import { attributeFields } from "graphql-sequelize";
import { GraphQLList, GraphQLString } from "graphql";
import { Question } from "../schemas/Question";
import ResponsePayload from "../schemas/ResponsePayload";
import _ from "lodash";

var base = _.assign(attributeFields(sequelize.models.question, {
  exclude: ["id", "createdAt", "updatedAt"]
}), { choices: { type: new GraphQLList(GraphQLString) }});

const CreateQuestion = {
  type: ResponsePayload,
  args: base,
  resolve: ...
};

export { CreateQuestion };
</code>```

specifically I had to change

```<code>var base = attributeFields(sequelize.models.question, {
  exclude: ["id", "createdAt", "updatedAt"]
});
</code>```

to

```<code>var base = _.assign(attributeFields(sequelize.models.question, {
  exclude: ["id", "createdAt", "updatedAt"]
}), { choices: { type: new GraphQLList(GraphQLString) }});
</code>```

This overrides the type of choices, which is defined as a String in the sequelize model, but needs to be an array as far as GraphQL is concerned.

Body:
I'm trying to stringify an array as I save it to my mysql database, and parse it when I retrieve it, but I'm getting "String cannot represent an array". Is changing the type in a getter possible with sequelize and if so how would it be done?

choices: {
  type:Sequelize.TEXT,
  get(){
    var val = this.getDataValue('choices');
    return val ? JSON.parse(val):null;
  },
  set(val){
    if(val && typeof(val)!=='string'){
      val = JSON.stringify(val);
    }
    this.setDataValue('choices',val);
  }
},

Body:
This was not a problem with sequelize or mysql. This was a problem with my GraphQL mutation where I had to override a type

import { attributeFields } from "graphql-sequelize";
import { GraphQLList, GraphQLString } from "graphql";
import { Question } from "../schemas/Question";
import ResponsePayload from "../schemas/ResponsePayload";
import _ from "lodash";

var base = _.assign(attributeFields(sequelize.models.question, {
  exclude: ["id", "createdAt", "updatedAt"]
}), { choices: { type: new GraphQLList(GraphQLString) }});

const CreateQuestion = {
  type: ResponsePayload,
  args: base,
  resolve: ...
};

export { CreateQuestion };

specifically I had to change

var base = attributeFields(sequelize.models.question, {
  exclude: ["id", "createdAt", "updatedAt"]
});

to

var base = _.assign(attributeFields(sequelize.models.question, {
  exclude: ["id", "createdAt", "updatedAt"]
}), { choices: { type: new GraphQLList(GraphQLString) }});

This overrides the type of choices, which is defined as a String in the sequelize model, but needs to be an array as far as GraphQL is concerned.


答:
IMO critical section leave/enter in your example is so fast that another thread is not fast enough to execute enter section during this moment.

Try to put some (maybe random) sleeps to slow down code to see desired effects.

Note:
Default timeout for EnterCriticalSection is like 30 days or so (means infinty) so you cannot expect that function will time out. And documentation says:

There is no guarantee about the order in which threads will obtain ownership of the critical section, however, the system will be fair to all threads.

Title: Windows Critical Section strange behaviour


问:
Areas with missing data are dropped from geom_sf /ggplot2 map. Why?
I have troubles to print maps with missing data.

I am able to produce an "empty" shapefile:

```<code>empty.shape.sf <-
  ggplot(BiH.shape.sf)+
  geom_sf(fill="grey",colour="black")+
  theme(legend.position="none",
        axis.title=element_blank(),
        axis.text=element_blank(),
        axis.ticks = element_blank(),
        strip.text.y = element_text(size = 10),
        panel.background=element_rect(fill="white"))

print(empty.shape.sf)
</code>```

I then add data to the shapefile

```<code>df.shape <- dplyr::left_join(BiH.shape.sf, data, by="ID_3")
</code>```

and produce the new maps.

```<code>data.map <- df.shape%>%
  filter(year==2000|year==2004)%>%
  ggplot()+
  geom_sf(aes(fill=res), colour="black")+
  theme(legend.position="none",
        axis.title=element_blank(),
        axis.text=element_blank(),
        axis.ticks = element_blank(),
        strip.text.y = element_text(size = 10),
        panel.background=element_rect(fill="white"))+
  scale_fill_gradient(low="blue", high="red", limits=c(0,100))+
  facet_wrap(~year)

print(data.map)
</code>```

Why are the areas for which the projected data is missing without borders/dropped? I would have assumed that by using left_join all borders/areas remain preserved. How can I keep these borders/areas? Is there no other way than to create a 'complete' dataset which includes rows with NAs for each missing area?

答:
I think you can simply add the argument na.value to your call to scale_fill_gradient. Here is a reproducible example using the North Carolina shapefile included in the sf package:

```<code>library(ggplot2)
library(sf)
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
nc$BIR74[1] <- NA
nc %>% ggplot()+
  geom_sf(aes(fill=BIR74), colour="white")+
  theme(legend.position="none",
        axis.title=element_blank(),
        axis.text=element_blank(),
        axis.ticks = element_blank(),
        strip.text.y = element_text(size = 10),
        panel.background=element_rect(fill="white"))+
  scale_fill_gradient(low="blue", high="red",na.value = "black")
</code>```

Since I can't reproduce your particular example, I'd guess that you want to use a different type of join, otherwise the shapefile will retain those missing rows (and missing shapes) as mentioned.

Body:
I have troubles to print maps with missing data.

I am able to produce an "empty" shapefile:

empty.shape.sf <-
  ggplot(BiH.shape.sf)+
  geom_sf(fill="grey",colour="black")+
  theme(legend.position="none",
        axis.title=element_blank(),
        axis.text=element_blank(),
        axis.ticks = element_blank(),
        strip.text.y = element_text(size = 10),
        panel.background=element_rect(fill="white"))

print(empty.shape.sf)

I then add data to the shapefile

df.shape <- dplyr::left_join(BiH.shape.sf, data, by="ID_3")

and produce the new maps.

data.map <- df.shape%>%
  filter(year==2000|year==2004)%>%
  ggplot()+
  geom_sf(aes(fill=res), colour="black")+
  theme(legend.position="none",
        axis.title=element_blank(),
        axis.text=element_blank(),
        axis.ticks = element_blank(),
        strip.text.y = element_text(size = 10),
        panel.background=element_rect(fill="white"))+
  scale_fill_gradient(low="blue", high="red", limits=c(0,100))+
  facet_wrap(~year)

print(data.map)

Why are the areas for which the projected data is missing without borders/dropped? I would have assumed that by using left_join all borders/areas remain preserved. How can I keep these borders/areas? Is there no other way than to create a 'complete' dataset which includes rows with NAs for each missing area?

Body:
I think you can simply add the argument na.value to your call to scale_fill_gradient. Here is a reproducible example using the North Carolina shapefile included in the sf package:

library(ggplot2)
library(sf)
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
nc$BIR74[1] <- NA
nc %>% ggplot()+
  geom_sf(aes(fill=BIR74), colour="white")+
  theme(legend.position="none",
        axis.title=element_blank(),
        axis.text=element_blank(),
        axis.ticks = element_blank(),
        strip.text.y = element_text(size = 10),
        panel.background=element_rect(fill="white"))+
  scale_fill_gradient(low="blue", high="red",na.value = "black")

Since I can't reproduce your particular example, I'd guess that you want to use a different type of join, otherwise the shapefile will retain those missing rows (and missing shapes) as mentioned.


问:
Best Kentico Way to Host Multiple 404 pages in the Content Tree
I'm looking for the best (or a very good) "Kentico way" to accomplish having multiple 404 Not Found pages inside the content tree, each for a different area of the content tree.

For example, given the following hypothetical content tree structure with blog items and partner profiles,

```<code>% Root Master
|__ Home
|__ Blog ._ Blog Item A
         |_ Blog Item B
         |_ Blog Item C
         |_ 404 Page for Blogs
|__ Policy
|__ Partners ._ Partner Profile A
             |_ Partner Profile B
             |_ Partner Profile C
             |_ 404 Page for Partners
|_ Site 404 Page
</code>```

I'm looking for the following behaviour:

if the user visits a Blog Item D which does not exist, I want to 404 Page for Blogs to be displayed.

likewise if the user visits a Partner Profile D which does not exist,I want the 404 Page for Partners to show.

If any other page is Not found in the site then the Site 404 Page should be shown, as per normal, through Kentico setting for this.

I'm hesitant to dip down into only using ASP.NET configuration for this because I want to maintain the solution inside Kentico and without recycling the website's application pool when adding new 404 pages.

My immediate thought is to create a custom web part that I can drop onto the Site's global 404 Page Template (the default place for every 404).  This web part would use the Error Path (ala querystring value aspxerrorpath=) to  see the path that was not found and then check to see if it contains the word "blogs" or "partners" and redirect the browser to the appropriate sub-404-page respectively. Or, is there an even simpler approach -- maybe using page aliases and/or macros -- while keeping the solution inside Kentico?

I'm using Kentico 9 & 10.

答:
I do not believe there is a good way to handle this within Kentico.  The best way is most likely going to be adding <location> elements in your master web.config and setting those paths and 404 pages in there.

Another might be to manage it via a webpart as you mentioned.  But I might take it one step further and make a module out of it so your webpart could perform a lookup based on the referring URL or error page in question and do any custom displaying or redirecting based on the lookup values it matches.

Body:
I'm looking for the best (or a very good) "Kentico way" to accomplish having multiple 404 Not Found pages inside the content tree, each for a different area of the content tree.

For example, given the following hypothetical content tree structure with blog items and partner profiles,

% Root Master
|__ Home
|__ Blog ._ Blog Item A
         |_ Blog Item B
         |_ Blog Item C
         |_ 404 Page for Blogs
|__ Policy
|__ Partners ._ Partner Profile A
             |_ Partner Profile B
             |_ Partner Profile C
             |_ 404 Page for Partners
|_ Site 404 Page

I'm looking for the following behaviour:

if the user visits a Blog Item D which does not exist, I want to 404 Page for Blogs to be displayed.

likewise if the user visits a Partner Profile D which does not exist,I want the 404 Page for Partners to show.

If any other page is Not found in the site then the Site 404 Page should be shown, as per normal, through Kentico setting for this.

I'm hesitant to dip down into only using ASP.NET configuration for this because I want to maintain the solution inside Kentico and without recycling the website's application pool when adding new 404 pages.

My immediate thought is to create a custom web part that I can drop onto the Site's global 404 Page Template (the default place for every 404).  This web part would use the Error Path (ala querystring value aspxerrorpath=) to  see the path that was not found and then check to see if it contains the word "blogs" or "partners" and redirect the browser to the appropriate sub-404-page respectively. Or, is there an even simpler approach -- maybe using page aliases and/or macros -- while keeping the solution inside Kentico?

I'm using Kentico 9 & 10.


答:
try to run DBCC CHECKDB against your DB, it looks like you have corrupted system table with ID 60 holding information about object in your DB.

jaromora;
go

Title: SQL Server- The provided statistics stream is corrupt

Body:
I am trying to add statistics to a table that I already created. When I tried to run it, it throws an error:

The provided statistics stream is corrupt

This is my query for an example of a stats:

IF NOT EXISTS (SELECT *
               FROM sys.stats
               WHERE name = N'_WA_Sys_00000027_3C69FB99'
                 AND object_id = object_id(N'[dbo].[PromotionEvent]'))
    CREATE STATISTICS [_WA_Sys_00000027_3C69FB99]
        ON [dbo].[PromotionEvent]([CRMCode])
        WITH STATS_STREAM = 0x010000000100000000000000000000008B95918100000000C4040000000000008404000000000000E7020000E7000000480000000000000008D0000090D4B94007000000AB7FBA0034A60000BA29000000000000BA290000000000000000803FD9899D3D00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000B0000000B0000000100000010000000ACB7283D00E8264600E02446ACB7283D000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000013000000000000000000000000000000E1020000000000001003000000000000180300000000000058000000000000006B00000000000000AA00000000000000E90000000000000028010000000000006701000000000000A601000000000000E50100000000000024020000000000006302000000000000A202000000000000100010000000EE42000000000000803F040000300010000000803F0000803F0000803F04000001003F00320046003200300043003100350037002D0034003500330044002D0045003600310031002D003800300010000000803F000000000000803F04000001003F00330036003300380043003300300039002D0033003500330044002D0045003600310031002D003800300010000000803F000000000000803F04000001003F00330046003600350039003300440044002D0030003400330044002D0045003600310031002D003800300010000000803F000000000000803F04000001003F00350045003000320030003800460044002D0034004200330044002D0045003600310031002D003800300010000000803F000000000000803F04000001003F00380045003400370044003100310045002D0034003000330044002D0045003600310031002D003800300010000000803F000000000000803F04000001003F00410030003100310033003100330039002D0034004500330044002D0045003600310031002D003800300010000000803F000000000000803F04000001003F00410045003400460037004200440046002D0033003100330044002D0045003600310031002D003800300010000000803F000000000000803F04000001003F00430041003300360044003000340031002D0038003700330043002D0045003600310031002D003800300010000000803F000000000000803F04000001003F00430045003600410039003200320042002D0034003700330044002D0045003600310031002D003800300010000000803F000000000000803F04000001003F00450044004500340043003300310039002D0034003800330044002D0045003600310031002D003800FF010000001A0200002002000002000000280000002800000000000000000000000000000001000000060000000000BA29000000000000
GO

Why do I get this error? Is it because the stream is too long? How do I fix this?
I have to stick with this stream  because I am doing data archiving so the stats must have similar name.

Thanks


问:
Android Google place picker
I am using google place picker in my app and each and everything is working fine. But there are some requirements of my app too.

When we open the place picker via intent it just look like this

As you can see there is a search field on the top of Place picker , I just want to change the hint from the search to the string that I want. let say locate or anything else.

Please tell me how can I do this . I am pretty sure it can be done. But from intent builder it seems impossible.

Please help.

答:
I'm afraid currently this is not possible to set custom placeholder text in search element. I can see the following feature requests in Google issue tracker you might be interested in:

https://issuetracker.google.com/issues/64892097

https://issuetracker.google.com/issues/62256415

Feel free to star these feature requests to add your vote and subscribe to notifications.

Title: Android Google place picker


问:
How can I pass a list of objects from Controller to View, where data is retrieved from database using Linq in ASP.Net MVC5
I am trying to pass a list of Objects from controller to View ,where the attributes of the objects are retrieved from database using LINQ. The MODEL Code is given below:

```<code>public class Department
    {

        [Key]
        public int DepartmentId { get; set; }

        [Required(ErrorMessage = "Enter Department Name")]
        [DisplayName("Department Name")]
        public string DepartmentName { get; set; }
    }
</code>```

The Controller Code is :

```<code>public ActionResult ShowDepartments()
        {

          var departmentList = db.Deapartment.Select(x => new
            {
                x.DepartmentId,
                x.DepartmentName

            }).ToList();

            return View(departmentList);
        }
</code>```

And the View Code is:

```<code>@model List<PractiseMVC11_17_2017.Models.Department>

@{
    ViewBag.Title = "ShowDepartments";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Show Departments</h2>

        <div>

    <table class="table table-bordered table-hover">
        <tbody>

            @foreach (var department in Model)
            {

                <tr>
                    <td>
                        @department.DepartmentId
                    </td>

                    <td>
                        @department.DepartmentName

                    </td>

                </tr>

            }

        </tbody>

    </table>

</div>

}
</code>```

But when I run the project, it shows the following exception:

Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List1[<>f__AnonymousType32[System.Int32,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[PractiseMVC11_17_2017.Models.Department]'.

答:
Shyju answer works because the object you are passing to the View happens to be the same as the database object.  This will not always be the case (it's, in fact, better if it is not).

The correct way to handle this is to create a named object:

```<code>      var departmentList = db.Deapartment.Select(x => new Department
        {
            x.DepartmentId,
            x.DepartmentName

        }).ToList();
</code>```

(I'd go with the LINQ syntax, but the lambda syntax works just as well)

```<code>      var departmentList =
                  (from x in db.Deapartment
                   select new Department
                  {
                       x.DepartmentId,
                       x.DepartmentName
                  }).ToList();
</code>```

Body:
I am trying to pass a list of Objects from controller to View ,where the attributes of the objects are retrieved from database using LINQ. The MODEL Code is given below:

public class Department
    {

        [Key]
        public int DepartmentId { get; set; }

        [Required(ErrorMessage = "Enter Department Name")]
        [DisplayName("Department Name")]
        public string DepartmentName { get; set; }
    }

The Controller Code is :

public ActionResult ShowDepartments()
        {

          var departmentList = db.Deapartment.Select(x => new
            {
                x.DepartmentId,
                x.DepartmentName

            }).ToList();

            return View(departmentList);
        }

And the View Code is:

@model List<PractiseMVC11_17_2017.Models.Department>

@{
    ViewBag.Title = "ShowDepartments";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Show Departments

            @foreach (var department in Model)
            {

                        @department.DepartmentId

                        @department.DepartmentName

            }

}

But when I run the project, it shows the following exception:

Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List1[<>f__AnonymousType32[System.Int32,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[PractiseMVC11_17_2017.Models.Department]'.

Body:
Shyju answer works because the object you are passing to the View happens to be the same as the database object.  This will not always be the case (it's, in fact, better if it is not).

The correct way to handle this is to create a named object:

      var departmentList = db.Deapartment.Select(x => new Department
        {
            x.DepartmentId,
            x.DepartmentName

        }).ToList();

(I'd go with the LINQ syntax, but the lambda syntax works just as well)

      var departmentList =
                  (from x in db.Deapartment
                   select new Department
                  {
                       x.DepartmentId,
                       x.DepartmentName
                  }).ToList();


问:
asp.net mvc - how to write ajax request in javascript
i would like to update follow div with ajax request written in javascript method.

asp.mvc view:

```<code><div id="feed" onload="GetFeeds()">
            <span id="feeds" runat="server">
                    <%= Model.Feeds %>
            </span>
        </div>
</code>```

what schould i do in javasript?:

```<code><script type="text/javascript">

   // some AJAX Request with 'feed' Update, but HOW??
   document.getElementById('feed');

    function GetFeeds() {
    // need to call method from HomeModel.cs GetAllFeeds()??
    // or i should to write hole methode here?
    }

</script>
</code>```

it schould work without any controller action.
method for FeedUpdating is written in HomeModel.cs / GetAllFeeds() and it works. I need just call it from javascript

答:
Highly recommend using jQuery

```<code>$.ajax(
   url: 'http://localhost/feeds/feed1',
   type:'GET',
   dataType: 'json',
   success: function(data) {
         //Process data
   },
   error: function(error) { }
);
</code>```

It does all the heavy lifting for you and is tested on many more browsers than you will be able to test on in your lifetime :)

Body:
i would like to update follow div with ajax request written in javascript method.

asp.mvc view:

                    <%= Model.Feeds %>

what schould i do in javasript?:

it schould work without any controller action.
method for FeedUpdating is written in HomeModel.cs / GetAllFeeds() and it works. I need just call it from javascript

Body:
Highly recommend using jQuery

$.ajax(
   url: 'http://localhost/feeds/feed1',
   type:'GET',
   dataType: 'json',
   success: function(data) {
         //Process data
   },
   error: function(error) { }
);

It does all the heavy lifting for you and is tested on many more browsers than you will be able to test on in your lifetime :)


问:
wso2IS login issue after configuring with external LDAP server
I have installed WSO2 identity server 5.3.0 in our system and tried to establish external LDAP connection using steps provided by LABKIT.pdf.
I have successfully configured "apache directory studio" on my windows server 20008 R2 Stand. To communicate or authenticate to  "Active Directory"  using Bind DN and password

```<code>Bind DN       : CN=Administrator,CN=Users,DC=orap,DC=co,DC=in
Bind Password : Psas@2017!!
</code>```

after configuring necessary settings in a file "user-mgt.xml" for external LDAP settings.Then restarting services  "./wso2servr.sh" shows embedded LDAP settings disabled and External  LDAP connection successful, but login page of WSO2 can't able to log in using

default admin login

LDAP  Username and password.

How to solve this issue in order to communicate our own LDAP server to WSO2 IS?

答: You need to setup your external LDAP connection as a secondary store. What you define in 'user-mgt.xml' becomes your primary store. Your primary store should be a JDBC store in this instance since you're disabling embedded LDAP. If you do it this way, you'll be able to login with your default admin login. Don't forget to disable the admin settings at the top of user-mgt.xml once you start your WSO2 IS for the first time.</p>

Body:
I have installed WSO2 identity server 5.3.0 in our system and tried to establish external LDAP connection using steps provided by LABKIT.pdf.
I have successfully configured "apache directory studio" on my windows server 20008 R2 Stand. To communicate or authenticate to  "Active Directory"  using Bind DN and password

Bind DN       : CN=Administrator,CN=Users,DC=orap,DC=co,DC=in
Bind Password : Psas@2017!!

after configuring necessary settings in a file "user-mgt.xml" for external LDAP settings.Then restarting services  "./wso2servr.sh" shows embedded LDAP settings disabled and External  LDAP connection successful, but login page of WSO2 can't able to log in using

default admin login

LDAP  Username and password.

How to solve this issue in order to communicate our own LDAP server to WSO2 IS?


问:
Avoid global functions when compiling typescript
How can I avoid the creation of global functions when compiling typescript into javascript.

Benefit: obfuscator won't have to provide a public API

Foo.ts:

```<code>class Foo {}
</code>```

Foo.js:

```<code>var Foo = (function () {
    function Foo() {
    }
    return Foo;
}());
</code>```

Foo.obfuscated.js (using npm jsobfuscator):

```<code>var _0xcd14=[];var _0x12e2=[];var Foo=(function(){function Foo(){}return Foo}())
</code>```

Foo is still visible. I understand why (public API). Solution would be:

Foo.isolated.js:

```<code>(function() { /* code from Foo.js */ })();
</code>```

Foo.isolated.obfuscated.js (what I want):

```<code>var _0xe1f1=[];var _0xa6a8=[];(function(){var _0x64f8x2=(function(){function _0x64f8x2(){}return _0x64f8x2}())})()
</code>```

Is there a typescript setup for tsconfig.js / compiler options like isolation: true or something?

答:
Wrapping the class inside a function scope should do the trick.

```<code>(function(){
    class Foo {}
})
</code>```

There isn't built in support in the form of an option as far as I am aware. Let me know if doing the above does not achieve your aim - in which case some more details about exactly what the goal is will help us understand what you're going for here.

Body:
How can I avoid the creation of global functions when compiling typescript into javascript.

Benefit: obfuscator won't have to provide a public API

Foo.ts:

class Foo {}

Foo.js:

var Foo = (function () {
    function Foo() {
    }
    return Foo;
}());

Foo.obfuscated.js (using npm jsobfuscator):

var _0xcd14=[];var _0x12e2=[];var Foo=(function(){function Foo(){}return Foo}())

Foo is still visible. I understand why (public API). Solution would be:

Foo.isolated.js:

(function() { /* code from Foo.js */ })();

Foo.isolated.obfuscated.js (what I want):

var _0xe1f1=[];var _0xa6a8=[];(function(){var _0x64f8x2=(function(){function _0x64f8x2(){}return _0x64f8x2}())})()

Is there a typescript setup for tsconfig.js / compiler options like isolation: true or something?

Body:
Wrapping the class inside a function scope should do the trick.

(function(){
    class Foo {}
})

There isn't built in support in the form of an option as far as I am aware. Let me know if doing the above does not achieve your aim - in which case some more details about exactly what the goal is will help us understand what you're going for here.


问:
the event deviceready isn't triggered on my apps
I'm trying to load a cordova plugin using vue.js, and vue-cordova.

I'm using vue-cordova, with the plugin open-native-settings to access to the settings of the device (ios or android).
This works just fine with the demo app provided by the vue-cordova plugin on github, but when i add it to my apps (the same way) the event seems to never trigger.
So i tried to wait for the event using

Vue.cordova.on('deviceready', () => {
  // here check for your variable
})

or with

```<code>document.addEventListener('deviceready', deviceReady, false);
</code>```

but since the event never trigger they are doing nothing.
I'm kinda lost on the way to  get this event to be triggered, so i can load my plugin properly.
I'm a beginner using this so i might be missing something.

UPDATE

I'm loading vue-cordova in my main.js this way:

```<code>import VueCordova from 'vue-cordova'
Vue.use(VueCordova, {
optionTestKey: 'optionTestValue'
})
</code>```

after that, i try to load the plugins in another view this way:

```<code>import Vue from 'vue'
//some code here
mounted: function() {
this.cloudyConnection();
this.lastUpdateDate = this.getLastUpdateDate();
if (this.cordova.deviceready === true) {
  this.onDeviceReady()
}
</code>```

},
I also tried to do it out of the mounted function and with the function listed above.

I also added the  in www/index.html as indicated by a--m but this doesn't do anything

I thank you all for the time you take to help me !

答:
Reading from http://kartsims.github.io/vue-cordova/ troubleshooting section:

“My events don’t seem to be fired”

Cordova documentation isn’t obvious about it but you need to include the following script tag in your www/index.html.

Ensure that cordova.js is loaded before your scripts and vue-cordova since the last depends on that.

Body:
I'm trying to load a cordova plugin using vue.js, and vue-cordova.

I'm using vue-cordova, with the plugin open-native-settings to access to the settings of the device (ios or android).
This works just fine with the demo app provided by the vue-cordova plugin on github, but when i add it to my apps (the same way) the event seems to never trigger.
So i tried to wait for the event using

Vue.cordova.on('deviceready', () => {
  // here check for your variable
})

or with

document.addEventListener('deviceready', deviceReady, false);

but since the event never trigger they are doing nothing.
I'm kinda lost on the way to  get this event to be triggered, so i can load my plugin properly.
I'm a beginner using this so i might be missing something.

UPDATE

I'm loading vue-cordova in my main.js this way:

import VueCordova from 'vue-cordova'
Vue.use(VueCordova, {
optionTestKey: 'optionTestValue'
})

after that, i try to load the plugins in another view this way:

import Vue from 'vue'
//some code here
mounted: function() {
this.cloudyConnection();
this.lastUpdateDate = this.getLastUpdateDate();
if (this.cordova.deviceready === true) {
  this.onDeviceReady()
}

},
I also tried to do it out of the mounted function and with the function listed above.

I also added the  in www/index.html as indicated by a--m but this doesn't do anything

I thank you all for the time you take to help me !

Body:
Reading from http://kartsims.github.io/vue-cordova/ troubleshooting section:

“My events don’t seem to be fired”

Cordova documentation isn’t obvious about it but you need to include the following script tag in your www/index.html.

<script src="cordova.js"></script>

Ensure that cordova.js is loaded before your scripts and vue-cordova since the last depends on that.


问:
How do I create the semi-transparent grey tutorial overlay in Android?
You know when you run an Android device for the first time (something you see a lot if you use the emulator) that there's a helpful little tutorial about how to use the launcher and add widgets, etc.  I'm trying to find an example of this on Google, but I can't.  I'm hoping you know what I mean.  It's the one with the blue "okay" buttons at each step.

Anyway, I want to create one for my app, but I'm not sure which is the best way to go about doing it.

Do I create a Fragment that I can make semi-transparent on top of my regular activity and have it show up on only the first run?

Do I make a semi-transparent .png for each section of the tutorial and overlay it over the regular launcher activity on the first run?

If I do the latter, how can I adjust for all the various screen sizes?  I could just render the image in Photoshop to various dimensions, but that won't cover all of them.  If I go the fragment route, I can just say "match_parent" and not worry about it.  But then I have to figure out how Fragments work, and they confuse the hell out of me.

答:
There is an award-winning library for this called "FancyShowcaseView":

https://github.com/faruktoptas/FancyShowCaseView

Add to your project like this:

In the top-level build.gradle (not the module level):

```<code>allprojects {
    repositories {
        ...
        maven { url "https://jitpack.io" }
    }
}
</code>```

In the module-level (app) build.gradle

```<code>dependencies {
    compile 'com.github.faruktoptas:FancyShowCaseView:1.0.0'
}
</code>```

Then you can call:

```<code>new FancyShowCaseView.Builder(this)
        .focusOn(view)
        .title("Focus on View")
        .build()
        .show();
</code>```

Body:
There is an award-winning library for this called "FancyShowcaseView":

https://github.com/faruktoptas/FancyShowCaseView

Add to your project like this:

In the top-level build.gradle (not the module level):

allprojects {
    repositories {
        ...
        maven { url "https://jitpack.io" }
    }
}

In the module-level (app) build.gradle

dependencies {
    compile 'com.github.faruktoptas:FancyShowCaseView:1.0.0'
}

Then you can call:

new FancyShowCaseView.Builder(this)
        .focusOn(view)
        .title("Focus on View")
        .build()
        .show();


问:
How to validate the number of arguments (mandatory and optional) in a shell script?
I am having trouble validating my script arguments. I am trying to achieve 5 mandatory arguments and 2 optional arguments to my script. Here is what I have tried so far.

```<code>#!/bin/sh

if [ $# -lt 5 ] || [ $# -gt 7 ]
then
  echo "Please supply 5 or 6 or 7 parameters. Aborting."
  exit 1
fi

echo MP1 = "$1"
echo MP2 = "$2"
echo MP3 = "$3"
echo MP4 = "$4"
echo MP5 = "$5"

while getopts c:a: optionalargs
do
        case $optionalargs in
          c)copt=$OPTARG;;
          a)aopt=$OPTARG;;
          *)echo "Invalid arg";;
        esac
done

if [ ! -z "$copt" ]
then
    export CHAR_SET=$copt
fi

if [ ! -z "$aopt" ]
then
    export ADDITIONAL_FLAGS=$aopt
fi

shift $((OPTIND -1))

echo OP_C = "${CHAR_SET}"
echo OP_A = "${ADDITIONAL_FLAGS}"
</code>```

The problem is validating the total number of arguments to this script as I can have a total of 5 or 7 arguments. Providing -a additional -c character is treated as 9 arguments.

```<code>./a.sh 1 2 3 4 5 -a additional -c character
Please supply 5 or 6 or 7 parameters. Aborting.
</code>```

I am open to designs with no - as long as I am able to have both mandatory and optional parameters.

How to get this properly validated?

答:
First: the shell doesn't know anything about optional vs. mandatory arguments, doesn't treat arguments that start with "-" specially, anything like that. It just has a list of "words", and it's up to your script to figure out what they mean. The getopts command can help with parsing the arguments, but it handles a fairly limited syntax:

Options start with a single dash, and are a single letter (maybe with an argument after that). For options that don't take arguments, you can stack multiple options on a single dash (e.g. ls -la).

After all the options, there can be a number of positional parameters (the meaning of these is defined -- as the name implies -- by their position in the list, e.g. first, second, etc).

There are a number of syntax extensions (mostly GNU conventions) that getopts does not support:

Putting options after positional parameters (e.g. ls filename -l). Options must always come first.

Long options (multi-letter and/or double-dash, e.g. ls --all).

Using -- to separate the options from the positional parameters.

So if you want to use getopts-style optional arguments, you need to put them first in the argument list. And when parsing them, you need to parse and remove* them from the argument list (with shift) before you check the number of positional parameters, and use $1 etc to access the positional parameters. Your current script is running into trouble because it's trying to handle the positional parameters first, and that won't work with getopts (at least without some heavy-duty kluging).

If you need a more general argument syntax, you might be able to use getopt (note the lack of "s" in the name). Some versions of getopt support the GNU conventions, some don't. Some have other problems. IMO this is a can of worms that's best left unopened.

Another possibility is to abandon the - option syntax, and give the script 7 positional parameters where the last two can be omitted. The problem with this is that you can't omit the sixth but pass the seventh (unless you're willing to consider the sixth being blank as equivalent to omitting it). The code for this would look something like this:

```<code>if [ $# -lt 5 ] || [ $# -gt 7 ]
then
  echo "Please supply 5 or 6 or 7 parameters. Aborting."
  exit 1
fi

echo "MP1 = $1"
echo "MP2 = $2"
echo "MP3 = $3"
echo "MP4 = $4"
echo "MP5 = $5"

if [ -n "$6" ]; then
    # This will run if a sixth argument was specified AND it wasn't blank.
    export CHAR_SET=$6
    echo "OP_C = ${CHAR_SET}"
fi

if [ $# -ge 7 ]; then
    # This will run if a seventh argument was specified EVEN IF it was blank.
    # If you want to omit this for a blank arg, use the `-n` test instead.
    export ADDITIONAL_FLAGS=$7
    echo "OP_A = ${ADDITIONAL_FLAGS}"
fi
</code>```

...and then run the script with e.g.

```<code>./a.sh 1 2 3 4 5 character additional    # Both optional args supplied
./a.sh 1 2 3 4 5 character               # Only first optional arg supplied
./a.sh 1 2 3 4 5 "" additional           # Only second optional arg supplied
</code>```

Or, if you really want the more extended syntax and don't want to risk the vagaries of the getopt command, you can spend a lot of time and effort writing your own parsing system. IMO this is way more work than it's worth.

Body:
I am having trouble validating my script arguments. I am trying to achieve 5 mandatory arguments and 2 optional arguments to my script. Here is what I have tried so far.

#!/bin/sh

if [ $# -lt 5 ] || [ $# -gt 7 ]
then
  echo "Please supply 5 or 6 or 7 parameters. Aborting."
  exit 1
fi

echo MP1 = "$1"
echo MP2 = "$2"
echo MP3 = "$3"
echo MP4 = "$4"
echo MP5 = "$5"

while getopts c:a: optionalargs
do
        case $optionalargs in
          c)copt=$OPTARG;;
          a)aopt=$OPTARG;;
          *)echo "Invalid arg";;
        esac
done

if [ ! -z "$copt" ]
then
    export CHAR_SET=$copt
fi

if [ ! -z "$aopt" ]
then
    export ADDITIONAL_FLAGS=$aopt
fi

shift $((OPTIND -1))

echo OP_C = "${CHAR_SET}"
echo OP_A = "${ADDITIONAL_FLAGS}"

The problem is validating the total number of arguments to this script as I can have a total of 5 or 7 arguments. Providing -a additional -c character is treated as 9 arguments.

./a.sh 1 2 3 4 5 -a additional -c character
Please supply 5 or 6 or 7 parameters. Aborting.

I am open to designs with no - as long as I am able to have both mandatory and optional parameters.

How to get this properly validated?

Body:
First: the shell doesn't know anything about optional vs. mandatory arguments, doesn't treat arguments that start with "-" specially, anything like that. It just has a list of "words", and it's up to your script to figure out what they mean. The getopts command can help with parsing the arguments, but it handles a fairly limited syntax:

Options start with a single dash, and are a single letter (maybe with an argument after that). For options that don't take arguments, you can stack multiple options on a single dash (e.g. ls -la).

After all the options, there can be a number of positional parameters (the meaning of these is defined -- as the name implies -- by their position in the list, e.g. first, second, etc).

There are a number of syntax extensions (mostly GNU conventions) that getopts does not support:

Putting options after positional parameters (e.g. ls filename -l). Options must always come first.

Long options (multi-letter and/or double-dash, e.g. ls --all).

Using -- to separate the options from the positional parameters.

So if you want to use getopts-style optional arguments, you need to put them first in the argument list. And when parsing them, you need to parse and remove* them from the argument list (with shift) before you check the number of positional parameters, and use $1 etc to access the positional parameters. Your current script is running into trouble because it's trying to handle the positional parameters first, and that won't work with getopts (at least without some heavy-duty kluging).

If you need a more general argument syntax, you might be able to use getopt (note the lack of "s" in the name). Some versions of getopt support the GNU conventions, some don't. Some have other problems. IMO this is a can of worms that's best left unopened.

Another possibility is to abandon the - option syntax, and give the script 7 positional parameters where the last two can be omitted. The problem with this is that you can't omit the sixth but pass the seventh (unless you're willing to consider the sixth being blank as equivalent to omitting it). The code for this would look something like this:

if [ $# -lt 5 ] || [ $# -gt 7 ]
then
  echo "Please supply 5 or 6 or 7 parameters. Aborting."
  exit 1
fi

echo "MP1 = $1"
echo "MP2 = $2"
echo "MP3 = $3"
echo "MP4 = $4"
echo "MP5 = $5"

if [ -n "$6" ]; then
    # This will run if a sixth argument was specified AND it wasn't blank.
    export CHAR_SET=$6
    echo "OP_C = ${CHAR_SET}"
fi

if [ $# -ge 7 ]; then
    # This will run if a seventh argument was specified EVEN IF it was blank.
    # If you want to omit this for a blank arg, use the `-n` test instead.
    export ADDITIONAL_FLAGS=$7
    echo "OP_A = ${ADDITIONAL_FLAGS}"
fi

...and then run the script with e.g.

./a.sh 1 2 3 4 5 character additional    # Both optional args supplied
./a.sh 1 2 3 4 5 character               # Only first optional arg supplied
./a.sh 1 2 3 4 5 "" additional           # Only second optional arg supplied

Or, if you really want the more extended syntax and don't want to risk the vagaries of the getopt command, you can spend a lot of time and effort writing your own parsing system. IMO this is way more work than it's worth.


问:
Compile time safety of derived classes virtual functions?
I have this code, the question is below the code:

```<code>public class MainProgram
{
    public static void Main()
    {
        List<Animal> Animals = new List<Animal>();
        Animals.Add(new Dog());
        Animals.Add(new Poodle());
        Animals.Add(new Poodle());
        Animals.Add(new Beagle());
        Animals.Add(new Cat());

        Bark[] JustTheBarks = Dog.GetBarkList(Animals);
        foreach (Bark B in JustTheBarks)
        {
            Console.WriteLine(B.ToString());
        }
    }
}

abstract class Animal
{
    public abstract Noise GetNoise();
}

class Dog : Animal
{
    public override Noise GetNoise()
    {
        return new Bark("bark");
    }

    public static Bark[] GetBarkList(List<Animal> List)
    {
        return List
            .OfType<Dog>()
            .Select(r => r.GetNoise())
            .Cast<Bark>()
            .ToArray();
    }
}

class Beagle : Dog
{
    public override Noise GetNoise()
    {
        return new Woof("woof", 7);
    }
}

class Poodle : Dog
{
    public override Noise GetNoise()
    {
        return new Purr();
    }
}

class Cat : Animal
{
    public override Noise GetNoise()
    {
        throw new NotImplementedException();
    }
}

class Noise
{
}

class Bark : Noise
{
    protected string Text;
    public Bark(string Text)
    {
        this.Text = Text;
    }

    public override string ToString()
    {
        return $"{Text}";
    }
}

class Woof : Bark
{
    protected int Pitch;

    public Woof(string Text, int Pitch) : base(Text)
    {
        this.Pitch = Pitch;
    }
    public override string ToString()
    {
        return $"{Text}->{Pitch}";
    }
}

class Purr : Noise { }
</code>```

}

In plain text, Animals and Noises, each animal returns its own type of noise, the noises correspond to the animal class, although sometimes an animal might return different Noises based on some variable (but for a dog only some form of Bark).

This code crashes of course. The Poodle returns a Purr(), and it "should" return something of type Bark.  I have the abstract function GetNoise() which just returns a Noise. What I want/need is to write

```<code>class Dog
{
    public override Bark GetNoise();
}
</code>```

But this is not allowed, the return type must be the same. I don't want to write a second layer of GetBark() functions in every Dog class, etc.

What I want is to re-write this such that there is no casting, and everything that is derived from Dog is forced to return a Bark in its GetNoise() function such that I can safely write:

```<code>Bark B = Dog.GetNoise();
</code>```

答:
The way to do this is you seal the overload at the Dog level then make a new protected method that the children must implement.</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;

public class MainProgram
{
    public static void Main()
    {
        List<Animal> Animals = new List<Animal>();
        Animals.Add(new Dog());
        Animals.Add(new Poodle());
        Animals.Add(new Poodle());
        Animals.Add(new Beagle());
        Animals.Add(new Cat());

        Bark[] JustTheBarks = Dog.GetBarkList(Animals);
        foreach (Bark B in JustTheBarks)
        {
            Console.WriteLine(B.ToString());
        }
    }
}

abstract class Animal
{
    public abstract Noise GetNoise();
}

class Dog : Animal
{
    public sealed override Noise GetNoise()
    {
        return GetBark();
    }

    protected virtual Bark GetBark()
    {
        return new Bark("bark");
    }

    public static Bark[] GetBarkList(List<Animal> List)
    {
        return List
            .OfType<Dog>()
            .Select(r => r.GetBark()) //Now calls GetBark() instead of GetNoise()
            .ToArray();
    }
}

class Beagle : Dog
{
    protected override Bark GetBark()
    {
        return new Woof("woof", 7);
    }
}

class Poodle : Dog
{
    protected override Bark GetBark()
    {
        return new Purr(); //This is now a compiler error.
    }
}

class Cat : Animal
{
    public override Noise GetNoise()
    {
        throw new NotImplementedException();
    }
}

class Noise
{
}

class Bark : Noise
{
    protected string Text;
    public Bark(string Text)
    {
        this.Text = Text;
    }

    public override string ToString()
    {
        return $"{Text}";
    }
}

class Woof : Bark
{
    protected int Pitch;

    public Woof(string Text, int Pitch) : base(Text)
    {
        this.Pitch = Pitch;
    }
    public override string ToString()
    {
        return $"{Text}->{Pitch}";
    }
}

class Purr : Noise { }
</code>```

Body:
I have this code, the question is below the code:

public class MainProgram
{
    public static void Main()
    {
        List<Animal> Animals = new List<Animal>();
        Animals.Add(new Dog());
        Animals.Add(new Poodle());
        Animals.Add(new Poodle());
        Animals.Add(new Beagle());
        Animals.Add(new Cat());

        Bark[] JustTheBarks = Dog.GetBarkList(Animals);
        foreach (Bark B in JustTheBarks)
        {
            Console.WriteLine(B.ToString());
        }
    }
}

abstract class Animal
{
    public abstract Noise GetNoise();
}

class Dog : Animal
{
    public override Noise GetNoise()
    {
        return new Bark("bark");
    }

    public static Bark[] GetBarkList(List<Animal> List)
    {
        return List
            .OfType<Dog>()
            .Select(r => r.GetNoise())
            .Cast<Bark>()
            .ToArray();
    }
}

class Beagle : Dog
{
    public override Noise GetNoise()
    {
        return new Woof("woof", 7);
    }
}

class Poodle : Dog
{
    public override Noise GetNoise()
    {
        return new Purr();
    }
}

class Cat : Animal
{
    public override Noise GetNoise()
    {
        throw new NotImplementedException();
    }
}

class Noise
{
}

class Bark : Noise
{
    protected string Text;
    public Bark(string Text)
    {
        this.Text = Text;
    }

    public override string ToString()
    {
        return $"{Text}";
    }
}

class Woof : Bark
{
    protected int Pitch;

    public Woof(string Text, int Pitch) : base(Text)
    {
        this.Pitch = Pitch;
    }
    public override string ToString()
    {
        return $"{Text}->{Pitch}";
    }
}

class Purr : Noise { }

}

In plain text, Animals and Noises, each animal returns its own type of noise, the noises correspond to the animal class, although sometimes an animal might return different Noises based on some variable (but for a dog only some form of Bark).

This code crashes of course. The Poodle returns a Purr(), and it "should" return something of type Bark.  I have the abstract function GetNoise() which just returns a Noise. What I want/need is to write

class Dog
{
    public override Bark GetNoise();
}

But this is not allowed, the return type must be the same. I don't want to write a second layer of GetBark() functions in every Dog class, etc.

What I want is to re-write this such that there is no casting, and everything that is derived from Dog is forced to return a Bark in its GetNoise() function such that I can safely write:

Bark B = Dog.GetNoise();

Body:
The way to do this is you seal the overload at the Dog level then make a new protected method that the children must implement.

using System;
using System.Collections.Generic;
using System.Linq;

public class MainProgram
{
    public static void Main()
    {
        List<Animal> Animals = new List<Animal>();
        Animals.Add(new Dog());
        Animals.Add(new Poodle());
        Animals.Add(new Poodle());
        Animals.Add(new Beagle());
        Animals.Add(new Cat());

        Bark[] JustTheBarks = Dog.GetBarkList(Animals);
        foreach (Bark B in JustTheBarks)
        {
            Console.WriteLine(B.ToString());
        }
    }
}

abstract class Animal
{
    public abstract Noise GetNoise();
}

class Dog : Animal
{
    public sealed override Noise GetNoise()
    {
        return GetBark();
    }

    protected virtual Bark GetBark()
    {
        return new Bark("bark");
    }

    public static Bark[] GetBarkList(List<Animal> List)
    {
        return List
            .OfType<Dog>()
            .Select(r => r.GetBark()) //Now calls GetBark() instead of GetNoise()
            .ToArray();
    }
}

class Beagle : Dog
{
    protected override Bark GetBark()
    {
        return new Woof("woof", 7);
    }
}

class Poodle : Dog
{
    protected override Bark GetBark()
    {
        return new Purr(); //This is now a compiler error.
    }
}

class Cat : Animal
{
    public override Noise GetNoise()
    {
        throw new NotImplementedException();
    }
}

class Noise
{
}

class Bark : Noise
{
    protected string Text;
    public Bark(string Text)
    {
        this.Text = Text;
    }

    public override string ToString()
    {
        return $"{Text}";
    }
}

class Woof : Bark
{
    protected int Pitch;

    public Woof(string Text, int Pitch) : base(Text)
    {
        this.Pitch = Pitch;
    }
    public override string ToString()
    {
        return $"{Text}->{Pitch}";
    }
}

class Purr : Noise { }


问:
Finding nearest timestamp in Mathematica
in Mathematica I have to find a timestamp closest to a given one. I have:

```<code>alltrafotstamps = (DateList[#1]) & @@@ reddata[[All, 1]]
</code>```

what gives something what looks like a list of timestamps:

```<code>{"2017-11-10 21:36:12.135", "2017-11-10 21:36:50.535",
 "2017-11-10 21:37:28.935", "2017-11-10 21:38:07.335", ...}
</code>```

So now I do:

```<code>Nearest[alltrafotstamps, DateList["2017-11-10 22:56:50.535"]]
</code>```

and I get this message:

```<code>Nearest::neard: The default distance function does not give a real numeric distance when applied to the point pair 2017 and 2017-11-10 21:36:12.135.
</code>```

Can it be that Nearest cannot do this for timestamp, but can do it only for times?

Body:
in Mathematica I have to find a timestamp closest to a given one. I have:

alltrafotstamps = (DateList[#1]) & @@@ reddata[[All, 1]]

what gives something what looks like a list of timestamps:

{"2017-11-10 21:36:12.135", "2017-11-10 21:36:50.535",
 "2017-11-10 21:37:28.935", "2017-11-10 21:38:07.335", ...}

So now I do:

Nearest[alltrafotstamps, DateList["2017-11-10 22:56:50.535"]]

and I get this message:

Nearest::neard: The default distance function does not give a real numeric distance when applied to the point pair 2017 and 2017-11-10 21:36:12.135.

Can it be that Nearest cannot do this for timestamp, but can do it only for times?

Body:
alltrafotstamps = {
  "2017-11-10 21:36:12.135",
  "2017-11-10 21:36:50.535",
  "2017-11-10 21:37:28.935",
  "2017-11-10 21:38:07.335"};

target = "2017-11-10 21:37:00";

nearest = Nearest[
   AbsoluteTime /@ alltrafotstamps,
   AbsoluteTime[target]];

DateObject @@ nearest

DateList @@ nearest

{2017, 11, 10, 21, 36, 50.535}


问:
New to C,Loop Issues
I want to enter value to my array and between 0 and 101 and trying to put zero or 101 will return an error but putting anything from 1-100 will allow me to enter a second number.

but i am stuck when  write code to add a second number the loop keeps going in 1 and i cant figure out my error. any help would be apreciated

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

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
char letter;

int main()
{
    int i;
    int grades[12] ;

    for ( i = 0; i < 12; i++)
        do{//loops the following peice of code if values over 100 or less than 0 are entered

            printf("Please Enter Grade 1:\n");
            scanf("%f", & grades[i]);
            if (grades > 100 || grades < 0)
                printf("Invalid Entry please enter another between 0 and 100:\n");
        }while(grades < 100 || grades > 0);
}
</code>```

答:
The mistake here is you're comparing the whole array to a value. What you want is one element, plus you need to test that you're outside of the acceptable bounds:

```<code>while(grades[i] > 100 || grades[i] < 0);
</code>```

As Jonathan points out below, the logic in your code tests that it's within, which means only valid answers will loop forever, the opposite of what you wanted.

Title: New to C,Loop Issues

Body:
I want to enter value to my array and between 0 and 101 and trying to put zero or 101 will return an error but putting anything from 1-100 will allow me to enter a second number.

but i am stuck when  write code to add a second number the loop keeps going in 1 and i cant figure out my error. any help would be apreciated

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
char letter;

int main()
{
    int i;
    int grades[12] ;

    for ( i = 0; i < 12; i++)
        do{//loops the following peice of code if values over 100 or less than 0 are entered

            printf("Please Enter Grade 1:\n");
            scanf("%f", & grades[i]);
            if (grades > 100 || grades < 0)
                printf("Invalid Entry please enter another between 0 and 100:\n");
        }while(grades < 100 || grades > 0);
}

Body:
The mistake here is you're comparing the whole array to a value. What you want is one element, plus you need to test that you're outside of the acceptable bounds:

while(grades[i] > 100 || grades[i] < 0);

As Jonathan points out below, the logic in your code tests that it's within, which means only valid answers will loop forever, the opposite of what you wanted.


问:
returning a pointer that points to char array. How do i print out the entire contents of the array?
This program reverses a given string but i can't seem to figure out how to return the entire buffer, all answers welcome.

```<code>#include <iostream>
#include <string.h>
using namespace std;

char  ReverseString(char *input);

int main()
{
    string str;
    cout << "Please Enter a String: ";
    getline(cin,str);
    cout << "The string you entered is: " << str << endl;
    str = ReverseString(&str[0]);
    cout << str;
}

char  ReverseString(char* input)
{
    int size = strlen(input);
    char *it;
    char *revBuffer = new char[size];
    it = revBuffer;
    for(int i=0; i<size; i++)
    {
       *it = input[(size-1)-i];
       it++;
    }
    return *revBuffer; //
</code>```

I can't seem to figure out how to return the entire buffer instead of just one element the pointer is pointing to.

答:
Your function is set to return a single character char and that's what you've done, you've returned the first char of the reversed string by de-referencing the revBuffer pointer which is a pointer to the first element of the char array.

What you need to do is to set your function to return a pointer char* instead of a char and so you can return revBuffer.

So your code should look like this :

```<code>#include <iostream>
#include <string.h>
using namespace std;

//Function return a char pointer instead of a char
char*  ReverseString(char *input);

int main()
{
    string str;
    cout << "Please Enter a String: ";
    getline(cin,str);
    cout << "The string you entered is: " << str << endl;
    str = ReverseString(&str[0]);
    cout << str;
}

char*  ReverseString(char* input)
{
    int size = strlen(input);
    char *it;
    char *revBuffer = new char[size+1];
    it = revBuffer;
    for(int i=0; i<size; i++)
    {
       *it = input[(size-1)-i];
       it++;
    }
    *it = '\0';
    //return a pointer to the reversed string
    return revBuffer;
}
</code>```

Body:
This program reverses a given string but i can't seem to figure out how to return the entire buffer, all answers welcome.

#include <iostream>
#include <string.h>
using namespace std;

char  ReverseString(char *input);

int main()
{
    string str;
    cout << "Please Enter a String: ";
    getline(cin,str);
    cout << "The string you entered is: " << str << endl;
    str = ReverseString(&str[0]);
    cout << str;
}

char  ReverseString(char* input)
{
    int size = strlen(input);
    char *it;
    char *revBuffer = new char[size];
    it = revBuffer;
    for(int i=0; i<size; i++)
    {
       *it = input[(size-1)-i];
       it++;
    }
    return *revBuffer; //

I can't seem to figure out how to return the entire buffer instead of just one element the pointer is pointing to.

Body:
Your function is set to return a single character char and that's what you've done, you've returned the first char of the reversed string by de-referencing the revBuffer pointer which is a pointer to the first element of the char array.

What you need to do is to set your function to return a pointer char* instead of a char and so you can return revBuffer.

So your code should look like this :

#include <iostream>
#include <string.h>
using namespace std;

//Function return a char pointer instead of a char
char*  ReverseString(char *input);

int main()
{
    string str;
    cout << "Please Enter a String: ";
    getline(cin,str);
    cout << "The string you entered is: " << str << endl;
    str = ReverseString(&str[0]);
    cout << str;
}

char*  ReverseString(char* input)
{
    int size = strlen(input);
    char *it;
    char *revBuffer = new char[size+1];
    it = revBuffer;
    for(int i=0; i<size; i++)
    {
       *it = input[(size-1)-i];
       it++;
    }
    *it = '\0';
    //return a pointer to the reversed string
    return revBuffer;
}


问:
Generalization vs Specialization of DB table
When I want to design database tables that model a finite parent-child relationship, for e.g., computer as parent, and the components inside as the child; or a simple organizational hierarchy, I am usually torn at which approach to use -

A 'specialized table' approach, in which I create a table for each of the possible entity. In the computer component example, I would have a Computer table and a Component table, with the ComputerID as FK in the Component table referencing back to Computer.ComputerID.
or

A 'generalized table approach, in which I have one table table called Component, with ComponentID as PK, and a ParentComponentID as FK referencing to its parent's ComponentID.

答:
Having used both, the former is definitely easier to grasp by new programmers. It is also simpler to deal with in most simple cases.

Where the latter comes in handy, is where the hierarchy of things could change; or an object changes its hierarchical order or the hierarchy itself changes. It is also useful when the hierarchy is complex, as you don't have to model it as tables in the database.

OwnerDisplayName: Loki


问:
Alarm Even Application Closed in iPhone
I am working on iPhone application in which there is an option for Alarm. Is it possible to araise alarm even my application close.</p>

答:
Yes to a certain degree there is, check out the local notifications programming guide (local notifications are available in iOS 4 and newer).

http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Introduction/Introduction.html

Title: Alarm Even Application Closed in iPhone


问:
How to partition a table in MySQL which has 2 million records
I having a table which contains around 2 million records, all of which are for same node. I cannot partition based on date, as data is continually inserted and deleted each day.

The remaining data is in string format.

Every 15 minutes, the application takes backups from this table (only partial data which was collected for that 15 minutes); while doing this operation, the table is locked and unable to be accessed.

What kind of partitioning can I use to help solve this problem?

答:
If the problem you're trying to solve is the locking by the backup, partitioning won't help solve that.

Also, there are better solutions to avoid locking during backups. These solutions work equally well with or without partitioned tables.

If you use InnoDB tables (which you should), you can dump data with transaction isolation instead of locking.

```<code>mysqldump --single-transaction mydatabase mytable ...
</code>```

Read the manual for more information: https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html

You can also use Percona XtraBackup to create a physical backup instead of a data dump. This also depends on using InnoDB tables. Percona XtraBackup is free software.

Body:
If the problem you're trying to solve is the locking by the backup, partitioning won't help solve that.

Also, there are better solutions to avoid locking during backups. These solutions work equally well with or without partitioned tables.

If you use InnoDB tables (which you should), you can dump data with transaction isolation instead of locking.

mysqldump --single-transaction mydatabase mytable ...

Read the manual for more information: https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html

You can also use Percona XtraBackup to create a physical backup instead of a data dump. This also depends on using InnoDB tables. Percona XtraBackup is free software.


问:
IF user is in a certain page/url DO this
I have a website that the user can read both in Italian and English language.

The English website is characterized by the following path: mysite.com/…

While the Italian one has the following path: mysite.com/it/…

I am now implementing a booking module that should be displayed only in the home and in the “Fares” pages in order to provide the user a tool to reserve a spot for the service I offer (taxi services). The module is connected to a Database containing the cities (departures and arrivals) and the related prices. For module I mean a box where you are asked some information (in my case: Departure, arrival, # of passengers and # of luggages), you press a button and something happen (in my case you query the database getting the price of the trip).

Since the website has two languages I need to translate both the module and the database as well. I proceeded in the following way:

I created two folders containing the same module but one is in
Italian while the other is in English;

Each module queries the
correct database, the Italian module takes the data from the Italian
DB while the English module read the data from the translated one
(es. Malpensa Aeroporto -> Malpensa Airport).

What I would like to do now is to create an if statement that does the following:

```<code>IF (on the homepage of mysite.com/) {
Get the English module
} else IF (on the homepage of mysite.com/it/) {
    Get the Italian module
    } else {
    Do nothing because you are not on any homepage
    }
</code>```

I already have searched in the blog and around the internet but I am not able to find something working. How can I develop this "IF statement"?

Thank you all

答:
You can do it by this,

```<code>$explode = explode('/', $_SERVER['REQUEST_URI']);
if($explode[1] == 'it'){
    echo 'call Italian';
}else{
    echo 'call English';
}
</code>```

$_SERVER['REQUEST_URI'] contain the path in site.
In my case

/stack/help.php

So explode() it and then check if the directory name equal to it you call the module for Italian language else call English one.

And this you must call in file included in both
index.php, /it/index.php

Or try this

explode getcwd() and use end()

```<code>$directory = explode('/', getcwd());
if( end($directory) == 'it' ){
    //call Italian Module
}else{
    //call English Module
}
</code>```

Hope this helps,

Body:
I have a website that the user can read both in Italian and English language.

The English website is characterized by the following path: mysite.com/…

While the Italian one has the following path: mysite.com/it/…

I am now implementing a booking module that should be displayed only in the home and in the “Fares” pages in order to provide the user a tool to reserve a spot for the service I offer (taxi services). The module is connected to a Database containing the cities (departures and arrivals) and the related prices. For module I mean a box where you are asked some information (in my case: Departure, arrival, # of passengers and # of luggages), you press a button and something happen (in my case you query the database getting the price of the trip).

Since the website has two languages I need to translate both the module and the database as well. I proceeded in the following way:

I created two folders containing the same module but one is in
Italian while the other is in English;

Each module queries the
correct database, the Italian module takes the data from the Italian
DB while the English module read the data from the translated one
(es. Malpensa Aeroporto -> Malpensa Airport).

What I would like to do now is to create an if statement that does the following:

IF (on the homepage of mysite.com/) {
Get the English module
} else IF (on the homepage of mysite.com/it/) {
    Get the Italian module
    } else {
    Do nothing because you are not on any homepage
    }

I already have searched in the blog and around the internet but I am not able to find something working. How can I develop this "IF statement"?

Thank you all

Body:
You can do it by this,

$explode = explode('/', $_SERVER['REQUEST_URI']);
if($explode[1] == 'it'){
    echo 'call Italian';
}else{
    echo 'call English';
}

$_SERVER['REQUEST_URI'] contain the path in site.
In my case

/stack/help.php

So explode() it and then check if the directory name equal to it you call the module for Italian language else call English one.

And this you must call in file included in both
index.php, /it/index.php

Or try this

explode getcwd() and use end()

$directory = explode('/', getcwd());
if( end($directory) == 'it' ){
    //call Italian Module
}else{
    //call English Module
}

Hope this helps,


问:
Replacing NaN with other value (mean) in MATLAB
I have matrix A such as:

```<code>A = [1  2  3 NaN;
     1 NaN 2 NaN;
     NaN 2 3 4]
</code>```

I would like to replace every NaN in A with a predefined value such as my columns vector B:

```<code>B = [2; 1.5; 3]
</code>```

So for the second row, I'd like to obtain a new matrix, where every NaN in this particular row is replaced by 1.5. It would be 2 in the first row and 3 in the third row.

Is there a better way to do so other than looping through the entire matrix? I used a for loop with the if and else conditions. However, this solution does not execute very fast.

答:
Here you are:

```<code>A = [
    1 2 3 NaN;
    1 NaN 2 NaN;
    NaN 2 3 4
];

B = [2; 1.5; 3];
B = repmat(B,1,size(A,2));

idx = isnan(A);
A(idx) = B(idx);
</code>```

Since you are speaking about a row mean in the title of your question, I suppose that the vector B must not be manually defined, but it should rather be calculated from your A matrix. So:

```<code>A = [
    1 2 3 NaN;
    1 NaN 2 NaN;
    NaN 2 3 4
];

B = repmat(nanmean(A,2),1,size(A,2));

idx = isnan(A);
A(idx) = B(idx);
</code>```

Body:
I have matrix A such as:

A = [1  2  3 NaN;
     1 NaN 2 NaN;
     NaN 2 3 4]

I would like to replace every NaN in A with a predefined value such as my columns vector B:

B = [2; 1.5; 3]

So for the second row, I'd like to obtain a new matrix, where every NaN in this particular row is replaced by 1.5. It would be 2 in the first row and 3 in the third row.

Is there a better way to do so other than looping through the entire matrix? I used a for loop with the if and else conditions. However, this solution does not execute very fast.

Body:
Here you are:

A = [
    1 2 3 NaN;
    1 NaN 2 NaN;
    NaN 2 3 4
];

B = [2; 1.5; 3];
B = repmat(B,1,size(A,2));

idx = isnan(A);
A(idx) = B(idx);

Since you are speaking about a row mean in the title of your question, I suppose that the vector B must not be manually defined, but it should rather be calculated from your A matrix. So:

A = [
    1 2 3 NaN;
    1 NaN 2 NaN;
    NaN 2 3 4
];

B = repmat(nanmean(A,2),1,size(A,2));

idx = isnan(A);
A(idx) = B(idx);


问:
How to edit permissions on CryptoKeySecurity?
I have posted about this already but no luck since then I have more information I thought I would try again I really hope someone can help. Basically I am reading an XML file and verifying the fact that it has been signed. This code works perfectly when run as an adminitrator but not as network service, the final line resolves to 'true' but when not run as admin doesnt.

NOTE: this is not a problem with reading the XML file this opens fine. The problem is with one of the objects in memory. I 'think' the problem is to do with access control lists on the CryptoKeyRights object.

I have used the following (in the below code) to try and grant everyone access to the CspParams object:

```<code>CryptoKeyRights rightsForall = CryptoKeyRights.FullControl;

CryptoKeyAccessRule everyone = new CryptoKeyAccessRule(@"Everyone", CryptoKeyRights.FullControl, AccessControlType.Allow);

cspParams.CryptoKeySecurity = new CryptoKeySecurity();

cspParams.CryptoKeySecurity.AddAccessRule(everyone);
</code>```

The above code

The code is:

```<code>// Verify the signature of an XML file against an asymmetric
// algorithm and return the result.XmlDocument Doc, RSA Key
public static Boolean VerifyLicenceFile(string xmlLicFilePathArg)
{
    bool isVerified = false;

    try
    {

        CspParameters cspParams = new CspParameters();

        cspParams.KeyContainerName = containerName;

        RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);

        // Create a new XML document.
        XmlDocument xmlDoc = new XmlDocument();

        // Load an XML file into the XmlDocument object.
        xmlDoc.PreserveWhitespace = true;
        xmlDoc.Load(xmlLicFilePathArg);

        // Check arguments.
        if (xmlDoc == null)
            throw new ArgumentException("Doc");
        if (rsaKey == null)
            throw new ArgumentException("Key");

        // Create a new SignedXml object and pass it
        // the XML document class.
        SignedXml signedXml = new SignedXml(xmlDoc);

        // Find the "Signature" node and create a new
        // XmlNodeList object.
        XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Signature");

        // Throw an exception if no signature was found.
        if (nodeList.Count <= 0)
        {
            throw new CryptographicException("Verification failed: No Signature was found in the document.");
        }

        // This example only supports one signature for
        // the entire XML document.  Throw an exception
        // if more than one signature was found.
        if (nodeList.Count >= 2)
        {
            throw new CryptographicException("Verification failed: More that one signature was found for the document.");
        }

        // Load the first <signature> node.
        signedXml.LoadXml((XmlElement)nodeList[0]);

        // Check the signature and return the result.
        isVerified = signedXml.CheckSignature(rsaKey);
    }
    catch (Exception ex)
    {
    }

    return isVerified;

}
</code>```

答:
The anser for this was not to use the machine to store the keys in...export them and load them independantly...

Is it possible to sign an xml document without having to use KeyContainerName?

Body:
I have posted about this already but no luck since then I have more information I thought I would try again I really hope someone can help. Basically I am reading an XML file and verifying the fact that it has been signed. This code works perfectly when run as an adminitrator but not as network service, the final line resolves to 'true' but when not run as admin doesnt.

NOTE: this is not a problem with reading the XML file this opens fine. The problem is with one of the objects in memory. I 'think' the problem is to do with access control lists on the CryptoKeyRights object.

I have used the following (in the below code) to try and grant everyone access to the CspParams object:

CryptoKeyRights rightsForall = CryptoKeyRights.FullControl;

CryptoKeyAccessRule everyone = new CryptoKeyAccessRule(@"Everyone", CryptoKeyRights.FullControl, AccessControlType.Allow);

cspParams.CryptoKeySecurity = new CryptoKeySecurity();

cspParams.CryptoKeySecurity.AddAccessRule(everyone);

The above code

The code is:

// Verify the signature of an XML file against an asymmetric
// algorithm and return the result.XmlDocument Doc, RSA Key
public static Boolean VerifyLicenceFile(string xmlLicFilePathArg)
{
    bool isVerified = false;

    try
    {

        CspParameters cspParams = new CspParameters();

        cspParams.KeyContainerName = containerName;

        RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);

        // Create a new XML document.
        XmlDocument xmlDoc = new XmlDocument();

        // Load an XML file into the XmlDocument object.
        xmlDoc.PreserveWhitespace = true;
        xmlDoc.Load(xmlLicFilePathArg);

        // Check arguments.
        if (xmlDoc == null)
            throw new ArgumentException("Doc");
        if (rsaKey == null)
            throw new ArgumentException("Key");

        // Create a new SignedXml object and pass it
        // the XML document class.
        SignedXml signedXml = new SignedXml(xmlDoc);

        // Find the "Signature" node and create a new
        // XmlNodeList object.
        XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Signature");

        // Throw an exception if no signature was found.
        if (nodeList.Count <= 0)
        {
            throw new CryptographicException("Verification failed: No Signature was found in the document.");
        }

        // This example only supports one signature for
        // the entire XML document.  Throw an exception
        // if more than one signature was found.
        if (nodeList.Count >= 2)
        {
            throw new CryptographicException("Verification failed: More that one signature was found for the document.");
        }

        // Load the first <signature> node.
        signedXml.LoadXml((XmlElement)nodeList[0]);

        // Check the signature and return the result.
        isVerified = signedXml.CheckSignature(rsaKey);
    }
    catch (Exception ex)
    {
    }

    return isVerified;

}