How do you upgrade PHP 5.1 to PHP 5.3 using yum on CentOS

Question: Using Yum/CentOS.
The problem is that php 5.1 is already installed and running so

yum update php

dont work!
I looked around the net for a solution but they say to do the above =/
Comment: There are a bunch of answers here on serverfault.
Comment: See: http://serverfault.com/questions/106801/recommended-method-to-upgrade-php-5-1-6-to-5-2-x-on-centos-5
Comment: You do realise that CentOS has different versions, right?
Comment: possible duplicate of [How do I install php 5.3 on CentOS?](http://serverfault.com/questions/221251/how-do-i-install-php-5-3-on-centos)
Comment: @codeninja: Please state which CentOS 5 version you are using (5.1? 5.3? 5.6? 6.1?), because that is an important difference. php53 wasn't included with RHEL/CentOS/SL until version 5.6. Many answers say you need third party repositories, but that is no longer necessary. Those answers are now outdated. See my answer below for more information.
Comment: There really isn't any CentOS version but the latest; if you initially installed CentOS 5.1 and kept up with patches, you have 5.6. (And if you haven't kept up with patches, please don't install PHP.)
Answer: You'll want to yum install php53. Unfortunately, you will need to remove php (which is php 5.1, see below) first.
php53 is available in CentOS as of CentOS 5.6 and above. It is not available in CentOS 5.5 and previous, unless you go through a third-party repository. That is why many answers on Serverfault tell you to use third party repositories-- that's not necessary anymore.
Note that php53 has many dependencies, so you should consider updating CentOS to the latest CentOS 5.x branch as part of this upgrade (which is CentOS 5.6 as of this writing). This is a major upgrade of PHP, and RedHat forced it through because they were way behind the times as of RHEL5.5.
Note how the package is named php53, while php is php 5.1:
$ yum info php53
Available Packages
Name       : php53
Arch       : x86_64
Version    : 5.3.3
Release    : 1.el5_6.1
Size       : 1.3 M
Repo       : updates
Summary    : PHP scripting language for creating dynamic web sites
URL        : http://www.php.net/
License    : PHP and LGPLv2 and LGPLv2+
Description: PHP is an HTML-embedded scripting language. PHP attempts to make it
           : easy for developers to write dynamically generated webpages. PHP also
           : offers built-in database integration for several commercial and
           : non-commercial database management systems, so writing a
           : database-enabled webpage with PHP is fairly simple. The most common
           : use of PHP coding is probably as a replacement for CGI scripts.
           :
           : The php package contains the module which adds support for the PHP
           : language to Apache HTTP Server.

$ yum info php
Available Packages
Name       : php
Arch       : x86_64
Version    : 5.1.6
Release    : 27.el5_5.3
Size       : 2.3 M
Repo       : base
Summary    : The PHP HTML-embedded scripting language. (PHP: Hypertext Preprocessor)
URL        : http://www.php.net/
License    : The PHP License v3.01
Description: PHP is an HTML-embedded scripting language. PHP attempts to make it
           : easy for developers to write dynamically generated webpages. PHP also
           : offers built-in database integration for several commercial and
           : non-commercial database management systems, so writing a
           : database-enabled webpage with PHP is fairly simple. The most common
           : use of PHP coding is probably as a replacement for CGI scripts.
           :
           : The php package contains the module which adds support for the PHP
           : language to Apache HTTP Server.

Comment: Yep - notice the version postfix.  So now php 5.5 would be php55...
Answer: You need any additional repo to upgrade php as php 5.3 is not yet included in the CentOS Base Repo. You can use the atomic repo which works for me flawlessly,
wget -q -O - http://www.atomicorp.com/installers/atomic | sh
yum upgrade php
yum -y remove atomic-release*

This will install the atomic repo, upgrade php and then remove the atomic-repo (to make sure that any future system update won't install any additional packages from atomic).
Comment: @Stefan Lasiewski It is from my personal reference doc and not a cut-n-paste answer. I would have added the source if it was from some other source actually, but it is not.
Comment: This is not necessary, and also has some disturbing repercussions. For one, now you've not got an easy source for updates for php, and while php is better than it was for a while there, php is generally something you want to stay on top of security patches for.
Comment: This answer looks very similar to http://serverfault.com/questions/106801/recommended-method-to-upgrade-php-5-1-6-to-5-2-x-on-centos-5-4/106871#106871 . If you cut-n-paste this answer from another answer, please cite the original answer. If this is from the Atomic documentation, then please link to the original documentation.
Comment: @mattdm : it use to work for me without any trouble. Actually the packages are from a well know 3rd party repo. So, if you are aware of any repercussions, please enlighten me.
Comment: @Stefanl Thank you for the head-up to centos 5.6 release notes :)


what's the difference between exporting a component and importing its module in another module?

Question: when working in Angular, let's say we have module A and module B, if I want to use "A-component" inside components of module B, then what's the difference between importing module A inside Module B
, and adding the "A-component" in the exports of module A ?
I tried both, and I think they are not the same thing, this is confusing.
Comment: if you want to use A-component directly in  module B you have to export it and import the exporting module. *

I think im missing some part of your question
Comment: A component can only "declared" in one (and only in one) Module. This is the reason that components that we want use in severals modules (generally utils components) should be declared and exported in one module that is imported by the others modules
Answer: You need to export and import, not just one.
Unless you use default exports, your code would need to look something like this:
a.mjs
export class myClass {
  ...
}

b.mjs
import { myClass as myClassFromA } from './a.mjs'

or with default exports:
a.mjs
export default class myClass {
  ...
}

b.mjs
import myClassFromA from './a.mjs'

Answer:
importing module A inside Module B
It means that you would like to access inside Module B components, pipes, directives and sevices from module A
adding the "A-component" in the exports of module
It means that you are making this component accessible for those who is using module A
Answer: Angular based on Dependency injection. For example, you want to use A-component from B-module, you NEED to export A-component from A-module and import A-module in B-module.
What if you directly use A-component without exporting?
Then, you have to provide all dependencies of A-component in B-module, so it's a bad practice. It's better to export it from module.


Recording Yamaha Keyboard Audio on Macbook Pro

Question: I have a Yamaha P45 whose audio I want to record on my Macbook Pro. I followed instructions from this video so to summarize:
I have a 3.5mm stereo y-splitter plugged into the Yamaha P45, and two patch cables running from the y-splitter: one into my Audio-Technica headphones, and the other into a StarTech TRRS adapter that I have plugged into my Macbook Pro. When I play keys on the piano, I can hear them in my headphones so the y-splitter probably isn't the issue.
The only input audio I see listed when I try recording with any software is the built-in microphone (internal), so the keyboard's audio isn't getting picked up by the Macbook Pro.
As an aside, I do notice that if I plug my Apple headphones into the headphones port of the y-splitter I can receive audio output from the Macbook Pro.... so does that mean the y-splitter should be able to capture the keyboard's input or that it actually is capturing the keyboard's input but the Macbook Pro just isn't recognizing it?
Answer: Edit: I tried a few advanced settings on my MacBook Pro 2017 in Launchpad and audio input only has the built in mic as an option. The headphone jack is now just that, no line input option. I assume you have a fairly recent MacBook. I found this on an Apple support site: https://discussions.apple.com/thread/7086508
Sorry for the bad news. I'm not surprised Apple has removed such a basic function from their laptops. Your best bet if cost is a issue is to look for a used audio interface. Make sure you check for compatibility with your machine and OS. There are some inexpensive usb-C adapters that give you audio as well but these are probably sketchy.


Unable to resolve "expo-app-loading" from "App.js"

Question: I am getting this error:

Failed building JavaScript bundle. Unable to resolve
"expo-app-loading" from "App.js"

when I ran my project after a couple of months. Earlier it was working fine but not now.
Can someone please help me out?
Comment: Welcome to Stack Overflow ! Please add some code snippet to reproduce the error. (https://stackoverflow.com/help/how-to-ask)[https://stackoverflow.com/help/how-to-ask] Please read this.
Comment: Please post your package.json too and the part where you use App Loading
Answer: If you recently updated SDK versions (expo upgrade), please be sure to review the breaking  changes carefully as is advised when you complete the install.
For instance, SDK-40 which was released in December has breaking changes notes about expo-app-loading that probably addresses what you're seeing perfectly.
Read this page : https://blog.expo.io/expo-sdk-40-is-now-available-d4d73e67da33
Look for section title: AppLoading has been extracted from the expo package
Answer: There were two problems:

expo-app-loading was not in my package.json, so I just installed it again and boom, it was in my packege.json then.

I was importing 'AppLoading' the wrong way. I wrote
 import {AppLoading} from "expo-app-loading";  //wrong way

Which was breaking. Then I corrected it to
 import AppLoading from "expo-app-loading";    //correct way

Which solved the issue.

Unable to resolve “expo-app-loading” from “App.js”


Multiple sliders on page

Question: Hello everyone I'm using this plugin http://www.jqueryscript.net/slider/Fullscreen-Horizontal-Page-Slider-with-jQuery-CSS3-HSlider.html and I want to have more than one slider on single page. Here is my code:
        height = $( window ).height() - 98;
    transalte = (height/2);
    $.each($('.gallery section'),function(i){
        $(this).css({
            position:"absolute",
            width:"100%",
            height: height+'px',
            left:i*100 +"%"
        }).addClass("section").attr("data-index", i+1);
        $(this).find(".img").css({
            minWidth: "100%",
            minHeight: "100%",
            position:"absolute",
            zIndex:5
        })
        $(this).find("article").css({
            position:"absolute",
            width:"100%",
            height: '100%',
            bottom:0,
            padding:42,
            zIndex:6,
            'transform':'translateY(-'+(height+10)+'px)',
            'color': 'white',
        })
    });

I tried to reset i in each function but it doesn't works properly. It adds next data-index to section in another gallery. Is there any way to make multiple sliders using this plugin?
Comment: If you don't mind changing to another plugin, [fullpage.js](http://alvarotrigo.com/fullPage/) allows exactly that. Multiple sliders, all of them full screen.
Answer: What is it exactly you want to accomplish? By looking at the demo and your question, it seems to me that you want to add multiple slides (images) to one gallery.
In this case, move all of your
 into one wrapping
 and initialize the plugin as shown on the page.
$(".slider").HSlider();

Does this help?
Comment: No, it doesn't work. It just add slider to one gallery.

Multiple sliders on page


Defining a PHP variable using a field

Question: Is is possible to define a PHP variable using a field?
eg. In the field a contributor would enter [ABC]
which would translate to: <?php $VARIABLE = '[ABC]'; ?>
which would be repeatedly used in the node as:
<img src="http://www.example.com/<?php echo "$VARIABLE"; ?>/image_01.jpg/>
<img src="http://www.example.com/<?php echo "$VARIABLE"; ?>/image_02.jpg/>

etc
Comment: Why would you want the user to define the path of the images?
Comment: I would look into the https://drupal.org/project/token_filter or https://drupal.org/project/customfilter modules as I think they solve what you are trying to ask here
Comment: Sorry I meant contributor, not user - edited.

Unfortunately those modules will not work.

I am essentially trying to post a buzz feed image list style article. The images live on an external server in a static location. The variable needs to be set to define the folder location and the file name (among other things). I have tried to simplify the problem to the lowest common denominator in the hope I would get the simplest answer giving me a starting point (at the minute I am completely lost)
Comment: Btw you should rethink the title of this question.
Answer: You could create a simple text field to store the string, and then a custom formatter to render it as an image. Then under "Manage display" for the content type, you choose the formatter you just created.
If you don't want to create the custom formatter programmatically, you could use the Custom formatters module.
If you want to use the value of the text field for more than one output element, you could create Display suite custom fields using this value e.g. as a token.
Answer: What you're asking for (linking remote images) can be done the File Field Sources module. This way for instance drupal will "copy down" the remote image locally and you may use Image Styles and other things to theme it (locally). If the remote image is deleted or the URL changes you're website in turn will not break.

FileField Sources is an extension to the FileField module. The
  FileField module lets you upload files from your computer through a
  CCK field. The FileField Sources module expands on this ability by
  allowing you to select new or existing files through additional means,
  including:

Re-use files by an auto-complete textfield
Attach server-side files uploaded via FTP
Transfer files from a remote server (cURL required)
Paste a file directly from the clipboard (Drupal 7 only)
Select existing files through the IMCE file browser

Although FileField
  Sources provides several built-in sources, it can be extended by any
  module through an API for creating new sources. Users can toggle
  between any of the available methods for selecting a file.

See these Additional File Field Sources add-on Modules.
Retrieving the remote image to a local version is the "typical" Drupal pattern here. If you want the specific drop-downs for certain remote paths or folders -- try to extend the feature-set by using their API to write your own little dialog similiar to the default ones (see the project page) and have its form values be your desired criteria.
EDIT:
it looks like the AmazonS3 module can work with the FileFieldSources module from this issue https://drupal.org/node/1585188. It stores/retrieves files to your S3 account. I still think you can use the FileFieldSources API to build whatever interface you need to poke, prod and otherwise fetch data from Amazon for your images and feeds. In short I would try to use the AmazonS3 module + FileFieldSources as the groundwork to create you're own custom UI for your contributors.
Comment: Unfortunately our images exist on a remote amazon server because we have been using a massive amount of bandwidth (250gb a day) and having images locally is not an option.
Comment: If I find an answer to my OP I will use the information to create a content type that enables my contributors to create an image based articles similar to this one:

http://www.newageman.co.uk/14-time-travelling-celebrities
Comment: These articles are currently being produced using php code that lives in the body area but as my contributors are not developers I wanted to give them text fields only to work with
Comment: @user3169181 please see my edit. If I were you I'd try to avoid hand crafting all this stuff by hand -- and try to leverage existing module based APIs. Without more details this is the best help I can offer at this time.

Defining a PHP variable using a field


Create a set of macros to define a type called RETURN_STATUS and the following values:

Question: I'm attempting to complete an O'reilly textbook on my own. I'm at a point where I really dont understand what's going on anymore. I read the chapters but simply dont know what to do when I get to the programming exercises. I know this problem looks like it should be easy but I have no idea.
The question:
Create a set of macros to define a type called RETURN_STATUS and the following values: RETURN_SUCCESS, RETURN_WARNING, and RETURN_ERROR. Define a macro, CHECK_RETURN_FATAL,,, that takes a RETURN_STATUS as its argument and returns true if you have a fatal
e r r o r.
my approach:
#include <iostream>

#define RETURN_STATUS RETURN_SUCCESS RETURN_WARNING RETURN_STATUS RETURN_ERROR
#define CHECK_RETURN_FATAL (RETURN_STATUS)

int main()
{
    if (RETURN_STATUS == RETURN_ERROR)
        return true;
    else
    return false;

    return 0;
}

This is just some BS I threw together hoping that a miracle would happen. I was wrong. An explanation of what I'm really supposed to do would be perfect. Thanks.
Comment: I think the first step would be to create a **type** `RETURN_STATUS` using a macro. The "following values" indicate (to me) that it's an `enum`.
Answer: In C/C++ macro definitions consist of identifiers on the left side and stuff on the right side with which each occurrence of the macro is replaced in the body of your program. This mechanism is useful when you need to use a constant in multiple places (C++ provides better mechanisms for situations like that, but since your question asks about preprocessor, let's concentrate on it).
For example, you can define a type of RETURN_STATUS to be an int, like this:
#define RETURN_STATUS int

Now you can define the constants by choosing integer constants for their values, like this:
#define RETURN_SUCCESS 0
#define RETURN_WARNING 1
#define RETURN_ERROR 2

Finally, you can check the return status for error with this macro:
#define CHECK_RETURN_FATAL(s) (s == RETURN_ERROR)

Here is how you can use these definitions in a real code:
RETURN_STATUS check_password(const string& pwd) {
    if (pwd.size() == 0) return RETURN_ERROR;  // Empty passwords are not allowed
    if (pwd.size() < 8) return RETURN_WARNING; // Short passwords are bad
    return RETURN_SUCCESS;
}

...
string pwd("tiger");
RETURN_STATUS checkPwdStatus = check_password(pwd);
if (CHECK_RETURN_FATAL(checkPwdStatus)) {
    cerr << "Password check failed." << endl;
}

Comment: @MauriceAbney Most people say, if you can avoid a macro, you should avoid it. Macros do have their place/usages though. You'll most certainly see some macros "later in life" so you should at least know the basics. I'd say this particular exercise is using macros in a way where they can be avoided => you can learn from this exercise how you **can** use macros, but not how you **should** use them IMO.
Comment: @MauriceAbney This is definitely a good exercise to understand, because there is a lot of code that uses macros. This is probably the simplest demonstration of what macros do, so it's worth doing simply to be able to read other people's code. I also agree with DyP that you should avoid using macros when you can avoid using them.
Comment: Does this `#define RETURN_STATUS int` "define a type"?
Comment: @DyP That's the best interpretation of the task from the book that I could come up with. Of course I'd never use this in production code: I'd go for an `enum`, or use `typedef`. However, this is a learning exercise, so I must assume that this is what they want students to do.
Comment: You could mentions this in your answer. I don't think it's neither a clear nor a good (as in "a good, useful, realistic") exercise..
Comment: @DyP so the question isn't a good question? is it even worth me stressing about how it's supposed to be done by the textbook's standards? Because I'm confused and I would love to skip this section if it's not going to be used later in life :)
Answer: I think a typical way is to return an error code, which is defined as enumerate type, for example:
enum ReturnStatus {
    SUCCESS = 0,
    WARNING,
    ERROR
};

and then you can check return status using an inline function:
inline bool checkReturnFatal(const ReturnStatus status) {
    return status == ERROR;
}

Hope this helps.
Comment: I guess you either need a `typedef` or move the `ReturnStatus` before the `{`. atm, you're creating an anonymous `enum` and an object of that anonymous `enum` called `ReturnStatus`.


How to rotate MKMapView and keep the Annotation and the view don't rotate?

Question: I am making an MKMapView that shows the user's current location.
I want to rotate the map like the Google Maps App without rotating the annotations. Im using the following code
-(void) locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading{
     mapView.transform=CGAffineTransformMakeRotation(-1*newHeading.magneticHeading*3.14159/180)};

but the whole view is rotated like this image.
The image of the problem in my app
Answer: You basically need to apply a the same transform to all annotation views but with negative angle, i.e.
for (id<MKAnnotation> annotation in mapView.annotations)
{
    MKAnnotationView* annotationView = [mapView viewForAnnotation:annotation];
    [annotationView setTransform:CGAffineTransformMakeRotation(-angle)];
}

If you're planning to add more annotations you should place the same code in mapView:didAddAnnotationViews: too:
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    for (MKAnnotationView* annotationView in views)
    {
        [annotationView setTransform:CGAffineTransformMakeRotation(-angle)];
    }
}

Comment: There's no need for the code in - (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views, the rotation in applied on heading change is enough (testing it on a device right now! :) )
Answer: All the annotations and callouts that are shown on an MKMapView are subviews of MKMapView so if you rotate the container view all of its subviews are also going to be rotated.
Comment: yes, that is the point. In the controller, I only add the mapView as subview. When I put the annotations on the mapView, and transform the mapView. All content will be rotated, including the Google logo.
Comment: sorry did i miss something? My answer basically means there isnt a way of doing it that is supported currently in the sdk
Comment: you add mapview as subview but all the other things in the map are added as subview to the map. You dont do it but thats how its implemented at the back end.


How many points in the finite plane will random lines cover?

Question: Fix a prime power $q$ and a positive integer $n$. On average, what proportion of $\mathbb{F}_q^n$ will be covered by randomly drawing $k$ (not necessarily distinct) lines in that space? In other words, if $X_k = |L_1 \cup L_2 \cup \cdots \cup L_k|$, where the $L_i$'s are lines in $\mathbb{F}_q^n$ drawn uniformly, what is $E[X_k]$?
For $k = 2$ I believe that the answer is $$E[X_2] = q P(L_1 = L_2) + (2q - 1) P(L_1 \neq L_2).$$ The probability $P(L_1 = L_2)$ is ${q^n \choose 2}^{-2}$, which means this expectation is very close to $2q - 1$. I see how I might evaluate the probability for $k = 3$, but my idea gets foggier as $k$ grows. I can't see any simple recurrences between probabilities here.
As some visual motivation, here's a random drawing of 7 lines in $\mathbb{F}_{17}^2$, where the small, black dots are the uncovered ones:
Answer: For an arbitrary point in $\mathbb F_q^n$, what is the probability that one randomly chosen line falls on the point? It must be $\frac{1}{q^{n-1}}$ on symmetry grounds, since there are $q$ points on every line, and no point is on more lines than any other point does.
Therefore, the probability for an arbitrary point in $\mathbb F_q^n$ to not be hit by any of $k$ randomly chosen lines is
$$ \left(1 - \frac1{q^{n-1}}\right) ^ k $$
And therefore, thanks to additivity of expectations, the expected number of uncovered points is
$$ q^n \cdot \left(1 - \frac1{q^{n-1}}\right) ^ k $$
Comment: Ah, working with the *uncovered* points is significantly easier. Thanks for pointing that out!


is it possible to return a function from another function in C?

Question: I have a project in C. In the function adminpanel()  there are some selections such as add, delete, modify etc. Each of these selections is a function.Now, for example i call the add() function and when it ends i need to return at the begging on the adminpanel() function to make another selection. This happens with the delete() etc.
Is it possible to set as return value in the function add(), delete() etc. the function adminpanel() ? If not, what i have to set as a return value?
Comment: No. You can't return a function or arrays from a function. It's possible to return a pointer to a function.
Comment: @T.J.Crowder; No. Not a dupe of that.
Comment: @haccks: The standard for "is this a dupe" is "Does an answer to the other question answer this question." So yes, it's a dupe. (If I were making the rules, the rule would probably be different.)
Comment: @T.J.Crowder: So if you do not like the rules, why stick to them? ;-)
Comment: @alk: Because otherwise, chaos.
Answer: It is possible to return a function pointer:
<code>int inc( int x ) { return x + 1; }
int dec( int x ) { return x - 1; }

int( * func( int t ) ) ( int )
{
    return t ? &inc : &dec;
}

int test_C( void )
{
    int( *f1 )( int ) = func( 1 ); // f1 = &inc
    int x1 = ( *f1 )( 1 );         // x1 = 2

    int( *f2 )( int ) = func( 0 ); // f2 = &dec
    int x2 = ( *f2 )( 1 );         // x2 = 0

    return 0;
}
</code>
Comment: `return inc;` would do, as well as `... = f(1);` would.


CSS margin-top is incorrect value

Question: I have very simple markup and style rules that should put my div in the middle of the page, but it does not (actually, the top of the div would be at the middle, not 100% truly centered vertically) when the viewport is of a small enough height.
HTML:

adf

CSS:
div {
    background-color:red;
    margin-top:50%;
}

You can look at my Fiddle to see this. It will require you shrink the rendered window (bottom right) a bit, as it is correct initially.
Comment: `margin-top` uses the width of the element when using percents. See the answer to this question: http://stackoverflow.com/questions/7266363/margin-top-percentage-does-not-change-when-window-height-decreases
Comment: See [the spec](http://www.w3.org/TR/CSS2/box.html#margin-properties): The percentage is calculated with respect to the **width** of the generated box's containing block. Note that this is true for 'margin-top' and 'margin-bottom' as well.
Answer: Instead of 50% try 50vh
50% doesn't do what you think it would - it actually uses the width of the parent container, not the height to calculate.
Comment: Keep in mind that not all browsers support the vh unit. http://caniuse.com/#feat=viewport-units
Comment: I remember reading about this... It's very annoying.
Comment: Good point fanfavorite - this won't work in IE8 at all.
Comment: @fanfavorite Thanks. The support is good enough for me; only a personal project.
Answer: Try replacing percentages with vh

div {
    background-color:red;
    margin-top:50vh;
}

adf

Here are more cool stuff about viewport sized measures
Comment: well, I didn't see an answer was posted when I was copying code to snippet. So it seems you downvote me. Thanks!
Comment: I know, but you say I have to delete my own answer, which is right and helpful, because someone posted answer half a minute before me?!
Comment: It's nothing personal. It just makes it hard for future readers to find the complete answer in a nice way. willoller's answer should just be edited and improved with your info. It happens all the time.
Comment: I delete my answers when I get scooped, but I don't downvote answers for being essentially too late. According to mods, though, downvotes are the right action since they encourage the user to delete and get some rep back (http://meta.stackoverflow.com/questions/255571/what-to-do-with-late-answers-which-retread-the-same-ground-as-previous-answers/255602#255602 and http://meta.stackoverflow.com/questions/263046/should-i-delete-my-own-downvoted-answer)
Comment: Your answer is essentially a repeat of willoller's.
Comment: Yeah not sure that deserves a downvote - those hang around, you know?
Answer: Here is another solution:
http://jsfiddle.net/nb6pq14v/

html, body{height:100%; margin:0;padding:0}

.container-fluid{
  height:100%;
  display:table;
  width: 100%;
  padding: 0;
}

.row-fluid {height: 100%; display:table-cell; vertical-align: middle;}

.centering {
  float:none;
  margin:0 auto;
    background: #abc;
    height: 25px;
}

Comment: Thanks for the answer. This is very verbose compared to other answers, including an option to simply change the units I was using. Other viewers should be directed there.
Comment: Okay, anyway the code is compatible with all the browsers. Just wanted to give it a try. All the best.

CSS margin-top is incorrect value


Natural in key signature

Question: Something I haven't run across before.  In an exercise, the beginning of the staff has A key signature. However, past a double bar, there's a natural on the G space and sharps on the F line and C space.
I'm assuming this is an indication of a key change to D. However, why use this notation instead of using the bass clef and normal D key signature notation?
Answer: It's a courtesy marking. There is a style that cancels the previous signature before making the new one. It's advantageous when the key changes across a page turn (or even before the next system.) It also helps in sight reading.
Answer: This is a rather old-fashioned notation. The idea was to remind you that the G has changed from sharp to natural. But a lot of "classical" music that is still in print was actually engraved more than 100 years ago, even if it is now reproduced by modern technology which works more like a photocopier than a 19th-century printing press.
Sometimes, the first note after the key change was also marked with a natural, as a reminder.
The only place where this is still used is when the key signature changes to C major or A minor. If the naturals were not displayed, there would be nothing at all to show the key change.
Comment: I see plenty of new music that has this notation.  Especially in Musicals, because it seems like there are more "active" key changes than I've seen elsewhere.
Comment: Musescore and Finale default to using naturals in key signature changes. This includes switching from key signatures with sharps to those with flats.
Answer: It is part of the key sig., but not the key sig. When a key changes - often accompanied by a double bar line, the natural/s are put in to cancel any previous # or b that were in the previous key, as a courtesy reminder only at the beginning of the new key.
Here, it's gone from A major (F#m) with 3# to D (Bm) with 2#. Thus, the writer shows that the G# is no longer needed, and puts a natural in its place. Note that it's only there for the beginning - at the start of the next line, there's the standard two sharps of the new key sig.
I've had several longish pieces that change key, and the new key sigs are only put in at the beginning of each section - not repeated in the traditional way at the start of each line. Unusual, but not really a problem, once it's got used to. After all, we don't expect to see the time sig. repeated at the start of each line, do we...

Natural in key signature


PHP see if a 'last sent' date was 30+ days ago

Question: I have this PHP Code:
$last_sent=strtotime('2013-08-12');
if($last_sent < strtotime('now +30 days'))
{
    echo 'send survey';
}
else
{
    echo 'dont send survey';
}

i need to see if the $last_sent date is 30 days ago or more than 30 days ago. this doesnt seem to be working though.
i i change the last sent date to 2013-07-12 (exactly 30 days ago) it echoes send survey and then when i change the date to today (2013-08-12) it still says 'send survey'
Comment: You are currently checking to see if it was sent before 30 days from now.... I think you need to put the +30 on the other side of your comparison
Answer: Instead of strtotime('now +30 days') use strtotime('-30 days').
Answer: Use
$last_sent < time() - 30 * 24 * 3600

Comment: This solution is probably faster - it doesn't have to parse and interpret the relative time, it just has to do the arithmetic.  Both posted solutions should work.
Answer: Maybe try with dateTime object, this kind of objects can be compared :
$date1 = new DateTime('2013-08-12');
$date2 = new DateTime('+30 days);
if($date2 > $date1) //do somethings

another solution is date_diff : http://www.php.net/manual/en/datetime.diff.php


Adding VM's to Domain

Question: I am trying to configure SP farm, in Azure, following steps mention in this article - https://technet.microsoft.com/en-us/library/mt723354(v=office.16).aspx
But after creating Sql VM('sqlVM' ), I am not able to add this to the AD domain.
Below error message is displayed while trying to connect to Domain.

PS C:\Users\anuvya> Add-Computer -DomainName "corp.contoso.com"
cmdlet Add-Computer at command pipeline position 1 Supply values for
  the following parameters: Add-Computer : Computer 'sqlVM' failed to
  join domain 'corp.contoso.com' from its current workgroup 'WORKGROUP'
  with  following error message: The specified domain either does not
  exist or could not be contacted. At line:1 char:1
  + Add-Computer -DomainName "corp.contoso.com"
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : OperationStopped: (sqlVM:String) [Add-Computer], InvalidOperationException
      + FullyQualifiedErrorId : FailToJoinDomainFromWorkgroup,Microsoft.PowerShell.Commands.AddComputerComman

Any inputs will be appreciated.
Thanks,
====================
Answer: Agree with @garbrad. According to the error message, the SQL VM can't locate the DC.
Please check the DNS settings on the SQL VM, if it is not the private IP address of your DC VM, then you need to check the DNS settings of VNET. VNET uses Azure provided name resolution as the default settings. To change it, please refer to the screenshot below:

If the DNS settings are correct, then you need to check if the DNS records are created on the DC VM properly.
Also, here is a good article about How Domain Controllers are Located in Windows, which is helpful for you to understand the whole process.
Answer: Generally when domain join says "the domain doesn't exist or cannot be contacted" it's because the VM isn't configured to use the AD DC as its DNS server.  Check if the DNS server on the VNET matches the IP of the DC and that the VM is using that IP (ipconfig /all).  If the DNS server was set on the vnet after the VM was recreated then the vm either needs a reboot or an ipconfig /refresh
Answer: You would need to have restart flag at the end.
Also this command uses the local user account to add to the domain.
Add-Computer -DomainName "corp.contoso.com" -restart

IF the local user account cannot add the PC to the domain you can use:
Add-Computer -ComputerName "Server01" -LocalCredential "Server01\Admin01" -DomainName "Domain02" -Credential Domain02\Admin02 -Restart -Force

It will prompt your for a password

Adding VM's to Domain


Expliquem de uma forma mais simples o que são esses ataques?

Question: Gostaria de saber de uma forma mais simplificada o que são esses tipos de ataques.

Keylogger
Ataque de força bruta
Criptoanálise de mangueira de borracha
Sql injection

E por favor se puderem aprofundar mais no assunto, poderiam me dizer um exemplo simples de como se proteger deles. Estou criando um site para uma empresa e gostaria de entender melhor eles e como me proteger.
Obrigado
Comment: Relacionado: [Como acontece um SQL Injection](http://pt.stackoverflow.com/questions/100729/como-acontece-um-sql-injection)
Comment: Relacionado: [O que é PHP injection e qual é a diferença entre ele e SQL Injection?](http://pt.stackoverflow.com/questions/80699/o-que-%C3%A9-o-php-injection-qual-a-diferen%C3%A7a-dele-para-o-sql-injection-e-como-evit)
Comment: É bom dar uma lida no conteúdo já presente no site, assim você pode honrar quem já esforçou para trazer o conteúdo no sentido que você está procurando.
Comment: Eu já li varias matérias sobre os 4 tipos de problemas mas preciso intender melhor, se alguém puder me ajudar, agradeço.
Comment: Não seria melhor criar uma pergunta separada para cada tipo de ataque? A resposta do Renan sumariza bem, mas algumas coisas poderiam ser bem mais detalhadas (há muito a se dizer sobre ataques de força bruta, por exemplo), e não dá pra fazer isso com "4 perguntas em 1"...
Answer:
Keylogger:

Ocorre quando alguém utiliza hardware ou software para registrar cada tecla que o usuário utilizou. O atacante pode depois fazer uma análise dos textos para encontrar nomes de usuário, senhas, números de contas bancárias etc.
Como se defender: utilize anti-vírus para se proteger da versão em software, uma vez que se trata de malware. A versão em hardware é raríssima - trata-se de um aparelhinho que fica na porta USB, entre o teclado e o computador. Esse é mais fácil de resolver, basta jogar o keylogger fora caso o encontre.

Ataque de força bruta

Trata-se de ficar testando senhas até uma dar certo. Muitos sistemas hoje em dia têm proteções automáticas contra esse tipo de ataque. Se você errar a senha cinco vezes seguidas em um iPhone com o iOS mais atual, por exemplo, o telefone apaga todos os arquivos :D
Esse ataque funciona melhor contra sistemas que não limitam a quantidade máxima de erros de senha, e se o atacante tiver acesso físico a máquina.
Como se defender: garanta uma complexidade mínima de senhas. Não perdõe quem errar a senha mais do que algumas poucas vezes.

Criptoanálise de mangueira de borracha

Esse é o método mais antigo de todos de ataque para se obter informações confidenciais. Trata-se de encher um usuário de porrada até ele dizer as senhas e demais informações confidenciais.
Como se defender: treine seus usuários em artes marciais e manejo de armas de fogo. Dentes falsos com cápsulas de cianureto são uma opção para os membros da equipe que forem mais fracos fisicamente.

Sql Injection

Trata-se de explorar uma falha de programação em geral cometida por pessoas que descobriram o que é SQL há pouco tempo. Ocorre quando um programa passa para uma consulta SQL um dado informado pelo usuário, sem fazer qualquer tratamento sobre esse input.
Como se defender: nunca deixe seu sistema nas mãos apenas de um iniciante. A equipe de desenvolvimento precisa ter pelo menos um profissional experiente para evitar não apenas esse, como também outros tipos de falhas de programação que podem ser causadas por falta de experiência.
Comment: Acerca de SQL injection, não acontece só com iniciantes @Renan, à vários tipos de SQL injection, error based, union based, blind. Qualquer sistema pode estar vulnerável, uns mais que outros. Aqui está dois videos bastante interessantes acerca disso: https://www.youtube.com/watch?v=eUv9XPgeUww , https://www.youtube.com/watch?v=qBVThFwdYTc
Comment: @Miguel todos esses tipos de injeção são possíveis quando o código tem vulnerabilidades extremamente básicas. Eu continuo achando que são coisas de iniciante. Na empresa onde trabalho nós realizamos testes de habilidade antes de contratar qualquer pessoa. Se o candidato expõe o código a qualquer ameaça de injeção de SQL - não importa o tipo - nós não oferecemos mais do que uma vaga de estágio.
Answer: Amigo e simples
Um ataque de força bruta nada mais é que um bot ou uma rede de bots (robôs) que tentam pelo método "tentativa e erro" acertar a sua senha. Conseguindo o acesso ele captura a sua senha e volta mais tarde através de uma invasão, de certa forma pela porta da frente do seu site.
Forma de se proteger: criar e trocar com frequência senhas fortes, que contenham pelo menos 8 caracteres, letras maiúsculas e minúsculas, números e caracteres especiais (!@#$%ˆ&*), e não colocando palavras conhecidas ou fáceis de serem descobertas, melhor ainda que sejam totalmente aleatórias.
manter seu computador (principalmente se nele rodar o sistema operacional Windows em qualquer versão) limpo e longe de vírus, com verificações frequentes com bons antivírus (aquele antivírus gratuito nem sempre resolve).
nunca, jamais e sob qualquer hipótese salvar senhas no seu computador ou pedir para que o navegador/browser salve para futuros acessos.
keylogger:  (ou registrador de teclas), apesar de muitas vezes entendi como spyware, é um programa de computador cuja finalidade é registrar tudo o que é digitado em um teclado, na maioria das vezes objetivando capturar senhas, números de cartão de crédito e outras informações importantes. Ele tem um funcionamento típico de vírus, pois é instalado e atua sem que o usuário perceba sua presença.
Forma de se proteger: Manter um antivírus atualizado é fundamental, ainda mais atualmente quando estamos quase o tempo todos conectado a internet, baixando arquivos, trocando música, vídeos e testando programas e jogos.
Sql Injection:  é um ataque que consiste na inserção (conhecido como injeção) de uma query via aplicação web. A Locaweb sempre toma todas as precauções em relação a atualizações para evitar quaisquer brechas de segurança nos sites hospedados.
Entretanto às vezes surgem vulnerabilidades que são exploradas através de programação, de nada adiantando as precauções que tomamos.
Tais vulnerabilidades estão presentes em códigos (ASP, PHP, etc.) colocados pelos próprios clientes. Este é o caso da "SQL Injection", brecha através da qual um invasor pode executar queries ou statements arbitrários numa base relacional via "injeção" de comandos em campos de formulários.
Forma de se proteger: Usando a função addslashes() tem o mesmo efeito que habilitar magic quotes, porém só aplica onde for conveniente. O que ela faz é colocar um caracter de escapa antes das aspas simples ou dupla, antes da barra invertida e do caracter NULL.
Usar 'prepared statements' ao invés do próprio código SQL atribuíndo todas as outras medidas de prevenção usar esta, nos daria mais performace e segurança, além de ser mais simples de ler e escrever. Porem só pode ser usado em SELECT, INSERT, UPDATE, REPLACE, DELETE e CREATE TABLE.
$login = $_GET['login'] $query = "SELECT * FROM registos WHERE login = '$login'";
Ficaria assim:
$query = "SELECT * FROM registos WHERE login = OR 1";
Criptoanálise de mangueira de borracha: Na criptografia, criptoanálise de mangueira de borracha é a extorsão de segredos criptográficos (por exemplo, a senha para um arquivo cifrado) de uma pessoa por coação ou tortura,[1] [2] em contraste com o ataque de criptoanálise matemática ou técnica. O eufemismo refere-se a golpear alguém com uma mangueira de borracha até que ela coopere.
Forma de se proteger: Treinamento aos usuários para qualquer tipo de tortura.


Determine whether tha Galois Group can be $S_{4}$.

Question: Let $f(x) \in \mathbb{Q}[x]$ be a polynomial of degree 4 with distinct roots $r_{1}, r_{2}, r_{3}, r_{4} \in \mathbb{C}$, such that:
$$
\prod_{i<j}\left(r_{i}-r_{j}\right)=9
$$
Let $E$ be the splitting field of $f$. Can the Galois group of $E/\mathbb{Q}$ be $S_{4}$?
I am supposed to answer this without any other information, like the resolvent cubic. Also, we have not introduced in class the concept of the discriminant for quartics, so maybe I should not use that as well. I cannot come up with a solution.
Thank you in advance for any help.
Answer: Let $D=\prod_{i<j}\left(r_{i}-r_{j}\right)$. For any permutation $\sigma\in S_{\{r_1,...,r_4\}}$ we have:
$\sigma.D=sgn(\sigma)\times D$.
This follows from the definition of sign of a permutation. It means that $\sigma.D=D$ if and only if $\sigma\in A_{\{r_1,...,r_4\}}$. Now, $D=9\in\mathbb{Q}$ and hence $D$ belongs to the fixed field of the group $Gal(E/\mathbb{Q})$. But only permutations in the alternating group are fixing $D$, hence there can be only even permutations in $Gal(E/\mathbb{Q})$. So $Gal(E/\mathbb{Q})\leq A_4$.
Comment: Thank you for the great answer.


Bagging vs pasting: bias-variance tradeoff

Question: In the Hands-On ML with Scikit-Learn book, it states that,

...bagging ends up with a slightly higher bias than pasting, but... the ensemble's variance is reduced.

I am a bit confused about this part. Wouldn't bagging have higher variance and lower bias, since the sampled instances will be more correlated with each other compared to pasting? (Similar to how leave-one-out CV has higher variance due to higher correlation compared to K-fold.)
Or, is it just because bagging can sample more instances and train higher number of predictors compared to pasting? But in this case, bagging will have lower variance but not necessarily higher bias?
Answer: I wasn't totally sure about the pasting method.
From Hands-On Machine Learning with Scikit-Learn it's written :

Another Approach is to use the same training algorithm for every predictor, but to train them on different random subsets of the training set. When sampling is perform with replacement, this method is called bagging, when sampling is performed without replacement it is called pasting

Because the bagging method use replacement, you can see data that wouldn't appear IRL ( let say two occurences of the same unique data), so the bias can be higher.
But, you are not limited by the number of classifier you train, because you can take the same data other times. The more classifier you train, the less variance you have
Answer: After thinking for a long time, my conclusion is that the author is not referring to the MSR version of variance but this on page 126:
<code>The Bias/Variance Tradeoff
--------------------------

An important theoretical result of statistics and Machine Learning is the fact that a
model's generalization error can be expressed as the sum of three very different
errors:

**Bias**

This part of the generalization error is due to wrong assumptions, such as assuming
that the data is linear when it is actually quadratic. A high-bias model is most
likely to underfit the training data.10

**Variance**

This part is due to the model's excessive sensitivity to small variations in the
training data. A model with many degrees of freedom (such as a high-degree polynomial
model) is likely to have high variance, and thus to overfit the training
data.
</code>
To answer your question more specifically:
When we use bagging (with replacement), we are more likely to learn from the same training instances and have an underfit result in the end. Thus, the model would be less sensitive to small variances in the training data (since the chances are less likely to be selected by a particular predictor).


Why am I getting a 400 BAD REQUEST error for simple GET request?

Question: I'm using an old programming language (Adobe's Extendscript). It has a simple Socket object to send TCP/IP requests.
The following lines always used to work for me:
reply = "";
conn = new Socket;
if (conn.open ("www.freelancebookdesign.com:80")) {
    conn.write ("GET /license.txt HTTP/1.1\nhost: freelancebookdesign.com\n\n");
    reply = conn.read(9999);
    conn.close();
}

But a couple of days ago, my hosting company (Bluehost) migrated my website to a new box (without being asked to do so, or giving advanced warning).
Now the same lines above return the following 400 error:
HTTP/1.1 400 Bad Request
Date: Thu, 02 Jul 2020 10:14:48 GMT
Server: Apache
Upgrade: h2,h2c
Connection: Upgrade, close
Accept-Ranges: bytes
host-header: c2hhcmVkLmJsdWVob3N0LmNvbQ==
Content-Length: 130
Content-Type: text/html; charset=UTF-8

I've contacted their customer support, but received a clueless response.
I don't know if this is the right place to ask for help, but I would really appreciate it if anyone has any ideas what the issue might be, even if I can just give their customer support some pointers in the right direction.
What might be the difference between the old server setup and the new that would be causing this?
Comment: We do not support shared web hosting platforms here. You may be able to get help at [webmasters.se].
Comment: Ok, thanks I'll try that.
Answer: According to the response headers, the target server wants you to speak HTTP 2.0, as indicated by
Upgrade: h2,h2c
Connection: Upgrade, close

I think it would be nicer (and more easy to understand) if the sever sent a 426 (Upgrade required) error, but still, the headers suggest you should speak HTTP 2.0 to the server, so your old script won't work.
Comment: Thanks, that does look likely. But the Adobe Extendscript socket object is very old and cannot speak HTTP 2.0. Might there be a setting on the new server that would allow it to accept HTTP 1.1 or HTTP 1.0, or be lenient in some way so that it does not reject this request?
Comment: Yes, web servers can be configured so, however, it is another question whether your provider wants to configure the servers this way. You should ask them about it.
Comment: Do you know what is the change that needs to be made to the server to make this work?
Comment: It depends on what kind of webserver is used.
Answer:
But a couple of days ago, my hosting company (Bluehost) migrated my
website to a new box (without being asked to do so, or giving advanced
warning). Now the same lines above return the following 400 error:

This is just a hunch but: your website may now be hosted on a different set of IP addresses. It is conceivable that your application is still trying to connect to the previous IP address(es) because of a cached record or an entry in your hosts file, bypassing normal DNS resolution. If that is the case you would need to update the DNS records for your domain name.
Comment: Thanks. I don't think we referenced a static IP address anywhere in the code.
Answer: The question (and the answer) in the end turn out to be identical to this: https://stackoverflow.com/questions/43574428/have-apache-accept-lf-vs-crlf-in-request-headers
In other words, Adobe's Extendscript Socket will convert any \r\n sequences to plain \n (this is actually mentioned in the Socket object's documentation) unless the Socket object's encoding is set to binary. At a certain point, Apache servers stopped recognizing \n in request headers and demanded \r\n.
Changing HttpProtocolOptions to Unsafe is not an option with shared hosting and my provider was unwilling to do this.
Therefore the only answer is to rewrite the original code by setting the encoding to Binary.


What can we say about $\ker(\theta)$ and $\mathrm{im}(\theta)$ of $\theta: S_3 \rightarrow \mathbb{Z}_{15}$

Question: θ : S3 → Z15 is a group homomorphism.
 I know the kerθ={x∈S3: θ(x)=$[0]$}.  Obviously we can say θ(e)=$[0]$, however I believe there is more to say about the kernel...
 Meanwhile the Imθ is a subset of Z15.  I also know |Imθ| is divisble by 15 and the |Imθ| is divisble by gcd(6,15)=3.  So the |Imθ|=1 or |Imθ|=3.
 S3/Kerθ is isomporhic to Imθ so |S3/Kerθ|=|Imθ| divided by |S3|=6.  Am I on the right track?
Comment: [Here's a MathJax tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) :)
Comment: Yes. Clearly there is a homomorphism with $|\mathrm{Im}\theta|=1$ (the trivial homomorphism). And you can conclude from what you've already done that $|\mathrm{ker}\theta| = 2$ or $6$. That should give you enough to proceed.
Comment: You're confusing "divides" with "is divisble by".
Answer: You are on the right track but there is much more to say.
$S_3$ is not abelian but $\Bbb Z_{15}$ is abelian so $\theta$ cannot be an isomorphism into its image.  Thus, $\vert \ker(\theta) \vert \gt 1$.
Since $\ker (\theta) \lhd S_3$, we also know $\ker(\theta)  =A_3$ or $\ker(\theta)= S_3$.  But if $\ker(\theta) = A_3$, then $\vert \theta(S_3) \vert = 2$, which isn't possible because $2$ does not divide $\vert \Bbb Z_{15} \vert = 15$.  Thus, $\theta$ must be the trivial homomorphism.
Comment: That actually makes so much sense thanks for that explanation!  Can I say anything else about the Imθ or is what I said you think sufficent.  Also what about the statement I  stated "|S3/Kerθ|=|Imθ| divided by |S3|=6"
Comment: This result says $\operatorname{Im}(\theta)=\{0\}$.  Yes, in general the size of the image of a finite group under any homomorphism must divide the order of the group.


Single MySQL session per python\django process

Question: If at the start of a python\django program I load a module that executes a raw custom sql command such as
from django.db import connection
cursor = connection.cursor()
cursor.execute("SET SESSION wait_timeout=2147483")

thus changing a session variable, will it hold for all the rest of the program run? i.e. is the module in the same MySQL session as the rest of the code running in the same python\django process?
Answer: Not reliably.
The correct way to do this is to use init_command within the OPTIONS dictionary of the db settings:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        ...
        'OPTIONS': {
            'init_command': '"SET SESSION wait_timeout=2147483',
        },
    }
}

Comment: Daniel, could you elaborate why "not reliably"?
Comment: Because there isn't really any concept in Django of 'start'. A new process can be started any time by the server itself, and there aren't really any hooks to tie into that process at the moment.


Find files containing a string on the whole filesystem

Question: I need to find all the instances of a given string in the whole filesystem, because I don't remember in which configuration files, script or any other programs I put it and I need to update that string with a new one.
I tried with the following command
`grep -nr 'needle' / --exclude-dir=.svn | mail firstname.lastname@example.com -s 'References on xxx'
If I run this command on a small directory it gives me the output I need in the form
/path1/:nn:line containing needle
/path2/:nn:line containing needle

where /path1 is the full path of the file, nn is the row containing the needle and last field is the content of the line.
However when I run the command on the root directory the grep process hang after a while. I run this script about 8 hours ago and even on a small filesystem (less than 5GB) it doesn't end and if I run top or ps the process seems sleeping
root     24909  0.0  0.1   3772  1520 pts/1    S+   Feb10   0:15 grep -nr needle / --exclude-dir=.svn
Why it doesn't end? Is there any better way to do this (it's a one time job, I don't need to execute this more than once)
Thanks.
Update: I found a working solution with find and xargs which seems to be working and uses less system resources than the find -exec solution. Here is my final command line:
find /{boot,etc,home,lib,lost+found,opt,root,sbin,usr,var} -type f -print0 | xargs -r0 grep -nr 'needle' | mail email@example.com -s 'References on xxx'

I used the /{dir1,dir2,...,dirn} syntax because I want the output lines with the fullpath including the leading slash, and in this way you can use the command without cd / i.e. from any directory.
Answer: There are some files in the file system that aren't real files, but are instead hooks into the kernel.  Some of those can be read from forever.  Try
grep foo /dev/zero

to see this in action.  Get ready to stop it with ctrl-C before it takes over the whole system.
If I wanted to do what you're doing, I'd enumerate the subdirectories of / that I wanted scanned, and make sure I only checked text files, probably with
cd /
find boot etc home lib lost+found media mnt opt root sbin tmp usr var -type f -exec grep needle {} /dev/null \;

Note how the list does not contain /dev, /proc, /sys or /selinux.
Comment: I'm gonna try, I think it should work. I'll let you know. What a stupid mistake...
Answer: You can try using find + xargs + grep for that, kinda:
find /there -type f :MaybeSomeRestrictingFlagsLikeSizeNotBigger500MB_or_FS_type_if_u_know_its_exactly_on_EXT3_AndSoOn: -print0 | xargs -0r grep needle /dev/null
(/dev/null makes grep printing file name even if only one file was found)
Answer: I don't know why it doesn't end but "fgrep -R" usually works in those cases.
Answer: You might want to exclude dev and proc from that command. I would do it with find instead and exclude special files:
find . -type f -exec grep -H "My search string" '{}' \; -print

Comment: That's very ineffective due to running `grep` every time `find` finds a file. That brings too much overhead in.
Comment: @poige I found something about your point, to avoid that I should use `find . -type f -exec grep -H "My search string" '{}' + -print` i.e. `+` instead of `\;`. In that way the find program will build the command line by appending files instead of calling the program once per file.
Comment: @Fabio, does it allow limiting number of files (arguments) to fire up grep with? xargs does.
Comment: @poige, I haven't found it because I'm experiencing some problems with that syntax. I just found a working solution with xargs and I'm gonna update my question to share it.
Comment: @Fabio, well, anyways I'm quite happy with «find × xargs × grep». It's UNIX-way. :)
Answer: As some of the others pointed out, the error is occuring because you are using grep on some 'files' that will produce weird results. For example grep XXX /dev/zero will go on forever.
I would first exclude the directories such as /dev/ and /proc/ from your search. Another way is to only search for 'files' and no other types.
Also if your argument list in grep is too long, you will get this error:
bash: /bin/grep: Argument list too long

You can get around this with a loop, such as this:
for i in `find -type f /`; do grep -H "sample string" $i; done

Or by executing it from find, whatever floats your boat.
find / -type f -exec grep -H "sample string" '{}' \; -print

This should do a find and then grep each file. Although some have pointed out that it is inefficient to spawn grep each time you find a file, you will have to do something which will be 'inefficient' because you do literally have to search every file for that string.


Determine the number of irreducible monic polynomials of degree 3 in $\mathbb F_p[x]$

Question: Determine the number of irreducible monic polynomials of degree 3 in $\mathbb F_p[x]$ where $p$ is a prime.
I'd like to start off by acknowledging that I know there are many posts relating to similar problems both on here and mathoverflow, however none address my problem.
In class, my professor went over the monic polynomials of degree 2 by reasoning that there are $p^2$ distinct polynomials, the reducible ones look like $(x - a)^2$ and $(x - a)(x - b)$ for the first one there are $p$ of them and for the second one there are $p(p-1)/2$ of them, subtracting the reducible ones from the total ones gives $$p^2 - p - \frac{p(p - 1)}{2} = \frac{2p^2 - 2p - p(p-1)}{2} = \frac{2p^2 - 2p - p^2 + p}{2} = \frac{p^2 - p}{2}.$$
I'm trying to use similar reasoning for polynomials of degree three using the fact that there are $p$ irreducible monic linear polynomials and $p(p-1)/2$ irreducible monic quadratic polynomials. But I can never get the result shown here and here.
My reasoning is as follows: Observe that reducible polynomials would look like $(x - a)(x - b)(x - c)$, $(x - a)^2(x - b)$, $(x - c)^3$ and $(x^2 + ax + b)(x - c)$ formed from irreducible linear and quadratic monic polynomials.

For the first type where all three are distinct we can surmise that there are $p$ choices for the first, $p-1$ choices for the second and $p - 2$ choices for the third. So we have $p(p-1)(p-2)$. (is it $p$ choose $3$? Do I have to account for order not mattering?)
For the second type there are $p$ choices for the square, and $p-1$ choices for the linear polynomial, so we have $p(p-1)/2$.
For the third type, we have shown that there are $p(p-1)/2$ choices for the quadratic polynomials and there are $p$ choices for the linear polynomial. So we have $p^2(p-1)/2$.

Subtracting these values from $p^3$ should give me what I'm looking for, which is $p(p^2 - 1)/3$. But I'm not getting that.
Can someone tell me where my reasoning is wrong? Or tell me how to go about counting the number of irreducibles? (I know there are other methods of getting the answer, even more general ones, but I'm looking for a simple counting method that can help me better understand where my reasoning is wrong and help me correct it.)
Comment: For step 1, you do need $\binom{p}{3}$.  For step 2, you've incorrectly divided by $2$: here the order does matter, since $(x-a)^2(x-b) \ne (x-b)^2(x-a)$.  Finally, you forgot the perfect cubes, of which there are $p$.  This should give you the right answer.
Comment: See also http://math.stackexchange.com/questions/40811/number-of-monic-irreducible-polynomials-of-degree-p-over-finite-fields? and http://math.stackexchange.com/questions/190994/alternative-solution-to-determine-the-number-of-irreducible-monic-polynomials-i?
Comment: Very similar: [How many irreductible polynoms of degree $n=3$ are there over $\mathbb Z_{3}=\{\overline{0}, \overline{1}, \overline{2}\}$?](http://math.stackexchange.com/questions/924103/how-many-irreductible-polynoms-of-degree-n-3-are-there-over-mathbb-z-3)
Answer: There are, as you pointed out, four types.
For the three distinct roots, it is $\dfrac{p(p-1)(p-2)}{3!}$. Whatever order you pick the three distinct roots, you get the same cubic.
For the two identical, and one different, it is $p(p-1)$. (There should not have been division by $2$: a double root of $a$ and a single of $b$ is different from single $a$, double $b$.)
For all identical, it is of course $p$.
And you are right about the quadratic times linear, it is $\dfrac{p^2(p-1)}{2}$.
Calculate. We get the right answer.
Answer: The general formula is obtained by G. J. Simmons in The Number of Irreducible Polynomials of Degree $n$ Over $GF(p)$.
Comment: This was great, thanks!


Given 2 points and a radius, find the equation of the circle

Question: Find the general equation of the circle with radius 5 and contains the points $A=(-8,0)$ and $B=(-4,-2)$.
Comment: I don't know where to start
Comment: I don't know if this will help but my professor put a hint, "Hint: Equate radii. Or use the fact that D = h^2+k^2-r^2, then, systems."
Answer: There isn't a unique circle satisfying these properties. (To visualize this, plot any two points, and draw the two circles of equal radii that go through those two points.)
Comment: True, but there are only two circles.
Comment: I don't know if this will help but my professor put a hint, "Hint: Equate radii. Or use the fact that D = h^2+k^2-r^2, then, systems."
Comment: Ross: Yes, but the question was to find *the* equation of *the* circle.
Answer: Hint:  if the center is $(x,y)$, the statement that $(-8,0)$ is at a distance $5$ from it means $(x-(-8))^2+(y-0)^2=5^2$.   You can get a second equation from the other point.  Solve them simultaneously.  You should find two points $(x,y)$ that satisfy the equations.  Write the equation for a radius $5$ circle around each one.
Comment: I don't get it, why would it be possible to put (-8,0) to the place of (h,k) if it isn't the points of the center of the circle?
Comment: You want the center to be $5$ units from $(-8,0)$, so we draw a circle of radius $5$ around $(-8,0)$ and say the center must be somewhere on the circle.
Comment: Oh i get what your saying now, but still i'm confused  on how to solve this question.
Comment: Can you write the corresponding equation based on $(-4,-2)$?  That gives you two equations in two unknowns.  As you have a quadratic, there are two solutions.  They correspond to the two different circles that each pass through the given points.
Comment: (x+4)^2 + (y+2)^2 = 5^2
Comment: That is right.  Now solve the two equations for $x,y$  You can subtract them to remove the squared terms from one, solve that for one of the variables, substitute into the other, and have a one variable quadratic.
Answer: Let $\Omega $ be the desired circle.
The equation of this circle is
$\Omega  : (x-a)^2 + (y-b)^2 = 5^2$
Where $I (a,b)$ is the center of $\Omega $
$$A \in \Omega\quad \text {and}\quad B \in \Omega\\
\begin {align}
&\Leftrightarrow
\begin {cases}
(-8 - a)^2 + b^2 = 5^2\\
(-4 - a)^2 + (-2-b)^2 = 5^2
\end{cases} \\
&\Leftrightarrow
\begin {cases}
a^2 + 16a + 64 + b^2 - a^2 -  8a - 16 -  b^2 - 4b - 4 = 0\\
a^2 + 8a + 16 + b^2 +4b +4 = 5^2
\end{cases} \\
&\Leftrightarrow
\begin {cases}
8a - 4b + 44 = 0\\
a^2 + 8a  + b^2 +4b  -5 =0
\end{cases} \\
&\Leftrightarrow
\begin {cases}
2a - b + 11 = 0\\
a^2 + 8a  + b^2 +4b  -5 =0
\end{cases} \\
&\Leftrightarrow
\begin {cases}
b  = 2a + 11\\
a^2 + 8a  + (2a+ 11)^2 + (44 +8a)  -5 =0
\end{cases} \\
&\Leftrightarrow
\begin {cases}
b  = 2a + 11\\
a^2 + 8a  + 4a^2+ 44a + 121 +8a + 39 =0
\end{cases} \\
&\Leftrightarrow
\begin {cases}
b  = 2a + 11\\
 5a^2+ 60a + 160  =0
\end{cases}\\
&\Leftrightarrow
\begin {cases}
b  = 2a + 11\\
 a^2+ 12a + 32  =0 \quad \Delta = 144 - 128 =16
\end{cases}\\
&\Leftrightarrow
\begin {cases}
b  = 2a + 11\\
a_1= \frac {-12+4}2 \quad a_1= \frac {-12- 4}2
\end{cases}\\
&\Leftrightarrow
\begin {cases}
b  = 2a + 11\\
a_1= -4 \quad a_2= -8
\end{cases}\end {align}\\
\Leftrightarrow  (a_1,b_1) = (-4,3)\quad\text {or}\quad(a_2,8) = (-8,-5)$$
So there exists exaclty two circles:
The first $\Omega_1$ with center $(-4,3)$.
And the second $\Omega_2$ with center $(-8,-5)$.


Order $n$ elements of infinite groups of finite exponent $n>2$

Question: I want to show or to disprove the following result:

If $G$ is an infinite group, $n$ the exponent of $G$ is finite, $n>2$, then there are infinitely many elements of order $n$ and infinitely many elements of order less than $n$.

(Clearly this fails when $n=2$ as only the identity $e$ has order $\ne2$.)
The first part I think can be shown thus: if there are finitely many elements of order $n$, say $a_1,\dots,a_n$, then $b=a_1\cdots a_n a_{n-1}^{-1}\cdots a_1^{-1}$ has order $n$, but I'm not sure how to show that $b$ is distinct from $a_1,\dots,a_n$ (and $b\ne e$). I'm also not very sure on how to start the proof of the second part, if it is true at all.
Comment: The exponent of $G$ is the least $n$ such that $g^n=e$ for all $g$. So every element has order dividing $n$... So are you asking if there are always infinitely many elements of order $n$?
Answer: There are always infinitely many elements with order $n$, and as I point out in the comments it is trivial that every elements order divides the exponent of the group:
Let $G$ be a group of exponent $n$ with finitely many elements of order $n$, say $g_1,...,g_m$ is an enumeration of the elements. Note that the set of order $n$ elements are closed under conjugation, any conjugation gives a permutation of $1,...,m$ by how conjugation acts on the labels of the $g_i$. Well there are only finitely many permutations of $1,...,m$. Suppose for now there are infinitely many elements in $G$, then for infinitely many $h_i \in G$ we get conjugation by $h_i$ corresponds to the same permutation, and we also get that conjugation by $h_i h_j ^{-1}$ corresponds to the identity permutation, hence $h_i h_j ^{-1}$ commute with all $g_i$. Note there are infinitely many distinct $h_ih_j^{-1}$, and so $g_1 h_i h_j^{-1}$ can not be a $g_k$ for infinitely many $(i,j)$, but $g_1 h_i h_j^{-1}$ has order $n$ for infinitely many $(i,j)$, so we reach a contradiction, and we must actually have infinitely many elements of order $n$.
Comment: This is true, I was confused about the part about "order not dividing $n$". Now I see that I don't actually need that part, and your proof is exactly what I need to proceed. Thank you!
Comment: I think there is a gap in my argument as I am assuming there is at least one element of order $n$, but apriori it could be that maybe there are only elements of order 2,3, so the exponent would be 6. I will think about it some more and see if it can be fixed, and put more detailed clear proof later. @Marc
Comment: @Marc My answer is flawed, could you unaccept it so I can delete it? (It assumes there are elements of order equal to the exponent, and the last part about infinitely many $g_1h_ih_j^{-1}$ of order $n$ is not as clear as I thought it was when writing it)
Answer: For any $n>2$ the direct product $\bigoplus_{k\in\mathbb{Z}}Z_n$ where $Z_n$ denotes the cyclic group of order $n$ has all elements of order dividing $n$; in particular it has infinitely many elements of order $n$ and none of order not dividing $n$.
Comment: It is, but $n$ must be prime.
Comment: Unless I misunderstand your question this is a counterexample to the claim.
Comment: Why does $n$ have to be prime? (I think I must be misunderstanding the problem if $n$ has to be prime) @NoamD.Elkies
Comment: sorry, I retract the comment: I misread the problem as asking for elements of exponent not *equal* to $n$, but in fact it says not *dividing* $n$.
Comment: @NoamDElkies It was my question that was incorrect. But now I see that this example with $n$ prime does provide a counterexample.
Answer: A Tarski Monster is a counterexample for every prime $\;p>10^{75}\;$ .
Comment: That is serious overkill!
Comment: @DerekHolt Thank you. I think it is a rather easy reachable one for every one who's come across these astonishing groups.


Decide whether vectors are linear independent

Question: We have $\alpha_1, \alpha_2, ...,\alpha_n$ set of $n$ vectors in linear space $V$
such that every $n-1$ subset of vectors is linear independent. The question is if this condition is sufficient to state that all vectors $\alpha_1, \alpha_2, ... , \alpha_n$ are linear independtent ?
Answer: Nope. Consider $\alpha_1 = \alpha_2$ for $n=2$.
Comment: I'm not sure if I understand it correctly. For $n=2$ we have $a\alpha_1=0$ and $b\alpha_2=0$ implies that $a=b=0$, but if $\alpha_1=\alpha_2$  then $k=a\alpha_1+b\alpha_2=\alpha_1(a+b)=0$ hence we have for instance $(a,b)=(2,-2)$ and $k=0$ . Is my reasoning OK ?
Comment: @John Yes, it is.
Answer: Just take $n-1$ linearly independent vectors $v_1,v_2,\dots,v_{n-1}$ and set
$$
v_n=v_1+v_2+\dots+v_{n-1}
$$
If
$$
\beta_2v_2+\dots+\beta_{n-1}v_{n-1}+\beta_nv_n=0,
$$
then
$$
\beta_nv_1+(\beta_2+\beta_n)v_2+\dots+(\beta_{n-1}+\beta_n)v_{n-1}=0
$$
forcing $\beta_n=0$ and so $\beta_2=\dots=\beta_{n-1}=0$.
The same for proving that any other subset of $n-1$ vectors is linearly independent.


How do I solve the IVP $Y^{''}-8Y^{'}+16Y = 2\cos(x)$ with $y(0)=1$ & $y^{'}(0)=2$?

Question: I have gotten as far as getting the complimentary function :
$$y(x) = (A_1x+A_2)e^{4x}$$
But I don't know how to go about the particular solution?
Answer: Hint
As $x=i$ is not a root of the characteristic equation, you will look for a particular solution of the form
$$y_p=A\cos(x)+B\sin(x)$$
Answer: For the homogeneous part, guess $y_h=ce^{rt}$:
$$r^2e^{rt}-8re^{rt}+16e^{rt}=0$$
$$r^2-8r+16=(x-4)^2=0$$
so $r=4$ and we have $y_h=c_1e^{4t}+c_2te^{4t}$.
For the particular solution, guess $y_p=c_3\cos x+c_4\sin x$. Then $y_p'=c_4\cos x-c_3\sin x$ and $y_p''=-c_3\cos x-c_4\sin x$.
We have
$$(-c_3\cos x-c_4\sin x)-8(c_4\cos x-c_3\sin x)+16(c_3\cos x+c_4\sin x)=2\cos x$$
$$(15c_3-8c_4)\cos x+(15c_4+8c_3)\sin x=2\cos x$$
thus we have the system
$$15c_3-8c_4=2$$
$$8c_3+15c_4=0$$
Now you can solve for all four constants and obtain $y=y_h+y_p$.
Comment: I can see what you've done here but I learned once that if the RHS is of the form $A_1$Sin(Bx) + $A_2$Cos(Bx) where $A_1$ or $A_2$ equal zero then you cannot use $y_p$ = $c_3$ cos(x) + $c_4$ sin(x) ? Is this not the case then?
Comment: You may be thinking of when the RHS is $x\sin x$? There is a nice table about a third of the way down here http://tutorial.math.lamar.edu/Classes/DE/UndeterminedCoefficients.aspx
Comment: I thought so too but this isn't the case in the notes so I'm confused?
Comment: Dunno. I believe wolfram gave the same answer though.
Comment: Cheers anyway!!
Answer: Now that you have your complementary solution and your equation is clearly non-homogeneous, you can use the method of undetermined coefficients to find your particular solution which I think would be
\begin{equation}
y_{p}(x)=B_{1}cos(x)+B_{2}sin(x)
\end{equation}
where the $B_{i}$'s are constants
from here its a straightforward procedure
Answer: A more rigorous method to evaluating the solution of a non-homogeneous linear ODE is using Variation of Parameters. Essentially, the methodology is identical to what others have shown (Method of Undetermined Coefficients), however without having to 'guess' the form of the particular solution $y_p$.
This video link shows an example using Variation of Parameters for the differential equation $\frac{d^2{y}}{dx^2}-\frac{dy}{dx}-2y=4x^2$.
Alternatively, there are also written notes for the method, with some examples.
Note: The Wronskian determinant matrix is of the form:
$W= \begin{vmatrix}
f_1(x) & f_2(x) & \cdots & f_n(x) \\
f_1'(x) & f_2'(x) & \cdots & f_n' (x)\\
\vdots & \vdots & \ddots & \vdots \\
f_1^{(n-1)}(x)& f_2^{(n-1)}(x) & \cdots & f_n^{(n-1)}(x)
\end{vmatrix}$


MS Access show null values

Question: I just started learning MS access and I encountered the following problem:
I have a table in Ms Access which I would like to check for fields with no values (Null Values). I have a table with 6 columns for example and I would like to be able to query for all missing data.
The best thing I could come up is a Union Query in which I combined Queries for all columns. The problem I have with this solution is that if there are 2 null values in on row ,I get a duplicate entry in my result.
Is there a better way to show all null values from one table? Or a way to exclude the duplicate from the Union Query?
Thank you!
Comment: 6 columns is not a lot, why not `if col1 is null or col2 is null ...` ?
Comment: Hi thanks for your replay. I tried this : Design View->Criteria : Is Null -> The problem is that if I type this at col1 and I type the same thing col2 ,the query is only going to show me data where both col1 and col2 are null.But I want to see also the data where col 1  is null and col 2 is not null and vice versa. So if I type in Design view under all 6 Criteria ,,is null' - the query is only going to show entries where all 6 columns are blank. Or did u meant something ales?
Comment: You must use different lines so you get OR rather than AND, have a look at SQL View in the query design window.
Comment: Yep this worked, thank you
Answer: You can simply use:
<code>Select * From YourTable
Where (Field1 + Field2 + Field3 + Field4 + Field5 + Field6) Is Null
</code>
This will list all records where one or more fields are Null.
Comment: Thank you but it worked with Fionnuala solution. I guess this works as well , where should I type this command ? should I create a Macro?
Comment: That's the SQL for a query.
Answer: 6 columns is not a lot, you can use
<code> if col1 is null or col2 is null ...
</code>
In the Query Design Window, you must use different lines so you get OR rather than AND, have a look at SQL View to see this.

MS Access show null values


Getting the optimal age cut off

Question: I am working with a database of diseased and non-diseased patients.
I would like to recommend an optimal age cut off for disease screening. The common problem with screening is that it creates a large number of false positive, which is directly related to the positive predictive (PPV). The PPV in turn, is affected by the prevalence.
In a nutshell, I would like to derive an age that provides the best trade-off where I will be able to:

retain a large percentage of the diseased patients and
drop a large percentage of non-diseased patients.

The central idea is to avoid unnecessary screening of patients who have relatively low probability of having the disease.
In this case, the independent variable is the age while the dependent variable diseased, non diseased.
I tried running an ROC curve to get the optimal balance by the comparing highest Youden statistic.
I'll like to know if there's a better way to do this or if what I am is acceptable.
Please do let me know if you anything I've mentioned is unclear.
Thank you very much.
Comment: This is the kind of situation where any reasonable meaning that can be given to "optimal" has to take into account the relative *costs* of false positive & false negative results, as well as the prevalence of the disease.
Comment: In addition, what you are saying in effect is that age has a discontinuous effect on outcome and that the decision point for one patient depends on other patients.  Neither of these assumptions is correct.  ROC analysis plays no role in decision making except for mass one-time decisions where utilities are unknowable.
Comment: ROC curve is the standard way to get optimal cut-off values.
Comment: I should also have mentioned that it's very likely the kind of situation in which it would be extremely inappropriate not to consult a medical statistician before making any final decision.
Comment: @bluemudpie : you should post some details about your data / figure here for better analysis.
Answer: The easiest thing to do would be to first bin your data by age groups.
Then for disease and non disease I would go with using odds ratio and risk ratio calculations. Odds ratios are used to compare the relative odds of the occurrence.
http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2938757/
You should be able to grab the data used in a two-by-two frequency table (diseased and non-diseased patients) (screened and no screened)
Then plug and chug in the odds ratio equation. The higher the odds ratio means higher odds of getting the disease.
Another way to do this is to use a Q-Q plot but it is not used as often in the medical field
https://en.wikipedia.org/wiki/Q%E2%80%93Q_plot
Comment: This will cause a great many problems and result in misleading interpretations of what are truly continuous age effects.  Better is to model age as a smooth nonlinear effect using for example a regression spline.

Getting the optimal age cut off


Prove that $\sqrt [a_1] \alpha+\sqrt [a_2] \alpha+ \dots +\sqrt [a_n] \alpha \le \alpha +n-1.$

Question: Let $\alpha$ be a positive number and $a_1,a_2, \dots, a_n$ positive non-zero integers such that $\frac {1}{a_1}+ \frac {1}{a_2} + \dots+ \frac {1}{a_n}=1$. Prove that $\sqrt [a_1] \alpha+\sqrt [a_2] \alpha+ \dots +\sqrt [a_n] \alpha \le \alpha +n-1.$
Answer: Note that if $n$ is a natural number, then $(1+x)^{1/n}\leq 1+x/n$. Thus, letting $\beta = \alpha-1$,
$$\alpha^{1/\alpha_1}+...+\alpha^{1/\alpha_n} = (1+\beta)^{1/\alpha_1}+...+(1+\beta)^{1/\alpha_n}$$
$$\leq \left(1+\frac{\beta}{\alpha_1}\right)+...+\left(1+\frac{\beta}{\alpha_n}\right) = n+\beta\left(\frac{1}{\alpha_1}+...+\frac{1}{\alpha_n}\right)$$
$$=n+\beta = n+\alpha-1$$
Answer: By Bernoulli (https://en.wikipedia.org/wiki/Bernoulli%27s_inequality) we obtain:
$$\sum_{i=1}^n\alpha^{\frac{1}{a_i}}=\sum_{i=1}^n(1+\alpha-1)^{\frac{1}{a_i}}\leq\sum_{i=1}^n\left(1+\frac{1}{a_i}(\alpha-1)\right)=n+\alpha-1.$$


Python Password Validation

Question: I try to write a simple Regular Expression that checks for the following conditions:

At least six characters long
contains a lowercase letter
contains an uppercase letter
contains a number

I tried to work like this:
regex = re.compile(r'''([0-9])+([A-Z])+([a-z])+.{6,}''')

I found a lot of similar threads, but I would like to know why exactly mine is not working as I intend it too. As I am still new to programming and regex in general I apologize if I missed some trivial stuff right here.
Thanks for the help!
Comment: With your approach you must have at least one digit at the start of your password, followed by an uppercase character and so on. So `"A1xxxx"` won't work. Use lookahead assertions like @Thefourthbird said.
Comment: Did you try lookahead assertions? See https://stackoverflow.com/questions/19605150/regex-for-password-must-contain-at-least-eight-characters-at-least-one-number-a
Comment: Thanks! Got it now!
Answer: ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{6,}$

Python Password Validation


HTML Email - Media queries causes different height on images

Question: I have a problem, because I want to make a block in an email with one big image to the left, and 4 small images to the right.
Example of the block I want to make
On mobile I just want it to downscale it.
So I've set it up, but the problem is, when viewed on mobile devices the small images does not get the same height, because the total width is 350px and 1/4 of that is 87,5px. Therefore the first column gets 88px and the second column gets 87px and they therefore also upscale in height, causing them to not have the same height.
See example of not the same height on mobile
Is there a way to keep them all at the same height on mobile, even though they aren't exactly the same width when calculated in percentages? - And in a way that it also works, with images of other proportions of course.
This is my code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta content="width=device-width" name="viewport" />

<title>-</title>

Comment: You made the background color and the entire color in the images the same color. https://ol2013.capture.litmuscdn.com/856a0d6d-f092-47ff-a982-4eca38fff3e4/results/ol2013-vertical-allowed-1366.png I ran this through Litmus to see if I could determine the problem, but I can't tell what is an image, what is the background. This makes it really hard to determine what is the issue. The harder you make it for people to help you, the less desire we have to help.
Comment: The given answer didn't work?
Answer: I think this is what you are after. I have used you images but the table had to be redone. You had used quiet a lot of tables, maybe your editor is doing it (shurgs).
Breakdown of what I did:
Each image style has width 100% and height auto. This will mean the image resizes with the columns (each columns are 50% of the table).
Since you had provided these images I have used the same color as the background ;-)
Check out the code to see how it works.

Run the code above and do a full screen, resize the browser to see it work.
Cheers


Bound on expected number of isolated trees

Question: I'm reading Introduction to Random Graphs by Frieze and Karonski. In chapter 2, at the proof of Lemma 2.12, a random variable $X_k$ is introduced, which counts isolated trees of order $k$ in the random graph with $p=\frac{c}{n}$, $c<1$. Its expectation equals
$$\mathbb{E}(X_k)=\binom{n}{k}k^{k-2}p^{k-1}(1-p)^{k(n-k)+\binom{k}{2}-k+1}$$ (equation (2.8) in the book). Later on (page 32) it is bounded as follows:
$$\mathbb{E}(X_k)\leq \frac{A}{\sqrt{k}}\left(\frac{ne}{k}\right)^{k}k^{k-2}\left(\frac{c}{n}\right)^{k-1}\left(1-\frac{k}{2n}\right)^{k-1}e^{-ck+\frac{ck^{2}}{2n}}$$ where $A$ is some positive constant. Note that it is only known that $k\leq n$.
I do not entirely understand that bound; specifically where does the $\left(1-\frac{k}{2n}\right)^{k-1}$ term come from.
I can see that the bound $\binom{n}{k}\leq \frac{1}{2\sqrt{k}}\left(\frac{ne}{k}\right)^{k}$ was used on the binomial coefficient. I believe that $e^{-ck+\frac{ck^{2}}{2n}}$ comes from bounding $\left( 1-\frac{c}{n} \right)^{kn-\frac{k^2}{2}}$. However the remaining $\left( 1-\frac{c}{n} \right)^{-\frac{3k}{2}+1}$ definitely cannot be bounded by $\left(1-\frac{k}{2n}\right)^{k-1}$, as it is greater than $1$. So how did that term get there?
Answer: Unfortunately, this is not explained at all in the text. Here is where that term comes from.
To get from $\binom nk$ to $\frac{A}{\sqrt k} (\frac{ne}{k})^k$, we first use $\binom nk \le \frac{n^k}{k!}$, then $k! \ge \frac{A}{\sqrt k} (\frac ke)^k$. However, when $k$ is large, we give a lot away in the first bound $\binom nk \le \frac{n^k}{k!}$. More precisely, we have
$$
   \binom nk = \frac{n^k}{k!} \cdot \frac{(n-1)(n-2)\dotsm (n-k+1)}{n^{k-1}}.
$$
Now let's look at this factor some more. By AM-GM, the product $(n-1)(n-2)\dotsm (n-k+1)$ is at most $\left(\frac{(n-1) + (n-2) + \dots + (n-k+1)}{k-1}\right)^{k-1}$, or $(n - \frac k2)^{k-1}$, giving us an upper bound of exactly
$$
   \frac{(n - \frac k2)^{k-1}}{n^{k-1}} = \left(1 - \frac{k}{2n}\right)^{k-1}.
$$
In case you are also worried about the remaining factor of $(1 - \frac cn)^{-3k/2 + 1}$, it is at most $\exp(\frac{3ck}{2n} - \frac cn) \le e^{3c/2}$, which is absorbed in the constant $A$.
Comment: awesome, thanks!


SQL Server Mgt Studio Query Editor window tabs aren't descriptive

Question: In SQL Server Mgt Studio 2005, when I open the Object Explorer to script an object to a new Query Editor window, the tab for that new script window is titled something like 'MyServerName.MyDatabaseName - sqlquery37.sql'
Not very descriptive. So when I get a bunch of windows open at the same time, I have no idea which one is which.
The 'Active Files' dropdown is useless because of this.
Is there a way to configure Mgt. Studio so that the Query Editor Window tab title more accurately reflects the object that I'm working on?
Thanks!
Answer: Not [easily] without actually saving the script window to a file - then you get
<code>MyServerName.MyDatabaseName - MyFileName.sql
</code>
as the title.
You might be able to change this with a plugin/add-on, but not without writing code.
Answer: This is something that the SQL team is aware of (see this connect item) but there is no firm deadline on when it will be addressed. Saving your file as Ken G suggested is the only work around at the moment.
Answer: I recently created this suggestion in which I offer an alternative UI for the tabs:
(image) http://img190.imageshack.us/img190/7130/exampletabs2.png
If enough people upvote it, perhaps they will take it seriously!


Loop through  elements and define rows / columns

Question: I have an HtmlNodeCollection of HTML  elements that I have collected from a table using HTMLAgilityPack. Normally, I would just select the
 elements in the table and loop through the  elements, but unfortunately the
 opening tag is generated through JavaScript and isn't rendered from the server. I have no control over how the HTML is rendered. Therefore, I've resorted to getting an HtmlNodeCollection from this XPATH query:
HtmlNode table = htmlDoc.DocumentNode.SelectSingleNode("//table[@width='100%' and @cellpadding='1' and @cellspacing='1' and @border='0']");
HtmlNodeCollection tds = table.SelectNodes(".//td[@align and string-length(@width)=0]"); // only select td elements that have the align attribute and don't have a width attribute

In the table, there are six columns and any number of rows. I'd like to process each individual row and parse out the columns into an intermediate data structure. I have this code for getting each "row" and "column", but it isn't quite correct:
int cols = 6; // six columns
int rows = tds.Count / cols;

// loop through the rows
for (int row = 1; row <= rows; row++)
{
    for (int col = 0; col < cols; col++)
    {
        HtmlNode td = tds[col * row]; // get the associated td element from the column index * row index
        MessageBox.Show(td.InnerHtml + "\n" + td.InnerText);
    }
}

I start at row 1 instead of row 0 and end at the row count since I don't want to multiply zero out six times. I'm attempting to treat this as a matrix, but I'm having trouble defining when one row ends and the next one starts. Do you have any suggestions on how to properly loop through all rows and columns?
Answer: After drawing out a grid on paper, it became clear what I was missing. I needed to add the column index to the number of columns multiplied by the current row like this:
for (int row = 0; row < rows; row++)
{
    for (int col = 0; col < cols; col++)
    {
        HtmlNode td = tds[col + cols * row]; // get the associated td element from the column index * row index
        MessageBox.Show(td.InnerHtml + "\n" + td.InnerText);
    }
}


Questions about Android Management API in Kiosk mode

Question: This application is for tablets for students in K-12.  Thank you for any help or pointers.  The basic management software is up and running just fine.

Is there a way to upload wallpaper in Kiosk mode?  I see the option to prevent Wallpaper changes, but I don't see anyway to change the wallpaper programmatically.
Comment: SO is a question and answer site. Note that *question* is singular, not plural. If you have multiple questions, they need to be in separate posts. You'll find your experiences here will be much better if you spend some time taking the [tour] and reading the [help] pages to learn how the site works before you begin posting, as was suggested when you created your account here.
Answer: There is currently no way to change the wallpaper in kiosk mode. However, there is an existing feature request to enable this functionality via kioskCustomLauncherEnabled. The request is currently in Engineering's backlog. Unfortunately, there is no guarantee that Engineering will pick up the request for future work. As such, we have no sharable timelines or additional info.
I suggest that you Join the Android Management API mailing list to receive monthly updates and service advisories directly to your inbox.
Comment: Can we build a customer launcher for this ?


How to get notification on custom lock screen

Question: I have created a Lock screen and i want to show the notifications of messages,missed call etc on the lock screen for example if i received 2 messages and 3 missed calls then it should display on lock screen.
Anyone please tell me how i can do this?
Comment: Any luck? I wish to do the same as you
Answer: you can use App Widgets which can also be displayed in the lock screens (maybe not all types).
Consider the android:widgetCategory="home_screen|keyguard" property.

See these
App Widgets
you can make use of flag FLAG_SHOW_WHEN_LOCKED
and This great example by google.
Hope this helps.


How do I set default product attribute?

Question: Simple Question here I hope.
I've got a Format taxonomy field on my product type Record that's defining an attribute (cd, vinyl, download etc.).
I'd like to have the same order and default value on the attribute dropdown on product displays. I've set the terms in the vocabulary in the order I want on product displays but it still seems the order is random when browsing the site...
any ideas?
Comment: Are you wanting to set the default-selected product entity on the product display or the order of the attributes?
Comment: Both actually..
Answer: According to Ryan, it's based on the weight of the terms you reference.
As far as the default product that is selected, it should be the first product referenced in the field. If you're wanting to set that dynamically, you can look at Commerce Product URLs which provides that functionality.

How do I set default product attribute?


Can I add and edit a custom entity from the same URL?

Question: I am creating a custom entity called user_profile. Each logged in user will have a user profile. I want to be able to add and edit the user_profile entity from the same URL.
The example module provided at
Creating a Content Entity Type in Drupal 8
shows adding and editing with the same form but from different URLs.
I want to be able to create the profile when the profile does not exist and edit the profile when the profile does exist from the same URL like /user/3/my-profile
Comment: Maybe the profile module (https://www.drupal.org/project/profile) will suit your needs.
Comment: Thanks @quex. Wanted to handle it with custom entity.
Answer: You can create a controller in its simplest form.
In my_module.routing.yml :
my_module.profile_controller_profile:
  path: '/user/{user}/my-profile'
  defaults:
    _controller: '\Drupal\my_module\Controller\ProfileController::profile'
    _title: 'Profile'
  requirements:
    _permission: 'edit profile'
    user: \d+

In ProfileController.php :
<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityFormBuilderInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\my_module\Entity\Profile;
use Drupal\user\Entity\User;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class ProfileController.
 */
class ProfileController extends ControllerBase {

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a new ProfileController object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   * @param \Drupal\Core\Entity\EntityFormBuilderInterface $entity_form_builder
   */
  public function __construct(
    EntityTypeManagerInterface $entity_type_manager,
    EntityFormBuilderInterface $entity_form_builder
  ) {
    $this->entityTypeManager = $entity_type_manager;
    $this->entityFormBuilder = $entity_form_builder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('entity.form_builder')
    );
  }

  /**
   * @param \Drupal\user\Entity\User $user
   *
   * @return array
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function profile(User $user) {
    $profiles = $this->entityTypeManager->getStorage('profile')->loadByProperties(
      ['user_id' => $user->id()]
    );
    if ($profiles) {
      $profile = array_pop($profiles);
      $action = 'edit';
    } else {
      $profile = Profile::create([
        'user_id' => $user->id(),
      ]);
      $action = 'add';
    }
    return $this->entityFormBuilder->getForm($profile, $action);
  }

}

You can choose to redirect after submitting the form, etc.
Answer: That's simple. In your form's build() function check for an existing entity for that user. If there is one, prefill the fields (set #default_value). Maybe add the existing entity-id as hidden field (if any).
In your form's submit() check again for an existing entity (for security reasons) or use the hidden entity-id. Then decide in your code if you create an new entity or modify the existing one.
Comment: That would work for a custom form. This is the entity form for a custom entity. The answer by @Condutiarii works