How to query all tables data available in MySQL database using node.js

Question: I am new to the node.js script I want to calculate the sum of Distance column where the Distance column is available in every table in database before I used looping through tables but it takes so much time to give every table result, is there any method to fetch result fast.
this is the sample code which I am using for individual table selection now I want for all tables
app.post('/fetch-data', (req, res) => {
   const selectedTable = req.body.table;
   const dateTimeRange = req.body.dateTimeRange;
   const [fromDateTime, toDateTime] = dateTimeRange.split(' - ');
   const fromDateTimeObj = new Date(fromDateTime);
   const toDateTimeObj = new Date(toDateTime);
   const fromDateTimeSQL = fromDateTimeObj.toISOString().slice(0, 19).replace('T', ' ');
   const toDateTimeSQL = toDateTimeObj.toISOString().slice(0, 19).replace('T', ' ');  // querying database and fetching data based on selected table and selected date
   const fetchDataQuery = `SELECT * FROM \`${selectedTable}\`WHERE date_time BETWEEN STR_TO_DATE(?, '%Y-%m-%d %H:%i:%s') AND STR_TO_DATE(?, '%Y-%m-%d %H:%i:%s');`;
   const getTableNamesQuery = "SELECT TABLE_NAME FROM information_schema.TABLES WHERE table_schema = 'ingodata';";
   pool.query(getTableNamesQuery, (err, results) => {
       if (err) {
           console.error('Error fetching table names:', err);
           return res.status(500).json({ error: 'Error fetching table names' });
       }
       const tableNames = results.map((row) => row.TABLE_NAME);

   });
   pool.query(fetchDataQuery, [fromDateTimeObj, toDateTimeObj], (err, results) => {
       if (err) {
           console.error(`Error fetching data from ${selectedTable}:`, err);
           return res.status(500).send(`Error fetching data from ${selectedTable}`);
       }
       if (!results || results.length === 0) {
           // Handle the case when no data is found
           const noDataHtml = `

No data found for the selected date range.

           `;
           return res.send(noDataHtml);
       }
const data = results;

Comment: What exactly are you trying to achieve? Looping through the tables is not something you should be doing in a regular query.
Comment: Without knowing how many tables you have, their strucure, etc, and what you mean exactly by "takes so much time" it's hard to tell if it's a normal timing or if there is a problem with your code. From what I know about SQL, i doubt a query aggregating all the tables result in a single query would speed up the process, you probably have better performance querying each table separately like you do already. A change in tables structure may be needed for better performances SQL wise
Comment: Having 170 separate tables with exactly the same structure seems like an anti-pattern to me, it would be interesting to know why this design. From what you are trying to achieve it looks like you want to treat them as a single table, can we know which engine is used for these tables? (Innodb, MyIsam, etc?)
Comment: from the above code calculates and gives the data based on single table selection, but i want the sum of Distance column for every table available in a database each and every Distance value has to be stored in array, with looping i can able to achieve but it takes too much time to display the result, is there any possible way to get the result at a short period of time
Comment: I have 170 tables in my database, each and every table has same column names, and i want the sum of the Distance value from Distance column from every table  based on the date range selection
Comment: this 170 tables having 170  electric vehicles data, IOT device sending data like voltage, distance, Ignition on/off data for every vehicle in that I want to calculate the sum of Distance  for every vehicle i just want to see the Top 5 vehicles which is covering max distance
Answer: There are few things you can do to calculate sums of distance and query it for every table.

Instead of using for loop to loop over table names and use
Promise.all(Read more here). It will call all the promises
nearly together which will drop total query time. While using for
loop it's sequential, meaning 1 async request will wait for another.
But for that you will have to promisify callback functions since
Promise.all accepts array of promises. You can read more on how to
promisify callback function here. pros -> It is relatively
small change for your current code and if you have small datasets,
it may be right solution for you. cons-> Does not scale well,
if your dataset is big, querying some of distance maybe even issue
in 1 table, let alone on every table and in nearly same time. Can
potentially cause slow queries and even timeouts and db overloading.
Create new table where you will save total distance for each of the table. So you would have columns like total_distance_table_a, total_distance_table_b and etc... If distance updates in one of the tables, you would also update it in real time here. This way you will be making only 1 query to get all your totals. This will simplify your code, dramatically reduce load on database and greatly increase average query time.

I would recommend 2nd approach, since it simplifies your code and scales much better than your looping over tables and querying total distance from them
Comment: i think the 2nd approach won't work for me, based on date range i want to sum the Distance column for every table
Answer: Looking at your code there are a number of areas for improvement:

Using SELECT *  reads and returns all columns. See if you can select only the columns you need, or aggregate them at the db already, e.g. Select SUM(distance) ...

Interating over ALL tables sounds like a bad idea. DBs are optimized to iterate over rows. If you really need to split your data over several tables, Partitioning may be useful to logically split data. See answers here on how to partition a table by a datetme column

You can explore using a cache table (or stored view) to speed up your queries. The cache is optimized for quick lookups and is updated whenever base tables are updated. Window functions may come useful. However, I would explore caching only when #1-2 are fixed.


Touches event for a UIScrollView

Question: How can I get touch event for UIScrollView.I have a UIViewController and I placed a scrollView in viewController.I need to add imageViews to scrollView and if a particular image is clicked it should redirect to its corresponding viewController.
I knew how to add touch event to a UIViewController.But that doesn't work for a scrollView.
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch= [touches anyObject];
    if ([touch view] == img1)
    {

        ViewController2 *viewController2=[[ViewController2 alloc]initWithNibName:@"ViewController2" bundle:nil];
        [self presentViewController: viewController2 animated:YES completion:nil];

    }
}

HOw can I get touches event for a scrollView ?
Comment: http://stackoverflow.com/questions/14785395/dismissing-the-keyboard-from-a-uitextfield-uitextview-as-a-subview-of-uiscrollvi/14788474#14788474
Answer: The only way to do this is by creating a custom UIScrollView Your custom UIScrollView will be a subclass of UIScrollView.
Also for more options you can check this
Comment: Can u please tell me how ?.I have referred the link u gave but where did he made subclass?There are all events of a view
Comment: @NikhatAfshan : 1. Create a subclass of UIScrollView
2. override Touches end methods
Comment: @NikhatAfshan : check this http://iphonedevsdk.com/forum/iphone-sdk-development/6686-uiscrollview-wont-respond-to-touch-event-scrolls-pans-but-tochesshouldbegin-ne.html
Answer: Set things like below:
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
[scrollView addGestureRecognizer:singleTap];

and you get the touch in:

- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
  {
    CGPoint touchPoint=[gesture locationInView:scrollView];
  }

Comment: Yes we will get the touch point(width and height).Can u please tell me How can I get if the touched event is image1 or image2 ?
Answer: You can use the ScrollViewDelegate and can use the function "ScrollViewDidScroll" for getting the scrollview scroll event.
Set up a tap gesture recognizer:
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
[scrollView addGestureRecognizer:singleTap];

- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
  {
    CGPoint touchPoint=[gesture locationInView:scrollView];
  }

Comment: Yes we will get the touch point(width and height).Can u please tell me How can I get if the touched event is image1 or image2 ?
Comment: You will get the X and Y axis and according to that , You can find out, whether at that position which Image is placed either it will be Image 1 or Image 2
Comment: I got x=283 and y=228 when I click on the middle of the image.When I click on the left of the image I do get some other positions.So how can I compare an image within some area?
Comment: You don't need to compare image with an area, but you need to perform the task depending upon the area tapped.
Comment: Yes my image dimensions are (217,257,89,82).When I click at varoius points of image I get separate x and y touchpoints.Do I need to write separately for all the points to go to same ViewController?
Comment: You can compare the range of coordinates, If the coordinates are that in which your image is lying then perform the function else leave it.

Touches event for a UIScrollView


What is the Key of 'Cuts Like a knife'

Question: While trying to improve my music theory, I found myself confused by this song ( Cuts like a Knife-Bryan Adams). On many sites on the internet I have read that the Key is D Major. The chord structure doesn't fit as the C chord rules that out. If I play the solo note for note, I found myself playing in D Mixolydian...Does any one else agree that this is the Key ?...and if so can you tell me where the A(Major?) chord is borrowed from, as D Mixolydian has an A minor.
It's not a secondary dominant as the next chord is not a D. The parent Major scale of D Mixolydian is G...G's parallel minor is Bb...that has an 'A' but its's diminshed...so i'm very confused.
Hope someone can answer these 2 questions.
Comment: I have voted to reopen as it's not so much about the song itself as the 'strange' chords within. Maybe you could re-word the question with no reference to one particular song. Read the help centre rules, and you'll see that it's not because you can't read music. A lot of our questions are from non-readers. We're just not that precious here, although you seem to have that impression, which is erroneous, generally speaking.
Comment: G's parallel minor is Gm.    G's *relative* minor is Em.    Gm is the *relative* minor *of* Bb.
Answer: You've fallen into the trap of believing music theory is music law. It isn't. It tries (very hard) to explain what happens - not really what should happen.
Many songs have chord structures that get explained by a bit of theory you maybe haven't met, till now. Borrowed chords are often used, so that the main chords from a key, say D major, (D, Em, F#m, G, A, Bm, C#o) are used, but supplemented with those from the parallel minor. (Here, Dm, Eo, F, Gm, Am, Bb, C).
Sometimes other 'foreign' chords creep in to songs, and while there will be theory which explains, or tries to, it isn't that important. The old adage of 'if it sounds good, it probably is' is so important...
Comment: Hi Tim....thanks for your reply and I take your point to not get hung up on everything having a reason in the future. I guess, looking a little deeper at my own question, it comes from looking for "Rules" I can understand to expand my musical knowledge and make my next song have that different twist. Example if I'm writing a song I can 'try' some of these things and see if they suit my song, rather than just tying every chord to see if it fits. I have learnt some new things recently ( like Secondary dominants and parallel minor) and was hoping this was a new 'Rule' to add to my arsenal. Cheers
Comment: Really... this question is "On Hold" because its Off topic. So as I didn't include sheet music. Well I cant read sheet music...I'm a guitarist for Christ's sake. So, Dom the moderator...can you suggest a Forum I can join where the Moderator's aren't so picky... and someone who has some limited musical knowledge can post a reasonable question

What is the Key of 'Cuts Like a knife'


UAG Direct Access - Exporting GPO to offline hosts

Question: I'm probably missing  something here, but I couldn't find any reference to this.
I have a host that is using Direct Access from a remote location. We had to make changes on the server side and ofc, update the GPO.
Is there a way to manually push the policy to the client? It seems rather useless using a tool that requires you to be connected to the network in order to connect to it.
Answer: This could take you sometime but it's fully possible.
Possible for two reason:

Since Windows 7 you can do a offline domain join.
Direct access does not install anything new. Nor in the server or the client. It's only a group policy that the wizard creates and that policy configure some special parameters of the TCP/IP Stack to get Direct Access working. But you, if you want, can implement the Direct Access manually. This is the procedure on the server and this is on the client.

So for answer your question what you have to do is a offline domain join and a manually direct access configuration following the steps describe in the links of microsoft that i'm putting here. You can create a Bat to automate the process.
Regards.


Group theory: permutation of group elements

Question: I want to prove that if $G = \{g_1, g_2, ..., g_n\}$ is a finite group and $h \in G$, then $G = \{hg_1,hg_2, ..., hg_n\} $.
My attempt:
Let $hg_i = hg_j = g_k \quad\quad 1 \leq i,j,k \leq n$.
Then:
$g_i = g_j$
By contraposition, we find that $gi \neq g_j \Rightarrow hg_i \neq hg_j$. Thus, all elements in $\{hg_1,hg_2, ..., hg_n\}$ are different. As this is a subset of $G$, with as many elements as in $G$, we deduce that $G = \{hg_1,hg_2, ..., hg_n\}$
Can someone verify whether this is correct?
Comment: You might add half a line as to *why* $hg_i=hg_j=g_k$ implies $g_i=g_j$. -- For an alternative proof, note that the map $G\to G$, $x\mapsto h^{-1}x$ is a right and left inverse inverse map to $x\mapsto hx$, hence the latter is injective and surjective. It may be interesting to note that finiteness of $G$ is not needed for the proof.
Comment: @Math_QED you're exactly right (though I realise Hagen did get his comment down before me). As he explained, the existence of a left and right inverse of $g\mapsto hg$ implies that it is bijective
Comment: Although I think your proof looks technically correct it's kind of weird. Notice that your second set is the image of $G$ under $g\mapsto hg$ for $g\in G$. Can you think of an inverse map?
Comment: @Hagen von Eitzen We can multiply both sides with the inverse of h (which exists by definition of group) to the left, then use associativity and definitions of neutral element, inverse element to get what we want.
Comment: @RobertChamberlain These are just the basics for me. We did not study isomorphisms and other functions yet, but I think the inverse function would be $g \mapsto h^{-1}g$
Answer: The approach in my original post is correct, but this is a more intuitive way.
Call $H = \{hg_1, \dots,hg_n\}$
Define a mapping $\phi: G\rightarrow H: g \mapsto hg.$ We prove that this mapping is bijective:
Surjective:
Let $y \in H$. Then there is a $g_i \in G$ such that $y = hg_i$. Because $\phi(g_i) = y$, the mapping is surjective.
Injective:
Let $g_i, g_j \in G$ with $\phi(g_i) = \phi(g_j)$. Then $hg_i = hg_j$ and because $h,g_i,g_j$ are elements of the group G, we can cancel the $h$ on both sides, obtaining that $g_i = g_j$. Hence, $\phi$ is injective.
Now, we have shown that this mapping is bijective. Because any bijective mapping between $2$ finite sets implies that both sets contain the same amount of elements, we are done.
Notice that we also could construct the inverse function (as mentioned in the comments) to show bijectivity.


Having trouble formatting this JSON data from the server

Question: I'm creating a section of a site in Angular JS that displays some reporting data from the server. Since I'm displaying it in a table I need it in a format that can easily be displayed with ng-repeat.
I therefore need to translate JSON data from the server into a JavaScript object. I've got the target format of the data I want, an object that uses the names of the 'Donor Programs' as keys, and as their values an array of objects that each correspond to a month. Each of the objects has the name of the month, the amount of people who registered on the site, the amount of those people who donated, and the total amount donated.
I'm just having a really hard time iterating through the JSON and getting it to translate to that format. Can someone have a look? I've included both the server data I'm getting as well as how I'm trying to format it. Thanks.
Server Data:
<code>$scope.serverData = {
"registration_by_month": [
    {
        "month": "November 2015",
        "registration_program": "Donor Program 1",
        "count": 3
    },
    {
        "month": "November 2015",
        "registration_program": "Donor Program 2",
        "count": 4
    },
    {
        "month": "December 2015",
        "registration_program": "Donor Program 1",
        "count": 5
    },
    {
        "month": "December 2015",
        "registration_program": "Donor Program 2",
        "count": 6
    }
],

"donors_by_month": [
    {
        "month": "November 2015",
        "registration_program": "Donor Program 1",
        "count": 2
    },
    {
        "month": "November 2015",
        "registration_program": "Donor Program 2",
        "count": 1
    },
    {
        "month": "December 2015",
        "registration_program": "Donor Program 1",
        "count": 2
    },
    {
        "month": "December 2015",
        "registration_program": "Donor Program 2",
        "count": 1
    }
],

"donated_amount_by_month": [
    {
        "month": "November 2015",
        "registration_program": "Donor Program 1",
        "amount": 100
    },
    {
        "month": "November 2015",
        "registration_program": "Donor Program 2",
        "amount": 200
    },
    {
        "month": "December 2015",
        "registration_program": "Donor Program 1",
        "amount": 50
    },
    {
        "month": "December 2015",
        "registration_program": "Donor Program 2",
        "amount": 40
    }
]
</code>
};
Target Data:
<code>$scope.targetData = {
"Donor Program 1": [{month:"November 2015", registered:3, donors:2, donated_amount:100},{month:"December 2015", registered:4, donors:1, donated_amount:200}],
"Donor Program 2:": [{month:"November 2015", registered:5, donors:2, donated_amount:50},{month:"December 2015",registered:6, donors:1, donated_amount:40}]
</code>
};
Answer: Try like this
<code> var temp = {};
 data.registration_by_month.forEach(function (x) {
     if (!temp[x.registration_program]) {
         temp[x.registration_program] = [];
     }
     var dtmon = data.donors_by_month.find(function (y) {
         return y.registration_program == x.registration_program;
     });
     var dnmon = data.donated_amount_by_month.find(function (y) {
         return y.registration_program == x.registration_program;
     });
     temp[x.registration_program].push({
             month: x.month,
             registered: x.count,
             donors: dtmon ? dtmon.count : 0,
             donated_amount: dnmon ? dnmon.amount : 0
     });

 });
console.log(temp);
</code>
JSFIDDLE
EDIT
.find is not supported in IE and opera.
You can try .filter instead
Like this
<code> var temp = {};
 data.registration_by_month.forEach(function (x) {
     if (!temp[x.registration_program]) {
         temp[x.registration_program] = [];
     }
     var dtmon = data.donors_by_month.filter(function (y) {
         return y.registration_program == x.registration_program;
     });
     var dnmon = data.donated_amount_by_month.filter(function (y) {
         return y.registration_program == x.registration_program;
     });
     temp[x.registration_program].push({
             month: x.month,
             registered: x.count,
             donors: dtmon.length > 0 ? dtmon[0].count : 0,
             donated_amount: dnmon.length > 0 ? dnmon[0].amount : 0
     });

 });
</code>
JSFIDDLE
Comment: Minor/potentially useful point if you're chained to older browsers by your requirements: you may not have native `forEach` or `find`. Angular comes with a `forEach` implementation, but look to underscore/lodash/pick your poison/brew your own for the `find` and similar
Comment: Wow... awesome. I wasted a couple hours with a couple nested loops and wasn't getting anywhere. Thank you!


Web crawler stops at first page

Question: I'm working on a webcrawler which should be working like this:

go to a website, crawl all links from the site
download all images (starting from the startpage)
if there are no images left on the current page, go to the next link found in step 1 and do step 2 and 3 until there are no links/images left.

It seems like the code below is somehow working, like when I try to crawl some sites, I get some images to download.
(even I dont understand the images I get, cause I cant find them on the website, it seems like the crawler does not start with the startpage of the website).
After a few images (~25-500), the crawler is done and stops, no errors, it just stops. I tried this with multiple websites and after a few images it just stops. I think the crawler somehow ignores step 3.
package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
    "os"
    "strconv"
    "strings"

    "github.com/PuerkitoBio/goquery"
)

var (
    currWebsite  string = "https://www.youtube.com"
    imageCount   int    = 0
    crawlWebsite string
)

func processElement(index int, element *goquery.Selection) {
    href, exists := element.Attr("href")
    if exists && strings.HasPrefix(href, "http") {
        crawlWebsite = href
        response, err := http.Get(crawlWebsite)
        if err != nil {
            log.Fatalf("error on current website")
        }

        defer response.Body.Close()

        document, err := goquery.NewDocumentFromReader(response.Body)
        if err != nil {
            log.Fatal("Error loading HTTP response body.", err)
        }

        document.Find("img").Each(func(index int, element *goquery.Selection) {
            imgSrc, exists := element.Attr("src")
            if strings.HasPrefix(imgSrc, "http") && exists {
                fileName := fmt.Sprintf("./images/img" + strconv.Itoa(imageCount) + ".jpg")
                currWebsite := fmt.Sprint(imgSrc)
                fmt.Println("[+]", currWebsite)
                DownloadFile(fileName, currWebsite)
                imageCount++
            }
        })
    }
}

func main() {
    err := os.MkdirAll("./images/", 0777)
    if err != nil {
        log.Fatalln("error on creating directory")
    }

    response, err := http.Get(currWebsite)
    if err != nil {
        log.Fatalln("error on searching website")
    }

    defer response.Body.Close()

    document, err := goquery.NewDocumentFromReader(response.Body)
    if err != nil {
        log.Fatalln("Error loading HTTP response body. ", err)
    }

    document.Find("a").Each(processElement)
}

func DownloadFile(filepath string, url string) {
    response, err := http.Get(url)
    if err != nil {
        log.Fatalln("error getting the website infos")
    }
    defer response.Body.Close()

    if response.StatusCode != 200 {
        log.Fatalln("received non 200 response code")
    }

    file, err := os.Create(filepath)
    if err != nil {
        log.Fatalf("error creating file at %v\n", filepath)
    }

    defer file.Close()

    _, err = io.Copy(file, response.Body)
    if err != nil {
        log.Fatalln("error copy file from src to dst")
    }
}

Answer:
(even I dont understand the images I get, cause I cant find them on the website, it seems like the crawler does not start with the startpage of the website).

Yes you are right. Your code will not download images from the start page because the only thing it is fetching from start page are all anchor tag elements and then calling processElement() for each anchor element found on the start page -
response, err := http.Get(currWebsite)
if err != nil {
    log.Fatalln("error on searching website")
}

defer response.Body.Close()

document, err := goquery.NewDocumentFromReader(response.Body)
if err != nil {
    log.Fatalln("Error loading HTTP response body. ", err)
}

document.Find("a").Each(processElement) // Here

To download all images from start page, you should define another function processUrl() to do the work of fetching img elements and download images but then in processElement() function you just need to get the href link and invoke processUrl() on that link -
func processElement(index int, element *goquery.Selection) {
    href, exists := element.Attr("href")
    if exists && strings.HasPrefix(href, "http") {
        crawlWebsite = href
        processUrl(crawlWebsite)
    }
}

func processUrl(crawlWebsite string) {
    response, err := http.Get(crawlWebsite)
    if err != nil {
        log.Fatalf("error on current website")
    }

    defer response.Body.Close()

    document, err := goquery.NewDocumentFromReader(response.Body)
    if err != nil {
        log.Fatal("Error loading HTTP response body.", err)
    }

    document.Find("img").Each(func(index int, element *goquery.Selection) {
        imgSrc, exists := element.Attr("src")
        if strings.HasPrefix(imgSrc, "http") && exists {
            fileName := fmt.Sprintf("./images/img" + strconv.Itoa(imageCount) + ".jpg")
            currWebsite := fmt.Sprint(imgSrc)
            fmt.Println("[+]", currWebsite)
            DownloadFile(fileName, currWebsite)
            imageCount++
        }
    })
}

Now just crawl images from start page before processing all links -
func main() {
    ...
    document, err := goquery.NewDocumentFromReader(response.Body)
    if err != nil {
        log.Fatalln("Error loading HTTP response body. ", err)
    }
    // First crawl images from start page url
    processUrl(currWebsite)
    document.Find("a").Each(processElement)
}

Web crawler stops at first page


Do I need a guitar cabinet in addition to an amplifier head for performing with a PA?

Question: I have guitar, a multi-effects processor, and a public announcement (PA) system. When I perform I use an in-ear monitoring system. I want the warm, rich tone and dynamics that come from having a tube amp and am thinking about what to buy. Will both of these work equally well or is one better than the other?
a) Guitar > Multi-Effects Processor > Tube Amp Head > PA
b) Guitar > Multi-Effects Processor > Tube Amp Head + Cabinet > Microphone > PA
Comment: There exist a multitude of type of cabs. Have you considered just investing in a small one?
Answer: It's not easy to say which is "better", but they will definitely be different.
First, if you go straight from a tube head to the PA, you'll need some way to match the output of the head to one of the PA's inputs, and you'll want to simulate the sound of a guitar speaker cabinet. A good way to do this for a tube head is with a speaker simulator and a passive load box. The speaker simulator shapes the speaker output sound from the head so that it sounds like it has been run through a speaker cabinet and miked up, and most speaker simulators have an XLR output which is good for running to the PA. The passive load box is to provide the correct amount of resistance to the tube power output. Without that, the head can easily supply too much current which can damage the head.
Advantages of Speaker Sim with Load Box:

Reduced stage noise
Consistent sound
Light weight (no cabinet to carry!)
Less expensive than some cabinets
No mic bleed

Disadvantages of Speaker Sim with Load Box:

Power supply or phantom power usually needed for speaker sim
The sound is not quite authentic
Good monitoring must be available to hear what you're playing
"Good" guitar feedback may be more difficult or impossible to get
Ground loops are possible
Mix/Monitor engineers may not like the setup as much as their favorite mic in front of a cab
You'll need some kind of monitoring setup for band practice, which will likely sound different from the live shows

Obviously, the advantages and disadvantages of going with a miked speaker cabinet are pretty much those two lists reversed. Personally, I prefer either a small head and cabinet or a combo amp. I make it so the amp is pointed at my ears, instead of my knees, so that I'm getting the loudest and most direct guitar sound. I set up the same way at practice as I do at gigs so I can keep my sound and feel consistent and also play with feedback in a more consistent way. Using a smaller, lower powered amp helps with reduced stage volume and bleed into vocal mics, saves my back (smaller amps are lighter), and makes sound engineers happier.
I do own two great speaker sims and two different kinds of load boxes, but I just can't handle the difference in sound and feel. I use them mainly for doing scratch takes when recording or for playing along with a drummer when laying down drum tracks, so there's no guitar bleed into the drum mikes.
As a sound engineer, I usually actually prefer to mike up sources, rather than DI. I do bring a lot of DIs to a gig but I don't bring speaker sims. A guitarist rolling with their own speaker sim would be a pain, IMHO, since it would be directly connecting gear that I have no expectation of function or reliability. With a mic, you know there are no ground loops and you know what the mic is going to give you, because it's your mic. It's almost the same with a good DI, although a lot of direct sources require a lot more processing (compression and EQ) than miked sources.
Comment: There is just something about how a cabinet moves air that makes the sound it produces wonderful. I have heard certain cab sims that are OK,  but still there is something magical about a real cabinet.
Comment: Well I was counting on you to do this one justice and you did not disappoint +1 for a job well done!  Do you have any experience with any of the newer micro tube amps with cab simulated output jacks designed for outputting to a recording interface - plugging in to a PA instead of recording interface?
Answer: If you go with no cab you probably want a speaker simulation method in addition to having a line out and a load box to compensate for no load on the head.
I personally prefer the actual tone of a cabinet over a sim, mostly because of the warmth and compression. I would try both out, especially since there are great options both ways. Since you mentioned warmth, try a few cabs. I suggest a 1x10 or 1x12 for balance of size/weight vs tone. YMMV


Natural Deduction Proof With Quantifiers

Question:
Here is a natural deduction proof where my answers are in the red.
I have questions on the following lines:
Line 8: Could we introduce an $\lor$ operator here? We have $\exists xQ(x)$ so with $\lor$ introduction we can say have it or anything right, because it is already true?
Line 12 and 13: We eliminate $\exists x (P(x) \rightarrow Q(x))$ on line 1 because there is more than one element in this statement. And we introduce $\exists$ on 13 because we proved that there is only one element that satisfies this.
Anything else in the red look incorrect?
Does the above sound correct? I am struggling with the $\exists$ part of this kind of proofs.
Answer: Line 8 is correct, exactly for the reason you said.
But there are other mistakes in your proof, most of them are related to the way to manage the existential quantifier.
The big external box (lines 3-12) is what you do to eliminate the existential quantifier $\exists x$ from premise 1 ($\exists x (P(x) \to Q(x))$).
Hence, the formulas in lines 12 and 13 must coincide and line 13, not line 12, is the rule $\exists_\text{elim}$ which closes the box.
So, in line 13, the formula is correct but the inference rule is $\exists_\text{elim}$ (1, 3-12).
Line 3 opens the box for to eliminate the existential quantifier $\exists x$ from premise 1 ($\exists x (P(x) \to Q(x))$), therefore the formula in line 3 (the assumption) must be the one in line 1 without the existential quantifier and with a generic term $c$ instead of $x$, i.e. $P(c) \to Q(c)$.
In line 6, you cannot apply $\to_\text{elim}$ to a formula that is not of the form $A \to B$ (premise 1 has the form $\exists x (A \to B)$, which is not the needed one).
The problem is that in your attempt of proof you didn't have such a formula.
But now we have it (line 3), so the correct inference rule is $\to_\text{elim}$ (3, 5).
In line 9 the assumption at the beginning of the rule to eliminate the disjunction $P(c) \lor \lnot P(c)$ must be exactly one of the two formulas in the disjunction, in this case $\lnot P(c)$, and not $\lnot P(x)$.
In line 12, the formula is correct but the inference rule is $\lor_\text{elim}$ (4, 5-11). Indeed, the two internal boxes are what you do to eliminate the disjunction in line 4, and line 12 is the rule $\lor_\text{elim}$ that closes the two boxes (and formula in line 12 is the same as the last ones in the two internal boxes, lines 8 and 11).
Comment: @M__ - Yes, exactly. And the box associated with that elimination rule is in lines 3-12.
Comment: Last question I have, is the reason on line 13 a $\exists$ elimination of line 1?


Removing and joining workstations to AD

Question: When removing and re-joining a workstation from and to AD, are there any drawbacks from dis-joining it from AD, without deleting the AD object, and re-joining it back? Please detail.
Answer: If you are dis-joining and re-joining the computer without changing its name it will continue to use the same computer object upon rejoining as it was using when it was disjoined. This does not cause any ill effects and is a pretty common practice.
If you rename the computer after dis-joining and then re-join a new computer object will be created and the existing "stale" computer object will remain in the AD database unused. You can clean up "stale" computer objects, in some cases, by querying all the domain controllers for the computer account's last logon date. This can be a problem, however, if a computer has not logged-on for awhile because it's simply been turned off.
Comment: I agree, I have never had any issues dis-joining and re-joining the domain, and I have done this several times over the years.
Comment: In this case System Center Configuration Manager creates a new client with no earlier data attached, making the first one obsolete. So you'll end up with two clients sharing the same name but different SID. You can delete the obsolete one or let the SCCM delete it after a while when running a cleaning script.
Answer: The problem can be with the SID of the object, in the computer pulled out of the AD you are deleting everything that linked that computer with the AD Object and re-joining it will cause discrepancies with the Object in the AD...

Removing and joining workstations to AD


Windows IIS6 site authentication

Question: I have a site running on IIS6 and I want to make it authenticate via the standard gray pop-up window. I.e. it should use Windows to authenticate. I want to make it so only one single user on the system can get in, not any user setup on the server. Its currently setup without anonymous access and with Integrated Windows Auth. Any user on the system can use their credentials to log in. How do I make it so only a single user can get it?
Answer: That sounds like two different problems... If you want your users to authenticate with the pop-up window (rather than just using their Windows credentials through NTLM or Kerberos), you would need to setup Forms Based Authentication (FBA) through ASP.Net (more information here: http://msdn.microsoft.com/en-us/library/aa480476.aspx)
As far as allowing only a single user to get in... you need to setup permissions (anonymous access will allow anyone in): http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/cf7f59d4-9ab9-4038-a482-d72d3e6f801e.mspx?mfr=true
Comment: When I say the gray pop-up, I'm talking about the Windows auth pop-up. I am using Windows auth, not FBA -- I don't want FBA. I guess my question is, how can I lock down the folder security so ONLY a specific Windows user can log in, not all of them?
Comment: Aaah, gotcha.  You can modify the NTFS permissions of the website (probably somewhere under C:\inetpub\wwwroot), or right-click the website in IIS Manager, choose permissions, and modify them there.
Comment: Walkthrough here: http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/ea46e264-32db-47a0-b755-2c2262fcc078.mspx?mfr=true
Answer: Yes you are correct there and that is how we are using it. We have multple websites on that server and our main site they are using LDAP to authenticate. We use local Windows Authentication on 2 other websites on that server.
I have setup the persmissions on the folder and it has worked for years with no issues till they started to mess with the authentication of LDAP.  I know it is two serperate areas but we are seeing the same results. Once the user logs in the index.php, index.cfm nor does index.html display. remove authenication and it works with no issue.  Its a funny problem to solve to be honest I am not sure if we have a DLL that may be bad but I show no errors in any logs.
The event viewer security log shows the user logged in successfuly but no webpage :(

Windows IIS6 site authentication


Error when trying to update a field in datagridview which is outer join

Question: I have two tables called appointment and patient which have relationship with each other. I use outer join on appointment form to display the pFirstName field of patient table instead of the patientID. Now I want to try updating the pFirstName at appointment form, etc changing adam name to something else and clicking update button, but it gives me Invalid column name 'pFirstName'. Only this field cannot work since it is outer join. the other fields like aStatus, aDate works fine. Previously I was using commandbuilder to generate the update so cannot work for outer join for update, so I have to switch to this method which is manually typing the update query. Any help???
APPOINTMENT FORM

APPOINTMENT AND PATIENT TABLE

Column 'patientid' does not belong to table following @Ralf advice

private void LoadAppointmentRecords()
        {

            //retrieve connection information info from App.config
            string strConnectionString = ConfigurationManager.ConnectionStrings["SACPConnection"].ConnectionString;
            //STEP 1: Create connection
            SqlConnection myConnect = new SqlConnection(strConnectionString);
            //STEP 2: Create command
            string strCommandText = "SELECT appointmentID, aDate, aTime, aStatus, aContact, aHeight, aWeight, pat.pFirstName, cen.mcCentre, nur.nFirstName FROM APPOINTMENT AS app";
            strCommandText += " LEFT OUTER JOIN PATIENT as pat on app.patientid = pat.patientid";
            strCommandText += " LEFT OUTER JOIN MEDICALCENTRE as cen on app.mcid = cen.mcid";
            strCommandText += " LEFT OUTER JOIN NURSE as nur on app.nurseid = nur.nurseid";

            /*
            string strCommandText = "SELECT appointmentID, aDate, aTime, aStatus, aContact, aHeight, aWeight, p.pFirstName , m.mcCentre , n.nFirstName FROM APPOINTMENT";
            strCommandText += " AS a LEFT OUTER JOIN Nurse AS n ON a.nurseID = n.NurseID";
            strCommandText += " Left outer join Patient as p on a.patientid = p.patientId";
            strCommandText += " left outer join medicalcentre as m on a.mcID = m.mcid";
            */

            AppointmentAdapter = new SqlDataAdapter(strCommandText, myConnect);

            //command builder generates Select, update, delete and insert SQL
            // statements for MedicalCentreAdapter

            // Empty Employee Table first
            Appointment.Clear();
            // Fill Employee Table with data retrieved by data adapter
            // using SELECT statement
            AppointmentAdapter.Fill(Appointment);

            // if there are records, bind to Grid view & display
            if (Appointment.Rows.Count > 0)
                grdApp.DataSource = Appointment;
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            string strQuery = string.Empty;
            string strQuery2 = string.Empty;
            DataTable dtChanges;
            //
            // Get the Updated DataTable back from the DataGridView
            DataTable dtAppointment = (DataTable)grdApp.DataSource;
            //
            // Get the Connection string from App.config.
            string strConn = ConfigurationManager.ConnectionStrings["SACPConnection"].ConnectionString;
            SqlConnection objConn = new SqlConnection(strConn);
            SqlCommand objCmd = new SqlCommand();
            //
            // Get the Modified Rows by filtering on their RowState
            dtChanges = dtAppointment.GetChanges(DataRowState.Modified);
            if (dtChanges != null)
            {
                //
                // Form the UPDATE Query to Update the Rows.
                objConn.Open();
                objCmd.Connection = objConn;
                for (int i = 0; i < dtChanges.Rows.Count; i++)
                {
                    strQuery = "UPDATE APPOINTMENT SET ";
                    strQuery += "aDate = '" + dtChanges.Rows[i]["aDate"].ToString() + "',";
                    strQuery += "pFirstName = '" + dtChanges.Rows[i]["pFirstName"].ToString() + "',";
                    strQuery += "aStatus = '" + dtChanges.Rows[i]["aStatus"].ToString() + "'";
                    strQuery += "WHERE appointmentID = '" + dtChanges.Rows[i]["appointmentID"].ToString() + "'";

                    //strQuery2 = "UPDATE APPOINTMENT SET ";
                    //strQuery2 += "pFirstName = '" + dtChanges.Rows[i]["pFirstName"].ToString() + "'";
                    //strQuery2 += "WHERE appointmentID = '" + dtChanges.Rows[i]["appointmentID"].ToString() + "'";

                    //
                    // Execute the Update Query.
                    objCmd.CommandText = strQuery;
                    objCmd.ExecuteNonQuery();
                }
                objConn.Close();
                dtChanges = null;
                MessageBox.Show("Record Updated");
            }

            else
            {
                MessageBox.Show("No update to change");
            }
        }

Trying to follow @Ralf advice I remove the var in each line of using (var objCmd = objConn.CreateCommand()) since it gives me A local variable named 'objCmd' cannot be declared in this scope because it would give a different meaning to 'objCmd', which is already used in a 'parent or current' scope to denote something else. But now i have this error, Column 'patientid' does not belong to table, whatever i try to update.
    private void btnUpdate_Click(object sender, EventArgs e)
{
    string strQuery = string.Empty;
    string strQuery2 = string.Empty;
    DataTable dtChanges;
    //
    // Get the Updated DataTable back from the DataGridView
    DataTable dtAppointment = (DataTable)grdApp.DataSource;
    //
    // Get the Connection string from App.config.
    string strConn = ConfigurationManager.ConnectionStrings["SACPConnection"].ConnectionString;
    SqlConnection objConn = new SqlConnection(strConn);
    SqlCommand objCmd = new SqlCommand();
    //
    // Get the Modified Rows by filtering on their RowState
    dtChanges = dtAppointment.GetChanges(DataRowState.Modified);
    if (dtChanges != null)
    {
        using (objConn = new SqlConnection(strConn))
        {
            objConn.Open();
            for (int i = 0; i < dtChanges.Rows.Count; i++)
            {
                long? patientid = (long?)dtChanges.Rows[i]["patientid"]; // you must return the id in your sql to distinguish a needed INSERT from an UPDATE

                if (!patientid.HasValue)
                {
                    using (objCmd = objConn.CreateCommand())
                    {
                        objCmd.CommandText = "INSERT INTO Patient(pFirstName) VALUES(@pFirstName); SELECT SCOPE_IDENTITY();";
                        objCmd.Parameters.AddWithValue("@pFirstName", (string)dtChanges.Rows[i]["pFirstName"]);
                        patientid = (long)objCmd.ExecuteScalar();
                    }
                }
                else
                {
                    using (objCmd = objConn.CreateCommand())
                    {
                        objCmd.CommandText = "UPDATE Patient SET pFirstName = @pFirstName WHERE patientid = @patientid";
                        objCmd.Parameters.AddWithValue("@pFirstName", (string)dtChanges.Rows[i]["pFirstName"]);
                        objCmd.Parameters.AddWithValue("@patientid", patientid);
                        objCmd.ExecuteNonQuery();
                    }
                }

                using (objCmd = objConn.CreateCommand())
                {
                    objCmd.CommandText = "UPDATE APPOINTMENT SET aDate = @date, aStatus = @status, patientid = @patientid WHERE appointmentID = @appointmentID";
                    objCmd.Parameters.AddWithValue("@date", (DateTime)dtChanges.Rows[i]["aDate"]);
                    objCmd.Parameters.AddWithValue("@status", (string)dtChanges.Rows[i]["aStatus"]);
                    objCmd.Parameters.AddWithValue("@patientid", patientid);
                    objCmd.Parameters.AddWithValue("@appointmentID", (long)dtChanges.Rows[i]["appointmentID"]);
                    objCmd.ExecuteNonQuery();
                }
            }

            objConn.Close();
            dtChanges = null;
            MessageBox.Show("Record Updated");
        }
    }

    else
    {
        MessageBox.Show("No update to change");
    }
}

Comment: You are updating APPOINTMENT but pFirstName is not part of APPOINTMENT. You need to UPDATE, INSERT OR maybe even DELETE on PATIENT if the pFirstName column has changed. First Insert or Update Patient retrieve the patientid and then update APPOINTMENT with the retrieved patientid.
Comment: Hmm, duno how to do it. Erm, now I have a strQuery at the update button there, I need to create another which is strQuery2 which is to update patient and retrieve patientid is it? @Ralf
Comment: Yes. Retrieving patientid is only needed when there was no Patient before and you need to execute an INSERT on the Patient Table. In the other case when an UPDATE is needed you should have it already. Just fetch patientid also with you initial select.
Comment: I updated my post. Is it like this? update patient table pFirstName too after appointment table pFirstName? But I duno about retrieveing the patientID.. @Ralf
Comment: No you still try to update pFirstName in Appointment Appointnment has no pFirstName it just has a patientid that might be updated if a new patient is created and attached top the appointment. And you should update patient before appointment since teh patient can be new. I tried a little guessing and put it in an answer.
Answer: I guessed the datatypes in your DataTable and cleaned up the code (especially using Usings and Parameteres). You will need to return the patientid in you select Statement also to get it working this way.
if (dtChanges != null)
{
    using(var objConn = new SqlConnection(strConn))
    {
        objConn.Open();
        for (int i = 0; i < dtChanges.Rows.Count; i++)
        {
            long? patientid = (long?)dtChanges.Rows[i]["patientid"]; // you must return the id in your sql to distinguish a needed INSERT from an UPDATE

            if (!patientid.HasValue)
            {
                using (var objCmd = objConn.CreateCommand())
                {
                    objCmd.CommandText = "INSERT INTO Patient(pFirstName) VALUES(@pFirstName); SELECT SCOPE_IDENTITY();";
                    objCmd.Parameters.AddWithValue("@pFirstName", (string)dtChanges.Rows[i]["pFirstName"]);
                    patientid = (long)objCmd.ExecuteScalar();
                }
            }
            else
            {
                using (var objCmd = objConn.CreateCommand())
                {
                    objCmd.CommandText = "UPDATE Patient SET pFirstName = @pFirstName WHERE patientid = @patientid";
                    objCmd.Parameters.AddWithValue("@pFirstName", (string)dtChanges.Rows[i]["pFirstName"]);
                    objCmd.Parameters.AddWithValue("@patientid", patientid);
                    objCmd.ExecuteNonQuery();
                }
            }

            using (var objCmd = objConn.CreateCommand())
            {
                objCmd.CommandText = "UPDATE APPOINTMENT SET aDate = @date, aStatus = @status, patientid = @patientid WHERE appointmentID = @appointmentID";
                objCmd.Parameters.AddWithValue("@date", (DateTime)dtChanges.Rows[i]["aDate"]);
                objCmd.Parameters.AddWithValue("@status", (string)dtChanges.Rows[i]["aStatus"]);
                objCmd.Parameters.AddWithValue("@patientid", patientid);
                objCmd.Parameters.AddWithValue("@appointmentID", (long)dtChanges.Rows[i]["appointmentID"]);
                objCmd.ExecuteNonQuery();
            }
       }
  }

}
Comment: Omg can;t undestand, anyway I have updated my codes and added a image above, what;s wrong? I got error @Ralf
Comment: Don't remove the var. Remove your predefined objCmd Object in your code. Its not used. The commands get defined and initialized in the using block.
Comment: And to solve the problem shown in the screenshot you need to change the select statement in the LoadAppointmentRecords method. It must return patientid.


0% of the site has been indexed. There are 400 items left to index

Question: Drupal core search doesn't re-index the site and it always shows this message.

0% of the site has been indexed. There are 453 items left to index.

What settings do I need to change to make Drupal re-index the site properly?
Answer: You need to run cron.  Because building the search engine can take time, Drupal does it on cron runs (the scheduling system).
First, to make sure everything is OK, run cron manually from <code>/admin/config/system/cron</code> to ensure that the search items get indexed.
Then set up cron to run automatically following the instructions in the documentation.


From a development standpoint, what are the advantages/disadvantages of the major Content Management Systems?

Question: I'm interested in using a CMS instead of building a website from scratch. However, as a software engineer, if I'm going to be using open-source tools, I'm going to use them to their full extent, including the possibility of developing plugins/extensions/modules and maybe even contributing core code.
I'm currently looking at WordPress, Drupal, and Joomla!. They all appear to have the features I need, either as core features or plugins. However, I'm curious how hard it is to learn the system and then develop for it.
Does anyone have experience with this? When using and developing WordPress, Drupal, and/or Joomla!, what were your experiences like?
Comment: Given the three systems mentioned, I'd say PHP is a safe bet. ;-)
Answer: I avoid Joomla like the plague. It is highly difficult to extend, especially if your use case isn't one of the ones their devs specifically designed the CMS for. Great if you want to do a small business brochure site, but if you're looking to heavily customise... ditch it. The pay-to-play nature of much of the dev community is a turnoff, too.
WordPress is very heavily specialised in the blogging direction. If that fits your needs, go for it - it's a slick, well supported, system. If you're looking for something that's a bit more complex in a CMS, though, go with...
Drupal. My favourite PHP CMS, hands down, with the exception of blogging. Functions like hook_nodeapi, hook_user, hook_form_alter, etc. make it essentially effortless to heavily tweak the function of nearly everything in the system. If I want to replace the password field in the user login form  with an upload field and MD5() the uploaded file to verify the user, I can do that - without hacking core code, and in a few lines of form alteration and validation code. Pretty astounding the first couple times you do something slightly nutty like that.
Comment: It has a pretty extensive set of hooks. Can't manipulate quite as much as Drupal, but there are a lot of injection spots for plugins that allow you to tweak, add code, etc. without having to hack the core.

Documentation at times is a bit sparse, but there's such a large development community (including this site) that it's quite easy to get assistance when you get stuck.
Comment: Could you elaborate any more on WordPress development (both core development and extension development)?
Answer: I haven't used Joomla much and have never really needed to tweak Wordpress outside the design but have used Drupal quite extensively. Drupal seems to be becoming the standard for PHP CMS' which I think is quite a shame given how much is wrong with it. I won't try to tell you why you should use it, or shouldn't, but here's a few things that I find really annoying with it.

Complete lack of OOP. Ok, in Drupal 7 they're finally doing some OOP with the Abstraction Layer but the community as a whole still shuns the entire concept of OOP as it applies to the CMS as a whole. And given their dependence on modules and third party code doing a decent OOP setup would help keep the code more organized. Currently to avoid naming conflicts you need to prefix all functions and constants with your module name which can lead to some very long function names which can lead to some very long lines of code which can make things a little less readable than doing something like $node->parent()->parent()->title;
Drupal content is completely unorganized. When doing an information heavy site it's imperative that you have well organized content and Drupal simply doesn't allow this. Drupal's content management is just one large list of nodes with a few filters you can apply. There are ways you can use Drupal's taxonomy system and other modules to setup relationships but I've never found any that actually make the interface easier to navigate and make it easy to manage the content on the templates. At work I've created a module that allows this but it's required dumping weeks worth of development time into it a simple feature that any good CMS should come with out of the box.
The admin interface is absolutely rancid. This one pretty much speaks for its self but install a copy of Drupal and click around. Then take a look at say, the Radiant interface (Radiant is Rails I know, but we're talking UI here). Another example of a good UI for the admin would be FrogCMS, a PHP port of Radiant.
No ORM, and absolutely no attempt to have one, means you better like writing lots of SQL to get the data you need. While I generally have no problems with writing my own SQL it's starting to get a bit old when most good frameworks and CMS' built on them have at least some kind of ORM for you to use. Even if it's a botched one.
Drupal loves to use non-standard file extensions (.module, .info, .install, .inc, etc) so you better make sure your htaccess and/or virtual host is setup to not allow direct access to these files or all your source code will be wide open for the world to see.

Personally I think FrogCMS looks like it's off to a good start to be an up-and-comer if the maintainers allow the community to contribute to it and allow it to grow. You'll need to do more coding as it doesn't have a big feature set out of the box and doesn't have a plugin repository like Drupal or Joomla but from a coding standpoint it's setup with a pretty well done, albeit basic, MVC implementation that will help your code be more organized and easier to maintain.
Comment: #2: Completely unorganized? Content types, node reference fields, and the like make associating nodes together a cinch. #4: ORM exists in Drupal 6 - http://api.drupal.org/api/function/drupal_write_record/6.
Comment: OOP and admin interface are matters of familiarity and opinion. Non-standard file extensions are dealt with in the .htaccess if you're using Apache.
Comment: A single function, or even a couple, does not constitute an ORM. Take a look at Doctrine or ActiveRecord and notice their feature sets and what they're capable of doing. And part of my mentioning the non-standard file extensions is that is causes another potential point-of-failure in the application that needs to be maintained outside the application.
Comment: So "ORM" is defined as "an ORM that is complicated enough for Steven to like it"?
Answer: I've only developed for Joomla! and have been a user of wordpress, but Joomla! development is too clumsy if you want to completely change the layout. Writing a plugin or 'component' is fairly easy if you know the way around the code, but getting it to do exactly what you want isn't so easy because it likes to force you to use it's MVC design pattern which I find too clumsy.
I've seen both the Joomla! and Drupal code base, and I'd say that Joomla!'s code is much cleaner and better documented. It also heavily uses the MVC design pattern which can be good or bad depending on your preference and what you want to use it for. It has the most extensive use of OO programming in any php project I've seen.
I haven't developed for wordpress, but as a user, automatic updates are a godsend! plugins and themes can be found and installed through an interface in wordpress itself, so as a developer you save a bit of time in trying to promote your plugin because it gets made available to everyone right away. Heavy modifications might break some of of this though, so I wouldn't recommend it if you want to modify it a lot.
Joomla!'s plugin community is heavily monotized, but there is a huge community of plugin developers. I don't know about Drupal, and most wordpress plugins are free. So that's something to consider as well if you plan on using third party plugins.
Comment: Drupal and WordPress have large plugin communities, and GPL is enforced on both of their official listings.

Joomla's code may be cleaner (I can't speak to that, haven't looked), but somewhat messy and functional beats out clean and non-functional in my book any day.
Comment: Also - even if Joomla's core code is cleaner (again, can't speak to), the third-party modules I looked at were often horrid.
Comment: Yeah, I've seen some horrid third party plugin code myself, but I'm not saying that it's non-functional, just that (at least in version 1.5+) you are forced to use OOP and the MVC design pattern which makes it harder. This can be good if you come from a java background, because coding in joomla really feels like coding a webapp in java, but it'll take a while to get used to if you're more familiar with the usual anything goes php background.
Answer: over the years, i began hating PHP, since i had to work a lot with it until i found good alternatives, so the first question i ask you is: does it have to be PHP?
but staying with PHP i'd add the following:

most people like Drupal a lot because of it's extensibility ... that's fine, but it still has some design problems ... it's is very potent and flexible and has a huge user base -> lot of plugins, big community to ask for advice etc.
when it comes to Joomla, one has to say, that in the past, this has been a really a complete mess ... but in version 1.5 the whole thing was redesigned and is now very clean ... i always laughed down at joomla, but recently i had a talk with some other developer i had worked with on several occasion, who quite conviced me, that it has become a developer friendly software ... plus, it is soooooooo damn easy to administrate ... i know no other CMS that is so easy to use (and is a "real" CMS, not a forum or blogging engine)
you might wanna have a look at Vanilla CMS ... very sexy, still slick and powerful ...
use a CMS based on a good PHP framework ... typo3 (Flow3 (IMHO really the most funky PHP framework)), something based on symfony (can't find anything, but this should be a good start), mambo (CakePHP) or maybe something based on code igniter ... you will always need to get familiar with the framework, but a) this is always good, b) if the framework is good, the app is likely to be good and extensible, c) you yourself will have a high productivity when building extensions since the framework will do a lot for you ...

finally, you might wanna have a look at opensourcecms ... always helpful ...
good luck with your choice then ... ;)
greetz
back2dos


Algoritmo de fatorial em Portugol Studio

Question: Eu tenho esse algoritmo:
programa
{
    inteiro numero, fatorial, resultado=1

    funcao inicio()
    {
        escreva ("Insira um número a ser fatorado: ")
        leia (numero)

        para (fatorial = 1; fatorial <= numero; fatorial++)
        {
            resultado = resultado * fatorial
        }

        escreva ("O fatorial de ", numero, " é: ", resultado)
    }
}

Que me retorna corretamente o fatorial. Mas como que eu faço pra ele retornar toda a matemática?
Ex.:

5! = 5x4x3x2x1=120
Answer: A primeira coisa que você precisa ter em mente é que o loop (para) precisa estar ao contrário. Isso porque vai ficar mais fácil para concatenar as multiplicações numa string (variável do tipo cadeia).
Por exemplo, o fatorial de 3 tem resultado 6 a representação seria 3! = 3x2x1 = 6. Perceba que é bem mais fácil fazer a concatenação do texto se a multiplicação começar pelo 3.
Tendo isto em mente, segue o algoritmo
inteiro numero, fatorial, resultado = 1
cadeia texto = "" //Variavel para salvar a representação final (3x2x1)

escreva ("Insira um número a ser fatorado: ")
leia (numero)

/* Perceba que aqui o loop (para), corre de trás pra frente. Ou seja, ele começa no número
 * que foi digitado pelo usuário (fatorial = numero), acontece enquanto o multiplicador
 * for maior ou igual a 1 (fatorial >= 1) e vai diminuindo 1 do multiplicador
 * a cada passada (fatorial--) */

para (fatorial = numero; fatorial >= 1; fatorial--)
{
    // Aqui, se for 1 não precisamos concatenar o sinal de multiplicação (x)
    se(fatorial == 1){
        texto = texto + fatorial
    }senao{
        texto = texto + fatorial + "x"
    }

    resultado = resultado * fatorial
}

escreva (numero, "! = ", texto, " = ", resultado)

Comment: Rapaz é isso aí mesmo! Eu preciso melhorar a minha lógica! Eu já tinha desistido desse algoritmo! Vlw jbueno!
Comment: @SandsonCosta Por nada. Sempre que precisar pode postar aqui, as vezes demora um pouco, mas perguntas bem feitas sempre serão respondidas.
Answer: texto t = ""
para (fatorial = numero; fatorial >= 1; fatorial--) //Realiza o decremento
{
    if(fatorial != 1){ //Verifica se diferente de 1 para não adicionar o "x"
       t = t + fatorial + "x"
    } else {
       t = t+ fatorial
    }
    resultado = resultado * fatorial
}
escreva (fatorial, "! = ",t , " = ", resultado)

//Fazem anos que não vejo portugol
Comment: O que seria esse texto t = " " ?
Comment: Eu fiz aqui o código... não deu o resultado direito...
Comment: @Sandson Costa esse t="" é a cadeia que irá definir o caracter ou a palavra em específico


Why is logistic regression giving a better prediction than linear reg in XGBoost?

Question: I am building a predictive model with 7 features. My target is binary. I have tried using XGBoost in R.
bst <- xgboost(data = as.matrix(trainSet[,predictors]),
               label = trainSet[,outcomeName], max.depth=10,
               nround=1000, objective="reg:linear", verbose=0)
pred <- predict(bst, as.matrix(testSet[,predictors]), outputmargin=TRUE)
rmse(as.numeric(testSet[,outcomeName]), as.numeric(pred))

Since my target is binary, I used logistic regression. But the prediction quality goes very bad compared to linear regression. Is it OK to use linear regression or am I overfitting? Misclassification is 23.4% with linear regression but it goes 47% with logistic.
Comment: Can you provide a [reproducible example](http://stackoverflow.com/q/5963269/1217536)? It isn't clear to me if this will be answerable as posted.
Comment: You're evaluating your model with rmse, is this a good choice for a probabilistic model with a binary response?
Comment: as @gung mentioned. with such information, this question is impossible to answer...
Answer: I think Matthew Drury had the answer. In the last line of the code, you are using rmse, which is not 0-1 loss on your testing data. That could be one reason.
On the other hand, with the information there there is no way to answer this question. Because we do not know what is trainSet and testSet.
If you want to know if you are over fitting, you can change the number of iterations (nround) and observe the performance respect to number of iterations.
Details can be found in following link (although it is the question tile has SVM, but my answer uses boosted trees as example.)
How to know if a learning curve from SVM model suffers from bias or variance?


Usar múltiplas base de dados

Question: Não tenho muito conhecimento sobre banco de dados e nunca trabalhei com sistemas grandes... Estou criando uma aplicação com CakePHP que servirá de webservice para dois tipos de clientes distintos, um cliente é simples e só terá um relacionamento de tabela, o outro cliente é mais complexo e terá mais volume de dados e relacionamentos com tabelas (tabelas que não se relacionam com o cliente 1 e vice versa) e os dois clientes usarão aplicativos android diferentes.
Eu sempre usei 1 banco de dados para uma aplicação, e notei que sistemas como wordpress e joomla usam, mas imaginei, já que terei 2 aplicativos diferentes mas com o mesmo objetivo, seria melhor usar dois bancos de dados? (um para o cliente1 e outro pro cliente2).
Pela lógica seria melhor... Mas e se eu precisar ter uma tabela relacionada entre os dois tipos de clientes?
Estou usando MariaDB
Comment: são clientes distintos que usam o mesmo sistema, por exemplo no app do ifood tem o cliente que quer comprar comida e o cliente que quer anunciar, eles usam aplicativos diferentes e tem cadastros semelhantes, mas diferentes, o meu aplicativo segue esse modelo, com outro objetivo. Também não consigo imaginar um cenário que isso possa ocorrer, talvez não aconteça ou talvez sim. Também nunca vi alguém fazendo assim. Mas creio que vou separar os bancos, fica mais organizado, e é melhor na hora de realizar backups
Comment: [Relacionado](http://pt.stackoverflow.com/q/32270/215). Há vantagens e desvantagens de se usar bancos distintos pra clientes distintos, mas como no seu caso a *aplicação em si* é suficientemente distinta de um cliente pro outro, eu diria que bancos separados é o caminho mais recomendado. Ainda que eles tenham algumas tabelas semelhantes (mas não compartilhadas), é melhor repeti-las em um e outro banco, compartilhando somente os módulos de software que criam e gerenciam essas tabelas.
Comment: A performance ficaria melhor? levando em conta que os dois  bancos estão no mesmo servidor. O problema seria futuramente tivesse que implementar uma tabela relacionada entre os dois... Isso não tem como fazer né?
Comment: Não sei se a diferença de performance seria significativa. O fato do SGBD ser o mesmo ameniza as coisas - se fossem dois SGBDs diferentes, aí sim eles iam "brigar" pelos recursos da máquina... Quanto a uma tabela relacionando os dois, só no mesmo banco mesmo. Se você precisar de integridade referencial, é claro. Mas eu tenho dificuldade de imaginar um cenário em que os dados de dois clientes distintos precisem ser relacionados; são mesmo clientes distintos, ou apenas **usuários** distintos de um mesmo cliente? (tipo, dois departamentos numa mesma empresa).
Comment: @mgibsonbr cria uma resposta para o conteúdo
Answer: Quando se tem uma única aplicação e vários clientes diferentes, pode ser vantajoso ter um único banco de dados atendendo a todos (como você afirma ser o caso do Wordpress e Joomla). Isso não vem sem desafios, entretanto - veja minha resposta a essa pergunta relacionada para um exemplo real de como isso pode ser feito, e dos cuidados que precisam ser tomados para os dados de um cliente não se misturarem com os de outro. Esse artigo sobre multi-tenancy cita outras estratégias possíveis, como usar a mesma aplicação mas bancos diferentes, ou mesmo instâncias separadas da aplicação para cada cliente (estratégia que eu próprio usei em um projeto recente).
Se é ou não vantajoso manter um único banco para todos os clientes, seja do ponto de vista do desempenho ou da manutenção, é discutível. Pessoalmente, creio que um único banco traz mais agilidade para cadastrar e descadastrar clientes (basta inserir/apagar registros de uma tabela, em vez de criar/destruir bancos inteiros), enquanto múltiplos bancos torna mais simples fazer backups (não é preciso se preocupar com dados de um cliente indo parar nos backups de outro) e talvez simplifique o crescimento em escala (dá pra escalonar sistemas com banco único também - através de particionamento "vertical" ou "horizontal" - mas não tenho experiência prática suficiente para comentar).
No seu caso, entretanto, o fato dos clientes - e da aplicação que os servirá - serem substancialmente diferentes um do outro é praticamente o argumento decisivo para se escolher ter bancos separados; um fator complicador na arquitetura multi-tenant é justamente como customizar a experiência de um cliente sem "quebrar" o sistema para todos  os outros (se o cliente quer um campo a mais na tabela X, você não pode simplesmente colocar, pois do contrário todos os outros também teriam de receber aquele campo). E nesse caso o fator está presente desde o início, pois você sabe que vai precisar de estruturas de dados (e código) diferentes...
Quanto a um cliente precisar referenciar o outro na sua base de dados, eu diria pra não se preocupar muito com isso: em primeiro lugar porque esse caso não está previsto, é só uma especulação "e se?", e até onde eu saiba esse não é um cenário nem um pouco comum; segundo, porque mesmo que no final acabe precisando, a falta de integridade referencial (i.e. não poder criar chaves estrangeiras de um banco pra outro, com garantia de integridade) não deve ser um problema tão grande que não possa ser tratado na sua camada de aplicação.

Usar múltiplas base de dados


Counting numbers vs Natural numbers; Peano Axioms

Question: I can feel that my question is going to be a somewhat lengthy one, but I will try my best to deliver it in as short a form as I can manage.
So to begin, I've always thought that the numbers such as 1, 2, 3, etc. exist outside of the realm of mathematics, i.e., one does not need to "define" what it means to have ONE apple, TWO apples, etc. Following this line of thought, we can also believe that there is a natural concept of "order" for instance, we can always determine which basket has "more" apples (of course, so long as they hold only finitely many of them). In sum, we have the concept of "unity", which we will represent as the symbol 1, the concept of "quantity immediately follows the unity", which we will write as 2, and so on. So it makes sense to talk about these "numbers" without ever invoking the concept of natural numbers, and we can even develop the method of mathematical induction on this set. I will call this "naive" set as the counting numbers, since they are what you use to "count" things.
Now, there is what is called the Peano Axioms, which in essence declare the qualities that any candidates of "natural numbers" must possess. Clearly, the above mentioned set {1,2,...} meets this criteria if we define 2 to be the successor of 1, 3 to be that of 2, etc.
But here is the question: to me, it seems all fine to just have these "naive" set of "symbols" i.e., $\{1,2,3,\ldots\}$ that we will casually call natural numbers. We can go all fancy and define additional properties such as addition, multiplication, etc., but the fact remains that these are NOT the fruit of human creation, but something that inherently exist in "nature" (hence the name natural numbers, I presume). So, why do we bother in the first about these Peano Axioms? Is there a necessity to include in our system of natural numbers sets as $\{-1,-2,-3,-4,\ldots\}$, $\{\frac12,\frac 32, \frac 52,\ldots\}$,$\{e,e+1,e+2,\ldots\}$, etc.?
Thanks in advance
Comment: Your statement that the natural numbers are something that inherently exist in nature is a view on a very ancient philosophical question, and that question, I believe, is devoid of mathematical content (which is probably quite a strong philosophical statement on my part). I think your question would be more appropriate for http://philosophy.stackexchange.com
Comment: Is one of your questions, "*Since* the natural numbers clearly exist, why do we bother to define them?"
Answer: First off, the distinction you're attempting to between "counting numbers" and "natural numbers" doesn't match how the words is usually used in mathematics. To a mathematician, "the natural numbers" in general means the pre-formal concept you're calling "counting numbers". (And the phrasing "counting numbers" generally isn't used at all). In particular, being a model of this or that formal system doesn't qualify anything as being the natural numbers; only the true Platonic natural numbers are natural numbers.
(That's except for people who have learned enough set theory to know how natural numbers are usually modeled there, but haven't yet gained a sufficiently wide horizon on the matter to know that the model is not the actual thing).
Whether the natural numbers are a human invention or not is something of a philosophical morass that I won't go into -- but the mere fact that they were not created by Peano is not a controversial statement.
Now, since we understand the naturals intuitively, at least to a pretty good extent, what do we need axioms for? Well, most primitively, to see how well we can do by reasoning purely mechanically from axioms. For example, it led to a significant improvement in geometrical reasoning when the ancient Greeks started demanding rigorous proofs from axioms rather than just geometrical intuition; it is natural to wish to know whether something similar could be done for arithmetic.
As it happens, it took many centuries after the Greeks before formal mathematical reasoning had progressed enough that it was thinkable that it might be possible to reason about integer arithmetic without depending on intuition. Peano's axioms were not aimed at telling anything new about the integers -- he was simply one of the first to have a sufficiently well developed notion of formal logic that he could hope to make an axiomatic treatment of the integers work.
The goal of the investigation, then, is not primarily to discover something new about the integers themselves, but to see whether a formal system can be made to support a "mechanical" reasoning about them that is rich and strong to conclude what we already know about them intuitively.
The Peano axioms (and their modern first-order successor, Peano Arithmetic) were somewhat successful in that, but nonetheless the crowning achievement of the whole program turned out to be a negative result: Gödel's Incompleteness Theorem tells us that every reasonable formal system for proving things about the integers will be incomplete: there are truths about the natural numbers that it cannot prove.
Nevertheless, it is still interesting in itself to investigate the strength and properties of various such formal systems.
Also, of course, it is pragmatically useful that when something can be proved in a formal system with few axioms to it, then it is very certain to be true about the actual naturals ... there's a much smaller risk of having overlooked something during the proof than if we base our reasoning purely on an intuitive understanding of how the naturals ought to behave. In this way it's kind of a gold standard for a proof that it can (in principle) be reduced to Peano Arithmetic or a similarly bare-bones system. We recognize that there will be things that can't, but these exceptions will be subject to a lot more scrutiny before one considers oneself convinced that they are in fact true.
Answer: There are people who will disagree with you. They think that the natural numbers end somewhere. There is a largest natural number.
Can you argue with beliefs? Thousands of years of human history taught us that the answer is more or less negative. If I believe that the natural numbers have an end somewhere, there is nothing you can do to convince me otherwise.
So you might say now, "okay, but suppose that for the sake of proof there is no largest number and now proceed ..." so I'll argue again, I disagree about the definition of addition, and I disagree about the order and about multiplication and so on and so forth. I mean, sure, I am willing to agree with your definition which "clearly" and "obviously" seem true all the way up to $2^{1000000}$. But not a single number above that. After $2^{1000000}$ everything goes haywire!
Can you prove me wrong? Can you convince me that my belief is somewhat mistaken? No, you probably can't, again look at history.
So you want to say now "Okay, fine, but suppose that you agree with me about the basic definitions ..." and then you show me a proof about one thing or another.
What happened here? You essentially wrote me a list of properties which you think are obviously true for the natural numbers, and then you showed that if those properties are indeed true then some proposition is also true.
So what you really did was to write down some axioms and claim that from those axioms you can prove something. The axioms for the natural numbers are no different than that. They help us put aside whatever belief we have and agree that these axioms, at least for sake of argument, are all true in the natural numbers. Then we can start proving all sort of things.
Answer: Just to add a different perspective, counting numbers go with the idea of the first, second, third etc and this idea is formalised in mathematics by the notion of ordinal numbers. You don't need to formalise the idea, but formalisation goes with making things precise so that simple observations can be generalised.
There is a different concept of number associated with measuring - "the same size as four", for example. This is captured in various ways, including in cardinal numbers. But the concept of measuring is different from the concept of counting, for example in the need to measure fractional or continuous amounts. The formalisation of cardinality gives an isomorphic structure for the positive integers, but is mathematically distinct for infinite cardinals.
So even in thinking naïvely about numbers, the concepts of order and measure arise. The first is discrete and the second is continuous even in informal thinking. Making these ideas precise is tricky (it took clever mathematicians centuries to pin the ideas down).
Answer: Peano's axioms give us the (usually 5) essential properties of these "counting numbers" from which, it appears, all of their known properties can be derived. There is no axiom that no number is its own successor, for example, but we can prove it using only Peano's axioms and the rules of logic.
As far as we know, all of current number theory, if not all future developments in the field (see Godel), can be derived from Peano's Axioms using the rules of logic and the axioms of set theory. In the most commonly used version of Peano's axioms, there is no mention of addition, multiplication or exponentiation, but you can construct each of them (i.e. prove their existence) using logic and set theory. It is even possible, to construct the real and complex numbers.
Just how "natural" are Peano's axioms? I think each can be easily justified at a very intuitive level. (See "What is a number again?" at my math blog.)
But if you really insist on constructing the natural numbers from some other, simpler structure, you can do so starting with a set $X$ on which we have function $f: X \to X$ such that is $f$ is injective, but not surjective (i.e. $X$ is Dedekind-infinite). From this set, you can extract a subset $n$ that satisfies all of the Peano axioms, including induction, where $f$ is used as the successor function. (See "Daddy, where do numbers come from?" also at my math blog.)


Highest Points to finish Runner-Up in Champions League Group? Lowest points to win Champions League Group?

Question: Theoretically, you could finish second even with 15 points. And win the group with just 5 points. But, in reality what are the records?
Is it Arsenal (with 13 points) this season and Monaco (with 11 points) this season?
Answer: Most points achieved in the group stage, not winning the group (2nd): Manchester City, 15, 2013-2014.
Most points achieved in the group stage, yet knocked out (3rd): Napoli, 12, 2013-2014.
Fewest points achieved in the first group stage, yet won the group: Juventus, 8, 1998-1999 and Milan, 8, 1993-1994.‡
Fewest points achieved in the second group stage: Valencia, 9, 2002-2003 and Barcelona, 2001-2002.
Fewest points achieved in the group stage, yet advanced: Milan, 5, 1994-1995.‡
‡ Prior to 1995-1996 season two points were awarded for a win instead of three.
Source
Comment: Valencia and Barcelona, which you mention as teams to win a group in second group stage with fewest points, actually had 9 points, not 8.
Comment: I think it's essential to mention that prior to 1995/96 UEFA Champions League season **two points** were awarded **for a win** instead of three. So, keeping that in mind, Milan would accumulate 10 points in 1993/94 and 8 points in 1994/95.


Como printar algo dentro da janela em Python

Question: def text():
    print('Olá, mundo!')

from tkinter import *
janela = Tk()
janela.title('Teste')
janela.geometry('800x800')
botao = Button(janela,text='Clique aqui',command=text)
botao.grid(column=0,row=0)
janela.mainloop()´´´

Ao clicar no botão, o texto só é printado dentro do IDE, queria que fosse possível printá-lo para a janela do programa, de modo a ficar visível para qualquer usuário, sem precisar necessariamente ver o código.

Answer: Olá, para criar um label com texto modificável você irá precisar de um label e uma stringvar, abaixo segue um exemplo:
from tkinter import *

master = Tk()
label_var = StringVar()
label = Label(master, textvariable=label_var).pack()

def msg():
    label_var.set('Olá Mundo')

button = Button(master, text="Mostrar Mensagem", command=msg)
button.pack()

mainloop()

Quando você usa o 'print' o resultado é exibido apenas no console/prompt
Comment: Obrigado pela resposta. Porém, gostaria de saber o que exatamente faz a função "pack(_)"?
Comment: O pack é o gerenciador de layout do tkinter, ele coloca como visível seu widget, outras opções são o place() e o grid(), cada um funciona de uma forma


Clear value and dropdown of ng-select after select the value

Question: I am working on an angular 8 project which contains ng-select dropdown. It is a combination of typehead and ng-select. So that I can fetch the data from the api in real time. The dropdown is working fine. But I am unable to find a functionality.
I need to make the selection and the pre-filled dropdown get cleared after I make the selection.
I am able to clear the selection. But I have no idea on how to clear the dropdown which is already filled with the previous search data.
I am using this.selectedCustomer = null; to clear the selection.
and I tried the answer given in this question and it also giving the same result.
I tried it like
@ViewChild(
'customerSearch', {
  static: true,
  read: NgSelectComponent
}
) customerSearch: NgSelectComponent;

and
this.customerSearch.handleClearClick();

This is doing the same purpose of this.selectedCustomer = null
My html is
<form [formGroup]="heroForm">
<ng-select
[items]="customers | async"
bindLabel="name"
[addTag]="addNewPersonRef"
addTagText="Add new person"
[hideSelected]="false"
[trackByFn]="trackByFn"
[loading]="customerLoading"
[typeahead]="searchInput"
[(ngModel)]="selectedCustomer"
[ngModelOptions]="{standalone: true}"
(ngModelChange)="openCustomerWindow($event)">
<ng-template ng-option-tmp let-item="item" let-search="searchTerm">

{{item.name}}

   {{item.fileId}}     {{item.qid}}
</ng-template>
</ng-select>
</form>

Is there any option to clear the already filled dropdown programatically? Any help could be appreciated. Thank you.
Comment: have you tried clearing `customers`?
Answer: In your HTML:
[items]="customers | async"

This is where the different options are, emptying it should clear the dropdown.
Answer: Add param clearSearchOnAdd - clears search input when item is selected. Default true. Default false when closeOnSelect is false:
[clearSearchOnAdd]="true"


How to solve $\lim _{ x\to 0 } \frac { { \sin }^{ -1 }x }{ x }$?

Question: Solve the following equation:

\begin{eqnarray}
\lim _{ x\to 0 } f(x)= \lim _{ x\to 0 } \frac { { \sin }^{ -1 }x }{ x }\\
\end{eqnarray}

The answer in my book is 1.
Can I do this?

\begin{eqnarray}
\lim _{ x\to 0 } \frac { { \sin }^{ -1 }x }{ x }=\lim_{x\to 0} \frac{1}{x\sin x}
\end{eqnarray}

I think $\sin^{-1}x$ is an inverse, not equal to $(\sin x)^{-1}$, so I can't do this. Right?
Are there any easily ways to deal with $\lim_{x\to a}$ including $\sin^{-1}x$, $\cos^{-1}x$ and $\tan^{-1}x$?
I have no idea to deal with this question.

Thank you for your attention.
Answer: HINT:
Put  $\sin^{-1}x=h\implies x=\sin h$ and as $x\to0,h=\sin^{-1}x\to0$
Comment: Apart from Lab's correct answer, Casper, do you understand your mistake, i.e. that the inverse sine does NOT pop up as a regular sine in the denominator? That's very important!
Comment: Since $h=sin^{−1}x$, then $x=sinh$. If x→0, h can be 0, $\pi$, or $2\pi$ [0, $2\pi$]. However, the denominator is still 0 so the calculator returned me "Error Math". Sorry, I don't understand.=(
Comment: @CasperLi, http://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Principal_values
Comment: @Casper: There are a few problems with that. For one, the range of $\sin^{-1}x$ is $\left[-\frac\pi2,\frac\pi2\right],$ so $h$ cannot be $\pi$ or $2\pi$. For another, we aren't just "plugging in $0$," but rather taking a limit.


Duplicated results using fields from relation File Usage: file

Question: I have a content type with a field image and a field file. I made a simple view to get all items of that content. I included in my view a relation ¨File Usage: File¨ to get some data like file size, upload date and uri of file field and for using VBO to download all files.
Now Im getting duplicate results, all data (file size, upload date, vbo) for image field and the same for file field when I just want to get the information for the file field, the image is just a thumbnail. Any ideas of how to get real results over duplicates?
Comment: And checking "reduce duplicates" in the Views advanced settings doesn't help?
Comment: Nop, I already tried but remains duplicated
Answer: You need to add a File relationship for a specific field, not a File Usage relationship.
In the options for 'Add relationships' select the 'File' filter and you should see an option for each field e.g. 'File: Content using My Field'. Use this and it will give you the same data (file size etc.) but just for files attached to that field.
Comment: Excellent! it works like a charm! thank you very much, its very useful for all my projects. Thank you again!
Comment: I'm having this issue on a view for a content type with a File field and an Image field, I don't see a 'File: Content using My Field' option. When I use the File filter the only option I get is File: Usage
Comment: Should probably mention that you need to add the File:Usage relationship first for the other options to show up and you need to 'require this relationship'. That was the only way I could avoid duplicates.
Answer: You can use aggregation settings to yes.

Go and edit your view
In FIELDS or FILTER CRITERIA section, select and apply Aggregation settings for which fields you want to group by or distinct.


Does 31 necessarily imply the end of the month in a cron job?

Question: For cron job we know we can set time as below.
# +------------ Minute (0 - 59)
# | +---------- Hour (0 - 23)
# | | +-------- Day of the Month (1 - 31)
# | | | +------ Month (1 - 12)
# | | | | +---- Day of the Week (0 - 7) (Sunday is 0 or 7)
# | | | | |
# * * * * * command

What I want to know is that when we set day of the month 31, does this means the end of each month though the month does not  have day 31.
Answer: No, 31 means 31.
However, you can do some trickery. Set the job to run on any day which could potentially be the last day of the month (ie 28-31 in the day-of-month field), and then replace your command with a shell expression comprising a test on the date guarding the command:
0 0 28-31 * * [ "`date +%m`" != "`date --date=tomorrow +%m`" ] && command

The expression inside the test brackets just asks if the month number today is different to the month number tomorrow, which of course will only be true on the last day of the month. Note that the form of this expression depends on your local date - you may need to tweak it if you don't have the current GNU version.
I should say that I didn't invent this - I found it with a quick Google in a mailing list post by a Matthew Jarvis. I would imagine this is very much a standard old Unix wizard's trick, though.
Comment: On stackexchange sites, asking a question which can be answered with a Google search, is NOT a bad thing. In fact it is a good thing, as the next person who will search this in Google will find the answer on stackexchange and come here.
Comment: It can't be too old of a trick given the GNU-specific options to "date" =)
Answer: No, I think the best you can do is run at midnight on the 1st of the month, or set up individual crontab lines for each month (or at least, a line for months with 28,29,30 and 31 days)
0 0 28,29 2               * /my/command
0 0 30    4,6,9,11        * /my/command
0 0 31    1,3,5,7,8,10,12 * /my/command

Comment: I have no experience with cron, but wouldn't "0 0 28,29 2" execute twice in a leap year? Not that this would be a problem for the next two years, but still...
Comment: Thanks Paul! I will follow the second one. For second method do i need to set the same file for three times right? Thanks again :)
Comment: Yes, you will need to repeat it.
Comment: That's a good point, no easy way around that
Answer: I don't think you can do this easily in the crontab.
One option would be to set cron to run the script every day and then make the script itself check if it is the last day of the month.
Answer: I guess some implementations of cron have a special character 'L' meant for this purpose:
*    *    L    *    *    your_script.sh

would execute your script on the last day of every month
On the other hand,
*    *    0    *    *    your_script.sh

You can even specify something like:
*    *    *    *    1,5L    your_scrript.sh

to run the script on the last Monday and Friday of each month
or
*    *    *    *    1    your_script.sh

to run the script every Monday at midnight.
Answer: This will do the job:
if [ $( date +%-d --date="tomorrow" ) -eq 1 ]
then echo Last day of the current month
else echo Not yet!
     exit 0
fi

exit 1


What is the probability of exactly two accidents on at least one day of a week, in case of 7 indistinguishable accidents per week

Question: If 7 accidents (all are indistinguishable i.e we care only about whether accident happen or not, not the details of it) happen in a week.  What is the probability of exactly two accidents on at least one day of a week.
My solution is given below
$$
\frac{1}{13 \choose 6} \Bigg[{7 \choose 1}{10 \choose 5} - {7 \choose 2} {7 \choose 4} + {7\choose 3} 4 \Bigg] = 0.681
$$
I used the equation that number of ways $r$ balls can be arranged in $n $ cells in ${n+r-1 \choose n-1}$ distinguishable ways.
Is it correct ?
Comment: I cant follow your reasoning. Can you explain why this formula should be correct?
Comment: @Nurator included the information.
Comment: In order to have an unambiguous way of answering, we need to know how the accidents themselves are distributed.  In a similar "balls-in-bins" problem, we might say "take a ball, throw it at the bins so that it randomly lands in one of the bins uniformly at random.  Then take another ball and throw it in as well, so that where that ball lands is uniformly distributed and independent to the previous."  As alluded to below, it is very uncommon for the $\binom{13}{6}$ outcomes to be equally likely in practice, making this an uncommon assumption.
Comment: @JMoravitz, yes in practice uniform at random assumption might not hold. But in my case, I assume it. Thanks
Comment: I think the word "probability" should have some unusual meaning, so that your solution was correct.
Answer: The number of all possible distributions of accidents is (stars and bars method) $${13\choose 6}$$
The number of all possible distributions of accidents if 2 happend on monday is $${10\choose 5}$$
The number of all possible distributions of accidents if 2 happend on monday and 2 on thuesday is $${7\choose 4}$$
The number of all possible distributions of accidents if 2 happend on monday and 2 on tuesday and 2 on wednesday   is $${4\choose 1}$$ So the naswer is, by PIE: $$P={{7\choose 1}{10\choose 5}
  -{7\choose 2} {7\choose 4}+{7\choose 3}{4\choose 1}\over {12\choose 6}}$$
So, your answer maches with my answer.
Comment: why it is downvoted ?
Comment: That makes the wild assumption that each of the possible outcomes where you treat days as distinct and accidents as indistinct are equally likely to have occurred.  Do you really think it is equally likely that all seven accidents occur on monday as it is that one accident happens each of the days?
Comment: Despite the fact that we *say* the accidents are indistinguishable, under most sensible interpretations of this problem and problems like it, it makes the most sense to treat this behind the scenes as each of the accidents (*or balls for a balls-in-bins problem*) as being distinct so that we can work within an equiprobable sample space.  The probability of occurrence isnt simply "*total number of good outcomes divided by total number of outcomes.*"  That *only* works if the outcomes are equally likely to have occurred, which the problem statement does *not* imply that the outcomes you use are.
Comment: @JMoravitz Will you provide a correct solution?
Comment: @Aqua linked a duplicate above.  Note the usage of $7^7$ as the sample space size, rather than $\binom{13}{6}$
Comment: @JMoravitz. $7^7$ indicates that accidents are distinguishable right ?
Comment: @Shew if you want to think of it that way, yes, but you can always after the fact choose to partition the resulting sample space so that you "forget" that they were indistinguishable.  This is just like how if you want to talk about the problem where we toss several coins and ask how many total tails we got (*by treating the coins as indistinguishable*) we might choose to first treat the coins as distinct, looking at the $2^n$ equally likely outcomes, find probabilities with that, and use those probabilities when describing the probabilities had the sample space been of size $n+1$
Comment: The probability of zero tails out of $n$ flips of identical fair coins is not equal to $\frac{1}{n+1}$... it is $\frac{1}{2^n}$.  Yes... the coins are indistinguishable, but no that doesn't mean that we avoid the sample space where they are distinguishable.  The sample space where they are distinguishable is far too useful.  All that the tails being indistinguishable means is that we can't tell HHHTTT apart from HTHTHT in the end and so our events must group them together.
Comment: @JMoravitz I got your point.  So the correct answer is to use $7^7$ instead of ${13 \choose 6}$ Thanks.


Generating samples for $p(\theta_{i}|\pmb{x})$ if samples from $p(\phi|\pmb{x})$ are known

Question: Suppose $X_{i}|\theta_{i} \sim D_{1}(\theta_{i})$ and $\theta_{i}|\phi \sim D_{2}(\phi)$. Moreover $\phi \sim D_{3}(c)$ where c is known. How would I generate samples for $p(\theta_{i}|\pmb{x})$ if I know samples from $p(\phi|\pmb{x})$?
Comment: That "$/$"  may be ambiguous. Could you define what you intend by $\theta_i/\pmb{x}$?
Comment: Sorry that should have been a conditional sign. Changed it.
Comment: I took the liberty of making the same change in the title
Comment: @Xi'an All $D_{1}, D_{2}, D_{3}$ are known . But except for $D_{3}$ you see everyone else's parameter is not fixed but follows a probability distribution. We know $p(\phi|\pmb{x}) \propto f(\phi, \pmb{x})$, where $f$ is some function of known $\pmb{x}$ and random variable $\phi$. So I plan on using Metropolis Hastings to pick $p(\phi|\pmb{x})$. Once I pick up $\phi$'s , I see you can sample $\theta|x_{i}, \phi$ because you can get a distribution for  $\theta_{i}|x_{i}, \phi$ . But I don't understand why would the simulation automatically marginalize to $\theta_{i}|x_{i}$?
Comment: @Xi'an Thanks a lot for your prompt response. But I still don't completely see how first generating from $p(\phi|x)$ and then from $p(\theta_{i}| x_{i}, \phi)$ is equivalent to generating from the marginal posterior of $\theta_{i}$'s (the integral). Can you please dumb it down for me and provide it as an answer instead of a comment so I can upvote and accept it ?
Comment: @Xi'an Okay I can see how first generating from $p(\phi|\pmb{x})$ and then from $p(\theta_{i}|x_{i}, \phi)$ is equivalent to $p(\phi|\pmb{x})\times p(\theta_{i}|x_{i}, \phi)$. But I dont understand why it would be equal to the integral over $\phi)$
Comment: This is the definition of marginals:$$P(\theta_i\in A)=P(\theta_i\in A, \theta_{-i}\in\Omega)$$
Answer: If one considers a hierarchical model like
\begin{align*}
\phi &\sim p_3(\phi)\\
\theta_i\mid\phi &\sim p_2(\theta_i|\phi)\qquad i=1,\ldots,I\\
x_i|\theta_i,\phi &\sim p_1(x_i|\theta_i)\qquad i=1,\ldots,I
\end{align*}
the joint distribution of the parameters $(\phi,\vartheta)$ is
$$p_3(\phi)\prod_{i=1}^Ip_2(\theta_i|\phi)p_1(x_i|\theta_i)$$up to a constant. Generating realisations from that joint distribution, one produces vectors $(\phi_t,\vartheta_t)$ such that components are marginally distributed from the marginals$$\theta_i|\mathbf{x} \sim \int p_3(\phi)\prod_{i=1}^Ip_2(\theta_i|\phi)p_1(x_i|\theta_i)\text{d}\phi\text{d}\vartheta_{-i}$$Hence, when samples of $\phi$'s from the marginal $p(\phi|\mathbf{x})$ are available, completing the samples into samples of $(\phi,\vartheta)$'s can be done by simulating the $\vartheta$'s from the conditional $p(\vartheta|\mathbf{x},\phi)$.
Comment: This is a choice of notation to write $\vartheta=(\theta_1,\ldots,\theta_I)$.
Comment: Shouldn't the curly theta just be equal to theta, $\vartheta=\theta$ ?