Can you listen to your computer's sound with a soundcard

Question: I would like to buy a Lexicon Alpha Studio, but I wanted to make sure that I can listen to my computers sound through it (it seems logical to me). Because my computer's jack plug is broken and my current adapter reduces low frequencies so that's not good for music production.
But in every review or video I see about this sound card (or any other sound card), people just use it to record sound, not to play sound, so that's why I'm asking this.
Comment: what kind of computer do you have?  Mac/PC/Linux?  If you set Lexicon Alpha Studio as your main output, then you'll notice that all your audio will be sent out to the device's monitor outputs.  Therefore, bypassing your headphone jack on your computer.
Comment: It's a Windows so I see how to do this. Thanks for your comment
Answer: Soundcards are classified by (amongst other things) their number of inputs and outputs. In general, a soundcard that has outputs is one that you'll be able to listen to (from the outputs!). This Lexicon is 2 in*, 2 out, so we expect to be able to listen to 2 channels (which should be fine for normal stereo listening.)
Another question is what outputs it has; if you want to plug in headphones, it's not much good if your soundcard only has XLR outputs. This Lexicon seems to have 1/4 inch, RCA, and headphone outputs - if one of those fits your needs, you should be fine.
* actually they seem to describe it as '2x2' in, i.e. 2 stereo channels
Comment: Indeed I wanted jack and not xlr outputs, so the Lexicon Alpha seem to have this, and if I remember right it also has an xlr mic input, so that would allow me to use good hq xlr mics
Answer: Yes, you can select the Lexicon as your computer's default audio output for all purposes.  There are line level and headphone output sockets.  Not, I think, the stereo 3.5mm jacks that your computer probably had, but a cheap adapter cable will sort that out.
If you intend to do music production, you probably want to go a bit up-market from this device.  But it should do a fine job at replacing a broken output jack on your computer.
Comment: *"If you intend to do music production, you probably want to go a bit up-market from this device."* I'd add the word *large-scale* to that sentence. So many people out there "producing" music with laptops and budget gear.
Answer: I should note that the Lexicon Alpha solution is actually quite solid yet very limited in regards to how many channels you have to work with. That being said, as I own one, it is fantastic for on-the-go gigs such as recital recordings and so on. But, as Lawrence Payne previously noted, you should certainly go up-market if you intend to do some more serious production. It's great for getting your feet wet, though.
At any rate, the Lexicon Alpha is indeed an Input/Output interface. The back side allows to plug in microphones and such, and it has audio output RCA jacks on the back side, but on the front side, on the right side of all the controls and knobs, is a standard 3.5mm headphone jack.
You may either plug a 3.5mm audio cable to your speakers or to a headphone set to that jack, or you may plug speakers to the back RCA jacks. The monitor mix knob to the left of the front headphone jack allows you to shift the sound to the monitor headphone jack (by turning it to the right) or to the RCA jacks on the back (by turning it to the left).
Comment: Thanks, I read a lot of reviews saying that Lexicon Alpha was a very good low-cost soundcard, that's why I was interested in it. And I think I still need to get my feet on mixing and mastering before buying a more expansive and serious sound card


Tools to wipe a hard disk

Question:
Possible Duplicate:
Deep Format of a Harddrive on a Linux System

Do you know tools (Linux live CDs, bootable DOS tools) to wipe hard drives?
Comment: Somehow a duplicate of http://serverfault.com/questions/48922/deep-format-of-a-harddrive-on-a-linux-system
Comment: So fire isn't an option?
Answer: Dban
"Darik's Boot and Nuke ("DBAN") is a self-contained boot disk that securely wipes the hard disks of most computers. DBAN will automatically and completely delete the contents of any hard disk that it can detect, which makes it an appropriate utility for bulk or emergency data destruction."
Answer: I'll use dd if=/dev/urandom of=/dev/*disk* bs=1024
ISTR that DoD recommends 7 passes, so you could do something like:
for n in {1...7}; do dd if=/dev/urandom of=/dev/*disk* bs=1024; done

Just be careful you get the correct disk or you could really shoot yourself in the foot.  If I'm wiping a desktop or laptop I'll boot off a linux liveCD and run dd from that.
Answer: dd bs=1MB if=/dev/urandom of=/dev/sdX
from a USB bootable key.
Answer: You can use shred which is installed by default in Ubuntu. So just get a live CD of that.
shred [OPTIONS] filename

or secure-delete (most likely not installed by default)
srm myfile.txt

Answer: DBAN boot disk
Answer: I like Darik's Boot and Nuke (DBAN):
http://www.dban.org
Very handy for secure drive wipes!
Answer: what's wrong with dd? dd is a tool that comes with (my belief) any linux live/install/repair image.
dd if=/dev/zero of=/dev/diskname

isn't zeroing the disk clean/secure enough? just wondering
Comment: There was something called The Great Zero Challenge that offered a reward for any company that could recover data from a hard drive zeroed out with `dd`. The reward was never claimed, however that really doesn't say much, as it was a small amount of money, and if you're the conspiracy type person, isn't it better for the public to *think* that `dd` is a secure way of wiping a disk?
Comment: come on :) you must really be into "something" if your disk is getting such attention (assuming zeroing isn't really zeroing). normal people just need to wipe out their passwords and adult movies and NSA won't spend money for recovering common passwords and bad movies ;)
Comment: Depends on the data being wiped. Supposedly drive recovery companies can get data back from zeroed disks and/or slack space in the drive, but you're talking lots of lots of cash and they are analyzing it on the platter for residual charges. The way to wipe it short of physical shredding is to zero, write data, zero, write it again, repeat several times until even that signature of a charge is irrelevant. There's a document for the military that talks about wiping procedures depending on the information being secured.
Comment: @Adirau: if the OP works for a bank, medical institution, etc. their data is *supposed* to be secured for auditing purposes, if nothing else, when retiring hardware. Other institutions having an accidental slip can cost a lot of money if, for example, credit card info slips into someone's latest score of cheap hardware from ebay or dumpster diving. The extra hours wiping the drive is little compared to the potential PR/financial disaster for an organization.
Comment: what i am saying is that even if zero recovery is doable it probably costs too much to implement. i agree to some point tho. the down vote wasn't necessary. i consider zeroing secure "enough", as i said.
Comment: Must agree with adirau. Multiple passes with random data is simply overkill for the average joe. Just zero it. If the NSA/FBI/etc is interested enough in you to be reading your discarded drives, you'll know why, and you should probably be physically destroying them with fire, acid, grinder, etc. anyway.

Tools to wipe a hard disk


How to redirect audio stream from microphone to headphone instantly

Question: I need to open the incoming  audio stream from the microphone and address it  instantly to the headphones so you  hear what is being acquired by the microphone.
it is not possible to do this using xna microphone, because it is  necessary to pass through a buffer that slows down the headphone listening. I think needs to use Windows.Phone.Media.Capture as AudioDevice and perhaps AudioSink but do not understand how. Do you have any suggestions?
thanks
Comment: possible duplicate of [How to stream audio from microphone to speaker?](http://stackoverflow.com/questions/14405771/how-to-stream-audio-from-microphone-to-speaker)
Comment: no, I need to address instantly to the headphone, without latency
Comment: No latency is not possible - the electrons have to travel between the microphone to the speaker at least, not to mention the OS' software layers involved.
Comment: @PaulAnnetts Many audio codecs have are able to loop microphone/headset back to the output mixer with only the converters' latency.
This is not to say that this functionality is exposed in an API.
Comment: @Marko I agree - but if such an API was available on this platform (which it is not) that would/should already be in the linked question.
Comment: @PaulAnnetts the latency is mainly due to the filling of the buffer used in the xna framework, whose minimum size can not be less than 100ms. The electrons are fast enough for what I plan to do. If you open the microphone channel on the audio mixer of an windows 95 does not notice a valuable latency
Answer: It looks you've got tighter latency requirements than the a previous question in this area. For phone 8 the best latency result is probably going to be to use the DirectX audio APIs from C++.
The documentation on MSDN will tell you which APIs you can use from the phone, but if I know MSDN I expect you will need to go digging to find examples of how to use them - and when you find them you'll need to be familiar with C/C++, and how to set up a "hybrid" C#/C++ project in Visual Studio.
Even then you'll have to try and it out on a real phone to see if the latency performance is good enough for your purposes.


Integrate another api's return data to service method

Question: Below is my service code for uploading questions into my database; However, I have another api for loading images into these questions from my frontend.
In order to set that relevant image into the database, i have the code:
<code>question.setImage_urls(cloudStorageHelper.getUrl());
</code>
This is the code for setImage url to the database where used in cloudstoragehelper class. So how should I integrate that piece of code into following code.
<code>@RequestMapping(method = RequestMethod.POST, value = "/saveQuestion")
public ResponseEntity<?> saveQuestion( @RequestBody Question question ) throws IOException, ServletException, InterruptedException, NullPointerException
{           return new ResponseEntity<>( questionService.saveQuestion( question ), HttpStatus.CREATED );
}
</code>
Answer: why don't you try to create a new data base to save image urls and from creating a service get those image urls to your front end( seems you want to bind data to front end) so from front end bind the value to the image url. will be much more beneficial for you in future. just a suggestion
Comment: just try it. just a suggestion :D


Drupal 6 Ahah With FileField Problem

Question: i'm creating a form which uses ahah in Drupal 6.
I have 2 select fields. The first uses ahah in order to populate the second and it works well.
But the problem is when I add a file field to the form because the ahah call doesn't work (it doesn't appear in firebug and the page is refreshed instead of the normal behavior). If I remove the file field it works again.
Any idea please? I'm getting frustrated thinking about the solution.
Thanks
Comment: I experimented on it, file upload element appears and flash outs immediately. So strage :(
Answer: It's a common issue that is reported here and even in the drupal documentation, the issue is reported so I think it's not yet solved at all so you need to find another solution that AHAH for the file upload filed.

Drupal 6 Ahah With FileField Problem


Upload de Imagens

Question: Não tenho tanto conhecimento na área de back-end, mas preciso de um uploader de imagens, procurei uma maneira que não use banco de dados, mas acredito que seja impossível.
Preciso de um uploader semelhante ao do Froala editor, resolvi observar melhor o código do dele para entender um pouco mais como funciona, descobrir que ele usa uma url ( http://i.froala.com/upload ) para fazer um upload temporário das imagens, então como sou limitado na area de back-end descobrir um projeto no GitHub mas estou com problemas em configurar.
Então preciso de ajuda para configura-lo porque sou leigo nessa área. Quais dados eu preciso para configurar um uploader de imagens? , É possível usar a mesma url de upload temporário do Froala nele?, ou precisa de algum dado a mais do servidor? não é uma atitude muito boa mas preciso de algo provisório.
Se tiverem outras opções a me recomendar, fiquem a vontade.
Answer: é totalmente possível um upload de imagem sem banco de dados, se é para armazenar num diretório dentro de sua hospedagem, ou em uma pasta do seu projeto local, tudo o que tem que fazer é recuperar os dados do arquivo via php, e especificar um diretório destino, se for muito leigo, tente usar alguma coisa que facilite, veja esse plugin:
http://blueimp.github.io/jQuery-File-Upload/ (ps: o plugin é estatico, ainda precisa manipular o arquivo via php)
e veja alguns tutoriais na internet
Comment: Em parte essa resposta resolveu meu problema, o autor deste plugin que você me enviou havia feito outro, especifico para load de imagens, fica aqui o link para se por acaso isso ajudar alguém no futuro com o mesmo problema que eu https://github.com/blueimp/JavaScript-Load-Image

De qualquer forma, muito obrigado. o/

Upload de Imagens


What percentage of football goals originate from corner kicks?

Question: What are the odds that getting a corner kick result in a goal?
Note, I am not asking the percentage of corner kicks that result in a goal. I am after stats from pro-level soccer, for example, the EPL. Anyone know of any others?
Comment: You might want to narrow this down. What play level are you looking at? Professional defenders might be better at sweeping these out than your pee-wee leagues. This *might* not be answerable in its current state.
Comment: I will not downvote this question, but I really fell it need some localization to work. like the answers says, this change form league to league and from year to year.
Comment: The question in the title is different than the question in the first sentence. Perhaps consider editing one or the other.
Comment: Related: [What percent of corner kicks turn into goals?](http://sports.stackexchange.com/q/977)
Answer: The question is very broad. However, taking statistics from the 2012-13 English Premiership (Games played till 29-Oct-2012), the total number of goals scored are 262, of which 36 are scored from corners. This gives a percentage figure of 13.74%
The breakup of each team are as follows.
<code>+---------------------+---------------+--------------------+------------+
|         Team        |  Goals Scored | Goals from Corners | Percentage |
+---------------------+---------------+--------------------+------------+
|        Arsenal      |       14      |          1         |    7.14    |
|      Aston Villa    |        7      |          2         |   28.57    |
|        Chelsea      |       21      |          1         |    4.76    |
|        Everton      |       17      |          2         |   11.76    |
|        Fulham       |       19      |          3         |   15.79    |
|        Liverpool    |       12      |          1         |    8.33    |
|    Manchester City  |       18      |          3         |   16.67    |
|   Manchester United |       24      |          6         |   25.00    |
|    Newcastle United |       11      |          0         |    0.00    |
|      Norwich City   |        7      |          1         |   14.29    |
| Queens Park Rangers |        7      |          0         |    0.00    |
|       Reading       |       11      |          0         |    0.00    |
|      Southampton    |       14      |          3         |   21.43    |
|      Stoke City     |        8      |          2         |   25.00    |
|      Sunderland     |        6      |          0         |    0.00    |
|     Swansea City    |       14      |          1         |    7.14    |
|  Tottenham Hotspur  |       17      |          3         |   17.65    |
| West Bromwich Albion|       13      |          3         |   23.08    |
|   West Ham United   |       12      |          2         |   16.67    |
|    Wigan Athletic   |       10      |          2         |   20.00    |
+---------------------+---------------+--------------------+------------+
|        Total        |      262      |         36         |   13.74    |
+---------------------+---------------+--------------------+------------+
</code>
Comment: Wonderful, thanks. Was thinking it should be somewhere from 10-30%. Clearly a big part of offensive strategy for some teams. But interestingly, the top 5 teams in EPL standings now are all over the place w.r.t. success in corners, so definitely not the be-all, end-all. Arsenal(6) & Chelsea(2) are clearly benefiting from some solid defense so far this season, despite converting very few corners.
Comment: @Orangecrush - Can I please know your source from which the data has been taken?
Comment: 13.77% of 2010/11 Premiership goals were from corners. Source: http://bit.ly/SoiR1i
Answer: This question is very general and can be change through time and league.
In the best research I found was from:
Science and Football V: The Proceedings of the 5th World Congress on Science and Football.

20 English Premier League matched from 2001-02 season were randomly
  sampled.
  The analysed matches resulted in 59 goals scored with 6 (10.2%) as a
  direct result of corner kicks.

Of course this can change between leagues and tournaments and through times.
Sources 1 2
Comment: Why did the researchers sample here? You have all data right?
Comment: @Bernhard You can read the research
Comment: @DorCohen To Bernhard's point, some context relevant to the question being asked would make this answer that much more valuable.


Solve $ \frac{d^2y}{dx^2} \cos x + \frac{dy}{dx} \sin x - 2y \cos^3 x = 2\cos^5x $ by a suitable transformation

Question: Consider $ \frac{d^2y}{dx^2} \cos x + \frac{dy}{dx} \sin x - 2y \cos^3 x = 2\cos^5x  $.
By a suitable transformation, reduce this equation to a second order linear differential equation with constant coefficients.
My try:
$$ \frac{d^2y}{dx^2} \cos x + \frac{dy}{dx} \sin x - 2y \cos^3 x = 2\cos^5x  \\ \Rightarrow \frac{\frac{d(\frac{dy}{dx})}{dx} \cos x - \frac{dy}{dx} \frac{d(\cos x)}{dx} }{\cos^2x} -2y \cos^3 x = 2\cos^5x  \\ \Rightarrow \frac{d\left( \frac{\frac{dy}{dx}}{\cos x} \right)}{dx} - 2y\cos^3x = 2\cos^5x$$
Unable to get rid of $\sin x$ or $\cos x$ terms from the coefficients.
Comment: I suppose that the transformation would be $x=f(t)$ and the problem is "just" to find $f(t)$.
Comment: Hi Claude! I didn't noticed your comment before posting my answer. I should have let the OP "just" find $f(t)$ instead of giving the hint. Cheers !
Comment: Hi, my question is, finding the transformation, is a totally trial and guessing effort, or there is any rule/intuition? I am not an expert here, trying to learn.
Answer: $$ \frac{d^2y}{dx^2} \cos x + \frac{dy}{dx} \sin x - 2y \cos^3 x = 2\cos^5x  $$
HINT :
The change of variable $\quad t=\sin(x)\quad$ leads to :
$$\frac{d^2y}{dt^2}-2y=2(1-t^2)$$
Solving leads to :
$$y=c_1e^{\sqrt{2}\:t}+c_2e^{-\sqrt{2}\:t}+t^2$$
Comment: Do you know "the principle of least effort"? Before trying transformations involving $x$ and $y$ together, better try transformations involving $y$ only or $x$ only. And before trying complicated functions first try the simplest functions, for example $t=\cos(x)$ or $\sin(x)$.
Comment: Thank you Claude Leibovici  and JJacquelin. I am able to solve it now. Before posting this question, I tried many other transformations like v = y cosx, y/cosx etc. What is the intuition / rule behind selecting this transformation t = sin x ?


Create PDF iOS7

Question: to create a pdf programmaticallly inside my iOS app I followed this tutorial on mobile.tut+:
http://mobile.tutsplus.com/tutorials/iphone/generating-pdf-documents/
but two methods are now deprecated in iOS7, but what xcode suggest to use instead of old methods doesn't seems to work. somebody have an idea?
thanks!
<code>    - (CGRect)addText:(NSString*)text withFrame:(CGRect)frame fontSize:(float)fontSize{
    UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Light" size:fontSize];

    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.alignment = NSTextAlignmentNatural;

    NSDictionary*attributi = @{ NSForegroundColorAttributeName: [UIColor blackColor],NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraph};

    NSStringDrawingContext* drawCont = [[NSStringDrawingContext alloc]init];
    drawCont.minimumScaleFactor = 0.0;

    //IOS6 deprecated method

//  CGSize stringSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(_pageSize.width - 2*20-2*20, _pageSize.height - 2*20 - 2*20) lineBreakMode:NSLineBreakByWordWrapping];

//IOS7 method suggested by xcode

    CGRect stringSIZ = [text boundingRectWithSize:CGSizeMake(_pageSize.width - 2*20-2*20, _pageSize.height - 2*20 - 2*20) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributi context:drawCont];

    float textWidth = frame.size.width;

    if (textWidth < stringSIZ.size.width)
        textWidth = stringSIZ.size.width;
    if (textWidth > _pageSize.width)
        textWidth = _pageSize.width - frame.origin.x;

    CGRect renderingRect = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSIZ.size.height);

         //IOS6 deprecated method
//    [text drawInRect:renderingRect
//            withFont:font
//       lineBreakMode:NSLineBreakByWordWrapping
//           alignment:NSTextAlignmentNatural];

    //IOS7 method suggested by xcode
    [text drawInRect:renderingRect withAttributes:attributi];

    frame = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSIZ.size.height);

    return frame;
}
</code>
Answer: I create my own class to create pdf as easy as possible in iOS7. if somebody need it, here it is:
PDFHelper.h
<code>#import <Foundation/Foundation.h>

@interface PDF : NSObject{
}
@property(nonatomic, readwrite) CGSize size;
@property(nonatomic, strong) NSMutableArray *headerRect;

@property(nonatomic, strong) NSMutableArray *header;

@property(nonatomic, strong) NSMutableArray *imageArray;
@property(nonatomic, strong) NSMutableArray *imageRectArray;

@property(nonatomic, strong) NSMutableArray *textArray;
@property(nonatomic, strong) NSMutableArray *textRectArray;

@property(nonatomic, strong)  NSMutableData *data;

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize;
// i metodi vanno invocati nel seguente ordine:
-(void)initContent;
-(void)addImageWithRect:(UIImage*)image inRect:(CGRect)rect;
-(void)addTextWithRect:(NSString*)text inRect:(CGRect)rect;
-(void)addHeadertWithRect:(NSString *)text inRect:(CGRect)rect;

- (void) drawText;
- (void) drawHeader;
- (void) drawImage;
- (NSMutableData*) generatePdfWithFilePath: (NSString *)thefilePath;
@end
</code>
PDFHelper.m
<code>#import "PDF.h"

@implementation PDF
@synthesize size, imageArray, header, imageRectArray, textArray, textRectArray, data, headerRect;
-(void)initContent{
    imageArray = [[NSMutableArray alloc]init];
    imageRectArray = [[NSMutableArray alloc]init];

    textArray = [[NSMutableArray alloc]init];
    textRectArray = [[NSMutableArray alloc]init];

    header = [[NSMutableArray alloc]init];
    headerRect = [[NSMutableArray alloc]init];

    data = [NSMutableData data];
  //  data = [NSMutableData data];

}
- (void) drawHeader
{
    for (int i = 0; i < [header count]; i++) {

        CGContextRef    currentContext = UIGraphicsGetCurrentContext();
        CGContextSetRGBFillColor(currentContext, 0.0, 0.0, 0.0, 1.0);

        NSString *textToDraw = [header objectAtIndex:i];

        NSLog(@"Text to draw: %@", textToDraw);
        CGRect renderingRect = [[headerRect objectAtIndex:i]CGRectValue];
        NSLog(@"x of rect is %f",  renderingRect.origin.x);

        UIFont*font = [UIFont fontWithName:@"HelveticaNeue-Light" size:30.0];

        UIColor*color = [UIColor colorWithRed:255/255.0 green:79/255.0 blue:79/255.0 alpha:1.0];
        NSDictionary*att = @{NSFontAttributeName: font, NSForegroundColorAttributeName:color};
        NSStringDrawingContext *context = [NSStringDrawingContext new];
        context.minimumScaleFactor = 0.1;
        //        [textToDraw drawInRect:renderingRect withAttributes:att];
        [textToDraw drawWithRect:renderingRect options:NSStringDrawingUsesLineFragmentOrigin attributes:att context:context];
    }

}
-(void)drawImage{
    for (int i = 0; i < [imageArray count]; i++) {
        [[imageArray objectAtIndex:i] drawInRect:[[imageRectArray objectAtIndex:i]CGRectValue]];

    }
}
- (void) drawText
{
    for (int i = 0; i < [textArray count]; i++) {

    CGContextRef    currentContext = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(currentContext, 0.0, 0.0, 0.0, 1.0);

    NSString *textToDraw = [textArray objectAtIndex:i];

        NSLog(@"Text to draw: %@", textToDraw);
        CGRect renderingRect = [[textRectArray objectAtIndex:i]CGRectValue];
        NSLog(@"x of rect is %f",  renderingRect.origin.x);

        UIFont*font = [UIFont fontWithName:@"HelveticaNeue-Light" size:22.0];

        UIColor*color = [UIColor blackColor];
        NSDictionary*att = @{NSFontAttributeName: font, NSForegroundColorAttributeName:color};

        [textToDraw drawWithRect:renderingRect options:NSStringDrawingUsesLineFragmentOrigin attributes:att context:nil];
}

}
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //UIGraphicsBeginImageContext(newSize);
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
-(void)addImageWithRect:(UIImage *)image inRect:(CGRect)rect{
    UIImage *newImage = [PDF imageWithImage:image scaledToSize:CGSizeMake(rect.size.width, rect.size.height)];

    [imageArray addObject:newImage];
    [imageRectArray addObject:[NSValue valueWithCGRect:rect]];
}
-(void)addTextWithRect:(NSString *)text inRect:(CGRect)rect{
    [textArray addObject:text];
    [textRectArray addObject:[NSValue valueWithCGRect:rect]];
}
-(void)addHeadertWithRect:(NSString *)text inRect:(CGRect)rect{
    [header addObject:text];
    [headerRect addObject:[NSValue valueWithCGRect:rect]];
}

- (NSMutableData*) generatePdfWithFilePath: (NSString *)thefilePath
{

    UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);

    BOOL done = NO;
    do
    {
        //Start a new page.
        UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, size.width, size.height), nil);

        //Draw Header
        [self drawHeader];
        //Draw Text
        [self drawText];
        //Draw an image
        [self drawImage];

        done = YES;
    }
    while (!done);

    // Close the PDF context and write the contents out.
    UIGraphicsEndPDFContext();

    //For data
    UIGraphicsBeginPDFContextToData(data, CGRectZero, nil);

    BOOL done1 = NO;
    do
    {
        //Start a new page.
        UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, size.width, size.height), nil);

        //Draw Header
        [self drawHeader];
        //Draw Text
        [self drawText];
        //Draw an image
        [self drawImage];

        done1 = YES;
    }
    while (!done1);

    // Close the PDF context and write the contents out.
    UIGraphicsEndPDFContext();
    return data;
}
</code>
Now import the PDf.h in the class and use something like this to create and draw your pdf:
<code>-(void)CreaPDFconPath:(NSString*)pdfFilePath{

    UIFont*font = [UIFont fontWithName:@"HelveticaNeue-Light" size:22.0];

    UIColor*color = [UIColor blackColor];
    NSDictionary*att = @{NSFontAttributeName: font, NSForegroundColorAttributeName:color};

    NSString* text = [NSString stringWithFormat:@"%@ \n\n%@", self.ingredienti.text, self.preparazione.text];

    CGFloat stringSize = [text boundingRectWithSize:CGSizeMake(980, CGFLOAT_MAX)// use CGFLOAT_MAX to dinamically calculate the height of a string
                                            options:NSStringDrawingUsesLineFragmentOrigin
                                         attributes:att context:nil].size.height;

    //creo pdf e vi aggiungo testo e immagini
    PDF*pdfFile = [[PDF alloc]init];
    [pdfFile initContent];
    [pdfFile setSize:CGSizeMake(1000, 400+stringSize)];

    [pdfFile addHeadertWithRect:self.fieldNome.text inRect:CGRectMake(10, 10, 980, 60)];

    [pdfFile addImageWithRect:self.image.image inRect:CGRectMake(10, 80, 250, 250)];

    NSString*stringInfo = [NSString stringWithFormat:@"%@:%@ \n\n%@",self.oreCottura.text,self.minutiDiCottura.text,self.numeroPersone.text];
    [pdfFile addHeadertWithRect:stringInfo inRect:CGRectMake(300, 190, 500, 120)];

    [pdfFile addTextWithRect:text inRect:CGRectMake(10, 350, 980, CGFLOAT_MAX)];

    //disegno header immagine e testo
    [pdfFile drawHeader];
    [pdfFile drawImage];
    [pdfFile drawText];
    //genero pdf
    [pdfFile generatePdfWithFilePath:pdfFilePath];
}
</code>
Comment: Looks like a handy class, but I don't know why you called it a singleton.
Answer: This is my solution to the PDF Generation issues from recent deprecated methods since IOS7 release:
<code>- (void)drawDate
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
    CGRect textRect = CGRectMake(160, 120, [[self date]frame].size.width, self.date.frame.size.height);
    NSString *dateString = self.date.text;
    UIFont *font = [UIFont fontWithName:@"Helvetica" size:14];
    NSMutableParagraphStyle *paragraphstyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphstyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphstyle.alignment = NSTextAlignmentLeft;
    NSDictionary * attributes = @{ NSFontAttributeName:font, NSParagraphStyleAttributeName: paragraphstyle };
    [dateString drawInRect:textRect withAttributes:attributes];
}
</code>
Hope this helps.  LMK if you have comments...
Answer: You can this code working. Please try!
<code>#import <Foundation/Foundation.h>

@interface PDFHelper : NSObject{
}
@property(nonatomic, readwrite) CGSize size;
@property(nonatomic, strong) NSMutableArray *headerRect;

@property(nonatomic, strong) NSMutableArray *header;

@property(nonatomic, strong) NSMutableArray *imageArray;
@property(nonatomic, strong) NSMutableArray *imageRectArray;

@property(nonatomic, strong) NSMutableArray *textArray;
@property(nonatomic, strong) NSMutableArray *textRectArray;

@property(nonatomic, strong)  NSMutableData *data;

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize;
// i metodi vanno invocati nel seguente ordine:
-(void)initContent;
-(void)addImageWithRect:(UIImage*)image inRect:(CGRect)rect;
-(void)addTextWithRect:(NSString*)text inRect:(CGRect)rect;
-(void)addHeadertWithRect:(NSString *)text inRect:(CGRect)rect;

- (void) drawText;
- (void) drawHeader;
- (void) drawImage;
- (NSMutableData*) generatePdfWithFilePath: (NSString *)thefilePath;
@end
</code>
>
<code>#import "PDFHelper.h"
@implementation PDFHelper
@synthesize size, imageArray, header, imageRectArray, textArray, textRectArray, data, headerRect;
-(void)initContent{
    imageArray = [[NSMutableArray alloc]init];
    imageRectArray = [[NSMutableArray alloc]init];

    textArray = [[NSMutableArray alloc]init];
    textRectArray = [[NSMutableArray alloc]init];

    header = [[NSMutableArray alloc]init];
    headerRect = [[NSMutableArray alloc]init];

    data = [NSMutableData data];
    //  data = [NSMutableData data];

}
- (void) drawHeader
{
    for (int i = 0; i < [header count]; i++) {

        CGContextRef    currentContext = UIGraphicsGetCurrentContext();
        CGContextSetRGBFillColor(currentContext, 0.0, 0.0, 0.0, 1.0);

        NSString *textToDraw = [header objectAtIndex:i];

        NSLog(@"Text to draw: %@", textToDraw);
        CGRect renderingRect = [[headerRect objectAtIndex:i]CGRectValue];
        NSLog(@"x of rect is %f",  renderingRect.origin.x);

        UIFont*font = [UIFont fontWithName:@"HelveticaNeue-Light" size:30.0];

        UIColor*color = [UIColor colorWithRed:255/255.0 green:79/255.0 blue:79/255.0 alpha:1.0];
        NSDictionary*att = @{NSFontAttributeName: font, NSForegroundColorAttributeName:color};
        NSStringDrawingContext *context = [NSStringDrawingContext new];
        context.minimumScaleFactor = 0.1;
        //        [textToDraw drawInRect:renderingRect withAttributes:att];
        [textToDraw drawWithRect:renderingRect options:NSStringDrawingUsesLineFragmentOrigin attributes:att context:context];
    }

}
-(void)drawImage{
    for (int i = 0; i < [imageArray count]; i++) {
        [[imageArray objectAtIndex:i] drawInRect:[[imageRectArray objectAtIndex:i]CGRectValue]];

    }
}
- (void) drawText
{
    for (int i = 0; i < [textArray count]; i++) {

        CGContextRef    currentContext = UIGraphicsGetCurrentContext();
        CGContextSetRGBFillColor(currentContext, 0.0, 0.0, 0.0, 1.0);

        NSString *textToDraw = [textArray objectAtIndex:i];

        NSLog(@"Text to draw: %@", textToDraw);
        CGRect renderingRect = [[textRectArray objectAtIndex:i]CGRectValue];
        NSLog(@"x of rect is %f",  renderingRect.origin.x);

        UIFont*font = [UIFont fontWithName:@"HelveticaNeue-Light" size:22.0];

        UIColor*color = [UIColor blackColor];
        NSDictionary*att = @{NSFontAttributeName: font, NSForegroundColorAttributeName:color};

        [textToDraw drawWithRect:renderingRect options:NSStringDrawingUsesLineFragmentOrigin attributes:att context:nil];
    }

}
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //UIGraphicsBeginImageContext(newSize);
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
-(void)addImageWithRect:(UIImage *)image inRect:(CGRect)rect{
    UIImage *newImage = [PDFHelper imageWithImage:image scaledToSize:CGSizeMake(rect.size.width, rect.size.height)];

    [imageArray addObject:newImage];
    [imageRectArray addObject:[NSValue valueWithCGRect:rect]];
}
-(void)addTextWithRect:(NSString *)text inRect:(CGRect)rect{
    [textArray addObject:text];
    [textRectArray addObject:[NSValue valueWithCGRect:rect]];
}
-(void)addHeadertWithRect:(NSString *)text inRect:(CGRect)rect{
    [header addObject:text];
    [headerRect addObject:[NSValue valueWithCGRect:rect]];
}

- (NSMutableData*) generatePdfWithFilePath: (NSString *)thefilePath
{

    UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);

    BOOL done = NO;
    do
    {
        //Start a new page.
        UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, size.width, size.height), nil);

        //Draw Header
        [self drawHeader];
        //Draw Text
        [self drawText];
        //Draw an image
        [self drawImage];

        done = YES;
    }
    while (!done);

    // Close the PDF context and write the contents out.
    UIGraphicsEndPDFContext();

    //For data
    UIGraphicsBeginPDFContextToData(data, CGRectZero, nil);

    BOOL done1 = NO;
    do
    {
        //Start a new page.
        UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, size.width, size.height), nil);

        //Draw Header
        [self drawHeader];
        //Draw Text
        [self drawText];
        //Draw an image
        [self drawImage];

        done1 = YES;
    }
    while (!done1);

    // Close the PDF context and write the contents out.
    UIGraphicsEndPDFContext();
    return data;
}
@end
</code>
>
<code>-(void)CreaPDFconPath:(NSString*)pdfFilePath{

    NSArray *arrayPaths =
    NSSearchPathForDirectoriesInDomains(
                                        NSDocumentDirectory,
                                        NSUserDomainMask,
                                        YES);
    NSString *path = [arrayPaths objectAtIndex:0];
    NSString* imagePath = [path stringByAppendingPathComponent:@"test.png"];

    UIImage *image = [[UIImage alloc]initWithContentsOfFile:imagePath];

    UIFont*font = [UIFont fontWithName:@"HelveticaNeue-Light" size:22.0];

    UIColor*color = [UIColor blackColor];
    NSDictionary*att = @{NSFontAttributeName: font, NSForegroundColorAttributeName:color};

    NSString* text = @"Test1";

    CGFloat stringSize = [text boundingRectWithSize:CGSizeMake(980, CGFLOAT_MAX)// use CGFLOAT_MAX to dinamically calculate the height of a string
                                            options:NSStringDrawingUsesLineFragmentOrigin
                                         attributes:att context:nil].size.height;

    //creo pdf e vi aggiungo testo e immagini
    PDFHelper*pdfFile = [[PDFHelper alloc]init];
    [pdfFile initContent];
    [pdfFile setSize:CGSizeMake(1000, 400+stringSize)];

    [pdfFile addHeadertWithRect:@"Field Text" inRect:CGRectMake(10, 10, 980, 60)];

    [pdfFile addImageWithRect:image inRect:CGRectMake(10, 80, 250, 250)];

    NSString*stringInfo = @"Info";
    [pdfFile addHeadertWithRect:stringInfo inRect:CGRectMake(300, 190, 500, 120)];

    [pdfFile addTextWithRect:text inRect:CGRectMake(10, 350, 980, CGFLOAT_MAX)];

    //disegno header immagine e testo
    [pdfFile drawHeader];
    [pdfFile drawImage];
    [pdfFile drawText];
    //genero pdf
    [pdfFile generatePdfWithFilePath:pdfFilePath];
}
</code>

Create PDF iOS7


Blatant ripoff site scraping Magento StackExchange

Question: Has anyone seen this site?  http://answermagento.com/
I know this subject has been briefly discussed but this isn't another site using a StackExchange-clone platform.  This site consists entirely of scraped content from Magento SE.
Frequently linked-to site ripping off Magento Stack Exchange
Answer: The content is CC share-alike, but this site isn't properly crediting the origin.
Not important though because the domain name infringes our mark. I've sent a note to our legal team to C&D the owner.
Comment: someones about to get #shrek'd.
Comment: Looks like it worked because they are down.
Comment: Intellectual Property Rights #FTW
Answer: Thats a common problem with stackoverflow/stackexchange content. Usually you dont find it on google anymore, as the duplicate content restrictions are good enough to recognize them.
If you still see such things, you can report them to the StackExchange Team via one of the communication ways.
I for example sent a mail 3 Years ago about one case. It took some days, but they answered and forwarded the case. They have dedicated persons for this kind of Issue.
So, just report it directly to StackExchange, they will forward it to the person responsible for this.
Answer: Meet "Alan Storm"

This is another website ripping Magento SE, compare this:

Ours: Inline translate Chrome Bug?
Theirs: http://worldofcoder.com/question/12459/how-to-inline-translate-chrome-bug.html

They left out the poster's names and replaced the pics, hence the good looking "Alan Storm"... ;)


D7 - Losing images when moving site location; placeholders point to old absolute path rather than relative path

Question: My file directories have not changed, but every time I move from local host to production, or just change the filename of a test site online, I loose the images.
For example if I use the backup of prodcution server in local I am getting the path name like below:

http://localhost/sites/all/sites/default/files/images/image_name.jpg

here the project name is missing. thats why I am not getting the images.
I have changed the base_url in local as

http://localhost/project-name

But even that doesn't helps. (Cleared the cache after changing)
Merely this is a duplicate of this question
But I didn't get what I need on that question. Thats why I reposted again.
Any help will be thankful and grateful...
Comment: I found this problem was solved by changing location of the public files to an incorrect location and then back to the correct one.
Answer: Have you tried using http://drupal.org/project/pathologic?
Which way are you using to migrate your database and files? I would also suggest that you clear the cache before exporting.
Comment: I used backup and migrate module to export DB.
Comment: I didn't try this before. But my query is there really neccessary of a module to solve this issue ?
Comment: alright, use pathologic...it will handle the links for you. Don't bother with changing the base-url for now. just install pathologic, backup everything normally then restore it.
Comment: **Yes** you have to install that module to handle the links to your files and the paths that you use. with pathologic you would then use relative links to files, it will turn them to absolutes when it needs to
Comment: Fine.. Let me check and get back to you....
Comment: @Chiko can I uninstal this module after moving site or it should remain?
Comment: @shekoufeh i'd recommend that you leave it installed. it includes a text filter for future image links and such so you do need it even afterwards.
Answer: I wanted to post an alternative solution mainly because I don't think that an Input Format is going to solve all the problems.
Basically, you can follow the instructions below.

Import your database
Within your database editing tool run this code : update files set filepath=REPLACE(filepath, 'sites/OLD_SITE_PATH/files', 'sites/NEW_SITE_NAME/files')
Log into your site and change your paths at

admin/config/media/file-system


Two questions about graded rings

Question: From Wikipedia, a graded ring is a ring $R$ that can be decomposed as the direct sum
$$
R=\bigoplus_{n\geq0}R_n
$$
of additive subgroups such that $R_mR_n\subset R_{m+n}$ for all $m,n\geq 0$. Wiki then claims that $R_0$ is a subring of $R$ but does not prove this. They then claim that "by definition of direct sum", every element $a$ of $R$ can be written uniquely as
$$
a=a_0+a_1+\ldots+a_n
$$
where each $a_i\in R_i$. Here are my questions:

How do we prove $R_0$ is a subring of $R$? I have searched many internet sources and I cannot seem to find a proof of this fact. We know it is an additive subgroup, so it must be closed under subtraction. But the subring test requires closure under multiplication, and $1\in R_0$ as well. How can we verify these?
I don't understand what they mean with "by definition of direct sum". I checked Wikipedia's definition of the direct sum of abelian groups, and it is simply the subgroup of the direct product such that all but finitely many of the entries are zero. I don't see how this yields the uniqueness property. I have, however, seen this uniqueness property when working with direct sums of vector subspaces, but with the additional assumption that the subspaces satisfy
$$(U_1+U_2+\ldots+\hat{U_i}+\ldots+U_n)\cap U_i=\{0\}.$$
That is, they are "mutually disjoint" in some sense (I know that's not what this property is called, I'm just not sure what else to call it). Anyway, without this assumption on the $R_i$, how do we know every element $a\in R$ can be written uniquely as above?
Comment: $R_0R_0\subseteq R_0$
Comment: Just a general word of advice, don't rely on definitions from wikipedia. Consulting a textbook is better, and consulting multiple textbooks is better still. You never know when an object or concept has more than one definition that wikipedia has failed to mention.
Comment: Thank you, and yeah that's what I was doing. I figured I'd use Wiki for this post so it would be easier for someone to look it up quickly if they wanted to. All of the definitions I found were essentially the same.
Answer: As mentioned in a comment, $R_0$ being a subring of $R$ follows from how $R_0R_0\subseteq R_{0+0}$.
As for your question on direct sums, it might be helpful to look at the finite analogue.
Given two abelian groups $R$ and $S$, the direct sum $R\oplus S$ will coincide with (as in, it is isomorphic to) the direct product $R\times S$.
The latter is a cartesian product of abelian groups, so the elements of $R\times S$ are of the form $(r,s)$ for $r\in R$ and $s\in S$, with addition and multiplication done component-wise.
With this notation, saying that an element of $R\times S$ is "in $R$" means that the $S$ component is zero. In other words, $R$ can be identified with the subgroup $\{(r,0)\mid r\in R\}$ of $R\times S$, and similarly for $S$.
Now, saying that an element of $R\times S$ can be written uniquely as a sum of an element of $R$ with an element of $S$ is to say that $(x,y)=(r,0)+(0,s)$ forces $x=r$ and $y=s$, which follows by computing the sum on the right-hand side.
In the infinite setting, this is no longer true for products only because infinite sums don't make sense in abelian groups. For example, you can't decompose $(1,1,1,\dots)\in\prod_{i=0}^\infty\mathbb Z$ into a sum where each summand lies in one of the $\mathbb Z$'s because such a sum would have to be infinite.
If we restrict our attention to the subgroup of $\prod_{i=0}^\infty\mathbb Z$ where we only take those $(x_1,x_2,x_3,\dots)$ where finitely many of the $x_i$ are nonzero, the decomposition is true again: if we let $I$ be the (finite) set of indices $i\in I$ for which $x_i\neq0$, then $(x_1,x_2,x_3,\dots)=\sum_{i\in I}\vec x_i$, where $\vec x_i=(0,\dots,0,x_i,0,\dots)$ is nonzero only in the $i$th index.
In general, the subgroup of $\prod_iR_i$ consisting of those sequences wherein only finitely many terms are nonzero is precisely the direct sum, denoted $\bigoplus_iR_i$. Intuitively, this is the resulting abelian group where you allow elements of the different rings to be added together "freely" (if $r_i\in R_i$ and $r_j\in R_j$, then $r_i+r_j$ only really makes sense if $i=j$; if $i\neq j$, then we don't know what to do, so just let their sum be this new element called $r_i+r_j$). In this way, it is essentially by definition that elements of $\bigoplus_iR_i$ are uniquely given by finite sums of elements in the individual $R_i$'s.
In fact, your disjointness of direct summands from linear algebra is still valid for direct sums of abelian groups: if you identify $R_j$ with the subgroup of $\bigoplus_iR_i$ consisting of those elements whose only nonzero term is at index $j$, then $R_i\cap R_j=\{0\}$ whenever $i\neq j$.
Comment: @LalbahadurSahu What does $R=\bigoplus_{n\geq0}2^n\mathbb{Z}$ mean to you, explicitly? Since $2^n\mathbb{Z}\cong\mathbb{Z}$ as abelian groups, your example is just a direct sum of infinitely many copies of $\mathbb{Z}$.

Consider the direct sum $2\mathbb{Z}\oplus4\mathbb{Z}$, which is isomorphic to $2\mathbb{Z}\times4\mathbb{Z}$. Although $4\in2\mathbb{Z}\cap4\mathbb{Z}$, each $4$ contributes differently to the direct sum, because $(4, 0) \neq (0, 4)$.
Comment: Welcome to the site, and thank you, this is very helpful.
Comment: I can not understand the last statement which you have given for this example $R = \oplus_{n\ge 0} 2^n\mathbb{Z}$, as $4\in2\mathbb{Z}\cap 4\mathbb{Z} $
Comment: @Zach Goldthorpe After reading in wiki, a link which was provided in another answer, I feel it's just a notation for a proper subgroup of direct products of infinite group and it does not have trivial intersection property. Please do correct if I am wrong.
Comment: @ZachGoldthorpe I see, but what about this $\mathbb{Z}_2\oplus\mathbb{Z}_{2^2}\oplus\mathbb{Z}_{2^3}\oplus\dots$? I had one more comment please have a look on that one as well. Thanks for your reply.
Comment: @LalbahadurSahu I was hoping my previous response would have addressed both comments. The point is that the direct sum is a _particular_ subgroup of the direct product (not just "any" subgroup). The trivial intersection follows from how you identify each $R_j$ with a subgroup of $\bigoplus_iR_i$. It is then irrelevant what inclusion relations the $R_j$s have with each other. If direct summands didn't have to be disjoint, wouldn't that mean $\bigoplus_{i=1}^\infty\mathbb{Z}\cong\mathbb{Z}$?
Comment: @ZachGoldthorpe It means that if I identify $R_j$ with $(0,...,0,r_j,0,...)$, then $R_j\cap R_i=\{\bar{0}\}$, for $i\neq j$.
Comment: Exactly, and that is precisely the disjointness condition explained at the bottom of my answer.
Answer: I'll try my best to answer this but I'm not that familiar with graded rings. But the definition seems pretty straightforward.
1.: It's closed under multiplication since $R_0 R_0 \subset R_{0+0} = R_{0}$. Now suppose $1 \in R_n$ with $n \neq 0$. Then $1 \cdot 1 = 1 \in R_{n}$ but $(1 \cdot 1) \in R_{n+n} = R_{2n}$. This implies $1 \in R_n\cap R_{2n} = \{0\}$ (because $n \neq 2n$, see shibais answer) which is a contradiction since $1 \neq 0$. Therefore $1 \in R_0$.
2.: There is a distinction between an internal and an external direct sum (see Wikipedia). You used the internal definition for vector subspaces and therefore needed the extra assumption. When using the external direct sum we already think of the objects as being disjoint, therefore we don't need an extra assumption. The uniqueness property still holds, see shibais answer for a more detailed answer regarding this.

Two questions about graded rings


How to show that a measurable set $E$, of measure 1, can be expressed as the union of sets $E_{i}$ of measure $1/2^{i}$.

Question: This question seemed relevant to me because it provides an interesting idea about the lebesgue measure. The problem is the following:
Let $\lambda$ be the Lebesgue measure on $\mathbf{R}$ and let $E$ be a measurable set of measure $\lambda(E)=1$. Prove that there exists a sequence of measurable subsets $E_{i}\subset E$ , of measure $\lambda(E_{i}) = 1/2^{i}$, whose union is $E$.
Answer: The key idea is to define the function $f: \mathbf{R} \to \mathbf{R}$ by $f(x) = \lambda (E \cap (-\infty, x))$. We need to show that this functions is continuous and to use the intermediate value theorem in order to construct the sequence $\{E_{i}\}.$

$\textit{Continuity from below }$: Let $x \in \mathbb{R}$. Then
$$
  \lim_{n \to \infty} f(x - \frac{1}{n}) = \lim_{n \to \infty} \lambda(E \cap (-\infty, x - \frac{1}{n})) = \lambda\left( \bigcup_{i = 1}^{\infty} E \cap (-\infty, x - \frac{1}{n})\right) = \lambda(E \cap (-\infty, x)) = f(x).
$$
$\textit{Continuity from above} :$ Let $x\in \mathbb{R}$. Then
$$
\lim_{n \to \infty} f(x + \frac{1}{n}) = \lim_{n \to \infty} \lambda (E \cap (-\infty, x + \frac{1}{n})) = \lambda\left(\bigcap_{n = 1}^{\infty} E \cap (-\infty, x + \frac{1}{n})\right) = \lambda(E \cap (-\infty, x]) = \lambda(E \cap (-\infty, x)) = f(x)
$$

Due to the intermediate value theorem, there exist $x_{i} \in \mathbf{R}$ such that $f(x_{i}) = \sum_{k = 1}^{i} \frac{1}{2^{k}}$. Define $E_{i}$ by
$$
E_{i} = (E \cap (-\infty, x_{i}))-(E \cap (-\infty, x_{i-1})).
$$
Then $\lambda(E_{i}) = 1/2^{i}$ and
$$
\lambda(\bigcup_{i=1}^{\infty}E_{i}) = \sum_{i = 1}^{\infty} \lambda(E_{i}) = 1.
$$
Then we have that $\cup_{i} E_{i} = E - N$, where $N$ is a set of measure zero. So,
$$
\bigcup_{i = 1}^{\infty} (E_{i} \cup N) = E, \quad \lambda (E_{i} \cup N) = \frac{1}{2^i}.
$$
Answer: More on Diego's answer.
Define $f(x) = \lambda\big(E \cap (-\infty,x)\big)$.  We must show $f$ is continuous.
In fact, for $x<y$,
$$
0 \le f(y)-f(x) =
\lambda\big(E \cap (-\infty,y)\big) - \lambda\big(E \cap (-\infty,x)\big)
= \lambda\big(E \cap [x,y) \big) \le \lambda\big([x,y)\big) = y-x .
$$
This shows, in fact, that $f$ is uniformly continuous.

Note.  In general, to show a function $f$ is continuous it is not enough to show
$$
\lim_{n\to\infty} f\left(x-\frac{1}{n}\right) = f(x)\quad\text{and}\quad
\lim_{n\to\infty} f\left(x+\frac{1}{n}\right) = f(x) .
$$
These are enough in case $f$ is nondecreasing, however, but probably requires additional explanation.


Easily Determine if Field Is Required

Question: I have a large set of Content Types,each with a fair amount of fields.  IS there a way to programatically report on whether those fields are required or not?  It is tedious to click on each field to check it.
Answer: You can make use of Field Info API functions to get this information.
Since the 'required' setting is on the instance level, not the field level, you'll need to use either field_info_instances(), which will get the instance information for all fields attached to a given entity type and bundle:
$entity_type = 'node';
$bundle = 'article';

$info = field_info_instances($entity_type, $bundle);
foreach ($info as $field_instance) {
  $required = (bool)$field_instance['required'];
}

or alternatively, if you only want the info for a single field, the field_info_instance function:
$entity_type = 'node';
$bundle = 'article';
$field_name = 'field_my_field';

$info = field_info_instance($entity_type, $field_name, $bundle);
$required = (bool)$info['required'];

Answer: In Drupal 7 you can use field_info_fields() function to get list of all defined fields and its settings (i.e required this field or not).
In Drupal 6 the similar functionality provided by content_fields() function.

Easily Determine if Field Is Required


R programming Function (Returning a subset of Real Mean Squared)

Question: I am new to R and am working on writing some cool functions while I learn statistics in parallel.  I'm trying to make a function that will take a numeric vector, perform the "root mean squared" operations and then have the output return essentially same vector with the possible outliers removed.
For example, if the vector is c(2,4,9,10,100) the resulting RMS would be about 37.
Therefore, I want the output to return the same vector with the possible outlier (in this case, 100) removed from the dataset.  So the result would be 2, 4, 9, 10
I put my code below but the output isn't working.  I tried it 2 different ways.  Everything up to the line that says RMS final works.  But below that it does not.
How can I modify this function so that it does what I want?  Also, as a bonus, and this might be asking a lot but based on my coding below, any tips for a newbie on making functions would be something I'd be grateful for as well. Thanks so much!
RMS_x <- c(2,4,9,10,100)

#Root Mean Squared Function - Takes a numeric vector
RMS <- function(RMS_x){
    RMS_MEAN <- mean(RMS_x)
    RMS_DIFF <- (RMS_x-RMS_MEAN)
    RMS_DIFF_SQ <- RMS_DIFF^2
    RMS_FINAL <- sqrt(sum(RMS_DIFF_SQ)/length(RMS_x))

    for(i in length(RMS_x)){
            if(abs(RMS_x[i]) > RMS_FINAL){
                  output <- RMS_x[i]}
                  else {NULL} }
    return(output)
}

#Root Mean Squared Function - Takes a numeric vector
RMS <- function(RMS_x){
  RMS_MEAN <- mean(RMS_x)
  RMS_DIFF <- (RMS_x-RMS_MEAN)
  RMS_DIFF_SQ <- RMS_DIFF^2
  RMS_FINAL <- sqrt(sum(RMS_DIFF_SQ)/length(RMS_x))

    #output <- ifelse(abs(RMS_x) > RMS_FINAL,RMS_x, NULL)
  return(RMS_FINAL)
}

Answer: Try following in the first lines of the RMS function.
RMS <- function(RMS_x) {
   bp <- boxplot(RMS, plot = FALSE)
   RMS_x <- RMS_x[!(RMS_x %in% bp$out)]
   ...

Now, you have RMS_x sans the outliers.
The boxplot function has a way of determining the outliers. Here, I am using that to remove them.
Comment: I wanted to fix it as an exercise to learn R and not really to accomplish anything in particular.  And so I don't really want to use a boxplot.  I just want to learn how to make it work the way I had envisioned.  But I do thank you for the effort.
Answer: Since you are asking more specifically about R and R functions I'll focus my response on that. There are a couple errors I'll point out then provide a few alternative solutions.
Your first function isn't producing the output you want for two reasons:

The logic instructs the function to return a single value rather than a vector. If you're trying to load a vector within your for loop (one without the outlier) make sure to initialize the vector outside of the function : output <- vector() (note that in my solution below however this is not required). Also the value it is returning is just a value in your vector RMS_x  that is greater than the RMS rather that finding an outlier, just fyi if that's what you wanted.
There's an error and/or typo in your for loop argument, it's minor but it turns your for loop into not-a-loop whatsoever – which is obviously the total opposite of what you intended. The for loop needs a vector to loop through, the argument should be: for(i in 1:length(RMS_x))

In your code the loop is jumping straight to i = 5 because that is the length of your vector (length(RMS_x) = 5). Given that the values in the RMS_x vector were already in ascending order your code happens to give the "right" answer but that's just because of how you initially loaded the vector. This may have been a typo in your question, and it's a difference of only 2 code characters, but it totally changes what the function looks for.
Solution:
To get what you are trying to accomplish, you need to write two functions: 1.)  that defines what's considered an outlier in your data set and 2.) a second function that strips out the outliers and calculates RMS. Then from there either make the functions independent or nest them to pass variables (this kind of goes with your bonus request as well since it's multiple ways of writing functions).
Function to identify outliers:
outlrs <- function(vec){

 Q1 <- summary(vec)["1st Qu."]
 Q3 <- summary(vec)["3rd Qu."]

 # defining outliers can get complicated depending on your sample data but
 # your data set is super simple so we'll keep it that way
 IQR <- Q3 - Q1
 lower_bound <- Q1 - 1.5*(IQR)
 upper_bound <- Q3 + 1.5*(IQR)

 bounds <- c(lower_bound, upper_bound)
 return(bounds)
 assign("non_outlier_range", bounds, envir = globalEnv())

 # the assign() function will create an actual object in your  environment
 # called non_outlier_range that you can access directly - return()
 # just mean the result will be spit out into the console or into a variable
 # you load it into

}

Now moving on to the second function, a few options here:

First Way:  Input bounds argument into RMS_func()

RMS_func <- function(dat, bounds){

 dat <- dat[!(dat < min(bounds)) & !(dat > max(bounds))]

 dat_MEAN <- mean(dat)
 dat_DIFF <- (dat-dat_MEAN)
 dat_DIFF_SQ <- dat_DIFF^2
 dat_FINAL <- sqrt(sum(dat_DIFF_SQ)/length(dat))

 return(dat_FINAL)

}

# Call function from approach 1 - note that here the assign() in the
# definition of outlrs() would be required to refer to non_outlier_range:

RMS_func(dat = RMS_x, bounds = non_outlier_range)

Second Way: Call outlrs() inside the second function

 RMS_func <- function(dat){

 bounds <- outlrs(vec = dat)

 dat <- dat[!(dat < min(bounds)) & !(dat > max(bounds))]

 dat_MEAN <- mean(dat)
 dat_DIFF <- (dat-dat_MEAN)
 dat_DIFF_SQ <- dat_DIFF^2
 dat_FINAL <- sqrt(sum(dat_DIFF_SQ)/length(dat))

 return(dat_FINAL)

}

# Call RMS_func - here the assign() in outlrs() would not be needed is not
# needed because the output will exist within the functions temp environment
# and be passed to RMS_func
RMS_func(dat = RMS_x)

Third Way: Nest outlrs() definition within the RMS_Func - in this case you only need one nested function to accomplish your task

 RMS_Func <- function(dat){

    outlrs <- function(vec){

    Q1 <- summary(dat)["1st Qu."]
    Q3 <- summary(dat)["3rd Qu."]
    #Q1 <- quantile(vec)["25%"]
    #Q3 <- summary(vec)["75%"]

    IQR <- Q3 - Q1
    lower_bound <- Q1 - 1.5*(IQR)
    upper_bound <- Q3 + 1.5*(IQR)

    bounds <- c(lower_bound, upper_bound)
    return(bounds)

  }

bounds <- outlrs(vec = dat)

dat <- dat[!(dat < min(bounds)) & !(dat > max(bounds))]

dat_MEAN <- mean(dat)
dat_DIFF <- (dat-dat_MEAN)
dat_DIFF_SQ <- dat_DIFF^2
dat_FINAL <- sqrt(sum(dat_DIFF_SQ)/length(dat))

return(dat_FINAL)

}

P.S. Wrote this pretty quickly - will likely re-test and edit later. Hopefully for now this helps.


Can nsupdate.exe on Windows updates BIND on Linux?

Question: Can nsupdate.exe on Windows (from BIND for Windows) updates a BIND DNS server on Linux?
Answer: Should be no problem, all the protocols should be the same in the client if you're taking it from a BIND build for Windows and running against a BIND server.  Test it on a development BIND server before using in production if you're not sure about it.  I'd also recommend making sure you are using the same version on the client as you are on the server.


Snapsvg - get height and width of text element

Question: I am altering the  elements contents using
svgTextLines[name].node.innerHTML = line.val();
svgTextLines[name].node.textContent = line.val();

and trying to get the height and width of the element after the content has changed but I cant seem to find any property in the elemement.node object that gets updated. As the element has not transformed I can understand why but is there a way I can get this information?
Regards
Comment: getBBox is the way to go.
Comment: getBBox will only return the bounding box of a transformed element wont it? its not transformed.
Comment: I've no idea what you mean. If you explain with examples what you want and why getBBox does not give you the values you want that would be helpful.
Comment: @RobertLongson I'm doing this but I'm getting zeros in all even though it was added to the DOM and it has text.
Comment: @kuhaku I suggest you ask your own question with a [mcve]
Answer: I'm using SnapSVG and I had the same problem.
You can use getBoundingClientRect to get an object with this parameter.
var s = Snap("#svg");
Snap.load("mascot.svg", function (f) {
  s.append(f);
  var rect = s.searchAll("g")[0];
  var dimens = rect.node.getBoundingClientRect();
  console.log(dimens.width)
});


Logic App Standard using Azure Free Account

Question: Is it possible to create a Logic App Standard using Azure Free Account ? When I try creating a Logic App standard I get the below error.
{"code":"InvalidTemplateDeployment","details":[{"code":"ValidationForResourceFailed","message":"Validation failed for a resource. Check 'Error.Details[0]' for more information.","details":[{"code":"SubscriptionIsOverQuotaForSku","message":"This region has quota of 0 WorkflowStandard instances for your subscription. Try selecting different region or SKU."}]}],"message":"The template deployment 'Microsoft.Web-LogicApp-Portal-0d4d6b7c-81c9' is not valid according to the validation procedure. The tracking id is 'e27f567b-756f-4ea8-bf6d-dcb0d2c21329'. See inner errors for details."}
Get the same error if I try creating an App Service Plan.
{"code":"InvalidTemplateDeployment","message":"The template deployment 'Microsoft.Web-ASP-Portal-6840ee67-88e4' is not valid according to the validation procedure. The tracking id is 'a7cb9292-0509-487b-b628-e1d9e8969b45'. See inner errors for details.","details":[{"code":"ValidationForResourceFailed","message":"Validation failed for a resource. Check 'Error.Details[0]' for more information.","details":[{"code":"SubscriptionIsOverQuotaForSku","message":"This region has quota of 0 instances for your subscription. Try selecting different region or SKU."}]}]}
My billing shows I have $200 credit remaining.
Comment: @Skin, yes, I did try multiple regions. Tried US East, West, Japan East, Australia East
Comment: @Skin, i was finally able to create it after upgrading to a Pay as You Go account.
Answer: I was able to create it after upgrading to a Pay as you go account.
Answer: I ran into the same problem just now and did not want to risk expenses by upgrading to pay-as-you-go.
I was able to create a Logic App by selecting Plan Type: "Consumption" (instead of "Standard") in the apps basic settings.


How do you differentiate a Laplace transform?

Question: Consider the Laplace transform of $\color{green}{t\cfrac{\mathrm{d^2}f}{\mathrm{d}t^2}}$:
$$\mathcal{L}\left[{t\cfrac{\mathrm{d^2}f}{\mathrm{d}t^2}}\right]=\int_{t=0}^{\infty}e^{-st}{t\cfrac{\mathrm{d^2}f}{\mathrm{d}t^2}}\mathrm{d}t=-\cfrac{\mathrm{d}}{\mathrm{d}s}\int_{t=0}^{\infty}e^{-st}{\cfrac{\mathrm{d^2}f}{\mathrm{d}t^2}}\mathrm{d}t=\color{red}{-\cfrac{\mathrm{d}}{\mathrm{d}s}\left[s^2\widetilde f(s)-sf(0)-f^{\prime}(0)\right]}=\color{blue}{-s^2\cfrac{\mathrm{d}\widetilde f}{\mathrm{d}s}-2s\widetilde f +f(0)}$$
Could someone please explain/show the steps that were taken to get from the $\color{red}{\mathrm{red}}$ expression to the $\color{blue}{\mathrm{blue}}$ expression?
Thanks.
Comment: This is not really about Laplace transforms.  Just think of $f(s)$ as any differentiable function, and the two expressions are equivalent: just use the product rule.
Comment: @Erick Your right, the Laplace transform is not the subject of this question but it is the context of this question. I still have no idea how to get from red expression to blue one. You said use the product rule, where is the product then? I'm afraid I need you to literally spell it out for me step by step in an answer then i'll accept it. And by the way, it must be something simple as what I have written here is actually from a textbook, so they just went straight from red to blue with no explanation.
Answer: $s^2 \tilde{f}(s)$ is the product of the functions $s^2$ and $\tilde{f}(s)$.  By the product rule, the derivative of $s^2 \tilde{f}(s)$ with respect to $s$ is $$s^2 \frac{d\tilde{f}}{ds} + 2s \tilde{f}(s)$$.
$f(0)$ is constant (does not depend on $s$).  The derivative of $sf(0)$ is $f(0)$.  $f'(0)$ is also constant.  Its derivative is zero.
Comment: Thank you very much, exactly what I needed to see (+1)


Updating Values of a table from same table without using a select query

Question: My Requirement
 Updating Values of a table from same table without using a select query
    this query won't effect any rows.
    My aim : Update val2 of #table where slno=1 with the value of val2 of slno=2
      Is there any other way without doing this method
 Declare @val2 nvarchar(50)
  select @val2=val2  from #table where slno=2
  update #table set val2=@val2 where slno=1

    create table #table
    (
     slno int identity(1,1),
     val nvarchar(50),
     val2 nvarchar(50)
    )

    insert into #table(val,val2)values('1',newID())
    insert into #table(val,val2)values('1',newID())
    insert into #table(val,val2)values('1',newID())

    select * from #table

    update #table set val2=T.val2
      from #table T where slno=1 and T.slno=2

      drop table #table

I have lot of records in the table.
So If i am selecting and update it may effect the performance.
Answer: Please, provide more info.
Do you have only 2 rows in your table?
Why do you need this kind of update?
I suppose, that your db structure is wrong, but I can't tell exactly, until you explain why do you need this.
Anyway I can suggest a poor way to do this without using select. You can self join the table. It would be better to have addition column, but if you don't have it, how's you should do
    UPDATE T1
    SET T1.val2 = T2.val2
    FROM #table T1 INNER JOIN #table T2
       ON T1.slno = 1 AND T2.slno = 2


Backwards many-to-many relationship with Proxy models in Django

Question: I have a model name 'Group' with a ManyToMany relationship with the Django User, and a 'Membership' table between.
<code>class UserManager(models.Manager):get_query_set(self):
        return super(UserManager, self).get_query_set().select_related('expenses')

class User(DjangoUser):
    objects = UserManager()
    class Meta:
        proxy = True

class Group(models.Model):
    name = models.CharField(verbose_name=_('Name'), max_length=255)
    users = models.ManyToManyField(User, related_name='groups', through='Membership')

class Membership(models.Model):
    user = models.ForeignKey(User)
    group = models.ForeignKey(Group)
    date_joined = models.DateField(auto_now_add=True, verbose_name=_('Date joined'))
</code>
When I try to get the groups for a user, everything is fine:
<code>>>> User.objects.get(id=2).groups.all()
[<Group: Group object>]
>>> User.objects.get(id=2).groups.get(id=1)
<Group: Group object>
</code>
The problem is that I can't get the users for a group:
<code>>>> Group.objects.get(id=1).users.all()
[]
</code>
The one thing I noticed is that the field 'user_id' in my database (generated by django) does not have the foreign key for the auth_user table, but the 'group_id' field has the foreign key for the myapp_group table.
Thanks in advance.
EDIT:
There is clearly something wrong here:
<code>>>> User.objects.get(id=2).groups.get(id=1).users.all()
[]
</code>
Comment: I temporarily found this ugly the ugly solution to add raw sql to the group model:

    def get_users(self):
        return User.objects.raw('SELECT * FROM '+User._meta.db_table+' JOIN '+Membership._meta.db_table+' ON '+Membership._meta.db_table+'.user_id = '+User._meta.db_table+'.id WHERE '+Membership._meta.db_table+'.group_id = '+str(self.id))
Answer: This is unfortunately a documented bug in the Django ORM. You will find more information about it here:
https://code.djangoproject.com/ticket/17299
The best alternative is to simply point to the default model. Since both save to the same place in the database, you can "convert" the returned models from auth.models.User to your proxy user model using the following technique. Make sure you use the one that doesn't hit your database a second time.
Comment: The question is about having a ManyToMany field *to* a proxy model, whereas the referenced Django bug ticket is about having a ManyToMany field *on* a proxy model. Two completely different things.
Comment: I am still unable to get the users for a group. I think your solution would apply if I were unable to get the groups for a user, but that's not a problem.
Comment: Are you sure you are doing it correctly? Change your foreignkey to DjangoUser instead of your proxy user class.
Comment: I tried that. The only thing it did is that I can't get the m2m relation from neither the group or the user or the djangouser. It says: AttributeError: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache'.


Does a first time bar always need a repeat?

Question: I want to notate a piece which finishes in the middle section with a fine, but to do so I need to repeat from the end and then skip a few bars.
Can I put the few bars I need to skip under a 1st time bar with no repeat at the end of the time bar, but rather a DS al Fine at the end of the piece which takes me back before the time bar, and then play through a 2nd time and skip the 1st time bar proceeding to the 2nd time bar and the Fine?
I have never seen a 1st time bar without a repeat sign, but my repeat sign appears after the second time bar at the end as a DS al Fine.
Is this sensible notation?
Comment: Killian are you sure you mean a fermata? The fermata has a specific meaning (extend the note beyond the notated length) which is very different to the function of D.S. Al Fine, and I've not seen it used in the way you describe. That aside I would agree with the rest of your answer, of using a D.S. Al Fine at the end of the piece, a segno at the re-entry point, and a Fine to mark the end point.
Comment: I'd go with  Da Capo al Segno and place the sign where you want to jump to the Fine section.
Comment: You don't need a repeat sign for this. In addition to the "Fine" sign (traditionally this was just a fermata), there are also various "reentry" signs which mean exactly what you want: "when returning from the middle section, jump here rather than to the very beginning". (I'm leaving this as a comment because I don't have a handy link to a notation example.)
Comment: A fermata over a barline is an old equivalent of 'Fine'.
Answer: It sounds like you want D.S. al Fine - and not "Da Capo al Segno" as given in the comments to your question, which I believe is incorrect.

D.S. = "dal segno", or "from the sign", i.e. go to the sign (an ornate "S" shape)
al Fine = "to the end".

In full: "go from the sign to the end"
The suggestion "Da Capo al Segno" does not make sense. "Da Capo" means "from the head" (i.e. the beginning). It would be very confusing to be instructed to "go from the start to the sign", because the sign/Segno (that ornate "S") is conventionally a place you start at, not finish at.
Your solution of a 1st-time bar (at the start, if I read you right) without a repeat sign would be confusing and unconventional. The proper way is (assuming I've understood your question correctly) - as you say yourself - to use "D.S. al Fine". By the way: it's normal to put a double barline where you have your Fine. This reinforces for the player that there's something special about that barline.
If you want the ending to be slightly different to when it's played the first time, you should additionally use a Coda, which is probably beyond the scope of this answer.
Answer: There is no hard and fast rules about the use of repeats in notation. You are just governed by the need to make your score as easy to read as possible.
I have seen pieces where a repeat is used to add brevity to a piece but I have also seen repeats omitted. It will all depend on whether you think it would be easier to just keep on reading the score or go back to the beginning for a repeat.
Just keep in mind if you are on a second page and you repeat from the beginning then it is going to pretty hard to easily start sight reading from the beginning.
Your eyes are very quickly going to have to scan all the way back to the beginning of the first page. It could be very easily for an inexperienced sight reader to loose the tempo like that. Especially if the tempo of the piece is resembling anything fast.
Answer: You can notate however you like as long as it's clear.
I'm not quite clear what you want.  Maybe a DC (or DS) al Coda would fit the job.   Or maybe something like this.  Not standard notation, and a computer scoring program would need persuading to play it back!   But it's clear, and not uncommon in pop song copies.  Just make sure that if you use non-standard notation, it IS clear.  Just a 2X bracket won't cut it here, full instructions are required.

There are levels of permissibility.  In scores to be sight-read at a recording session, even a simple repeated section is a bad idea - write it out.  Where the music will be read, but with rehearsal, repeated sections and coda etc. jumps can be tolerated (but watch out for clumsy page turns if you don't want your music to be fluffed.  Where a score is more for reference than for live performance, we can be much less fussy.


Apache or PHP problem?

Question: Here is my problem. Sorry if the subject was discussed before, but I didn't find it. Also, sorry if the place for my question is not here.
I have a website on a server using Apache 2.04 and PHP 5.
During website navigation, a script creates a .xml file with 755 rights and apache:apache owner. The problem is that this file created is not accessible from a .swf file neither from a different browser window - trying to access it directly by typing it's absolute path.
I discovered that changing owner to root:root, the .xml file became accessible in both situations.
Trying to change owner or rights using PHP function, no changing happened.
Please help me and tell me what can I do in order to fix this problem. It is a PHP configuration?
Thank you in advance.
Comment: +1 for pointing out a common programming pitfall.
it should be fixed by programmers, not by server admins. :)
Answer: Maybe a directory in the full path of xml file is not readable by apache user.
Check permissions of every directory of xml path file, you can try to read directory content:
sudo -u apache ls -l /GRAPHICS/
sudo -u apache ls -l /GRAPHICS/video/
sudo -u apache ls -l /GRAPHICS/video/files/
Maybe you should add apache user to the proper group, but it depens by you user rights on this directory.
Comment: Thank you for your fast answer.
I think so, but how can I fix it? Where to looking for? Apache settings?
Comment: I edited my answer
Comment: For sure you are right about the apache rights. This is my problem! Where to set the rights? In a .htaccess file placed in folder it is ok?
Answer: it's not a php configuration problem or apache problem.
just a programming pitfall.
While uploading or creating new files with PHP,
it always will use default "umask".
if you did not provide correct umask or CHMOD of file,
it may not be accessable by other applications even apache.
(because it's made by your code)
here is link for umask & chmod.
http://php.net/manual/en/function.umask.php
http://www.php.net/manual/en/function.chmod.php
Try to solve the problem with php code.
like: just after you upload or create new file, change chmod of file.
chmod("/somedir/somefile", 0644);
this way is better, efficent, compatible.
Answer: It's possible you're server permissions require 644 for PHP scripts, assuming it gives an Internal Server Error
Comment: Here the error:
You don't have permission to access /GRAPHICS/video/files/video_ro_biz02.xml on this server.

Rather is a problem of owner:group access.

Apache or PHP problem?


STATA - Mean differences between treated and control groups after matching

Question:
Relevant Files:
https://www.dropbox.com/sh/0jnj3txf4stb2q8/AAD58COnAUysul58qG2p5emwa?dl=0

import excel "merge_db_environment_korea_kospi200_findel.xlsx", firstrow
keep if ksic1 != "K"
gen CO2Sale = co2_sale_gr_1000
keep if year<=2019
keep if year>=2011

global control_lag = "lag_size lag_cf_vol lag_capex lag_leverage lag_roa lag_ln_firm_age lag_rnd_sale"
global ESG_lag "lag_E_num lag_G_num lag_S_num"
global d_control_lag = "d_size d_cf_vol d_capex d_leverage d_roa d_ln_firm_age d_rnd_sale"
global d_ESG_lag "d_E_num d_G_num d_S_num"

**teffects nnmatch (CO2Sale ${control_lag} ${ESG_lag} ${d_control_lag} ${d_ESG_lag} i.ksic1_num i.year) (CarbonOffset), gen(match)**

I want to conduct a "t-difference mean test between treated and control groups after matching".

For instance, I can calculate a "t-difference mean test between treated and control groups" before matching like this:

ttest CO2Sale,by(CarbonOffset) level(99) unequal

And I can also calculate an Average Treatment Effect (ATE) like this as well:

teffects nnmatch (CO2Sale ${control_lag} ${ESG_lag} ${d_control_lag} ${d_ESG_lag} i.ksic1_num i.year) (CarbonOffset), gen(match)

However, I don't know how to conduct a "t-difference mean test between treated and control groups after matching". If there is someone who can conduct a similar test, I really want to know how to do it.
Answer: This is a bad idea, so I am adding a solution that demonstrates that.
In this example, the ATE of maternal smoking on birthweight is biased down by ~40%: The ATE from teffects nnmatch is -240 grams, but the corresponding difference from the t-test you propose is only -153 grams.
. /* Setup Data */
. webuse cattaneo2, clear
(Excerpt from Cattaneo (2010) Journal of Econometrics 155: 138–154)

. keep bweight mage mbsmoke prenatal1 mmarried fbaby

. gen id = _n

. order id

.
. /* Store Duplicate Data */
. tempfile copy

. save `copy'
file /var/folders/62/51hy7j9958xd03txmytygwwc0000gn/T//S_57805.000001 saved as .dta format

.
. /* Matching Step */
. teffects nnmatch (bweight mage prenatal1 mmarried fbaby) (mbsmoke), nn(1) gen(match) level(99)

Treatment-effects estimation                   Number of obs      =      4,642
Estimator      : nearest-neighbor matching     Matches: requested =          1
Outcome model  : matching                                     min =          1
Distance metric: Mahalanobis                                  max =        139
----------------------------------------------------------------------------------------
                       |              AI robust
               bweight | Coefficient  std. err.      z    P>|z|     [99% conf. interval]
-----------------------+----------------------------------------------------------------
ATE                    |
               mbsmoke |
(Smoker vs Nonsmoker)  |  -240.3306   28.43006    -8.45   0.000    -313.5616   -167.0997
----------------------------------------------------------------------------------------

.
. /* Get Data Into T-Test Format */
. reshape long match, i(id) j(match_num)
(j = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
> 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
> 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
> 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 1
> 23 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139)

Data                               Wide   ->   Long
-----------------------------------------------------------------------------
Number of observations            4,642   ->   645,238
Number of variables                 146   ->   9
j variable (139 values)                   ->   match_num
xij variables:
             match1 match2 ... match139   ->   match
-----------------------------------------------------------------------------

. drop if missing(match)
(575,801 observations deleted)

. sort id match_num

. rename (id mbsmoke bweight mage prenatal1 mmarried fbaby) =_original

. rename  match id

. merge m:1 id using `copy', nogen keep(match)
(variable id was long, now double to accommodate using data's values)
(label YesNo already defined)
(label mmarried already defined)
(label mbsmoke already defined)

    Result                      Number of obs
    -----------------------------------------
    Not matched                             0
    Matched                            69,437
    -----------------------------------------

. rename (id mbsmoke bweight mage prenatal1 mmarried fbaby) =_matched

. sort id_original

.
. /* Average Over Birthweight in Case There Are Ties */
. /* Or To Keep Only the First Match Uncomment the Next Line */
. // keep if match_num == 1
. collapse (mean) bweight_matched, by(*_original)

.
. /* Hypothesis Test */
. gen effect = cond(mbsmoke_original == "Smoke":mbsmoke, bweight_original - bweight_matched, bweig
> ht_matched - bweight_original)
(value label dereference "Smoke":mbsmoke not found)

. ttest effect = 0, level(99)

One-sample t test
------------------------------------------------------------------------------
Variable |     Obs        Mean    Std. err.   Std. dev.   [99% conf. interval]
---------+--------------------------------------------------------------------
  effect |   4,642   -153.7954    9.362789    637.9077   -177.9223   -129.6686
------------------------------------------------------------------------------
    mean = mean(effect)                                           t = -16.4262
H0: mean = 0                                     Degrees of freedom =     4641

    Ha: mean < 0                 Ha: mean != 0                 Ha: mean > 0
 Pr(T < t) = 0.0000         Pr(|T| > |t|) = 0.0000          Pr(T > t) = 1.0000

Code:
/* Setup Data */
webuse cattaneo2, clear
keep bweight mage mbsmoke prenatal1 mmarried fbaby
gen id = _n
order id

/* Store Duplicate Data */
tempfile copy
save `copy'

/* Matching Step */
teffects nnmatch (bweight mage prenatal1 mmarried fbaby) (mbsmoke), nn(1) gen(match) level(99)

/* Get Data Into T-Test Format */
reshape long match, i(id) j(match_num)
drop if missing(match)
sort id match_num
rename (id mbsmoke bweight mage prenatal1 mmarried fbaby) =_original
rename  match id
merge m:1 id using `copy', nogen keep(match)
rename (id mbsmoke bweight mage prenatal1 mmarried fbaby) =_matched
sort id_original

/* Average Over Birthweight in Case There Are Ties */
/* Or To Keep Only the First Match Uncomment the Next Line */
// keep if match_num == 1
collapse (mean) bweight_matched, by(*_original)

/* Hypothesis Test */
gen effect = cond(mbsmoke_original == "Smoke":mbsmoke, bweight_original - bweight_matched, bweight_matched - bweight_original)
ttest effect = 0, level(99)

Comment: I like the idea of responding to what appears to be a software question by instead addressing a key *statistical* idea.  However, could you indicate specifically what part of all this computer output supports your contention about the bias?  That would make your answer accessible to the vast majority of readers who are not conversant with the Stata language or don't care to pick through all the output for the one or two numbers that might be relevant.
Answer: This doesn't make sense beceause teffects doesn't create a matched sample. You can't just extract the matched units and run a t-test on them. teffects creates pairs and imputes the missing potential outcomes in one group with the paired units in the other group. No units are discarded. If you want the treatment effect estimate, you need to use the ATE output provided by teffects. See my answer here and the links therein for more information on the differences between matching imputation (what teffects does) and matching as nonparametric preprocessing (what almost all papers about matching do). If you want to do matching as nonparametric preprocessing, this is not possible in Stata. The MatchIt package in R and PROC PSMATCH in SAS do allow this, though.


Strange mails from my email server

Question: My postfix server and website (WordPress, Apache) resides on the same server box. 2 days ago, we decided to use 3rd party smtp relay host for our mail server. All the DKIM and spf records are in place. They are also validated as domain by the 3rd party smtp provider.
So far, so good. I received message from the 3rd party provider stating that I need to remove gmail, aol etc. free senders from my validation list. Somehow, some people tries to send mails using our smtp server. Seemingly, this originates from the website. Here is the maillog sniplet to show what is going on:
Maillog excerpt

Mar  2 21:55:13 linsvr postfix/pickup[29824]: 25277220008: uid=48
  from= Mar  2 21:55:13 linsvr postfix/cleanup[31693]:
  25277220008: message-id=<firstname.lastname@example.com>
  Mar  2 21:55:13 linsvr opendkim[25596]: 25277220008: no signing table
  match for 'firstname.lastname@example.com' Mar  2 21:55:13 linsvr
  opendkim[25596]: 25277220008: no signature data Mar  2 21:55:13 linsvr
  postfix/qmgr[9766]: 25277220008: from=, size=638,
  nrcpt=1 (queue active) Mar  2 21:55:13 linsvr amavis[15091]:
  (15091-12) ESMTP :10024
  /var/spool/amavisd/tmp/amavis-20190302T140517-15091-fQptiP_v:
   ->  SIZE=638 Received: from
  mail.mydomain.com ([127.0.0.1]) by localhost (mail.mydomain.com
  [127.0.0.1]) (amavisd-new, port 10024) with ESMTP for
  ; Sat,  2 Mar 2019 21:55:13 +0300 (+03) Mar  2
  21:55:13 linsvr amavis[15091]: (15091-12) Checking: ZnqhsWDKWMOr
  [127.0.0.1]  ->  Mar  2
  21:55:13 linsvr amavis[15091]: (15091-12) p001 1 Content-Type:
  text/html, 7bit, size: 157, SHA1 digest:
  69dbad8db3546a316ce6dbb17f2b13d26c929154 Mar  2 21:55:13 linsvr
  amavis[15091]: (15091-12) wbl: soft-whitelisted (-20) sender
   => , recip_key="." Mar  2
  21:55:29 linsvr amavis[15091]: (15091-12) spam-tag,
   -> , No, score=-6.956
  tagged_above=-999 required=6.2 tests=[AM.WBL=-20, BAYES_99=3.5,
  BAYES_999=0.2, DKIM_ADSP_CUSTOM_MED=0.001,
  FREEMAIL_FORGED_FROMDOMAIN=0.001, FREEMAIL_FROM=0.001,
  FSL_BULK_SIG=0.839, HEADER_FROM_DIFFERENT_DOMAINS=0.001,
  HTML_MESSAGE=0.001, HTML_MIME_NO_HTML_TAG=0.377, KAM_LINKBAIT3=1.5,
  MALFORMED_FREEMAIL=0.001, MIME_HTML_ONLY=0.723,
  NML_ADSP_CUSTOM_MED=0.9, NO_RELAYS=-0.001, RAZOR2_CF_RANGE_51_100=2.5,
  RAZOR2_CHECK=2.5] autolearn=no autolearn_force=no Mar  2 21:55:29
  linsvr postfix/smtpd[31781]: connect from localhost[127.0.0.1] Mar  2
  21:55:29 linsvr postfix/smtpd[31781]: EAD92220007:
  client=localhost[127.0.0.1] Mar  2 21:55:29 linsvr
  postfix/cleanup[31693]: EAD92220007:
  message-id=<email@example.com> Mar  2
  21:55:29 linsvr postfix/qmgr[9766]: EAD92220007:
  from=, size=1708, nrcpt=1 (queue active) Mar  2
  21:55:29 linsvr postfix/smtpd[31781]: disconnect from
  localhost[127.0.0.1] Mar  2 21:55:29 linsvr amavis[15091]: (15091-12)
  ZnqhsWDKWMOr FWD from  -> ,
  BODY=7BIT 250 2.0.0 from MTA(smtp:[127.0.0.1]:10025): 250 2.0.0 Ok:
  queued as EAD92220007 Mar  2 21:55:29 linsvr amavis[15091]: (15091-12)
  Passed CLEAN {RelayedInbound}, [127.0.0.1]  ->
  , Message-ID:
  <firstname.lastname@example.com>, mail_id: ZnqhsWDKWMOr,
  Hits: -6.956, size: 671, queued_as: EAD92220007, 16754 ms Mar  2
  21:55:29 linsvr amavis[15091]: (15091-12) TIMING-SA total 16625 ms -
  parse: 0.74 (0.0%), extract_message_metadata: 8 (0.0%),
  get_uri_detail_list: 0.49 (0.0%), tests_pri_-1000: 2.00 (0.0%),
  tests_pri_-950: 0.76 (0.0%), tests_pri_-900: 1.07 (0.0%),
  tests_pri_-90: 8 (0.0%), check_bayes: 6 (0.0%), b_tokenize: 2.1
  (0.0%), b_tok_get_all: 0.95 (0.0%), b_comp_prob: 1.13 (0.0%),
  b_tok_touch_all: 0.06 (0.0%), b_finish: 0.56 (0.0%), tests_pri_0:
  11061 (66.5%), check_dkim_signature: 0.49 (0.0%), check_spf: 0.25
  (0.0%), tests_pri_10: 4290 (25.8%), check_dcc: 4283 (25.8%),
  tests_pri_20: 1179 (7.1%), check_razor2: 1175 (7.1%), tests_pri_30: 58
  (0.3%), check_pyzor: 56 (0.3%), tests_pri_500: 7 (0.0%), get_report:
  0.80 (0.0%) Mar  2 21:55:29 linsvr amavis[15091]: (15091-12) size: 671, TIMING [total 16757 ms] - SMTP greeting: 1.5 (0%)0, SMTP EHLO:
  0.5 (0%)0, SMTP pre-MAIL: 0.3 (0%)0, SMTP MAIL: 0.8 (0%)0, SMTP pre-DATA-flush: 0.8 (0%)0, SMTP DATA: 41 (0%)0, check_init: 0.4 (0%)0,
  digest_hdr: 0.3 (0%)0, digest_body: 0.1 (0%)0, collect_info: 0.8
  (0%)0, mime_decode: 5 (0%)0, get-file-type1: 15 (0%)0, parts_decode:
  0.1 (0%)0, check_header: 0.3 (0%)0, AV-scan-1: 19 (0%)1, spam-wb-list: 1.1 (0%)1, SA msg read: 0.5 (0%)1, SA parse: 1.3 (0%)1, SA check: 16620 (99%)100, decide_mail_destiny: 8 (0%)100, notif-quar: 0.3
  (0%)100, fwd-connect: 18 (0%)100, fwd-mail-pip: 8 (0%)100,
  fwd-rcpt-pip: 0.2 (0%)100, fwd-data-chkpnt: 0.0 (0%)100, write-header:
  0.3 (0%)100, fwd-data-contents: 0.0 (0%)100, fwd-end-chkpnt: 6 (0%)100, prepare-dsn: 0.6 (0%)100, report: 1.3 (0%)100,
  main_log_entry: 3.5 (0%)100, update_snmp: 1.1 (0%)100, SMTP
  pre-response: 0.2 (0%)100, SMTP response: 0.2 (0%)100, unlink-2-files:
  0.2 (0%)100, rundown: 0.6 (0%)100 Mar  2 21:55:29 linsvr postfix/smtp[31699]: 25277220008: to=,
  relay=127.0.0.1[127.0.0.1]:10024, delay=17, delays=0.07/0.01/0/17,
  dsn=2.0.0, status=sent (250 2.0.0 from MTA(smtp:[127.0.0.1]:10025):
  250 2.0.0 Ok: queued as EAD92220007) Mar  2 21:55:29 linsvr
  postfix/qmgr[9766]: 25277220008: removed Mar  2 21:55:30 linsvr
  postfix/smtp[31784]: EAD92220007: to=,
  relay=in.mailjet.com[188.8.131.52]:25, delay=0.5,
  delays=0.01/0.02/0.4/0.07, dsn=2.0.0, status=sent (250 OK queued as
  49e13879-c3e9-4012-ba3a-c7caff2b9d41) Mar  2 21:55:30 linsvr
  postfix/qmgr[9766]: EAD92220007: removed}

Can someone enlighten me on this? And how to fix?
Thanks.
Comment: Not sure what exactly they asked of you. You may be an open relay perhaps. But as a random note: most self-hosting e-mail servers from the companies I know of have the top 2 deny all positions occupied by AOL and hotmail. 99.98% of what's coming from there is confirmed spam.
Comment: They ask us to delete any gmail, hotmail, etc address in the sender list. It is not open relay as confirmed by some testing sites. However, I suspect that someone has got the username:password of a legitimate user or WordPress site has a security problem. The code sniplet show that those email originates from the website. But, I don't know how.
Comment: This is strange, why would you authorize such senders initially ?
Answer: The Postfix pickup process seems to be indicating that these messages are being generated locally by the apache user.
Is your WordPress version up to date with security updates? If not, it's probably being hacked. The intruder may have used a WordPress vulnerability that allows them to submit a PHP script of their own to be run by WordPress, and that script is acting as an unauthorized email generator/forwarder. They might even be doing that separately for each email they're sending, and making the script delete itself as it's done its deed.
Otherwise, do you have an unprotected or vulnerable email sending script (PHP, CGI or whatever) in your website?
Your Postfix email server might not be an open relay, and that is what those testing sites are likely to be testing; but something in the Apache + PHP + WordPress combination is allowing the intruder to get in and use the local facilities to send email out. And as far as Postfix is concerned, those messages are originating locally, so they are not subject to relay checks.
As a result, even though your Postfix may not be an open relay, your server taken as a whole effectively is. The intruder just needs to use a bit more complex protocol than plain SMTP to submit messages, but the "exploit an unpatched WordPress" protocol is very well known among spammers.
Comment: This is my guess also.
Comment: WordPress was not updated untill 2-3 days ago. I think you are right. The must be a problem with Apache + PHP + WordPress. I had plugin for newsletter. Deactivated now. I will check it carefully and report if I find anything.

Thank you.

Strange mails from my email server


A partir de um checkbox selecionado, pegar o valor de um atributo data proximo

Question: Boa tarde,
eu tenho um checkbox selecionado (check = true)

        <input type="radio" id="cat5" name="rd_categoriaRamal" value="cat5" checked>

    Cat. 5
    Cat. 5

e eu quero pegar o valor do data-content que está perto dele:
"data-content="Ligações locais, celular e DDD."

eu tentei com esse codigo aqui, porem sem sucesso:
var explicacaoCategoriaRamal    =   $('input[name=rd_categoriaRamal]:radio:checked').closest("span .fluigicon").data("content");

Alguem consegue me explicar porque não está dando certo? Tentei algumas variações disso sem sucesso.
Comment: Tenta assim `var explicacaoCategoriaRamal    =   $('input[name=rd_categoriaRamal]:radio:checked').closest("span .fluigicon").attr("data-content");`
Comment: Infelizmente, assim não funciona. Dá undefined.
Answer: Tens de subir no DOM até .input-group-addon, procurar o sibling .input-group-addon e depois procurar um descendente com data-content.
Poderia ser assim:

$(':checkbox').on('change', function() {
  var data = $(this)
    .closest('.input-group-addon')
    .nextAll('.input-group-addon:first')
    .find('[data-content]')
    .data('content');
  console.log(data);
});

        <input type="checkbox" id="cat5" name="rd_categoriaRamal" value="cat5" checked>

    Cat. 5
    Cat. 5

Comment: @leonardopessoa Usar `.data('content')` vai pegar o atributo `[data-content]`, como você pode ver aqui: https://api.jquery.com/data/.
Comment: @leonardopessoa como o AP escreveu `pegar o valor de um atributo` achei esta a melhor solução. Não sei de `.attr` será a melhor solução por causa [da maneira como o jQuery lê campos `data-`](http://pt.stackoverflow.com/a/50355/129)
Comment: Compreendido. Obrigado pelo esclarecimento!
Comment: Excelente resposta, funcionou aqui. Eu tentei fazer algo parecido com o children sem sucesso. Vlw pela resposta.
Comment: Entendi que ele queria pegar o valor dentro do atributo `data-content`, não? Com isso, sugiro a função `.attr('data-content')` do jQuery http://api.jquery.com/attr/