问:
How to convert lists of lines in strings to lists of lists, with each item in the lines stripped
I want to convert lists of lines in strings to lists of lists, with each item in the lines stripped.

The following works, but I suspect there is a sleeker way to do this.

```<code>def str_to_lst_of_lsts(s):
    lst = s.splitlines()[1:]
    lst2 = [i.split(';') for i in lst]
    lst3 = []
    for i in lst2:
        i2 = [j.strip() for j in i]
        lst3.append(i2)
    return lst3

s = '''
c; German for dog; Hund
c; capital of France; Paris
c; company; IBM
c; nation; Sweden
c; nickname for James; Jim
'''

print(str_to_lst_of_lsts(s))

# [['c', 'German for dog', 'Hund'], ['c', 'capital of France', 'Paris'], ['c', 'company', 'IBM'], ['c', 'nation', 'Sweden'], ['c', 'nickname for James', 'Jim']]
</code>```

答:
This will work also - </p>

```<code>p = s.split("\n")
l = [x.split(";")  for x in p if x != ""]
print l
>>> [['c', ' German for dog', ' Hund'], ['c', ' capital of France', ' Paris'], ['c', ' company', ' IBM'], ['c', ' nation', ' Sweden'], ['c', ' nickname for James', ' Jim']]
</code>```

Body:
I want to convert lists of lines in strings to lists of lists, with each item in the lines stripped.

The following works, but I suspect there is a sleeker way to do this.

def str_to_lst_of_lsts(s):
    lst = s.splitlines()[1:]
    lst2 = [i.split(';') for i in lst]
    lst3 = []
    for i in lst2:
        i2 = [j.strip() for j in i]
        lst3.append(i2)
    return lst3

s = '''
c; German for dog; Hund
c; capital of France; Paris
c; company; IBM
c; nation; Sweden
c; nickname for James; Jim
'''

print(str_to_lst_of_lsts(s))

# [['c', 'German for dog', 'Hund'], ['c', 'capital of France', 'Paris'], ['c', 'company', 'IBM'], ['c', 'nation', 'Sweden'], ['c', 'nickname for James', 'Jim']]

Body:
This will work also -

p = s.split("\n")
l = [x.split(";")  for x in p if x != ""]
print l
>>> [['c', ' German for dog', ' Hund'], ['c', ' capital of France', ' Paris'], ['c', ' company', ' IBM'], ['c', ' nation', ' Sweden'], ['c', ' nickname for James', ' Jim']]


来源: stackexchange

问:
Create a new column following complex condition
Here is the full explanation of the situation. My code seems to not be very helpful in understanding what I want, so I try to describe it in words:

I had people play auctions for 5 rounds, where they were paired with another participant, and each one of them had certain (random, different each round) "Value". Each of them could place as many bids ("Amount") as they wanted. The time at which the bid was placed was also saved, along with info whether the bid was successful. What I ultimately want to find out, is if the person with the highest value won the auction (= placed the highest successful bid[and was the first one in case of a draw]).

To do that (and also for practice) I first wanted to create a column where I check if there have occurred identical values in groups ("0"). Along the way I figured I could also check if the player had the higher ("1"), or lower ("-1") value of the two. To do that I wanted to loop through the rows, check the conditions, and write the corresponding value into the new column.

Below: old explanation

I am trying to create a new column, which should take values of 1, 0, or -1, if someone in the same round had a lower, same, or higher value in the column "Value". The other questions on here seem to only handle very simple situations (or I don't see the connection, I just started this)
What I try is:

```<code>dat_A08["ValueIsHigher"] <- NA
for (bid in dat_A08){
  if (bid$Value == max(dat_A08[dat_A08&Round == bid&Round & dat_A08&GroupID == bid&GroupID,]$Value)){
    bid&ValueIsHigher = 0
  } else if (bid$Value < max(dat_A08[dat_A08&Round == bid&Round & dat_A08&GroupID == bid&GroupID,]$Value)) {
    bid&ValueIsHigher = -1
  } else {
    bid&ValueIsHigher = 1
  }
}
</code>```

I pretty much define a new column, and then try to write new values to it, depending on the condition. But I get the error

Error: $ operator is invalid for atomic vectors

How can I access this value?

The data file looks like this:

```<code>Mode;Round;Value;Amount;At_time;In_stage;Success;participant_code;GroupID;BidToValue;GebAlsHoechstb
2;5;41;41;264.537.857.723.236;1;1;p10;1;1;
2;5;37;37;264.558.881.688.118;1;1;p4;1;1;
2;5;37;38;265.961.394.166.946;2;1;p4;1;2;
2;5;40;60;2.589.505.194.664;2;1;p11;2;2;
2;5;40;40;252.504.601.478.577;1;1;p11;2;1;
2;5;45;45;257.754.272.294.044;1;1;p3;2;1;
2;5;40;61;266.139.678.239.822;2;1;p11;2;2;
</code>```

The whole script should work like this:

```<code>dat_A08 = read.csv("csv_A08.csv", header = TRUE, sep = ";")
dat_A08 <- dat_A08[,!(names(dat_A08) %in% c("GebAlsHoechstb"))]

dat_A08$At_time <- as.numeric(as.character(gsub("\\.","",dat_A08$At_time)))

dat_A08["ValueIsHigher"] <- NA
for (bid in dat_A08){
  if (bid$Value == max(dat_A08[dat_A08&Round == bid&Round & dat_A08&GroupID == bid&GroupID,]$Value)){
    bid&ValueIsHigher = 0
  } else if (bid$Value < max(dat_A08[dat_A08&Round == bid&Round & dat_A08&GroupID == bid&GroupID,]$Value)) {
    bid&ValueIsHigher = -1
  } else {
    bid&ValueIsHigher = 1
  }
}
</code>```

答:
Please tell me if it's what you want. as I'm not sure I understand the whole question (check the last 3 cols of the result).

If it's what you want I can explain in more depth

```<code>dat_A08 <- read.table(text ="Mode;Round;Value;Amount;At_time;In_stage;Success;participant_code;GroupID;BidToValue;GebAlsHoechstb
2;5;41;41;264.537.857.723.236;1;1;p10;1;1;
2;5;37;37;264.558.881.688.118;1;1;p4;1;1;
2;5;37;38;265.961.394.166.946;2;1;p4;1;2;
2;5;40;60;2.589.505.194.664;2;1;p11;2;2;
2;5;40;40;252.504.601.478.577;1;1;p11;2;1;
2;5;45;45;257.754.272.294.044;1;1;p3;2;1;
2;5;40;61;266.139.678.239.822;2;1;p11;2;2;",sep=";",header=TRUE)

max_values <- setNames(aggregate(Value ~ Round,dat_A08,max)   ,c("Round","max_value"))
min_values <- setNames(aggregate(Value ~ Round,dat_A08,min)   ,c("Round","min_value"))
n_values   <- as.data.frame(table(dat_A08[,c("Value","Round")]))
dat_A08b <- merge(dat_A08 ,min_values)
dat_A08b <- merge(dat_A08b,max_values)
dat_A08b <- merge(dat_A08b,n_values)
dat_A08b$is_max   <- dat_A08b$Value == dat_A08b$max_value
dat_A08b$is_min   <- dat_A08b$Value == dat_A08b$min_value
dat_A08b$somebody_has_same_value <- dat_A08b$Freq > 1

# Round Value Mode Amount             At_time In_stage Success participant_code GroupID BidToValue GebAlsHoechstb min_value max_value Freq is_max is_min
# 1     5    37    2     37 264.558.881.688.118        1       1               p4       1          1             NA        37        45    2  FALSE   TRUE
# 2     5    37    2     38 265.961.394.166.946        2       1               p4       1          2             NA        37        45    2  FALSE   TRUE
# 3     5    40    2     60   2.589.505.194.664        2       1              p11       2          2             NA        37        45    3  FALSE  FALSE
# 4     5    40    2     40 252.504.601.478.577        1       1              p11       2          1             NA        37        45    3  FALSE  FALSE
# 5     5    40    2     61 266.139.678.239.822        2       1              p11       2          2             NA        37        45    3  FALSE  FALSE
# 6     5    41    2     41 264.537.857.723.236        1       1              p10       1          1             NA        37        45    1  FALSE  FALSE
# 7     5    45    2     45 257.754.272.294.044        1       1               p3       2          1             NA        37        45    1   TRUE  FALSE
# somebody_has_same_value
# 1                    TRUE
# 2                    TRUE
# 3                    TRUE
# 4                    TRUE
# 5                    TRUE
# 6                   FALSE
# 7                   FALSE
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is the full explanation of the situation. My code seems to not be very helpful in understanding what I want, so I try to describe it in words:

I had people play auctions for 5 rounds, where they were paired with another participant, and each one of them had certain (random, different each round) "Value". Each of them could place as many bids ("Amount") as they wanted. The time at which the bid was placed was also saved, along with info whether the bid was successful. What I ultimately want to find out, is if the person with the highest value won the auction (= placed the highest successful bid[and was the first one in case of a draw]).

To do that (and also for practice) I first wanted to create a column where I check if there have occurred identical values in groups ("0"). Along the way I figured I could also check if the player had the higher ("1"), or lower ("-1") value of the two. To do that I wanted to loop through the rows, check the conditions, and write the corresponding value into the new column.

Below: old explanation

I am trying to create a new column, which should take values of 1, 0, or -1, if someone in the same round had a lower, same, or higher value in the column "Value". The other questions on here seem to only handle very simple situations (or I don't see the connection, I just started this)
What I try is:

dat_A08["ValueIsHigher"] <- NA
for (bid in dat_A08){
  if (bid$Value == max(dat_A08[dat_A08&Round == bid&Round & dat_A08&GroupID == bid&GroupID,]$Value)){
    bid&ValueIsHigher = 0
  } else if (bid$Value < max(dat_A08[dat_A08&Round == bid&Round & dat_A08&GroupID == bid&GroupID,]$Value)) {
    bid&ValueIsHigher = -1
  } else {
    bid&ValueIsHigher = 1
  }
}

I pretty much define a new column, and then try to write new values to it, depending on the condition. But I get the error

Error: $ operator is invalid for atomic vectors

How can I access this value?

The data file looks like this:

Mode;Round;Value;Amount;At_time;In_stage;Success;participant_code;GroupID;BidToValue;GebAlsHoechstb
2;5;41;41;264.537.857.723.236;1;1;p10;1;1;
2;5;37;37;264.558.881.688.118;1;1;p4;1;1;
2;5;37;38;265.961.394.166.946;2;1;p4;1;2;
2;5;40;60;2.589.505.194.664;2;1;p11;2;2;
2;5;40;40;252.504.601.478.577;1;1;p11;2;1;
2;5;45;45;257.754.272.294.044;1;1;p3;2;1;
2;5;40;61;266.139.678.239.822;2;1;p11;2;2;

The whole script should work like this:

dat_A08 = read.csv("csv_A08.csv", header = TRUE, sep = ";")
dat_A08 <- dat_A08[,!(names(dat_A08) %in% c("GebAlsHoechstb"))]

dat_A08$At_time <- as.numeric(as.character(gsub("\\.","",dat_A08$At_time)))

dat_A08["ValueIsHigher"] <- NA
for (bid in dat_A08){
  if (bid$Value == max(dat_A08[dat_A08&Round == bid&Round & dat_A08&GroupID == bid&GroupID,]$Value)){
    bid&ValueIsHigher = 0
  } else if (bid$Value < max(dat_A08[dat_A08&Round == bid&Round & dat_A08&GroupID == bid&GroupID,]$Value)) {
    bid&ValueIsHigher = -1
  } else {
    bid&ValueIsHigher = 1
  }
}

Body:
Please tell me if it's what you want. as I'm not sure I understand the whole question (check the last 3 cols of the result).

If it's what you want I can explain in more depth

dat_A08 <- read.table(text ="Mode;Round;Value;Amount;At_time;In_stage;Success;participant_code;GroupID;BidToValue;GebAlsHoechstb
2;5;41;41;264.537.857.723.236;1;1;p10;1;1;
2;5;37;37;264.558.881.688.118;1;1;p4;1;1;
2;5;37;38;265.961.394.166.946;2;1;p4;1;2;
2;5;40;60;2.589.505.194.664;2;1;p11;2;2;
2;5;40;40;252.504.601.478.577;1;1;p11;2;1;
2;5;45;45;257.754.272.294.044;1;1;p3;2;1;
2;5;40;61;266.139.678.239.822;2;1;p11;2;2;",sep=";",header=TRUE)

max_values <- setNames(aggregate(Value ~ Round,dat_A08,max)   ,c("Round","max_value"))
min_values <- setNames(aggregate(Value ~ Round,dat_A08,min)   ,c("Round","min_value"))
n_values   <- as.data.frame(table(dat_A08[,c("Value","Round")]))
dat_A08b <- merge(dat_A08 ,min_values)
dat_A08b <- merge(dat_A08b,max_values)
dat_A08b <- merge(dat_A08b,n_values)
dat_A08b$is_max   <- dat_A08b$Value == dat_A08b$max_value
dat_A08b$is_min   <- dat_A08b$Value == dat_A08b$min_value
dat_A08b$somebody_has_same_value <- dat_A08b$Freq > 1

# Round Value Mode Amount             At_time In_stage Success participant_code GroupID BidToValue GebAlsHoechstb min_value max_value Freq is_max is_min
# 1     5    37    2     37 264.558.881.688.118        1       1               p4       1          1             NA        37        45    2  FALSE   TRUE
# 2     5    37    2     38 265.961.394.166.946        2       1               p4       1          2             NA        37        45    2  FALSE   TRUE
# 3     5    40    2     60   2.589.505.194.664        2       1              p11       2          2             NA        37        45    3  FALSE  FALSE
# 4     5    40    2     40 252.504.601.478.577        1       1              p11       2          1             NA        37        45    3  FALSE  FALSE
# 5     5    40    2     61 266.139.678.239.822        2       1              p11       2          2             NA        37        45    3  FALSE  FALSE
# 6     5    41    2     41 264.537.857.723.236        1       1              p10       1          1             NA        37        45    1  FALSE  FALSE
# 7     5    45    2     45 257.754.272.294.044        1       1               p3       2          1             NA        37        45    1   TRUE  FALSE
# somebody_has_same_value
# 1                    TRUE
# 2                    TRUE
# 3                    TRUE
# 4                    TRUE
# 5                    TRUE
# 6                   FALSE
# 7                   FALSE

ContentLicense: CC BY-SA 3.0


问:
Django cannot use Sum with SQLite and time fields?
I have a model with a time field, and I need to sum the time fields in all instances.

This is what I've tried:

```<code>total_hours = Day.objects.filter(date__year=current_year, date__month=current_month).aggregate(Sum('total_work_hours'))
print(total_hours)
</code>```

and I get this error:

You cannot use Sum, Avg, StdDev, and Variance aggregations on date/time fields in sqlite3 since date/time is saved as text.

Is there a way around this? I'd like to stick with SQLite for now.

答:
Ok here's what I ended up doing. I added a map to convert the time objects to hours.</p>

```<code>times = Day.objects.filter(date__year=current_year, date__month=current_month).values_list('total_work_hours', flat=True)
hours = map(lambda time: time.hour + (time.minute / 60.0), times)
total_hours = sum(hours)
</code>```

Body:
I have a model with a time field, and I need to sum the time fields in all instances.

This is what I've tried:

total_hours = Day.objects.filter(date__year=current_year, date__month=current_month).aggregate(Sum('total_work_hours'))
print(total_hours)

and I get this error:

You cannot use Sum, Avg, StdDev, and Variance aggregations on date/time fields in sqlite3 since date/time is saved as text.

Is there a way around this? I'd like to stick with SQLite for now.

Body:
Ok here's what I ended up doing. I added a map to convert the time objects to hours.

times = Day.objects.filter(date__year=current_year, date__month=current_month).values_list('total_work_hours', flat=True)
hours = map(lambda time: time.hour + (time.minute / 60.0), times)
total_hours = sum(hours)


问:
Servicenow script infinite recursion
I have the following ServiceNow script which inserts the record into live_message table.

```<code>(function executeRule(current, previous/*null when async*/) {

  var requestBody;
  var responseBody;
  var status;
  var request;
  var response;

  try {

    request = new sn_ws.RESTMessageV2("LiveMessageWebhook", "post");

    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    var parameters = "&chat_message=" + current.chat_message.toString();
    parameters = parameters + "&context=" + current.context.toString();
    parameters = parameters + "&formatted_message=" + current.formatted_message.toString();
    parameters = parameters + "&has_attachments=" + current.has_attachments.toString();
    parameters = parameters + "&has_links=" + current.has_links.toString();
    parameters = parameters + "&has_tags=" + current.has_tags.toString();
    parameters = parameters + "&ID=" + current.id.toString();
    parameters = parameters + "&in_reply_to=" + current.in_reply_to.toString();
    parameters = parameters + "&isLiked=" + current.is_liked.toString();
    parameters = parameters + "&lastActivity=" + current.last_activity.toString();
    parameters = parameters + "&lastMessage=" + current.last_message.toString();
    parameters = parameters + "&likeCount=" + current.like_count.toString();
    parameters = parameters + "&message=" + current.message.toString();
    parameters = parameters + "&next_reply_order_chunk=" + current.next_reply_order_chunk.toString();
    parameters = parameters + "&order=" + current.order.toString();
    parameters = parameters + "&poll=" + current.poll.toString();
    parameters = parameters + "&private=" + current.private_message.toString();
    parameters = parameters + "&profile=" + current.profile.toString();
    parameters = parameters + "&reflected_field=" + current.reflected_field.toString();
    parameters = parameters + "&reply_to=" + current.reply_to.toString();
    parameters = parameters + "&state=" + current.state.toString();
    parameters = parameters + "&group_type=" + current.sys_class_name.toString();
    parameters = parameters + "&created_by=" + current.sys_created_by.toString();
    parameters = parameters + "&created_on=" + current.sys_created_on.toString();
    parameters = parameters + "&domain=" + current.sys_domain.toString();
    parameters = parameters + "&domain_path=" + current.sys_domain_path.toString();
    parameters = parameters + "&sys_ID=" + current.sys_id.toString();
    parameters = parameters + "&to_profile=" + current.sys_domain.toString();
    parameters = parameters + "&updates=" + current.sys_mod_count.toString();
    parameters = parameters + "&updated_by=" + current.sys_updated_by.toString();
    parameters = parameters + "&updated_on=" + current.sys_updated_on.toString();

    request.setRequestBody(encodeURI(parameters));
    var l = request.getRequestBody();
    response = request.execute();

    responseBody = response.haveError()
      ? response.getErrorMessage()
      : response.getBody();
    status = response.getStatusCode();
    {
      var gr = new GlideRecord('live_message');

      gr.initialize();
      gr.chat_message = current.chat_message;
      gr.context = current.context.toString();
      gr.formatted_message = "abc";
      gr.group = current.group;
      gr.has_attachments = current.has_attachments;
      gr.has_links = current.has_links;
      gr.has_tags = current.has_tags;
      gr.id = current.id;
      gr.in_reply_to = "admin";
      gr.is_liked = current.is_liked;
      gr.last_activity = current.last_activity;
      gr.last_message = current.last_message;
      gr.like_count = current.like_count;
      gr.message = "abc";
      gr.next_reply_order_chunk = current.next_reply_order_chunk;
      gr.order = current.order;
      gr.poll = current.poll;
      gr.private_message = current.private_message;
      gr.profile = current.profile;
      gr.reflected_field = current.reflected_field;
      gr.reply_to = current.reply_to;
      gr.state = current.state;

      gr.sys_class_name = current.sys_class_name;
      gr.sys_created_by = current.sys_created_by;
      gr.sys_created_on = current.sys_created_on;
      gr.sys_domain = current.sys_domain;
      gr.sys_domain_path = current.sys_domain_path;
      gr.sys_mod_count = current.sys_mod_count;
      gr.sys_updated_by = current.sys_updated_by;
      gr.sys_updated_on = current.sys_updated_on;
      gr.to_profile = current.to_profile;
      gr.insertWithReferences();

    }

  } catch (ex) {
    responseBody = 'Exception: ' + ex;
    status = '900';
    requestBody = request
      ? request.getRequestBody()
      : null;
  } finally {
    gs.info("Final: Request Body: " + requestBody);
    gs.info("Final: Response: " + responseBody);
    gs.info("Final: HTTP Status: " + status);
    gs.addInfoMessage('Final: Finished');
  }

})(current, previous);
</code>```

But after inserting the record it again goes back to the try block again and does the whole thing again and now with the inserted record

答:
How is this business rule configured?
Is it possible that the changes made by this script, could also trigger the script to run?

Here's an example of what I mean:
Imagine I have a business rule that executes whenever a record in the table "u_arbitrary_counter" is updated.
Imagine that the function of this business rule is that whenever such a record is updated, we increase the value of the "u_counter" field by one, like so:

```<code>current.setValue('u_counter', parseInt(current.getValue('u_counter')) + 1);
current.update();
</code>```

By using .update(), I'm forcing an update to the database, EVEN if this is a "before" business rule.

Pro Tip: Note that "before" business rules run on the data that's about to be
  saved to the database, BEFORE the actual database operation has taken
  place. Any changes to the "current" object in a "before" business rule
  will be saved even without using current.update, because you're
  modifying the data that's about to be sent to the database anyway, in
  the natural course of this operation.

So using current.update() in a BEFORE business rule isn't a great idea. For the same reason though, performing any other operation which necessarily leads to a database update which could trigger this same business rule is a bad idea. It doesn't have to be current.update() -- Instead, imagine if rather than updating the current record, I did something like...

```<code>var gr = new GlideRecord('u_arbitrary_counter'); //the same table this BR is running on
gr.initialize();
gr.setValue('u_counter', parseInt(current.getValue('u_counter')) + 1);
gr.insert(); //This triggers a database action!
</code>```

This is no good for the same reason.
Ditto for any REST calls which would trigger a DB action on this table which may trigger this business rule.

The solution

If this is indeed the cause of your issue (and without knowing the configuration of your business rule, I can't be sure if it is or not), there is actually a way to tell the system not to run any further business rules as a result of the operation your script performs. Right before your gr.insertWithReferences(); line (line 91), IF that block of code is the issue (which I'm fairly confident it is), add:

```<code>gr.setWorkflow(false);
</code>```

This prevents business rules from running.
Unfortunately, since you're placing the record into the live_message table, that may not be a good idea either, since the messenger may require some business rule to propagate or present that information once inserted; I'm not sure.
If that is the case, I would recommend adding a condition to your business rule so that it only runs under certain circumstances, and then craft your inserted record to not meet those criteria.

Pro Tip: PS - I notice you access a table field using current.field_name.toString() in some places, and directly access
  current.field_name in others. While the former is acceptable (not
  that I recommend it in most cases), the latter should almost never be
  used -- except in the case of journal fields. Instead, I strongly
  recommend using the appropriate getter/setter methods, to avoid
  pass-by-reference issues and confusion, and to ensure you're not
  relying on JavaScript's coersion, which doesn't always play nice with
  Mozilla Rhino, which ServiceNow runs on the back-end. Example issue
  here.  For more info, please see my article on using getValue()
  and setValue() in ServiceNow.

Title: Servicenow script infinite recursion

Body:
I have the following ServiceNow script which inserts the record into live_message table.

(function executeRule(current, previous/*null when async*/) {

  var requestBody;
  var responseBody;
  var status;
  var request;
  var response;

  try {

    request = new sn_ws.RESTMessageV2("LiveMessageWebhook", "post");

    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    var parameters = "&chat_message=" + current.chat_message.toString();
    parameters = parameters + "&context=" + current.context.toString();
    parameters = parameters + "&formatted_message=" + current.formatted_message.toString();
    parameters = parameters + "&has_attachments=" + current.has_attachments.toString();
    parameters = parameters + "&has_links=" + current.has_links.toString();
    parameters = parameters + "&has_tags=" + current.has_tags.toString();
    parameters = parameters + "&ID=" + current.id.toString();
    parameters = parameters + "&in_reply_to=" + current.in_reply_to.toString();
    parameters = parameters + "&isLiked=" + current.is_liked.toString();
    parameters = parameters + "&lastActivity=" + current.last_activity.toString();
    parameters = parameters + "&lastMessage=" + current.last_message.toString();
    parameters = parameters + "&likeCount=" + current.like_count.toString();
    parameters = parameters + "&message=" + current.message.toString();
    parameters = parameters + "&next_reply_order_chunk=" + current.next_reply_order_chunk.toString();
    parameters = parameters + "&order=" + current.order.toString();
    parameters = parameters + "&poll=" + current.poll.toString();
    parameters = parameters + "&private=" + current.private_message.toString();
    parameters = parameters + "&profile=" + current.profile.toString();
    parameters = parameters + "&reflected_field=" + current.reflected_field.toString();
    parameters = parameters + "&reply_to=" + current.reply_to.toString();
    parameters = parameters + "&state=" + current.state.toString();
    parameters = parameters + "&group_type=" + current.sys_class_name.toString();
    parameters = parameters + "&created_by=" + current.sys_created_by.toString();
    parameters = parameters + "&created_on=" + current.sys_created_on.toString();
    parameters = parameters + "&domain=" + current.sys_domain.toString();
    parameters = parameters + "&domain_path=" + current.sys_domain_path.toString();
    parameters = parameters + "&sys_ID=" + current.sys_id.toString();
    parameters = parameters + "&to_profile=" + current.sys_domain.toString();
    parameters = parameters + "&updates=" + current.sys_mod_count.toString();
    parameters = parameters + "&updated_by=" + current.sys_updated_by.toString();
    parameters = parameters + "&updated_on=" + current.sys_updated_on.toString();

    request.setRequestBody(encodeURI(parameters));
    var l = request.getRequestBody();
    response = request.execute();

    responseBody = response.haveError()
      ? response.getErrorMessage()
      : response.getBody();
    status = response.getStatusCode();
    {
      var gr = new GlideRecord('live_message');

      gr.initialize();
      gr.chat_message = current.chat_message;
      gr.context = current.context.toString();
      gr.formatted_message = "abc";
      gr.group = current.group;
      gr.has_attachments = current.has_attachments;
      gr.has_links = current.has_links;
      gr.has_tags = current.has_tags;
      gr.id = current.id;
      gr.in_reply_to = "admin";
      gr.is_liked = current.is_liked;
      gr.last_activity = current.last_activity;
      gr.last_message = current.last_message;
      gr.like_count = current.like_count;
      gr.message = "abc";
      gr.next_reply_order_chunk = current.next_reply_order_chunk;
      gr.order = current.order;
      gr.poll = current.poll;
      gr.private_message = current.private_message;
      gr.profile = current.profile;
      gr.reflected_field = current.reflected_field;
      gr.reply_to = current.reply_to;
      gr.state = current.state;

      gr.sys_class_name = current.sys_class_name;
      gr.sys_created_by = current.sys_created_by;
      gr.sys_created_on = current.sys_created_on;
      gr.sys_domain = current.sys_domain;
      gr.sys_domain_path = current.sys_domain_path;
      gr.sys_mod_count = current.sys_mod_count;
      gr.sys_updated_by = current.sys_updated_by;
      gr.sys_updated_on = current.sys_updated_on;
      gr.to_profile = current.to_profile;
      gr.insertWithReferences();

    }

  } catch (ex) {
    responseBody = 'Exception: ' + ex;
    status = '900';
    requestBody = request
      ? request.getRequestBody()
      : null;
  } finally {
    gs.info("Final: Request Body: " + requestBody);
    gs.info("Final: Response: " + responseBody);
    gs.info("Final: HTTP Status: " + status);
    gs.addInfoMessage('Final: Finished');
  }

})(current, previous);

But after inserting the record it again goes back to the try block again and does the whole thing again and now with the inserted record

Body:
How is this business rule configured?
Is it possible that the changes made by this script, could also trigger the script to run?

Here's an example of what I mean:
Imagine I have a business rule that executes whenever a record in the table "u_arbitrary_counter" is updated.
Imagine that the function of this business rule is that whenever such a record is updated, we increase the value of the "u_counter" field by one, like so:

current.setValue('u_counter', parseInt(current.getValue('u_counter')) + 1);
current.update();

By using .update(), I'm forcing an update to the database, EVEN if this is a "before" business rule.

Pro Tip: Note that "before" business rules run on the data that's about to be
  saved to the database, BEFORE the actual database operation has taken
  place. Any changes to the "current" object in a "before" business rule
  will be saved even without using current.update, because you're
  modifying the data that's about to be sent to the database anyway, in
  the natural course of this operation.

So using current.update() in a BEFORE business rule isn't a great idea. For the same reason though, performing any other operation which necessarily leads to a database update which could trigger this same business rule is a bad idea. It doesn't have to be current.update() -- Instead, imagine if rather than updating the current record, I did something like...

var gr = new GlideRecord('u_arbitrary_counter'); //the same table this BR is running on
gr.initialize();
gr.setValue('u_counter', parseInt(current.getValue('u_counter')) + 1);
gr.insert(); //This triggers a database action!

This is no good for the same reason.
Ditto for any REST calls which would trigger a DB action on this table which may trigger this business rule.

The solution

If this is indeed the cause of your issue (and without knowing the configuration of your business rule, I can't be sure if it is or not), there is actually a way to tell the system not to run any further business rules as a result of the operation your script performs. Right before your gr.insertWithReferences(); line (line 91), IF that block of code is the issue (which I'm fairly confident it is), add:

gr.setWorkflow(false);

This prevents business rules from running.
Unfortunately, since you're placing the record into the live_message table, that may not be a good idea either, since the messenger may require some business rule to propagate or present that information once inserted; I'm not sure.
If that is the case, I would recommend adding a condition to your business rule so that it only runs under certain circumstances, and then craft your inserted record to not meet those criteria.

Pro Tip: PS - I notice you access a table field using current.field_name.toString() in some places, and directly access
  current.field_name in others. While the former is acceptable (not
  that I recommend it in most cases), the latter should almost never be
  used -- except in the case of journal fields. Instead, I strongly
  recommend using the appropriate getter/setter methods, to avoid
  pass-by-reference issues and confusion, and to ensure you're not
  relying on JavaScript's coersion, which doesn't always play nice with
  Mozilla Rhino, which ServiceNow runs on the back-end. Example issue
  here.  For more info, please see my article on using getValue()
  and setValue() in ServiceNow.


问:
postgres select by date (long) with timezone
This query gives duplicates however I am struggling to understand exactly why? I do have many rows per id in trading.delayed but only one with the exact same timestamp

Could someone explain me what I am missing ?

```<code>      SELECT t1.contract,t1.date FROM trading.delayed AS t1,
(SELECT contract, max(date) AS date FROM trading.delayed GROUP BY contract) AS t2
WHERE t1.date =t2.date order BY contract DESC;
</code>```

Results: contract, date

```<code>32;"2017-06-07 02:04:11.797+07"
32;"2017-06-07 02:04:14.489+07"
31;"2017-06-07 02:04:12.04+07"
30;"2017-06-07 02:03:54.182+07"
30;"2017-06-07 00:20:27.812+07"
30;"2017-06-07 02:03:51.177+07"
29;"2017-06-07 00:20:27.812+07"
28;"2017-06-07 01:45:53.129+07"
27;"2017-06-07 01:58:02.974+07"
</code>```

答:
This is not an answer but this version works

```<code>SELECT t1.contract,close
FROM trading.delayed AS t1,
    (
      SELECT max(id) as id,
             contract,
             max(date) AS date
      FROM trading.delayed
      GROUP BY contract
   ) AS t2
WHERE t1.id =t2.id
order by contract desc;
</code>```

Body:
This query gives duplicates however I am struggling to understand exactly why? I do have many rows per id in trading.delayed but only one with the exact same timestamp

Could someone explain me what I am missing ?

      SELECT t1.contract,t1.date FROM trading.delayed AS t1,
(SELECT contract, max(date) AS date FROM trading.delayed GROUP BY contract) AS t2
WHERE t1.date =t2.date order BY contract DESC;

Results: contract, date

32;"2017-06-07 02:04:11.797+07"
32;"2017-06-07 02:04:14.489+07"
31;"2017-06-07 02:04:12.04+07"
30;"2017-06-07 02:03:54.182+07"
30;"2017-06-07 00:20:27.812+07"
30;"2017-06-07 02:03:51.177+07"
29;"2017-06-07 00:20:27.812+07"
28;"2017-06-07 01:45:53.129+07"
27;"2017-06-07 01:58:02.974+07"

Body:
This is not an answer but this version works

SELECT t1.contract,close
FROM trading.delayed AS t1,
    (
      SELECT max(id) as id,
             contract,
             max(date) AS date
      FROM trading.delayed
      GROUP BY contract
   ) AS t2
WHERE t1.id =t2.id
order by contract desc;


问:
Accurate Pinch Zoom
I'm trying to figure out how to create an accurate pinch zoom for my camera in Unity3D/C#. It must be based on the physical points on the terrain. The image below illustrates the effect I want to achieve.

The Camera is a child of a null which scales (between 0,1 and 1) to "zoom" as not to mess with the perspective of the camera.

So what I've come up with so far is that each finger must use a raycast to get the A & B points as well as the current scale of the camera parent.

EG: A (10,0,2), B (14,0,4), S (0.8,0.8,0.8) >> A (10,0,2), B (14,0,4), S (0.3,0.3,0.3)

The positions of the fingers will change but the hit.point values should remain the same by changing the scale.

BONUS: As a bonus, it would be great to have the camera zoom into a point between the fingers, not just the center.

Thanks so much for any help or reference.

EDIT:
I've come up with this below so far but it's not accurate the way I want. It incorporates some of the ideas I had above and I think that the problem is that it shouldn't be /1000 but an equation including the current scale somehow.

```<code>if (Input.touchCount == 2) {
        if (!CamZoom) {
            CamZoom = true;
            var rayA = Camera.main.ScreenPointToRay (Input.GetTouch (0).position);
            var rayB = Camera.main.ScreenPointToRay (Input.GetTouch (1).position);
            int layerMask = (1 << 8);
            if (Physics.Raycast (rayA, out hit, 1500, layerMask)) {
                PrevA = new Vector3 (hit.point.x, 0, hit.point.z);
                Debug.Log ("PrevA: " + PrevA);
            }
            if (Physics.Raycast (rayB, out hit, 1500, layerMask)) {
                PrevB = new Vector3 (hit.point.x, 0, hit.point.z);
                Debug.Log ("PrevB: " + PrevB);
            }
            PrevDis = Vector3.Distance (PrevB, PrevA);
            Debug.Log ("PrevDis: " + PrevDis);
            PrevScaleV = new Vector3 (PrevScale, PrevScale, PrevScale);
            PrevScale = this.transform.localScale.x;
            Debug.Log ("PrevScale: " + PrevScale);
        }
        if (CamZoom) {
            var rayA = Camera.main.ScreenPointToRay (Input.GetTouch (0).position);
            var rayB = Camera.main.ScreenPointToRay (Input.GetTouch (1).position);
            int layerMask = (1 << 8);
            if (Physics.Raycast (rayA, out hit, 1500, layerMask)) {
                NewA = new Vector3 (hit.point.x, 0, hit.point.z);
            }
            if (Physics.Raycast (rayB, out hit, 1500, layerMask)) {
                NewB = new Vector3 (hit.point.x, 0, hit.point.z);
            }
            DeltaDis = PrevDis - (Vector3.Distance (NewB, NewA));
            Debug.Log ("Delta: " + DeltaDis);
            NewScale = PrevScale + (DeltaDis / 1000);
            Debug.Log ("NewScale: " + NewScale);
            NewScaleV = new Vector3 (NewScale, NewScale, NewScale);
            this.transform.localScale = Vector3.Lerp(PrevScaleV,NewScaleV,Time.deltaTime);
            PrevScaleV = NewScaleV;
            CamAngle();
        }
    }
</code>```

答:
Intro

I had to solve this same problem recently and started off with the same approach as you, which is to think of it as though the user is interacting with the scene and we need to figure out where in the scene their fingers are and how they're moving and then invert those actions to reflect them in our camera.

However, what we're really trying to achieve is much simpler.  We simply want the to user feel like the area of the screen that they are pinching changes size with the same ratio as their pinch changes.

Aim

First let's summarise our goal and constraints:

Goal: When a user pinches, the pinched area should appear to scale to match the pinch.

Constraint: We do not want to change the scale of any objects.

Constraint: Our camera is a perspective camera.

Constraint: We do not want to change the field of view on the camera.

Constraint: Our solution should be resolution/device independent.

With all that in mind, and given that we know that with a perspective camera objects appear larger when they're closer and smaller when they're further, it seems that the only solution for scaling what the user sees is to move the camera in/out from the scene.

Solution

In order to make the scene look larger at our focal point, we need to position the camera so that a cross-section of the camera's frustum at the focal point is equivalently smaller.

Here's a diagram to better explain:

The top half of the image is the "illusion" we want to achieve of making the area the user expands twice as big on screen.  The bottom half of the image is how we need to move the camera to position the frustum in a way that gives that impression.

The question then becomes how far do I move the camera to achieve the desired cross-section?

For this we can take advantage of the relationship between the frustum's height h at a distance d from the camera when the camera's field of view angle in degrees is θ.

Since our field of view angle θ is constant per our agreed constraints, we can see that h and d are linearly proportional.

This is useful to know because it means that any multiplication/division of h is equally reflected in d.  Meaning we can just apply our multipliers directly to the distance, no extra calculation to convert height to distance required!

Implementation

So we finally get to the code.

First, we take the user's desired size change as a multiple of the previous distance between their fingers:

```<code>Touch touch0 = Input.GetTouch(0);
Touch touch1 = Input.GetTouch(1);
Vector2 prevTouchPosition0 = touch0.position - touch0.deltaPosition;
Vector2 prevTouchPosition1 = touch1.position - touch1.deltaPosition;
float touchDistance = (touch1.position - touch0.position).magnitude;
float prevTouchDistance = (prevTouchPosition1 - prevTouchPosition1).magnitude;
float touchChangeMultiplier = touchDistance / prevTouchDistance;
</code>```

Now we know by how much the user wants to scale the area they're pinching, we can scale the camera's distance from its focal point by the opposite amount.

The focal point is the intersection of the camera's forward ray and the thing you're zooming in on.  For the sake of a simple example, I'll just be using the origin as my focal point.

```<code>Vector3 focalPoint = Vector3.zero;
Vector3 direction = camera.transform.position - focalPoint;
float newDistance = direction.magnitude / touchChangeMultiplier;
camera.transform.position = newDistance * direction.normalized;
camera.transform.LookAt(focalPoint);
</code>```

That's all there is to it.

Bonus

This answer is already very long.  So to briefly answer your question about making the camera focus on where you're pinching:

When you first detect a 2 finger touch, store the screen position and related world position.

When zooming, move the camera to put the world position back at the same screen position.

Title: Accurate Pinch Zoom

Body:
I'm trying to figure out how to create an accurate pinch zoom for my camera in Unity3D/C#. It must be based on the physical points on the terrain. The image below illustrates the effect I want to achieve.

The Camera is a child of a null which scales (between 0,1 and 1) to "zoom" as not to mess with the perspective of the camera.

So what I've come up with so far is that each finger must use a raycast to get the A & B points as well as the current scale of the camera parent.

EG: A (10,0,2), B (14,0,4), S (0.8,0.8,0.8) >> A (10,0,2), B (14,0,4), S (0.3,0.3,0.3)

The positions of the fingers will change but the hit.point values should remain the same by changing the scale.

BONUS: As a bonus, it would be great to have the camera zoom into a point between the fingers, not just the center.

Thanks so much for any help or reference.

EDIT:
I've come up with this below so far but it's not accurate the way I want. It incorporates some of the ideas I had above and I think that the problem is that it shouldn't be /1000 but an equation including the current scale somehow.

if (Input.touchCount == 2) {
        if (!CamZoom) {
            CamZoom = true;
            var rayA = Camera.main.ScreenPointToRay (Input.GetTouch (0).position);
            var rayB = Camera.main.ScreenPointToRay (Input.GetTouch (1).position);
            int layerMask = (1 << 8);
            if (Physics.Raycast (rayA, out hit, 1500, layerMask)) {
                PrevA = new Vector3 (hit.point.x, 0, hit.point.z);
                Debug.Log ("PrevA: " + PrevA);
            }
            if (Physics.Raycast (rayB, out hit, 1500, layerMask)) {
                PrevB = new Vector3 (hit.point.x, 0, hit.point.z);
                Debug.Log ("PrevB: " + PrevB);
            }
            PrevDis = Vector3.Distance (PrevB, PrevA);
            Debug.Log ("PrevDis: " + PrevDis);
            PrevScaleV = new Vector3 (PrevScale, PrevScale, PrevScale);
            PrevScale = this.transform.localScale.x;
            Debug.Log ("PrevScale: " + PrevScale);
        }
        if (CamZoom) {
            var rayA = Camera.main.ScreenPointToRay (Input.GetTouch (0).position);
            var rayB = Camera.main.ScreenPointToRay (Input.GetTouch (1).position);
            int layerMask = (1 << 8);
            if (Physics.Raycast (rayA, out hit, 1500, layerMask)) {
                NewA = new Vector3 (hit.point.x, 0, hit.point.z);
            }
            if (Physics.Raycast (rayB, out hit, 1500, layerMask)) {
                NewB = new Vector3 (hit.point.x, 0, hit.point.z);
            }
            DeltaDis = PrevDis - (Vector3.Distance (NewB, NewA));
            Debug.Log ("Delta: " + DeltaDis);
            NewScale = PrevScale + (DeltaDis / 1000);
            Debug.Log ("NewScale: " + NewScale);
            NewScaleV = new Vector3 (NewScale, NewScale, NewScale);
            this.transform.localScale = Vector3.Lerp(PrevScaleV,NewScaleV,Time.deltaTime);
            PrevScaleV = NewScaleV;
            CamAngle();
        }
    }

Body:
Intro

I had to solve this same problem recently and started off with the same approach as you, which is to think of it as though the user is interacting with the scene and we need to figure out where in the scene their fingers are and how they're moving and then invert those actions to reflect them in our camera.

However, what we're really trying to achieve is much simpler.  We simply want the to user feel like the area of the screen that they are pinching changes size with the same ratio as their pinch changes.

Aim

First let's summarise our goal and constraints:

Goal: When a user pinches, the pinched area should appear to scale to match the pinch.

Constraint: We do not want to change the scale of any objects.

Constraint: Our camera is a perspective camera.

Constraint: We do not want to change the field of view on the camera.

Constraint: Our solution should be resolution/device independent.

With all that in mind, and given that we know that with a perspective camera objects appear larger when they're closer and smaller when they're further, it seems that the only solution for scaling what the user sees is to move the camera in/out from the scene.

Solution

In order to make the scene look larger at our focal point, we need to position the camera so that a cross-section of the camera's frustum at the focal point is equivalently smaller.

Here's a diagram to better explain:

The top half of the image is the "illusion" we want to achieve of making the area the user expands twice as big on screen.  The bottom half of the image is how we need to move the camera to position the frustum in a way that gives that impression.

The question then becomes how far do I move the camera to achieve the desired cross-section?

For this we can take advantage of the relationship between the frustum's height h at a distance d from the camera when the camera's field of view angle in degrees is θ.

Since our field of view angle θ is constant per our agreed constraints, we can see that h and d are linearly proportional.

This is useful to know because it means that any multiplication/division of h is equally reflected in d.  Meaning we can just apply our multipliers directly to the distance, no extra calculation to convert height to distance required!

Implementation

So we finally get to the code.

First, we take the user's desired size change as a multiple of the previous distance between their fingers:

Touch touch0 = Input.GetTouch(0);
Touch touch1 = Input.GetTouch(1);
Vector2 prevTouchPosition0 = touch0.position - touch0.deltaPosition;
Vector2 prevTouchPosition1 = touch1.position - touch1.deltaPosition;
float touchDistance = (touch1.position - touch0.position).magnitude;
float prevTouchDistance = (prevTouchPosition1 - prevTouchPosition1).magnitude;
float touchChangeMultiplier = touchDistance / prevTouchDistance;

Now we know by how much the user wants to scale the area they're pinching, we can scale the camera's distance from its focal point by the opposite amount.

The focal point is the intersection of the camera's forward ray and the thing you're zooming in on.  For the sake of a simple example, I'll just be using the origin as my focal point.

Vector3 focalPoint = Vector3.zero;
Vector3 direction = camera.transform.position - focalPoint;
float newDistance = direction.magnitude / touchChangeMultiplier;
camera.transform.position = newDistance * direction.normalized;
camera.transform.LookAt(focalPoint);

That's all there is to it.

Bonus

This answer is already very long.  So to briefly answer your question about making the camera focus on where you're pinching:

When you first detect a 2 finger touch, store the screen position and related world position.

When zooming, move the camera to put the world position back at the same screen position.


问:
Can you assign a value to a returned object?
I am trying to implement Euclid's algorithm in Python3.
If max(a, b) returns the object with the largest value in (a, b),
why can't you operate on that object like so:

max(a, b) %= min(a, b)

答:
You can't do like this, the function max returns a value, not a variable, what you can do, however is to execute:

```<code>a,b = sorted((a,b))
</code>```

then, after this line, a will always be the greater value (or equal b)

this way you can just do in the line after:

```<code>a%=b
</code>```

Since b will be the min value...

Body:
You can't do like this, the function max returns a value, not a variable, what you can do, however is to execute:

a,b = sorted((a,b))

then, after this line, a will always be the greater value (or equal b)

this way you can just do in the line after:

a%=b

Since b will be the min value...


问:
Remove selected drop down1 value in drop down2 in select2 jquery
I have 5 drop downs in which if i select one value in drop down 1 and that selected value should not be there in remaining drop downs.

Im using select2 dropdown.
Here i have tried this one
    HTML:

      1
      2
      3
      4
      5

```<code><select class="select2" id="select2">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<select class="select2" id="select3">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<select class="select2" id="select4">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<select class="select2" id="select5">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

jQuery:

$("select").on("select2:select", function (evt) {
    var element = evt.params.data.element;
    var $element = $(element);
    $element.detach();
    $(this).append($element);
    $('.#merchant_referral_customer_gms_id2').trigger("change");
});
</code>```

This one removing option in self dropdown not in others.

Can  any one please help out.

答:
Your script does not have the required functionality I have tried and made seleted option as disabled in rest of select's please check at following link</p>

```<code>codepen.io/jainaman23/pen/zzvGpL
</code>```

Body:
I have 5 drop downs in which if i select one value in drop down 1 and that selected value should not be there in remaining drop downs.

Im using select2 dropdown.
Here i have tried this one
    HTML:

      1
      2
      3
      4
      5

<select class="select2" id="select2">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<select class="select2" id="select3">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<select class="select2" id="select4">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<select class="select2" id="select5">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

jQuery:

$("select").on("select2:select", function (evt) {
    var element = evt.params.data.element;
    var $element = $(element);
    $element.detach();
    $(this).append($element);
    $('.#merchant_referral_customer_gms_id2').trigger("change");
});

This one removing option in self dropdown not in others.

Can  any one please help out.

Body:
Your script does not have the required functionality I have tried and made seleted option as disabled in rest of select's please check at following link

codepen.io/jainaman23/pen/zzvGpL


问:
Generate a random point on a rectangle's perimeter with uniform distribution
Given any particular rectangle (x1,y1)-(x2,y2), how can I generate a random point on its perimeter?

I've come up with a few approaches, but it seems like there ought to be a pretty canonical way to do it.

First, I thought I'd generate a random point within the rectangle and clamp it to the closest side, but the distribution didn't seem uniform (points almost never fell on the shorter sides). Second, I picked a side at random and then chose a random point on that side. The code was kind of clunky and it wasn't uniform either - but in the exact opposite way (short sides had the same chance of getting points as long sides). Finally, I've been thinking about "unfolding" the rectangle into a single line and picking a random point on the line. I think that would generate a uniform distribution, but I thought I'd ask here before embarking down that road.

答:
Figured I would try to do this without branching, expressing both X and Y coords as a function of the random number that walks the "unfolded" rectangle.

JS:

```<code>function randomOnRect() {
    let r = Math.random();
    return [Math.min(1, Math.max(0, Math.abs((r * 4 - .5) % 4 - 2) - .5)),
            Math.min(1, Math.max(0, Math.abs((r * 4 + .5) % 4 - 2) - .5))]
}
</code>```

Body:
Figured I would try to do this without branching, expressing both X and Y coords as a function of the random number that walks the "unfolded" rectangle.

JS:

function randomOnRect() {
    let r = Math.random();
    return [Math.min(1, Math.max(0, Math.abs((r * 4 - .5) % 4 - 2) - .5)),
            Math.min(1, Math.max(0, Math.abs((r * 4 + .5) % 4 - 2) - .5))]
}


问:
PHP- Unable to Access Data from DB in dropdown menu
I am trying to create a drop down menu that will display Project Names off all Projects present in  the table Project in the database Testing... The drop down is created but it is not accessing the database and retrieving the required data...
The code is as follows:

```<code><html>
<head>
<title>Dynamic Drop Down List</title>
</head>

    <form id="form1" name="form1" method="post" action="<?php echo $PHP_SELF; ?>">
        Project List :
        <select Project Name='NEW'>
        <option value="">--- Select ---</option>
        <?
            $serverName = "Swagatha-PC";
            $connectionInfo = array( "Database"=>"Testing");
            $conn = sqlsrv_connect( $serverName, $connectionInfo);

            if( $conn )
            {
            echo "Connection established.<br />";
            }
            else
            {
            echo "Connection could not be established.<br />";
            die( print_r( sqlsrv_errors(), true));
            }
            if (isset ($select)&&$select!="")
            {
            $select=$_POST ['NEW'];
        }
        ?>
        <?
            $query=mysql_query("select ProjectName from dbo.Project");
            $menu=" ";
            while($row = sqlsrv_fetch_array($query))
            {
               $menu ="<option>" . $row["ProjectName"] . "</option>";
            }

            ?>
        </select>
        <input type="submit" name="Next" value="Select" />
    </form>
</body>
</html>
</code>```

Dropdown Error

What Do i do to fix this??

答:
Here is you fixed code. You can try it</p>

```<code><html>
<head>
<title>Dynamic Drop Down List</title>
</head>

    <form id="form1" name="form1" method="post" action="<?php echo $PHP_SELF; ?>">
        Project List :
        <select Project Name='NEW'>
        <option value="">--- Select ---</option>
        <?php
            $serverName = "Swagatha-PC";
            $connectionInfo = array( "Database"=>"Testing");
            $conn = sqlsrv_connect( $serverName, $connectionInfo);

            if( $conn )
            {
            echo "Connection established.<br />";
            }
            else
            {
            echo "Connection could not be established.<br />";
            die( print_r( sqlsrv_errors(), true));
            }
            if (isset ($select)&&$select!="")
            {
            $select=$_POST ['NEW'];
        }

            $query=sqlsrv_query("select ProjectName from dbo.Project");
            $menu=" ";
            while($row = sqlsrv_fetch_array($query))
            {
               echo "<option>" . $row["ProjectName"] . "</option>";
            }

            ?>
        </select>
        <input type="submit" name="Next" value="Select" />
    </form>
</body>
</html>
</code>```

Body:
I am trying to create a drop down menu that will display Project Names off all Projects present in  the table Project in the database Testing... The drop down is created but it is not accessing the database and retrieving the required data...
The code is as follows:

<title>Dynamic Drop Down List</title>

    <form id="form1" name="form1" method="post" action="<?php echo $PHP_SELF; ?>">
        Project List :
        <select Project Name='NEW'>
        <option value="">--- Select ---</option>
        <?
            $serverName = "Swagatha-PC";
            $connectionInfo = array( "Database"=>"Testing");
            $conn = sqlsrv_connect( $serverName, $connectionInfo);

            if( $conn )
            {
            echo "Connection established.
";
            }
            else
            {
            echo "Connection could not be established.
";
            die( print_r( sqlsrv_errors(), true));
            }
            if (isset ($select)&&$select!="")
            {
            $select=$_POST ['NEW'];
        }
        ?>
        <?
            $query=mysql_query("select ProjectName from dbo.Project");
            $menu=" ";
            while($row = sqlsrv_fetch_array($query))
            {
               $menu ="<option>" . $row["ProjectName"] . "</option>";
            }

            ?>
        </select>
        <input type="submit" name="Next" value="Select" />
    </form>

Dropdown Error

What Do i do to fix this??

Body:
Here is you fixed code. You can try it

<html>
<head>
<title>Dynamic Drop Down List</title>
</head>

    <form id="form1" name="form1" method="post" action="<?php echo $PHP_SELF; ?>">
        Project List :
        <select Project Name='NEW'>
        <option value="">--- Select ---</option>
        <?php
            $serverName = "Swagatha-PC";
            $connectionInfo = array( "Database"=>"Testing");
            $conn = sqlsrv_connect( $serverName, $connectionInfo);

            if( $conn )
            {
            echo "Connection established.<br />";
            }
            else
            {
            echo "Connection could not be established.<br />";
            die( print_r( sqlsrv_errors(), true));
            }
            if (isset ($select)&&$select!="")
            {
            $select=$_POST ['NEW'];
        }

            $query=sqlsrv_query("select ProjectName from dbo.Project");
            $menu=" ";
            while($row = sqlsrv_fetch_array($query))
            {
               echo "<option>" . $row["ProjectName"] . "</option>";
            }

            ?>
        </select>
        <input type="submit" name="Next" value="Select" />
    </form>
</body>
</html>


问:
Android Layout with height in percent
I want to make layout like that:

But I don't know how to make panel 2 and 3 filling remaining space (after adding fixed size panel 1) in 50:50 ratio. There must be something I am missing or just don't know about Android layout, but what is it?

I forgot to mention that I want to use Constraint Layout for these panels. I use Android Studio.

答:
```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<RelativeLayout
    android:id="@+id/panel1Layout"
    android:layout_width="match_parent"
    android:layout_height="100dp" />

<LinearLayout
    android:id="@+id/otherPanelContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/panel1Layout"
    android:orientation="vertical"
    android:weightSum="2">

    <RelativeLayout
        android:id="@+id/panel2Layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <RelativeLayout
        android:id="@+id/panel3Layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>
</code>```

Title: Android Layout with height in percent


问:
PHP and mpdf - Failed to load PDF in Chrome if charset_in='UTF-8'
I'm using mpdf to generate a pdf, and the way a did is something like this:

```<code>    header('Content-Type: application/pdf; charset=UTF-8');
    header('Content-Transfer-Encoding: binary');
    header('Accept-Ranges: bytes');
    define('MPDF_PATH', '../mpdf/');
    require(MPDF_PATH.'mpdf.php');
    require("../cnxdb.inc.php");
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    // some stuff to populate &html
    $html = is_utf8($html);
    $file_name = $title.'.pdf';
    ob_clean();
    $mpdf=new mPDF();
    $mpdf->SetTitle($title);
    $mpdf->setFooter($footer);
    $mpdf->allow_charset_conversion=true;
    $mpdf->charset_in='UTF-8';
    $mpdf->WriteHTML($html);
    header('Content-Disposition: attachment; filename="'.$file_name.'"');
    $mpdf->list_indent_first_level = 0;
    $mpdf->Output($file_name, 'I');
    $mpdf->debug = true;
</code>```

But if I change the line $mpdf->charset_in='UTF-8' to $mpdf->charset_in='windows-1252' it prints the PDF, but some letters get scrambled, like ç, á, ó, ...
And this code works perfectly in Firefox, so it must be something to Chrome.
Does anyone know a solution to this? Or Chrome just don't go with PDFs with UTF-8?

Any extra info just ask me,
Thanks!

答:
So, it happens I am dumb and the charset has nothing to do to Chrome not loading.
The real problem was the  $htmlis line $mpdf->WriteHTML($html); had style in it, so Chrome gets crazy, but firefox was okay with it.
The solution is to separate style and html body:

```<code>$mpdf->WriteHTML($style, 1); // 1 is for stylesheet
$mpdf->WriteHTML($html, 2); // 2 is for html body
</code>```

Good luck!

Body:
I'm using mpdf to generate a pdf, and the way a did is something like this:

    header('Content-Type: application/pdf; charset=UTF-8');
    header('Content-Transfer-Encoding: binary');
    header('Accept-Ranges: bytes');
    define('MPDF_PATH', '../mpdf/');
    require(MPDF_PATH.'mpdf.php');
    require("../cnxdb.inc.php");
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    // some stuff to populate &html
    $html = is_utf8($html);
    $file_name = $title.'.pdf';
    ob_clean();
    $mpdf=new mPDF();
    $mpdf->SetTitle($title);
    $mpdf->setFooter($footer);
    $mpdf->allow_charset_conversion=true;
    $mpdf->charset_in='UTF-8';
    $mpdf->WriteHTML($html);
    header('Content-Disposition: attachment; filename="'.$file_name.'"');
    $mpdf->list_indent_first_level = 0;
    $mpdf->Output($file_name, 'I');
    $mpdf->debug = true;

But if I change the line $mpdf->charset_in='UTF-8' to $mpdf->charset_in='windows-1252' it prints the PDF, but some letters get scrambled, like ç, á, ó, ...
And this code works perfectly in Firefox, so it must be something to Chrome.
Does anyone know a solution to this? Or Chrome just don't go with PDFs with UTF-8?

Any extra info just ask me,
Thanks!

Body:
So, it happens I am dumb and the charset has nothing to do to Chrome not loading.
The real problem was the  $htmlis line $mpdf->WriteHTML($html); had style in it, so Chrome gets crazy, but firefox was okay with it.
The solution is to separate style and html body:

$mpdf->WriteHTML($style, 1); // 1 is for stylesheet
$mpdf->WriteHTML($html, 2); // 2 is for html body

Good luck!


问:
Excel-VBA: run increments in same column depending on neighbouring column
it's sounds tricky and it is!

I have an example. I am trying to fill out the red values automatically

As you can see, column A and column B make a tuple and these tuples need to get incremented numbers.

While coding I feel like I am running out of functions to do this. I would be glad for hints, about even how to approach this problem the best!

Thank you!

答:
Use COUNTIFS()

Put this in C1:

```<code>=COUNTIFS($A$1:A1,A1,$B$1:B1,B1)
</code>```

Then copy down

Body:
Use COUNTIFS()

Put this in C1:

=COUNTIFS($A$1:A1,A1,$B$1:B1,B1)

Then copy down


问:
Gtk - draw event fired for wrong widget, and widget not redrawn
I'm trying to create a custom scrollable text area. I created a DrawingArea and a ScrollBar inside a Grid. I have attached the draw event of DrawingArea to this.on_draw method which simply looks at ScrollBar's value and moves the Cairo.Context appropriately before drawing the Pango.Layout.

The first problem is that this.on_draw is getting invoked whenever the ScrollBar is touched even though I have not registered any events with ScrollBar. How do I prevent this, or check this?

The second problem is that even though this.on_draw is invoked, the changes made to the Context is not displayed unless the ScrollBar value is near 0 or 100 (100 is the upper value of Adjustment). Why is this happening?

I did find out that if I connect the value_changed event of ScrollBar to a method that calls queue_redraw of DrawingArea, it would invoke this.on_draw and display it properly after it. But due to the second problem, I think this.on_draw is getting invoked too many times unnecessarily. So, what is the "proper" way of accomplishing this?

```<code>using Cairo;
using Gdk;
using Gtk;
using Pango;

public class Texter : Gtk.Window {
    private Gtk.DrawingArea darea;
    private Gtk.Scrollbar scroll;

    private string text = "Hello\nWorld!";

    public Texter () {
        GLib.Object (type: Gtk.WindowType.TOPLEVEL);

        Gtk.Grid grid = new Gtk.Grid();
        this.add (grid);

        var drawing_area = new Gtk.DrawingArea ();
        drawing_area.set_size_request (200, 200);
        drawing_area.expand = true;
        drawing_area.draw.connect (this.on_draw);

        grid.attach (drawing_area, 0, 0);

        var scrollbar = new Gtk.Scrollbar (Gtk.Orientation.VERTICAL,
                                           new Gtk.Adjustment(0, 0, 100, 0, 0, 1));

        grid.attach (scrollbar, 1, 0);

        this.darea = drawing_area;
        this.scroll = scrollbar;

        this.destroy.connect (Gtk.main_quit);
    }

    private bool on_draw (Gtk.Widget sender, Cairo.Context ctx) {
        ctx.set_source_rgb (0.9, 0.9, 0.9);
        ctx.paint ();

        var y_offset = this.scroll.get_value();
        stdout.printf("%f\n", y_offset);

        ctx.set_source_rgb (0.25, 0.25, 0.25);
        ctx.move_to(0, 100 - y_offset);

        var layout = Pango.cairo_create_layout(ctx);
        layout.set_font_description(Pango.FontDescription.from_string("Sans 12"));
        layout.set_auto_dir(false);
        layout.set_text(this.text, this.text.length);
        Pango.cairo_show_layout(ctx, layout);

        return false;
    }

    static int main (string[] args) {
        Gtk.init (ref args);

        var window = new Texter ();
        window.show_all ();

        Gtk.main ();

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

Also, please point out any (possibly unrelated) mistake if you find one in the above code.

答:
The part that you are missing is that a draw signal does not mean "redraw everything". Instead, GTK+ sets the clip region of the cairo context to the part that needs to be redrawn, so everything else you do doesn't have any effect. The cairo function cairo_clip_extents() will tell you what that region is. The queue_draw_area() method on GtkWidget will allow you to explicitly mark a certain area for drawing, instead of the entire widget.

But your approach to scrollbars is wrong anyway: you're trying to build the entire infrastructure from scratch! Consider using a GtkScrolledWindow instead. This automatically takes care of all the details of scrolling for you, and will give you the overlay scrollbars I mentioned. All you need to do is set the size of the GtkDrawingArea to the size you want it to be, and GtkScrolledWindow will do the rest. The best way to do this is to subclass GtkDrawingArea and override the get_preferred_height() and/or get_preferred_width() virtual functions (being sure to set both minimum and natural sizes to the sizes you want for that particular dimension). If you ever need to change this size later, call the queue_resize() method of GtkWidget. (You probably could get away with just using set_size_request(), but what I described is the preferred way of doing this.) Doing this also gives you the advantage of not having to worry about transforming your cairo coordinates; GtkScrolledWindow does this for you.

Body:
I'm trying to create a custom scrollable text area. I created a DrawingArea and a ScrollBar inside a Grid. I have attached the draw event of DrawingArea to this.on_draw method which simply looks at ScrollBar's value and moves the Cairo.Context appropriately before drawing the Pango.Layout.

The first problem is that this.on_draw is getting invoked whenever the ScrollBar is touched even though I have not registered any events with ScrollBar. How do I prevent this, or check this?

The second problem is that even though this.on_draw is invoked, the changes made to the Context is not displayed unless the ScrollBar value is near 0 or 100 (100 is the upper value of Adjustment). Why is this happening?

I did find out that if I connect the value_changed event of ScrollBar to a method that calls queue_redraw of DrawingArea, it would invoke this.on_draw and display it properly after it. But due to the second problem, I think this.on_draw is getting invoked too many times unnecessarily. So, what is the "proper" way of accomplishing this?

using Cairo;
using Gdk;
using Gtk;
using Pango;

public class Texter : Gtk.Window {
    private Gtk.DrawingArea darea;
    private Gtk.Scrollbar scroll;

    private string text = "Hello\nWorld!";

    public Texter () {
        GLib.Object (type: Gtk.WindowType.TOPLEVEL);

        Gtk.Grid grid = new Gtk.Grid();
        this.add (grid);

        var drawing_area = new Gtk.DrawingArea ();
        drawing_area.set_size_request (200, 200);
        drawing_area.expand = true;
        drawing_area.draw.connect (this.on_draw);

        grid.attach (drawing_area, 0, 0);

        var scrollbar = new Gtk.Scrollbar (Gtk.Orientation.VERTICAL,
                                           new Gtk.Adjustment(0, 0, 100, 0, 0, 1));

        grid.attach (scrollbar, 1, 0);

        this.darea = drawing_area;
        this.scroll = scrollbar;

        this.destroy.connect (Gtk.main_quit);
    }

    private bool on_draw (Gtk.Widget sender, Cairo.Context ctx) {
        ctx.set_source_rgb (0.9, 0.9, 0.9);
        ctx.paint ();

        var y_offset = this.scroll.get_value();
        stdout.printf("%f\n", y_offset);

        ctx.set_source_rgb (0.25, 0.25, 0.25);
        ctx.move_to(0, 100 - y_offset);

        var layout = Pango.cairo_create_layout(ctx);
        layout.set_font_description(Pango.FontDescription.from_string("Sans 12"));
        layout.set_auto_dir(false);
        layout.set_text(this.text, this.text.length);
        Pango.cairo_show_layout(ctx, layout);

        return false;
    }

    static int main (string[] args) {
        Gtk.init (ref args);

        var window = new Texter ();
        window.show_all ();

        Gtk.main ();

        return 0;
    }
}

Also, please point out any (possibly unrelated) mistake if you find one in the above code.


问:
JavaScript new Date Ordinal (st, nd, rd, th)
If at all possible, without JavaScript libraries or lots of clunky code I am looking for the simplest way to format a date two weeks from now in the following format:

13th March 2013

The code I am using is:

```<code>var newdate = new Date(+new Date + 12096e5);
document.body.innerHTML = newdate;
</code>```

which returns the date and time two weeks from now, but like this:
Wed Mar 27 2013 21:50:29 GMT+0000 (GMT Standard Time)

Here is the code in jsFiddle.

Any help would be appreciated!

答:
Here is a one liner inspired by the other answers. It is tested and will take 0 and negative numbers.

```<code>function getOrdinalNum(n) {
  return n + (n > 0 ? ['th', 'st', 'nd', 'rd'][(n > 3 && n < 21) || n % 10 > 3 ? 0 : n % 10] : '');
}
</code>```

Update 2020-06-23. The following is a better readable answer of the function above:

```<code>const getOrdinalNum = (number) => {
  let selector;

  if (number <= 0) {
    selector = 4;
  } else if ((number > 3 && number < 21) || number % 10 > 3) {
    selector = 0;
  } else {
    selector = number % 10;
  }

  return number + ['th', 'st', 'nd', 'rd', ''][selector];
};

</code>```

Body:
If at all possible, without JavaScript libraries or lots of clunky code I am looking for the simplest way to format a date two weeks from now in the following format:

13th March 2013

The code I am using is:

var newdate = new Date(+new Date + 12096e5);
document.body.innerHTML = newdate;

which returns the date and time two weeks from now, but like this:
Wed Mar 27 2013 21:50:29 GMT+0000 (GMT Standard Time)

Here is the code in jsFiddle.

Any help would be appreciated!

Body:
Here is a one liner inspired by the other answers. It is tested and will take 0 and negative numbers.

function getOrdinalNum(n) {
  return n + (n > 0 ? ['th', 'st', 'nd', 'rd'][(n > 3 && n < 21) || n % 10 > 3 ? 0 : n % 10] : '');
}

Update 2020-06-23. The following is a better readable answer of the function above:

const getOrdinalNum = (number) => {
  let selector;

  if (number <= 0) {
    selector = 4;
  } else if ((number > 3 && number < 21) || number % 10 > 3) {
    selector = 0;
  } else {
    selector = number % 10;
  }

  return number + ['th', 'st', 'nd', 'rd', ''][selector];
};


问:
Python return if not statement explanation
I couldn't understand this example:

```<code>def mysum(L):
 first, *rest = L
 return first if not rest else first + mysum(rest)
</code>```

I supposed that the statement means that first != rest, so it must returns first, but it returns first + mysum(rest).
Can you explain why?
TIA

答:
If you don't understand the ternary, re-write it.

```<code>if not rest:
    return first
else:
    return first + mysum(rest)
</code>```

In words, if there is nothing left, return what you have, otherwise return the current element plus the summation of the remaining list.

I supposed that the statement means that first != rest,

Nope. if not rest is the statement, as in

```<code>>>> not []
True
</code>```

Body:
I couldn't understand this example:

def mysum(L):
 first, *rest = L
 return first if not rest else first + mysum(rest)

I supposed that the statement means that first != rest, so it must returns first, but it returns first + mysum(rest).
Can you explain why?
TIA

Body:
If you don't understand the ternary, re-write it.

if not rest:
    return first
else:
    return first + mysum(rest)

In words, if there is nothing left, return what you have, otherwise return the current element plus the summation of the remaining list.

I supposed that the statement means that first != rest,

Nope. if not rest is the statement, as in

>>> not []
True


问:
Python user define Functions
I have read this tutorial for user define python Function.

This tutorial say:

```<code>def sum( arg1, arg2 ):
   total = arg1 + arg2
   return total;

# Now you can call sum Function
total = sum( 10, 20 );
print "Outside the function : ", total
</code>```

In my case I have this python function:

```<code>def myf(arg1):
   .................
   some python progress
   ...................
   return out1,out2,out3,out4,out5,out6
</code>```

And finally I have 6 outputs from my main Function

But if I try to call Function like this tutorial:

```<code>myf = out1(myvar)
</code>```

Then shows all outputs from out1,out2,out4=3,out4,out5,out6 and not specific where I want.

For example my correct output from my Function is:

out1=10,out2=30,out3=300,out4=12,out5=47,out6=77

that myf = out1(myvar) shows me :

```<code>(10,30,300,12,47,77) and not `10` where i want...
</code>```

Any idea how to get only that I need from outputs?

答:
Your function is returning a tuple of values, and this tuple is being assigned to myf.

If you want just the nth value in the tuple, you can refer to it by myf[n].

In your case, you're looking for myf[0].

```<code>>>> print(myf[0])
10
</code>```

Title: Python user define Functions

Body:
I have read this tutorial for user define python Function.

This tutorial say:

def sum( arg1, arg2 ):
   total = arg1 + arg2
   return total;

# Now you can call sum Function
total = sum( 10, 20 );
print "Outside the function : ", total

In my case I have this python function:

def myf(arg1):
   .................
   some python progress
   ...................
   return out1,out2,out3,out4,out5,out6

And finally I have 6 outputs from my main Function

But if I try to call Function like this tutorial:

myf = out1(myvar)

Then shows all outputs from out1,out2,out4=3,out4,out5,out6 and not specific where I want.

For example my correct output from my Function is:

out1=10,out2=30,out3=300,out4=12,out5=47,out6=77

that myf = out1(myvar) shows me :

(10,30,300,12,47,77) and not `10` where i want...

Any idea how to get only that I need from outputs?

Body:
Your function is returning a tuple of values, and this tuple is being assigned to myf.

If you want just the nth value in the tuple, you can refer to it by myf[n].

In your case, you're looking for myf[0].

>>> print(myf[0])
10


问:
Hibernate throws HibernateQueryException: could not resolve property
So I have a table that I've defined as an entity in hibernate like this:

```<code>@Entity
@Table(name = "sec_Preference")
public class Preference {
private long id;

@Column(name = "PreferenceId", nullable = false, insertable = true, updatable = true, length = 19, precision = 0)
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
public long getId() {
    return id;
}

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

private long systemuserid;

@Column(name = "SystemUserId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getSystemUserId() {
    return systemuserid;
}

public void setSystemUserId(long systemuserid) {
    this.systemuserid = systemuserid;
}

private long dbgroupid;

@Column(name = "DBGroupId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getDBGroupId() {
    return dbgroupid;
}

public void setDBGroupId(long dbgroupid) {
    this.dbgroupid = dbgroupid;
}

private long externalgroupid;

@Column(name = "ExternalGroupId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getExternalGroupId() {
    return externalgroupid;
}

public void setExternalGroupId(long externalgroupid) {
    this.externalgroupid = externalgroupid;
}

private long securityroleid;

@Column(name = "SecurityRoleId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getSecurityRoleId() {
    return securityroleid;
}

public void setSecurityRoleId(long securityroleid) {
    this.securityroleid = securityroleid;
}

public void setEnum(com.vitalimages.common.server.security.Preference pref) {
    this.preferencekey = pref.name();
}

private String preferencekey;

@Column(name = "PreferenceKey", nullable = false, insertable = true, updatable = true, length = 255, precision = 0)
@Basic
public String getKey() {
    return preferencekey;
}

public void setKey(String key) {
    this.preferencekey = key;
}

private String preferencevalue;

@Column(name = "PreferenceValue", nullable = true, insertable = true, updatable = true, length = 255, precision = 0)
@Basic
public String getValue() {
    return preferencevalue;
}

public void setValue(String value) {
    this.preferencevalue = value;
}

}
</code>```

When I tried to write a simple query against this table:

```<code>public Collection<Preference> getPreferencesForDBGroup(long dbgroupId) {
    final DetachedCriteria criteria = DetachedCriteria.forClass(Preference.class)
            .add(Restrictions.eq("dbgroupid", dbgroupId))
            .setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);

    return getHibernateTemplate().findByCriteria(criteria);
}
</code>```

I got the following error:

```<code>org.springframework.orm.hibernate3.HibernateQueryException: could not resolve property: dbgroupid of: com.common.server.domain.sec.Preference; nested exception is org.hibernate.QueryException: could not resolve property: dbgroupid of: com.common.server.domain.sec.Preference
</code>```

Why can't hibernate figure out what dbgroupid is on my class?

答: Maybe because You've labelled it "DBGroupId", and not "dbgroupid"?</p>

ContentLicense: CC BY-SA 2.5

Body:
So I have a table that I've defined as an entity in hibernate like this:

@Entity
@Table(name = "sec_Preference")
public class Preference {
private long id;

@Column(name = "PreferenceId", nullable = false, insertable = true, updatable = true, length = 19, precision = 0)
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
public long getId() {
    return id;
}

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

private long systemuserid;

@Column(name = "SystemUserId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getSystemUserId() {
    return systemuserid;
}

public void setSystemUserId(long systemuserid) {
    this.systemuserid = systemuserid;
}

private long dbgroupid;

@Column(name = "DBGroupId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getDBGroupId() {
    return dbgroupid;
}

public void setDBGroupId(long dbgroupid) {
    this.dbgroupid = dbgroupid;
}

private long externalgroupid;

@Column(name = "ExternalGroupId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getExternalGroupId() {
    return externalgroupid;
}

public void setExternalGroupId(long externalgroupid) {
    this.externalgroupid = externalgroupid;
}

private long securityroleid;

@Column(name = "SecurityRoleId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getSecurityRoleId() {
    return securityroleid;
}

public void setSecurityRoleId(long securityroleid) {
    this.securityroleid = securityroleid;
}

public void setEnum(com.vitalimages.common.server.security.Preference pref) {
    this.preferencekey = pref.name();
}

private String preferencekey;

@Column(name = "PreferenceKey", nullable = false, insertable = true, updatable = true, length = 255, precision = 0)
@Basic
public String getKey() {
    return preferencekey;
}

public void setKey(String key) {
    this.preferencekey = key;
}

private String preferencevalue;

@Column(name = "PreferenceValue", nullable = true, insertable = true, updatable = true, length = 255, precision = 0)
@Basic
public String getValue() {
    return preferencevalue;
}

public void setValue(String value) {
    this.preferencevalue = value;
}

}

When I tried to write a simple query against this table:

public Collection<Preference> getPreferencesForDBGroup(long dbgroupId) {
    final DetachedCriteria criteria = DetachedCriteria.forClass(Preference.class)
            .add(Restrictions.eq("dbgroupid", dbgroupId))
            .setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);

    return getHibernateTemplate().findByCriteria(criteria);
}

I got the following error:

org.springframework.orm.hibernate3.HibernateQueryException: could not resolve property: dbgroupid of: com.common.server.domain.sec.Preference; nested exception is org.hibernate.QueryException: could not resolve property: dbgroupid of: com.common.server.domain.sec.Preference

Why can't hibernate figure out what dbgroupid is on my class?


问:
Send push notification from web server to a desktop software (Windows)
This is a theoretical question. I first need help to know (understand) how to achieve my needs, so I can use the right keywords in a new research. Btw, sorry about my english, it is not my native language.

Well, I have a desktop (Windows) software created with Delphi and I'd like to allow users to change it configuration remotely, by a web page (PHP) or maybe using another software module (in a different place/lan/wan). E.g.: the user logs in my website, disable some checkbox, save and automatically the software installed in his computer updates itself. The main issue here is how to stabilish the communication (webserver -> desktop software), not the configuration.

Few days ago I heard about Android push notifications (Firebase Cloud Messaging) and think this is exacly what I need. So was wondering if there is something similar that I can use with Delphi and desktop softwares, but found nothing in Google.

Please, can someone help me? Thank you!

答: I think the simpliest way is to create an ini-file. You can configure the ini-file in your web-application and when the user starts your program it looks for an new ini-file, load it and use it. To manipulate your exe-file is maybe a bad idea, because of anti virus software which will block such activities.</p>


问:
How to get hostname call my API
Eg: website abc.com access my REST API  by link xyz.com/rest/api/order/new
. In my function, how can I get hostname abc.com?

I want to check the token is matched with the hostname that is saved in the database.

答:
use $_SERVER['REMOTE_HOST'] for get host name.

```<code>print_r($_SERVER);
</code>```

then you will see all output

or use

```<code>$hostname = gethostname();
</code>```

or use

```<code> $_SERVER['HTTP_HOST']
</code>```

or if you want something else then

```<code>print_r($_SERVER);
</code>```

then check data and use your require data

for more information

http://php.net/manual/en/reserved.variables.server.php

Title: How to get hostname call my API

Body:
use $_SERVER['REMOTE_HOST'] for get host name.

print_r($_SERVER);

then you will see all output

or use

$hostname = gethostname();

or use

 $_SERVER['HTTP_HOST']

or if you want something else then

print_r($_SERVER);

then check data and use your require data

for more information

http://php.net/manual/en/reserved.variables.server.php


问:
Alfresco - Want to Change Content store path
I want to change the existing content store path of my Alfresco instance just because it is about to get full. One solution is to move existing content store at another location and change the path in alfresco.global.properties but I want to write new data at another location and read the existing from the current one.</p>

答:
You can't edit the "dir root" property because that folder contains files needed for a proper Alfresco boot up. However, you can use the Alfresco "content store" feature to simply add any number of additional stores.

Read up on content stores.

http://docs.alfresco.com/5.1/concepts/store-manage-content.html

http://docs.alfresco.com/4.1/concepts/store-config-fullexample.html

I just now see that Krutik used the same links as I did, sorry about that. If you're using CE you can still use/add your own content stores. The feature missing is the OOTB "content store selector" where you would choose the concrete content store by setting a property/aspect on a specific node.