Checagem de arquivo existente de maneira assíncrona

Question: Meu código recebe escreve um arquivo, porém, precisa verificar se o arquivo já existe e, caso exista, renomeá-lo. É possível fazer isso sem usar o fs.existsSync?
Meu código atual:
fs.readFile(file.path, function (err, data) {

    for (i=2; !fs.existsSync(file.path); i++){
        file.name =file.name + i.toString();
        file.path = "./public/files/" + file.name;
    };
}

fs.writeFile(file.path, data, function (err) {
  if (err) {
    return console.warn(err);
  }
  console.log("The file: " + file.name + " was saved as " + file.path);
});

Answer: Será que isso pode te ajudar? Documentação
var fs = require("fs");
var Promise = require("bluebird");

function existsAsync(path) {
  return new Promise(function(resolve, reject){
    fs.exists(path, function(exists){
      resolve(exists);
    })
  })
}

Ou então:
var path = require('path');

path.exists('foo.txt', function(exists) {
  if (exists) {
    // faça alguma coisa
  }
});

// ou

if (path.existsSync('foo.txt')) {
  // faça algo
}

Para versões acima de Node.js v0.12.x

path.exists efs.exists estão depreciados use fs.stat  :
fs.stat('foo.txt', function(err, stat) {
    if(err == null) {
        console.log('File exists');
    } else if(err.code == 'ENOENT') {
        // file does not exist
        fs.writeFile('log.txt', 'Some log\n');
    } else {
        console.log('Some other error: ', err.code);
    }
});

espero ter conseguido te ajudar!


Control flow during json parsing - Objective C

Question: I am trying to create a login screen where one has to enter his UserName and Password. On clicking the login button I am parsing the details to the server. Here's the code
<code>    NSString *post = [NSString stringWithFormat:@"username=%@&password=%@",[_userNameText text],[_passwordText text]];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu" , (unsigned long)[postData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://*******/*****/******/userLogin.php"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"sample data"];
    [request setHTTPBody:postData];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    [[session dataTaskWithRequest:request completionHandler:^(NSData *data , NSURLResponse *response , NSError *error){
        _requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
        NSLog(@"%@",_requestReply);
    }] resume];
</code>
So far the code works just as intended. Now I want to check if the "requestReply" that is returned from the server has the value "success" for it's "status" key. So I tried to print it's value with the following code.
<code>    _responseData = _requestReply;
    NSLog(@"%@" , _responseData[@"status"]);
</code>
And here's the console output
<code>2016-10-21 06:44:03.424 QuizApp2[65724:1287972] (null)
2016-10-21 06:44:03.501 QuizApp2[65724:1288003] {"status":"success","message":"Welcome admin","code":true}
</code>
I am not sure, but I felt that the last line of the code is executing before the parsing happens. Can someone please highlight how the control flows here? Or is there anything wrong with my code?
Comment: where do you call `_responseData = _requestReply;`? inside the block `session dataTaskWithRequest` or outside?
Comment: ahh if so at the time it runs, `_requestReply` has no data because the block runs asynchronously. If you put those 2 lines inside the block, it will work
Comment: right after "resume". Outside
Comment: @Ti3t - Oh! That's really helpful. Thanks mate!
Answer: I didn't see any code about parse data. Do you mean this line
<code>_requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
</code>
If the userLogin.php returns a JSON data, just do this:
<code>[[session dataTaskWithRequest:request completionHandler:^(NSData *data , NSURLResponse *response , NSError *error){
    NSError *err = nil;
    id jsonData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
    if (err) {
        NSLog(@"%@", err);
    }
    else {
        NSLog(@"%@", jsonData[@"status"]);
    }
}] resume];
</code>
Comment: Thanks. This actually worked, but I am not sure I understand how. And I can't understand why any statements I write after the "resume" get executed before the parsing. I am new to Objective C.


How to change the speed of AVPlayerViewController?

Question: Below is an factory method to setup an AVPlayerViewController.
Everything except the speed control works fine.
In an older version of this app I was able to go from half speed to double speed by simply setting the player.rate.
Double doesn't work anymore but half speed does and I'm not sure why.
The docs say that canPlayFastForward and canPlaySlowForward need to be true however i don't see a way to set them to true.
<code>extension AVPlayerViewController {

    static func create(url: URL, rate: Float, time: CMTime, delegate: AVPlayerViewControllerDelegate?) -> AVPlayerViewController {
        let avPlayerVC = AVPlayerViewController()
        avPlayerVC.delegate = delegate
        let playerItem = AVPlayerItem(url: url)
//        playerItem.canPlayFastForward = true
//        playerItem.canPlaySlowForward =  true
        let player = AVPlayer(playerItem: playerItem)
        player.rate = rate
        player.seek(to: time)
        avPlayerVC.player = player
        return avPlayerVC
    }
}
</code>
Answer: So what seems to be the solution is that one cannot set the rate of the AVPlayer to 2 but one can set it to 1.99.


Good, authoritative recent book on factor analysis and principal component analysis

Question: Questions regarding factor analysis and principal component analysis, both here and elsewhere, reveal considerable confusion of terms, disagreements about requirements, different recommendations for different issues and so on.  Different programs label the same output differently. There is a fairly bewildering number of choices of extraction, rotation and so on.  In addition, there is confusion about exploratory vs. confirmatory factor analysis and how both differ from principal component analysis.
I studied factor analysis way back in the late 1990s.  I've read a bunch of recent articles. I think I more or less know what I am doing. However, it would be good to know of some authoritative recent source; perhaps an edited collection.
Some quick searching on Amazon didn't reveal any obvious candidates; are there any?
Comment: If you think PCA is worth an entire book, you don't take FA very seriously, and vice versa. I doubt that the books focused on PCA (Jolliffe, Jackson) would be regarded as good treatments of FA by FA specialists or enthusiasts. I don't really know the reverse literature, but the reasons underlying confusion and controversy also imply that impartial, dispassionate treatments will be elusive.
Comment: Peter, my own _opinion_ is that almost all issues of confusion you mention have been discussed and settled in good old thick books (such as Harman. Modern Factor Analysis). _Linear_ classic PCA/FA seem to already stop developing. But most "disagreements" are yet about these classic versions. I suppose it is due to the vulgarization of their knowledge among students and even professionals, which is the reverse of the pop status of the techniques. The same as with linear regression: people and managers use it mechanically every day because it is "basic", and still, know it very superficially.
Comment: There has been work in journal articles e.g. by Joresgkog and others on ordinal data, by Muthen and others on missing data, etc. Maximum likelihood FA was barely possible when some of the old books were written (computer speed issue). But even on "old" stuff like sample size requirements, I've seen different advice in various places.
Answer: There was a conference in 2004 »Factor Analysis at 100. Historical Developments and Future Directions«.
An edited book of chapters based on conference presentations followed:
Cudeck/MacCallum. 2007. Factor Analysis at 100. Historical Developments and Future Directions. Lawrence Erlbaum.
From the preface:

This book is the result of a conference that was held at the University of North Carolina in the spring of 2004 to commemorate the 100 year anniversary of Spearman's famous article. The purpose of the conference and of this book was to review the contributions of the last century that have produced the extensive body of knowledge associated with factor analysis and other latent variable models. The contributors also took the occasion to describe the main contemporary themes in statistical models for latent variables and to give an overview of how these ideas are being extended.
Answer: By just looking at (or seeing) this
In 1977, [Yoshio Takane] earned his Ph. D. in Psychometrics from the Univeraity of
   North Carolina at Chapel Hill.
and this
Peter Flom received his Ph.D. in Psychometrics in 1999 from
   Fordham University, where he was a Presidential fellow.
it is possible to assume that you are looking for the book entitled "Constrained Principal Component Analysis and Related Techniques" authored solely by Yoshio Takane and published by CRC press in 2014
I think it is reasonably authoritative but please let us know if it is modern enough (Japanese version is dated 1995).
Comment: Neither a book nor especially recent, but Multivariate Behavioral Research published a dynamite issue about 10-12 years ago all about EFA and PCA.
Comment: @gung and ttnphns:  The journal issue I mentioned seems to have been in 1990, volume 25, judging from Wayne Velicer's publication list at http://www.uri.edu/research/cprc/Publications/Authors/WVelicer.htm.  See #10, Velicer, W. F., & Jackson, D.N.  (1990).  Component analysis vs. common factor analysis: Some issues in selecting an appropriate procedure.   Multivariate Behavioral Research, 25, 1-28. Also see the many references to articles from this issue in http://pareonline.net/pdf/v10n7.pdf.
Comment: @rolando2, could you track down the issue?
Comment: I did get my degree in psychometrics, but these days my work is almost all in statistics. 1995 is pretty old.... But maybe nothing major has been done recently.
Comment: @rolando2, I follow with gung in my interest.
Comment: @Peter Flom I did not say the English version of 2014 was a direct translation of the Japanese version of 1995. A quick look at the references should tell you how much new was added. Page 1 shows the author does refer to works (including his own) dated 2011 and 2013.
Comment: @Hibernating OIC! Thanks, however, this book is on one particular subset of PCA - constrained PCA (at least from reading the table of contents and the preface). Still, it looks interesting


Multinomial theorem problem

Question: I am supposed to determine the coefficient of $$x^{2}z^{3}$$ of expression:$$(x+y+z)^{5}$$. What I did:
$$\sum _{i=0}^{5}\binom{5}{i}x^{5-i}\left ( y+z \right )^{i}=\sum _{i=0}^{5}\binom{5}{i}x^{5-i}\sum _{j=0}^{i}\binom{i}{j}y^{i-j}z^{j}$$ and that should be equal to$$\binom{5}{i,j,5-i-j}x^{i}y^{j}z^{5-i-j}$$ Can anyone please explain the last step?
Comment: There are really many duplicates (or almost duplicates) here of this question, e.g., [here](https://math.stackexchange.com/questions/484908/find-the-coefficient-of-w3x5z2-in-the-expansion-of-wxyz10), or [here](https://math.stackexchange.com/questions/2258535/find-the-coefficient-of-x2y2z4-in-the-expansion-of-x-2yz8), or [here](https://math.stackexchange.com/questions/2418955/find-the-coefficient-of-x15y4-in-the-expansion-of-2x-3y19?rq=1), etc.
Answer: $$\require{cancel} \dbinom{5}{i}\dbinom{i}{j} = \dfrac{5!}{(5-i)!\cancel{i!}}\cdot \dfrac{\cancel{i!}}{j!(i-j)!} = \dfrac{5!}{(5-i)!j!(i-j)!}$$
Now, we re-index:
$$i' = i-j, j'=j$$
This implies $i = i'+j'$, so the RHS of the equation above becomes:
$$\dfrac{5!}{(5-i'-j')!j'!i'!} = \dbinom{5}{i',j',5-i'-j'}$$
Comment: Thank you so much

Multinomial theorem problem


repeating elements in common lisp

Question: I am try to create a function with two arguments x and y which creates a list of y times repeated elements X but im getting confused on how to do it which or which method to use i think list compression  can do but i want a shorter and simple method for example i want my simple code to be like this
if y = 4
 and x = 7
 result is list of elements (7, 7, 7, 7)

how can i go about it any ideas?? books links or anything that will give me a clue i tried searching but i have not been lucky
Answer: You can use make-list with the initial-element key:
CL-USER> (make-list 10 :initial-element 8)
   (8 8 8 8 8 8 8 8 8 8)

While a good example of how you can code such a function by yourself is provided by Óscar answer.
Comment: This should be the accepted answer
Answer: Try this, it's in Scheme but the general idea should be easy enough to translate to Common Lisp:
(define (repeat x y)
  (if (zero? y)
      null
      (cons x
            (repeat x (sub1 y)))))

EDIT:
Now, in Common Lisp:
(defun repeat (x y)
  (if (zerop y)
      nil
      (cons x
            (repeat x (1- y)))))

Comment: if one of the results from `if` is going to be `nil` anyway, it seems cleaner to me to negate the condition and just leave off the second ("else") argument, which defaults to `nil` if not specified:  `(if (not (zerop y)) (cons x (repeat x (1- y))))`.
Comment: @MarkReed I dislike one-armed `if`s. They're forbidden in Racket for a good reason ;)

repeating elements in common lisp


How to include clock_gettime in a c make file

Question: I know that in order to use the clock_gettime(2) function, you have to include -lrt in the makefile but I have no idea where it goes. Where would I put it in the example makefile.
CFLAGS = -g -Wall -std=c99
CC = gcc

objects = example.o

example: $(objects)
    $(CC) $(CFLAGS) -o example $(objects)

example.o: example.c
    $(CC) $(CFLAGS) -c example.c
clean:
    rm test $(objects)

Edit: how my lrt looks.

What my code is:
#include "stdio.h"
#include "stdlib.h"
#include <time.h>

int main(int argc, char *argv[]) {

    struct timespec starttime, endtime;
    double elapsed;
    clock_gettime(CLOCK_REALTIME, &starttime);

    /// work to be timed

    clock_gettime(CLOCK_REALTIME, &endtime);
    elapsed = ((endtime.tv_sec-starttime.tv_sec)*1000000000.0 + (endtime.tv_nsec - starttime.tv_nsec))/1000000000;
    // elapsed time can also be calculated as
    if (endtime.tv_nsec < starttime.tv_nsec) {
        // borrow a second
        elapsed = (endtime.tv_sec - starttime.tv_sec - 1) + (1000000000.0 + endtime.tv_nsec - starttime.tv_nsec)/1000000000;
    }
    else {
        elapsed = (endtime.tv_sec - starttime.tv_sec ) + (endtime.tv_nsec - starttime.tv_nsec)/1000000000;
    }
}

Comment: Note that it's `-lrt`, not `-1rt` (it's an 'L', not the digit '1'). You need to put it on the line that builds the executable (so, in the line after `example: $(objects)`). Make sure it's the last thing on that line.
Comment: @FilipeGonçalves i changed it to lower case L but it still looks different. Does it have to look exactly like yours because in TextEdit it looks different.
Comment: It's a lower-case 'L'. I just typed upper-case to show the difference. See dbush's answer, that's what you need.
Comment: @FilipeGonçalves edited my question. Added a picture of how lrt looks in my text editor. Is the font of the l causing it to not work?
Comment: It looks good. I would suggest posting the actual error message (or describe whatever problem you're having); that might be a better clue for us to help you.
Comment: The font has nothing to do with it.  As long as it's a lower case L it should be fine.  If it's still not working, post the error message.
Comment: See my answer. You need to include `time.h` in the source code.
Comment: @dbush posted it, my code looks exactly like ritesh posted, and I'm importing time.h and I'm still getting those errors.
Comment: If that's the case, then something else is off.  Please post your code (in text format, not a screenshot) so we can get more context on what your error is.
Comment: @dbush added the code
Comment: It compiles fine for me with `gcc -Wall -o /tmp/x1 /tmp/x1.c -lrt`
Answer: You want to put it on the line that links the executable.  Namely, the line that specifies the -o option.  That's where the linker phase is carried out.
example: $(objects)
    $(CC) $(CFLAGS) -o example $(objects) -lrt

Answer: CFLAGS = -g -Wall -std=c99
CC = gcc
LDFLAGS = -lrt

objects = example.o

example: $(objects)
    $(CC) $(CFLAGS) -o example $(objects) $(LDFLAGS)

example.o: example.c
    $(CC) $(CFLAGS) -c example.c
clean:
    rm test $(objects)

As this is linker option, so its best to use as LDFLAGS variable which is common practice in Makefiles.
Comment: LDLIBS for libraries, LDFLAGS for other linker options, usually. Of course you can call it whatever you want as long as you don't need implicit rules to work.
Comment: @Wumpus I agree with you.
Comment: @Ritesh, that is confusing.  You agree you don't need implicit rules to work?
Answer: The other answers are correct, but your problem seems to be that you're not including the necessary header files.
Add this in your source code:
#include <time.h>


Why can't I access my CouchDB instance externally on Ubuntu 9.04 server?

Question: Update: I got it working now. Jim Zajkowski's answer helped me detect that my /etc/init.d/couchdb reboot calls weren't actually rebooting the instance. After I manually killed the CouchDB processes and started a new instance, it picked up the required BindAddress change.
I have installed CouchDB via

aptitude install couchdb

From my server, I can connect via

telnet localhost 5984

and execute RESTful commands. When I try to access the server from another machine on our network or from a machine external of our network, I get a The connection was reset error. I've set up port forwarding on the router, and the server is otherwise accessible via Apache, Tomcat, SSH, etc.
I'm new to Linux/Ubuntu, so I wasn't sure if there was a default firewall blocking the connection, so I ran:

iptables -A INPUT -p tcp --dport 5984 -j ACCEPT

but it didn't help.
Here is the dump from running iptables -L -n -v
Chain INPUT (policy ACCEPT 2121K packets, 1319M bytes)
 pkts bytes target     prot opt in     out     source               destination
   70  3864 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:5984
    9  1647 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:8080
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:8080

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 1708K packets, 1136M bytes)
 pkts bytes target     prot opt in     out     source               destination

I assume the bytes showing as transfered for 5984 are due to my localhost connection.
Here is the dump from running netstat -an | grep 5984
tcp        0      0 127.0.0.1:5984          0.0.0.0:*               LISTEN

I configured couch.ini to have "BindAddress=0.0.0.0" and rebooted, so it should be listening on all interfaces. When I run "sudo /etc/init.d/couchdb stop" then run netstat, however, I still see the above entry. It looks like CouchDB isn't actually stopping at all. This may explain my problem, because it means it may mean that CouchDB never actually rebooted and never picked up the BindAddress change.
I manually killed the CouchDB process and started it up again. Now netstat shows:
 tcp        0      0 127.0.0.1:5984          0.0.0.0:*               LISTEN
 tcp        0      0 127.0.0.1:5984          127.0.0.1:35366         TIME_WAIT

I still can't connect though, even from another machine on the LAN.
Comment: This problem still exists in Ubuntu 12. You'd think the package maintainer would have fixed this by now?
Answer: What does netstat -an | grep 5984 say?  Does it say 127.0.0.1:5984 or *:5984?  If it's 127.0.0.1, then couchdb needs to be set to listen to either all interfaces.
Comment: "tcp  0  0  127.0.0.1:5984  0.0.0.0:*  LISTEN" is the result. I configured couch.ini to have "BindAddress=0.0.0.0" and rebooted, so it should be listening on all interfaces. Here's the strange part though: when I run "sudo /etc/init.d/couchdb stop" then run netstat, I still see the above entry. It looks like CouchDB isn't actually stopping at all. This may explain my problem, because it means it probably never rebooted, and probably never picked up the BindAddress change
Comment: yep, I was running as a background process. it worked for me once i killed couchdb using couchdb -d and restarted it
Comment: This answer helped me! I wanted to share that **one may easily change this setting using the Futon web interface, without having to find and edit the actual config file on disk**. Just navigate to `127.0.0.1:5984/_utils/config.html` (or equivalent URL for your setup) and double click the option value, edit, then click the green check mark.
Comment: @Mr.Hyde Futon must be installed and running, in which case you acces it at the path `/_utils`. From the main Futon page you can navigate to the config section via the link on the right. Note that your base URL and port can vary depending on your CouchDB setup and system.
Comment: @SteveBenner Unfortunately 127.0.0.1:5984/_utils/config.html doesn't bring anything!
Comment: @rcampbell Where is couch.ini  ?!
Answer: You have to change the bind_address in /etc/couchdb/default.ini. Then restart the service and try again.
Comment: i.e. [change to 0.0.0.0](http://docs.couchdb.org/en/latest/config/http.html)
Answer: I noticed that in order for this to work you must manually kill the running erlang process for some reason.ps ax | grep beam ought to reveal the erlang process, you should get something along lines of 0:00 /usr/lib/erlang/erts somewhere in the output. If you kill this process and then run /etc/init.d/couchdb restart the new config file will be loaded.
Comment: same for me - only after killing the beam process, then do the couchdb -d, and then service stop/start.. did the new setting take effect.
Answer: On home PC/Mac run this command:
ssh -L 5984:localhost:5984 YOUR-SERVER-IP-HERE

next open in your browser localhost:5984/_utils ...
It works for me
Answer: Configuration docs:

If you change it from the Futon configuration panel, you don't have to do anything else (rebooting the db etc.):

Before changing the default bind_address:
peter@earth:~/$ netstat -an | grep 5984
tcp        0      0 127.0.0.1:5984          0.0.0.0:*               LISTEN

After changing to 0.0.0.0:
peter@earth:~/$ netstat -an | grep 5984
tcp        0      0 0.0.0.1:5984          0.0.0.0:*               LISTEN

Note non-gurus: computers which cannot access yours (normally, anything outside your local network) will still not be able to access your computer (CouchDB or anything else).
Comment: While this answer is pretty old, it seems to lead to the right place.  Futon has been replaced with Fauxton, but I think people will get the gist of changing the bind_address in the Configuration.
Answer: I encountered this, and my problem ended up being that there was, apparently, couchdb already installed in my installation of Ubuntu.  I had been editing the config files under /etc/couchdb, but the one that was running was in fact pulling config from /usr/local/etc/couchdb.
The tip-off was that the configs in /etc/couchdb mentioned couch 0.10, but I had just installed 1.0.1.
Answer: iptables -L -n -v will show you your current firewall rules.  See if there's one that's dropping those packets before it gets to your rule.
Comment: There are no DENY rules listed in the table. Otherwise, there are three ACCEPT, one for 5984  and two duplicates for 8080. I'm not sure why there are two exact duplicates for 8080, and when I try to hit Tomcat (running on 8080) external of our network it fails, even though machines on our network can hit Tomcat fine.
Comment: Mind showing the output?  Take your IP out if needed.
Comment: How about running `lsof -i -n -P | grep LISTEN` and posting that?  You're looking for the CouchDB process, and what it's bound to.  If it's `127.0.0.1:5984`, you need to configure CouchDB to listen to external connections.  If it's `*:5984`, well, at least CouchDB is configured right :)
Comment: Hi Bill, sorry for not responding sooner. I've posted the raw dump you requested to the question.
Comment: How about that `lsof` output?


Displaying Same images in gridview Based on dropdown selection

Question: I Have Menu Table and product table and MenuId ins the common field
Example
Menu Table
MenuId MenuName
11      Shirts
12      Tshirts

Product Table
ProductId ProductName MenuId ProductImage
1          Levisshirts 11     image
2          white shirt 11     image2

have display image in girdview based on drop down selection but the problem is it display same image for every products my code as follows
protected void Page_Load(object sender, EventArgs e)
{
    con.Open();
    if (!IsPostBack)
        ddlbind();
}
private void BindGridData()
{
    SqlCommand command = new SqlCommand("SELECT * from rsa_ProductItemTable where  MenuId=" + Dropsearch.SelectedItem.Value, con);
    SqlDataAdapter daimages = new SqlDataAdapter(command);
    DataSet ds = new DataSet();
    daimages.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();
    GridView1.Attributes.Add("bordercolor", "black");
}
public void ddlbind()
{
    SqlCommand command = new SqlCommand("SELECT * from rsa_mastermenu", con);
    SqlDataAdapter daimages = new SqlDataAdapter(command);
    DataTable dt = new DataTable();
    daimages.Fill(dt);
    Dropsearch.DataSource = dt;
    Dropsearch.DataTextField = "MenuName";
    Dropsearch.DataValueField = "MenuId";
    Dropsearch.DataBind();
    Dropsearch.Items.Insert(0, new ListItem("Select", "0"));
}
protected void Dropsearch_SelectedIndexChanged(object sender, EventArgs e)
{
    int imgid = int.Parse(Dropsearch.SelectedItem.Value);
    BindGridData();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Image img = (Image)e.Row.FindControl("Image1");
        img.ImageUrl = "GridviewImage.ashx?ImID=" + Dropsearch.SelectedItem.Value;
    }
}

What am i doing wrong please help me with this
Comment: can you share your html code
Comment: i am unable to add html code
Comment: you can use <%# "path" + Eval("imageid")> in imageurl of aspx page
Comment:
Comment: give your image path. i'll give you html markup
Comment: ImageUrl='<%# "GridviewImage.ashx?ImID=" + Eval("ProductID")%>'
Comment: tried That getting same output and i do have handler page too
Comment: Current code what you posted looks correct, look into `GridviewImage.ashx` code for any faults.
Answer: Set image url in aspx ,
something like this
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "your_path" + "ProductImage" %>'
   Height="300px" Width="300px"/>
</ItemTemplate>

Plese make sure your_path is physical path where image is stored, for example "~/images/myimg" and your image name is valid, for example image.jpg or image1.png
by this method you can show image in gridview.
Comment: IMage is Stored in Database
Comment: your database column is of image datatype ?
Comment: have you canvertde your image from bytes brfore showing it ?
Comment: yes it displaying the image but problem is first image for all products i mean it displays same image
Comment: then your code seem ok i think you should check your handler


Call a function from another javascript program - functional programming

Question: I have a program isOvel.js which has a function isOvel(str) and I want to use this function isOvel(str) in an another program translate.js. Am just started with Javascript functional programming, your help will be much appreciated.!! I could not find any duplicates, please post it if any.
Comment: You're looking for `require()`.  See the documentation.
Comment: Unless the scripts are included on the same page (isOvel.js first) and scoped globally, you can't do that as far as I know
Comment: is the function declared in global space?
Comment: That depends how you're running your Javascript (and has nothing to do with functional programming)
Comment: @Todd - No, I haven't declared in global space.
Comment: @SterlingArcher - I did not understand the part - 'the scripts are included on the same page'. Am trying to test something with javascript, not developing any webpage.
Comment: @SLaks I am just running individual javascript programs, mainly to test functionality.
Comment: @chivas_hvn: **How**? Node.js? Rhino? HTML?
Comment: @SLaks Using **Node.js**
Comment: @SLaks - Yes, this is what I was looking for. Thanks!!
Answer: Javascript file isn't "program" is "file" you can include several files on your page.

    <title>My page</title>

Comment: Am trying to call and test `isOvel()` functionality from another js program, not building any webpage so please let me know how I can call it.
Comment: Did you see onload event ? http://stackoverflow.com/questions/20180251/when-to-use-window-onload


Want to show the results of a page in another page?

Question: I've created a windows phone 7 application using Isolated Storage. In this application i've used a button named as btnRead, a textblock named as txtRead and a text box named as txtWrite. If i write something to the textbox(txtWrite) and clicked on the button(btnRead). Then the textblock(txtRead) shows or saves whatever i write on textbox(All these are created in a single MainPage.xaml). Now I have created another page1.xaml and created a textblock named as txtShow. But I want the textblock(txtShow) to show all the things that i write on textbox which is in MainPage.xaml. I have also uploaded my project- https://skydrive.live.com/redir.aspx?cid=ea5aaefa4ad2307a&resid=EA5AAEFA4AD2307A!133&parid=EA5AAEFA4AD2307A!109
Below is MainPage.xaml.cs source that i have used -:
<code>    private void button1_Click(object sender, RoutedEventArgs e)
    {
        IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
        myStore.CreateDirectory("Bookmark");

        using (var isoFileStream = new IsolatedStorageFileStream("Bookmark\\myFile.txt", FileMode.OpenOrCreate, myStore))
        {
            //Write the data
            using (var isoFileWriter = new StreamWriter(isoFileStream))
            {
                isoFileWriter.WriteLine(txtWrite.Text);
            }
        }

        try
        {
            // Specify the file path and options.
            using (var isoFileStream = new IsolatedStorageFileStream("Bookmark\\myFile.txt", FileMode.Open, myStore))
            {
                // Read the data.
                using (var isoFileReader = new StreamReader(isoFileStream))
                {
                    txtRead.Text = isoFileReader.ReadLine();
                }
            }
        }
        catch
        {
            // Handle the case when the user attempts to click the Read button first.
            txtRead.Text = "Need to create directory and the file first.";
        }
    }
</code>
Answer: If you are displaying the text from the TextBox in a TextBlock in the same page, it would be easier to do that through binding
<code><TextBox x:Name="txtWrite"/>
<TextBlock  Text="{Binding Text, ElementName=txtWrite}"/>
</code>
To put this information into the next page you could put it into the NavigationContext to pass to the next page
<code>    // Navigate to Page1 FROM MainPage
    // This can be done in a button click event
    NavigationService.Navigate(new Uri("/Page1.xaml?text=" + txtWrite.Text, UriKind.Relative));

// Override OnNavigatedTo in Page1.xaml.cs
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    string text;
    NavigationContext.QueryString.TryGetValue("text", out text);
    txtRead.Text = text;
}
</code>
If you like using IsoStorage, you could do the read like you are doing above in the OnNavigatedTo method.
Comment: Then add it to a ListBox: listBox.Items.Add(text);


Set path for favicon.ico and apple-touch-icon.png

Question: I would like my favicon.ico to be accessible by http://example.com/favicon.ico and http://example.com/apple-touch-icon.png, but I can't manage that.
I tried few things, but nothing helped. My favicon.ico/apple-touch-icon.png is located in the theme root folder.
How can I achieve this?
Answer: use a symlink, I typically keep my main favicon in my root theme folder, and then in the terminal navigate to the site root and symlink to that icon
ln -s PATH/TO/THEME/favicon.ico

it makes the most sense to me to keep my theme assets in my theme directory, but then I also like to have the same favicon accessible from the doc-root as well
Answer: Use Sumit Madan's answer for favicon.
You can put the touch-icon in the files folder too. And edit yourtheme's template.php
Put this:
  $appleIcon = array('#tag' => 'link', '#attributes' => array('href' => '/sites/default/files/apple-touch-icon-144x144.png', 'rel' => 'apple-touch-icon', 'type' => 'image/png'),);
  drupal_add_html_head($appleIcon, 'apple-touch-icon');

inside
function yourtheme_preprocess_html(&$variables) {

}

Answer: I would personally just do a .htaccess Rewrite rule:
RewriteCond %{REQUEST_URI} /favicon.ico
RewriteRule ^ /actual/path/to/favicon.ico

and same for apple touch icon
Answer: Just place your image in root folder and add the path as in screenshot :


How to span a div 100% of the available width

Question: I have two sibling divs nested inside a div like:

Filter

        ....

The first div with class col-md-1 has a border-right 1px solid black;.
And the second div col-md-9 may span two rows based on the number of items inside.
even if I say
 It does not span those two rows.

How to make sure the border spans across those two rows apart from saying a fixed height of some px?
Comment: wrap those two rows inside a `div`. Set the `border height` of that `div` to whatever you want to. That's how you wrap it all together in a border.
Comment: Why not just make `col-md-9` have a left border of `1px solid black`?
Comment: @GaryHoliday Thanks you. I just realized how stupid of a question it was.
Answer: I would just change the point of view, and add the border from the right side.
... {
    border-left: 1p solid black;
}

Comment: It's basically what @Gary Holiday commented initially. Feel free to give him some credit.
Comment: True that. It was indeed a stupid question to ask. Thanks a lot.
Comment: @ZombieChowder Sure. It would be entirely unethical if I do not.
Comment: @StrugglingCoder I wasn't referring to you haha, never mind. I'm glad you got your answer tho'


How to use focus() event in mozilla firefox?

Question: I have used focus() method, but it does not work on Mozilla Firefox. I have used the following code in asp .net:
protected void drgBranches_SelectedIndexChanged(object sender, EventArgs e)
{
  txtLoginName.Text = drgBranches.SelectedValue;
  txtLoginName.Focus();
}

Comment: Seems to be working fine on my end. Can you make an [MCVE](https://stackoverflow.com/help/mcve)?
Comment: This link says these events doesn't support mozilla http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onfocusin_eventdelegation
Comment: Just use the regular [`focus`](https://developer.mozilla.org/en-US/docs/Web/Events/focus) and [`blur`](https://developer.mozilla.org/en-US/docs/Web/Events/blur) events. You will probably have to use to set the `useCapture` argument in `addEventListener` to `true`.
Answer: You can just the regular focus
<input id="target" type="text" value="Field 1">

$("#target").focus(function() {
  alert( "Handler for .focus() called." );
});

https://jsfiddle.net/3o11wnus/


Limit of square root function at $x \to 6$

Question: I'm trying to find the limit of the following function at $x \to 6$:
$$\frac{x^2-36}{\sqrt{x^2-12x+36}}$$
i've simplified it so that it becomes $\dfrac{(x+6)(x-6)}{\sqrt{(x-6)^2}}$, which simplifies to $x+6$.
the problem is that i shouldn't be getting to $x+6$, because then id be able to plug in $6$, and say that the limit exists for the left hand side and the right hand side of $6$, when clearly i can tell from the graph that the limit does not exist.
What am I doing wrong?
Comment: The function is
$$f(x)=\frac{x^2-36}{\sqrt{x^2-12x+36}},$$
which is not defined for $x=6$.

When you simplify you have to take that into account, apart from $\sqrt{a^2}=|a|.$
Comment: right, but what i dont get is how to get to the two different left hand and right hand limits (they're apparently -12 and 12, i just can't see why!)
Answer: Hint:  That's because $\sqrt{(x-6)^2}$ doesn't simplify to $x-6$ but to $|x-6|$ which is very different since: $$|x-6|=\begin{cases}x-6, & x\geqslant6\\ -(x-6),&x\leqslant6\end{cases}.$$ So when you will compute the limit from the right and that from the left you'll get different results because of the difference in the sign engendered by $|x-6|$.
Comment: even though i gave stefanos the answer, your post really helped me. i'd vote it up, but i dont have the rep!
Comment: @theboythatcould That's not a problem, the important thing is that it helped you! :-)
Answer: Hint: $$\sqrt{(x-6)^2}=|x-6|$$ which is in turn equal to $$|x-6|=\begin{cases}-(x-6)=-x+6, & x<6\\ \phantom{+}(x-6)=\phantom{-}x-6,&x>6\end{cases}$$ This implies that $$\lim_{x\to6^-}\dfrac{(x+6)(x-6)}{\sqrt{(x-6)^2}}=\lim_{x\to6^-}\dfrac{(x+6)(x-6)}{-(x-6)}=\lim_{x\to6^-}-(x+6)$$ but $$\lim_{x\to6^+}\dfrac{(x+6)(x-6)}{\sqrt{(x-6)^2}}=\lim_{x\to6^+}\dfrac{(x+6)(x-6)}{(x-6)}=\lim_{x\to6^+}\phantom{+}(x+6)$$
Comment: right, so then i would get ((x+6)(x-6))/(|x-6|), how exactly do i calculate the limit of that? thanks again for the quick response
Comment: your explanation is great, but i don't get why we can just ignore the positive sign for the left hand limit, and ignore the negative sign when calculating the right hand limit. in my mind, i keep making two separate cases for both lhl and the rhl.
Comment: Sorry, I don't understand your question. We did not ignore any sign, can you explain what you mean?
Comment: like, why don't we have two different cases when calculating for the left hand limit (one for the negative sign in front of the denominator, and another for the positive sign), and then do the same for the calculation of the right hand side limit..? this is all after you remove the square root
Comment: Oh, ok. Because for the LHL you have that x<6 (since x approaches 6 from below) so you have only the negative sign. Then for the RHL x approaches 6 from above, so you have the case x>6 with the positive sign. Is it clear now?


How to open a link without page refresh

Question: I have been observing that whenever I click a link in phpMyAdmin it opens the respective link without refreshing the page. I have searched on the internet but I don't get a proper solution. If anyone knows the way to do it, please tell me. I don't want answers like: document.write() or document.open. They don't work as I expect. Thanks in advance for help!
Comment: What you're referring to is called a **Single Page Application**. JavaScript Frameworks and Libraries like *Angular* and *React* are responsible for such applications.

Search on how you can achieve the same in PHP
Comment: Ok Thanks! I will search on that.
Answer: What do you want to refresh without reloading the whole page? If you want to make such a single-page web application, there is a technique called Ajax. You can refer to it by going through this link. Thank You!
Comment: What I want is to change the whole page's content. I don't want to change the contents partially.
Answer: Answering my own question
To achieve what I have asked in the question, you need to use Single Page Application frameworks. Using single page application, we can navigate between pages of the same site without letting the page reload all its contents. You can use any of the Single Page Application frameworks like React, Next.JS (recommended), Angular, Vue.JS etc.
Comment: Since this was suggested to you in a comment several years ago, it's best to reply to the comment and ask the user if they would like to answer it.

How to open a link without page refresh


What are the first three chords from the "Wind Cries Mary" called?

Question:

Those first three chords in the intro. I can always tell when improv people use them and I have not heard them in other songs. What are they called and what is the theory behind them?
Comment: I didn't downvote but I do find the question confusing. A) they are not unusual chords so you are definitely hearing them in other songs whether you know it or not. B) what exactly are you asking for? The name of the chords? Did you find sheet music for it and the chord spellings didn't make sense or could you not find any music at all or did you not even try to find the music?
Comment: People who downvote and don't leave a comment are not helping. I do think this is a interesting enough chord question.
Comment: Technical point: not hearing them in any other songs does not allow us to conclude that they don't appear in any other songs. Have you looked for tab or sheet music and found none?
Comment: Ok, I may have overestimated how interesting these chords were, they did sound unique to me.
Answer: It is Eb>E>F, although it probably is D>Eb>E on Jimi's guitar, as he often tunes a semitone lower than concert.Having said that, the lowest note (root, later on) sounds open, which means he may well have tuned UP a semitone for this one.Think the first three are 'power chords', with no 3. The next part is similar, but with a resolved sus 2 on each.
It's not that common, but I've used it in improv a few times in other stuff.
It's what's called chromatic, and is very basic.It involves the use of a borrowed chord from the parallel minor, up a semitone to become an unusual leading tone, not really, but with every note a semitone away from resolving to the root, it might as well be!
Comment: Shows you how much mystique there is about the man. He can just take chromaticisms and you have your head blown away thinking it is the weirdest jazz chords you have ever heard.
Comment: If he tunes his guitar a semitone *down*, then sounding pitch is lower than played pitch, so he plays E F F#. Which makes sense (lowest note being E).
Comment: @RosieF - what I meant is the low open string I hear on a I chord is representing where he played it. The chromatic intro doesn't use an open string for the 1st chord, it comes in an octave higher, and later there's the open bottom string for the root, 5 or 6 bars in. A more intriguing question could be - what was Jimi's guitar tuned to? But that is out of the site's remit.
Answer: Going by ear it sounds like Eb major - E major - F major.
Correct me if I'm wrong the song might be in Eb major. The F major is a lydian borrow and the E major is a passing chord.
Comment: You are wrong, I'm afraid! The key of the song is definitely F major.
Comment: The key is concert F major, but that has no direct relationship unless we know exactly how Jimi's guitar was tuned.
Answer: The other answers give what a "normal guitarist" would traditionally describe them as, but they are a shorthand for...I don't know the specific names, possibly xAdd4.
Basically there are two sets of 3 "walk-ups". The first form is where you barre all 6, and then place a finger +2 frets from the barre on the D string. You want to strum at least the top 3 strings (E,A,D strings). This is what people call the "Eb-E-F"
The second set of three is where you barre all 6, and then hammer-on at +2 frets on the A string for each of the three. You want to skip the low E string on the strum and strum at least the A,D,G strings
Here is a video that shows how to play the outro as Jimi played it at Monterey: note that the person in the video is referring to the abbreviated names of the chords:

Jimi seems to favor a mix of C-ish and A-ish forms played as if he is playing slide guitar, but even when you "know" how to play his songs, when you look at his handwork, it is still somewhat confusing.
Comment: "the chorderator" website suggests these two chord forms are, at least at the ninth fret: {C#madd4, F#7sus2/C#, E6no5add2/C#} and {C#madd4, F#7sus2/C#, E6no5add2/C#}
Comment: That shows you the pure brilliance of the man (Jimi that is.)
Comment: oops, I pasted the same chord list for both! Anyway, the guy in the video does a good job of it, but the thing about Jimi, for me, isn't his genius or even his showmanship, but his completely relaxed way he does all this stuff. In most movies, they focus on Jimi's face (unfortunately for people who want to see the chords), but while he sings, the music is going over the place and he never looks and never struggles and you forget he is also playing the lead and rhythm.
Comment: E A and D are usually referred to as the bottom strings - lower in pitch.
Comment: which is why I qualified it. As a self-taught person, I usually think of the high e as lower, since it is closer to the ground. Also, see the video, low e is at the top. I don't have a problem with the other description of course. I am fully aware that people tend to use other ways to describe it, but I personally know people who describe it the same way as me. See also "inverted Y-axis"


CONSTRAINT que adiciona parametro à FOREIGN KEY?

Question: Tenho o seguinte código para a criação de tabelas:
CREATE TABLE pessoa (
cod_pessoa int NOT NULL IDENTITY PRIMARY KEY,
nm_pessoa varchar (50) NOT NULL,
tp_pessoa char(1) NOT NULL,
endereco_pessoa varchar(50) NOT NULL,
CONSTRAINT pessoa_tipo CHECK (tp_pessoa = 'F' or tp_pessoa = 'J')
);

CREATE TABLE pessoa_fisica (
cod_pessoaf int NOT NULL PRIMARY KEY,
cpf int NOT NULL UNIQUE,
FOREIGN KEY(cod_pessoaf) REFERENCES pessoa(cod_pessoa)
);

CREATE TABLE pessoa_juridica (
cod_pessoaj int NOT NULL PRIMARY KEY,
cnpj int NOT NULL UNIQUE,
FOREIGN KEY(cod_pessoaj) REFERENCES pessoa(cod_pessoa)
);

O meu problema esta nas tabelas pessoa_fisica e pessoa_juridica. Como puderam ver a tabela pessoa tem um campo que indica seu tipo tp_pessoa (F para física e J para jurídica), gostaria de adicionar uma CONSTRAINT ou algo do tipo nas tabelas pessoa_fisica e pessoa_juridica que delimite as foreign keys somente para o tipo correto de pessoa. Ex (código entre **):
CREATE TABLE pessoa_fisica (
cod_pessoaf int NOT NULL PRIMARY KEY,
cpf int NOT NULL UNIQUE,
FOREIGN KEY(cod_pessoaf) REFERENCES pessoa(cod_pessoa) **WHERE pessoa.tp_pessoa = 'F'**
);

Tem como fazer isso?
Comment: Uma `CHECK CONSTRAINT` seria suficiente?
Comment: @GuilhermePortela Até poderia mas como ela deve ser criada? Não tenho como usar uma subquery dentro de uma constraint, tenho? Ou referenciar colunas de outras tabelas? Acho que deve ser algo na própria constraint foreign key ou um check aplicado a ela, mas como?
Comment: @MarianaSempe Não sei se estas tabelas são apenas para exemplificar a necessidade. Em sendo uma necessidade real, eu resolveria com outra modelagem que dispensasse esse tipo de constraint.
Comment: @Caffé essa é a necessidade real! Como você sugere?
Comment: @MarianaSempe Considerando só estes campos, você pode simplesmente sumir com as tabelas `pessoa_fisica` e `pessoa_juridica` e adicionar um campo `cpf_cnpj` em `pessoa`; seria o correto porque CPF e CNPJ são de fato o mesmo tipo de informação (identificação única nacional de uma pessoa). Se os demais campos destas duas tabelas forem `rg` e `inscricao_estadual`, ainda não justifica a complexidade das novas tabelas. Veja que algumas empresas são isentas de inscr.estadual e algumas pessoas usam outra identificação que não RG; estes docs são apenas atributos e não parte da identidade de uma pessoa.
Comment: @MarianaSempe Se houver muito mais campos exclusivos para `pessoa_fisica` ou `pessoa_juridica`, informe na sua pergunta que ajudará a sugerir uma modelagem.
Comment: @Caffé poderiam ter vários (este é um trabalho), o problema é que preciso mostrar normalização (aqui a 2FN) por isso das duas tabelas. Coloquei somente cpf/cnpj para simplificar o cadastro depois.
Comment: @MarianaSempe Entendo... Resolver um problema que de fato não existe é mais difícil. É difícil normalizar pessoa porque ela é muito simples. Talvez você possa escolher uma entidade mais fácil de normalizar, e o mais fácil para exercitar normalização é com entidades complexas. Um "cliente", por exemplo, poderia ter categoria, tipo de relacionamento, % permitido de comprometimento de renda... E alguns destes atributos podem estar relacionados de modo a dar origem a novas tabelas, facilitando a demonstração da normalização.
Answer: Como não sei a estrutura da sua aplicação e não sei as permissões de banco de dados e quem vai ter acesso, para fazer o que você precisa eu faria assim:
Function para a constraint
CREATE FUNCTION dbo.ValidaPessoa (@id integer, @tipo varchar(1))
RETURNS int
AS
BEGIN
  DECLARE @retorno int;
  select @retorno = count(*) from pessoa where cod_pessoa = @id and tp_pessoa = @tipo;
  RETURN(@retorno);
end;

Constraint
alter table pessoa_fisica add constraint pessoa_fisica_ck check (dbo.ValidaPessoa(cod_pessoaf, 'F') = 1)

alter table pessoa_juridica add constraint pessoa_fisica_ck check (dbo.ValidaPessoa(cod_pessoaj, 'J') = 1)

Explicação
Ao tentar salvar o registro, o sistema irá pegar o valor de cod_pessoaj e/ou cod_pessoafe vai chamar a função criada, fazendo o SQL e retornando o erro se não estiver com o cadastro certo.
Desta forma você consegue garantir que insert diretos no banco de dados, também sejam validados. Na minha opinião a store procedure, somente aumenta a complexidade de algo simples e pode ser burlada facilmente.
Comment: +1 O bacana desta solução é que mantém simétrica a inserção de registros em vez de inserirmos ora por *INSERT* em algumas tabelas e ora por *stored procedure* em outras. Eu só não acho que seja mais difícil de burlar do que a Stored Procedure. E onde você foi buscar esse nome *ValidaUsuario*? :D
Comment: @Caffé Agora que vi que fumei legal escrevendo ValidaUsuario. Editado.
Answer: Existe uma maneira usando chave estrangeira, mas nesta resposta explico porque isso não é uma boa ideia.
O correto, como dito na mesma resposta, é você impedir manipulação direta dos dados pelos usuários do banco, e criar Stored Procedures que façam essa conferência pra você.
Há, ainda, uma alternativa usando Triggers, mas por experiência não recomendo por causa dos falsos positivos (principalmente envolvendo vários registros inseridos ou atualizados ao mesmo tempo) e pelo desempenho, que cai muito.
Na prática:
Create PROCEDURE dbo.InserirPessoaFisica
 @CodPessoa INT,
 @Cpf INT
AS
BEGIN

 INSERT INTO pessoa_fisica (cod_pessoaf, cpf)
 SELECT p.cod_pessoa, @Cpf
 FROM pessoa p
 WHERE p.cod_pessoa = @CodPessoa
 AND p.tp_pessoa = 'F'

END
GO

Create PROCEDURE dbo.AtualizarPessoaFisica
 @CodPessoa INT,
 @Cpf INT
AS
BEGIN

 UPDATE pessoa_fisica
 SET cpf = @Cpf
 FROM pessoa p
 WHERE p.cod_pessoa = @CodPessoa
 AND p.cod_pessoa = pessoa_fisica.cod_pessoaf
 AND p.tp_pessoa = 'F'

END
GO


How to make two cards the same height

Question: How can I make two cards for Black African Players and for White Players the same height All those cards is using the same class is there perhaps a way to make it the same height

div.card {
    overflow: hidden;
}

.card {
    width: 100%;
    padding: 9px 20px 9px 20px;
    margin-bottom: 0px;
    background: #ffffff;
    box-shadow: 1px 1px 1px #dfdfdf;
    box-sizing: border-box;
    height: 100% !important;

Comment: What is a `.card`? Where is the HTML?
Comment: You can use flexbox, the shortest will take the height of the tallest and everything will stretch out evenly. https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Comment: those are tables inside a div, right?
Answer: Flexbox comes in handy here. Notice how the last element (with three
's is taller than the other two, yet they are all the same height:

* { box-sizing: border-box; }

.container {
  display: flex;
  flex-flow: row wrap;
}

.card-wrap {
  flex: 0 0 33.333%;
  display: flex;
  padding: 10px; /* gutter width */
}

.card {
  box-shadow: 0 0 4px rgba(0,0,0,0.4);
  flex: 0 0 100%;
}

Comment: this answer saved a lot of my time. thanks.
Answer:

.container {
  width: 100%;/*whatever size you want your container*/
  border: 3px solid teal;
  display: flex; /*Make sure to call this on your container*/
  align-items: stretch; /*stretches all cards same height*/
  justify-content: space-around; /*some space between cards*/
}

.card {
  width: 150px; /*or whatever size card you want*/
  border: 2px solid red;
}

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

This is what worked best for me,
I set display: flex on the container of the cards (not the card itself)
It is flex-direction: row by default when you say display: flex
and then simply added align-items: stretch on the container as well...
This caused my cards to have an equal height.
(This solution works only when your flex-direction is set to row)
Hope this helps
Comment: Since it's old question and the other answers weren't that bad, if you feel answering you should add code snippet to show your solution..
Comment: Sure, if you would like to see an example, I will edit my answer to add a snippet.
Answer: If they are in the same row then you can use display:flex;flex-direction:row; on that row but if they are not in the same row, you can do it with jQuery. the snippet below will make every div with class="card" of same height
$(document).ready(function (){
  var maxHeight = 0;
  for(i=0;i<$(".card").length;i++){
    if($(".card").eq(i)){
      var currentHeight = $(".card").eq(i).height();
      if(currentHeight>=maxHeight){
        maxHeight = currentHeight;
      }
    }
    else{
      break;
    }
  }
  $(".card").height(maxHeight);
});

Comment: best way is to use `flex:row;` but if they are not in the same row that wont work
Comment: Did it solve your problem . If yes then can you please select an answer for this problem
Comment: This is probably the quickest solution.
Answer:
use flex-grow: 1 for element whose height should expand inside container to account for available space

height: -webkit-fill-available to overall container

margin-top: auto can be used to automatically use extra margin to push last element at the bottom

an example of CSS below
{
        display: 'flex',
        flexDirection: 'column',
        position: 'relative',
        '.image': {
            width: fluid ? '100%' : '300px',
            height: '300px',
            objectFit: 'cover',
        },
        '.content': {
            display: 'flex',
            width: fluid ? '100%' : '300px',
            flexDirection: 'column',
            flexGrow: 1, // <--- content can expand to fill available space
        },
        '.cta': {
            marginTop: 'auto', //<-- so that button is at the bottom of card
            ...textVariantCssModification,
        },

How to make two cards the same height


Solving limits that approach infinity

Question: Solve limit:
$$\lim_{k\to\infty}\frac{4k+3}{2}$$
My approach.
$$\lim_{k\to\infty}\frac{(4k+3)}{2} \frac{1/k}{1/k}$$
$$\lim_{k\to\infty}\frac{4+3/k}{2/k}$$
Then, we know that the limit of k as k approaches inf for $$\frac{3}{k}$$ goes to 0 and the same goes for $$\frac{2}{k}$$ however for both limits, they can also be viewed as infinitesmall such that the final answer is $$\frac{4}{0+} = \infty$$
Can somebody verify if I did this correctly? I'm confused as to whether the fraction limits approach 0 or infinitesmall because if it's 0 then my limit is undefined
Comment: You have limits for $n$, but the arguments are in terms of $k$.
Comment: Sry I fixed it to be variable k.
Comment: Isn't it obvious from the beginning that $4k+3\to\infty$ as $k\to\infty?$
Comment: True... I actually didn't have to do anything. But for curiosity's sake can you help me with my understanding for the fraction limits?
Comment: You did this correctly (as in you are using heuristics which can be made rigorous). You should dispense of your worries with the limit begin undefined; the limit must be infinite, since $(4k+3)/2$ becomes arbitrarily large as $k$ does.
Comment: @DonaldDevy Please recall that if the OP is solved you can evaluate to accept an answer among the given, more details here https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Answer: Simply note that
$$\frac{4k+3}{2}=2k+\frac32\ge 2k \ge k \to \infty$$
then conclude by squeeze theorem.
Answer: Why so complicated?
$$\lim_{k\to\infty}\frac{4k+3}{2}=\lim_{k\to\infty}(2k+1.5)=2\infty+1.5=\infty$$
Comment: While right in spirit, treating $\infty$ as a number gives me the willies.
Comment: As long as you don't do things like $\infty/\infty$ or $\infty\cdot 0$ or $\infty-\infty$, you should be fine. It will boil down to the answer form @gimusi
Answer: Can't you find $k$ such that $$\frac{4k+3}2>1000000\ ?$$
And larger numbers ?
If yes, the expression is unbounded.

Solving limits that approach infinity


Is $E[1_A | \mathscr{F_t}] = 0 ~\text{or} ~ 1 \ \Rightarrow E[1_A | \mathscr{F_{s}}] = E[1_A | \mathscr{F_t}]$ is only almost surely?

Question: Spin-off from my previous question: Prove/Disprove $E[1_A | \mathscr{F_t}] = 0 ~\text{or} ~ 1 \ \Rightarrow E[1_A | \mathscr{F_{s}}] = E[1_A | \mathscr{F_t}]$
Apparently the conclusion holds true almost surely. Is it really only almost surely? What is an example of a filtered probability space and event $A$ s.t.
$\exists t \in \mathbb N$ s.t. $P(P(A|\mathscr F_t) = 0) = 1$ or $P(P(A|\mathscr F_t) = 1) = 1$
but
$\exists \omega \in \Omega$ s.t. $P(A|\mathscr F_t)(\omega) \ne P(A|\mathscr F_s)(\omega)$ for some $s > t$?
Comment: Conditional expectations are only unique up to null-sets, so, of course, we can only hope that the equality holds almost surely.
Answer: I'm not sure if this is what you need, but I will try to give a constructive example where your conditions hold true.
Consider $U_t$~ $DiscreteUniform\{0,1\}$ for $ k \geq t \geq 0, t \neq k$ and $U_t = 2$ for $t > k$. Define $Z_t = 1_{\{U_t = 2\}}$. Define filtration $\mathbb{F_t} = \sigma\{U_m:t \leq m\leq 0\}$.
Clearly, $P(P(Z_t| \mathbb{F_{t-1}}) = 2) = 0$ for $t<k$. Choose $s = k+1$ - now $P(P(Z_s| \mathbb{F_{s-1}}) = 2) = 1 \neq 0$. Hence, it suffices to choose $\omega = \{2\}$ and $A_t = \{U_t = \omega\}$ to see that $P(A_t|F_{t-1})(\omega) \neq P(A_s|F_{t-1})(\omega)$.
This answers your question if and only if $A$ can be time-dependent, which it usually should be (since one of your tags is 'filter').
Comment: Filter can refer to filtration? Or not?
Comment: @BCLC Yep, but also to something else (e.g., Kalman Filter). Does the answer help you?
Comment: Lol forgot all about this. Well...should it be $Z_t = \{U_t = 2\}$? Not sure what it means to say $P(Z_t | F) = 2$ if $Z_t$ is a random variable


Do the parameters that arise in de Finetti`s representation theorem follow the rules of probability?

Question: I recently stumbled upon de Finetti`s (pretty cool) representation theorem (What is so cool about de Finetti's representation theorem?). I wondered whether the RV $\Theta$ that arises in this context follows the rules of the probability calculus. Or framed differently: I am pretty sure that it does and I am looking for a reference where I can look up this topic.
An example for what I have in mind: if we have an exchangeable sequence of throws with a die, we can create the following (exchangeble sequences):
$$X:=(X_1,X_2,  ...): (\Omega,A)\to \in ({\{0,1\}^\infty}, 2^{\{0,1\}^\infty})$$, where $X_i(\omega)= 1$ if the outcome is even and $X_i(\omega)=0 $ otherwise.
Furthermore we could define
$$Y:=(Y_1, Y_2, ...): (\Omega,A)\to ({\{0,1\}^\infty}, 2^{\{0,1\}^\infty})$$
where $Y_i(\omega)=1$ if the outcome is 3, and $Y_i(\omega)=0$ otherwise.
Now we could form the new sequence:
$$Z:=(Z_1, Z_2, ...):=(Y_{\phi(1)}, Y_{\phi(2)}, ...)$$ where $\phi(n)$ indicates whether the $n$th die-throw was uneven.
Now it seems to me that it should hold that  $\Theta_Z=\frac{\Theta_Y}{\Theta_X} \quad a.s.$
Now as I already said I am looking for a reference that covers the relationship between this parameter that arises in Bayesian exchangeability modelling and the rules of the probability calculus
Answer: Infinite additivity:
Let $(X_{i,k})_{i=1...\infty}$, $k=1...\infty$ be Random Variables, where $X_{i,k}=1$ if the event $E_k$ happens at the i-th toss (0 otherwise) and we assume that $E_k \cap E_j = \emptyset \quad  k \neq j $. Furthermore let all $(X_{i,k})_{i=1...\infty} $and $(Z_i)_{i=1...\infty}=(\sum_{k=1}^\infty X_{i,k})_{i=1...\infty}$ be infinitely exchangeable. Therefore $Z_i$ indicates whether one of the events E happens (as they are mutually exclusive)
We know by De Finetti`s law of large numbers that for every set of infinitely exchangeable Random Variables that our beliefs about the outcomes can be represented via our beliefs about the limiting relative frequency. Where I denote the parameter for the sequence $(X_{i,k})_{i=1... \infty}$ with $\Theta_k$ and the parameter for $(Z_i)_{i=1...\infty}=(\sum_{k=1}^\infty X_{i,k})_{i=1...\infty}$ with $\Theta_Z$, What I want to show is that
$$\Theta_Z= \sum_{k=1}^\infty \Theta_k$$
By De Finetti's law of large numbers we know that all exchangeable sequences converge towards their parameter with probability 1:
$$P( \lim_{n \to \infty} 1/n \sum_{i=1}^n X_{i,k})=\Theta_k \quad a.s. $$ $\forall k =1...\infty$ and $$P( \lim_{n \to \infty} 1/n \sum_{i=1}^n \sum_{k=1}^\infty X_{i,k})=\Theta_k \quad a.s.$$. As the events are disjoint we know that the Random variable $Z_i=(\sum_{k=1}^\infty X_{i,k})$ indicates that one of these events $E_K$ happens at the $i-th$ trial.
Therefore we have that  $$\lim_{n \to \infty} \frac{1}{n} \sum_{i=1}^n \sum_{k=1}^K X_{i,k}=\lim_{n \to \infty}  \sum_{k=1}^K \frac{1}{n} \sum_{i=1}^n X_{i,k} =
 \sum_{k=1}^K \lim_{n \to \infty}\frac{1}{n} \sum_{i=1}^n X_{i,k} = \sum_{k=1}^K\Theta_k \quad \forall K \in \mathbb{N}$$ and therefore
letting $K \to \infty $ we obtain that $\Theta_Z = \sum_{k=1}^\infty \Theta_k \quad a.s.$
Conditional Probability:
Assumptions: $(X_i)_{i \in \mathbb{N}}, (Y_i)_{i \in \mathbb{N}}, (X_iY_i)_{i=1...\infty}$ are infinitely exchangeable and $P(\sum_{i=1}^\infty Y_i<\infty)=0$.
By De Finetti`s representation theorem we can express our beliefs about the oucomes via our beliefs about the limiting relative frequency, I denote with $\Theta_{X}, \Theta_{Y} ,\Theta_{XY}$ the respective Parameters.
Now we define $$Z:(\Omega, A)\to (\mathscr{M}, 2^{\mathscr{M}}), \quad Z(\omega)=(X_{\phi_2(\omega)}(\omega), X_{\phi_2(\omega)}(\omega), ...) $$
where $\mathscr{M}=\{\{0,1\}^n|n=1...\infty\}$ and $\phi_k(\omega) =n$ if $Y_n(\omega)=1, \sum_{i=n}^NY_n(\omega)=k$ .Note that $Z(\omega)$ can also be finitely dimensional if one obtains only a finite number of successes.
We  can apply De Finetti's representation theorem again and obtain:
the parameter $\Theta_Z$, such that $$P((Z_1, ..., Z_n)=(z_1, ..., z_n))= \int_\Omega \Pi_{i=1}^n \theta^{z_i}(1-\theta)^{1-z_i}dP(\Theta_Z)$$
What we want show is that: $\Theta_Z= \frac{\Theta_{XY}}{\Theta_{Y}}$.
This follows again from De Finetti's law of large numbers, as
$$\Theta_Z= \lim_{n \to \infty}\frac{\sum_{i=1}^nX_i(\omega)Y_i(\omega)}{\sum_{i=1}^nY_i({\omega)}} =\frac{\lim_{n \to \infty}1/n\sum_{i=1}^nX_i(\omega)Y_i(\omega)}{\lim_{n \to \infty}1/n\sum_{i=1}^nY_i({\omega)}}= \frac{\Theta_{Y X}}{\Theta_{Y}} \quad a.s.$$
Note that $\Theta_Y\neq0 \quad a.s.$ as I assumed that $P(\sum_{i=1}^\infty Y_i<\infty)=0$.


Quantity of an object after proliferation

Question: A small creature called "Charza" lives in blocks of an infinite square. An infinite number of them can live in a block. After one hour , one Charza is divided into 4 Charzas and each one moves into one of the adjacent blocks. we have only one Charza at the first . after 6 hours , how many Charzas will be in a block which has only one common vertex with the first block? ( for example , after one hour , there will be one Charza in each adjacent block )
Answer: Impose a coordinate system that makes the originally occupied cell $\langle 0,0\rangle$. Let $c(m,n,t)$ be the number of Charzas in cell $\langle m,n\rangle$ at time $t$ hours; clearly $c(0,0,0)=1$, $c(m,n,0)=0$ for $\langle m,n\rangle\ne\langle 0,0\rangle$, and the recurrence is
$$c(m,n,t+1)=c(m-1,n,t)+c(m+1,n,t)+c(m,n-1,t)+c(m,n+1,t)\;.$$
It's not hard to see that $c(m,n,t)=c(|m|,|n|,t)$ for all $m,n,t\in\Bbb Z$.
A little numerical experimentation suggests that if we set
$$d(m,n,t)=\frac{t-(|m|+|n|)}2$$
for $m,n\in\Bbb Z$ and $t\in\Bbb N$, then
$$c(m,n,t)=\begin{cases}
\binom{t}{d(m,n,t)}\binom{t}{m+d(m,n,t)},&\text{if }|m|+|n|\equiv t\pmod 2\\\\
0,&\text{otherwise}\;.\end{cases}\tag{1}$$
Clearly $(1)$ satisfies the initial conditions on $c$, so it only remains to show that it satisfies the recurrence. Suppose that $m,n\ge 0$ and $m+n\equiv t+1\pmod2$. Then
$$\begin{align*}
\binom{t+1}{d(m,n,t+1)}&=\binom{t+1}{\frac12(t+1-m-n)}\\\\
&=\binom{t}{\frac12(t-1-m-n)}+\binom{t}{\frac12(t+1-m-n)}
\end{align*}$$
and
$$\begin{align*}
\binom{t+1}{m+d(m,n,t+1)}&=\binom{t+1}{m+\frac12(t+1-m-n)}\\\\
&=\binom{t}{m+\frac12(t-1-m-n)}+\binom{t}{m+\frac12(t+1-m-n)}\;,
\end{align*}$$
so
$$\begin{align*}
&c(m,n,t+1)=\\\\
&\binom{t}{\frac12(t-1-m-n)}\binom{t}{m+\frac12(t-1-m-n)}+\\\\
&\qquad\binom{t}{\frac12(t-1-m-n)}\binom{t}{m+\frac12(t+1-m-n)}+\\\\
&\qquad\binom{t}{\frac12(t+1-m-n)}\binom{t}{m+\frac12(t-1-m-n)}+\\\\
&\qquad\binom{t}{\frac12(t+1-m-n)}\binom{t}{m+\frac12(t+1-m-n)}=\\\\
&\\\\
&\binom{t}{d(m,n+1,t)}\binom{t}{m+d(m,n+1,t)}+\\\\
&\qquad\binom{t}{d(m+1,n,t}\binom{t}{m+1+d(m+1,n,t)}+\\\\
&\qquad\binom{t}{d(m-1,n,t)}\binom{t}{m-1+d(m-1,n,t)}+\\\\
&\qquad\binom{t}{d(m,n-1,t)}\binom{t}{m+d(m,n-1,t)}=\\\\
&\\\\
&c(m,n+1,t)+c(m+1,n,t)+c(m-1,n,t)+c(m,n-1,t)\;,
\end{align*}$$
as desired.
Added: The specific number desired is
$$c(1,1,6)=\binom62\binom63=15\cdot20=300\;.$$
Comment: +1 .brilliant . but I think it has an easier solution.
Comment: @amatr can you show your easier solution?
Comment: @DonAnselmo my answer is 300 . I will write the solution after finding some additional data which I need to write it.
Comment: @amatr: I was more interested in finding the general solution than in specifically finding $c(1,1,6)$.
Comment: @BrianM.Scott yes , I think everybody who loves math , thinks like that ! thank you anyway.
Answer: sorry , I was very busy .
My solution : after n hours ,we write the number of walks from center to a block . so we should count the number of walks from $(0.0)$ to $(1,1)$ and this is equivalent to counting the number of sequences of length 6 , consisted of elements called U , R , D , L _( R = L + 1 ) , ( U = D + 1 ) and the sum of these elements should be 6 . so we have 3 situations:
$$ U = 3 , D = 2 , R = 1 , L = 0 $$
$$ U = 2 , D = 1 , R = 2 , L = 1 $$
$$ U = 0 , D = 1 , R = 3 , L = 2 $$
so $\frac{6!}{0!1!2!3!} + \frac{6!}{1!2!1!2!} + \frac{6!}{2!3!1!0!} = 60 + 180 + 60 = 300$


Can I use Visual Studio 2010 without breaking my 2008 apps?

Question: Now Visual Studio 2010 is out can I use Visual Studio 2010 without breaking my 2008 apps? Can I still compile to .Net 2.0 etc?
Thanks
Steven
Answer: Yes, you can still target framework 2.0 in VS2010. And you can also run VS2008 alongside VS2010.
Answer: Basically, yes, but there are a few things that get changed, for instance:

Testing projects always get converted to .NET 4.0
Project files get stored in "VS 2010" format.

So downgrading back to VS 2008 is not directly possible (in 99% of all cases it's still not a problem by hand-editing the files, takes just a few seconds).
However, usually, this is not an issue though. Your deployment capabilities are not limited by that. You can still target any framework.
Additionally, I found that running VS 2008 alongside 2010 made no problems at all. Including 2008 projects in a 2010 solution works fine and does not change the project file. It's very easy to slowly transmit to the new version step-by-step.
Comment: +1 for pointing out VS2010 saves projects in its own format. While code and targeted framework don't break, project files can (and can generally be fixed as you mentioned).


Decrypting an AES256-rijdeal encrypted file with initialization vector

Question: I've got a tricky situation at the moment.
I need to create an android method that will decrypt an encrypted file that has been encrypted like this:

AES256 (Rijndael)
Cipher-Block-Chaining (CBC) using an initialization vector of 16 bytes that look like:

{ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 122, 100 }
I also know the encryption key to the file, but for now let's say it's: "Boat"
I've been searching around on Google but I could not find a online that used this combination of encryption. Some involved the Rijndael algorithm but didn't let me choose an initialization vector, while others did not support AES256 at all.
Can someone point me into the right direction where to find an example or post some sample code that does the above?
N.B. I don't know if it's important to mention but the output file is always .pdf
Answer: This is a very standard configuration, hard to believe you didn't find any samples. All you need to do is create an IvParameterSpec from your IV bytes and initialize the Cipher with it. Something like this:
SecretKey key = getEncryptionKey();
byte[] iv = new byte[] { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, (byte)144, (byte)233, 122, 100 };
byte[] cipherBytes = readEncryptedFile();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, key, ivParams);
byte[] plaintext = cipher.doFinal(cipherBytes);

BTW, 'Rijndael' is the same as AES, so you'd get better results if you just search for 'AES'.
Comment: Thanks, but how can I fill `key` with my own key?
Comment: OK, getting there. What sort string format? Hexadecimal? Base64 encoded? Not actually a key, but a password? Replace characters and post a sample if you are not sure.
Comment: It looks like this: `$0rEoS5uAkNk5ovovVWPXsW2buwUy0TU` As far as I know this is not encoded at all. This IS the encryption key.
Comment: If it is a string, it mean is is encoded. A key is a sequence of bytes. You have to check with whoever produced this key about the actual format. If you assume that each character is a byte (unlikely, unless you have a really weak key), you can convert to a `SecretKey` like this: `SecretKey = new SecretKeySpec("$0rEoS5uAkNk5ovovVWPXsW2buwUy0TU".getBytes("ASCII"));`
Comment: Ahh I get it now, I didn't realize I had to create the `SecretKey` using `SecretKeySpec`. Thanks for your help!
Comment: Buggers the mind. First choose AES-256 encryption, and then more than half the key size by allowing ASCII characters only. Keys should be specified in bytes, and *if* they are needed as String, hex or base64 encode them.
Comment: @owlstead Sad but true. If it were only this one case... Some people even pad the string with zeros if it's shorter than the 128/256 bits needed.


How to assign "Access Results" permission per Webform?

Question: On Drupal 7, my client would like to give a user to see a particular Webform's "Access Results". How can I assign the "Access Results" permission per Webform, beside using "Permissions per Webform"?
Answer: Sounds like you need Permissions per Webform module
You can set permissions per Webform as it suggests. Under the form settings.
Comment: Does this also set Webform View Permission? How to set those?
Answer: Try Webform access granular module.  This allow you to specify a specific user(s) per webform.


GraphDB Free 8.3: generate war files

Question: Is it still possible to generate war files in version 8.3 of graphDB?
I didn't find the generate-war-files file in my distribution.
Thank you.
Answer: The support for war files was dropped officially in version 8.0, due to various deployment, logging and exception handling issues. GraphDB uses an embedded Tomcat which handles all the work.

GraphDB Free 8.3: generate war files


How To Write To A OneNote 2013 Page Using C# and The OneNote Interop

Question: I have seen many articles about this but all of them are either incomplete or do not answer my question.  Using C# and the OneNote Interop, I would like to simply write text to an existing OneNote 2013 Page.  Currently I have a OneNote Notebook, with a Section titled "Sample_Section" and a Page called "MyPage".
I need to be able to use C# code to write text to this Page, but I cannot figure out how or find any resources to do so.  I have looked at all of the code examples on the web and none answer this simple question or are able to do this.  Also many of the code examples are outdated and break when attempting to run them.
I used the Microsoft code sample that shows how to change the name of a Section but I cannot find any code to write text to a Page.  There is no simple way to do this that I can see. I have taken a lot of time to research this and view the different examples online but none are able to help.
I have already viewed the MSDN articles on the OneNote Interop as well.  I vaguely understand how the OneNote Interop works through XML but any extra help understanding that would also be appreciated.  Most importantly I would really appreciate a code example that demonstrates how to write text to a OneNote 2013 Notebook Page.
I have tried using this Stack Overflow answer:
Creating new One Note 2010 page from C#
However, there are 2 things about this solution that do not answer my question:
1)  The marked solution shows how to create a new page, not how to write text to it or how to populate the page with any information.
2)  When I try to run the code that is marked as the solution, I get an error at the following line:
var node = doc.Descendants(ns + nodeName).Where(n => n.Attribute("name").Value == objectName).FirstOrDefault();
return node.Attribute("ID").Value;

The reason being that the value of "node" is null, any help would be greatly appreciated.
Answer: I asked the same question on MSDN forums and was given this great answer.   Below is a nice, clean example of how to write to OneNote using C# and the OneNote interop.  I hope that this can help people in the future.
    static Application onenoteApp = new Application();
    static XNamespace ns = null;

    static void Main(string[] args)
    {
        GetNamespace();
        string notebookId = GetObjectId(null, OneNote.HierarchyScope.hsNotebooks, "MyNotebook");
        string sectionId = GetObjectId(notebookId, OneNote.HierarchyScope.hsSections, "Sample_Section");
        string firstPageId = GetObjectId(sectionId, OneNote.HierarchyScope.hsPages, "MyPage");
        GetPageContent(firstPageId);
        Console.Read();
    }
    static void GetNamespace()
    {
        string xml;

        onenoteApp.GetHierarchy(null, OneNote.HierarchyScope.hsNotebooks, out xml);
        var doc = XDocument.Parse(xml);
        ns = doc.Root.Name.Namespace;
    }

    static string GetObjectId(string parentId, OneNote.HierarchyScope scope, string objectName)
    {
        string xml;
        onenoteApp.GetHierarchy(parentId, scope, out xml);

        var doc = XDocument.Parse(xml);
        var nodeName = "";

        switch (scope)
        {
            case (OneNote.HierarchyScope.hsNotebooks): nodeName = "Notebook"; break;
            case (OneNote.HierarchyScope.hsPages): nodeName = "Page"; break;
            case (OneNote.HierarchyScope.hsSections): nodeName = "Section"; break;
            default:
                return null;
        }

        var node = doc.Descendants(ns + nodeName).Where(n => n.Attribute("name").Value == objectName).FirstOrDefault();

        return node.Attribute("ID").Value;
    }
    static string GetPageContent(string pageId)
    {
        string xml;
        onenoteApp.GetPageContent(pageId, out xml, OneNote.PageInfo.piAll);
        var doc = XDocument.Parse(xml);
        var outLine = doc.Descendants(ns + "Outline").First();
        var content = outLine.Descendants(ns + "T").First();
        string contentVal = content.Value;
        content.Value = "modified";
        onenoteApp.UpdatePageContent(doc.ToString());
        return null;
    }

Comment: If you use this code, be aware that the innocently named method GetPageContent() actually *updates* the content to the word "modified". This may not be what you intended.
Answer: This is just what I've gleaned from reading examples on the web (of course, you've already read all of those) and peeking into the way OneNote stores its data in XML using ONOMspy (http://blogs.msdn.com/b/johnguin/archive/2011/07/28/onenote-spy-omspy-for-onenote-2010.aspx).
If you want to work with OneNote content, you'll need a basic understanding of XML.  Writing text to a OneNote page involves creating an outline element, whose content will be contained in OEChildren elements.  Within an OEChildren element, you can have many other child elements representing outline content.  These can be of type OE or HTMLBlock, if I'm reading the schema correctly.  Personally, I've only ever used OE, and in this case, you'll have an OE element containing a T (text) element.  The following code will create an outline XElement and add text to it:
// Get info from OneNote
string xml;
onApp.GetHierarchy(null, OneNote.HierarchyScope.hsSections, out xml);
XDocument doc = XDocument.Parse(xml);
XNamespace ns = doc.Root.Name.Namespace;

// Assuming you have a notebook called "Test"
XElement notebook = doc.Root.Elements(ns + "Notebook").Where(x => x.Attribute("name").Value == "Test").FirstOrDefault();
if (notebook == null)
{
    Console.WriteLine("Did not find notebook titled 'Test'.  Aborting.");
    return;
}

// If there is a section, just use the first one we encounter
XElement section;
if (notebook.Elements(ns + "Section").Any())
{
    section = notebook.Elements(ns + "Section").FirstOrDefault();
}
else
{
    Console.WriteLine("No sections found.  Aborting");
    return;
}

// Create a page
string newPageID;
onApp.CreateNewPage(section.Attribute("ID").Value, out newPageID);

// Create the page element using the ID of the new page OneNote just created
XElement newPage = new XElement(ns + "Page");
newPage.SetAttributeValue("ID", newPageID);

// Add a title just for grins
newPage.Add(new XElement(ns + "Title",
    new XElement(ns + "OE",
        new XElement(ns + "T",
            new XCData("Test Page")))));

// Add an outline and text content
newPage.Add(new XElement(ns + "Outline",
    new XElement(ns + "OEChildren",
        new XElement(ns + "OE",
            new XElement(ns + "T",
                new XCData("Here is some new sample text."))))));

// Now update the page content
onApp.UpdatePageContent(newPage.ToString());

Here's what the actual XML you're sending to OneNote looks like:
<Page ID="{20A13151-AD1C-4944-A3D3-772025BB8084}{1}{A1954187212743991351891701718491104445838501}" xmlns="http://schemas.microsoft.com/office/onenote/2013/onenote">
  <Title>
    <OE>
      <T><![CDATA[Test Page]]></T>
    </OE>
  </Title>
  <Outline>
    <OEChildren>
      <OE>
        <T><![CDATA[Here is some new sample text.]]></T>
      </OE>
    </OEChildren>
  </Outline>
</Page>

Hope that helps get you started!
Answer: If you're using C#, Check out the newer OneNote REST API at http://dev.onenote.com. It already supports creating a new page and has a beta API to patch and add content to an existing page.
Comment: Thank you, however I have already read the above article before posting and even tried some code examples.  And I was still not able to find the code to add text/content to a OneNote document using the Interop.  I am not trying to develop an application such as a Windows Store/Windows Phone application that is going to constantly commmunicate with OneNote or the OneNote API.  I am ideally just looking to design a console application to create and edit a One Note document.  Similar to what can be done using Interop for Word and Excel
Comment: Isn't this solely for online OneNote documents?
Comment: See if http://stackoverflow.com/questions/14875760/onenote-inserting-elements-with-updatepagecontent helps.


Siegel's theorem, best possible bound?

Question: I am studying classic Siegel's theorem, and I was wondering if that result is the best possible bound, meaning: is there a compact connected complex manifold $X$ of dimension $n$ in which $\operatorname{trdeg}_{\mathbb{C}} K(X) = n$ ?
Also, is there one in which it is $0$? (I was thinking about the manifold made of a single point, but is there another less trivial one?) And more in general, how can I compute this value for the classic ones? (projective complex space, torus, etc)
Answer:
Any quasiprojective algebraic manifold (or indeed any quasiprojective algebraic variety at all) of dimension $n$ always has $\operatorname{trdeg}_{\mathbf C} K(X) = n$. (Indeed, this is a popular way to define the dimension of an algebraic variety!) This is very clear for projective space: picking an affine patch $\mathbf C^n$, the $n$ coordinate functions are an algebraically independent set which generate the field of meromorphic functions.
Yes, there are complex manifolds with no nonconstant meromorphic functions. The most common examples are complex tori $X=\mathbf C^n/\Lambda$: for a general choice of the lattice $\Lambda$, the only meromorphic functions on $X$ will be the constants.

A reference for these things is Chapter VIII of Basic Algebraic Geometry by Shafarevich.
Comment: Dear @AnalysisStudent0414, sure: for example, by taking a product $X \times Y$ of a complex torus with no meromorphic functions and an algebraic manifold $Y$, one can achieve any value between 0 and $n$.
Comment: I'm not an expert, so you'll probably do just as well googling as asking me. Anyway, there are K3 surfaces with no nonconstant meromorphic functions: see Verbitsky's answer here http://mathoverflow.net/questions/167675/meromorphic-extension-of-local-defining-equations-of-a-complex-submanifold, also so-called Hopf surfaces, and so on. Another good reference is the book by Barth-Hulek-Peters-van de Ven. Soory I can't give more details.
Comment: Thank you very much. I'll leave the question open for a while, are there any examples of a complex manifold of dimension $n$ in which it is neither 0 nor $n$ ?
Comment: Right. What about the other "classic" examples of complex varieties? If I can find that in the book you told me (sadly library's closed until 7th) just tell me, I can wait... otherwise, some referencies to do some research on my own?

Siegel's theorem, best possible bound?


How to blend multiple time series models?

Question: I have three different linear, multi-variate time series models with a best fit against the same observed value $Y$ at 1 minute, 3 minutes and 10 minutes horizons respectively. Each model is using different predictors data. There is no serial correlation or ARIMA involved here.
I want to blend the three models to predict $Y$ every second, on a rolling base. The prediction for the three models is thus overlapping. For example, at time $t_3$ minutes, we'll have the prediction for the first and second model colliding (third prediction for the 1 minute model and first for the 3 minutes model).
How should I approach the problem?
Answer: Your problem looks like it's related to looking at time series aggregates on different frequencies. That is, one could look at daily sales data, build a model on that, forecast daily data... then aggregate historical data to weeks, build a model on weekly data and forecast weekly data... finally do the same exercise after aggregating to monthly data. Then finally one would combine the forecasts on different frequencies - and this last step seems to be what you are mainly interested in.
There is a recent very nice paper on the whole procedure by Kourentzes, Petropoulos and Trapero. I imagine that you could profit from looking at the final combination step in the paper.
Comment: That's a very good resource, thank you. In my case the models are based on different predictors data (not just different aggregation periods), but it looks like the methodology is still relevant.


Error while compiling the nested table type in oracle pl/sql

Question: I have created a type like this:
create or replace TYPE "DUMMY_TYPE_25MAY2017"
AS OBJECT
(
   programdata     VARCHAR2(2000)
)

Which is used by a nested table type
create or replace TYPE "TYP_DUMMY_TYPE_25MAY2017" AS TABLE OF DUMMY_TYPE_25MAY2017;

and a table
CREATE TABLE DUMMY_TABLE_25MAY17 OF DUMMY_TYPE_25MAY2017;

Then I altered the type DUMMY_TYPE_25MAY2017
ALTER TYPE DUMMY_TYPE_25MAY2017
   MODIFY ATTRIBUTE (programdata VARCHAR2(4000)) CASCADE;

But now when I compile the type "TYP_DUMMY_TYPE_25MAY2017 " I am getting the error

"error: ora-22308: operation not allowed on evolved type".

Please help me how to resolve this.
Comment: also im getting a error while performing the frontend functionality related to this " java.sql.SQLException: ORA-00932: inconsistent datatypes: expected SCHEMA.TYP_DUMMY_TYPE_25MAY2017 got SCHEMA.TYP_DUMMY_TYPE_25MAY2017" .  Also the TYP_DUMMY_TYPE_25MAY2017  has dependency to package .view and trigger .
Comment: Tip for future reference: please make it easier for us to figure out what's going on with clear object naming. Three different things with virtually the same dummy name is unnecessary.
Comment: And the comment regarding `ORA-00932` is a separate question. The StackOverflow rule is one question per thread. So start a new question. Include **all the relevant details**. Link to this question if necessary.
Answer:
"But now if I compile the type "TYP_DUMMY_TYPE_25MAY2017 " im getting the error"

It depends how you compile the nested table object. This error occurs with create or replace. The trick is to use alter type ... compile instead:
Here's your set-up:
SQL> create or replace TYPE "DUMMY_TYPE_25MAY2017" AS OBJECT
  2  (programdata     VARCHAR2(2000));
  3  /

Type created.

SQL> create or replace TYPE "TYP_DUMMY_TYPE_25MAY2017" AS TABLE OF DUMMY_TYPE_25MAY2017;
  2  /

Type created.

SQL> CREATE TABLE DUMMY_TABLE_25MAY17 OF DUMMY_TYPE_25MAY2017;

Table created.
SQL>

Now apply the change.
SQL> ALTER TYPE DUMMY_TYPE_25MAY2017
  2     MODIFY ATTRIBUTE (programdata VARCHAR2(4000)) CASCADE;

Type altered.

SQL> create or replace TYPE "TYP_DUMMY_TYPE_25MAY2017" AS TABLE OF DUMMY_TYPE_25MAY2017;
  2  /
create or replace TYPE "TYP_DUMMY_TYPE_25MAY2017" AS TABLE OF DUMMY_TYPE_25MAY2017;
*
ERROR at line 1:
ORA-22308: operation not allowed on evolved type

SQL> alter TYPE "TYP_DUMMY_TYPE_25MAY2017" compile
  2  /

Type altered.

SQL> insert into  DUMMY_TABLE_25MAY17 values ( DUMMY_TYPE_25MAY2017 ('this is a test'));

1 row created.

SQL>

Comment: I have also done the same thing :alter TYPE "TYP_DUMMY_TYPE_25MAY2017" compile .  but then also getting the error :"java.sql.SQLException: ORA-00932: inconsistent datatypes: expected SCHEMA.TYP_DUMMY_TYPE_25MAY2017 got SCHEMA.TYP_DUMMY_TYPE_25MAY2017"


Extract facebook users IDs who like or comment a post

Question: I wonder if anyone knows or has a tool which allows to extract the list of users IDs who liked or commented a Facebook post (especially a page post).
I've tried many softwares that claim performing this task in vain...
If you have a miracle, please share the love. I'd be glad to have either a software name, a java script, or anything that can do so.
Thank you all.
Answer: Would you mind telling what are you going to do with this?
Answer
263907926200 is the sample post id used
Through browser
https://graph.facebook.com/263907926200/comments
https://graph.facebook.com/263907926200/likes

Through API Explorer
->/v2.2/263907926200/comments
->/v2.2/263907926200/likes

FQL Method if you have an old app
Likes
https://graph.facebook.com/fql?q=SELECT user_id FROM like WHERE post_id = "xxxxx_xxxxx"
Comments
https://graph.facebook.com/fql?q=SELECT fromid FROM comment WHERE post_id ="xxxxx_xxxxx"


Date range facets with Sunspot in Ruby on Rails

Question: I am using Sunspot to search for events (parties, concerts, ...) in a Ruby on Rails 3 application.
I have managed to set up free text search and facet search on a couple of different category types.
Now, I am stuck with my next task. I want to set up facets related to when the event is occuring.
I want to have facets describing both relative date/time ranges such as "today", "this weekend", "next weekend" and absolute date/time ranges, such as "Easter Holiday 2011", "New Years Day 2012", ... The datetime ranges are sometimes overlapping each other.
I have browsed around in the Sunspot API documentation, the Sunspot wiki, here at Stackoverflow, read and loads of articles and blogs. People are writing it is possible to to achieve but I find no examples or implementation ideas that makes me understand how to do this.
Any suggestions?
Since my problem is not in my code, I don't publish any code. The class Event has a DateTime instance named "start_time". I do understand it's my job to define when the absolute date/time ranges appear in the calender.
Best regards,
./stefan
PS Did I tell I'm a newbie? ;-) DS
Answer: You should set up your fields as trie time fields for efficient range queries:
class Event
  searchable do
    time :start_time, :trie => true
  end
end

Then you can use query facets to facet based on ranges:
Event.search do
  facet :start_time do
    bod = Time.zone.now.beginning_of_day
    row :today do
      with :start_time, bod..(bod + 1)
    end
    row :tomorrow do
      with :start_time, (bod + 1)..(bod + 2)
    end
    # etc.
  end
end

The key insight here is that you can construct facets using arbitrary scopes. Note that the facet name :start_time is just used to reference the facet in the search results, and the row labels :today and :tomorrow are similarly just used on the client side to identify the row counts corresponding to those queries; they have no meaning from Solr's standpoint, so you can call them whatever you want (using whatever data type you want -- they don't have to be symbols).
More information on query facets here: http://sunspot.github.com/docs/Sunspot/DSL/FieldQuery.html#facet-instance_method
Comment: Thanks. Looks exactly like what I need.
Comment: Should the + time i.e. (bod + 1) not be (bod + 1.day) ? else its perfect
Answer: You can do in this way:
with(:registration_date).between(params[:start_date].to_date..params[:end_date].to_date)

Look here: http://sunspot.github.io/docs/Sunspot.html#search-class_method


Quick Search Button in Android

Question: I'm trying to display a password dialogue at the start of the application and on pressing the search button , the dialogue disappears and get destroyed , how to recover that ?
Answer: You can override onSearchRequested() in your password activity and return false.  This will prevent the search window from showing up while that activity is active.
Comment: It does work in the activity but it doesn't work in the password dialog .

Quick Search Button in Android


Using Access 2010 database in c#

Question: I am currently accessing a access 2010 database in c# and its unable to open the database as it doesn't seem to have the correct driver when I was using a .mdb this worked, but now since I'm using a .accdb it doesn't seem to want to open the database.  Here's the opening code.  I was wondering if there was anything you could help me with?
public void openDatabase(string dbname)
    {
        //dataBaseName = dbname;
        dataBaseName = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=houses.accdb"; //Defines the location of the database and its type.

        connection = new OleDbConnection(dataBaseName); //Creates a new OleDbConnection using the data from dataBase.

        connection.Open(); //Opens the TCP/IP connection.
    }`enter code here`

Answer: You need to change:
Provider=Microsoft.Jet.OLEDB.4.0

To
Provider=Microsoft.ACE.OLEDB.12.0

See also: http://www.connectionstrings.com/access-2007#84
Answer: You need the driver for Office 2007 - 2007 Office System Driver: Data Connectivity Components
Answer: to use the datbase without Access installed on a client you must also Engine2010 Access Database
http://www.microsoft.com/download/en/details.aspx?id=13255
Regards.

Using Access 2010 database in c#


Fontes não funcionam no Safari/ Firefox

Question: opa, boa noite.
desenvolvi meu site, porém a família tipográfica que usei no site não aparece no navegador Safari e Firefox, ao invés da Nunito é outra... E é uma fonte do Google Fonts, se alguém puder ajudar, tentei usar o @fontface porém não deu, não sei se usei da maneira correta, sou iniciante é meu primeiro site se alguém conseguir ajudar.

@import url("https://fonts.googleapis.com/css2?family=Nunito:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap");

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.body {
  font-family: "Nunito", sans-serif;
}

/* menu */
#navbar {
  text-align: center;
  position: absolute;
  width: 105px;
  background-color: white;
  box-shadow: -10px 0px 20px #00000007;
  height: 100vh;
  right: 0;
}
#navbar-item {
  margin-top: 40vh;
}

ul {
  list-style: none;
}
.chama-text {
  font-family: nunito-extrabold;
  transform: rotate(270deg);
  padding-left: 55px;
}
.chama {
  padding-bottom: 10px;
}
.whats {
  padding: 0px 15px 0;
  padding-bottom: 20px;
}
.linkedin {
  margin-top: 30px;
  padding-top: 30px;
}

/* texto principal*/
#showcase {
  background-color: white;
  height: 100vh; /* aqui 100vh para ocupar toda tela*/
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

#showcase-container {
  text-align: center;
}
#showcase-container h1 {
  margin-bottom: 64px;
  height: 364px;
  font-family: nunito-semibold;
  font-size: 302px;
  margin-left: auto;
}
.ponto {
  color: #00ff6c;
}
.foto {
  top: 222px;
  left: 1135px;
  width: 274px;
  height: 364px;
}
#showcase-container .apresentacao {
  margin: auto;
  max-width: 800px;
  font-family: nunito-extralight;
  font-size: 32px;
}
.box-apres {
  font-family: nunito-bold;
  background-color: #00ff6c;
}

.candido {
  font-family: nunito-bold;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="footer.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Nunito:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
  <title>portfólio do cândido</title>

CHAMA

olá.

meu nome é cândido, aqui estão alguns dos meus projetos, você pode conferir eles logo abaixo

Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Acho que o problema é o uso de nunito-semibold e nunito-extralight, que não são nomes reconhecidos da fonte. O font-family deve ser sempre "Nunito". Se quer que fique semibold, defina font-weight: 600, e para extralight use font-weight: 200 (acho que seria 100, mas seu import do google fonts não está incluindo esse peso, começa no 200).

Fontes não funcionam no Safari/ Firefox


Feathers-Sequelize with Postgres: How to query an Array

Question: I want to see if an array contains one or more values inside it.
This is a model field definition:
 keywords: {
              type: Sequelize.ARRAY(Sequelize.STRING),
              defaultValue: [],
              allowNull: false,
           },

This is the query I am testing:
context.app.services.jobOffers.Model.findAll({
        where: {
            keywords: {
                $contains: ['hello'],
            },
        },
    })
     .then(result => {
         console.log('RESULT:', result)
     })
     .catch(err => {
            console.log('ERROR:', err)
     })

This is the error I am receiving:
ERROR: TypeError: values.map is not a function

This is a reference to a similar issue, where I tried to replicate the solution but to no effect.
https://github.com/feathersjs-ecosystem/feathers-sequelize/issues/135
Answer: It seems the issue was with the Sequelize versions. This was made clear to me by one of the authors of Feathers.js @daffl
"In Sequelize v5 and later you need to use Symbols like [Op.contains] see (http://docs.sequelizejs.com/manual/querying.html#operators)"
So the fix is to change this line of code
where: {
         keywords: {
          [Op.contains]: ['hello'],
         },
       },