text:
Q: For loops in R and computational speed In the past I have written R code that requires for loops inside of for loops. Generally this code is rather time consuming to execute. I have read online this is a result of how for loops in R work. I have also read that using for loops in another language inside R e.g. C++ or Java, can speed up the computational time.
Does anyone have experience with this and can point me to some simple examples that I can read?
Also can you call another language for the for loop, but still have everything inside the loop be in standard R code?

A: I do have some experience of this as I worked on a project in which it was necessary to write some loops in C in order to speed up the code.
First, it's useful to note that there is a lot of information about R's for loops on the main Stackoverflow site. For example, the question Speed up the Loop Operation in R has at least two excellent answers which I found very helpful. Also, the R Inferno as suggested by Roman Luštrik above has a lot of good advice.
Assuming that you've vectorised everything that can be vectorised, removed as much as possible from inside the loops, worried about the fact that ( is a function call, and so on, you are asking: what to do next?
(Aside: as I understand it, from asking questions on various sites, R is written in C, and almost everything you write in R is a function call at the C level. This means that if you are doing things over and over again, you should make sure that your code makes as few function calls as possible, as these can really add up, paricularly in a double for loop. That's why it's interesting that innocent-looking things like brackets are actually function calls.)
The first place you will be told to look when trying to extend R is the Writing R extensions manual. This hasn't worked out very well for me as it's not written with the casual R user in mind. Instead, I have found Matloff's book The Art of R Programming to be a lot more helpful. The link is to a pdf draft of the book; the book itself contains more detailed examples. In fact, I now see that the example is not included in the above pdf; sorry.
Anyway, it turns out that there are two ways to call C from R, called .C and .Call. Many people don't recommend using .C, but it has the advantage of being much easier to use, and the people who tend to discourage it also tend to be hard-core programmers.
There are numerous online tutorials on how to use the .C Interface with examples, for example this one from Simon Fraser University. Basically, you have to write the function you want to call in C, it has to have return type void and it has to accept pointers as arguments. I hadn't tried using C when I first started trying to learn this, and I learned what I needed to know from a book called C Programming in Easy Steps. Another good reference, which is available online for free, is the book Modeling with Data by Ben Klemens, which is a statistics textbook which uses C as the language of choice and assumes no prior knowledge. I found it very helpful for learning about pointers.
If you are trying to make examples of .C run "out of the box" then it helps to be working in a UNIX environment. I haven't been using one of those, and it is much harder to get things to work on Windows; I have a feeling that many people feel that using Windows is somehow evil and are reluctant to help those who use it, which is a pain if you are a data analyst who happens to have no other choice. Or possibly this is unfair, and people who use Windows are simply expected to be familiar with the command line.
I don't want to go into the details of getting .C to work on Windows, just in case you aren't using it. What I can say is that I know nothing about computers, but I did manage to do it, and so it can be done.
A newer alternative to using .C or .Call is the Rcpp package. Dirk Edelbuettel, one of the package authors, is very active on Stackexchange and is very likely to help you if you have questions about this package, or any other R/C interface. As recommended above by Roman Luštrik, this package is likely to be a very good option. I haven't used it myself as I have not yet been able to install it under Windows.
As for the final part of your question, asking whether you can write a for loop in a foreign language and then just use R code inside the loop, I am pretty sure, unfortuately, that there is no good way of doing this. It would be great if you could just skip over having to use R's for altogether, but I don't think it works this way. You can, however, use various R functions in the C code if you include the R.h header file. Again, it's hard to get this to work on Windows. In particular, you have to install a thing called Rtools. But once it's working, writing a small piece of C code is almost as easy as writing the corresponding R code.
Anyway, I hope some of these references are somewhat helpful. The best option to try first is to write the R code as efficiently as possible. Next, try Rcpp. If this doesn't work, or if you are doing something fairly minor, then I recommend .C. I am sure some experts will turn up with better advice, but I hope it's at least somewhat useful to have an answer from a non-programmer who has struggled with these issues.

A: If you're nesting loops in R, but haven't got enough experience of R to know when to use them and when not to, you're probably not taking full advantage of the language.
For loops in R are not always slower than other approaches, like apply - but there's one huge bugbear -

*

*never grow an array inside a loop

Instead, make your arrays full-size before you loop and then fill them up.
Outside of that, there are frequently functions which do vector-type operations that are pretty fast that you can take advantage of that do sometimes speed up code, and sometimes ways of organizing your code that can have substantive speed improvements.
You can go to tools like Rccp and inline which can be a big help, but often you can do a lot just in vanilla R.
More explicit help would depend on your specific problems.


text:
Q: Prevent a layer rotation on map rotate in mapbox-gl Is there anyway to disable layer rotation on map ratation ?
I am using a symbol layer with arrow image icon and I don't want them ro ratate with map and stay fixed.

A: You should set "icon-rotation-alignment" to "map" (it's "auto" by default).
https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#layout-symbol-icon-rotation-alignment:

"map": When symbol-placement is set to point, aligns icons east-west.
When symbol-placement is set to line or line-center, aligns icon
x-axes with the line.

redpajama_set_name: RedPajamaStackExchange


text:
Q: EDMX and stored procedures; I can't see a method to call my SPROC in the context I added a SPROC to my EDMX using the update model option.
I then did a function import and assigned it a null return type.
The problem is when I try to call the SPROC from myContext.Current, there is no sign of it.
Am I missing something?

A: Are you using EF v4? This was not possible in EF v1, see, for example, this question.


text:
Q: How to convert country code to name with country_converter, in pandas df
         Date        Value CODE
0      2020-03-12      7  AFG
1      2020-03-11      7  AFG
...

How could I generate the country from the code? I tried which just generated the code from the CODE variable
import country_converter as coco
df['country'] = df['CODE'].apply(coco.convert)

Actual Output:
         Date        Value CODE  country
0      2020-03-12      7  AFG     AFG
1      2020-03-11      7  AFG     AFG

Expected Output:
         Date        Value CODE  country
0      2020-03-12      7  AFG     Afghanistan
1      2020-03-11      7  AFG     Afghanistan

A: *

*As per the country_converter documentation.

*Valid values for the to and src parameters can be found with coco.CountryConverter().valid_class.

import country_converter as coco
import pandas as pd

# setupt test dataframe
df = pd.DataFrame({'code': ['AFG', 'USA', 'RU']})

# add country name by applying the convert method
df['short name'] = df.code.apply(lambda x: coco.convert(names=x, to='name_short', not_found=None))

# display(df)
  code     short name
0  AFG    Afghanistan
1  USA  United States
2   RU         Russia

# converting the column to a list and passing it to the method also works to add the short name
df['short name'] = coco.convert(names=df.code.tolist(), to='name_short', not_found=None)


text:
Q: Decode Email body in GMAIL (ios) I have problems reading an email from GMAIL.
This is how I get each email:
- (void)displayResultMessageWithTicket:(GTLServiceTicket *)ticket
                    finishedWithObject:(GTLGmailMessage *)email
                                 error:(NSError *)error
{
    if (error == nil) {
        NSMutableString *labelString = [[NSMutableString alloc] init];

        GTLGmailMessagePart* payload=email.payload;
        NSLog(@"payload =%@",payload);

        for(GTLGmailMessagePart* part in payload.parts)
        {
            GTLGmailMessagePartBody* body = part.body;
            NSLog(@"body =%@",body);
            NSLog(@"data =%@",body.data);
        }
        self.output.text = labelString;
    }
    else
    {
        [self showAlert:@"Error" message:error.localizedDescription];
    }
}

I think that body is encoded with something like base64, but i'm not sure.
this is an example of what I get:
Q3J1bmNoIERhaWx5DQoNClRvZGF5J3MgVG9wIFN0b3JpZXMgLy8gSnVsIDYsIDIwMTUgUmVhZCBtb3JlIGF0IHRlY2hjcnVuY2guY29tIDwjPiBJZiB5b3UgZG8gbm90IHdhbnQgdG8gcmVjZWl2ZSB0aGlzLCB5b3UgY2FuIHVuc3Vic2NyaWJlIHdpdGggb25lIGNsaWNrIGhlcmUgPGh0dHA6Ly9saW5rLnRlY2hjcnVuY2guY29tLzU0ZWQ3ZDc2ZmExM2ExYWQyMjhiNTA2ZjJzcGJnLmc4aS9VQnJ0TnFndnVHMEFyVWxLQjA5YWQ-Lg0KDQpUZWNoQ3J1bmNoIDQxMCBUb3duc2VuZCBTdHJlZXQsIFNhbiBGcmFuY2lzY28sIENBIDk0MTA3DQoNCsKpIDIwMTIgQU9MIEluYy4gQWxsIHJpZ2h0cyByZXNlcnZlZC4gUHJpdmFjeSBQb2xpY3kgPGh0dHA6Ly9saW5rLnRlY2hjcnVuY2guY29tLzU0ZWQ3ZDc2ZmExM2ExYWQyMjhiNTA2ZjJzcGJnLmc4aS9VQnJ0TnFndnVHMEFyVWxLQ2NiNWE-IFRlcm1zIG9mIFNlcnZpY2UgPGh0dHA6Ly9saW5rLnRlY2hjcnVuY2guY29tLzU0ZWQ3ZDc2ZmExM2ExYWQyMjhiNTA2ZjJzcGJnLmc4aS9VQnJ0TnFndnVHMEFyVWxLRDRkZjU-DQoNCklmIHlvdSBiZWxpZXZlIHRoaXMgaGFzIGJlZW4gc2VudCB0byB5b3UgaW4gZXJyb3IsIHBsZWFzZSBzYWZlbHkgdW5zdWJzY3JpYmUgPGh0dHA6Ly9saW5rLnRlY2hjcnVuY2guY29tL29jLzU0ZWQ3ZDc2ZmExM2ExYWQyMjhiNTA2ZjJzcGJnLmc4aS84YzIyN2ZiNz4u

How can i decode it??

A: Body of the message is base64url encoded. You need to decode that also replace "_" with "/" and "-" with "+" in the encoded string before base64 decoding it.

A: Complementing the Furhan's answer
var parts = eachItem.payload.parts
let body: AnyObject? = parts[0].valueForKey("body")
var base64DataString =  body!.valueForKey("data") as! String
base64DataString = base64DataString.stringByReplacingOccurrencesOfString("_", withString: "/", options: NSStringCompareOptions.LiteralSearch, range: nil)
base64DataString = base64DataString.stringByReplacingOccurrencesOfString("-", withString: "+", options: NSStringCompareOptions.LiteralSearch, range: nil)

let decodedData = NSData(base64EncodedString: base64DataString, options:NSDataBase64DecodingOptions(rawValue: 0))
let decodedString = NSString(data: decodedData!, encoding: NSUTF8StringEncoding)
println(decodedString)

A: There is a GTL API can do decode OOTB.
Here is my working code.
//... get part
let body : GTLGmailMessagePartBody = part.body
let bodyAttachmentId = body.attachmentId
let bodyData : String! = body.data
let bodySize = body.size

//Use GTLDecodeWebSafeBase64
if bodyData != nil
{
    let decodedData = GTLDecodeWebSafeBase64(bodyData)
    let decodedString = NSString(data: decodedData!, encoding: NSUTF8StringEncoding)

    print("after decoded: \(decodedString)")
}

A: if let bodyPart = message.payload?.parts.filter({ $0.mimeType == "text/html" }).first, let bodyDataEncoded = bodyPart.body?.data {
    logger(bodyPart.body?.size)
    let base64Encoded = bodyDataEncoded.replacingOccurrences(of: "_", with: "/").replacingOccurrences(of: "-", with: "+")
    let data = Data(base64Encoded: base64Encoded)
    logger(data?.count)
}

You can load data in webview
webView.load(data, mimeType:mimeType, textEncodingName: "", baseURL: baseUrl)

See more: https://developers.google.com/gmail/api/v1/reference/users/messages#resource


text:
Q: Dummy variables overpower important feature I'm trying to use linear regression to predict estimated queueing time given a dataset of queueing records. The records contain the day of week, hour of day, and number of customers ahead in line.
Clearly, the number of customers ahead in line is the most important variable, so we would expect that that variable will have the "biggest" coefficient in the linear regression.
I want to also include the other variables, but since they're categorical, I used dummy variables (so I have 7 for day of week: is_Monday, is_Tuesday,... is_Sunday). I feel, however, that the dummy variables are too many so they're "overpowering" the important variable.
How do I solve this issue?

A: I believe you are misinterpreting your results. I see two issues. You are mistaking statistical significance for effect size, and misinterpreting the regression coefficients. There is no reason for the estimated coefficient of the "CustomersAhead" variable to be larger than the ones estimated for the dummies. In fact, i would expect it to be lower!
Suppose you have the following regression:
WaitingTime =  MondayDummy + TuesdayDummy + ... + 10amDummy + 11amDummy +...+
               CustomersAhead
What the estimated coefficients are telling you:
MondayDummy = Average waiting time on Mondays (same interpretation applies for the other day dummies)
10amDummy = Average waiting time at 10am (same interpretation applies for the other time dummies)
and the most important variable to your question:
CustomersAhead = the increase in waiting time if we increase the customers ahead in line by 1 person.
Making sense of it
From the above, it is easy to see why you should not expect the coefficient for the last variable to be higher than the other coefficients. Adding one more person to the line cannot add more than the average waiting time...it will add much less.
For example, the average waiting time on Mondays could be 35 minutes. But the difference between having n or n+1 CustomersAhead of you could be an extra 2 minutes.
This does not mean that CustomersAhead does not have a "big importance" (as you put it in your question). This is in fact determined by the p-value. The coefficient is merely telling you the effect size of the addition of an extra person.
Finally:
As pointed out in the comments under your question, since you have count data (number of minutes or hour?) perhaps a GLM approach using a Poisson model would yield more appropriate results, but this is unrelated to your initial question.


text:
Q: Integer valued MLE in normal distribution Suppose $Z_1,...Z_n$ are i.i.d $N(\mu,\sigma^2)$ where  both $\mu$ and $\sigma$ are integers, while $\sigma$ is a power of 10. (So $\log_{10}(\sigma)\in\mathbb{Z}$). I am trying to show that the MLE can be found by rounding the sample mean to the nearest integer. Additionally I want to construct an estimator for $\sigma$ that maximizes the likelihood that $\log_{10}(\sigma)\in\mathbb{Z}$.
Attempt: define the function $f(\delta)=\sum_{i=1}^n(x_i-(\bar{x}+\delta))^2$. This function is even as a function of $\delta$. The Log-likelohood is of this form. Since this is a parabola we have that the maximum must occur at the unique value (since $f$ is an even function, our max has to be unique) however I have no idea how to incorporate the fact that $\mu$ is an integer? Furthermore I have no idea how to construct an estimator for $\sigma$.


text:
Q: get all attributes from nodes with same name I have an xml-file with products.
I have split it up into a table with one row for each product with product number and xml
SKU |  xml
----|-------
1111|<product><price>123</price....</product>
1112|<product><price>345</price....</product>

The attributes are stored like this:
<attribute-list>
    <attribute name="tax_id" attribute-type="integer"><value default="1">2</value></attribute>
        <attribute name="weight" attribute-type="integer"><value default="1">258</value></attribute>
        <attribute name="length" attribute-type="integer"><value default="1">180</value></attribute>
        <attribute name="width" attribute-type="integer"><value default="1">115</value></attribute>
        <attribute name="height" attribute-type="integer"><value default="1">15</value></attribute>
        <attribute name="series_name" attribute-type="string"><value language-id="DE" default="1"><![CDATA[CSV]]></value></attribute>
        <attribute name="country_of_origin_code" attribute-type="string"><value default="1">LT</value></attribute>
        <attribute name="number_of_pages" attribute-type="string"><value default="1">288</value></attribute>
...
</attribute-list>

Different products may have different attributes, for instance shoe-size is not relevant for a book :-)
I'd like to select all possible attribute-names.
attr
----
weight
length
number_of_pages
shoe_size

I can get all the possible values for a given attribute-name
select distinct xml.value('(/product/attribute-list/attribute[@name="color"])[1]',
'varchar(100)') as colors from product_xml

I'm getting close with
 SELECT distinct cast(T2.attr.query('.') as nvarchar(max))
 FROM   product_xml
 CROSS APPLY xml.nodes('/product/attribute-list/attribute') as T2(attr)

Here I get a record for each possible attribute-name and value
So I'm just missing the last step of only getting the name.
EDIT: The quick-and-dirty version is here:
;with p as (SELECT distinct cast(T2.attr.query('.') as nvarchar(max)) at
FROM   product_xml
CROSS APPLY xml.nodes('/product/attribute-list/attribute') as T2(attr))
select distinct left(at,CHARINDEX('>',at)) from p

This produces each attribute in a record by itself, which I can then manipulate in the application (php), Not as clean as just getting the name alone, but easily parsed, and only to be used very rarely.
<attribute name="age_rating" attribute-type="string">
<attribute name="aroma" attribute-type="string">
<attribute name="barcode" attribute-type="string">
<attribute name="barcode_type" attribute-type="string">

A: Is this what you're looking for? This statement lists all @name attributes for each attribute, and then also grabs the actual Value as well as the @DefaultValue from the <Value> subnode:
SELECT DISTINCT
    AttrName = XC.value('@name', 'varchar(50)'),
    DefaultValue=XC.value('(value/@default)[1]', 'varchar(50)'),
    Value=XC.value('(value)[1]', 'varchar(50)')
FROM
    product_xml
CROSS APPLY
    xml.nodes('/product/attribute-list/attribute') AS XT(XC)

This shows me something like:

A: Solution based on @mark_s
SELECT distinct AttrName = attr.value('@name', 'varchar(50)')
FROM   product_xml
CROSS APPLY xml.nodes('/product/attribute-list/attribute') as T2(attr)


text:
Q: Regression following Principal Component Analysis I am not sure if i did not add enough information or i am posting to the wrong section but if i am please let me know as it is my first time using the site.
I have carried out Principal Component Analysis on my dataset and have reduced my dimensions. I would like to run some basic regressions using the first two components as explanatory variables.
Does anyone know how I would do this and what code I would need to use.
I am not the greatest on R as you may tell so any help anyone can provide would be gratefully appreciated.
One of the replies had suggested using prcomp but as i used a correlation matrix and the princomp command would that still be appropriate?
pro1.pca <- princomp(pro1,cor = T)
k <- 4
pro1.scores <- pro1.pca$scores[,1:k]
    round(pro1.pca$loadings[,1:k],3)
    ##                          Comp.1     Comp.2    Comp.3     Comp.4
    ## Hazardous Drinker         0.292     0.381     0.423      0.478
    ## Cardiovascular Condition -0.351    -0.238     0.599     -0.350
    ## Fruit + Veg-5 or more     0.444    -0.039     0.139     -0.558
    ## General Health Score 4+  -0.099     0.603     0.350     -0.148
    ## Obese                    -0.457    -0.131    -0.196      0.281
    ## health- very good         0.357    -0.289     0.273      0.461
    ## Current Smoker           -0.133     0.576    -0.294     -0.048
    ## Meets Activity Levels:    0.480     0.005    -0.348     -0.149

A: You did not share any data but this example may be useful. First code the PCA, then store the components in a new dataframe. After that, bind components with original data and then design the linear model. Here the code uses only base-R and example data iris:
#Data
data(iris)
#PCA
pcamod <- prcomp(iris[,-5],scale. = T)
#Extract components
comp <- as.data.frame(pcamod$x)
#Create dataframe for regression
newdata <- cbind(iris[,-5],comp)
#linear model
mod <- lm(Sepal.Length~PC1+PC2,data=newdata)
summary(mod)

Output:
summary(mod)

Call:
lm(formula = Sepal.Length ~ PC1 + PC2, data = newdata)

Residuals:
     Min       1Q   Median       3Q      Max
-0.61478 -0.12606 -0.00421  0.15399  0.48173

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  5.84333    0.01894  308.56   <2e-16 ***
PC1          0.43148    0.01112   38.79   <2e-16 ***
PC2         -0.31253    0.01987  -15.72   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.2319 on 147 degrees of freedom
Multiple R-squared:  0.9226,    Adjusted R-squared:  0.9215
F-statistic: 876.1 on 2 and 147 DF,  p-value: < 2.2e-16


text:
Q: How to use spring cloud sleuth traceId in kafka consumers I am using springboot 2.3.4, corresponding spring-kafka 2.5.6.RELEASE, springcloud sleuth 2.2.5,
I use @KafkaListener to listen for Kafka messages, but during the test I found that the producer has a traceId, and I need the consumer to generate a new traceId, but unfortunately there is no traceId in the log print. I am a novice, which makes me very confused. Do I need to enable certain configurations, or I need to implement trace by myself?
thanks!!
 @KafkaListener( topics = {"#{'${kafka.topics}'}"}, containerFactory = "batchMessageFactory")
    public void onMessage(List<ConsumerRecord<String, String>> records) {
        if(!CollectionUtils.isEmpty(records)) {

            records.stream().forEach(record -> {
                String message = record.value();
                log.info("messge:{}",message)
            }
            });
        }


text:
Q: py.test: command not found I installed pytest via MacPorts:
sudo port install py34-pytest

but it doesn't work:
py.test --version
-bash: pytest: command not found

pip freeze shows it as installed. If I install it via pip instead of ports the same thing happens.


text:
Q: Populate dynamically added select boxes from MySQL Database I got confused at some point in my project.
The thing I am trying to make here is as following:
Get data from the database
Create a new select box with the button - create
Populate this select box with values from the database
Option to delete that select box through the button - delete
The code I have so far PHP/HTML:
   <button type="button" name="add" onclick="return false;" id="addField" class="nice_button">Добавить(ADD)</button>

   <button type="button" name="remove" onclick="return false;" id="remove" class="nice_button">Удалить(DELETE)</button>

        <select size="1" name="hardware[]" style='width:400px;'>
        <option value=""></option>
        <?php   while($hardware = $get_hardware->fetch_array()){
          echo "<option  value='".$hardware['st_id']."'>".$hardware['st_name']." ".$hardware['st_producer']." ".$hardware['st_model']."</option>";
        }
        ?>
        </select>

JS script I have so far looks like that:
var g = 1;
var id = [ <? php echo $js_id; ?> ];
$(document).ready(function Product_add() {
    $("#addField").click(function () {
        $("#documentFields").append('
<select size="1" name="hardware[]" style="width:400px;"><option value=""></option></select>
');
        g++;
    });
});
$(document).ready(function Product_add() {
    $('#remove').click(function () { // similar to the previous, when you click remove link
        if (g > 1) { // if you have at least 1 input on the form
            g--; //deduct 1 from i so if i = 3, after i--, i will be i = 2
            $('#fieldset_p' + g + '').remove(); //remove the last fieldset
        }
    });
});

The thing is that I cannot append php function: while, so I cannot populate this select box as the one before.

A: In this case you could use Ajax.
What's ajax:
http://en.wikipedia.org/wiki/Ajax_(programming)
It's providing a page with just your information in a specific format. Then call it with your javascript and then parse it into the page.
Documentation how to do this in jquery:
http://api.jquery.com/jQuery.ajax/

Update:
Code example:
$.get('ajax/test.html', function(data) {

    // read in data = = [{'option':'option 1'},{'option':'option 2'}]

      $.each(data, function(index, itemData) {
       /// do stuff
         $('<option>' + itemData.option + '</option>').appendTo('#myselectbox');
      });

});


text:
Q: Override WordPress media manager hook I am creating a WordPress plugin and am trying to overwrite the following value in javascript:
'query-attachments' within /wp-includes/js/media-models.js around line 1086.
However the issue the I am having is I cannot seem to figure out where I can change the options parameter within the sync function, where from there I can change the action value?


text:
Q: Delete ,then Insert Data on table without closing program and run it again I want to insert data on mysql database  directly after delete ,my program check if there is no data on table before insert, i delete data from table ,the program run perfectly and data are deleted, but when I want TO insert ,message apppear tell me that the table contain data !?, it's some thing of cache or handling ,,!!!? , Have you any idea
MY Code :
     try {
            String sqll = "Select * from CG1";
            pst = con.prepareStatement(sqll);
            rs = pst.executeQuery();
            // int c = 0;
            while (rs.next()) {
                nam = rs.getString(1);

            }
            System.out.println(nam);
        } catch (SQLException ex) {
            Logger.getLogger(NewJFrame1.class.getName()).log(Level.SEVERE, null, ex);
        }

    //
        if (nam == null || Integer.parseInt(nam.toString()) == 0) {
            try {

                //   con.setAutoCommit(false);

                pst = con.prepareStatement("insert into CG1(Exe,Mois,Journal)values(?,?,?)");

                for (int i = 0; i < dtm.getRowCount(); i++) {
                    String exe = dtm.getValueAt(i, 0).toString();
                    String mois = dtm.getValueAt(i, 1).toString();
                    String journal = dtm.getValueAt(i, 2).toString();

                    pst.setString(1, exe);
                    pst.setString(2, mois);
                    pst.setString(3, journal);

                    pst.addBatch();

                }
                pst.executeBatch();
                //  con.commit();

            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);
            }

        } else {
            if (JOptionPane.showConfirmDialog(null, "Data EXIST,Would You Like TO DeLETE IT !!", "INFO", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                try {
                    pst = con.prepareStatement("delete * from CG1 ");
                    pst.executeUpdate();

                } catch (SQLException ex) {
                    Logger.getLogger(NewJFrame1.class.getName()).log(Level.SEVERE, null, ex);
                }finally{
if(pst!=null){
pst.close();
}
if(rs!=null){
rs.close();
}
if(con!=null){
con.close();
}
}
                JOptionPane.showMessageDialog(rootPane, "DATA DELETED");

            }

        }

        }catch(Exception e){

        }

A: If you want to insert data after delete then your insert logic should be in else part after performing delete.
You should have your insert logic in a different method and call it inside if statement when no data is present in DB and also in else statement after performing delete.


text:
Q: Stored procedure call fails when called from asp.net web app but works when called from SSMS Background:
We recently had a project where we had to plot Institutions on a Google map however using the address to pinpoint the institution took way to long to load. Therefore we decided to store the lat/lng in the database against the institution record. To get this we created a Stored Procedure usp_web_kam_Geocode that calls the GoogleMaps geocoding service to return the coordinates which are then stored.
We then created a trigger trg_Geocode on tblInstitution after INSERT, UPDATE which providing some conditions were met (bIncludeInKAMMap = 1 i.e. its to be plotted) then it called usp_web_kam_Geocode and updates the coordinates on the record.
Problem:
Once this trigger was added to the table any call to usp_web_InsertUpdateInstitution (responsible for inserting and updating tblInstitution) fails without a error when called from the web app..
We have used SQL Server Profiler to trace this call to usp_web_InsertUpdateInstitution which produced the following:

declare @p1 int
set @p1=149078313
exec usp_web_InsertUpdateInstitution @lInstitutionID=@p1 output,@lRegionID=132,@TOREFMadisunNumber=N'',@sSageNumber=N'',@sName=N'Replication Test Changed',@Xaddress=N'',@sPostCode=N'GU97DR',@sPhone=N'',@sFax=N'',@lInstitutionTypeID=14,@sNote=N'',@lModifiedByID=0,@sAddress1=N'',@sAddress2=N'',@sAddress3=N'',@sTown=N'',@sCounty=N'',@TOREFCountry=N'',@sWebsite=N'',@lDistributorID=2,@XFCRef=0,@sSICCode=N'',@lEmployees=0,@sSource=N'',@bKeyAccount=0,@TOREFProspectType=N'',@sVAddress1=N'',@sVAddress2=N'',@sVAddress3=N'',@sVTown=N'',@sVCounty=N'',@TOREFVCountry=N'',@sVPostcode=N'',@bHasSepticUnit=0,@lBusinessManagerTempID=0,@lProspectTypeID=1,@lGroupID=1,@lCountryID=180,@lVCountryID=-2,@bDeleted=0,@lValueID=NULL,@sGeneralEmail=N'',@lMarketingID=48509669,@sVisitingAddress=N'',@bIsolator=0,@bLAF=0,@bGradeAB=0,@bGradeCD=0,@bUnclassified=0,@bNoProduction=0,@sIsolatorQty=N'',@sLAFQty=N'',@sGradeABArea=N'',@sGradeCDArea=N'',@sUnclassifiedArea=N'',@bIncludeInKAM=1,@fLat=55.378050999999999,@fLong=-3.4359730000000002,@bRespQuality=0,@bRespMicro=0,@bRespPurchasing=0,@bRespValidation=0,@bKindIsolator=0,@bKindRABS=0,@bKindOLA=0,@bKindOLB=0,@bKindOLC=0,@bKindOLD=0,@lNoCleanroomOperatives=0,@sProductsManufactured=N'',@sComments=N'Test wm4',@lValueAlcohol=0,@lValueBiocides=0,@lValueWipes=0,@lValueEquipment=0,@lValueNonSterile=0,@lValueOther=0,@lGeocodeAttempts=6,@sGeocodeLastStatus=N'OK'
select @p1

The first two rows of the screenshot are from the web app (which doesn't work) and the last two are from SSMS (which work correctly)
BUT if we copy the exact SQL from above and run it in SSMS (with the same login as the web app) it works correctly inserting or updating a record and successfully retrieves the lat/lng from the webservice
Code:
Institution.Save()
Public Function Save() As Integer

    Dim cn As New SqlConnection(My.Settings.ShieldCRMConnectionString)
    Dim cmd As New SqlCommand
    Dim strSQL As String = "usp_web_InsertUpdateInstitution"

    Try
    cn.Open()
    cmd.Connection = cn
    cmd.CommandText = strSQL
    cmd.CommandType = CommandType.StoredProcedure

    Dim prmInstitutionID As New SqlParameter
    prmInstitutionID.ParameterName = "@lInstitutionID"
    prmInstitutionID.Value = intInstitutionID
    prmInstitutionID.Direction = ParameterDirection.InputOutput
    cmd.Parameters.Add(prmInstitutionID)

    '** Parameters clipped out for readability

    cmd.ExecuteNonQuery()

    Return cmd.Parameters("@lInstitutionID").Value

Catch ex As Exception
    Elmah.ErrorSignal.FromCurrentContext.Raise(ex)
    Return -1
Finally
    cmd.Dispose()
    cn.Close()
    cn.Dispose()
End Try

trg_Geolocation
ALTER TRIGGER [dbo].[trg_Geolocation] ON [dbo].[tblInstitution] AFTER INSERT, UPDATE
AS
BEGIN

    DECLARE @lInstitutionID INT
    DECLARE @sAddress1 VARCHAR(500)
    DECLARE @sAddress2 VARCHAR(500)
    DECLARE @sAddress3 VARCHAR(500)
    DECLARE @sTown VARCHAR(500)
    DECLARE @sCounty VARCHAR(500)
    DECLARE @sPostcode VARCHAR(500)
    DECLARE @sCountry VARCHAR(500)
    DECLARE @lCountryID INT

    DECLARE cur CURSOR FOR

    SELECT lInstitutionID,
           sAddress1,
           sAddress2,
           sAddress3,
           sTown,
           sCounty,
           sPostCode,
           C.lCountryID,
           C.sName AS sCountry
    FROM inserted I
    INNER JOIN refCountry C ON I.lCountryID = C.lCountryID
    WHERE ISNULL(bIncludeInKAM, 0) = 1

    OPEN cur

    FETCH NEXT FROM cur INTO @lInstitutionID, @sAddress1, @sAddress2, @sAddress3, @sTown, @sCounty, @sPostCode, @lCountryID, @sCountry

    WHILE @@FETCH_STATUS = 0
    BEGIN

        DECLARE @fLat FLOAT
        DECLARE @fLng FLOAT
        DECLARE @sAddress VARCHAR(MAX)
        DECLARE @sLastStatus VARCHAR(200)

        SELECT @fLat = NULL, @fLng = NULL, @sAddress = NULL

        SELECT @sAddress =
        CASE WHEN REPLACE(REPLACE(ISNULL(@sAddress1 + ', ', '') + ISNULL(@sAddress2 + ', ', '') + ISNULL(@sAddress3 + ', ', '') + ISNULL(@sTown + ', ', '') + ISNULL(@sCounty + ', ', '') + @sCountry, ', , , ', ', '), ', , ', ', ')
        LIKE ', %' THEN RIGHT(REPLACE(REPLACE(ISNULL(@sAddress1 + ', ', '') + ISNULL(@sAddress2 + ', ', '') + ISNULL(@sAddress3 + ', ', '') + ISNULL(@sTown + ', ', '') + ISNULL(@sCounty + ', ', '') + @sCountry, ', , , ', ', '), ', , ', ', '),
        LEN(REPLACE(REPLACE(ISNULL(@sAddress1 + ', ', '') + ISNULL(@sAddress2 + ', ', '') + ISNULL(@sAddress3 + ', ', '') + ISNULL(@sTown + ', ', '') + ISNULL(@sCounty + ', ', '') + @sCountry, ', , , ', ', '), ', , ', ', ')) - 2)
        ELSE REPLACE(REPLACE(ISNULL(@sAddress1 + ', ', '') + ISNULL(@sAddress2 + ', ', '') + ISNULL(@sAddress3 + ', ', '') + ISNULL(@sTown + ', ', '') + ISNULL(@sCounty + ', ', '') + @sCountry, ', , , ', ', '), ', , ', ', ') END

        BEGIN TRY
            EXEC usp_web_kam_Geocode @sAddress = @sAddress OUTPUT, @fLat = @fLat OUTPUT, @fLng = @fLng OUTPUT, @sGeocodeLastStatus = @sLastStatus OUTPUT
        END TRY
        BEGIN CATCH
            SELECT ERROR_MESSAGE()
        END CATCH

        IF NOT (@fLat IS NULL AND @fLng IS NULL)
        BEGIN

            UPDATE tblInstitution
            SET fLat = @fLat,
               fLong = @fLng,
               lGeocodeAttempts = ISNULL(lGeocodeAttempts, 0) + 1,
               sGeocodeLastStatus = @sLastStatus
            WHERE lInstitutionID = @lInstitutionID

        END

        FETCH NEXT FROM cur INTO @lInstitutionID, @sAddress1, @sAddress2, @sAddress3, @sTown, @sCounty, @sPostCode, @lCountryID, @sCountry

    END

    CLOSE cur
    DEALLOCATE cur

END

usp_web_kam_Geocode
ALTER PROCEDURE [dbo].[usp_web_kam_Geocode]

    @sAddress VARCHAR(80) = NULL OUTPUT,

    @sCity VARCHAR(40) = NULL OUTPUT,
    @sState VARCHAR(40) = NULL OUTPUT,
    @sCounty VARCHAR(40) = NULL OUTPUT,
    @sCountry VARCHAR(40) = NULL OUTPUT,
    @sPostCode VARCHAR(20) = NULL OUTPUT,

    @sGeocodeLastStatus VARCHAR(200) = NULL OUTPUT,
    @fLat FLOAT = NULL OUTPUT,
    @fLng FLOAT = NULL OUTPUT,
    @sMapURL VARCHAR(1024) = NULL OUTPUT

AS

BEGIN

    SET NOCOUNT ON

    DECLARE @sURL varchar(MAX)
    SET @sURL = 'http://maps.google.com/maps/api/geocode/xml?sensor=false&address=' +
    CASE WHEN @sAddress IS NOT NULL THEN @sAddress ELSE '' END +
    CASE WHEN @sCity IS NOT NULL THEN ', ' + @sCity ELSE '' END +
    CASE WHEN @sState IS NOT NULL THEN ', ' + @sState ELSE '' END +
    CASE WHEN @sPostCode IS NOT NULL THEN ', ' + @sPostCode ELSE '' END +
    CASE WHEN @sCountry IS NOT NULL THEN ', ' + @sCountry ELSE '' END
    SET @sURL = REPLACE(@sURL, ' ', '+')

    DECLARE @Response varchar(8000)
    DECLARE @XML xml
    DECLARE @Obj int
    DECLARE @Result int
    DECLARE @HTTPStatus int
    DECLARE @ErrorMsg varchar(MAX)

    EXEC @Result = sp_OACreate 'MSXML2.ServerXMLHttp', @Obj OUT

    BEGIN TRY
    EXEC @Result = sp_OAMethod @Obj, 'open', NULL, 'GET', @sURL, false
    EXEC @Result = sp_OAMethod @Obj, 'setRequestHeader', NULL, 'Content-Type', 'application/x-www-form-urlencoded'
    EXEC @Result = sp_OAMethod @Obj, send, NULL, ''

    EXEC @Result = sp_OAGetProperty @Obj, 'status', @HTTPStatus OUT
    EXEC @Result = sp_OAGetProperty @Obj, 'responseXML.xml', @Response OUT
    END TRY
    BEGIN CATCH
    SET @ErrorMsg = ERROR_MESSAGE()
    END CATCH

    EXEC @Result = sp_OADestroy @Obj

    IF (@ErrorMsg IS NOT NULL) OR (@HTTPStatus <> 200) BEGIN
    SET @ErrorMsg = 'Error in Geocode: ' + ISNULL(@ErrorMsg, 'HTTP result is: ' + CAST(@HTTPStatus AS varchar(10)))
    RAISERROR(@ErrorMsg, 16, 1, @HTTPStatus)
    RETURN
    END

    SET @XML = CAST(@Response AS XML)

    SET @sGeocodeLastStatus = @XML.value('(/GeocodeResponse/status) [1]', 'varchar(200)')
    SET @fLat = @XML.value('(/GeocodeResponse/result/geometry/location/lat) [1]', 'numeric(9,6)')
    SET @fLng = @XML.value('(/GeocodeResponse/result/geometry/location/lng) [1]', 'numeric(9,6)')

    SET @sCity = @XML.value('(/GeocodeResponse/result/address_component[type="locality"]/long_name) [1]', 'varchar(40)')
    SET @sState = @XML.value('(/GeocodeResponse/result/address_component[type="administrative_area_level_1"]/short_name) [1]', 'varchar(40)')
    SET @sPostCode = @XML.value('(/GeocodeResponse/result/address_component[type="postal_code"]/long_name) [1]', 'varchar(20)')
    SET @sCountry = @XML.value('(/GeocodeResponse/result/address_component[type="country"]/short_name) [1]', 'varchar(40)')
    SET @sCounty = @XML.value('(/GeocodeResponse/result/address_component[type="administrative_area_level_2"]/short_name) [1]', 'varchar(40)')

    SET @sAddress =
    ISNULL(@XML.value('(/GeocodeResponse/result/address_component[type="street_number"]/long_name) [1]', 'varchar(40)'), '???') + ' ' +
    ISNULL(@XML.value('(/GeocodeResponse/result/address_component[type="route"]/long_name) [1]', 'varchar(40)'), '???')
    SET @sMapURL = 'http://maps.google.com/maps?f=q&hl=en&q=' + CAST(@fLat AS varchar(20)) + '+' + CAST(@fLng AS varchar(20))

END


text:
Q: Can't start up python3 on embeded system I'm building python 3.4.4 on a mips CPU running linux using the cross-compiler method on Ubuntu.
Now I have successfully built the python3 and installed it on the mips system.
But when running python3 on the mips system, it just can't start up the python3 shell.
/lib/python3.4 # echo $PYTHONPATH
/lib/python3.4/
/lib/python3.4 # echo $PYTHONHOME
/bin
/lib/python3.4 # python3 -v
import _frozen_importlib # frozen
import imp # builtin
import sys # builtin
# installing zipimport hook
# installed zipimport hook
# possible namespace for /lib/python3.4/encodings
import 'encodings' # None
Fatal Python error: Py_Initialize: Unable to get the locale encoding
LookupError: no codec search functions registered: can't find encoding

Current thread 0x00000400 (most recent call first):
Aborted
/lib/python3.4 #

I checked the python source code, and find the error is reported from the function _PyCodec_Lookup() in Python-3.4.4\Python\codecs.c.
/* Next, scan the search functions in order of registration */
    args = PyTuple_New(1);
    if (args == NULL)
        goto onError;
    PyTuple_SET_ITEM(args,0,v);

    len = PyList_Size(interp->codec_search_path);
    if (len < 0)
        goto onError;
    if (len == 0) {
        PyErr_SetString(PyExc_LookupError,
                        "no codec search functions registered: "
                        "can't find encoding");
        goto onError;
    }

Anyone encounter this problem before or is there anything wrong with the cross-compiler building?
Thanks


text:
Q: Content zoomed out using .NET WebBrowser control in Windows CE 7 I've recently upgraded to Windows CE7 for one of my personal projects written in C#. As you may know, CE7 introduced touch support, so the WebBrowser control works differently in regards to panning and zooming.
Here's my setup:

*

*Windows CE7 running on an Atom processor

*Using mouse and keyboard as inputs

*Edit: Targeting framework 2.0

The problem:

*

*When you load a page in the WebBrowser, it appears zoomed out by default

*I can't seem to find a way to render the page in it's original size

*I can't use the mouse scroll to zoom in

*The images in the web page look pixelated because of that

Any idea why this is happening and if there's a way to fix this?

A: Turns out my question was similar to this one
You need to add metadata to the web page you want to display. Thankfully I have access to those pages which will make my job easier. Otherwise you need to play around the content and add this tag programmatically.
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" />

PS. I honestly didn't know how closely related WP7 and CE7 were. Now I know.


text:
Q: How to interpret data types obtained from  library? Q1 - Since both begin(arr) & &arr will return hexadecimal pointer location of starting of the arr, wondering what is the difference between the outputs of data types printed by the following script?
#include <iostream>
#include <typeinfo>
#include <string>

using namespace std;

int main()
{
    int arr[] = {10, 20, 30, 40, 50, 60, 77};

    cout << typeid(begin(arr)).name() << " , " << typeid(&arr).name() << endl;
    cout << begin(arr) << " , " << &arr << endl;

    return 0;
}

OUTPUT
Pi , PA7_i
0x7ffc79a99500 , 0x7ffc79a99500

Q2 - how can we get decimal representation of hex pointer location?

A: For Q1:
Note that begin(arr) and &arr are different things (with different types). begin(arr) gives the pointer to the 1st element of arr with type int*, &arr gives the pointer to the array arr with type int (*)[7].


text:
Q: pandas: subtracting subsequent row of a DF and create a new DF with no column to groupby I am trying to create a new DF by subtracting the subsequent rows of a DF. There is no column that I can use to group by and subtract. the operation should subtract row 0 with row 1, row 2 with row 3, row 4 with row 5, and so on.
df1:

needs to result in df2:

I tried to iterate over rows using
for ii in [0,2,4]:
and using the value in ii for .iloc, but the result is a column df instead of a row.

A: You can calculate the .diff of each row from the previous, then select the even elements from that via iloc:
out = df.diff(-1).iloc[::2].reset_index(drop=True)

print(out)
      a     b      c    d
0  28.0   1.0  147.0 -7.0
1  87.0  10.0  151.0 -7.0
2  -2.0   1.0   77.0 -7.0

Not that the subtraction in your sample output isn't correct (unless I mistunderstood something, which is entirely possible). But for your first row columns "a", performing 633 - 605 should be 28, not 27. Then in column "d": 1 - 8 is -7, not -8


text:
Q: Why is Cacti showing an empty graph, even though the rrd file is created? I have developed my own SNMP service, and i want to plot a graph of an OID provided.
So, i have created a graph in Cacti.
-) It is showing device up.
-) It is creating rrd file. (RRDTool says OK).
-) Showing the graph, but it's empty.
But when I check it, say
rrdtool fetch <rrd file> AVERAGE

it shows me nan for all the values. The monitored OID has value 47 and i have set min=0 and max=100.
I am using Cacti appliance by rpath:
http://www.rpath.org/ui/#/appliances?id=http://www.rpath.org/api/products/cacti-appliance
Still, I can't show value on graph..
Where is the problem? Can anyone please tell me?

A: First of all, use Cacti's "Rebuild Poller Cache" function under the Utilities menu.
If that didn't work ,check if the RRD file is actually updating with new data.
To do this use the command:
rrdtool last [filename.rrd]
This will output the last time (in unix timestamp) that a new value has been inserted into the RRA file which you can compare to the current time that date +%s will output.
If it's not updating with data then you should change the cacti log level to DEBUG via the settings page on Cacti's web UI and look for appropriate messages.
If the poller couldn't get the data then it's usually an issue relating to connectiviy/SNMP.
You can further check issues as such by manually polling the specific OID on that host:
snmpwalk -c[SNMP COMMUNITY] -v2c [HOSTNAME OR IP ADDRESS] 1.3.6.1.2.1

You can use the above command and OID (1.3.6.1.2.1) just to see if you're getting a reply.
If that worked then you should change the command from snmpwalk to snmpget and the OID to the actual OID you're trying to poll and retry.
If the RRD is updating with new data but you're still getting NaN in your graphs then I suggest looking into the heartbeat and step values of the data source (via the data template) in relation to your polling interval and poller cronjob interval.
These values determine how many times the RRD file will miss data before inserting a NaN.
The cronjob calls the cacti poller to start performing it's polling cycle.
The poller interval is the actual time that the poller will wait between two polling cycles if it was indeed invoked in time by the cronjob.
So for 1 minute polling (on the poller and the cronjob) you will have to use a step of 60 (seconds) and a heartbeat of 120.
For 5 minutes polling, the step will be 300 and the heartbeat will be 600.
This is mainly caused by someone changing the poller interval on the settings page.
Gandalf from the Cacti forums wrote a nice Guide that you can use and further help can be found on Cacti forums.
Good luck! :)

A: Maybe cacti doesn't have the needed permissions to access the rrd file and your test was done with a user who has the required permissions, for example root?

A: Are you sure you have collected enough data?
If your RRD has a step of 1 minute, and your first RRA has a consolidated count of 1 (1cdp=1pdp), then you should collect data for at least (step x ( count + 1 )) seconds before you expect to see any data in the graph.  Make sure you are collecting data at least as often as the step size.
If you collect data for 10 min and nothing shows up, then make sure you are actually collecting the data, make sure the values you get are within range, and that they are being used.  Check the last modification time on the RRD file.  Print out the values before you update to verify they are what you think they are.

A: You should double check the range Cacti is plotting in. I moved the values in the graph filter and spotted a little chunk of data in the graphs, then you just have to adjust it.


text:
Q: BLOB , Insert SQL Database I have an error that I can't fix ... I really don't know why .
I'm using this code tu upload a file in my database, i want to use the BLOB now .
if (FileUpload1.HasFile)
                    try
                    {

                        //FileUpload1.SaveAs("C:\\inetpub\\wwwroot\\ClientPortalCs\\"
                        //+ GetTheCurrentDirectory(MyTreeView.SelectedNode)
                        //+ "\\" + FileUpload1.FileName);
                        //LabelFile.Text = "File name: " +
                        //FileUpload1.PostedFile.FileName + "
" +
                        //FileUpload1.PostedFile.ContentLength + " kb
" +
                        //"Content type: " + FileUpload1.PostedFile.ContentType;

                        dbConnection.Open();
                        dynamic queryString = ("INSERT INTO Files (Name,Path,UserUpload,Date,Data) VALUES ('"
                        + FileUpload1.FileName + "','" + GetTheCurrentDirectory(MyTreeView.SelectedNode) + "','" + Request.Cookies["UserSettings"]["UserName"] + "','" + DateTime.Now + "','" + FileUpload1.FileBytes + "' );"
                        + "SELECT CAST(scope_identity() AS int)");

                        SqlCommand theCommand1 = new SqlCommand(queryString, dbConnection);

                        int newFid = (Int32)theCommand1.ExecuteScalar();

                        dynamic queryStringFolder = ("INSERT INTO FILES_FOLDERS (Folder_Id,File_Id) VALUES ('"
                        + MyTreeView.SelectedValue + "'," + "'" + newFid + "')");
                        theCommand1 = new SqlCommand(queryStringFolder, dbConnection);

                        theCommand1.ExecuteNonQuery();

                        dbConnection.Close();

                    }

In my database the field DATA in the table files is a varbinary(max) .
The parameter for DATA field in the query is the bytes of the file I try to upload .
The error occured is :
"Error Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. "
Can someone tell me why ?
Thank you very much .

A: The problem, I think, is that you are passing in the byte []  of your image as a string because you are enclosing it in single quotes.
Remove the single quotes around here:
'" + FileUpload1.FileBytes + "'"

One more recommendation: Use parameters for your queries. You'll save yourself from sql injection attacks, your queries may run faster and you'll eliminate this kind of mistakes in the future.
UPDATE - using parameters:
string queryString = "INSERT INTO Files (Name,Path,UserUpload,Date,Data) VALUES (@Name,@Path,@UserUpload,@Date,@Data)";
SqlCommand theCommand1 = new SqlCommand(queryString, dbConnection);
theCommand1.Parameters.AddWithValue("@Name",FileUpload1.FileName);
theCommand1.Parameters.AddWithValue("@Path",GetTheCurrentDirectory(MyTreeView.SelectedNode));
theCommand1.Parameters.AddWithValue("@UserUpload",Request.Cookies["UserSettings"]["UserName"]);
theCommand1.Parameters.AddWithValue("@Data",FileUpload1.FileBytes);
theCommand1.Parameters.AddWithValue("@Date",DateTime.Now);

int newFid = (Int32)theCommand1.ExecuteScalar();


text:
Q: Side by side divs filling height in container I've got a set of side by side divs (actually using HTML5 sections but I'm assuming the solution and behavior is just the same).  They sit in a container with the right side holding form fields and left side a summary title and information.  The structure looks something like this:

Summary here

Form fields here

The catch is I have to hide or show various fields depending on actions taken with javascript so the actual height of the right side and container are not static.  What I need is to get the left side to fill the height of the container so it will match the right.  I've tried the numerous solutions on the internet but none seem to be working.
Thanks in advance!

A: This is a very common question. Take a look at this article... it has all the answers:
http://matthewjamestaylor.com/blog/equal-height-columns-cross-browser-css-no-hacks
Now, here's a quick fiddle of putting that to use. Try clicking on any of the "Column #" text elements to remove them from the document... the columns will resize nicely :)
http://jsfiddle.net/UnsungHero97/qUT3d/9/
HTML

Column 1

Column 2

Column 3

CSS
#container3 {
    float:left;
    width:100%;
    background:green;
    overflow:hidden;
    position:relative;
}
#container2 {
    float:left;
    width:100%;
    background:yellow;
    position:relative;
    right:30%;
}
#container1 {
    float:left;
    width:100%;
    background:red;
    position:relative;
    right:40%;
}
#col1 {
    float:left;
    width:26%;
    position:relative;
    left:72%;
    overflow:hidden;
}
#col2 {
    float:left;
    width:36%;
    position:relative;
    left:76%;
    overflow:hidden;
}
#col3 {
    float:left;
    width:26%;
    position:relative;
    left:80%;
    overflow:hidden;
}


text:
Q: Как запросом показать список файловых групп базы данных? Как для заданной базы данных запросом показать ее список файловых групп?
Сервер баз данных Microsoft SQL Server 2012.

A: Как ни странно, довольно просто.
use <database_name>;
select * from sys.filegroups where type="FG";


text:
Q: Is it a good practice to set all the fields to null? Is it a good practice to have all the fields equal to null and just create them when they are required ?
public class Products {

   private Map listofProducts = null;
   private Owner owner = null;
   private List<listOfProductsResults> listofProductsResults = null;
   private String fileName = null;
   private long id = 0L;

   public Products(){
   }

In this way whenever a method needs each of them I do the following
  if(listOfProducts == null){
      this.listOfProducts = new HashMap();
  }

A: private Map listofProducts = null;

and
private Map listOfProducts;

Are equal statements, so no. It is pointless and I really don't like the look of the code with this.

A: Java auto initializes objects to null, but sometimes setting it to null explicitly can be a form of documentation if nothing else. For example, normally one would expect a constructor to initialize instance attributes. The one property explicitly initialized to null could say "this is not initialized in the constructor" or "this uses lazy initialization, beware". That might signify to always proxy through a getter or expect access to be protected with a null check. But it would be up to you to establish such a pattern.


text:
Q: When developing models for effect estimation, is it advisable to perform internal validation and calibration using resampling methods? #rms In predictive modelling, it is useful to perform resampling methods to assess performance e.g. validate() and calibrate() in the rms package in R. Is it useful / advisable to perform such methods when the primary purpose is estimating effects e.g. hazard ratios from a Cox model, odds ratios from logistic regression etc.?

A: If you sole goal is effect estimation, then Frank Harrell says in Section 4.12.2 of Regression Modeling Strategies, 2nd edition:

Model validation is not necessary unless the analyst wishes to use it to quantify the degree of overfitting.

That said, the quality of your effect estimation depends directly on the quality of your model.  For your own peace of mind and that of your audience it can be helpful to quantify the degree of overfitting by model validation. You don't want to make an effect estimate based on a severely overfit model.
Evaluating model calibration might help identify problems with model specification (e.g., missing predictors or interaction terms associated with outcome); the effect estimated from a mis-specified model might not be correct. In Cox or logistic regression models, omitting any outcome-associated predictor from a model can bias the coefficient estimates of included predictors toward 0.
There's little cost to doing that validation and calibration and potentially much to gain.


text:
Q: XmlReader skips half data sent to webservice I have a web service that has one method:
[WebMethod]
public bool SyncUserData(string userxml)

The xml is a series of user records and I use an XmlReader to read through the data and process it.
When I call the web service with 2000 records, it processes 2000 records.
When my client calls it with the same xml, it processes 1000 records.
It processes every other record.
Does anyone have any experience with this sort of problem?
My thought is that it is an encoding issue but I have tried sending the data to the service as ASCII, ISO-8859-1 etc in my tests and cannot recreate.
Any help much appreciated.
This is the calling code:
while (userXml.Read())
{

    if (userXml.Name == NODE_NAME_FILE_NAME && userXml.NodeType == XmlNodeType.Element)
    {
        _importFilename = userXml.ReadString();
    }

    if (userXml.Name == NODE_NAME_USER && userXml.NodeType == XmlNodeType.Element)
    {
        ProcessUser(userXml);
    }
}

and this is what processUser does with teh xml reader
private void ProcessUser(XmlReader userXml)
{
    _usersinfeed++;
    XmlDocument user = new XmlDocument();
    user.LoadXml(userXml.ReadOuterXml());
     ...

}

A: What's biting you is the side-effect of ReadOuterXml - it most likely advances the current position of the XmlReader - but then, in your loop while (userXml.Read()) you advance it again - skipping one xml element in the process.
There are various ways of solving this - but the easiest and cleanest would be to not use XmlReader.  Is that an option?
An easier way to process xml is Linq to Xml:
public static void Main()
{
    SyncUserData(@"
    <doc>
    <filename>test</filename>
    <user>Someone</user>
    <user>Someone2</user>

    <filename>testA</filename>
    <user>Someone else</user>
    <user>Someone else2</user>
    </doc>
    ");
}

const string  NODE_NAME_FILE_NAME = "filename";
const string  NODE_NAME_USER = "user";

static string _importFilename;
static int _usersinfeed;

public static bool SyncUserData(string userxml) {
    foreach(XElement el in XDocument.Parse(userxml).Descendants()) {
        //or: XDocument.Parse(userxml).Root.Elements() -- this depends on your document

        if (el.Name == NODE_NAME_FILE_NAME)
            _importFilename = el.Value;
        if (el.Name == NODE_NAME_USER)
            ProcessUser(el);
    }
    return true;
}

private static void ProcessUser(XElement el)
{
    _usersinfeed++;
    Console.WriteLine("User:{0}, file:{1}\n{2}\n",_usersinfeed,_importFilename,el);
    //you probably don't need the following anymore
    //XmlDocument user = new XmlDocument();
    //user.LoadXml(el.CreateReader());

    //...
}

Which outputs:
User:1, file:test
<user>Someone</user>

User:2, file:test
<user>Someone2</user>

User:3, file:testA
<user>Someone else</user>

User:4, file:testA
<user>Someone else2</user>

However, you may be able to use XML Serialization - that's a very easy way to parse/generate XML without much boilerplate at all also gives you a .NET native datastructure to work with to boot!  Then, you just need a small set of classes to define the document structure, and the framework can create instances auto-magically from XML for you, without any manual parsing code whatsoever.  Not all XML syntaxes are amenable to that, however.


text:
Q: Collecting new fairies in Hyrule Warriors Legends I recently started playing Hyrule Warriors Legends for the first time. When I first launched the game, it downloaded a bunch of updates and then bombarded me with a massive list of rewards that went with the updates (e.g. 6 million rupees, 6 fairies, tons of food, etc).
The game lets you collect fairies in the Adventure mode. Or at least, it's supposed to. However, when I collect a fairy in Adventure mode (by capturing the keep that holds the fairy, walking over the fairy, and getting a message that I've collected a new fairy), nothing happens at the end of the mission related to the fairy, and no new fairies are added to my inventory.
This wiki page says that you can only hold a maximum of 3 fairies, but that maximum can increase by completing Adventure Mode maps. Since I already have 6 fairies, I assume the maximum is at least 6. The page also says that when you collect a new fairy, the game will ask whether you want to get rid of a previous fairy. However, I've never seen such a dialog. I started the game with two water fairies and two light fairies, so I'd like to get rid of the duplicates, but can't figure out any way to dismiss fairies and don't seem to be given the opportunity after "collecting" new fairies.
Am I misunderstanding something about the fairy system? How come nothing happens when I collect a new fairy?

A: The fairies you get when freeing a fort are different from the ones you can use in battle.
Fairies that you capture when freeing a fort are only for freeing an elemental fort with the same element. You'll see a message "Fairy acquired! Rescued a fairy of {element}".
Fairies that you can keep, train and use in combat, on the other hand, can only be found on certain maps in Adventure Mode, where you'll see a small fairy icon as you go through the various rewards that the particular battle has in store for you.
These fairies are usually only found in pots that you can find in forts. You can usually find them in the bright yellow/beige pots, where you can also find rupees and food. When you capture these fairies, the message will specifically mention "MY FAIRY" and "Companion Fairy".
From these fairies you can have 6 at the beginning and unlock the possibility to have more by finishing more adventure maps.


text:
Q: Palindrome Golf The goal: Any language. The smallest function which will return whether a string is a palindrome. Here is mine in Python:
R=lambda s:all(a==b for a,b in zip(s,reversed(s)))

50 characters.
The accepted answer will be the current smallest one - this will change as smaller ones are found. Please specify the language your code is in.

A: 73 clean, readable, chars written in java
boolean p(String s){return s.equals(""+new StringBuffer(s).reverse());}

peace :)

A: Pointless Haskell version (15 chars, though doesn't really work unless you include Control.Arrow and Control.Monad and ignore the monomorphism restriction):
p=ap(==)reverse

A: (equal p (reverse p))

lisp. 18 characters.
ok, this is a special case. This would work if typed directly into a lisp interpreter and p was already defined.
otherwise, this would be necessary:
(defun g () (equal p (reverse p)))

28 characters.

A: Lua aims more at readability than conciseness, yet does an honest 37 chars:
function p(s)return s==s:reverse()end

variant, just for fun (same size):
p=function(s)return s==s:reverse''end

The JavaScript version is more verbose (55 chars), because it doesn't has a string reverse function:
function p(s){return s==s.split('').reverse().join('')}

A: I'll take it a little bit further: full c code, compile and go.
90 characters
main(int n,char**v){char*b,*e;b=e=v[1];while(*++e);for(e--;*b==*e&&b++<e--;);return b>e;}

A: 7 characters in J: Not sure if this is the best way, I'm somewhat new to J :)
p=:-:|.

explanation: |. reverses the input. -: compares. the operands are implicit.
p 'radar'
1

p 'moose'
0

A: Here's mine; it's written in a domain-specific language I invented, called 'palindrome'.
p

Edit: Less flippant version (i386 asm, AT&T syntax)
xor %eax, %eax
mov %esi, %edi
#cld    not necessary, assume DF=0 as per x86 ABI
repne scasb
scan:
    dec %edi
    cmpsb
    .byte 0x75, 6    #jnz (short) done
    dec %edi
    cmp %esi, %edi
    .byte 0x72, -9    #jb (short) scan
inc %eax
done:

16 bytes, string pointer goes in ESI, result is in EAX.

A: PHP:
function p($s){return $s==strrev($s);} // 38 chars

or, just
$s==strrev($s); // 15 chars

A: Isn't using the reverse function in your language kind of cheating a bit?  I mean, looking at the Ruby solution give as
def p(a)a==a.reverse end

you could easily rewrite that as
def p(a)a==a.r end

and just say that you made an extension method in your code so that "r" called reverse. I'd like to see people post solutions that don't contain calls to other functions. Of course, the string length function should be permitted.
Ruby without reverse - 41 characters
def m(a)a==a.split('').inject{|r,l|l+r}end

VB.Net - 173 Chars
Function P(ByVal S As String) As Boolean
    For i As Integer = 0 To S.Length - 1
        If S(i) <> S(S.Length - i - 1) Then
            Return False
        End If
    Next
    Return True
End Function

A: F# (a lot like the C# example)
let p s=let i=0;let l=s.Length;while(++i<l)if(s[i]!=[l-i-1]) 0; 1;;

A: Golfscript, 5 char
.-1%=

$ echo -n abacaba | ruby golfscript.rb palindrome.gs
1

$ echo -n deadbeef | ruby golfscript.rb palindrome.gs
0

A: Sadly, I'm unable to get under a thousand words...

(LabVIEW.  Yeah, they'll let just about any hobo post here ;)

A: C# Without Reverse Function 84 chars
int p(char[]s){int i=0,l=s.Length,t=1;while(++i<l)if(s[i]!=s[l-i-1])t&=0;return t;}

C# Without Reverse Function 86 chars
int p(char[]s){int i=0;int l=s.Length;while(++i<l)if(s[i]!=s[l-i-1])return 0;return 1;}

VBScript 41 chars
function p:p=s=strreverse(s):end function

A: Common Lisp, short-and-cheating version (23 chars):
#L(equal !1(reverse !1))

#L is a reader macro character implemented by SHARPL-READER in the iterate package. It's basically equivalent to (lambda (!1) ...).
Common Lisp, long version using only primitives (137 including whitespace, compressible down to 108):
(defun p (s)
  (let ((l (1- (length s))))
    (iter (for i from l downto (/ l 2))
          (always (equal (elt s i) (elt s (- l i)))))))

Again, it uses iterate, which is basically a cleaner version of the builtin LOOP facility, so I tend to treat it as being in the core language.

A: Inspired by previous post, 69 characters
p(char*a){char*b=a,q=0;while(*++b);while(*a)q|=*a++!=*--b;return!q;}

EDIT: Down one char:
p(char*a){char*b=a,q=0;while(*++b);while(*a)q|=*a++%*--b;return!q;}

EDIT2: 65 chars:
p(char*a){char*b=a;while(*b)b++;while(*a&&*a++==*--b);return!*a;}

A: Not the shortest, and very after-the-fact, but I couldn't help giving it a try in MATLAB:
R=@(s)all(s==fliplr(s));

24 chars.

A: 18 character perl regex
/^(.?|(.)(?1)\2)$/

A: 52 characters in C, with the caveat that up to half the string will be overwritten:
p(char*s){return!*s||!(s[strlen(s)-1]-=*s)&&p(++s);}
Without library calls it's 64 characters:
p(char*s){char*e=s;while(*e)++e;return!*s||!(*--e-=*s)&&p(++s);}

A: Haskell, 15 chars:
p=ap(==)reverse

More readable version, 16 chars:
p x=x==reverse x

A: Another python version that is rather shorter (21 chars):
R=lambda s:s==s[::-1]

A: Haskell, 28 chars, needs Control.Arrow imported.
p=uncurry(==).(id&&&reverse)

A: Straightforward implementation in C using standard library functions, inspired by the strlen in the other C answer.
Number of characters: 57
p(char*s){char*r=strdup(s);strrev(r);return strcmp(r,s);}

Confession: I'm being the bad guy by not freeing r here. My current attempt at being good:
p(char*s){char*r=strdup(s);s[0]=strcmp(strrev(r),s);free(r);return s[0];}

brings it to 73 characters; I'm thinking of any ways to do it shorter.

A: Without using any library functions (because you should really add in the #include cost as well), here's a C++ version in 96:
int p(char*a,char*b=0,char*c=0){return c?b<a||p(a+1,--b,c)&&*a==*b:b&&*b?p(a,b+1):p(a,b?b:a,b);}

A: Groovy 17B:

p={it==it[-1..0]}

Downside is that it doesn't work with emptry string.
On second thought, throwing exception for empty string is reasonable since you can't tell if nothing is palindrome or not.

A: Clojure using 37 characters:
user=> (defn p[s](=(seq s)(reverse(seq s))))
#'user/p
user=> (p "radar")
true
user=> (p "moose")
false

A: 24 characters in Perl.
sub p{$_[0]eq+reverse@_}

A: At the risk of getting down votes, most all of these just call a command reverse of some sort that hides all the real programming logic.
I wonder what the shortest manual way to do this is in each of these languages.

A: With C# and LINQ operators:
public bool IsPalindrome(string s)
{
    return s.Reverse().SequenceEqual(s);
}

If you consider Reverse as cheating, you can do the entire thing with a reduction:
public bool IsPalindrome(string s)
{
    return s.Aggregate(new StringBuilder(),
                       (sb, c) => sb.Insert(0, c),
                       (sb) => sb.ToString() == s);
}

A: Perl (27 chars):
sub p{$_[0]eq reverse$_[0]}

Ruby (24 chars):
def p(a)a==a.reverse end

A: My attempt in C (70 chars):
P(char*s){char*e=s+strlen(s)-1;while(s<e&&*s==*e)s++,e--;return s>=e;}

[Edit] Now actually working
[Edit 2] Reduced from 74 to 70 by using default int return
In response to some of the comments: I'm not sure if that preprocessor abuse counts - you could just define the whole thing on the command line and make the function one character.

A: Haskell, 36 characters including its own reverse function.  (Actually, if you use semicolons to make it a one-liner, and ignore the newline at the end, it'd be 35...)
r[]y=y
r(a:x)y=r x$a:y
p s=s==r s[]

As with other implementations, "p" is the palindrome predicate.

A: Perl (21 characters):
sub{"@_"eq reverse@_}

Hey, the question didn't specify a named subroutine!

A: F#, no LINQ and Reverse method.
Seq.fold:
let p (s : string) =
  fst(s |> Seq.fold (fun (r, i) c -> (r && c = s.[s.Length - 1 - i], i + 1)) (true, 0))

The same, but with Seq.iteri and ref variables instead of Seq.fold:
let p (s : string) =
  let r = ref true
  Seq.iteri (fun i c -> r :=  (!r && c = s.[s.Length - 1 - i])) s
  !r

A: CFScript, 39 characters:
function y(x){return(x is reverse(x));}

I was never very good at golf.

A: Java:
boolean y(StringBuffer x){return x.equals(x.reverse());}

The above doesn't work, oops!
boolean y(StringBuffer x){return x.toString().equals(x.reverse().toString()); }

Ew.

A: Shell-script (sed + tac + tr):
test "`echo $1|sed -e 's/\(.\)/\1\n/g'|tac|tr -d '\n'`" == "$1"

A: Definitely not the smallest, but I still wanted to add a entry:
sub p{return @_==reverse split//;}

My perl's rusty tho and this is untested.

A: C, no libraries, 70 characters:
p(char*a){char*b=a-1;while(*++b);while(a<b&&*a++==*--b);return!(a<b);}

As one of the comments on another C solution mentioned, prototypes are completely optional in C, int is assumed everywhere a type would go but isn't mentioned.  Has nobody ever programmed in pre-ANSI C?
Edit: shorter and handles empty strings.

A: JavaScript: 55 chars
p=function(x){return (x==x.split('').reverse().join())}

The above won't work because you need to call join with ""
JavaScript: 55 chars
function p(s){return s==s.split("").reverse().join("")}

A: Java, without using reverse:
boolean p(String s){int i=0,l=s.length();while(i<l){if(s.charAt(i++)!=s.charAt(--l))l=-1;}return l>=0;

A: Standard ML (34 characters and boring):
fun p s=s=implode(rev(explode(s)))

A: C, 68 characters, no libs:
p(char *s){char *e=s;while(*++e);for(;*s==*--e&&s++<e;);return s>e;}

A: may was well give a c++ example which uses the standard library:
bool p(const std::string &s){std::string s2(s);std::reverse(s2);return s==s2;}

Thanks to Jon For pointing out that this could be shorter if we make some unnecessary copies. Totalling 67 chars.
bool p(std::string s){std::string x=s;std::reverse(x);return s==x;}

A: 58 characters in Python, without reversing the string:
r="y"
for i in range(len(s)):
 if(s[i]!=s[-i-1]):
  r="n"
Maybe the for loop could be optimized? Python is new to me...

A: javascript recursive version (no reverse junk)
function p(s){l=s.length;return l<2||(s[0]==s[l-1]&&p(s.substr(1,l-2)))}

(72 chars)
or implement reverse inside:
p=function(s,y){return y?(s==p(s)):s[1]?(p(s.substr(1))+s[0]):s[0]}

p("hannah",1);

(67 chars)
or, using no built in functions at all...
p=function(s,y,i){
return i?s[i]?s[i]+p(s,0,i+1):'':y?(s==p(s)):s[1]?(p(p(s,0,1))+s[0]):s[0]
}

p("hannah",1);

(92 chars)
shortest I could come up with: (iterative)
function p(s,l){for(c in s){if(s[c]!=s[l-1-c])s=0}return s}

p("hannah",6);// (is this cheating?)

(59 chars)
looking forward to seeing you do it better in javascript!
(preferably without using any built in functions, especially reverse)
(not really very impressed by the 'return s==s.reverse()' type answers)

A: F#: 29 chars
let p(s:string)=s=s.Reverse()

(assuming System.Linq is imported)

A: C# using a recursive lambda function and not using the Reverse function (115 chars):
Func<string,bool>p=null;p=w=>{if(w.Length<2)return true;return w[0]==w[w.Length-1]&&p(w.Substring(1,w.Length-2));};

A: Impossible! language, assuming that string is passed by using normal args:
;~=

3 chars

A: JavaScript, 64 bytes.
function a(x){for(r='',i=x.length;i>0;i--)r+=x[i-1];return x==r}

Test case:
a('lolol'); // true
a('haha');  // false

A: Josh's Java snippet above will return true every time.


text:
Q: Mule SOAP generic config reference for implementing security Just tried with implementing WS Security in SOAP using UsernameToken in mule. It worked fine.
Now since i am using SOAP component at various locations in my mule project, i want to know if there is any way to define WS security parameter globally and then refer those properties in each SAOP component, without having to define them for each component. Such global WS security definitions should be used in various deployed mule packages.
Thanks

A: Just create a spring config file and import that in each application. Alternatively just use a properties file with your definitions.


text:
Q: Center a div, as width as its content I want to center a DIV which width is unknown. It should be as width as the actual content. I tried:

dsffsffsfsddf

it only works when "width" is set. Auto wont help.

A: display: table; margin: 0 auto;
http://jsfiddle.net/vabxz/

A: div{
    display:table
    margin:0 auto;
}

A: Take a look at this previous answer: centering variable width divs
But one answer is to basically use css-floats

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id velit vel  augue fringilla rhoncus at et odio. Suspendisse potenti. Aliquam justo  libero, commodo ut iaculis in, placerat vel purus.

A: It's quite simple (http://jsfiddle.net/bukfixart/tYyJN/):

some content

The key points are text-align:center for the outer box and display:inline-block for the inner box

A: Check out my fiddle: http://jsfiddle.net/PRUBd/
CSS
body {
    text-align: center;
}

#container {
    text-align: left;
    border: 1px solid black;
    padding: 10px;
    display: inline-block;
}

HTML

   This div is as wide as its content and centered!


text:
Q: reset auto increment to zero in mysql trigger when current year changed I need unique reference number combining year with auto increment field (like 17001.. here 17 is last two digit of 2017 and 001 is auto increment field) somehow i manage to create this combination using triggers but my problem is when new year starts auto increment should start from 001 again (like 18001 when 2018 starts)..
Thanks in advance
my table name is chalan and trigger table namem is chalan_seq
my code is:
    DELIMITER $$
    CREATE TRIGGER tg_chalan_insert
    BEFORE INSERT ON chalan
    FOR EACH ROW
    BEGIN
    DECLARE curdate INT;
    DECLARE lastdate INT;
    SET curdate = DATE_FORMAT(CURDATE(), '%y');
    SET lastdate = (SELECT SUBSTR(ref,5,2) from chalan order by ref DESC LIMIT 1
    );
    END
    if(curdate != lastdate)
    BEGIN
    DELETE FROM chalan_seq;
    ALTER TABLE chalan_seq AUTO_INCREMENT = 0;
    END$$
    ELSE
    BEGIN
    INSERT INTO chalan_seq VALUES (NULL);
    SET NEW.ref = CONCAT('GEMS',DATE_FORMAT(CURDATE(), '%y'),
    LPAD(LAST_INSERT_ID(), 3, '0'));
    END$$
    DELIMITER ;

A: Just create a column with AUTO_INCREMENT and:
http://www.tutorialspoint.com/mysql/mysql-using-sequences.htm
 ALTER TABLE chalan AUTO_INCREMENT = 2018000;

But this can create a problem if you insert more than 1000 records in one year.


text:
Q: Database table structuring I am a little confused about how I would restructure my database, currently I am engaged with three tables:

*

*Items: which contains the basic information of an "item" (user.id, name, description, feature_1(bool), feature_2(bool) .. etc)

*Feature_1: Which contains some optional values for an "item", so if the user decides to have Feature 1 to his item we it will create a record in Feature_1 and fill in those values. 1 item cannot have more than one record in "Feature_1" table so either it has 1 record or none.

*Feature_2: Same as Feature_1 but has different optional values, so the user could add Feature_1 to his Item and/or Feature_2. Again each item can have 0 or 1 Feature_2 record.
I am not sure if it is the best practice or not, one of the options was mashing all values in 1 table "Items" with many NULL values.
Any advice and pointers will be greatly appreciated.

A: Separating out values like this can be helpful in terms of dealing with locking issues.  If you have multiple daemons/scripts running that are updating and those tables and holding locks on them, it can be an issue to keep all those values together on one table.  Of course, now that the values for the 'item' are separated on to three tables, you are going to have issues with chasing them down if/when you need all of them.  Generally it is fine to keep these tables split up like this.
Additional, before anyone goes down the road of splitting data like this, it is generally better to try/exhaust each of the following:
Use 'with (nolock)' as much as possible to prevent locking issues where you can.
Modify the scripts that maintain this data to use 'begin tran' type transactions as little as possible.
Modify the execution of the scripts that maintain the data so they are more likely to be called sequentially than concurrently.  e.g. put them in the same job.

A: I would tend to agree with the three tables. Because you say the items can only be linked to zero or one Feature_1 and zero or one Feature_2, you could add two columns to the item table with the reference to Feature_1 and Feature_2 primary keys. You can use foreign key constraints on those columns and make them null-able to indicate the feature isn't present. This also means that you can drop the booleans and keep the benefit of checking whether a type 1 or 2 feature is available without joining tables.

A: Purists would say you should have each of the Features as separate tables, each with a foreign key to the Items table.  And, generally, I'd agree, although if a fairly small percentage of items won't have both features, and the size of the feature records are small, it might be worth eliminating the overhead of having to join the tables.

A: There is no one-size-fits-all solution to these types of problems.  But you have described two very common, and appropriate, solutions.
In theory, you can actually remove the feature_x Boolean fields from the main table.  That 'fact' is implicit in the existence, or not, of a record in the feature tables.  Having them isn't bad, it's a type of caching/denormalisation that increases complexity in order to potentially increase performance.
The only time I may potentially avoid this set-up is when users can create new features, or you have an unfeasibly large number of features.  Then you may want an Entity-Attribute-Value setup.  EAV is extremely flexible, but has significant problems of it's own.  Again, no one-size-fits all.
In short, if what you have is working for you, what you have seems fine.


text:
Q: Actionscript 3 - Image not showing when printed I have a png image on top of any elements that are added to the working area. The user can click and drag new elements to the area and then print the picture they create. The png image is not moveable. The png image acts as a background image or like a container for the user's picture.
When I try to print it, the png image does not show. I get the elements to show nicely, but that is it. If I change a few things I am able to print only the png image and not the elements. How do I get them to print together?
//This puts my png image on top and unclickable
stage.addChild(seal);
seal.mouseEnabled = false;

//this brings the current element to the front
for (var fl_ChildIndex_5:int = 0;
    fl_ChildIndex_5 < this.numChildren;
    fl_ChildIndex_5++) {
    this.getChildAt(fl_ChildIndex_5).addEventListener(MouseEvent.CLICK, fl_ClickToBringToFront_5);
}
function fl_ClickToBringToFront_5(event:MouseEvent):void {
    this.addChild(event.currentTarget as DisplayObject);
}

//This is my print button
var button:Sprite = new Sprite();
button.graphics.beginFill(0xf67821, 1);
button.graphics.drawRect(0, 0, 120, 60);
button.graphics.endFill();
addChild(button);

button.addEventListener(MouseEvent.CLICK, printContent);

var myArea:MovieClip = root as MovieClip;
var myRectangle:Rectangle = new Rectangle(150,0,700,500);

function printContent(event:MouseEvent) {
   var printJob:PrintJob = new PrintJob();
   if (printJob.start()) {
       if (myArea.width > printJob.pageWidth){
           myArea.width = printJob.pageWidth;
           myArea.scaleY = myArea.scaleX;
           {printAsBitmap:true};
       }
       printJob.addPage(myArea, myRectangle);
    }
    printJob.send();
    printJob = null;
}

NEWEST CODE
var workingarea:MovieClip = new MovieClip();
stage.addChild(workingarea);

var seal:Sprite = new Sprite();
seal = new SealImg();
seal.x = 475;
seal.y = 271;
workingarea.addChild(seal);

seal.mouseEnabled = false;
seal.mouseChildren = false;


text:
Q: How to sort a collection based on a custom list I have a number of lists.. in Scala or Java. List looks like this
List({cat, toronto}, {dog, vancouver}, {mouse, calgary} ... ). Assume {cat, toronto} is an object of two strings.
I need to sort these lists based on another criteria which is also a list, for example>> List(dog, cat, mouse). As you can see, the sort criteria has no particular logic or natural sort order.
I understand it is always possible to use brute force approach. That is what I want to avoid. I want to sort like this >> myList1.sort(listCriteria), and then myList2.sort(listCriteria), and so on.
Is there any way to do this? Thanks.

A: Not sure I understand the question, but it seems you just want to map a list of keys to a list of key-value pairs. Like
val in   = List(("cat", "toronto"), ("dog", "vancouver"), ("mouse", "calgary"))
val dict = in.toMap

def sort(keys: List[String]): List[(String, String)] =
  keys.map(key => key -> dict(key))

sort(List("dog", "cat", "mouse"))

res3: List[(String, String)] = List((dog,vancouver), (cat,toronto), (mouse,calgary))

A: You can create a HashMap that maps each string from the criterion list to its position and then create a comparator that gets values from the HashMap and compares those. This way, a comparison requires O(1) time (on average).

A: You can create a comparator/lambda expression that compares elements by their index in your second list. Here's a plain java approach:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MapSort {

    private static class MyObject {
        final String first;
        final String second;

        public MyObject(String first, String second) {
            this.first = first;
            this.second = second;
        }

        @Override
        public String toString() {
            return this.first + "/" + this.second;
        }
    }

    public static void main(String[] args) {
        List<String> desiredOrder = Arrays.asList("dog", "cat", "mouse");
        List<MyObject> listToBeSorted = new ArrayList<>();
        listToBeSorted.add(new MyObject("cat", "toronto"));
        listToBeSorted.add(new MyObject("dog", "vancouver"));
        listToBeSorted.add(new MyObject("mouse", "calgary"));

        System.out.println(listToBeSorted);

        listToBeSorted.sort((o1, o2) -> desiredOrder.indexOf(o1.first) - desiredOrder.indexOf(o2.first));

        System.out.println(listToBeSorted);
    }
}

Output:
[cat/toronto, dog/vancouver, mouse/calgary]
[dog/vancouver, cat/toronto, mouse/calgary]


text:
Q: Recursive method using List Within an asp.net application I have a list of categories objects, within this list each category can be a parent of another category.
Example:
catid 1 catname cat1 parentid null
catid 2 catname cat2 parentid null
catid 3 catname cat3 parentid 2
catid 4 catname cat4 parentid 2
catid 5 catname cat5 parentid 4
catid 6 catname cat6 parentid 5
catit 7 catname cat7 parentid 5

I want to write a method that loops through the list of categories, pulls out the parent categories and acquires the child categories from the list.
Doing this is easy the hard part I am having problems with is how do I know when the last category object has been reached within a recursive method.
This is the logic I am looking for
protected void load_categories(ref List<category> list, category item)
{
     //loop through list and match item ID with list item parent ID
     //loop through child items of category item using load_categories()
     //HOW DO I STOP ONCE EVERYTHING IS DONE?
}

A: I would do so:
List<category> categoryWithParents = new List<category>();
protected void load_categories(List<category> list, category item)
{
    foreach(category cat in list)
    {
       if(item.id == cat.id)
       {
         categoryWithParents.Add(cat);
         if(cat.parentid != null) //if category has parent
           load_categories(list, cat); //load that parent
         break; //adding break should stop looping because we found category
       }
    }
}

when you call method with category catid 5 catname cat5 parentid 4 categoryWithParents list should contain(in adding order):
catid 5 catname cat5 parentid 4
catid 4 catname cat4 parentid 2
catid 2 catname cat2 parentid null

A: You could pass the index of the current item around and only continue while the index is less than the number of items in the list.

A: I suppose you have some code like this
 results = new empty results

 For childItem in list
     if ( childItem.parentId == item.id )
           results.add ( loadCategories( list, item )
     else
           // nothing to do

 return results

so your recursion-stopping just falls out, it's the else => nothing to do


text:
Q: AngularJS ng-repeat with filter - notarray error I have a list of items that I'm displaying with ng-repeat.  I want to add a filter to show/hide archived items.
I have added a checkbox:
<input type="checkbox" ng-model="queryFilter.archived">Show archived messages

In my controller I have this:
$scope.queryFilter = {
    archived: false
};

My list of items is displayed in a table.  I've tried the following:

I get this error:

Error: [filter:notarray]
Expected array but received: {}

The filtering does work but I want to know why I am getting the error.

A: I had initialised messages as an object.
Changing $scope.messages = {}; to $scope.messages = []; made the error go away.

A: Your messages must be containing the data in Object form not in the Array form.
That is why this error is being thrown. Check the doc https://docs.angularjs.org/error/filter/notarray
From the docs:

Filter must be used with an array so a subset of items can be
  returned. The array can be initialized asynchronously and therefore
  null or undefined won't throw this error.

So make sure, your $scope.messages containing data in array form not in the Object form.

A: The track by $ index makes angular syntax incorrect, since it is directly positioned behind the filter instruction. Try moving it behind the repeat statement so there is a clear separation between the track by and filter statements.

A: queryfilter is an object not an array. So apply the ng-repeat on queryfilter as given below

if queryfilter is array then simply use

track by $index is necessary whenever we loop the object


text:
Q: Order of Affine non-soluble groups 2-Transitive groups has been classified. The complete table has been mentioned in this Textbook ( see e.g., Table 7.3 and Table 7.4, page no. 194-197). Table 7.3 contains Affine 2-transitive groups and Table 7.4 contains Almost Simple 2-transitive groups.
Question
Consider only first 6 entries of the Table 7.3. Which groups out of these 6 are non-solvable ?
Note Refer this  for the definition of 2-transitive group and this for the definition of solvable group.


text:
Q: Re-run last failed test in PHPUnit You may use --stop-on-failure flag to break the unit testing when one of the tests fails.
Is there any way quick way to tell PHPUnit to re-run this failed test, instead providing the full path manually?

A: Since PHPUnit 7.3, you can cache the results of your tests, then order your tests by defects.
In phpunit.xml, enable cacheResults:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit cacheResult="true"
         ...>

If you don't want to edit your phpunit.xml, you could also run your tests with the --cache-result flag.
When caching results, PHPUnit will create a .phpunit.result.cache file after running tests. Make sure to add this file to your global gitignore file.
You can run your tests like this to run previously failed tests first:
phpunit --order-by=defects --stop-on-failure

A: The way I've found to implement it is fairly easy, but requires logging to be implemented. You setup phpunit to log to a json file. Then you alter the phpunit command to something similar to:
cd /home/vagrant/tests && php -d auto_prepend_file=./tests-prepend.php /usr/local/bin/phpunit

What this does is auto_prepend a php file before the execution of phpunit. This way we can capture $argsv and supply the required filter command automatically to phpunit.
tests-prepend.php
(make sure to amend the file pathway of the json log)
<?php

global $argv, $argc;
if(empty($argv) === false) {
    // are we re-running?
    $has_rerun = false;
    foreach ($argv as $key => $value) {
        if($value === '--rerun-failures') {
            $has_rerun = true;
            unset($argv[$key]);
            break;
        }
    }
    if($has_rerun === true) {
        // validate the path exists and if so then capture the json data.
        $path = realpath(dirname(__FILE__).'/../logs/report.json');
        if(is_file($path) === true) {
            // special consideration taken here as phpunit does not store the report as a json array.
            $data = json_decode('['.str_replace('}{'.PHP_EOL, '},{'.PHP_EOL, file_get_contents($path).']'), true);
            $failed = array();
            // capture the failures as well as errors but taking care not to capture skipped tests.
            foreach ($data as $event) {
                if($event['event'] === 'test') {
                    if($event['status'] === 'fail') {
                        $failed[] = array($event['test'], 'failed');
                    }
                    elseif($event['status'] === 'error' && $event['trace'][0]['function'] !== 'markTestIncomplete') {
                        $failed[] = array($event['test'], 'error\'d');
                    }
                }
            }
            if(empty($failed) === true) {
                echo 'There are no failed tests to re-run.'.PHP_EOL.PHP_EOL;
                exit;
            }
            else{
                echo '--------------------------------------------------------------------'.PHP_EOL;
                echo 'Re-running the following tests: '.PHP_EOL;
                foreach ($failed as $key => $test_data) {
                    echo ' - '.$test_data[0].' ('.$test_data[1].')'.PHP_EOL;
                    // important to escapre the namespace backslashes.
                    $failed[$key] = addslashes($test_data[0]);
                }
                echo '--------------------------------------------------------------------'.PHP_EOL.PHP_EOL;
            }
            $argv[] = '--filter';
            $argv[] = '/('.implode('|', $failed).')/';
            // important to update the globals in every location.
            $_SERVER['argv'] = $GLOBALS['_SERVER']['argv'] = $GLOBALS['argv'] = $argv = array_values($argv);
            $_SERVER['argc'] = $GLOBALS['_SERVER']['argc'] = $GLOBALS['argc'] = $argc = count($argv);
        }
        else{
            echo 'The last run report log at '.$path.' does not exist so it is not possible to re-run the failed tests. Please re-run the test suite without the --rerun-failures command.'.PHP_EOL.PHP_EOL;
            exit;
        }
    }
}

A: Take a look at the --filter cli option. You can find an example in the organisation docs and in the CLI Docs.

--filter
Only runs tests whose name matches the given pattern. The pattern can be either the name of a single test or a regular expression that matches multiple test names.

Assume your run phpunit Tests/ and Tests/Stuff/ThatOneTestClassAgain::testThisWorks fails:
your options are:
phpunit --filter ThatOneTestClassAgain
and
phpunit --filter testThisWorks
or most other strings that somehow make sense


text:
Q: How to get autofill for Safari for last name/family-name fields? I have troubles getting autofill work for iOS Safari browser in a form where name is parted up into first and last name.
I have tried with this simple example:
<input type="text" placeholder="e.g. John" autocomplete="given-name" name="firstName">
<input type="text" placeholder="e.g. Doe" autocomplete="family-name" name="lastName">

But that only suggest to autofill the firstname.
Here's a codepen: https://codepen.io/simplenotezy-the-looper/pen/PoOoqjx
Options I've tried for autocomplete="":

*

*family-name

*surname

*lastname

*last-name

*lname

*last name

I've also tried changing the name="" field to names from above list to no avail.

A: It's disabled by default, you must enable it in your iOS settings
See https://support.apple.com/guide/iphone/automatically-fill-in-forms-iphccfb450b7/ios


text:
Q: Can I switch database with mysql_select_db? Will this works, or should I disconnect first?
<?php
mysql_connect('localhost','root','');
mysql_select_db('DB1');
//Code...
//Now I need to change of db
mysql_select_db('DB2');
//More code...

I know mysql() is being deprecated, but I'm working with a old (not so much) system. Thanks!

A: The documentation say yes:
Ref: http://php.net/manual/en/function.mysql-select-db.php
All queries will run on the current active database, at this case DB2.
Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database.

A: You can use it in sql like
SELECT `database`.`table`.`value` FROM `database`.`table`

A: The docs say:

Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database.

So yes. I guess it is comparable to a use <database> command on the client.

A: you can have more than one active connection
$db1=mysql_connect('localhost','root','');
mysql_select_db('DB1', $db1);

$db2=mysql_connect('localhost','root','');
mysql_select_db('DB2', $db2);

mysql_query("SELECT * FROM table", $db1);
mysql_query("SELECT * FROM table", $db2);


text:
Q: Connecting RDS instance via mysqlworkbench failing I have created RDS instance with my own VPC. I had selected public accessible while creating the RDS instance. I have attached internet gateway with VPC. The security group for RDS has entry for 3306 port with my system IP address. I am using default ACL. Still on connecting the RDS instance from mysqlworkench error is coming.

A:
Double check that you have added to correct information and test connection from above
  image. You also need to open 3306 port for your instance.  Check if
  you have root user privileges in console.


text:
Q: Saving Traned AI models In Google Colab After training a twin delayed DDPG agent in Google colab for 10 hours I downloaded the python file to continue the work on another platform. The problem however is that the training data is not included when I save the python notebook file, hence the training data was lost. How can I save the file, move it to for example to the Unity 3D environment without dropping the training so I don't have to re-train the agent.
I sincerely appreciate any answers, comments, thoughts etc!

A: Store files you want to be persistent across sessions in Drive.
Here's a snippet showing how to mount your Google Drive as a FUSE filesystem in Colab:
https://colab.research.google.com/notebooks/io.ipynb#scrollTo=u22w3BFiOveA