text:
Q: Return a specific word in a string of multiple words in java public class test{

     //my words
        private static String[] words = {"apple", "banana", "cat", "dog", "elf", "frog" };

    public static void main(String[] args) {
       int randomWord = (int) (Random() * words.length);

        System.out.println(randomWord);

    }//end string
}//end class

I just start a project and all i want to know is how to return a specific word while still having it be random. At the moment it just prints/returns the number of the position in the string. For example i want it to return "cat" and if it does the print "" for every letter in cat. I already have the code to print the "" for every letter i just need to get the word back instead of an int.

A: Instantiate Random:
Random random = new Random();

Use it to get a random number*:
int randomNumber = random.nextInt(words.length);

Print index of said random number:
System.out.println(words[randomNumber]);

*Note that normally you use something like random.nextInt(max - min + 1) + min but because your min is 0 and because of 0-based array indexes, you can just use words.length in this example


text:
Q: Bash: /gradlew: No such file or directory (Windows) I'm trying to compile a Springboot application on Amazon AWS:
https://aws.amazon.com/blogs/devops/deploying-a-spring-boot-application-on-aws-using-aws-elastic-beanstalk/
When I try to package the application with Gradle in GitBash I get the following error message:
$ ./gradlew bootRepackage
bash: /gradlew: No such file or directory

I'm using Windows. I tried git config core.autocrlf false as suggested here: Error with gradlew: /usr/bin/env: bash: No such file or directory. I still have the same issue. What am I missing?

A: Try it with ./gradlew bootRepackage

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accessing files containing whitespace from a zip Static Resource in Apex There is a known issue with zip Static Resources that prevents files with whitespace in their names from being extracted (I suppose the Static Resource web service on SFDC cannot handle whitespaces). In light of this, what options do we have to access JSON files (containing whitespace in their names) from a zip Static Resource in Apex?
Visualforce is suffering from the same issue so I cannot use Page.Name.getContent(). In Aura the same issue is present (since we'd need to make an explicit GET request to the Static Resource web service). In LWC the platformResourceLoader module only offers loadScript and loadStyle. There' nothing to load a JSON file.

A: My workaround was to rename the files, replacing spaces with %20. So if the static resource was:
"images.zip/large image.png"

it became
"images.zip/large%20image.png"


text:
Q: Plotting a differentiated graph from nested lists in Python I have made a script which produces a graph from data in a nested list (temperature and changes).
#!/usr/bin/python
import matplotlib.pyplot as plt

temperature = [['65', '65.5', '66', '66.5', '67', '67.5', '68', '68.5', '69', '69.5', '70', '70.5', '71', '71.5', '72', '72.5', '73', '73.5', '74', '74.5', '75', '75.5', '76', '76.5', '77', '77.5', '78', '78.5', '79', '79.5', '80', '80.5', '81', '81.5', '82', '82.5', '83', '83.5', '84', '84.5', '85', '85.5', '86', '86.5', '87', '87.5', '88', '88.5', '89', '89.5', '90', '90.5', '91', '91.5', '92', '92.5', '93', '93.5', '94', '94.5', '95'], ['65', '65.5', '66', '66.5', '67', '67.5', '68', '68.5', '69', '69.5', '70', '70.5', '71', '71.5', '72', '72.5', '73', '73.5', '74', '74.5', '75', '75.5', '76', '76.5', '77', '77.5', '78', '78.5', '79', '79.5', '80', '80.5', '81', '81.5', '82', '82.5', '83', '83.5', '84', '84.5', '85', '85.5', '86', '86.5', '87', '87.5', '88', '88.5', '89', '89.5', '90', '90.5', '91', '91.5', '92', '92.5', '93', '93.5', '94', '94.5', '95'], ['65', '65.5', '66', '66.5', '67', '67.5', '68', '68.5', '69', '69.5', '70', '70.5', '71', '71.5', '72', '72.5', '73', '73.5', '74', '74.5', '75', '75.5', '76', '76.5', '77', '77.5', '78', '78.5', '79', '79.5', '80', '80.5', '81', '81.5', '82', '82.5', '83', '83.5', '84', '84.5', '85', '85.5', '86', '86.5', '87', '87.5', '88', '88.5', '89', '89.5', '90', '90.5', '91', '91.5', '92', '92.5', '93', '93.5', '94', '94.5', '95']]
changes = [['94.566', '94.210', '93.836', '93.443', '93.030', '92.597', '92.145', '91.673', '91.181', '90.669', '90.137', '89.585', '89.011', '88.409', '87.760', '87.019', '86.063', '84.577', '81.806', '76.130', '65.071', '47.659', '28.454', '14.158', '6.305', '2.678', '1.128', '0.480', '0.210', '0.095', '0.045', '0.022', '0.012', '0.006', '0.004', '0.002', '0.002', '0.001', '0.001', '0.001', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000'], ['94.566', '94.210', '93.836', '93.443', '93.030', '92.597', '92.145', '91.673', '91.181', '90.669', '90.138', '89.588', '89.016', '88.420', '87.788', '87.088', '86.239', '85.028', '82.929', '78.744', '70.282', '55.446', '36.209', '19.361', '8.976', '3.874', '1.634', '0.691', '0.298', '0.132', '0.060', '0.029', '0.015', '0.008', '0.004', '0.003', '0.002', '0.001', '0.001', '0.001', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000'], ['94.566', '94.210', '93.836', '93.443', '93.030', '92.597', '92.145', '91.673', '91.181', '90.669', '90.138', '89.588', '89.016', '88.421', '87.790', '87.093', '86.255', '85.072', '83.059', '79.131', '71.434', '58.441', '41.784', '25.977', '14.170', '6.919', '3.146', '1.386', '0.608', '0.270', '0.122', '0.057', '0.028', '0.014', '0.007', '0.004', '0.003', '0.001', '0.001', '0.001', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000']]

products=[]
for t,c in zip(temperature,changes):
    products.append(t)
    products.append(c)

plt.plot(*products)
plt.xlabel('temperature')
plt.ylabel('changes')
plt.show()

And the graph looks like:

Just wondering how to go about making a differentiated version of the graph as well (E.G. rate of change over temperature)?
The examples for plotting derivatives I have tried working with all deal with two or three numbers, and nothing this big and nested, hence I had a hard time trying to apply them to my dataset. (The data generated and fed into this script is always in the form of a nested list).

A: You can easily approximate derivatives by calculating finite differences. While you can do this with nested lists, you are much better off using numpy arrays. See below:
import matplotlib.pyplot as plt
import numpy as np

temperature = [['65', '65.5', '66', '66.5', '67', '67.5', '68', '68.5', '69', '69.5', '70', '70.5', '71', '71.5', '72', '72.5', '73', '73.5', '74', '74.5', '75', '75.5', '76', '76.5', '77', '77.5', '78', '78.5', '79', '79.5', '80', '80.5', '81', '81.5', '82', '82.5', '83', '83.5', '84', '84.5', '85', '85.5', '86', '86.5', '87', '87.5', '88', '88.5', '89', '89.5', '90', '90.5', '91', '91.5', '92', '92.5', '93', '93.5', '94', '94.5', '95'], ['65', '65.5', '66', '66.5', '67', '67.5', '68', '68.5', '69', '69.5', '70', '70.5', '71', '71.5', '72', '72.5', '73', '73.5', '74', '74.5', '75', '75.5', '76', '76.5', '77', '77.5', '78', '78.5', '79', '79.5', '80', '80.5', '81', '81.5', '82', '82.5', '83', '83.5', '84', '84.5', '85', '85.5', '86', '86.5', '87', '87.5', '88', '88.5', '89', '89.5', '90', '90.5', '91', '91.5', '92', '92.5', '93', '93.5', '94', '94.5', '95'], ['65', '65.5', '66', '66.5', '67', '67.5', '68', '68.5', '69', '69.5', '70', '70.5', '71', '71.5', '72', '72.5', '73', '73.5', '74', '74.5', '75', '75.5', '76', '76.5', '77', '77.5', '78', '78.5', '79', '79.5', '80', '80.5', '81', '81.5', '82', '82.5', '83', '83.5', '84', '84.5', '85', '85.5', '86', '86.5', '87', '87.5', '88', '88.5', '89', '89.5', '90', '90.5', '91', '91.5', '92', '92.5', '93', '93.5', '94', '94.5', '95']]
changes = [['94.566', '94.210', '93.836', '93.443', '93.030', '92.597', '92.145', '91.673', '91.181', '90.669', '90.137', '89.585', '89.011', '88.409', '87.760', '87.019', '86.063', '84.577', '81.806', '76.130', '65.071', '47.659', '28.454', '14.158', '6.305', '2.678', '1.128', '0.480', '0.210', '0.095', '0.045', '0.022', '0.012', '0.006', '0.004', '0.002', '0.002', '0.001', '0.001', '0.001', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000'], ['94.566', '94.210', '93.836', '93.443', '93.030', '92.597', '92.145', '91.673', '91.181', '90.669', '90.138', '89.588', '89.016', '88.420', '87.788', '87.088', '86.239', '85.028', '82.929', '78.744', '70.282', '55.446', '36.209', '19.361', '8.976', '3.874', '1.634', '0.691', '0.298', '0.132', '0.060', '0.029', '0.015', '0.008', '0.004', '0.003', '0.002', '0.001', '0.001', '0.001', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000'], ['94.566', '94.210', '93.836', '93.443', '93.030', '92.597', '92.145', '91.673', '91.181', '90.669', '90.138', '89.588', '89.016', '88.421', '87.790', '87.093', '86.255', '85.072', '83.059', '79.131', '71.434', '58.441', '41.784', '25.977', '14.170', '6.919', '3.146', '1.386', '0.608', '0.270', '0.122', '0.057', '0.028', '0.014', '0.007', '0.004', '0.003', '0.001', '0.001', '0.001', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000']]

temperature = np.array(temperature, dtype=np.float32).transpose()
changes = np.array(changes, dtype=np.float32).transpose()

plt.figure()
plt.plot(temperature, changes)
plt.xlabel('temperature')
plt.ylabel('changes')
plt.show()

delta_t = temperature[1:]-temperature[:-1]
t_av = 0.5*(temperature[1:]+temperature[:-1])
dc_dt = (changes[1:]-changes[:-1])

plt.figure()
plt.plot(t_av, dc_dt)
plt.xlabel('temperature')
plt.ylabel('dc/dt')
plt.show()

A: Going on from @DavePs solution, you can use np.gradient:
import matplotlib.pyplot as plt
import numpy as np

temperature = [['65', '65.5', '66', '66.5', '67', '67.5', '68', '68.5', '69', '69.5', '70', '70.5', '71', '71.5', '72', '72.5', '73', '73.5', '74', '74.5', '75', '75.5', '76', '76.5', '77', '77.5', '78', '78.5', '79', '79.5', '80', '80.5', '81', '81.5', '82', '82.5', '83', '83.5', '84', '84.5', '85', '85.5', '86', '86.5', '87', '87.5', '88', '88.5', '89', '89.5', '90', '90.5', '91', '91.5', '92', '92.5', '93', '93.5', '94', '94.5', '95'], ['65', '65.5', '66', '66.5', '67', '67.5', '68', '68.5', '69', '69.5', '70', '70.5', '71', '71.5', '72', '72.5', '73', '73.5', '74', '74.5', '75', '75.5', '76', '76.5', '77', '77.5', '78', '78.5', '79', '79.5', '80', '80.5', '81', '81.5', '82', '82.5', '83', '83.5', '84', '84.5', '85', '85.5', '86', '86.5', '87', '87.5', '88', '88.5', '89', '89.5', '90', '90.5', '91', '91.5', '92', '92.5', '93', '93.5', '94', '94.5', '95'], ['65', '65.5', '66', '66.5', '67', '67.5', '68', '68.5', '69', '69.5', '70', '70.5', '71', '71.5', '72', '72.5', '73', '73.5', '74', '74.5', '75', '75.5', '76', '76.5', '77', '77.5', '78', '78.5', '79', '79.5', '80', '80.5', '81', '81.5', '82', '82.5', '83', '83.5', '84', '84.5', '85', '85.5', '86', '86.5', '87', '87.5', '88', '88.5', '89', '89.5', '90', '90.5', '91', '91.5', '92', '92.5', '93', '93.5', '94', '94.5', '95']]
changes = [['94.566', '94.210', '93.836', '93.443', '93.030', '92.597', '92.145', '91.673', '91.181', '90.669', '90.137', '89.585', '89.011', '88.409', '87.760', '87.019', '86.063', '84.577', '81.806', '76.130', '65.071', '47.659', '28.454', '14.158', '6.305', '2.678', '1.128', '0.480', '0.210', '0.095', '0.045', '0.022', '0.012', '0.006', '0.004', '0.002', '0.002', '0.001', '0.001', '0.001', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000'], ['94.566', '94.210', '93.836', '93.443', '93.030', '92.597', '92.145', '91.673', '91.181', '90.669', '90.138', '89.588', '89.016', '88.420', '87.788', '87.088', '86.239', '85.028', '82.929', '78.744', '70.282', '55.446', '36.209', '19.361', '8.976', '3.874', '1.634', '0.691', '0.298', '0.132', '0.060', '0.029', '0.015', '0.008', '0.004', '0.003', '0.002', '0.001', '0.001', '0.001', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000'], ['94.566', '94.210', '93.836', '93.443', '93.030', '92.597', '92.145', '91.673', '91.181', '90.669', '90.138', '89.588', '89.016', '88.421', '87.790', '87.093', '86.255', '85.072', '83.059', '79.131', '71.434', '58.441', '41.784', '25.977', '14.170', '6.919', '3.146', '1.386', '0.608', '0.270', '0.122', '0.057', '0.028', '0.014', '0.007', '0.004', '0.003', '0.001', '0.001', '0.001', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000', '0.000']]

temperature = np.array(temperature, dtype=np.float32).transpose()
changes = np.array(changes, dtype=np.float32).transpose()

plt.figure()

distances = np.gradient(temperature)[0]

plt.plot(temperature, np.gradient(changes, distances)[0])
plt.xlabel('temperature')
plt.ylabel('dc/dt')
plt.show()


text:
Q: Conditional difference calculation in data table I have a millions row long data.table with about 20 counter-style columns. Those columns display various storage system operations' counters increasing in time. Sometimes however, the counter gets reset on the monitored system and the single observation value is lower than a previous one.
I need to calculate a opsdiff column, which would contain an arithmetical difference (expected to be positive) of subsequent values of same type based on column type. When a counter reset situation is identified - ie. the difference is negative, the actual value of the counter should be used.
> dt <- data.table(type=rep(c("a","b"),each=6),opscounter=c(105609,106316,106705,489,723,1250))
> dt
    type opscounter
 1:    a     105609
 2:    a     106316
 3:    a     106705
 4:    a        489
 5:    a        723
 6:    a       1250
 7:    b     105609
 8:    b     106316
 9:    b     106705
10:    b        489
11:    b        723
12:    b       1250

The result I wish to get:
> dt
    type opscounter     opsdiff
 1:    a     105609          NA
 2:    a     106316         707
 3:    a     106705         389
 4:    a        489         489
 5:    a        723         234
 6:    a       1250         527
 7:    b     105609          NA
 8:    b     106316         707
 9:    b     106705         389
10:    b        489         489
11:    b        723         234
12:    b       1250         527
>

I tried to build a construction based on ifelse() but I don't know how to address the current row's opscounter value in else part and neither the dual call of diff() is perhaps an efficient usage:
dt[,opsdiff:=c(NA, ifelse(diff(opscounter)>0, diff(opscounter), opscounter)), by=type]

How can I correctly calculate the opsdiff column?

A: The preferred solution would be:
dt[, opsdiff := c(NA, diff(opscounter)),
   by = type][opsdiff < 0, opsdiff := opscounter][]
#     type opscounter opsdiff
#  1:    a     105609      NA
#  2:    a     106316     707
#  3:    a     106705     389
#  4:    a        489     489
#  5:    a        723     234
#  6:    a       1250     527
#  7:    b     105609      NA
#  8:    b     106316     707
#  9:    b     106705     389
# 10:    b        489     489
# 11:    b        723     234
# 12:    b       1250     527

Note that I've added additional [] in order to print results on the fly and in order to illustrate that you can add more than one of these.

In general, it would be better to avoid ifelse (especially in your case with such big data set) as it can to be slow (although vectorized) due to it evaluating both yes and no cases. In your case, you found another "flaw", that you need to tell it the exact locations where you want to pull opscounter from, which adds to the complexity (see @Aruns comment for possible override).
Regarding your question in comments, a data.table operation of the form DT[...] just calls the function [.data.table(DT, ...). It's not any different on a data.frame; there is a similar function [.data.frame.

Note that a data.table is also a data.frame. See class(dt) and also read ?data.table.

To make it even clearer, in data.table, tacking [...] one after another is called chaining. This is something that comes for free. You can do the same in a data.frame as well (as shown below), but the operations you can perform on a data.frame are limited, and therefore the use of chaining itself, unlike data.table.
df <- as.data.frame(dt) # or `setDF(dt)` in 1.9.4+ to do this by reference
df[df$type == "a", ][2:3, ]
#   type opscounter
# 2    a     106316
# 3    a     106705

Finally, in order to illustrate the ineffectiveness of ifelse, here is a benchmark:
set.seed(123)
n <- 1e6
dt <- data.table(type = rep(c("a","b"), each = n),
                 opscounter = sample(1:1e5, n*2, replace = TRUE))

library(microbenchmark)
microbenchmark(
dt[, opsdiff := c(NA, diff(opscounter)), by = type][opsdiff < 0, opsdiff := opscounter],
dt[, opsdiff := c(NA, ifelse(diff(opscounter) > 0, diff(opscounter), tail(opscounter, -1L))), by=type]
)

# Unit: milliseconds
#                                                                                expr
#             dt[, `:=`(opsdiff, c(NA, diff(opscounter))), by = type][opsdiff <  0, `:=`(opsdiff, opscounter)]
# dt[, `:=`(opsdiff, c(NA, ifelse(diff(opscounter) > 0, diff(opscounter), tail(opscounter, -1L)))), by = type]
#      min       lq      mean    median        uq       max neval
# 228.0445 255.4006  285.8163  281.1388  307.4195  508.3841   100
# 899.1222 990.1478 1085.5492 1048.3704 1095.7179 1740.5704   100

The ifelse solution is slower by a factor of ~4.

A: Since this is not an approach with data.table, this would not be the ideal one. But, the following would be an alternative approach.
library(dplyr)
df <- data.frame(type=rep(c("a","b"),each=6),opscounter=c(105609,106316,106705,489,723,1250))

df %>%
    group_by(type) %>%
    mutate(opsdiff = opscounter - lag(opscounter)) %>%
    mutate(opsdiff = ifelse(opsdiff < 0, opscounter, opsdiff))

#   type opscounter opsdiff
#1     a     105609      NA
#2     a     106316     707
#3     a     106705     389
#4     a        489     489
#5     a        723     234
#6     a       1250     527
#7     b     105609      NA
#8     b     106316     707
#9     b     106705     389
#10    b        489     489
#11    b        723     234
#12    b       1250     527


text:
Q: How do I interpret a DCC model from EViews? How would I interpret this DCC model from EViews? I am trying to use this output to find whether bitcoin has safe haven properties in volatile markets. When I read journals it says if δ2 and δ3 are positive, its not a safe haven assets but what do those symbols refer to on this output?
LogL: DCC_BTC_JSE
Method: Maximum Likelihood  (BFGS / Marquardt steps)
Date: 11/04/22   Time: 11:32
Sample: 1/04/2017 9/30/2022
Included observations: 1498
Evaluation order: By observation
Estimation settings: tol= 1.0e-05, derivs=numeric
Initial Values: T(1)=0.20000, T(2)=0.70000
Convergence achieved after 49 iterations
Coefficient covariance computed using outer product of gradients

    Coefficient Std. Error  z-Statistic Prob.

T(1)    0.008406    0.005503    1.527410    0.1267
T(2)    -0.738400   0.142926    -5.166297   0.0000

Log likelihood  -4230.855       Akaike info criterion       5.651342
Avg. log likelihood -2.824336       Schwarz criterion       5.658434
Number of Coefs.    2       Hannan-Quinn criter.        5.653984


text:
Q: Wcf - Get Request and Response with System.Diagnostics .
Hello
I have a WCF and I have to record the request and the associated response.
Today I seem to get the request and response, but I have no ID to associate.
Using the following configuration in .config:
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="xml" />
        </listeners>
      </source>
    </sources>
    <sharedListeners>
    <add name="xml" type="Ctx_Host.WebTraceListener, Ctx_Host" />
    </sharedListeners>
  </system.diagnostics>
  <system.serviceModel>
    <diagnostics>
      <messageLogging
          logEntireMessage="true"
          logMalformedMessages="false"
          logMessagesAtServiceLevel="true"
          logMessagesAtTransportLevel="true"
          maxMessagesToLog="300000"
          maxSizeOfMessageToLog="200000"/>
    </diagnostics>
  </system.serviceModel>

And the .cs code is :
public class WebTraceListener : TraceListener
{
    public override void Write(string message)
    {
        using (var sw = new StreamWriter(@"F:\wcf\log.csv", true))
        {
            sw.WriteLine(message);
        }
    }

    public override void WriteLine(string message)
    {
        using (var sw = new StreamWriter(@"F:\wcf\log.csv", true))
        {
            sw.WriteLine(message);
        }
    }
}

Can you tell me if it is possible to link the request and response in this way or another?
thanks for your help

A: The diagnostics generates a "Correlation ActivityID" in messages, it's the same and relation requests and responses.
This link has more information about and can help you:
http://www.codeproject.com/Articles/392926/Grouping-application-traces-using-ActivityId
And this about ActivityID:
http://www.thejoyofcode.com/Propagating_the_ActivityId_to_a_WCF_service.aspx


text:
Q: Windows MSI installer fails with error 2053 Whenever I try to install or update a program which uses a .msi installer, the installation gets up to the final step and the progress bar almost reaches the end, but the install suddenly fails with an error 2503, followed by an error 2502. This happens with many different applications, including TortoiseSVN and Brackets. Strangely, uninstalling programs which use the .msi installer works fine.
Here's what I've tried:

*

*Checked permissions on C:\Windows\Installer. System and Administrators all have full permissions (excluding special permissions), and Everyone can Read, List Folder Contents and Read & Execute. This is apparently the correct permissions according to sites I've found.

*Tried temporarily removing the contents of the C:\Windows\Installer folder. No effect.

*Tried opening command prompt as an administrator and running these commands: msiexec /unreg
msiexec /regeserver
I'm using x64-bit Windows 8. Any suggestions on how to resolve this issue would be appreciated.
Update: By right-clicking on the MSI file and selecting 'Run as Administrator', the installation succeeds. However is a workaround, and I am still looking for how to solve the original problem

A: The solution I found for a similar problem is detailed on this page
http://www.energizedtech.com/2013/05/windows-installer-error-2502-a.html
Basically you use the Command Prompt as Administrator, then install your package from there. Worked for me.
Pat. M

A: I eventually solved this issue by preforming a refresh (keep personal files but reset Windows and programs).


text:
Q: In what (small) ways can I modify Octave's compile options to enhance it without breaking it? If the title to this question seems a bit vague, I am sorry. But I wasn't sure how to distill what I am attempting to do into a single sentence.
A few weeks back I learned that I could build and install recent releases of Octave on an Ubuntu 12.04 system by following the steps below.

*

*Install the tools needed to compile, link, and run octave.
For Ubuntu the commands below have worked for me.
sudo apt-get build-dep octave3.2
sudo apt-get install build-essential gnuplot gtk2-engines-pixbuf
sudo apt-get install libfontconfig-dev bison

*Next, download the source code for an Octave release from the Gnu Project Archives for Octave and unpack the archive into a folder on your system.

*Use the commands below to build, check, and install octave.
 ./configure
 make
 make check
 sudo make install

Unfortunately it turns out that the above builds an Octave that contains all the debugging symbol tables. The object files alone are huge taking up around 1.7 GB.
The current Octave documentation suggests

To compile without debugging symbols try the command
make CFLAGS=-O CXXFLAGS=-O LDFLAGS=
instead of just make.

However, when I tried this it did not work. The -g option was still used for the compiles. For the heck of it I instead tried ./configure CFLAGS=-O CXXFLAGS=-O and this did work. (Instead of ~1.7GB the result of the build now takes up around 253MB).
My questions are

*

*Is this actually the correct (recommended?) method to use to compile Octave without debugging symbols (i.e. without -g)?

*How would I compile Octave so it uses x86_64 rather than x86?
Note: I am not asking how to compile Octave to use the (experimental) 64-bit integers for array dimensions. I just want to allow the compiler to use the extra registers and word sizes available when an app runs in 64-bit mode.

*Is a (more) complete list available for the directives used with the Octave Makefile?
I have only seen make, make check, and make install documented. But apparently make distclean is also allowed. (It removes the compilation results so you can do a complete rebuild of everything.)
I'm wondering what else might be available.

FWIW, I have tried using
./configure CFLAGS="-O3 -mtune=core2 -m64" CXXFLAGS="-O3 -mtune=core2 -m64"
and, surprisingly, it not only appeared to build, but also ran and passed the make check tests.
But of course that's not the same thing as saying it actually "works". Is there a recommended way to enable Octave to run as an x86_64 app?
I have also tried looking inside the Octave Makefile to see if I could decipher what command line directives it accepts. I got nowhere. I have not a single clue as to how that Makefile does whatever it is that it does.

A: It depends on your version of gcc, your hardware, your distribution, and a lot of other things. Typically, your Linux distribution provider would have done that research for you and used those options when building your package. Distributions, however, try to make things work with most hardware and user expectations. I find the most customization without having to go to too much trouble with Gentoo. Linux from scratch or rolling your own distribution is a lot of work. I have a Gentoo installation with 32-bit emulation turned off in the kernel.
From Gentoo Optimization Guide, it's best to use -O2 instead of -O3

-O3: This is the highest level of optimization possible, and also the riskiest. It will take a longer time to compile your code with this option, and in fact it should not be used system-wide with gcc 4.x. The behavior of gcc has changed significantly since version 3.x. In 3.x, -O3 has been shown to lead to marginally faster execution times over -O2, but this is no longer the case with gcc 4.x. Compiling all your packages with -O3 will result in larger binaries that require more memory, and will significantly increase the odds of compilation failure or unexpected program behavior (including errors). The downsides outweigh the benefits; remember the principle of diminishing returns. Using -O3 is not recommended for gcc 4.x.

-mtune=core2 is ok if you're sure that's the best choice for your processor. I personally like -march=native instead. See Gentoo Safe CFlags

GCC 4.2 introduces a new -march option, -march=native, which automatically detects the features your CPU supports and sets the options appropriately. If you have an Intel or AMD CPU and are using >=sys-devel/gcc-4.2.3, using -march=native is recommended.

-m64 is a processor option and should be automatically set by -mtune=core2 or -march=native. See GCC i386 and x86-64 Options.
Disclaimer:
You do not have to switch to Gentoo in order to use their advice for compiling from source.


text:
Q: Color output in Sublime Text 2 console? Is there any way to output coloful text to the sublime text console? I tried this:
"\033[0;32mTest\033[0m"

and the console displays something similar to this:
ESC[0;32mTestESC[0m"

A: Unfortunately, the Sublime Text console is essentially monochrome. Its foreground and background colors can be changed via the Packages/Theme - Default/Widgets.stTheme file (or your theme's equivalent), but you can't colorize output using terminal escape codes, like you are using.


text:
Q: How do I translate LR(1) Parse into a Abstract syntax tree? I have coded a table driven LR(1) parser and it is working very well however I am having a bit of a disconnect on the stage of turing a parse into a syntax tree/abstract syntax tree. This is a project that I m very passionate about but I have really just hit a dead end here. Thank you for your help in advance.
Edit: Also my parser just uses a 2d array and an action object that tells it where to go next or if its a reduction where to go and how many items to pop. I noticed that many people use the visitor pattern. Im not sure how they know what type of node to make.
Here is the pushdown automata for context
 while (lexer.hasNext() || parseStack.size() > 0) {
        Action topOfStack = parseStack.peek();
        token = parseStack.size() > 0 ? lexer.nextToken() : new Token(TokenType.EOF, "EOF");
        topOfStack.setToken(token);

        int row = topOfStack.getTransitionIndex();
        int column = getTerminalIndex(token.getLexeme());

        column = token.getType() == TokenType.IDENTIFIER
                && !terminalsContain(token.getLexeme()) ? 0 : column;

        Action action = actionTable[row][column];

        if (action instanceof Accept) {
            System.out.println("valid parse!!!!!!");
        } else if (action instanceof Reduction) {
            Reduction reduction = (Reduction) action;

            popStack(parseStack, reduction.getNumberOfItemsToPop());
            column = reduction.getTransitionIndex();
            row = parseStack.peek().getTransitionIndex();

            parseStack.push(new Action(gotoTable[row][column]));
            lexer.backupTokenStream();
        } else if (action != null) {
            parseStack.push(actionTable[row][column]);
        } else {
            System.out.println("Parse error");
            System.out.println("On token: " + token.getLexeme());
            break;
        }

A: Each reduction in the LR parsing process corresponds to an internal node in the parse tree.  The rule being reduced is the internal AST node, and the items popped off the stack correspond to the children of that internal node.  The item pushed for the goto corresponds to the internal node, while those pushed by shift actions correspond to leaves (tokens) of the AST.
Putting all that together, you can easily build an AST by createing a new internal node every time you do a reduction and wiring everything together appropriately.


text:
Q: View model binding: Is there a way to access properties of a concrete implementation, when the class being bound to is abstract? I am attempting to access the concrete implementation of an abstract object within the bound model of an ASP.NET MVC view, but I don't know how to bind to that property's properties that are part of its concrete implementation.
public abstract class BasePageVO
{
    public string DisplayText { get; set; }
    public BaseFoo FooItem { get; set; }
}

public class ConcretePageVO : BasePageVO
{
    // some properties

    // in a concrete page, the concrete implementation of BaseFoo is known at compile time.
}

public abstract class BaseFoo
{
    public string FooText { get; set; }
}

public class ConcreteFoo : BaseFoo
{
    public string ConcreteProperty { get; set; }
}

The kicker, and why I have adopted such an unusual class structure, is that the shared partial also needs to know about the FooItem, but only its abstract properties. A much-simplified outline of the structure is below:
DisplayFoo.cshtml:
@model ConcretePageVO

@using (Html.BeginForm("Submit", "Foo", FormMethod.Post)
{
    @Html.Partial("DisplayFooShared", @Model)
    @Html.EditorFor(x => x.FooItem.ConcreteProperty) @* This fails *@
}

DisplayFooShared.cshtml:
@model BasePageVO

<div>
    @Html.DisplayFor(x => x.DisplayText)
    @Html.EditorFor(x => x.FooItem.FooText)
    @* More properties... *@
</div>

Is there a way to indicate to Razor that the BaseFoo object is of an expected concrete type, and still benefit from how I perform model binding in the shared partial view? I thought I was on the right track with creating my own custom model binding for BaseFoo, like in Darin's answer here, but ASP.NET throws a compilation error that Razor doesn't know what to do with the property name, since it isn't defined.
Is there a way to accomplish binding to these implementation-specific properties and still benefit from the strong typing ASP.NET MVC affords? Was I on the right track with custom binding, but merely botched the implementation? Thanks in advance for any advice.
EDIT: I replaced @Html.EditorFor(x => x.FooItem.ConcreteProperty) with @Html.EditorFor(x => (x.FooItem as ConcreteFoo).ConcreteProperty), which causes the binding to succeed. Is there still a better way to do this, though?

A:     public abstract class BaseFoo
    {
        public virtual string FooText { get; set; }
    }

    public class ConcreteFoo : BaseFoo
    {
        public override string FooText { get; set; }
    }

A: What you are doing violates the principles of object oriented programming.  You've got a base class and you're trying to treat it like a derived class, and that's simply a huge red flag.  If you need the derived class, then you should have a derived class in your model.
Your only option otherwise is to cast, and that is a huge code smell, and potential flaw if the object isn't actually the derived object you think it is.
More than likely, your real problem is that you're trying to use some kind of domain model as your view model.  You should customize your view model to be exactly the model you need for that view.  Then you should map your domain model to your view model and do any conversions that are necessary at that point.


text:
Q: kubuntu 15.04 trackpoint sensitivity I'm running the latest kubuntu with plasma 5 on a t440s laptop. The trackpoint is very slow and there's no option to increase the sensitivity under the system input settings. The same laptop is running elementary os freya and I can adjust this via xinput. On kubuntu changing the xinput values has no effect.
Any idea how I can adjust this?

A: The change the sensitivity (and speed, etc.) permanently, you can create an udev rule.
E.g. create a file 10-trackpoint.rules in /etc/udev/rules.d/ with the following contents:
SUBSYSTEM=="serio", DRIVERS=="psmouse", WAIT_FOR="/sys/devices/platform/i8042/serio1/serio2/sensitivity", ATTR{sensitivity}="220",  ATTR{speed}="190", ATTR{inertia}="6", ATTR{press_to_select}="0"

This method was tested on Ubuntu 14.04 up to 15.04.
For further explanations check on the Archwiki and Thinkwiki and look for "sensitivity".
Update for Ubuntu 15.10
The above rule does not trigger properly on Ubuntu 15.10. Instead use:
ACTION=="add", SUBSYSTEM=="input", ATTR{name}=="TPPS/2 IBM TrackPoint", ATTR{device/sensitivity}="220", ATTR{device/speed}="190", ATTR{device/inertia}="6", ATTR{device/press_to_select}="0"


text:
Q: Функция, работающая только 10 раз в минуту c# Функция вызывается, если в консоль пишешь test
Если много раз писать это слово, то будет флуд, надо чтобы функцию можно было вызывать 10 раз в минуту

A: Запомните отметку времени, а при следующем вызове проверяйте ее:
var sw = new Stopwatch(); // Секундомер
sw.Start();
// Переменная для хранения метки времени
var prevStamp = sw.ElapsedMilliseconds;
while (true)
{
    var c = Console.ReadLine();
    if (c == "test")
    {
        // Если прошло менее 6 с (6000 мс) - пропускаем
        if (sw.ElapsedMilliseconds - prevStamp < 6000) continue;
        // Иначе - выполняем метод
        Test();
        // И сохраняем новую отметку времени
        prevStamp = sw.ElapsedMilliseconds;
    }
}

A: Создайте переменную счётчик, которая будет увеличиваться каждый раз, когда пользователь вводит test. Если переменная больше или равна 10, тогда не вызывайте вашу функцию.
На C# особо не писал,  может можно лучше сделать, но смысл такой:
public class Program
    {
        public static int testCount = 0;
        public static void printTest1()
        {
            Console.WriteLine("test1");
        }

        public static void Main(string[] args)
        {
            Timer myTimer = new Timer();
            myTimer.Elapsed += (sender, arguments) => testCount = 0;
            myTimer.Interval = 60000;
            myTimer.Start();
            if (Console.ReadLine() == "test")
                testCount++;
            if (testCount < 10)
                printTest1();
        }
    }


text:
Q: How to make a triangle shape with Tailwind?

how to make a triangle with tailwindCss without plugin ??

A: You can also try using borders
tailwind playground

A: You may try using transform:

<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">

A: Maybe you want to use the triangle for tooltip. (such search got me here):

  <button type="button" class="rounded-md border border-neutral-600 px-1">...</button>

Do amazing stuff

Go back

Demo on play.tailwindcss.com
Based on:

*

*@temani-afif answer

*https://github.com/tesar-tech/BlazorAndTailwind/blob/master/Articles/DropdownMenu/README.md

A: By pseudo-element (small triangle):

small triangle:

By pseudo-element (normal triangle):

normal triangle:

By border:

triangle by border

By border (simplify):

triangle by border (simplify)


text:
Q: Snowflake: Joining a Table with Effective Dates and older records are showing NULL Summary:
In Snowflake I have a table which records the maximum number of an item which changes every so often. I want to be able to join the max number of the item for that date (effective_date). This is the most basic "example" as in my table has items "expire" when they are removed.
CREATE OR REPLACE TABLE ITEM
(
 Item VARCHAR(10),
 Quantity Number(5,0),
 EFFECTIVE_DATE DATE
)
;

CREATE OR REPLACE TABLE REPORT
(
 INVOICE_DATE DATE,
 ITEM VARCHAR(10)
)
;

INSERT INTO REPORT
VALUES
('2021-02-01', '100'),
('2021-09-10', '100')
;

INSERT INTO ITEM
VALUES
('100', '10', '2021-01-01'),
('101', '15', '2021-01-01'),
('100', '5', '2021-09-01')
;

SELECT * FROM REPORT t1
LEFT JOIN
(
SELECT * FROM ITEM
QUALIFY ROW_NUMBER() OVER (PARTITION BY ITEM ORDER BY EFFECTIVE_DATE desc) = 1
) t2 on t1.ITEM = t2.ITEM AND t1.INVOICE_DATE <= t2.EFFECTIVE_DATE
;

Returns
INVOICE_DATE,ITEM,ITEM,QUANTITY,EFFECTIVE_DATE
2021-02-01,100,100,5,2021-09-01
2021-09-10,100,NULL,NULL,NULL

How do I fix this so I no longer get NULL entries on my join.
Thank you for reading this!
I am hoping to get a result like this
INVOICE_DATE,ITEM,ITEM,QUANTITY,EFFECTIVE_DATE
2021-02-01,100,100,10,2021-01-01
2021-09-10,100,100,5,2021-09-01

A: The issue is with your data and your expectations.  Your query is this:
SELECT * FROM REPORT t1
LEFT JOIN
(
SELECT * FROM ITEM
QUALIFY ROW_NUMBER() OVER (PARTITION BY ITEM ORDER BY EFFECTIVE_DATE desc) = 1
) t2 on t1.ITEM = t2.ITEM AND t1.INVOICE_DATE <= t2.EFFECTIVE_DATE
;

which requires that the INVOICE_DATE be less than or equal to the EFFECTIVE DATE of the ITEM.  This isn't the case, though.  2021-09-10 is greater than 2021-09-01 so you don't get a join hit, which is why you get NULLs.  It's also why your other record is returning the wrong information from your expectations.


text:
Q: Cosmos DB Mongo API ChangeStream: Is there a way to read which fields where updated? We use mongodb as a database. In local development, the official image, but in production a Cosmos DB with Mongo API.
We use change streams to watch for changes in the database.
After we process the created or updated record, we need to make changes to the record again (set flags).
Maybe you guess it, this leads to an infinite loop.
I first designed a solution that works locally with the official mongo image. When I set the flags, I also set a Guid @changeId in the dataset and create a filter that checks if the @changeId has changed during an update, if so, the process is not triggered.
I do it like this:
public async Task Watch(CancellationToken token)
        {
            logger.LogInformation("Watching database for changes...");
            token.Register(() => this.logger.LogInformation("Stop Polling. Stop requested."));

            var filter = Builders<ChangeStreamDocument<BsonDocument>>
                .Filter.Where(change =>
                    change.OperationType == ChangeStreamOperationType.Insert
                    || change.OperationType == ChangeStreamOperationType.Update
                    || change.OperationType == ChangeStreamOperationType.Replace
                );

            var updateExistsFilter = Builders<ChangeStreamDocument<BsonDocument>>.Filter.Exists("updateDescription.updatedFields");
            var changeIdNotChangedFilter = Builders<ChangeStreamDocument<BsonDocument>>.Filter.Not(
                Builders<ChangeStreamDocument<BsonDocument>>.Filter.Exists("updateDescription.updatedFields.@changeId")
                );
            var relevantUpdateFilter = updateExistsFilter & changeIdNotChangedFilter;

            //if no updateDescription exists, its an insert so data should be processed anyway
            var insertFilter = Builders<ChangeStreamDocument<BsonDocument>>.Filter.Not(
                Builders<ChangeStreamDocument<BsonDocument>>.Filter.Exists("updateDescription.updatedFields")
            );

            filter &= relevantUpdateFilter | insertFilter;

            var definition = new EmptyPipelineDefinition<ChangeStreamDocument<BsonDocument>>()
                .Match(filter)
                .AppendStage<ChangeStreamDocument<BsonDocument>, ChangeStreamDocument<BsonDocument>, BsonDocument>(
                    "{ $project: { '_id': 1, 'fullDocument': 1, 'ns': 1, 'documentKey': 1 }}"
                );

            var options = new ChangeStreamOptions
            {
                FullDocument = ChangeStreamFullDocumentOption.UpdateLookup
            };

            while (!token.IsCancellationRequested)
            {
                using (var cursor = await base.collection.WatchAsync(definition, options, token))
                {
                    await cursor.ForEachAsync(async (doc) =>
                    {
                        ProcessData(doc);
                    }, token);
                }

                await Task.Delay(TimeSpan.FromSeconds(1), token);
            }
        }

Unfortunately, it wasn't until testing on QA with a Cosmos DB attached that I noticed Cosmos doesn't support UpdateDescription. see here
It goes to an infinity loop.
Is there a way to get the updated fields?
Or maybe is it possible to make sure that the changestream does not react when using the update function of the mongo driver?
Or is there any way to avoid this infinity loop?


text:
Q: Modular arithmetic terminology In division, we have terms like divisor, dividend, quotient, remainder. Do we have like terms for modular arithmetic? In particular, in the following, does $n$ have a special name such as "modulator" or something?
$$a \equiv b \quad (\text{mod}\: n)$$

A: It is normally called the modulus.


text:
Q: SQOOP uneven output file size I have a huge news database, but whenever i am trying to sqoop it, it writes to 2-3 files rather than whole 200.
sqoop import -D mapred.map.max.attempts=4 \
  -D dfs.blocksize=1073741824 \
  -D oraoop.block.allocation=RANDOM \
  -D mapred.job.queue.name=default \
  -m 200 \
  --split-by AUTHOR_ID \
  --connect jdbc:oracle:thin:@$127.0.0.1:1521:SRDB \
  --username abc \
  --password 1234 \
  --table L.ARTICLE \
  --null-string '' \
  --null-non-string '' \
  --target-dir /data/output1.0
  --outdir /tmp/output

But, when I ran it, I was getting 202 files instead of 200. And among those only 3 files has data and rest of the output files are empty.
What am I doing wrong? Any hint would be appreciated!
Thank you

A: You are splitting on AUTHOR_ID
Most probable reason -
AUTHOR_ID(on which you are splitting)  is not uniformly distributed.
Internally sqoop is fetching min and max values for splitting columns.
SELECT MIN(AUTHOR_ID) and MAX(AUTHOR_ID) FROM L.ARTICLE

Say output of the above query is:
1,20000

Now based on these values it will make range queries like:
SELECT * FROM L.ARTICLE WHERE AUTHOR_ID>=1 AND AUTHOR_ID<100
SELECT * FROM L.ARTICLE WHERE AUTHOR_ID>=100 AND AUTHOR_ID<200
SELECT * FROM L.ARTICLE WHERE AUTHOR_ID>=200 AND AUTHOR_ID<300
.
.
.
SELECT * FROM L.ARTICLE WHERE AUTHOR_ID>=19900 AND AUTHOR_ID<20000

(You can observe this in sqoop command itself. Add --verbose in your sqoop commands so that you can see extended logs.)
Now if data is not uniformly distributed then only few mappers will fetch record and others are empty.
Let's say for example if in your data we have the following case:
author_id record
1 record1
19900 record19900
19901 record19901
19902 record19902
19903 record19903
19904 record19904
19905 record19905
19906 record19906

The mapper#0 will sqoop 1 record and mapper#199 will sqoop 7 records. You can extrapolate this case with a huge number of records.


text:
Q: Pasar Parámetros a una función para insertarlos en una tabla
Recién acabo de terminar mi curso de Python y estoy intentado hacer un sistema de inventario simplificado. El programa consta de varias ventanas (para agregar algún ítem, para modificarlo, etc...). La idea del código que voy a colocar a continuación es que al momento de presionar el botón de "Crear", el mismo llame a una función pasándole los parámetros especificados en el código. He intentado de muchas formas posibles sin éxito alguno de que se pasen correctamente los parámetros. código:

def crear(datos1):

    con=sqlite3.connect("Inventario")
    cur=con.cursor()

    try:

        cur.execute("INSERT INTO INVENTARIO VALUES(NULL,?,?,?,?)", (datos1))

        con.commit()

        messagebox.showinfo("Agregar","Registro Agregado")

    except:

        messagebox.showwarning("Error","Ha ocurrido un error")

def agregar():

    root=Tk()

    pro=StringVar()
    pre=StringVar()
    can=StringVar()
    var=StringVar()

    frame1=Frame(root)
    frame1.pack()

    entry1=Entry(frame1, textvariable=pro)
    entry1.grid(row=1, column=1, padx=10, pady=10)

    entry2=Entry(frame1, textvariable=pre)
    entry2.grid(row=2, column=1, padx=10, pady=10)

    entry3=Entry(frame1, textvariable=can)
    entry3.grid(row=3, column=1, padx=10, pady=10)

    rb1=Radiobutton(frame1, text="Producto", variable=var, value="Producto")
    rb1.grid(row=4, column=1, sticky="w")
    rb2=Radiobutton(frame1, text="Servicio", variable=var, value="Servicio")
    rb2.grid(row=5, column=1, sticky="w")

    label1=Label(frame1, text="Producto:")
    label1.grid(row=1, column=0, padx=10, pady=10, sticky="w")

    label1=Label(frame1, text="Precio:")
    label1.grid(row=2, column=0, padx=10, pady=10, sticky="w")

    label1=Label(frame1, text="Cantidad:")
    label1.grid(row=3, column=0, padx=10, pady=10, sticky="w")

    label1=Label(frame1, text="Tipo:")
    label1.grid(row=4, column=0, padx=10, pady=10, sticky="w")

    frame2=Frame(root)
    frame2.pack()

    datos=pro.get(), pre.get(), can.get(), var.get()

    boton1=Button(frame2, text="Agregar", command=lambda:crear(datos))
    boton1.grid(row=1, column=0, padx=5)

    boton2=Button(frame2, text="Cancelar", command=lambda:root.destroy())
    boton2.grid(row=1, column=1, padx=5)

    root.mainloop()

Gracias de antemano.

A: El error se debe al momento en el que es evaluada la línea:
datos=pro.get(), pre.get(), can.get(), var.get()

esta línea se evalúa al ejecutar la función agregar, antes incluso de que la composición de la app esté completa y de que se muestre en pantalla (antes del mainloop). En ese momento todos los entries están lógicamente vacíos por lo que a crear siempre se le manda una tupla con cuatro cadenas vacías.
Debes obtener los cuatro valores en el momento en el que se pulsa el botón, no cuando la función es llamada. Hay muchas formas de hacer esto, pero sin modificar tu idea original puede simplemente valerte de que las expresiones lambda se evalúan en diferido, es decir, cuando son llamadas y no al ser definidas:
import sqlite3
import tkinter as tk

def crear(datos1):
    con = sqlite3.connect("Inventario")
    cur = con.cursor()

    try:
        cur.execute("INSERT INTO INVENTARIO VALUES(NULL,?,?,?,?)", datos1)
        con.commit()
        tk.messagebox.showinfo("Agregar","Registro Agregado")
    except:
        tk.messagebox.showwarning("Error","Ha ocurrido un error")
    finally:
        cur.close()
        con.close()

def agregar():

    root = tk.Tk()

    pro = tk.StringVar(root)
    pre = tk.StringVar(root)
    can = tk.StringVar(root)
    var = tk.StringVar(root)

    frame1 = tk.Frame(root)
    frame1.pack()

    entry1 = tk.Entry(frame1, textvariable=pro)
    entry1.grid(row=1, column=1, padx=10, pady=10)

    entry2 = tk.Entry(frame1, textvariable=pre)
    entry2.grid(row=2, column=1, padx=10, pady=10)

    entry3 = tk.Entry(frame1, textvariable=can)
    entry3.grid(row=3, column=1, padx=10, pady=10)

    rb1 = tk.Radiobutton(frame1, text="Producto", variable=var, value="Producto")
    rb1.grid(row=4, column=1, sticky="w")
    rb2 = tk.Radiobutton(frame1, text="Servicio", variable=var, value="Servicio")
    rb2.grid(row=5, column=1, sticky="w")

    label1 = tk.Label(frame1, text="Producto:")
    label1.grid(row=1, column=0, padx=10, pady=10, sticky="w")

    label2 = tk.Label(frame1, text="Precio:")
    label2.grid(row=2, column=0, padx=10, pady=10, sticky="w")

    label3 = tk.Label(frame1, text="Cantidad:")
    label3.grid(row=3, column=0, padx=10, pady=10, sticky="w")

    label4 = tk.Label(frame1, text="Tipo:")
    label4.grid(row=4, column=0, padx=10, pady=10, sticky="w")

    frame2 = tk.Frame(root)
    frame2.pack()

    crear_wrapper = lambda: crear((pro.get(), pre.get(), can.get(), var.get()))

    boton1 = tk.Button(frame2, text="Agregar", command=crear_wrapper)
    boton1.grid(row=1, column=0, padx=5)

    boton2 = tk.Button(frame2, text="Cancelar", command=root.destroy)
    boton2.grid(row=1, column=1, padx=5)

    root.mainloop()

if __name__ == "__main__":
    agregar()

Ten en cuenta que no necesitas usar lambda si la función no recibe argumentos, basta con pasar una referencia a la función en este caso (command=root.destroy en vez de command=lambda:root.destroy()):

*

*¿Cómo actuan las funciones lambda en este código?

Edición
Dado que la función agregar es lanzada al pulsar un botón en otra ventana debes tener en cuenta algunas cosas más:

*

*Pasa siempre el padre a los widget, incluidas las variables (StringVar, IntVar, etc).

*No debes usar en principio más de una sola instancia de tkinter.Tk en una aplicación. Si necesitas más ventanas usa TopLevel, mira esta pregunta relacionada:

*

*¿StringVar y texvariable no funcionan en una ventana secundaria?
Tu función debería quedar:
def agregar(root=None):

    window = Toplevel(root)

    pro = StringVar(window)
    pre = StringVar(window)
    can = StringVar(window)
    var = StringVar(window)

    frame1 = Frame(window)
    frame1.pack()

    entry1 = Entry(frame1, textvariable=pro)
    entry1.grid(row=1, column=1, padx=10, pady=10)

    entry2 = Entry(frame1, textvariable=pre)
    entry2.grid(row=2, column=1, padx=10, pady=10)

    entry3 = Entry(frame1, textvariable=can)
    entry3.grid(row=3, column=1, padx=10, pady=10)

    rb1 = Radiobutton(frame1, text="Producto", variable=var, value="Producto")
    rb1.grid(row=4, column=1, sticky="w")
    rb2 = Radiobutton(frame1, text="Servicio", variable=var, value="Servicio")
    rb2.grid(row=5, column=1, sticky="w")

    label1 = Label(frame1, text="Producto:")
    label1.grid(row=1, column=0, padx=10, pady=10, sticky="w")

    label1 = Label(frame1, text="Precio:")
    label1.grid(row=2, column=0, padx=10, pady=10, sticky="w")

    label1 = Label(frame1, text="Cantidad:")
    label1.grid(row=3, column=0, padx=10, pady=10, sticky="w")

    label1 = Label(frame1, text="Tipo:")
    label1.grid(row=4, column=0, padx=10, pady=10, sticky="w")

    frame2 = Frame(window)
    frame2.pack()

    boton1 = Button(frame2, text="Agregar", command=lambda: crear((pro.get(), pre.get(), can.get(), var.get())))
    boton1.grid(row=1, column=0, padx=5)

    boton2=Button(frame2, text="Cancelar", command=window.destroy)
    boton2.grid(row=1, column=1, padx=5)

    window.mainloop()

y debes llamarla mediante:
invMenu.add_command(label="Agregar Item", command=lambda: F.agregar(root))


text:
Q: Use compiled .mexw64 function without matlab This may be due to my inexpertise in the area, but I'm looking for a way to use a function already compiled in a .mexw64 in a language or program different than MATLAB.
So far, I've found plenty of ways to create a code in other languages to compile into a .mexw64  for a further use in MATLAB, but here what I want to do is to use a fully compiled .mexw64 function (given by someone else) in, lets say, scilab (or any other language for the matter).
I have no interest in looking at the code (although it is definitely a plus), I only want to use it as a black box where I input what it needs and I get the normal output of it. Any solution that allows me to do this in another program or language other than MATLAB is welcomed. I don't know if this is possible or if it is a lost cause.


text:
Q: Wrap type in enum and return reference type Id = u8;

struct A {
    id: Id,
}
struct B {
    id: Id,
}
struct C {
    id: Id,
}

struct State {
    a_vec: Vec<A>,
    b_vec: Vec<B>,
    c_vec: Vec<C>,
}

impl State {
    fn new() -> Self {
        Self {
            a_vec: Vec::new(),
            b_vec: Vec::new(),
            c_vec: Vec::new(),
        }
    }

    fn get_e0(&self, id: Id) -> &E0 {

        if let Some(a) = self.a_vec.iter().find(|x| x.id==id) {
            &E0::A(a)
        } else if let Some(b) = self.b_vec.iter().find(|x| x.id==id) {
            &E0::B(b)
        } else {
            panic!("ahh that id doesn't exist everbody panic!!!")
        }
    }

    fn get_e0_mut(&mut self, id: Id) -> &mut E0 {
        if let Some(a) = self.a_vec.iter_mut().find(|x| x.id==id) {
            &mut E0::A(a)
        } else if let Some(b) = self.b_vec.iter_mut().find(|x| x.id==id) {
            &mut E0::B(b)
        } else {
            panic!("ahh that id doesn't exist everbody panic!!!")
        }
    }
}

enum E0 {
    A(A),
    B(B),
}

enum E1 {
    A(A),
    C(C),
}

fn main() {
    let state = State::new();

    let a0 = A { id: 0 };
    let a1 = A { id: 1 };
    let b0 = B { id: 2 };
    let c0 = C { id: 3 };
    state.a_vec.push(a0);
    state.a_vec.push(a1);
    state.b_vec.push(b0);
    state.c_vec.push(c0);

    let e5 = state.get_e0(1);
}

I'm looking for a way to implement the function get_e0 and get_e0_mut that wrap several types into an enum so the caller doesn't have to care which of A or B their id relates to, only that they will get an E0. Yet an Vec of E0's seems unfeasible as there might be separate grouping such as E1.
If these functions are not possible then is there another method that could be used to reduce the overhead of searching all the respective Vec's individually each time.
It is guaranteed that the all id's are unique.

A: You cannot return a reference to a temporary. Instead, you can make your enums generic over their contents. You can therefore use a single enum:
enum E0<T, U> {
    A(T),
    B(U),
}

You can then use it like this:
fn get_e0(&self, id: Id) -> E0<&A, &B> {
    if let Some(a) = self.a_vec.iter().find(|x| x.id == id) {
        E0::A(a)
    } else if let Some(b) = self.b_vec.iter().find(|x| x.id == id) {
        E0::B(b)
    } else {
        panic!("ahh that id doesn't exist everbody panic!!!")
    }
}

fn get_e0_mut(&mut self, id: Id) -> E0<&mut A, &mut B> {
    if let Some(a) = self.a_vec.iter_mut().find(|x| x.id == id) {
        E0::A(a)
    } else if let Some(b) = self.b_vec.iter_mut().find(|x| x.id == id) {
        E0::B(b)
    } else {
        panic!("ahh that id doesn't exist everbody panic!!!")
    }
}

Thanks to lifetime elision rules, you don't have to specify lifetimes.
Playground link
Note that if you want to avoid the panic, your return type should express the notion that there can be no value found.
You can for example return an Option:
fn get_e0(&self, id: Id) -> Option<E0<&A, &B>> { ... }

Or alter the enum to have a None variant, similar to Option:
enum E0<T, U> {
    A(T),
    B(U),
    None,
}

And use it like this:
fn get_e0(&self, id: Id) -> E0<&A, &B> {
    if let Some(a) = self.a_vec.iter().find(|x| x.id==id) {
        E0::A(a)
    } else if let Some(b) = self.b_vec.iter().find(|x| x.id==id) {
        E0::B(b)
    } else {
        E0::None
    }
}

It is most of the time more idiomatic to express such situations using the type system instead of panicking.


text:
Q: Live agent pre chat custom detail I'm trying to push some custom data to the chat console from pre chat from but without success. I've tried hidden form elements like this:
<input type="hidden" name="liveagent.prechat:Username" value="Anonymous" />

And also tried JavaScript API
liveagent.addCustomDetail('Username', "Anonymous", true);

But the agent sees only most recently viewed pages when hovering over "Accept" chat button. Also no custom variables are displayed after chat is initialized.
The pre-chat form is embedded on a client site. To submit the form I just use this code:
START CHAT

How can I debug this? What is the correct way to pass this custom data?

A: You are using the deployment API which is different to the tags that must be used in the pre-chat form.
Here is an example on how to create a case with some information pre-populated that will also show in the console for the agent, you can do the same without creating a record, this should give you an idea.
<input type='hidden' name='liveagent.prechat:caseorigin' value='Chat'/>
<input type='hidden' name='liveagent.prechat:caseContactId' value='{!$User.ContactId}'/>
<input type="hidden" name="liveagent.prechat.findorcreate.map:Case" value="Origin,caseorigin;ContactId,caseContactId;" />
<input type="hidden" name="liveagent.prechat.findorcreate.map.doCreate:Case" value="Origin,true;ContactId,true;" />
<input type="hidden" name="liveagent.prechat.findorcreate.saveToTranscript:Case" value="Case" />
<input type="hidden" name="liveagent.prechat.findorcreate.showOnCreate:Case" value="true" />

The section you care about if all you want is to show the details on the console would be this
<input type='hidden' name='liveagent.prechat:caseContactId' value='{!$User.ContactId}'/>

in combination with this value
<input type= "hidden" name= "liveagent.prechat.findorcreate.displayToAgent:caseContactId" value= "true" />

With that, you are assigning a value to a custom chat detail that will be shown to the agent that gets the chat assigned.


text:
Q: Customized Radio Button Input does not work as supposed to, on re-render in react I created a customized radio button with help of styled-components and react-typescript The working code is here on codesandbox. So In this code when I pass explicitly checked props to true  on my RadioButton component, it gives me a checked radio button but when I try to select another radio button I need to click it twice to get it selected animation. Meanwhile in console log when on the first click it gives the changed value of another radio button. but to get the selected animation on that radio button I need to click it twice.
For my code, I made the Real input element invisible by opacity and overlapped with my custom-created RadioButton.
It works fine when I am not passing checked props on the component. It gives an issue when I am passing the checked props to component.
I am not sure is it related to my custom created Radiobutton or its something related to the re-render issue.

A: Try the below approach
const App = () => {
  const [selectedValue, setSelectedValue] = useState<string | number>("first");
  console.log(selectedValue);

  const handleInputChange = (value: string | number): void => {
    setSelectedValue(value);
  };

  return (
    <>
      <RadioButton
        onChange={handleInputChange}
        label="first"
        value="first"
        checked={selectedValue === "first"}
      />
      <RadioButton onChange={handleInputChange} label="second" value="second" />
    </>
  );
};


text:
Q: What is the difference between content=no-referrer and rel=noreferrer <meta name="referrer" content="no-referrer">
<a href="http://example.com" rel="noreferrer">
What is the difference between above 2 statements?

A: meta no-referrer

The Referrer-Policy HTTP header controls how much referrer information (sent via the Referer header) should be included with requests.
no-referrer
The Referer header will be omitted entirely. No referrer information is sent along with requests.

Rel "noreferrer"

The noreferrer keyword for the rel attribute of the <a>, <area>, and <form> elements instructs the browser, when navigating to the target resource, to omit the Referer header and otherwise leak no referrer information — and additionally to behave as if the noopener keyword were also specified.
Link types:
noreferrer Prevents the browser, when navigating to another page, to send this page address, or any other value, as referrer via the Referer: HTTP header.
(In Firefox, before Firefox 37, this worked only in links found in pages. Links clicked in the UI, like "Open in a new tab" via the contextual menu, ignored this).


text:
Q: How can I create an utility class? I want to create a class with utility methods, for example
public class Util {

   public static void f (int i) {...}

   public static int g (int i, int j) {...}

}

Which is the best method to create an utility class?
Should I use a private constructor?
Should I make the utility class for abstract class?
Should I do nothing?

A: I would make the class final and every method would be static.
So the class cannot be extended and the methods can be called by Classname.methodName. If you add members, be sure that they work thread safe ;)

A: Making a class abstract sends a message to the readers of your code that you want users of your abstract class to subclass it. However, this is not what you want then to do: a utility class should not be subclassed.
Therefore, adding a private constructor is a better choice here. You should also make the class final to disallow subclassing of your utility class.

A: According to Joshua Bloch (Effective Java), you should use private constructor which always throws exception. That will finally discourage user to create instance of util class.
Marking class abstract is not recommended because is abstract suggests reader that class is designed for inheritance.

A: For a completely stateless utility class in Java, I suggest the class be declared public and final, and have a private constructor to prevent instantiation. The final keyword prevents sub-classing and can improve efficiency at runtime.
The class should contain all static methods and should not be declared abstract (as that would imply the class is not concrete and has to be implemented in some way).
The class should be given a name that corresponds to its set of provided utilities (or "Util" if the class is to provide a wide range of uncategorized utilities).
The class should not contain a nested class unless the nested class is to be a utility class as well (though this practice is potentially complex and hurts readability).
Methods in the class should have appropriate names.
Methods only used by the class itself should be private.
The class should not have any non-final/non-static class fields.
The class can also be statically imported by other classes to improve code readability (this depends on the complexity of the project however).
Example:
public final class ExampleUtilities {
    // Example Utility method
    public static int foo(int i, int j) {
        int val;

        //Do stuff

        return val;
    }

    // Example Utility method overloaded
    public static float foo(float i, float j) {
        float val;

        //Do stuff

        return val;
    }

    // Example Utility method calling private method
    public static long bar(int p) {
        return hid(p) * hid(p);
    }

    // Example private method
    private static long hid(int i) {
        return i * 2 + 1;
    }
}

Perhaps most importantly of all, the documentation for each method should be precise and descriptive. Chances are methods from this class will be used very often and its good to have high quality documentation to complement the code.


text:
Q: VBA to save worksheet with a specific name Hi  probably a simple answer but im new to VBA.
I have a worksheet in a workbook.  This worksheet has a specific reference in cell A1 which changes each time its used.  It is basically an order number and formatted 03 01 15.  The next will be 03 02 15, then 03 03 15 and so on.
What I want to do is to use VBA to save the sheet in a new workbook in my orders folder, and for the new workbook to be called the order number.
I can use the record macro function to get the basic VBA to copy the sheet, open a new workbook, paste the values and close the workbook, but im struggling with getting the name right.  Each new workbook will have a different name based on the order number.
Any help would be appriciated.

A: Export a Worksheet to a Folder
Sub ExportWorksheetToFolder()
    Const ProcTitle As String = "Export Worksheet to Folder"

    ' Define constants.

    Const DESTINATION_SUBFOLDER_NAME As String = "Orders"
    Const DESTINATION_FILE_NAME_ADDRESS As String = "A1"

    ' Reference the worksheet.

    Dim ws As Worksheet: Set ws = ActiveSheet
    ' Instead, improve with e.g.
    'Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")

    ' Build the destination file path ('dFilePath').

    ' Since we will be saving an unsaved workbook (file), by not supplying
    ' the file extension and the parameter for the FileFormat argument
    ' of the SaveAs method, the new workbook will be saved
    ' with the .xlsx extension (losing any code in it) or,
    ' for Office prior to version 2007, with the .xls extension.

    Dim pSep As String: pSep = Application.PathSeparator

    ' If the cell is blank, we don't have a name.
    Dim dBaseName As String
    dBaseName = CStr(ws.Range(DESTINATION_FILE_NAME_ADDRESS))
    If Len(dBaseName) = 0 Then
        MsgBox "Cell " & UCase(DESTINATION_FILE_NAME_ADDRESS) & " is blank.", _
            vbCritical, ProcTitle
        Exit Sub
    End If

    ' If the workbook has never been saved, its path is "".
    Dim wbPath As String: wbPath = ws.Parent.Path
    If Len(wbPath) = 0 Then
        MsgBox "You need to save the workbook to use this procedure.", _
            vbCritical, ProcTitle
        Exit Sub
    End If

    ' Create the subfolder if it doesn't exist.
    Dim dFolderPath As String: dFolderPath = wb.Path _
        & pSep & DESTINATION_SUBFOLDER_NAME & pSep
    If Len(Dir(dFolderPath, vbDirectory)) = 0 Then MkDir dFolderPath

    Dim dFilePath As String: dFilePath = dFolderPath & dBaseName

    ' Copy.

    ws.Copy ' copies the worksheet to a new workbook

    ' Save.

    Dim MsgString As String

    With Workbooks(Workbooks.Count) ' reference the new workbook
        Application.DisplayAlerts = False
        ' 1. save without macros ... without confirmation
        ' 2. overwrite existing file ... without confirmation
            On Error Resume Next
                .SaveAs dFilePath
                If Err.Number <> 0 Then ' invalid file name, file open...
                    MsgString = "Run-time error '" & Err.Number & "':" _
                        & vbLf & vbLf & Err.Description _
                        & vbLf & vbLf & "Could not save as '" & dFilePath & "'."
                End If
            On Error GoTo 0
        Application.DisplayAlerts = True
        .Close SaveChanges:=False
    End With

    ' Inform.

    If Len(MsgString) = 0 Then
        MsgBox "Worksheet exported.", vbInformation, ProcTitle
    Else
        MsgBox MsgString, vbCritical, ProcTitle
    End If

End Sub


text:
Q: Best practices for file storage across multiple services? I came to coclusion what in my system I often want to manipulate not over actual files, but over references and in some cases metha-information about files (size, different types of hashes, extensions, defferent tags, etc), but where to store it all? I mean, I can easily create service with contract above almost anything: be it MS SQL or even simple shared folder.
But what is best practices? Main benefactor I look for is - speed. File retrieval should be as fast as possible, whether it's 4gb or 200mb, and I don't realy know how fast will be shared folder above MS SQL.
So, I appreciate if you tell, how you solve this problem (which system do you use, frameworks) and what is advantages/disadvantages of your selected choise?
PS: I know it's too broad, but well, we are not machines so sometimes question don't have real, single, answer but just food for thoughts.

A: There is no single best practice to solve your problem, it basically depends on your exact use-case.
While deciding where and how to store your files you should address and consider few things and possibilities:

*

*Local File System
1.1. Do your files need to be accessible from N server instances, i.e. you have distributed system? If that's the case, Local File System storage is not an option.
1.2. Does the Read/Write speed of your hard drive suits your performance needs? You should think about drives which are best suited for file storage.

*Database
2.1. What's the average size of files you working on? There are different options to store files inside MS SQL database.
2.2. How strong is your database server? If you are having distributed environment, you should keep in mind that database load will be higher due to additional file storage management and handling.
2.3. There are plenty of research papers and posts related to this topic, here are few of them:

*

*To BLOB or Not To BLOB

*Storing BLOBs

*Cloud Storage (Amazon s3, Azure File storage, etc...)
3.1. How good is server's network bandwidth? You should be aware that the server will fetch file via network
3.2. Do you find the storage expenses suitable? There are different options, you should research what's the best for your use-case
Since your question is too broad, I just dropped few things to think about. Hopefully, this will give you slightly broader view of your particular problem.
Last but not least, meta data and storage reference should be stored inside database. You can even achieve (with good table architecture) possibility to have different files stored on a different locations (i.e. multiple servers) in a different way (e.g. LFS, Cloud)


text:
Q: VS 2010 unable to locate WP7 Resources Lately I have installed Windows Phone 7 developement tools and noticed that VS2010 unable to resolve the phone resources like styles and fonts. But Blend does load them all, it's bit annoying that all time get exception message on designer.
Can anyone suggest the solution please?

A: Have you tried to repair or reinstall Visual Studio, Silverlight 4 and Windows Phone 7 Developer Tools? I don't think rebooting or reinstalling WP7DT will help in this case.


text:
Q: Jersey 2.2.0 on Google App Engine. Error 404. jersey init. works locally though I am deploying my app using jersey 2.2.0 jars onto google app engine. I have been developing and running locally and it works well during local run/test.
I deployed to the google app engine, and I start getting Error: 404 erros for all resources. Checking google logs, at the first request it spits out the following

org.glassfish.jersey.server.ApplicationHandler initialize: Initiating Jersey application, version Jersey: 2.7 2014-03-12 18:11:31...

The jersey servlet spits out the following

I 09:27:38.889 org.glassfish.jersey.filter.LoggingFilter log: 1 * Server has received a request on thread Request EE25C261
  GET http://xxxx.appspot.com/service/users/test
  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
  Accept-Language: en-US,en;q=0.8
  Host: xxxxx.appspot.com
  User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36
  X-AppEngine-City: bangalore
  X-AppEngine-CityLatLong: 12.971599,77.594563
  X-AppEngine-Country: IN
  X-AppEngine-Region: ka

and then spits out the resource not found

I 09:41:15.094 org.glassfish.jersey.filter.LoggingFilter log: 3 * Server responded with a response on thread Request 9826AB68
   < 404

It also adds one more line which suggests

I 09:27:39.180 This request caused a new process to be started for your application, and thus caused your application code to be loaded for the first time. This request may thus take longer and use more CPU than a typical request for your application.

Now, all this works on my local testing but is only an issue when deployed to Google App Engine.
Here's my web.xml
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <servlet>
      <servlet-name>Jersey Web Application</servlet-name>
      <servlet-class>
        org.glassfish.jersey.servlet.ServletContainer
      </servlet-class>
      <init-param>
          <param-name>jersey.config.server.provider.packages</param-name>
<!--           Enter your Jersey resources to speed up initial Jersey loading
          You can separate the java packages using , -->
          <param-value>com.poolE.web.rest</param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>org.glassfish.jersey.filter.LoggingFilter</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
      <servlet-name>Jersey Web Application</servlet-name>
      <url-pattern>/service/*</url-pattern>
    </servlet-mapping>
    <system-properties>
        <property name="java.util.logging.config.file" value="WEB-INF/logging.properties" />
    </system-properties>
</web-app>

and my jersey class is
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.poole.web.jpa.EMFService;
import com.poole.web.jpa.Users;
import com.poole.web.jpa.model.User;

@Path("/users/")
public class UsersResource {

    private static final Logger log = Logger.getLogger(UsersResource.class.getName());

    @GET
    @Produces("application/json")
    @Path("test")
    public String info() {
        log.info("comes into test");
        return "Hello Jersey on Google App Engine";
    }

}

Any help will be appreciated. I am stuck in this frustrating problem of just plumbing it all together in GAE


text:
Q: EmailAddress DataAnnotation marking as valid on View but ModelState.IsValid = false? I'm using MVC5 and trying to validate a form.
When I insert an invalid email address on the field, it shows the error message

If I insert a@a (which is a valid email address), the front-end validation pass, but on back end, my ModelState shows an error on the E-mail field, telling that is invalid.
If I insert a@a.com, both validation sides pass!
Note: Great part of the other SO answers related to "email validation not working on MVC", the solution was to use the EmailAddress attribute, which i'm already using.
View
@using (Ajax.BeginForm("EnviarMensagemContato", "home", new AjaxOptions { HttpMethod = "POST", OnBegin = "showLoading", OnComplete = "showJsonModalMessage" }, new { @id = "contact-form" }))
{
    @Html.AntiForgeryToken()

            @Html.TextBoxFor(m => m.ContatoViewModel.Nome, new { @class = "form-control required", placeholder = "nome" })
            @Html.ValidationMessageFor(m => m.ContatoViewModel.Nome)

            @Html.TextBoxFor(m => m.ContatoViewModel.EmailAddress, new { @class = "form-control required", placeholder = "email" })
            @Html.ValidationMessageFor(m => m.ContatoViewModel.EmailAddress)

            @Html.TextAreaFor(m => m.ContatoViewModel.Mensagem, 4, 4, new { @class = "form-control required", placeholder = "mensagem" })
            @Html.ValidationMessageFor(m => m.ContatoViewModel.Mensagem)

    <input type="submit" value="enviar" id="enviar-mensagem" class="btn btn-default" />

}

Model
public class ContatoViewModel
{
    [Required(ErrorMessage="campo obrigatório"),
    Display(Name = "nome")]
    public String Nome { get; set; }

    [Required(ErrorMessage = "campo obrigatório"),
    Display(Name = "nome"), MaxLength(254,ErrorMessage="email inválido"),
    EmailAddress(ErrorMessage="email inválido")]
    public String EmailAddress { get; set; }

    [Required(ErrorMessage = "campo obrigatório"),
    Display(Name = "nome"), MaxLength(500, ErrorMessage = "maximo de 500 caracteres")]
    public String Mensagem { get; set; }
}

Controller
public JsonResult EnviarMensagemContato(ModelContainer model)
{
    try
    {
        if (ModelState.IsValid)
        {
            //zalgo
        }
    }
}

A: I presume you're using the default jQuery Validation library in an ASP.NET MVC project. If that's the case, the problem resides in the fact that the regular expression used to validate an email is different in the jQuery Validation library and the EmailAddressAttribute, with the attribute being more strict. My suggestion would be to override the jQuery Validation email method as follows:
$.validator.methods.email = function (value, element) {
     return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/.test(value);
}

The regular expression is taken directly from the EmailAddressAttribute source code here. If you prefer to allow emails without a TLD (like user@localhost), you could write your own attribute as discussed in this answer and put the regular expression from the jQuery Validation library. This way you would have the same validation result client and server side.

A:     [Required(ErrorMessage = "The Email address is required")]
    [RegularExpression(RegularExpression.RegexEmail, ErrorMessage = "Invalid Email address")]
    public string Email { get; set; }

In RegularExpression.cs file include
    ///
    /// Regular expression for email
    ///
    public const string RegexEmail = @"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}";

A: I don't think a@a is a valid email address, or if it is, I don't think the Attribute takes it into account.
Having tested this, if I enter a@a I get client side validation error. I don't if I enter a@a.a
If you need this kind of email to be valid you can probably use your own regex expression.

A: If you need fine grained control and have your code transparent in front of you, i recommend you dont rely on HTML helpers to draw your controls and perform the validation on client side and server side for you.
I would use the following regular exp as mvc model attribute.
[Required]
[RegularExpression(BusinessRules.Email,ErrorMessage = Messages.EmailNotValid)]
public string LoginEmail { get; set; }

Where BusinessRules.Email is
public const string Email = "^[\\w!#$%&'*+\\-/=?\\^_`{|}~]+(\\.[\\w!#$%&'*+\\-/=?\\^_`{|}~]+)*@((([\\-\\w]+\\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\\.){3}[0-9]{1,3}))$";

On the client side validation, you can only make sure that email is not empty if you want. At the end, client side validation is not as important as server side validation since it can be easily spoofed.

A: It is good practice to represent you data annotations one at a time like the following code, this may also help with your error.
    [Required(ErrorMessage="campo obrigatório")]
    [Display(Name = "nome")]
    public String Nome { get; set; }

A: There are two separate control points. If you use the correct comparison once, you don't have to check the value again for later usage. Then, using regular expression will solve the problem.


text:
Q: What is the ratio of $\tan 37° / \tan 54°$? I was asked this question in my class test with the following choices.
Ratio of $\tan 37° / \tan 54°$
$ 1) 3^2 : 4^2 $
$ 2) 4 : 3$
$ 3) \sqrt 3 : 2 $
$ 4) \sqrt 3 : 1 $
I was not given any tables. How to find the values?

A: Whoever wrote this class test is being very unhelpful. They actually want the ratio of
$$\frac{\tan(36.86989765...)}{\tan(53.13010235...)}$$
And that is $$\frac {\tan(\arctan(\frac34))}{\tan(\arctan(\frac43))}=\frac {9}{16}$$
So the ratio is $3^2:4^2$


text:
Q: Change datepicker format and save to database in laravel I have a log_leave table like below
    id |  name   | request_day_leave | start_leave | end_leave
     1   Michael            5          2019-04-01    2019-04-05
     2   Johan              3          2019-04-08    2019-04-011

I want to change datepicker show in blade view form, so when the user click date, it shows dd-mm-yy. And when user see log report, it shows like below
     id |  name   | request_day_leave | Leave Start | Leave End
     1   Michael            5           01-04-2019    05-04-2019
     2   Johan              3           08-04-2019    11-04-2019

I have changed datepicker format in form blade view, but when I need to save the date to database, it's showing error message like below
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '08-04-2019' for column 'from_date' at row 1

I've tried using mutator in the model, and added a new value into config/app.php but it's still got the same error message
Here's the config/app code
'date_format' => 'd/m/Y',
'date_format_js' => 'dd/mm/yy'

Here's datepicker code
 $('#from').datepicker({
    showOnFocus: false,
    showTrigger: '#calImg',
    beforeShowDay: noWeekendsOrHolidays,
    numberOfMonths: 1,
    dateFormat: 'dd-mm-yy'
 });
    $('#to').datepicker({
        showOnFocus: false,
        showTrigger: '#calImg',
        beforeShowDay: noWeekendsOrHolidays,
        pickerClass: 'noPrevNext',
        numberOfMonths: 1,
        dateFormat: 'dd-mm-yy'
 });
});

Here's the code in Log Leave model
class LogLeave extends Model
{
//
protected $table = 'log_leave';

public function setEntryDateAttribute($input)
{
    $this->attributes['start_leave'] =
    Carbon::createFromFormat(config('app.date_format'), $input)->format('dd-mm-yy');
    $this->attributes['end_leave'] =
    Carbon::createFromFormat(config('app.date_format'), $input)->format('dd-mm-yy');
}

}
How to fix this issue ?
Thank you

A: You should convert the format to yyyy-mm-dd when storing in database
public function setEntryDateAttribute($input)
{
    $this->attributes['start_leave'] =
    Carbon::createFromFormat(config('app.date_format'), $input)->format('Y-m-d');
    //should be format('Y-m-d') not format('dd-mm-yy')

    $this->attributes['end_leave'] =
    Carbon::createFromFormat(config('app.date_format'), $input)->format('Y-m-d');
    //same applies here
}

And then use accessors to format the value to dd-mm-yyyy format
public function getStartLeaveAttribute($value)
{
    return Carbon::parse($value)->format('d-m-Y');
}

public function getEndLeaveAttribute($value)
{
    return Carbon::parse($value)->format('d-m-Y');
}

A: I think again format() is not required
Carbon::createFromFormat('d/m/Y',$input);

or
Carbon::createFromFormat(config('app.date_format'), $input);


text:
Q: How do I get a secure URL host for my Facebook app? I decided today that I wanted to learn JavaScript and create my own Facebook game app.  I registered as a developer, but I do not have a secure URL host to manage my app.  I am coming from MATLAB and Swift, so I am new to this whole URL hosting thing.  When I typed in google.com/ the app brought me to the Google homepage, and typing in facebook.com/ and permutations of it doesn't work.  So, how can I get a secure hosting URL?  I apologize if this is very simple, but I don't know how to do it; thank you!

A: Google App Engine does work.  Thanks to everyone who commented!


text:
Q: How to print spaces from inside a variable in jinja2 I am trying to print a variable number of spaces stored in a variable in jinja2, but jinja is escaping the contents of the variable. So when I store &nbsp in the variable it gets expanded to &nbsp thus printing the characters &nbsp on the page instead of the spaces.
Here is my code:
{% macro show_message(parent_id,count) %}
    {% set clist = get_message(post.id,parent_id) %}
    {% set countr = count + 1 %}
    {% set prefix = '-'*countr %}
    {% set prefix2 = "&nbsp"*countr %}
    {% if clist is defined %}
        {% for c in clist %}
            {{ prefix2 }} Author: {{ get_author(c.user_id) }}

            {{ prefix }}
            {{ c.message }}

            {{ show_message(c.id,countr) }}
        {% endfor %}
    {% endif %}
{% endmacro %}

Does anyone have a clue how to make this work?
Thanks :)

A: I tried Blender's way with
{{ " "|safe*10 }}

it'll generate 10 spaces

A: Mark it as safe with the |safe filter to prevent auto-escaping:
{{ prefix2|safe }}

You also need to include the semicolon at the end of each entity:
{% set prefix2 = " "*countr %}
                       ^


text:
Q: Does GSVD implement all linear multivariate techniques? I came across the article by Hervé Abdi about generalized SVD. The author mentioned:

The generalized SVD (GSVD) decomposes a rectangular matrix and takes into account constraints imposed on the rows and the columns of the matrix. The GSVD gives a weighted generalized least square estimate of a given matrix by a lower rank matrix and therefore, with an adequate choice of the constraints, the GSVD implements all linear multivariate techniques (e.g., canonical correlation, linear discriminant analysis, correspondence analysis, PLS-regression).

I'm wondering how the GSVD is related to all linear multivariate techniques (e.g., canonical correlation, linear discriminant analysis, correspondence analysis, PLS-regression).

A: Section 4.1 of the article describes what the matrices, M and W, have to be for the generalized SVD to yield results comparable to correspondence analysis.  The author also cites his reference #3 to explain how the generalized SVD can yield results comparable to the other multivariate methods mentioned.


text:
Q: How do I avoid duplicate/similar mod_rewrite rules? I have a number of URIs that read as follows;

*

*http://www.domain.com/index.php?route=information/information&information_id=2 (about)

*http://www.domain.com/index.php?route=information/information&information_id=4 (help)

*http://www.domain.com/index.php?route=information/information&information_id=7 (contact)

*....

Is there a way I could avoid writing explicit but similar rewrite rules?
EXAMPLE
 RewriteRule    ^contact$    index.php?route=information/information&information_id=2    [NC,L]    # About

 RewriteRule    ^help$    index.php?route=information/information&information_id=4    [NC,L]    # Help

A: Lots of possibilities.  Easiest might be something like this:
^(.*)$ index.php?route=information/information&information_id=$1

Then handle the information_id string in your index.php.  Make sure it only allows acceptable values and 404s everything else.
Or to be more restrictive at the mod_rewrite level:
^(contact|help|foo)$ index.php?route=information/information&information_id=$1

A: If you have more than a handful of pages to rewrite, the key is a to have a single, simple rewrite rule combined with logic in your index page to serve the correct content based on the URL requested.
Take a look at the .htaccess and index.php for any popular CMS which supports url rewriting and you will find what you seek.


text:
Q: Tremulous with unlimited building: Should aliens focus on destroying nodes or repeaters after destroying the human reactor? When the alien team destroys the human reactor, and there is a limited time before humans rebuild, what's a better tactic - focusing on destroying nodes or repeaters?
By killing nodes, aliens have a chance of winning right away, and low node count slows down spawning humans, making it harder for them to defend.
By killing repeaters, aliens make surrounding human buildings non-functional, even after humans build a new reactor, which makes it easy to destroy later, but spawned humans can rebuild the repeaters and defend the other buildings.


text:
Q: R package dependency hell. How to break out of it? An trying to install the package 'gsbufn' from CRAN to solve a dependency, but it depends on 'proto' which cannot be found during installation:

* installing *source* package 'gsubfn' ...
** package 'gsubfn' successfully unpacked and MD5 sums checked
** R
** demo
** inst
** byte-compile and prepare package for lazy loading
** help
*** installing help indices
  converting help for package 'gsubfn'
    finding HTML links ... done
    as.function.formula                     html
    fn                                      html
    gsubfn-package                          html
    gsubfn                                  html
    match.funfn                             html
    read.pattern                            html
    strapply                                html
** building package indices
** installing vignettes
** testing if installed package can be loaded
Error : package 'proto' required by 'gsubfn' could not be found
Error: loading failed
Execution halted
ERROR: loading failed
* removing '~/R/x86_64-redhat-linux-gnu-library/3.3/gsubfn'

However, 'proto' is installed and loads fine using library() and/or require(). My .libPaths() are correct, consistent and I can see the proto files on the filesystem.
Anyone know why 'gsubfn' is steadfastly refusing to acknowledge the existence of 'proto' and how to force it to behave, please?
This is for R 3.3.3.
> library('proto')
> sessionInfo()
R version 3.3.3 (2017-03-06)
Platform: x86_64-redhat-linux-gnu (64-bit)
Running under: CentOS release 6.8 (Final)

locale:
 [1] LC_CTYPE=en_GB.utf8       LC_NUMERIC=C
 [3] LC_TIME=en_GB.utf8        LC_COLLATE=en_GB.utf8
 [5] LC_MONETARY=en_GB.utf8    LC_MESSAGES=en_GB.utf8
 [7] LC_PAPER=en_GB.utf8       LC_NAME=C
 [9] LC_ADDRESS=C              LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_GB.utf8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] proto_1.0.0

loaded via a namespace (and not attached):
[1] tools_3.3.3 tcltk_3.3.3
> .libPaths()
[1] "/cluster/gjb_lab/username/R/x86_64-redhat-linux-gnu-library/3.3"
[2] "/cluster/gjb_lab/software/centos6.3/opt/R/3.3.3/lib64/R/library"
[3] "/usr/lib64/R/library"


text:
Q: FullCalendar Scheduler, problem with fullcalendar.print.css Versions :

FullCalendar: 3.9.0
Scheduler : 1.9.4

Browser view :
>
Print view :

fullcalendar.print.css is correctly included in HEAD of html :
<link rel="stylesheet" media="print" href="/assets/fullcalendar.print.css">

Content of fullcalendar.print.css :
/*********Here is custom css code in fullcalendar.print.css **************/

.main-header, .main-sidebar, #messages, .content-header, .cretrea, .validation, .main-footer, .control-sidebar, .modal, .formcheck, .nav, .btn_submit_global_form{
  display:none;
}
.table-striped > tbody > tr:nth-of-type(odd) {
    background-color: #f9f9f9;
}
.table > thead > tr > th, .table > thead > tr > td, .table > tbody > tr > th, .table > tbody > tr > td, .table > tfoot > tr > th, .table > tfoot > tr > td {
    padding: 8px;
    line-height: 1.428571429;
    vertical-align: top;
    border-top: 1px solid #ddd;
}

th {
    text-align: left;
}
.fc {
  max-width: 100% !important; }

    /* Global Event Restyling
    --------------------------------------------------------------------------------------------------*/
    .fc-event {
      page-break-inside: avoid; }

    .fc-cell-text a{
      page-break-inside: avoid; }

Update1 : I post Html code, All html in div#calendar is generated by fullcalendar.js, I use timelineMonth mode

<button type="button" class="fc-today-button fc-button fc-state-default fc-corner-left fc-corner-right">Aujourd'hui</button>
<button type="button" class="fc-prev-button fc-button fc-state-default fc-corner-left" aria-label="prev"></button><button type="button" class="fc-next-button fc-button fc-state-default fc-corner-right" aria-label="next"></button>

<button type="button" class="fc-timelineDay-button fc-button fc-state-default fc-corner-left">Jour</button><button type="button" class="fc-timelineWeek-button fc-button fc-state-default">Semaine</button><button type="button" class="fc-timelineMonth-button fc-button fc-state-default fc-corner-right fc-state-active">Mois</button>

août 2018

<colgroup><col class="fc-main-col"></colgroup>

Services/Dossiers

<colgroup><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col></colgroup>

me
1

je
2

ve
3

sa
4

di
5

lu
6

ma
7

me
8

je
9

ve
10

sa
11

di
12

lu
13

ma
14

me
15

je
16

ve
17

sa
18

di
19

lu
20

ma
21

me
22

je
23

ve
24

sa
25

di
26

lu
27

ma
28

me
29

je
30

ve
31

<colgroup><col class="fc-main-col"></colgroup>

AEMO37 - AEMO Renforcé

 BRIZIOU Océane

AEMO37 - AEMO

 BRIZIOU Océane

15:45Suspend de P.E.C.(S)

<colgroup><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col style="width: 44px;"><col></colgroup>

Question :
There is no background color for a.fc-event and div.fc-bgevent even I choose  "Background graphic" before printing.


text:
Q: wp_star_rating() - Adding a 5 star rating system to theme My goal is to add a 5 star rating system to my theme.  I read that there's a function wp_star_rating in wp-admin/includes/template.php on line 2121, that I've been trying to use for the ratings.  I am using WP 4.0.  Just using wp_star_rating() in my theme's content.php alone returns:

Fatal error: Call to undefined function wp_star_rating() in [LOCALHOST URI]\content.php on line 12

In my theme's content.php, I'm trying to use wp_star_rating().  If I redeclare wp_star_rating() in my theme's functions.php the content works but when I go to my admin panel I get the error (obviously) that I can't redeclare the function.
Besides redeclaring the function I also tried (in my theme's functions.php):

if( !function_exists('wp_star_rating') ){
    require admin_url() . 'includes/template.php';
}
I'm aware this doesn't work because it doesn't like the full url.
The only thing I tried that partially worked (displayed on front end but threw error on backend):
include '/wp-admin/includes/template.php';
So the question is:
How can I use wp_star_rating() in my theme's content.php file?  Or how do I include it in my theme?
I already have everything else enqueI'm sure there's a simple solution I'm missing but after a few days of searching I have not found much help.  I really can't afford spending all of my time on this issue.

A: Instead of redefining wp_star_rating() for the front end, you should be able to just use the built-in function.
From the Codex page for wp_star_rating():

In order to use this function on the front end, your template must include the wp-admin/includes/template.php file and enqueue the appropriate dashicons CSS font information.

(emphasis mine)
A code sample is also provided in the Notes section of the Codex page.
Edit
If you're getting Fatal error: Call to undefined function wp_star_rating()  messages, that means that you have not included wp-admin/includes/template.php in your file. Try adding this snippet somewhere prior to your call to wp_star_rating():
require_once( ABSPATH . 'wp-admin/includes/template.php' );

That should allow you to use wp_star_rating() in your front-end code.


text:
Q: Qt way to get libraries path I have several QPlugins (shared objects) that I install {CMAKE_PREFIX}/lib/<appname>,  how can I find out this path at runtime to load the plugins? Note that the CMAKE_PREFIX user user settable.

A: If these plugins are part of your application project and you are looking for a build time answer, you can generate a config.h file containing that path.
You can use CMake's configure_file command for that.