text:
Q: How to convert one of my columns from 226 FACTORS? New to programming in R. I have a dataset in which one column is or should be numeric since it has %values! I need to plot that data using ggplot2 but I can't since I'm pretty new with this.
Summary:
DataSet = 245 Rows, 6 columns.
I have spent  5 hours searching for the right code. But posts seem to be to advance for my understanding.
data.frame':    245 obs. of  6 variables:
 $ location : Factor w/ 8 levels "site01","site02",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ coralType: Factor w/ 5 levels "blue corals",..: 1 1 1 1 1 1 1 1 2 2 ...
 $ longitude: num  144 144 144 144 144 ...
 $ latitude : num  -11.8 -11.8 -11.8 -11.8 -11.8 ...
 $ year     : int  2010 2011 2012 2013 2014 2015 2016 2017 2011 2012 ...
 $ value    : Factor w/ 223 levels "10.01%","10.23%",..: 113 123 166 168 184 193 196 200 43 44 ...

See that df$value? That is my issue I need it to be numeric so I can plot it, right now I can't! Simply put $value needs to be numeric. Would really appreciate if any of you R veterans can help me out?!

A: You need to remove the percentage symbol and save it as a numeric value.
df <- data.frame(value = paste(1:100, "%", sep = ""))
df$value <- as.numeric(sub("%", "", df$value))


text:
Q: BizTalk 2013r2 - C# String Replace in Expression Editor I'm currently using an expression editor to build an XML payload within my orchestration, but I need to swap out any ampersands for the XML based escape character (&).
The unmodified XML is;
<value>" + StudentCanonical(Student_Feed.StudentCanonicalProperty.school_name) + @"</value>

I've tried adding the below, but I get an 'illegal dotted name' error on the .Replace method;
<value>" + StudentCanonical(Student_Feed.StudentCanonicalProperty.school_name).Replace("&","&") + @"</value>

Note; StudentCanonicalProperty.school_name) is a promoted property referenced from another class (it's a directly received message).
I believe this may be related to the field being Promoted and not Distinguished.
If this is the case, can I make the field both distinguished AND promoted, or is there an alternate approach?
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check for optional URL params using regex? I've been trying to use regex to determine if the current URL matches to either http://test.com or http://test.com/page/[0-9]+
I've been looking at countless of tutorials but couldn't find any that tackled anything even remotely such as this. I've tried just about everything but I'm just too inexperienced with regex to get it going.
Thank you for your help and I hope you could point me in the right direction.

A: You can try
"http://test\.com(?:/page/[0-9]+)?"


text:
Q: Unstack and merge based on column value as key I get an output from my grep command as below.
 grep -r GFD . | cut -d: -f2
out_GFD_994     NSE_FO_BHP_1703   -9425     6800       361.45      11900     359.96      5100      0.34%    6137085.0  -15.36
out_GFD_994     NSE_FO_BHP_1704   15651     -6800      360.38      6800      362.04      13600     26.66%   7374430.0  21.22
out_GFD_994     NSE_FO_TLS_1703        -4996     2000       603.57      5000      602.68      3000      0.46%    4825900.0  -10.35
out_GFD_994     NSE_FO_TLS_1704        4480      -2000      605.71      3000      606.44      5000      29.62%   4849350.0  9.24
out_GFD_994     NSE_FO_MQG_1703          -11717    -20000     148.64      50000     148.64      70000     0.46%    17837250.0  -6.57
out_GFD_994     NSE_FO_MQG_1704          17213     20000      149.29      75000     149.39      55000     36.11%   19413500.0  8.87
out_GFD_Part2                        NSE_FO_BHP_1703   -17597    -20000     0           0         39.25       20000     0.07%    785000.0  -224.17
out_GFD_Part2                        NSE_FO_BHP_1704   14481     20000      39.6        20000     0           0         1.38%    792000.0  182.84
out_GFD_Part2                        NSE_FO_TLS_1703         28312     1200       643.93      16800     645.52      15600     0.54%    20888220.0  13.55
out_GFD_Part2                        NSE_FO_TLS_1704         -23813    -1200      647.91      16800     646.87      18000     34.11%   22528620.0  -10.57
out_GFD_Part2                        NSE_FO_MQG_1703   -133456    8800       1029.33     25300     1025.86     16500     0.55%    42968915.0  -31.06 unhedged
out_GFD_Part2                        NSE_FO_MQG_1704   141534    -7700      1031.26     33000     1033.85     40700     49.62%   76109605.0  18.60

I need a purge/merge/unstack (whatever word sounds appropriate) according to 2nd column value as key.
So that output data transforms to (summation of corresponding values)
out_GFD_994     out_GFD_Part2    NSE_FO_BHP_1703   -9425-17597     6800-20000       361.45      11900     359.96      5100      0.34%    6137085.0  -15.36
out_GFD_994     out_GFD_Part2    NSE_FO_BHP_1704   15651+14481     -6800+20000      360.38      6800      362.04      13600     26.66%   7374430.0  21.22
out_GFD_994     out_GFD_Part2    NSE_FO_TLS_1703        -4996+28312     2000+1200       603.57      5000      602.68      3000      0.46%    4825900.0  -10.35
out_GFD_994     out_GFD_Part2    NSE_FO_TLS_1704        4480-23813     -2000-1200      605.71      3000      606.44      5000      29.62%   4849350.0  9.24
out_GFD_994     out_GFD_Part2    NSE_FO_MQG_1703          -11717-133456    -20000+8800     148.64      50000     148.64      70000     0.46%    17837250.0  -6.57
out_GFD_994     out_GFD_Part2    NSE_FO_MQG_1704          17213+141534     20000-7700      149.29      75000     149.39      55000     36.11%   19413500.0  8.87

                                       (only 2 columns shown in expected output format)

I can give names to columns and load it as pandas dataframe if that paves the way to solve this problem.
Update 1:
I would work on just 5 columns for now and have loaded it into my pandas dataframe as below
>>> df
      grep_string              key    val1   val2     val3
0     out_GFD_994  NSE_FO_BHP_1703   -9425   6800   361.45
1     out_GFD_994  NSE_FO_BHP_1704   15651  -6800   360.38
2     out_GFD_994  NSE_FO_TLS_1703   -4996   2000   603.57
3     out_GFD_994  NSE_FO_TLS_1704    4480  -2000   605.71
4     out_GFD_994  NSE_FO_MQG_1703  -11717 -20000   148.64
5     out_GFD_994  NSE_FO_MQG_1704   17213  20000   149.29
6   out_GFD_Part2  NSE_FO_BHP_1703  -17597 -20000     0.00
7   out_GFD_Part2  NSE_FO_BHP_1704   14481  20000    39.60
8   out_GFD_Part2  NSE_FO_TLS_1703   28312   1200   643.93
9   out_GFD_Part2  NSE_FO_TLS_1704  -23813  -1200   647.91
10  out_GFD_Part2  NSE_FO_MQG_1703 -133456   8800  1029.33
11  out_GFD_Part2  NSE_FO_MQG_1704  141534  -7700  1031.26

How do I do a  (summation) merge using key column
Update 2:
The summed column values are to be added to a logfile as below:
NSE_FO_BHP_1703_MAXLONGPOS = 200000
NSE_FO_BHP_1703_MAXSHORTPOS = 200000
NSE_FO_BHP_1703_MAXLONGEXPOSURE = 250000
NSE_FO_BHP_1703_MAXSHORTEXPOSURE = 250000
NSE_FO_BHP_1704_MAXLONGPOS = 200000
NSE_FO_BHP_1704_MAXSHORTPOS = 200000
NSE_FO_BHP_1704_MAXLONGEXPOSURE = 250000
NSE_FO_BHP_1704_MAXSHORTEXPOSURE = 250000
NSE_FO_TLS_1703_MAXLONGPOS = 100000
NSE_FO_TLS_1703_MAXSHORTPOS = 100000
NSE_FO_TLS_1703_MAXLONGEXPOSURE = 200000
NSE_FO_TLS_1703_MAXSHORTEXPOSURE = 200000
NSE_FO_TLS_1704_MAXLONGPOS = 100000
NSE_FO_TLS_1704_MAXSHORTPOS = 100000
NSE_FO_TLS_1704_MAXLONGEXPOSURE = 200000
NSE_FO_TLS_1704_MAXSHORTEXPOSURE = 200000
NSE_FO_MQG_1703_MAXLONGPOS = 300000
NSE_FO_MQG_1703_MAXSHORTPOS = 300000
NSE_FO_MQG_1703_MAXLONGEXPOSURE = 400000
NSE_FO_MQG_1703_MAXSHORTEXPOSURE = 400000
NSE_FO_DEF_1704_MAXLONGPOS = 300000
NSE_FO_MQG_1704_MAXSHORTPOS = 300000
NSE_FO_MQG_1704_MAXLONGEXPOSURE = 400000
NSE_FO_MQG_1704_MAXSHORTEXPOSURE = 400000

Can we add summed output value we get in df (say column d )to be added/subtracted to the above file by mapping it to substring. example we get -13200 in column d.  We have NSE_FO_BHP_1703_MAXLONGPOS = 200000. In the a file, change this to 213200 and change NSE_FO_BHP_1703_MAXSHORTPOS to 186800. Change the MAXLONGEXPOSURE and MAXSHORTEXPOSURE to 263200 and 236800 .

A: You can use groupby with agg by dict created by dict comprehension. Last create from first column another 2 by split:
print (df)
               0                1       2      3        4      5        6   \
0     out_GFD_994  NSE_FO_BHP_1703   -9425   6800   361.45  11900   359.96
1     out_GFD_994  NSE_FO_BHP_1704   15651  -6800   360.38   6800   362.04
2     out_GFD_994  NSE_FO_TLS_1703   -4996   2000   603.57   5000   602.68
3     out_GFD_994  NSE_FO_TLS_1704    4480  -2000   605.71   3000   606.44
4     out_GFD_994  NSE_FO_MQG_1703  -11717 -20000   148.64  50000   148.64
5     out_GFD_994  NSE_FO_MQG_1704   17213  20000   149.29  75000   149.39
6   out_GFD_Part2  NSE_FO_BHP_1703  -17597 -20000     0.00      0    39.25
7   out_GFD_Part2  NSE_FO_BHP_1704   14481  20000    39.60  20000     0.00
8   out_GFD_Part2  NSE_FO_TLS_1703   28312   1200   643.93  16800   645.52
9   out_GFD_Part2  NSE_FO_TLS_1704  -23813  -1200   647.91  16800   646.87
10  out_GFD_Part2  NSE_FO_MQG_1703 -133456   8800  1029.33  25300  1025.86
11  out_GFD_Part2  NSE_FO_MQG_1704  141534  -7700  1031.26  33000  1033.85

       7       8           9       10
0    5100   0.34%   6137085.0  -15.36
1   13600  26.66%   7374430.0   21.22
2    3000   0.46%   4825900.0  -10.35
3    5000  29.62%   4849350.0    9.24
4   70000   0.46%  17837250.0   -6.57
5   55000  36.11%  19413500.0    8.87
6   20000   0.07%    785000.0 -224.17
7       0   1.38%    792000.0  182.84
8   15600   0.54%  20888220.0   13.55
9   18000  34.11%  22528620.0  -10.57
10  16500   0.55%  42968915.0  -31.06
11  40700  49.62%  76109605.0   18.60

#sum all columns without first,second and 9 column with percentage
d = {x:'sum' for x in df if not x in [0,1,8]}
#add custom function for first column
d.update({0:'|'.join})
print (d)
{0: <built-in method join of str object at 0x0000000001180AE8>, 2: 'sum',
 3: 'sum', 4: 'sum', 5: 'sum', 6: 'sum', 7: 'sum', 9: 'sum', 10: 'sum'}

df = df.groupby(1).agg(d).reset_index()
df[[-2,-1]] = df.pop(0).str.split('|', expand=True)
#change order of columns
df = df.sort_index(axis=1)
#reset column names to  default (0,1...)
df.columns = np.arange(len(df.columns))
print (df)
            0              1                2       3      4        5   \
0  out_GFD_994  out_GFD_Part2  NSE_FO_BHP_1703  -27022 -13200   361.45
1  out_GFD_994  out_GFD_Part2  NSE_FO_BHP_1704   30132  13200   399.98
2  out_GFD_994  out_GFD_Part2  NSE_FO_MQG_1703 -145173 -11200  1177.97
3  out_GFD_994  out_GFD_Part2  NSE_FO_MQG_1704  158747  12300  1180.55
4  out_GFD_994  out_GFD_Part2  NSE_FO_TLS_1703   23316   3200  1247.50
5  out_GFD_994  out_GFD_Part2  NSE_FO_TLS_1704  -19333  -3200  1253.62

       6        7      8           9       10
0   11900   399.21  25100   6922085.0 -239.53
1   26800   362.04  13600   8166430.0  204.06
2   75300  1174.50  86500  60806165.0  -37.63
3  108000  1183.24  95700  95523105.0   27.47
4   21800  1248.20  18600  25714120.0    3.20
5   19800  1253.31  23000  27377970.0   -1.33

Solution with custom column names:
df.columns = list('abcdefghijk')
print (df)
                a                b       c      d        e      f        g  \
0     out_GFD_994  NSE_FO_BHP_1703   -9425   6800   361.45  11900   359.96
1     out_GFD_994  NSE_FO_BHP_1704   15651  -6800   360.38   6800   362.04
2     out_GFD_994  NSE_FO_TLS_1703   -4996   2000   603.57   5000   602.68
3     out_GFD_994  NSE_FO_TLS_1704    4480  -2000   605.71   3000   606.44
4     out_GFD_994  NSE_FO_MQG_1703  -11717 -20000   148.64  50000   148.64
5     out_GFD_994  NSE_FO_MQG_1704   17213  20000   149.29  75000   149.39
6   out_GFD_Part2  NSE_FO_BHP_1703  -17597 -20000     0.00      0    39.25
7   out_GFD_Part2  NSE_FO_BHP_1704   14481  20000    39.60  20000     0.00
8   out_GFD_Part2  NSE_FO_TLS_1703   28312   1200   643.93  16800   645.52
9   out_GFD_Part2  NSE_FO_TLS_1704  -23813  -1200   647.91  16800   646.87
10  out_GFD_Part2  NSE_FO_MQG_1703 -133456   8800  1029.33  25300  1025.86
11  out_GFD_Part2  NSE_FO_MQG_1704  141534  -7700  1031.26  33000  1033.85

        h       i           j       k
0    5100   0.34%   6137085.0  -15.36
1   13600  26.66%   7374430.0   21.22
2    3000   0.46%   4825900.0  -10.35
3    5000  29.62%   4849350.0    9.24
4   70000   0.46%  17837250.0   -6.57
5   55000  36.11%  19413500.0    8.87
6   20000   0.07%    785000.0 -224.17
7       0   1.38%    792000.0  182.84
8   15600   0.54%  20888220.0   13.55
9   18000  34.11%  22528620.0  -10.57
10  16500   0.55%  42968915.0  -31.06
11  40700  49.62%  76109605.0   18.60

d = {x:'sum' for x in df if not x in ['a','b', 'i']}
#add custom function for first column
d.update({'a':'|'.join})
print (d)
{'e': 'sum', 'k': 'sum', 'a': <built-in method join of str object at 0x0000000001180AE8>,
'f': 'sum', 'd': 'sum', 'g': 'sum', 'j': 'sum', 'c': 'sum', 'h': 'sum'}
df = df.groupby('b').agg(d).reset_index()
df1 = df.pop('a').str.split('|', expand=True)
df1.columns = ['out_' + str(x) for x in df1.columns]
df = pd.concat([df1, df],axis=1)
print (df)
         out_0          out_1                b        e       k       f  \
0  out_GFD_994  out_GFD_Part2  NSE_FO_BHP_1703   361.45 -239.53   11900
1  out_GFD_994  out_GFD_Part2  NSE_FO_BHP_1704   399.98  204.06   26800
2  out_GFD_994  out_GFD_Part2  NSE_FO_MQG_1703  1177.97  -37.63   75300
3  out_GFD_994  out_GFD_Part2  NSE_FO_MQG_1704  1180.55   27.47  108000
4  out_GFD_994  out_GFD_Part2  NSE_FO_TLS_1703  1247.50    3.20   21800
5  out_GFD_994  out_GFD_Part2  NSE_FO_TLS_1704  1253.62   -1.33   19800

       d        g           j       c      h
0 -13200   399.21   6922085.0  -27022  25100
1  13200   362.04   8166430.0   30132  13600
2 -11200  1174.50  60806165.0 -145173  86500
3  12300  1183.24  95523105.0  158747  95700
4   3200  1248.20  25714120.0   23316  18600
5  -3200  1253.31  27377970.0  -19333  23000


text:
Q: How does persistent mapped buffers work in OpenGL? In OpenGL 4.4 there was a nice extension added: ARB_buffer_storage
How does persistent buffers work (or might work) - using MAP_COHERENT_BIT and MAP_PERSISTENT_BIT set ?

*

*Is there some special intermediate buffer?

*Why it can be usually faster than normal mapped buffers?


text:
Q: Is there a way to export a custom Menu containing macro in Excel? Currently, I am working on a project using the VBA language on Excel, I have coded some macros and userforms, and to facilitate the exploitation for user, I customize the ribbon by integrating a new menu with the features of macros coded via VBA.
On my session, the program works well, however, when another user opens the file on his session, first the menu is not displayed and it is no longer available, I tried to export the menu, then I import it in the user's Excel file but unfortunately the result is negative. I would like to know if someone could help me solve this problem.


text:
Q: Print with lpr to userid protected network printer How can I print from the command line (e.g., with << lpr >>) to a network printer that requires a user id?
When I use the printer from an application, a dialog box requests my user id and a password.  There is no password, I give it my user id and it prints.
I've tried using the -U option to lpr, but this doesn't work.
Doing this from a Macbook.


text:
Q: Use Automapper to hide database primary key/ID (convert member with ValueConverter) I am trying to hide the real Ids of the objects in a database using Automapper's value converters, however they are not called when projecting one to the other.
Nothing special, I would like to use Hashids to convert the int ID to a random string ID (DB->DTO) and  vice versa. I want to do this for every object and every ID, but instead of my converter getting called the id's in the database simply get converted strings (so 1 would become "1" instead of for example "sd2+a!F").
My Class:
public class Category
{
    public Category(string name)
    {
        Name = name;
    }

    public int Id { get; set; }
    public string Name { get; set; }

    public int? ParentCategoryId { get; set; }
    public Category? ParentCategory { get; set; }

    public ICollection<Foodstuff> Foodstuffs { get; } = new List<Foodstuff>();

    public ICollection<int> FoodstuffIds { get; } = new List<int>();

    public byte[] RowVersion { get; set; }

}

My DTO:
public record class Category : IGenerateETag
{
    public Category(string name)
    {
        Name = name;
    }

    public string Id { get; init; }

    [Required(ErrorMessage = "Category name is required.", AllowEmptyStrings = false)]
    public string Name { get; init; }

    public string? ParentCategoryId { get; init; }

    public byte[] RowVersion { get; set; }
}

My converters:
public class HideIdConverter : IValueConverter<int, string>
{

    public string Convert(int sourceMember, ResolutionContext context)
    {
        var hashids = new Hashids();
        var shadow = hashids.Encode(sourceMember);
        return shadow;
    }
}

public class UnhideIdConverter : IValueConverter<string, int>
{

    public int Convert(string sourceMember, ResolutionContext context)
    {
        var hashids = new Hashids();
        var plain = hashids.Decode(sourceMember);
        return plain[0]; // TODO check this;
    }
}

Aaand my Automapper config:
CreateMap<Dal.Entities.Category, Category>()
    .ForMember(dest => dest.Id, opt => opt.ConvertUsing(new HideIdConverter(), src => src.Id))
    .ReverseMap()
    .ForMember(dest => dest.Id, opt => opt.ConvertUsing(new UnhideIdConverter(), src => src.Id));

A: It turns out that it this is not possible, because I was using LINQ expressions, especially ProjectTo(). It is stated that:

Value converters are only used for in-memory mapping execution. They will not work for ProjectTo.

Source.
I guess I will have to map the objects after I queried them from my database.


text:
Q: Statistically evaluating performance of algorithms I am working on a problem for which I have come up with a couple of algorithms. To assess which one is the best, I compare a set of algorithm outputs (set of numbers) against the "true" set of values by evaluating the absolute value of the difference between the two. I then take the mean of this difference set and also calculate its standard deviation. My approach was to choose the algorithm with mean closest to zero as the best. The problem is that the standard deviation of the least mean algorithm is larger than some of the other algorithms. The relevant values are:
$$ \begin{array}{|c|c|c|} \hline \mbox{Algorithm number}& \mbox{Mean} & \mbox{Standard Deviation} \\ \hline 1 & 0.316 & 0.615 \\ 2 & 0.298 & 0.615 \\ 3 & 0.253 & 0.657 \\ 4 & 0.283 & 0.657 \\ \hline \end{array}
$$
Based on the mean, I would choose the third algorithm. Is this really the best algorithm, given the large standard deviation? And is there any other way to evaluate which algorithm is the best, just by studying the outputs?

A: It really depends on how you want to penalize your errors. In the evaluation process, you need to define a "loss" function. Here, the loss function you chose is the mean of the absolute values of prediciton errors, also known as "MAE." This is a perfectly good loss function. One property of MAE is that it is not as significantly perturbed by outliers as many other loss functions: if you would like to penalize more strongly for outliers (I think you do) you should consider using the mean of the squared prediction errors (i.e. "mean squared error," or MSE). There are many common loss functions out there to choose from (RSS, RMSE, L1 norm, L2 Norm...), but you aren't limited to these: you can design any loss function you want. MSE is probably the most commonly used, but there are others to explore, and there's nothing inherently wrong with MAE.
Something else to consider is how you value accuracy vs. precision. Algorithm #3 has the highest accuracy, but is tied for the lowest precision. Just like choosing a loss function, you need to decide for yourself what you value most in this regard.
Presumably, your algorithms all had to be "trained" on some data where the desired result was known. Was your evaluation of these algorithms based on the data you used to train them? If so, I strongly recommend that you a) consider using cross validation to get a better understanding of the prediction errors you can anticipate, and b) if you have enough data, set some aside to not be used for training and evaluate based on the held out data in addition to cross validation.
Finally, it's worth noting that although you can make your selection based solely on a loss function, the numbers in your table all look very similar. The improvement you are receiving between these algorithms may be so negligible as to not be statistically significant. You should consider comparing the difference in your means with a one way ANOVA or a series of t-tests to confirm that the you are actually getting different results from your algorithms.


text:
Q: How to keep the form of tensor wedge, instead of using tensor product?
Why is an expression with full form of
TensorProduct[TensorWedge[v1, v2], w1]

changed into
TensorProduct[
  Plus[
    TensorProduct[v1, v2],
    Times[-1, TensorTranspose[TensorProduct[v1, v2], List[2, 1]]]],
  w1]?

How could I keep the form unchanged?

A: You must have done something like:
$Assumptions = (v1|v2) ∈ Vectors[d];
TensorProduct[TensorWedge[v1, v2], w1] //FullForm

TensorProduct[Plus[TensorProduct[v1,v2],Times[-1,TensorTranspose[TensorProduct[v1,v2],List[2,1]]]],w1]

If you don't want the automatic simplification done by TensorProduct to occur, just include the assumption using Assumptions->assumptions when you use TensorReduce instead.


text:
Q: I am trying to download data from Yahoo Finance using pandasb but nothing happens? import pandas_datareader.data as web
import datetime
start = datetime.datetime(2010, 1, 1)

end = datetime.datetime(2013, 1, 27)

f = web.DataReader("ugaz", 'yahoo', start, end)

f.ix['2010-01-04']

The above is the code I am currently trying to use to get data from Yahoo Finance. when I run the code I get this in the python shell 3.5.2 window
==================== RESTART: C:/Users/Zac/Desktop/ll.py ====================

That's all that I get. I am using python 3.5 on windows 10

A: The first datapoint is
f.ix['2012-02-08']

Open           48.360002
High           48.360002
Low            48.360002
Close          48.360002
Volume          0.000000
Adj Close    6045.000287
Name: 2012-02-08 00:00:00, dtype: float64

A: There are so many ways to download financial data, or any kind of data, from the web.  The script below downloads stock prices and saves everything to a CSV file.
import urllib2

listOfStocks = ["AAPL", "MSFT", "GOOG", "FB", "AMZN"]

urls = []

for company in listOfStocks:
    urls.append('http://real-chart.finance.yahoo.com/table.csv?s=' + company + '&d=6&e=28&f=2015&g=m&a=11&b=12&c=1980&ignore=.csv')

Output_File = open('C:/Users/your_path/Historical_Prices.csv','w')

New_Format_Data = ''

for counter in range(0, len(urls)):

    Original_Data = urllib2.urlopen(urls[counter]).read()

    if counter == 0:
        New_Format_Data = "Company," + urllib2.urlopen(urls[counter]).readline()

    rows = Original_Data.splitlines(1)

    for row in range(1, len(rows)):

        New_Format_Data = New_Format_Data + listOfStocks[counter] + ',' + rows[row]

Output_File.write(New_Format_Data)
Output_File.close()

The script below will download multiple stock tickers into one folder.
import urllib
import re
import json

symbolslist = open("C:/Users/rshuell001/Desktop/symbols/tickers.txt").read()
symbolslist = symbolslist.split("\n")

for symbol in symbolslist:
    myfile = open("C:/Users/your_path/Desktop/symbols/" +symbol +".txt", "w+")
    myfile.close()

    htmltext = urllib.urlopen("http://www.bloomberg.com/markets/chart/data/1D/"+ symbol+ ":US")
    data = json.load(htmltext)
    datapoints = data["data_values"]

    myfile = open("C:/Users/rshuell001/Desktop/symbols/" +symbol +".txt", "a")
    for point in datapoints:
        myfile.write(str(symbol+","+str(point[0])+","+str(point[1])+"\n"))
    myfile.close()

Finally...this will download prices for multiple stock tickers...
import urllib
import re

symbolfile = open("C:/Users/your_path/Desktop/symbols/amex.txt")
symbollist = symbolfile.read()

newsymbolslist = symbollist.split("\n")

i=0
while i<len(newsymbolslist):
    url = "http://finance.yahoo.com/q?s=" + newsymbolslist[i] + "&ql=1"
    htmlfile = urllib.urlopen(url)
    htmltext = htmlfile.read()
    regex = '(.+?)'
    pattern = re.compile(regex)
    price = re.findall(pattern,htmltext)
    print "the price of ", newsymbolslist[i] , "is", price[0]
    i+=1

# Make sure you place the 'amex.txt' file in 'C:\Python27\'

I wrote a book about these kinds of things, and lots of other stuff.  You can find it using the URL below.
https://www.amazon.com/Automating-Business-Processes-Reducing-Increasing-ebook/dp/B01DJJKVZC/ref=sr_1_1?


text:
Q: Configuring Jaeger in Spring application I would like to configure Jaeger in my Spring application. Somehow I cannot find a proper way to do this. Almost all Spring-Jaeger-related documentation is for Spring Boot where most of the properties are auto configured. Here's my approach.
Maven dependency:
    <dependency>
        <groupId>io.opentracing.contrib</groupId>
        <artifactId>opentracing-spring-jaeger-cloud-starter</artifactId>
        <version>1.0.3</version>
    </dependency>

Spring config for Jaeger:
@Configuration
public class JagerConfiguration {

    @Bean
    public io.opentracing.Tracer jaegerTracer() {
        Map<String, String> tags = new HashMap<>();
        tags.put(Constants.TRACER_HOSTNAME_TAG_KEY, "localhost");

        CompositeReporter reporter = new CompositeReporter(new LoggingReporter(), remoteReporter());

        return new Builder("myTestSpringApp")
                .withSampler(new ConstSampler(true))
                .withMetricsFactory(new InMemoryMetricsFactory())
                .withReporter(remoteReporter())
                .withTags(tags)
                .build();
    }

    @Bean
    public RemoteReporter remoteReporter() {
        return new RemoteReporter.Builder().withSender(new UdpSender("localhost", 6831, 0)).build();
    }
}

Jaeger is running locally in docker on port 6831.
docker run -d -p6831:6831/udp -p16686:16686 jaegertracing/all-in-one:latest

Once my application starts, I noticed that application slows down considerably, I assume that is because of metrics logged heavily to console by LoggingReporter.
However, My Spring app does not show up in Jaeger UI. In the beginning I would like to trace my REST endpoints. Can someone point me in the right direction why my app is missing from UI and how I configure Jaeger properly? Is there perhaps a sample project with Spring+Jaeger that does not rely on outdated Jaeger?

A: If anyone else would like to set up Jaeger in spring project, here's what I did:
Add dependencies to pom:
<properties>
    <opentracing.spring.web.version>0.3.4</opentracing.spring.web.version>
    <opentracing.jdbc.version>0.0.12</opentracing.jdbc.version>
    <opentracing.spring.configuration.starter.version>0.1.0</opentracing.spring.configuration.starter.version>
    <opentracing.spring.jaeger.starter.version>0.2.2</opentracing.spring.jaeger.starter.version>
</properties>

<dependency>
    <groupId>io.opentracing.contrib</groupId>
    <artifactId>opentracing-spring-web-starter</artifactId>
    <version>${opentracing.spring.web.version}</version>
</dependency>
<dependency>
    <groupId>io.opentracing.contrib</groupId>
    <artifactId>opentracing-jdbc</artifactId>
    <version>${opentracing.jdbc.version}</version>
</dependency>
<dependency>
    <groupId>io.opentracing.contrib</groupId>
    <artifactId>opentracing-spring-tracer-configuration-starter</artifactId>
    <version>${opentracing.spring.configuration.starter.version}</version>
</dependency>
<dependency>
    <groupId>io.opentracing.contrib</groupId>
    <artifactId>opentracing-spring-jaeger-starter</artifactId>
    <version>${opentracing.spring.jaeger.starter.version}</version>
</dependency>

Set up you web.xml to register new tracing filter tracingFilter to intercept REST API:
<filter>
    <filter-name>tracingFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <async-supported>true</async-supported>
</filter>
<filter-mapping>
    <filter-name>tracingFilter</filter-name>
    <url-pattern>/api/*</url-pattern>
</filter-mapping>

Register jaeger tracer in spring mvc:
<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**" />
        <bean class="io.opentracing.contrib.spring.web.interceptor.TracingHandlerInterceptor">
            <constructor-arg ref="jaegerTracer" />
        </bean>
    </mvc:interceptor>
</mvc:interceptors>

Set up the tracingFilter bean we described in web.xml:
import io.opentracing.Tracer;
import io.opentracing.contrib.web.servlet.filter.TracingFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JaegerFilterConfiguration {

    @Bean
    public TracingFilter tracingFilter(Tracer tracer) {
        return new TracingFilter(tracer);
    }
}

Finally define jaeger tracer spring configuration:
import io.jaegertracing.internal.JaegerTracer;
import io.jaegertracing.internal.metrics.NoopMetricsFactory;
import io.jaegertracing.internal.reporters.RemoteReporter;
import io.jaegertracing.internal.reporters.RemoteReporter.Builder;
import io.jaegertracing.internal.samplers.ProbabilisticSampler;
import io.jaegertracing.thrift.internal.senders.UdpSender;
import io.opentracing.Tracer;
import io.opentracing.util.GlobalTracer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.event.ContextRefreshedEvent;

@Configuration
public class JaegerConfiguration implements ApplicationListener<ContextRefreshedEvent> {

    private static final int JAEGER_PORT = 6831;
    private static final String JAEGER_HOST = "localhost";
    private static final String JAEGER_SERVICE_NAME = "my-awesome-jaeger";
    private static final double SAMPLING_RATE = 0.5;
    @Autowired
    private Tracer tracer;

    @Bean
    @Primary
    public Tracer jaegerTracer(RemoteReporter remoteReporter) {
        return new JaegerTracer.Builder(JAEGER_SERVICE_NAME)
                .withReporter(remoteReporter)
                .withMetricsFactory(new NoopMetricsFactory()).withSampler(new ProbabilisticSampler(SAMPLING_RATE))
                .build();
    }

    @Bean
    public RemoteReporter remoteReporter() {
        return new Builder().withSender(new UdpSender(JAEGER_HOST, JAEGER_PORT, 0)).build();
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (!GlobalTracer.isRegistered()) {
            GlobalTracer.register(tracer);
        }
    }
}

A: I have got following gradle dependencies working,
    implementation "io.opentracing.contrib:opentracing-spring-cloud-starter:0.1.13"
    implementation "io.jaegertracing:jaeger-client:0.31.0"

Following tracer bean configuration,
  @Bean
    public io.opentracing.Tracer initTracer() {
        Configuration.SamplerConfiguration samplerConfig = new Configuration.SamplerConfiguration().withType("const").withParam(1);
        return Configuration.fromEnv("sprint-service").withSampler(samplerConfig).getTracer();
    }

And then the spans can be recorded as
Span sprintSpan = tracer.buildSpan("my-span-name").withTag("player", player).start();

// some business functionality

sprintSpan.finish();

Here is the working example you can refer https://github.com/krushnatkhawale/jaeger-with-spring-boot-web-app


text:
Q: How to avoid destroying and recreating threads inside loop? I have a loop with that creates and uses two threads. The threads always do the same thing and I'm wondering how they can be reused instead of created and destroyed each iteration? Some other operations are do inside the loop that affect the data the threads process. Here is a simplified example:
const int args1 = foo1();
const int args2 = foo2();
vector<string> myVec = populateVector();
int a = 1;
while(int i = 0; i < 100; i++)
{
    auto func = [&](const vector<string> vec){
        //do stuff involving variable a
        foo3(myVec[a]);
    }
    thread t1(func, args1);
    thread t2(func, args2);
    t1.join();
    t2.join();

    a = 2 * a;
}

Is there a way to have t1 and t2 restart? Is there a design pattern I should look into? I ask because adding threads made the program slightly slower when I thought it would be faster.

A: You can use std::async as suggested in the comments.
What you're also trying to do is a very common usage for a Threadpool. I simple header only implementation of which I commonly utilize is here
To use this library, create the pool outside of the loop with a number of threads set during construction. Then enqueue a function in which a thread will go off and execute. With this library, you'll be getting a std::future (much like the std::async steps) and this is what you'd wait on in your loop.
Generically, you'd want to make access to any data thread-safe with mutexs (or other means, there are a lot of ways to do this) but under very specific situations, you'll not need to.
In this case,

*

*so long as the vector isn't being increased in size (doesn't need to reallocate)

*Only reading items  or only modifying each item at a time in its own thread

the you wouldn't need to worry about synchronization.
Though its just good habit to do the sync anyways... When other people eventually modify the code, they're not going to know your rules and will cause issues.


text:
Q: Adjusting bar graph generated with pandas I'm having a bit of trouble adjusting a bar chart created with the pandas. Is it possible to remove the space between the graph and the x and y axes? I am attaching 2 images from before and how I would like (after), I made several attempts but they were not satisfactory.
Thank you for your help
pandas version: 0.21.0
matplotlib version: 2.1.0
Before:

After:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

_file_bmu = '1941070.csv'

df = pd.read_csv(_file_bmu, sep=',', header=None)
df.columns = ['date_str', 'x', 'y']

df['DateTime'] = pd.to_datetime(df['date_str'], format='%d-%m-%Y')
df['day_of_week'] = df.DateTime.dt.strftime('%A')
df['id'] = df.DateTime.dt.strftime('%w')

output = pd.pivot_table(df, index=['id'], values=['x', 'y'], aggfunc=    [np.mean, np.std])

output.columns = output.columns.droplevel(0) #remove amount
output.columns.name = None                   #remove categories
output = output.reset_index()                #index to columns

output.columns = ['id','x_mean', 'y_mean','x_std','y_std']

# output.columns = output.columns.droplevel(0)
# output = output.reset_index().rename_axis(None, axis=1)

means = (output[['x_mean', 'y_mean']]).round(2)
means.columns = ['x', 'y']

errors = (output[['x_std', 'y_std']]).round(2)
errors.columns = ['x', 'y']

print('MEANS')
print(means)

print('ERRORS')
print(errors)

fig, ax = plt.subplots()
ax.tick_params(axis='x', which='both', top='off', bottom='off')
means.plot.bar(yerr=errors,ax=ax)

plt.show()
print("END")

1941070.csv file content
02-01-2016,34,45
03-01-2016,35,44
04-01-2016,0,45
05-01-2016,0,43
06-01-2016,7,46
07-01-2016,24,13
08-01-2016,20,0
09-01-2016,34,44
10-01-2016,34,45
11-01-2016,0,45
12-01-2016,0,43
13-01-2016,0,43
14-01-2016,23,12
15-01-2016,20,0
03-02-2016,0,43
06-02-2016,34,44
07-02-2016,34,44
08-02-2016,0,43
09-02-2016,0,41
10-02-2016,7,49
11-02-2016,16,48
12-02-2016,20,0
13-02-2016,19,0
14-02-2016,34,44
15-02-2016,0,45
16-02-2016,0,43
17-02-2016,0,43
18-02-2016,24,13
02-03-2016,6,46
04-03-2016,20,0
06-03-2016,33,45
07-03-2016,0,45
08-03-2016,0,43
09-03-2016,7,46
11-03-2016,20,0
13-03-2016,34,45
14-03-2016,0,45
15-03-2016,0,43
16-03-2016,8,46
17-03-2016,17,47
18-03-2016,24,47
19-03-2016,19,0
01-04-2016,25,47
02-04-2016,20,0
03-04-2016,34,45
04-04-2016,0,45
05-04-2016,0,43
06-04-2016,7,46
07-04-2016,24,12
08-04-2016,20,0
09-04-2016,34,44
10-04-2016,34,45
11-04-2016,0,45
14-04-2016,24,12
15-04-2016,24,48
16-04-2016,19,0
05-05-2016,17,47
08-05-2016,35,47
09-05-2016,0,46
10-05-2016,0,44
11-05-2016,9,47
12-05-2016,15,50
15-05-2016,36,47
16-05-2016,0,47
17-05-2016,0,46
18-05-2016,8,48
19-05-2016,16,48
20-05-2016,22,48
24-05-2016,0,45
25-05-2016,7,47
01-06-2016,7,47
02-06-2016,16,48
06-06-2016,0,46
11-06-2016,28,48
12-06-2016,36,47
13-06-2016,0,46
16-06-2016,15,50
17-06-2016,21,50
18-06-2016,27,48
19-06-2016,35,47
20-06-2016,0,47
23-06-2016,15,49
24-06-2016,23,48
25-06-2016,24,50
01-07-2016,23,48
02-07-2016,36,46
03-07-2016,36,46
04-07-2016,0,45
05-07-2016,0,44
06-07-2016,7,47
09-07-2016,26,49
10-07-2016,35,47
11-07-2016,0,45
12-07-2016,0,44
13-07-2016,7,47
14-07-2016,15,49
15-07-2016,21,50
16-07-2016,35,46
01-08-2016,0,45
03-08-2016,8,47
04-08-2016,16,48
05-08-2016,23,48
06-08-2016,34,46
07-08-2016,36,46
08-08-2016,0,47
10-08-2016,7,47
11-08-2016,16,48
12-08-2016,23,48
13-08-2016,33,45
14-08-2016,34,46
15-08-2016,0,45
16-08-2016,1,46
01-09-2016,15,48
02-09-2016,23,48
03-09-2016,35,45
05-09-2016,0,45
06-09-2016,0,44
07-09-2016,7,50
08-09-2016,15,51
09-09-2016,23,48
10-09-2016,34,45
11-09-2016,34,46
12-09-2016,0,45
13-09-2016,0,44
14-09-2016,7,47
15-09-2016,15,48
01-10-2016,35,46
02-10-2016,36,46
03-10-2016,0,46
04-10-2016,0,44
06-10-2016,15,50
07-10-2016,21,50
09-10-2016,36,46
10-10-2016,0,45
11-10-2016,0,44
12-10-2016,7,48
13-10-2016,15,49
14-10-2016,21,50
15-10-2016,35,46
18-10-2016,0,44
01-11-2016,0,44
03-11-2016,16,48
04-11-2016,23,48
05-11-2016,33,45
06-11-2016,34,46
07-11-2016,0,46
08-11-2016,0,45
09-11-2016,6,47
11-11-2016,20,0
12-11-2016,33,45
13-11-2016,35,46
14-11-2016,0,46
15-11-2016,0,45
16-11-2016,8,48
01-12-2016,15,49
03-12-2016,35,45
04-12-2016,34,46
07-12-2016,7,47
08-12-2016,16,48
09-12-2016,25,47
10-12-2016,32,46
11-12-2016,33,46
12-12-2016,0,47
13-12-2016,0,44
14-12-2016,7,47
15-12-2016,16,48
16-12-2016,23,48
17-12-2016,34,45


text:
Q: How to provide details about multiple operating systems? I'm adding schema.org-data to my site. I'm looking at operating-system-details. According to this speccs: https://schema.org/operatingSystem, you can use values like
Windows 7, OSX 10.6, Android 1.6

I build a web app so it's supported on basically all desktop-Os:es that can run a modern browser. What value should I use? Can I use more than one value, in that case how should the markup look?
<meta itemprop="operatingSystem" content="Windows" />
<meta itemprop="operatingSystem" content="OS X" />
<meta itemprop="operatingSystem" content="Linux" />

or
<meta itemprop="operatingSystem" content="Windows, OS X, Linux" />


text:
Q: AndEngine Box2D Body GetContactList Ive been trying to learn the Physics Box2D Extension for AndEngine and I have been reading http://www.box2d.org/manual.html#_Toc258082975
Under "9.3 Accessing Contacts" it says

You can also iterate over all the contacts on a body

My understanding is that I should be able to do
myBody().GetContactList()

But I cant seem to find it. Am I missing something here? should I be able to do this?
Thanks in advance
EDIT:
ok, I've looked in Body.java for the Box2DExtension and found
// ArrayList<ContactEdge> getContactList()
// {
// return contacts;
// }

commented out, does anybody know why. I will still have a look but if anybody could find the answer quicker than me it would be greatly appreciated

A: Thought id share what I found: After more googling I found this where it is explained that the Box2d extension is pulled from libgdx and the file that is supposed to have .GetContactList() is Body.java line 772 which has been commented out for a while. I don't know why it hasn't been implemented but at least I know why I'm not able to call it.


text:
Q: Need to create combinations of Parents/Children/Dogs, but can't get past 2nd level of CTE I've hit a brick wall and please ask help.
I'm building a table up for (in this example) a ticketing system
where e.g. Ticket 1 will allow
Parent: Either parent Peter or Sally,
Child: to come without a child or with a child (either Sam, Pete or John),
Dog: and either without a dog or with one of the dogs (DogMatix,Snowy,Bliksem)
The table layout is that the Parent/Child/Dog is a parameter, and I can get (with CTE) to the Parent/Child relationships to all show, but not the next level showing the dogs too
declare @Ticket table
(
TID int
)

declare @Param table
(PID int IDENTITY(1,1) not null,
TID int,
ParamType varchar(20),
Val  varchar(40)
)

Insert into @Ticket(TID) Select(1)
Insert into @Ticket(TID) Select(2)

Insert into @Param(TID,ParamType,Val) values(1,'Parent','ParentPeter')
Insert into @Param(TID,ParamType,Val) values(1,'Parent','ParentSally')
Insert into @Param(TID,ParamType,Val) values(1,'Child','ChildSam')
Insert into @Param(TID,ParamType,Val) values(1,'Child','ChildPete')
Insert into @Param(TID,ParamType,Val) values(1,'Child','ChildJohn')
Insert into @Param(TID,ParamType,Val) values(1,'Dog','DogDogMatix')
Insert into @Param(TID,ParamType,Val) values(1,'Dog','DogSnowy')
Insert into @Param(TID,ParamType,Val) values(1,'Dog','DogBliksem')

Insert into @Param(TID,ParamType,Val) values(2,'Parent','ParentParker')
Insert into @Param(TID,ParamType,Val) values(2,'Parent','ParentScarlett')
Insert into @Param(TID,ParamType,Val) values(2,'Child','ChildBrett')
Insert into @Param(TID,ParamType,Val) values(2,'Child','ChildBritney')
Insert into @Param(TID,ParamType,Val) values(2,'Child','ChildBronwyn')
Insert into @Param(TID,ParamType,Val) values(2,'Dog','DogRover')
Insert into @Param(TID,ParamType,Val) values(2,'Dog','Dog2')
Insert into @Param(TID,ParamType,Val) values(2,'Dog','Dog3')

;with cte  as (
Select TID,Val as 'Parent'
from @Param p
where  p.ParamType = 'Parent'
 )
Select cte.TID,cte.Parent,p.Val as 'Child'
from cte
left outer join @Param p on p.TID = cte.TID and  p.ParamType = 'Child'

--The required results will be (for ticket 1)
--TID       Parent          Child           Dog
--1     ParentPeter     ChildSam        DogDogMatix
--1     ParentPeter     ChildSam        DogSnowy
--1     ParentPeter     ChildSam        DogBliksem
--1     ParentPeter     ChildPete       DogDogMatix
--1     ParentPeter     ChildPete       DogSnowy
--1     ParentPeter     ChildPete       DogBliksem
--1     ParentPeter     ChildJohn       DogDogMatix
--1     ParentPeter     ChildJohn       DogSnowy
--1     ParentPeter     ChildJohn       DogBliksem
--1     ParentPeter     null            null
--1     ParentPeter     ChildSam        null
--1     ParentPeter     ChildPete       null
--1     ParentPeter     ChildJohn       null

--1     ParentSally     ChildSam        DogDogMatix
--1     ParentSally     ChildSam        DogSnowy
--1     ParentSally     ChildSam        DogBliksem
--1     ParentSally     ChildPete       DogDogMatix
--1     ParentSally     ChildPete       DogSnowy
--1     ParentSally     ChildPete       DogBliksem
--1     ParentSally     ChildJohn       DogDogMatix
--1     ParentSally     ChildJohn       DogSnowy
--1     ParentSally     ChildJohn       DogBliksem
--1     ParentSally     null            null
--1     ParentSally     ChildSam        null
--1     ParentSally     ChildPete       null
--1     ParentSally     ChildJohn       null

A: First off, I think you should consider rethinking your data model a little, and look into some normalization techniques before going ahead with your project.
But, using your model ( only slightly altering it ), you could accomplish what you're after using the following method.
Simply add nulls for the child / dog levels and use a simple cross apply query to create the Cartesian product you seem to be after. There's no need for recursive queries, since your data isn't defined recursively.
But, this will work :
declare @Ticket table
(
TID int
)

declare @EntityTypes table
(
 id int primary key,
 name varchar(20)
)

declare @TicketEntities table
(ID int IDENTITY(1,1) not null,
 TicketId int,
 TypeId INT,
 EntityName varchar(40)
)

Insert into @Ticket(TID) values(1)
Insert into @Ticket(TID) values(2)

insert into @EntityTypes (id, name) values (1, 'Parent');
insert into @EntityTypes (id, name) values (2, 'Child');
insert into @EntityTypes (id, name) values (3, 'Dog');

Insert into @TicketEntities(TicketId,TypeId,EntityName) values(1,1,'Peter')
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(1,1,'Sally')
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(1,2,'Sam')
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(1,2,'Pete')
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(1,2,'John')
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(1,2,NULL)
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(1,3,'Matix')
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(1,3,'Snowy')
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(1,3,'Bliksen')
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(1,3,NULL)

Insert into @TicketEntities(TicketId,TypeId,EntityName) values(2,1,'Parker')
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(2,1,'Scarlett')
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(2,2,'Brett')
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(2,2,'Britney')
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(2,2,'Bronwyn')
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(2,2,NULL)
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(2,3,'Rover')
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(2,3,'Sam')
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(2,3,'Laika')
Insert into @TicketEntities(TicketId,TypeId,EntityName) values(2,3,NULL)

Select par.ticketId, par.EntityName as Parent, child.EntityName as Child, dogs.EntityName as Dog
from @TicketEntities as par
    CROSS JOIN @TicketEntities child
    CROSS JOIN @TicketEntities dogs
where
    par.TypeId in (select id from @EntityTypes where name = 'Parent') AND par.TicketId = 1
    AND child.TypeId in (select id from @EntityTypes where name = 'Child') AND child.TicketId = 1
    AND dogs.TypeId in (select id from @EntityTypes where name = 'Dog') AND dogs.TicketId = 1


text:
Q: How can I select other div's child in jQuery? I want to select all previous ".pt" when I checked some element.
I tried
$('p').mouseover(function(){
$(this).css('font-size', 'bold');
$(this).prevAll('.pt').css('font-size', 'bold');
});

In second div, it just changed previous ".pt" in second div.
How can I changed first div's ".pt" even when checked second div element?

 //first

 //second

A: You can try getting the index of the element and then slice with that parameter:

$('.pt').click(function() {
  $('.red').removeClass('red');
  var ti = $(this).index('.pt');
  $('.pt').slice(0, ti + 1).addClass('red');
})
.pt {
  padding: 15px;
  background: gold;
  margin: 8px;
}
.red {
  background: red;
}

A:

$('.pt').mouseover(function() {
  $(this).css('font-weight', 'bold');
  $(this).prevAll('.pt').css('font-weight', 'bold');
  $(this).parent().prevAll().children('.pt').css('font-weight', 'bold');
});

$('.pt').mouseleave(function() {
  $('.pt').css('font-weight', 'normal');
});

first

paragraph

paragraph

paragraph

second

paragraph

paragraph

paragraph


text:
Q: Opencv Mat's element indexing producing garbage I'm collecting a bunch of pixel along an edge and saving them in a matrix.
    cv::Mat vals = cv::Mat(18,7,img.type(),cv::Scalar(0));

    for (int j=1; j<7; j++)
    {
      cv::Point2f coords = start + direction*(step_size*j) - 3*normal;
      cv::Point2f coords_successive = coords + direction - 3*normal;
      cv::Point2f coords_previous = coords - direction - 3*normal;

      for (int y=0; y<7; y++)
      {
        vals.at<int>((j-1)*3, y) = 1;    //this->sample(img, coords_previous+=normal);
        vals.at<int>((j-1)*3+1, y) = 1;  //this->sample(img, coords+=normal);
        vals.at<int>((j-1)*3+2, y) = 1;  //this->sample(img, coords_successive+=normal);
      }

    }

    std::cout << "----" << std::endl;

    for (int x=0; x<18; x++)
    {
        for (int y=0; y<7; y++)
        {
            std::cout << vals.at<int>(x,y) << "\t";
        }
        std::cout << std::endl;
    }

Result:
1   1   1   1   1   257 256
256 256 256 65792   65536   65536   65536
65536   16842752    16777216    16777216    16777216    16777216    16777216
1   1   1   1   1   257 256
256 256 256 65792   65536   65536   65536
65536   16842752    16777216    16777216    16777216    16777216    16777216
1   1   1   1   1   257 256
256 256 256 65792   65536   65536   65536
65536   16842752    16777216    16777216    16777216    16777216    16777216
1   1   1   1   1   257 256
256 256 256 65792   65536   65536   65536
65536   16842752    16777216    16777216    16777216    16777216    16777216
1   1   1   1   1   257 256
256 256 256 65792   65536   65536   65536
65536   16842752    16777216    16777216    16777216    16777216    16777216
1   1   1   1   1   1   1
256 256 256 256 256 0   1
65536   65536   65536   0   256 0   1
I've already tried:
1) uchar instead of int, as suggested in other posts when working with gray scale images,
2) using a int[][] matrix (which is working!) and passing the data to the matrix (which is producing the same garbage)
3) inverting indices (I thought "ok, maybe it's me taking values where the matrix is not defined) but...same garbage.

A: cv:Scalar is usually of type double.
And the first index  is usually the row and the second is the column. This is usual in image processing

A: You are confusing row and columns while printing the mat structure. You can use the following code. if your image is 8UC1 channel, you have to access using uchar like. vals.at(i,j). But you havent specified what is img.type()is. I am assuming it is CV_8UC1
 cv::Mat vals = cv::Mat(18,7,img.type(),cv::Scalar(0));

for (int j=1; j<7; j++)
{
  cv::Point2f coords = start + direction*(step_size*j) - 3*normal;
  cv::Point2f coords_successive = coords + direction - 3*normal;
  cv::Point2f coords_previous = coords - direction - 3*normal;

  for (int y=0; y<7; y++)
  {
    vals.at<int>((j-1)*3, y) = 1;    //this->sample(img, coords_previous+=normal);
    vals.at<int>((j-1)*3+1, y) = 1;  //this->sample(img, coords+=normal);
    vals.at<int>((j-1)*3+2, y) = 1;  //this->sample(img, coords_successive+=normal);
  }

}

std::cout << "----" << std::endl;
int rows=vals.rows;
int colms=vals.cols;
for (int x=0; x<rows; x++)
{
    for (int y=0; y<colms; y++)
    {
        std::cout << vals.at<uchar>(x,y) << "\t";
    }
    std::cout << std::endl;
}


text:
Q: How to insert element between other elements in KDB/Q list Say I have a list (1 3 4) and after 1 I want to insert another element 2 resulting in (1 2 3 4).
How can this be done efficiently in a generic way?

A: An alternative approach which allows for multiple inserts at once.
If the indices are to index the original list:
q){raze cut[(0,z);x],'(y,enlist ())}[til 10;999 998 994;2 4 8]
0 1 999 2 3 998 4 5 6 7 994 8 9

If the indices are to index consecutive iterations of the list:
q){raze cut[(0,z);x],'(y,enlist ())}/[til 10;999 998 994;2 4 8]
0 1 999 2 998 3 4 5 994 6 7 8 9

A: I think you need to be more specific about what you want, but for now here's an example of how you could achieve it
q)list:1 3 4
q)list
1 3 4
q)list: asc list,:2
q)list
`s#1 2 3 4

Or another way is let's say you know the index at which you want to add the element to the list, in this case at index 1, then you could create a function as such:
q)add:{[lst;ele;ind] (ind#lst),ele,(ind _ lst)}
q)list:1 3 4
q)add[list;2;1]
1 2 3 4


text:
Q: How to create custom events (they have to be at netbeans palette) I've been looking for hours a solution for my problem, I'm kinda new programming in Java languaje and already managed to create a custom panel that contains 6 custom buttons, but now I need to create an event that can detect wich one I pressed, I've done this with C# but can't find a way in Java.
This code is in C# but of course I need something similar for Java.
/// <summary>
/// Enumerator with buttons states
/// </summary>
public enum EstadoBoton
{
    Aceptar = 1,
    Nuevo = 2,
    Editar = 3,
    Cancelar = 4,
    Eliminar = 5,
    Imprimir = 6,
    Salir = 7
}
/// <summary>
/// Delegate method for buttons events
/// </summary>
/// <param name="edoBoton"></param>
public delegate void BotonPresionado(EstadoBoton edoBoton);

public partial class ctrlBotones : UserControl
{
    /// <summary>
    /// here I keep the state of the button
    /// </summary>
    private EstadoBoton estadoBoton;
    /// <summary>
    /// Event that manages the state of the button
    /// </summary>
    public event BotonPresionado BotonPresionado
    {
        add { this.botonpresion += value; }
        remove { this.botonpresion -= value; }
    }
    private BotonPresionado botonpresion;
    public ctrlBotones()
    {
        InitializeComponent();
    }

That example shows at visual studio's list of events the name "BotonPresionado" so I can select that event and the code will be generated.
I would apreciatte a lot any help you could give me.
Thanks in advance and sorry if my english is not very good, still learning. :)
I forgort to write the generated code when I press the custom event at GUI.
//As we can see, it generates en event for this control not for the buttons.
private void ctrlBotones1_BotonPresionado(HerramientasInterfaz.EstadoBoton edoBoton)
    {
        //I just use a switch to check wich button I pressed.
        switch (edoBoton)
        {
            case HerramientasInterfaz.EstadoBoton.Aceptar:
                Aceptar();
                break;
            case HerramientasInterfaz.EstadoBoton.Nuevo:
                Nuevo();
                break;
            case HerramientasInterfaz.EstadoBoton.Salir:
                Close();
                break;
        }
    }

A: ok, Aaron Daw i under stud some extent that you want to create your own "event".That means to reuse the same code for the components.
I tried custom components(JButtons,JMenu) in past this way
public class MyMenu extends JMenu
{
public MyMenu(ImageIcon i,String s)
{
    super();
    setIcon(i);
    setText(s);
    setVerticalTextPosition(SwingConstants.BOTTOM);
    setHorizontalTextPosition(SwingConstants.CENTER);
}
}

Create object for "MyMenu",here we don't need to add properties each time, that was advantage.
In a same way i tried with custom listener for JButton it's working.when you click on button it will prints "button pressed"
this is customEvent class
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

public class CustomListener
{
JButton button;
public CustomListener(JButton b)
{
button=b;

button.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource()==button)
        {
            System.out.println("button pressed");

        }
    }
});

}
}

this is main class
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MainClass extends JFrame
{
JButton jbutton;
public MainClass()
{
    setLayout(new FlowLayout());
    add(jbutton());
    setSize(800,600);
    setVisible(true);
}
public JButton jbutton()
{
    if(jbutton==null)
    {
        jbutton=new JButton("click");
        new CustomListener(jbutton);
    }
    return jbutton;
}

public static void main(String args[])
{
    new MainClass();
}
}

now I can REUSE the actionListener.

A: my friend
if you are looking for an userinterface similar to that of visual studio like easy drag drop
then in netbeans right click on your project then click new JFrame Form (if its not there then in others) and you will have a easy drag drop userinterface
then drop a JButton from palette and then double click that JButton and there you get event for that JButton ....


text:
Q: Vaadin 8 grid with multiple filters I want to filter grid content according to two filtering criterias, therefore I have the following
ListDataProvider<Person> dataProvider = (ListDataProvider<Person>) grid.getDataProvider();
SerializablePredicate<Person> filter = new SerializablePredicate<Person>() {
  @Override
  public boolean test(Person Person) {
    return false;
  }
};

filter.and(Person -> Person.getAge() == 30);
filter.and(Person -> Person.getName().equalsIgnoreCase("bernd"));
dataProvider.setFilter(filter);

}
However, the grid does not show anything.

A: Your conjunction always evaluates to false because it is modeled like:
false && Person.getAge() == 30 && Person.getName().equalsIgnoreCase("bernd")

Either you're using return true in the first filter, or you ommit it and start with Person.getAge() == 30.
Second problem is that you're ignoring the results of your conjunction. In addition to this, the method and is defined in Predicate and returns a non-serializable Predicate. Solution would be to use a simple &&.
SerializablePredicate<Person> filter = p -> p.getAge() == 30 &&
                                            p.getName().equalsIgnoreCase("bernd");

A: There are two different problems.
First one:
The function
default Predicate<T> and(Predicate<? super T> other)

returns a new predicate.
ListDataProvider<Person> dataProvider = (ListDataProvider<Person>)

grid.getDataProvider();
SerializablePredicate<Person> filter = new SerializablePredicate<Person>() {
  @Override
  public boolean test(Person Person) {
    return true;
  }
};

filter = filter.and(Person -> Person.getAge() == 30);
filter = filter.and(Person -> Person.getName().equalsIgnoreCase("bernd"));
dataProvider.setFilter(filter);

The other problem is, that ListDataProvider expected a SerializablePredicate.
You can extend the SerializiablePredicate
public interface ExtendedSerializablePredicate<T> extends SerializablePredicate<T> {

    default ExtendedSerializablePredicate<T> and(ExtendedSerializablePredicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }
}

now you can use this:
ListDataProvider<Person> dataProvider = (ListDataProvider<Person>)

grid.getDataProvider();
ExtendedSerializablePredicate<Person> filter = new ExtendedSerializablePredicate<Person>() {
  @Override
  public boolean test(Person Person) {
    return true;
  }
};

filter = filter.and(Person -> Person.getAge() == 30);
filter = filter.and(Person -> Person.getName().equalsIgnoreCase("bernd"));
dataProvider.setFilter(filter);


text:
Q: Windows Phone IsolatedStorageSettings: capacity and dynamic allocation I am going to save enough big amounts of data in my WP8 app using the handy IsolatedStorageSettings dictionary. However, the first question that arises is how big is it?
Second, in the documentation for the IsolatedStorageSettings.Save method we can find this:

If more space is required, use the IsolatedStorageFile.IncreaseQuotaTo
  method to request more storage space from the host.

Can we estimate the amount of required memory and increase the room for IsolatedStorageSettings accordingly? What if we need to do that dynamically, as the user is entering new portions of data to store persistently? Or, maybe, we need to use another technique for that (though I would like to stay with the handy IsolatedStorageSettings class)?

A: I have found the answer to the first part of my question in this article: How to find out the Space in isolated storage in Windows Phone?. Here is the code to get the required value on a particular device with some enhancements:
long availablespace, Quota;
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
   availablespace = store.AvailableFreeSpace ;
   Quota = store.Quota ;
}

MessageBox.Show("Available : " + availablespace.ToString("##,#") + "\nQuota : " + Quota.ToString("##,#));

The 512Mb WP8 emulator gave me the following values for a minimal app with few strings saved in IsolatedStorageSettings:

Lumia 920 reports even a much bigger value - about 20Gb, which gladdens my heart. Such a big value (which, I think, depends on the whole available memory in the device) will allow me to use the IsolatedStorageSettings object for huge amounts of data.
As for a method one can use to estimate the amount of data, I guess, this can be done only experimentally. For instance, when I added some strings to my IsolatedStorageSettings, the available space was reduced by 4Kb. However, adding the same portion of data again did not show any new memory allocation. As I can see, it is allocated by blocks of 4Kb.


text:
Q: Any line intersect with $bd(S)$ at at most two points. Then $S$ or $S^c$ must be convex.
Let $S$ be an open set on $\mathbb R^2$. $bd(S)$ is its boundary.
We've known that any line intersect with $bd(S)$ at at most two points.
Is it possible to show that one of the following conditions must hold?
(1) $S$ is connected convex or $S^c$ is connected convex
(2) $bd(S)$ is a discrete set

I first try to show that $S$ is connected by contradiction. Suppose $S$ is not connected. That is, there exists open sets $A,B\subset S$ such that $A\cap B=\emptyset$.
Then, there must exists a line crossing both $A,B$, and the line does not tangent their boundary (how to prove the existence of this line???)
This contradicts to the assumption that any line only intersect with $bd(S)$ twice.
Similarly, we can show that $S^c$ must either have empty interior, or $S^c$ is connected.
Therefore $bd(S)$ must be also connected.
Then suppose that $S$ is not convex. By definition, there exists two points, $x,y\in bd(S)$, such that, for some $a\in (0,1)$, $z=ax+(1-a)y$ does not belong to $S$. If the previous statement holds, then we have for any $a\in (0,1)$, $z=ax+(1-a)y$ does not belong to $S$.
This implies that $S^c$ is connected and convex?


text:
Q: 'System.AccessViolationException' Accessing SQL Query from VB.net Express 2013 I am having a weird problem with calling a SQL Stored Procedure from VB.
I have created a stored procedure on SQL. Code snippet as follows:
ALTER PROCEDURE [dbo].[PE0010_InsertDPW]
@DailyWashCycle AS INT,
@PumpNo AS INT,
@WashDurationSecs AS INT,
@Result AS INT OUTPUT
AS
BEGIN
SET @Result= 1
--All other code commented out
END

On the VB side, I have created a link to SQL and data set with this stored procedure in it. The actual VB code that calls the stored procedure is as follows:
Dim DailyCycle As Integer = 0
Dim PumpNo As Integer = 0
Dim Duration As Integer = 0
Dim res As Integer = 0
Dim DBQueries As New dsProcessDBTableAdapters.QueriesTableAdapter

DBQueries.PE0010_InsertDPW(DailyCycle, PumpNo, Duration, res)

I get the following message:

An unhandled exception of type 'System.AccessViolationException' occurred in Data Systems Manager.exe
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

However, if I comment out any variable other than @Result on SQL and update the stored procedure on VB and run it with 3 variables then it works fine.
The SQL procedure works fine if I execute it form SQL with all 4 variables so there must be something wrong with my link or something. I have tried changing the .NET Framework Data Provider to OLE DB from SQL Server when creating the link. Same problem occurs. Tried closing everything and opening it again. No difference.
Has anyone had the same problem? I'm completely out of ideas now.
PC:
Intel Core i5-3550 CPU @3.30GHz,
12GB RAM

A: Okay, I've figured out how to fix the issue but I still don't know why it was giving me so much trouble.
I compiled my project for .NET Framework 4 for compatibility with all our systems here at my work. This has never been an issue in the past but even new projects broke in the same way when I chose .NET 4. I had to install .NET Framework 4.5.2 (KB2901907) and everything just worked again after the system restart following that. Even for this project targeting .NET 4 (No other changes made). Weird, because a system restart was the first thing I tried. Seems like some kind of .NET Framework issue.


text:
Q: Per-word info needed in DVI to create touch rectangles on LaTeX documents in iTeX for the iPad When reading a LaTeX document on an iPad with iTeX, I need to know the position of every word on the page.  (I also need to know the positions of images, URLs, footnotes, etc., but they are all manageable by adding \special- s to the appropriate macros.) This could be used for searching, dictionary lookups, etc.
What I would love to do is insert a \special with some attribute before each word.  This would need some automatic per-word processing, because I want it for the whole document, and damn the expense! A new program, dvigrid, would emit lines needed containing the word's rectangle and other, specifiable information.
It needs to be a general solution, something that can live with the popular document classes.
A related need is the word ordinal in the output.  This would be a new answer to the old word-count question (which use external programs), except here TeX could count the words.
There are examples of commands that do this for every word in a parameter,
like putting the words in a box.  But none seem appropriate for doing an
entire document this way.  I can't find an appropriate hook or hack, even
deep inside the double danger parts of TeX.
Does anyone have a suggestion?  Can this even be done without modifying TeX?
For more information in iTeX, see http://itex.cheswick.com
My talk at TUG 2010 is at http://river-valley.zeeba.tv/tex-and-the-ipad/

A: Ideas:

*

*Use LuaTeX to intercept the paragraph breaker to emit whatsit nodes at every word boundary

*Study synctex - it may give you what you want (positions of every word etc.)

*Check out the creation of tagged PDF by ConTeXt or the patched pdfTeX


text:
Q: shared_ptr assignment in recursive function causing Segmentation Fault Apologies in advance for posting so much code...
I'm working on building a simulation of a dominoes-like game called Chickenfoot in which players draw "Bones" from a boneyard into their hands and then play dominoes on a field.
This is the first program in which I've tried using smart pointers and I've run into an issue that I cannot seem to pinpoint the cause. Occasionally running this program gives me a segmentation fault. A gdb stack trace can be seen below.
Strange shared_ptr behaviour this answer suggests that this could have something to do with this being a recursive function.
What am I doing wrong here? Also, if I am misusing any of these shared_ptr instances or could improve the implementation, any advice would be really appreciated - Thanks!
ChickenFoot.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Game.h"

const int NUM_OF_PLAYERS = 4;

int main(int argc, char** argv) {
    std::srand(std::time(0));

    Game* chickenfoot = new Game(NUM_OF_PLAYERS);
    chickenfoot->start(DOMINOES_SET_SIZE);

    delete chickenfoot;

    return 0;
}

Game.h
#include <memory>
#include <vector>
#include "Boneyard.h"
#include "Player.h"
#include "Field.h"

const int INITIAL_HAND_SIZE = 7;
static const int DOMINOES_SET_SIZE = 9;

const bool DEBUG = false;

class Game {
private:
    std::vector< std::shared_ptr<Player> > players;
    std::shared_ptr<Boneyard> boneyard;
    bool played_rounds[DOMINOES_SET_SIZE]; // This will keep track of which double rounds have already been played

    int getHighestUnplayedRound(bool* played);
    int getNextHighestUnplayedRound(bool* played, int round);
public:
    Game(int num_of_players);
    void start(int highest_double);
};

Game.cpp
#include "Game.h"
#include <iostream>

Game::Game(int num_of_players)
{
    boneyard = std::make_shared<Boneyard>();
    for (int i = 0; i < num_of_players; i++) {
        players.emplace_back(std::make_shared<Player>(i));
    }
    for (int i = 0; i <= DOMINOES_SET_SIZE; i++) {
        played_rounds[i] = false;
    }
}
void Game::start(int highest_double)
{
    if (highest_double < 0) {
        return;
    } else {
        boneyard->initialize();
        for (int i = 0; i < INITIAL_HAND_SIZE; i++) {
            for (std::vector< std::shared_ptr<Player> >::iterator j = players.begin(); j != players.end(); j++) {
                (*j)->draw(boneyard);
            }
        }
        for (std::vector< std::shared_ptr<Player> >::iterator i = players.begin(); i != players.end(); i++) {
            if ((*i)->hasDouble(highest_double)) {
                std::shared_ptr<Bone> hd_bone = (*i)->getDouble(highest_double);
                // Do something here to actually play the game...
                played_rounds[highest_double] = true;
                break;
            }
        }
    }
    for (std::vector< std::shared_ptr<Player> >::iterator i = players.begin(); i != players.end(); i++) {
        (*i)->discardAll();
    }
    if (played_rounds[highest_double]) {
        start(getHighestUnplayedRound(played_rounds));
    } else {
        start(getNextHighestUnplayedRound(played_rounds, highest_double));
    }
}

Player.h
#include "Bone.h"
#include "Boneyard.h"
#include <vector>
#include <memory>

class Player {
private:
    int id;
    std::vector< std::shared_ptr<Bone> > hand;
    struct isDouble {
        int m_value;
        isDouble(int value) : m_value(value) {}
        bool operator()(const std::shared_ptr<Bone> b) const {
            return (b->getLeft() == m_value && b->isDouble());
        }
    };

public:
    Player(int id);
    void draw(std::shared_ptr<Boneyard> yard);
    std::shared_ptr<Bone> getDouble(int number);
    bool hasDouble(int number);
    void discardAll();
};

Player.cpp
#include <iostream>
#include <algorithm>
#include "Player.h"
...
std::shared_ptr<Bone> Player::getDouble(int number)
{
    auto result = std::find_if(hand.begin(), hand.end(), isDouble(number));
    if (result != hand.end()) {
        hand.erase(std::remove_if(hand.begin(), hand.end(), isDouble(number)), hand.end());
        return *result;
    }
    return nullptr;
}
bool Player::hasDouble(int number)
{
    auto result = std::find_if(hand.begin(), hand.end(), isDouble(number));
    return (result != hand.end()) ? true : false;
}
void Player::discardAll()
{
    hand.clear();
}

trace:
(gdb) backtrace
#0  0x0000000000401a26 in std::_Sp_counted_base<(__gnu_cxx::_Lock_policy)2>::_M_release (this=0x622d10) at /usr/include/c++/5/bits/shared_ptr_base.h:150
#1  0x0000000000401505 in std::__shared_count<(__gnu_cxx::_Lock_policy)2>::~__shared_count (this=0x7fffffffd548, __in_chrg=<optimized out>) at /usr/include/c++/5/bits/shared_ptr_base.h:659
#2  0x0000000000401368 in std::__shared_ptr<Bone, (__gnu_cxx::_Lock_policy)2>::~__shared_ptr (this=0x7fffffffd540, __in_chrg=<optimized out>) at /usr/include/c++/5/bits/shared_ptr_base.h:925
#3  0x0000000000401384 in std::shared_ptr<Bone>::~shared_ptr (this=0x7fffffffd540, __in_chrg=<optimized out>) at /usr/include/c++/5/bits/shared_ptr.h:93
#4  0x0000000000405ad4 in Game::start (this=0x622030, highest_double=6) at Game.cpp:28
#5  0x0000000000405b8b in Game::start (this=0x622030, highest_double=7) at Game.cpp:39
#6  0x0000000000405b8b in Game::start (this=0x622030, highest_double=9) at Game.cpp:39
#7  0x0000000000405b8b in Game::start (this=0x622030, highest_double=8) at Game.cpp:39
#8  0x0000000000405bb7 in Game::start (this=0x622030, highest_double=9) at Game.cpp:41
#9  0x0000000000405b8b in Game::start (this=0x622030, highest_double=4) at Game.cpp:39
#10 0x0000000000405bb7 in Game::start (this=0x622030, highest_double=5) at Game.cpp:41
#11 0x0000000000405bb7 in Game::start (this=0x622030, highest_double=6) at Game.cpp:41
#12 0x0000000000405bb7 in Game::start (this=0x622030, highest_double=7) at Game.cpp:41
#13 0x0000000000405bb7 in Game::start (this=0x622030, highest_double=8) at Game.cpp:41
#14 0x0000000000405bb7 in Game::start (this=0x622030, highest_double=9) at Game.cpp:41
#15 0x0000000000408360 in main (argc=1, argv=0x7fffffffdaf8) at ChickenFoot.cpp:14

A: The problem is here...
std::shared_ptr<Bone> Player::getDouble(int number)
{
    auto result = std::find_if(hand.begin(), hand.end(), isDouble(number));
    if (result != hand.end()) {
        hand.erase(std::remove_if(hand.begin(), hand.end(), isDouble(number)), hand.end());
        return *result;
    }
    return nullptr;
}

You're erasing the value before returning it.  You can't do that.  Once you call hand.erase(), result (which is an iterator) is invalidated, and *result is garbage.
The function is pretty confusing in general, but I think you're shooting for something like this...
std::shared_ptr<Bone> Player::getDouble(int number)
{
    auto result_iter = std::find_if(hand.begin(), hand.end(), isDouble(number));

    if (result_iter != hand.end()) {
        // Saving the shared_ptr stops it from being released when we erase the iterator
        std::shared_ptr<Bone> result = *result_iter;

        // Remove the bone from hand
        hand.erase(result_iter);

        return result;
    }

    return nullptr;
}

Let me just add how I found this, because it boils down to reading the stacktrace.
The recursive calls to start are suspicious, but harmless.  This isn't a stack overflow error, so you're cool there.
The top 4 lines indicate that you're having an error in the destructor of a shared_ptr (meaning its data is corrupt somehow) and the line is Game.cpp:28 which is the line immediately after std::shared_ptr<Bone> hd_bone = (*i)->getDouble(highest_double);.
This is more or less a guarantee that your error is in getDouble which is a small enough function you can just focus on it to find the error.
The error here is unrelated to Strange shared_ptr behaviour.  In that case, the shared_ptr destructor call was happening recursively.  That's not happening here, where the shared_ptr destructor is only happening once.  This is a simple matter of you having a shared_ptr with corrupt data.


text:
Q: How to check if all numbers in a nested list are equal to n So I want to encode a secret image in another b&w image.
This image must have the same size as the original image that we are trying to hide the secret image in, so we have a correspondence of pixels for the two images.
To encode the secret image:
If a pixel in the secret image is white (so, with RGB values of [255, 255, 255]), add 1 to the blue component (last number).
Otherwise, leave the
blue component untouched.
So basically the coloured image is hidden in the b&w image by using an altered blue component from the original image.
Decoding the b&w image is done through reversal of the encoding process.
So lets say I currently have the following list of pixels:
P = [[0, 0, 0], [255, 255, 255], [255, 184, 254], [255, 0, 254]]

Assuming that the width and height of both images are the same.
How would I check if any 'pixel' in P is equal to 255? So this means that all 3 numbers in the 'pixel' must be equal to 255.

A: You can use
for idx,lst in enumerate(P):
    if lst==[255,255,255]:
       print(idx,lst)

or
enc_P=[]
for lst in P:
    if lst==[255,255,255]:
       print(lst)
    enc_P.append(lst)

A: Here is how you can check if all values in inner list are equal to 255 and it will return index of the inner list in P:
P = [[0, 0, 0], [255, 255, 255], [255, 184, 254], [255, 0, 254]]
def checker(P):
    for subP in P:
        if subP[1:] == subP[:-1] and subP[0] == 255:
            return subP, P.index(subP)

checker(P)

A: numpy based approach would be the fastest.
using numpy you could do something like this:
>>> import numpy as np
>>> P = np.array(P)
>>> np.all((P == 255), axis=1)
array([False,  True, False, False])

A: P = [[0, 0, 0], [255, 255, 255], [255, 184, 254], [255, 0, 254]]

count = 0
for i in range(len(P)):
    for j in range(len(P[i])):
        if P[i][j] == 255:
            count += 1
    if count == 3:
        print(i)
    count = 0

this way you can find all indexes that contains specific values in a 2D list.
the code above prints 1 because only P in index 1 contains the list [255, 255, 255]


text:
Q: Google map not shown? Searched every where what i did
1- created key in google console
2- enabled google maps for android
3- manifest
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="keyHere" />

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

4- added the fragment called async and still override fun onMapReady(p0: GoogleMap?) { not called

A: You might need a few more permissions up at the top:
<!--  Google Maps V2 API -->
<permission android:name="com.mycompany.myapp.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
<uses-permission
android:name="com.mycompany.myapp.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>


text:
Q: .Net Core 2.1 custom middleware issue with Authentication I have written a piece of custom middleware to check whether or not a user has a specific claim (required to use the application).  If the user doesn't I return a 422 Unprocessable.  I have noticed though that if I don't supply a token I receive a 422 and not a 401. If I check the IsAuthenticated property on the custom middleware it's false when you don't supply a token and true if you do.
Below is my Configure from Startup.cs.  You will notice that the UseAuthentication() happens before the UseClaimsValidationMiddleware() (my custom middleware).
My understanding of the request pipeline was that

*

*Authentication would fire.  If the user isn't authenticated (bearer token (jwt) using Auth0) then the middleware would short circuit and return a 401.

*If the user was authenticated it would hit my custom middleware and check if the claims exist.  If they don't the middleware will short circuit the request and return a 422.

*If the claims do exist it will pass onto the UseMvc() middleware and actually run the app.
I'm really confused as to why this happening, any ideas/pointers would be greatly appreciated :)
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseSwagger();

        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Test");
            c.RoutePrefix = string.Empty;
        });

        app.UseAuthentication();

        app.UseClaimsValidationMiddleware();

        app.UseMvc();
    }


text:
Q: Can someone compare SinonJS to Mock Service Worker MSW Can someone compare and contrast SinonJS to Mock Service Worker MSW? Something similar to https://mswjs.io/docs/comparison

A: Sinon is a general-purpose stubbing library for JavaScript. It allows you to stub (replace) various things: modules, functions, anything.
MSW specializes in API mocking and does not stub anything internally. Both in the browser and in Node.js, your request client (the code that does the actual request) gets executed, the requests get performed. They are then intercepted and responded with mocked data. This gives you much more confidence for testing and development simply because you're removing fewer parts of your application (stubbing === removing and replacing).
I can recommend Sinon for stubbing a module your application depends on during tests (although jest.mock is a good alternative). I would recommend MSW whenever you need to mock an API call.


text:
Q: Append data in file after time I created a method that append data to file .txt and it executes on Button_Click method. But I want to save the data to file not when I click the button but after time automatically (ex. after couple minutes starting from Application_Start). How can I solve my problem?
 static public bool appendToFileTxt(string input)
        {
            try
            {
                if (File.Exists(nameOfFile))
                    File.Copy(nameOfFile, nameOfFile + ".bak", true);
                        using (StreamWriter sw = new StreamWriter(nameOfFile, true)){
                                sw.WriteLine(input.Replace("\r", ""));
                        }
                return true;
            }
            catch{
                return false;
            }
        }

protected void Button1_Click(object sender, EventArgs e)
        {
             appendToFileTxt(newInput);
        }

A: You can use the Timer class for this usage.
// Simulate Application_Start
public static void Main()
{
    var appendToFileTimer = new Timer(AppendToFile, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
}

public static void AppendToFile(Object state)
{
    Console.WriteLine("Append to file");
}


text:
Q: Why do memcache calls (app engine) get interrupted? I'm using App Engine (java) with MemCache. When I try out my code all seems to work fine. But when I increase the load on my instances I sometimes get the following stacktrace.
com.google.api.server.spi.SystemService invokeServiceMethod: exception occurred while calling backend method
java.util.concurrent.ExecutionException: com.google.appengine.api.memcache.MemcacheServiceException: Unexpected failure
    at java.util.concurrent.FutureTask.report(FutureTask.java:106)
    at java.util.concurrent.FutureTask.get(FutureTask.java:186)
    at com.peerke.outdoorpuzzlegame.backend.gameclientendpoint.data.GameDataMerger.mergeGameData(GameDataMerger.java:52)
    at com.peerke.outdoorpuzzlegame.backend.gameclientendpoint.endpoints.ActiveGamesEndpoint.getMergedGameData(ActiveGamesEndpoint.java:236)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:44)
    at com.google.api.server.spi.SystemService.invokeServiceMethod(SystemService.java:363)
    at com.google.api.server.spi.SystemServiceServlet.execute(SystemServiceServlet.java:113)
    at com.google.api.server.spi.SystemServiceServlet.doPost(SystemServiceServlet.java:71)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
    at com.googlecode.objectify.ObjectifyFilter.doFilter(ObjectifyFilter.java:48)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.peerke.outdoorpuzzlegame.backend.common.gcp.NamespaceFilter.doFilter(NamespaceFilter.java:31)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:439)
    at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:446)
    at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:256)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:310)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:302)
    at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:443)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.google.appengine.api.memcache.MemcacheServiceException: Unexpected failure
    at com.google.appengine.api.memcache.MemcacheServiceImpl.quietGet(MemcacheServiceImpl.java:29)
    at com.google.appengine.api.memcache.MemcacheServiceImpl.get(MemcacheServiceImpl.java:49)
    at com.peerke.outdoorpuzzlegame.backend.common.datastore.DataManagerGame.getGame(DataManagerGame.java:39)
    at com.peerke.outdoorpuzzlegame.backend.common.datastore.DataManagerGame.getGameFromActiveGame(DataManagerGame.java:21)
    at com.peerke.outdoorpuzzlegame.backend.common.datastore.DataManagerGame$1.call(DataManagerGame.java:31)
    at com.peerke.outdoorpuzzlegame.backend.common.datastore.DataManagerGame$1.call(DataManagerGame.java:28)
    at com.peerke.outdoorpuzzlegame.backend.common.background.BackGroundTasks$ObjectifyCallable.call(BackGroundTasks.java:51)
    at java.util.concurrent.FutureTask.run(FutureTask.java:260)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1168)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:605)
Caused by: java.lang.InterruptedException
    at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:393)
    at com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:90)
    at com.google.appengine.tools.development.TimedFuture.get(TimedFuture.java:42)
    at com.google.common.util.concurrent.ForwardingFuture.get(ForwardingFuture.java:63)
    at com.google.appengine.api.utils.FutureWrapper.get(FutureWrapper.java:89)
    at com.google.appengine.api.memcache.MemcacheServiceImpl.quietGet(MemcacheServiceImpl.java:26)
    ... 9 more

When I look at the stacktrace I see that the MemcacheService.get(...) method is interrupted. But I have no idea why. The entire call was less then the 60 second limit.
Anybody has any idea?


text:
Q: jquery template engine, how to bind events Is there any way to pass function to bind into jQuery template engine?
http://api.jquery.com/tmpl/
If I create HTML without template I would do it like this:
jQuery("link").click(function(){alert('hi!')}).appendTo( "#forms_container" );

how to do this with jQuery templates?
------------EDIT
I found some library here
http://knockoutjs.com/documentation/template-binding.html
and seems it something like jQuery.live()
Is there any other ways for binding functions to templates, or this way is used as default mostly?
-----------EDIT
Ok, then let it be .delegate. I think for my small task it will be enough, without adding more complexity with Knockout

A: Similar to Ian's, but a bit different in implementation:
jQuery('#forms_container').delegate('a', 'click', function() {
   //Click event, with context (faster)
});

This means that all links in the forms_container will have that click event, no matter what changes.  This differs from Ian's (perfectly legitimate) use of live in that it has a context, so events don't need to bubble all the way up.  You can accomplish the same thing using live (as of 1.4) if you give it context, but I prefer delegate's syntax.

A: Give your link something to identify it by (a class or similar or based on the parent container(s)). then use .live

then:
$('a.tmplClick').live('click',function(){
    alert('clicked in template');
});


text:
Q: Getting error while I specify ajax response for attribute of an angular directive in DOM I created a new directive in Angular1(v1.3.15) and specified a new attribute for it in DOM like this:
<event-action-choices appointment-action-list="getAppointmentDataForEvent(${intEvent.id})" userbar="${false}" event-id="${intEvent.id}"></event-action-choices>
Following is the code for my controller and directive
module.controller('EventActionDataController', [
'$scope',
'$log',
function ($scope, $log) {

    $scope.getAppointmentDataForEvent = function (eventId) {

            return [{"childId":12,"parentId":11}];
    };

}]);

    module.directive("eventActionChoices", function() {
return {
  restrict: 'E',
  scope: {
    eventId: '=eventId',
    userbar: '=userbar',
    appointmentActionList: '=appointmentActionList',
  },
  templateUrl: $("#baseUrl").val()+'/path/to/eventActionChoices.html',
};});

However, I am getting error while calling this directive

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
  Watchers fired in the last 5 iterations: [[{"msg":"fn: regularInterceptedExpression","newVal":[{"childId":12,"parentId":11}],"oldVal":

My motive is to get the response of Ajax request from getAppointmentDataForEvent method. However, even the hardcoded response which I am trying to send back is giving me same error.


text:
Q: PDF field to query SQL database I'm attempting to find a way that a user can click a button (or something along those lines) on a PDF to query the SQL database.  I have the query running the way I want it to run.  My only problem is figuring out how to set up the connection from the PDF file to query the database.
This PDF is a template that the user will fill out completely except for one field.
Will this require an ODBC connection?  Any suggestions?


text:
Q: 13.10 Ubuntu mouse problem I have upgraded from Ubuntu 12.04 to 13.10 and I'm currently experiencing a mouse problem. The pointer blinks very fast and most of the time is not even visible.
I've tried the solution given in a different post, which was to change something on the display settings, but without any outcome.
On 12.04 there was no such a problem.

A: Try this:

*

*Open a terminal an run
gsettings set org.gnome.settings-daemon.plugins.cursor active false

*OR run dconf-editor
Navigate to org.gnome.settings-daemon.plugins.cursor and set the key active to false.

A: I have had the same problem you can push ctrl + alt + f6 goes to tty, and then type.
  sudo apt-get update
  sudo apt-get install --reinstall ubuntu-desktop
  sudo shutdown -r now

Or change mouse curser theme.
It will might work, and you can also disable mouse in settings, and then enable it again it works in kubuntu.


text:
Q: Windows 10 takes too long at logo and spinning dots on boot On hard reboots, that is, restarting the PC or unplugging it, Windows takes around 4-5 minutes to fully boot. The part that takes the longest is the logo + spinning dots.

The dots spin for maybe 4 minutes until I finally get to the log in screen. This is very tedious and shouldn't happen on a SSD.
The PC boots in mere seconds if I enable fast startup.
Things I have tried already:

*

*Disabling fast startup

*Checking for viruses

*Performing a clean boot

*Updating drivers

*Updating Windows

*Uninstalling NVIDIA drivers

*Disabling Intel Management Engine Interface

*Unplugging all unnecessary USB/external devices

My specifications:

*

*Intel i7 6700k @ 4.6Ghz

*NVIDIA GeForce GTX 1070

*SanDisk SSD Plus 240GB (boot and OS)

*Seagate Barracuda 2TB 7200RPM (for data)

*Corsair Vengeance 2x8GB DDR4 2400Mhz

*Gigabyte Z170X Gaming 3

I ran Windows Performance Recorder and I'm willing to share the boot trace. You can download the corresponding ETL file here (Google Drive).


text:
Q: How to determine the file name involved in an IO operation using windows etw tracing? I am trying to create a consumer application in  vc++, which will collect all disk events using etw tracing at real-time.
I have enabled two flags, the  EVENT_TRACE_FLAG_DISK_FILE_IO and the EVENT_TRACE_FLAG_DISK_IO for tracing but the problem is I am not getting as many FileIO_Name events compared to the number of DiskIo_TypeGroup1 events.
But If I only enable the EVENT_TRACE_FLAG_DISK_FILE_IO  flag then I am getting more number of FileIO_Name events in my calllback.
FLAG                                          EVENT

EVENT_TRACE_FLAG_DISK_IO                      Enables the following DiskIo event types:
0x00000100                                     DiskIo_TypeGroup1
                                               DiskIo_TypeGroup3

EVENT_TRACE_FLAG_DISK_FILE_IO                 Enables the following FileIo event type:
0x00000200                                    FileIo_Name

I guess I need both the flags because... from the FileIO_Name events I will get FileObject and FileName  data and from DiskIO_TypeGroup1  I will get FileObject , DiskNumber , TransferSize and other data's I need to match the common fileobjects to merge both separate data set and get the desired output.
so when I use both flags I get the DiskIO_TypeGroup1:FileObject ratio as 4:1.
But when I tweet my code to get only the FileIO_Name event I get 3x times the events that I was getting earlier, if not more.