Como realizar um Where utilizando Entity Framework

Question: Tenho uma aplicação web que preciso apresentar uma lista contendo alguns dados, para isso, criei o  Model: Crm_Analise:
public class Crm_Analise
{
    [Key]
    public int id { get; set; }
    public string cod_item_CRM { get; set; }
    public string TAG { get; set; }
    public string data_creat { get; set; }
    public string modelo { get; set; }

    public int cliente_CRM { get; set; }
}

E por Scaffolding criei o Controller e as Views.
Porém, preciso que, seja exibido somente os dados ref. ao cliente logado.
Então estou utilizando Session para armazenar o código do cliente.
Ai no Controller fiz o seguinte:
    public async Task<ActionResult> Index()
    {
        if(Session["cod_cli"] != null)
        {
            db.Crm_Analise.Where(x => x.cliente_CRM == Convert.ToInt32(Session["cod_cli"]));

            return View(await db.Crm_Analise.ToListAsync());
        }
        else
        {
            return Error();
        }
    }

Porém, não mudou em nada, continua me trazendo a lista inteira.
Comment: O where está correto. Tentou ver no banco se todos os registros estão para o mesmo usuário?
Comment: @FilipeOliveira sim, já verifiquei e tenho vários registros, para vários usuários diferentes..
Answer: Falta atribuir a query filtrada no ToListAsync().
Perceba que o Where não altera a coleção original, independentemente se for uma lista, um IQueryable ou qualquer outra coisa, ele retorna uma nova coleção com elementos que atendam ao predicado.
Ao retornar a view usando db.Crm_Analise.ToListAsync() você simplesmente está materializando todos os itens do DbSet e enviando para a view.
public async Task<ActionResult> Index()
{
    if(Session["cod_cli"] != null)
    {
        var query = db.Crm_Analise.
                       Where(x => x.cliente_CRM == Convert.ToInt32(Session["cod_cli"]));

        return View(await query.ToListAsync());
    }
    else
    {
        return Error();
    }
}

Comment: Só tem um erro no lugar de `retorno` é `query`!
Comment: Ótima resposta, explicou perfeitamente.
Comment: Valeu, @JulioBorges. Pela edição também =)
Answer: O problema é que vc está executando o Where, mais executa o ToListAsync em todo o DbSet, altere o seu código para:
public async Task<ActionResult> Index()
{
    if(Session["cod_cli"] != null)
    {
        return View(await db.Crm_Analise.Where(x => x.cliente_CRM == Convert.ToInt32(Session["cod_cli"])).ToListAsync());
    }
    else
    {
        return Error();
    }
}


Length Group By não funciona

Question: Estou utilizando essa funçao para agrupar uns dados que vem da API:
function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    var key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
}

var groupedYear = groupBy(this._data, 'year');

Trás os dados corretamente, neste caso ele trás o ano 2020 e 2021;

Quando eu dou um console.log(groupedYear.length); ele retorna undefined.
Eu preciso que ele me retorne os dois itens, que é o 2020, e 2021.
Answer: Nesse caso a variável groupedYear não é uma array, mas sim um objeto.
Apenas arrays possuem a propriedade length.
Você quer saber quantas chaves esse objeto possui, certo? Então você pode usar a função Object.keys, que retorna um array com todas as chaves do objeto.
const length = Object.keys(groupedYear).length;

Comment: Deu certinho, estou apenas esperando o tempo para aceitar a resposta. Obrigado.
Comment: E como faço pra pegar o length dentro do 2020 por exemplo? pra dar os 13 ?
Comment: @Mariana nesse caso só usar `groupedYear['2020'].length`.

Length Group By não funciona


How is this relation transitive?

Question: $$R = \{(0,1), (0,2)\}$$
I drew out a directed graph; however, I still do not see how this relation is transitive. If $0$ was reflexive, then it is transitive; however, that is clearly not the case here.
Answer: This relation is vacuously transitive as there is no case where $(a,b)\in R$ and $(b,c)\in R$ so the hypothesis for transitivity is never satisfied.
Comment: Would something like this be vacuously true for transitivity? R = {(0,3), (2,3)}?
Comment: Yes. Read carefully the definition.

How is this relation transitive?


Check if time is between two values with hours and minutes in javascript

Question: I need to check if a time is between a start and end time.  All times are on the same day, so date is not important.  I'm able to compare hours, but I'm unsure how to add in minutes to the start and end times.
var thedate = new Date();
var dayofweek = thedate.getUTCDay();
var hourofday = thedate.getUTCHours();
var minutesofday = date.getMinutes();
function inTime() { if (dayofweek != 0 && dayofweek != 7 && (hourofday > 13 && hourofday < 20)) { return true; } return false; }

If I want to check whether the time is between 13:05 and 19:57, how would I add the minutes to my inTime function?  If I add them to the if statement, it fails to work:
 function inTime() { if (dayofweek != 0 && dayofweek != 7 && ((hourofday > 13 && minutesofday > 5) && (hourofday < 20 && minutesofday < 57))) { return true; } return false; }

Comment: Really? The downvoter should rethink why he is on this site. #SOreadyToHelp !
Comment: I really hate answers that say "It's an X/Y problem."  No, it's a stated problem showing that I attempted to solve it before asking for help.  How are people supposed to show what they've done if they don't want comments like this?  And I checked for duplicates, but none included the issue with minutes in javascript.  I found solutions in PHP, but that doesn't necessary work in javascript.
Comment: @kevin everything is somehow slightly related to one of more than the millions of questions that exists on the internet. However its (sometimes) hard to find them, and the askers might not have the same knowledge or skill like you, so they might not be able to adapt the answers to their usecase. If there would be a real dupe, wheres your dupe vote?!
Comment: @kevin but you would need to set the `start` and `end` date to todays date ... which is slightly longer then the answers proposed below.
Comment: I recommend you checkout momentjs library https://momentjs.com/. It has method to check time. Please refer to this https://stackoverflow.com/questions/23620498/comparing-two-times-with-moment-js
Comment: It's not quite clear what you're asking, are you trying to figure out whether the time "now" is between two times of day?
Comment: it's an X/Y problem, and if you instead solve for X, surely it's a duplicate of one of the dozen "Check if date is between two dates" questions.
Comment: @Alligator "minutes" is the x/y problem. When dealing with date objects, they have minutes. If you compare two dates, you're comparing minutes too. so all you needed to do was create date objects for start date, end date, and the date you are comparing, then check of the latter is between the two former which is just a simple number comparison. Instead you were trying to individually compare time/date parts. x/y.
Answer: If its 14:04 your condition will fail as 4 is smaller 5. The simplest would probably be to just take the full minutes of the day:
 const start = 13 * 60 + 5;
 const end =  19 * 60 + 57;
 const date = new Date();
 const now = date.getHours() * 60 + date.getMinutes();

 if(start <= now && now <= end)
   alert("in time");

Comment: Apparently two people decided to downvote *every* answer (a third downvoted one of them). **sigh**
Comment: Yes, this is exactly what I was concerned about.  Excellent answer.
Comment: @alligator glad to help :)
Comment: Suggest using, or not using, the UTC methods consistently, rather than mix-and-match. :-)
Comment: what if the end is smaller than the start? like from 22 to 03 in the morning?
Answer: If you're saying you want to check if the time "now" is between two times, you can express those times as minutes-since-midnight (hours * 60 + minutes), and the check is quite straightforward.
For instance, is it between 8:30 a.m. (inclusive) and 5:00 p.m. (exclusive):

var start =  8 * 60 + 30;
var end   = 17 * 60 + 0;

function inTime() {
  var now = new Date();
  var time = now.getHours() * 60 + now.getMinutes();
  return time >= start && time < end;
}

console.log(inTime());

The above uses local time; if you want to check UTC instead, just use the equivalent UTC methods.
Comment: If the end date is in the following day, you just need to add 1440 mins to that time.
if (end < start) end += 1440;
Answer: Convert times to milliseconds and then you can compare easily.
short version:
if(timeToCheck.getTime() >= startTime.getTime() &&
        timeToCheck.getTime() <= endTime.getTime()) {
    // ...
}

OR:
let startTimeMilli = startTime.getTime();
let endTimeMilli = endTime.getTime();
let timeToCheckMilli = timeToCheck.getTime();

// change >= to > or <= to < as you need
if (timeToCheckMilli >= startTimeMilli && timeToCheckMilli <= endTimeMilli) {
    // do your things
}

Comment: I upvoted not because your answer is right or well written, but because its definetly not worth three downvotes.
Comment: I thought about that, but does that work once, or can I use that to check every single day?  For example, if I count up from 1970, I can only compare values within one day - or am I missing something?
Comment: check answer again
Comment: why are people voting down?
Comment: Alligator, I did not understand what you are asking. using milliseconds, you don't need to worry about date part. It will work even if start and end times fall on different dates.
Comment: I had downvoted because u had no code at that time. Ofc changed now.


the wall/fence on the right of PNC Park in Pittsburgh

Question: Here is PNC Park in Pittsburgh

I guess the wall/fence pointed out by red arrow is 21 feet
high.
What about the wall pointed out by blue arrow? I'm not even sure whether there is a wall there pointed out by yellow arrow?
Comment: I'm not quite sure what you're asking here - are you asking for the height of the wall pointed to by the blue arrow, and the height/presence of a wall pointed to by the yellow arrow? (It would probably also help if you could explain why this is important)
Answer: There is not a significant wall there, as is generally the case in (purpose-built) MLB parks.  Instead, you have seating; there is railing to demarcate where fans can be as opposed to the playing field, but not a wall.  It is traditional in baseball parks to allow fans to sit at field level and see the game; injuries to fans from batted balls (or thrown bats) has led to some netting being in place at most parks, usually at least extending to the dugouts now, but nothing further to interfere from seeing the field.
From this image   (see link to MLBCathedrals twitter for full res), you can see the railing from behind.  The blueish colored railing is still railing - just wtih some padding on it; and from other pictures including that on Wikipedia you can clearly see people with their arms resting on it, so it's around 4 feet high there.
The dugout area (yellow arrow) will typically be around the same height (around a person's height), so that it's not disturbing the view of the seats in row 5 or 6 (whatever row it goes back to).


Uploading an image from flutter to server using node.js

Question: I've made a flutter application which will open the camera and capture an image . What I want to do is to send that image to the backend using the http post services. I've created an api using node js and the problem im facing is that I dont know how to send the image to the backend ....please help
heres my code , can you please check whats wrong because the node.js part works fine when tested with postman. Im assuming its something to do with the front end.
Flutter front end code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';

class LandingScreen extends StatefulWidget {
  @override
  _LandingScreenState createState() => _LandingScreenState();
}

class _LandingScreenState extends State<LandingScreen> {
  PickedFile imageFile;
  Dio dio = new Dio();

  _openCamera(BuildContext context) async {
  //holds the image taken by the camera
var picture = await ImagePicker().getImage(source: ImageSource.camera);
if (picture != null) {
  this.setState(() {
    imageFile = picture;
  });
}
try {
  //Extracting the file name from the file
  String filename = imageFile.path.split('/').last;
  FormData formData = new FormData.fromMap({
    "image": await MultipartFile.fromFile(imageFile.path,
        filename: filename, contentType: new MediaType('image', 'png')),
    "type": "image/png"
  });
  //sending to the server
  Response response = await dio.post("http://localhost:3000/tea/",
      data: formData,
      options: Options(headers: {
        "accept": "*/*",
        "Authorization": "Bearer accesstoken",
        "Content-Type": "multipart/form-data"
      }));
} catch (e) {
  print(e);
}
}

 Widget _decideImageView() {
if (imageFile == null) {
  return Text("No selected Image");
} else {
  return Image.file(File(imageFile.path), width: 500, height: 400);
}
}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
    body: Container(
    color: Colors.indigo[900],
    child: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          _decideImageView(),
          SizedBox(
            height: 300,
            width: 420,
            child: RaisedButton.icon(
              onPressed: () {
                _openCamera(context);
                // _showChoiceDialog(context);
              },
              label: Text(
                'OPEN CAMERA',
                style: TextStyle(color: Colors.white, fontSize: 20),
              ),
              icon: Icon(
                Icons.camera_alt_outlined,
                color: Colors.white,
                size: 200,
              ),
              color: Colors.deepOrange,
            ),
          ),
        ],
      ),
    ),
  ),
);
}
}

server.js file
//import mongoose
const mongoose = require('mongoose');

   //establish connection to database
   const MongoClient = require('mongodb').MongoClient;
   const uri = "mongodb+srv://xxxxxxx:<password>@cluster0.s42z9.mongodb.net/myFirstDatabase?
   retryWrites=true&w=majority";
   const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
   client.connect(err => {
   const collection = client.db("test").collection("devices");
   // perform actions on the collection object
   client.close();
   });

     const express = require("express");
     const routes = require('./routes/image'); // import the routes

     const app = express();

     app.use(express.json()); // parses incoming requests with JSON payloads

     app.use('/', routes); //to use the routes

     app.use('/uploads', express.static('./uploads'));

     const listener = app.listen(process.env.PORT || 3000, () => {
     console.log('App is listening on port ' + listener.address().port)
      })

image.js(models)
const mongoose = require("mongoose"); //import mongoose

  // tea schema
  const TeaSchema = new mongoose.Schema({
    name: {type:String, required:true},
    image: String
    //description: String,
    //keywords: String,
    //origin: String,
    //brew_time: Number,
   //temperature: Number,
   //comments: [{ text: String, date: {type:String, default: new Date()} }]
    });

   const Tea = mongoose.model('Tea', TeaSchema); //convert to model named Tea
   module.exports = Tea; //export for controller use

image.js(routes)
const express = require('express'); //import express

// 1.
const router  = express.Router();
// 2.
const teaController = require('../controllers/image');
// 3.
//router.post('/image', imageController.newImage);
//router.post('/image2',imageController.newImage2);
router.post('/tea', teaController.uploadImg /*insert this guy*/ , teaController.newTea);
router.get('/tea', teaController.getAllTea);
router.delete('/tea', teaController.deleteAllTea);

router.get('/tea/:name', teaController.getOneTea);
router.post('/tea/:name', teaController.newComment);
router.delete('/tea/:name', teaController.deleteOneTea);

// 4.
module.exports = router; // export to use in server.js

image.js(controllers)
const multer = require('multer');

const storage = multer.diskStorage({
destination: function (req, file, cb) {
    cb(null, './uploads');
  },
filename: function (req, file, cb) {
    cb(null, file.originalname);
}
});
  const uploadImg = multer({storage: storage}).single('image');

 //import tea model
 const Tea = require('../models/image');
 // newTea function for post image route
 const newImage = (req, res, next) => {
  res.json({message: "POST new image"}); // dummy function for now
   };
   const newImage2 = (req, res, next) => {
      res.json({message: "POST new image2"}); // dummy function for now
    };

   //GET '/tea'
   const getAllTea = (req, res, next) => {
     //check if the tea name already exists in db
     //Tea.findOne({name:req.body.name},(data)=>{

    //if tea not in db, add it
    //if(data===null){
        //create a new tea object using the Tea model and req.body
        const newTea = new Tea({
            name:req.body.name,
            image: req.body.image, // placeholder for now
            description: req.body.description,
            keywords: req.body.keywords,
            origin: req.body.origin,
            brew_time: req.body.brew_time,
            temperature: req.body.temperature,
        })

        // save this object to database
        //newTea.save((err, data)=>{
        //    if(err) return res.json({Error: err});
        //    return res.json(data);
        //})
    //if tea is in db, return a message to inform it exists
    //}else{
        return res.json(newTea);
      //}
    //})
      };

    //POST '/tea'
    const newTea = (req, res, next) => {
     //check if the tea name already exists in db
     Tea.findOne({name:req.body.name},(data)=>{

       //if tea not in db, add it
       if(data===null){
            console.log("new object is creating");
           //create a new tea object using the Tea model and req.body
               const newTea = new Tea({
               name:req.body.name,
               image: req.file.path // placeholder for now
               //description: req.body.description,
               //keywords: req.body.keywords,
              //origin: req.body.origin,
              //brew_time: req.body.brew_time,
              //temperature: req.body.temperature,
           })

           // save this object to database
           newTea.save((err, data)=>{
               if(err) return res.json({Error: err});
               console.log("saved");
               return res.json(data);

             })
         //if tea is in db, return a message to inform it exists
          }else{
            console.log("not saved");
             return res.json(newTea);

             }
            })
             }

         //DELETE '/tea'
         const deleteAllTea = (req, res, next) => {
         res.json({message: "DELETE all tea"});
         };

          //GET '/tea/:name'
          const getOneTea = (req, res, next) => {
          res.json({message: "GET 1 tea"});
            };

           //POST '/tea/:name'
           const newComment = (req, res, next) => {
           res.json({message: "POST 1 tea comment"});
           };

          //DELETE '/tea/:name'
          const deleteOneTea = (req, res, next) => {
            res.json({message: "DELETE 1 tea"});
           };

             module.exports = {newImage,newImage2,getAllTea,
             newTea,
             deleteAllTea,
              getOneTea,
              newComment,
              deleteOneTea,uploadImg};

Comment: see if this helps... I prefer multer for uploading files....https://medium.com/flutter-community/flutter-file-upload-using-multer-node-js-and-mongodb-5ba4da44453e
Comment: Also check out this simple solution: https://stackoverflow.com/a/72711178/10131684
Answer: I can only provide insights on the Flutter-side of things. The way you've used image_picker to set the file to be uploaded and dio for the actual upload seems to be fine. What you'd want to do here is check the response from the server after the upload. Print response with debugPrint('Response: $response'); and see if there's any error thrown.


Manual ray cast when a plane is not in the hit results during a ARCore session

Question: I am creating points on a detected plane, but sometimes the plane is not tracked anymore (fast movement for example) and a hitTest may not return a hit on this plane.
ARKit will return hit result for every known plane could ARCore do the same?
Apparently, this notion exists in Unreal integration (EGoogleARCoreLineTraceChannel::InfinitePlane), could it be available in the Java API?
Also to work around this problem, I do a manual ray cast and for some reason, I have a really small offset between my computed position and the hitTest result.
A Screen to World coordinates would help to make sure no bias is introduced there. Is that something possible?
Thanks in advance for the help!
Julien.
Answer: As a current alternative I used the code from Jonas Jongejan and Dan Moore AR Drawing to get the right Ray origin and it is working much better.
The secret was to generate 2 points near and front screen point and start the ray at touchRay.direction.scale(AppSettings.getStrokeDrawDistance());. I now have a very accurate match between my manual ray cast and the result of the hitTest.


Cophenetic distance matrix to a dendrogram

Question: In hierarchical clustering procedure, a distance matrix is used to construct a dendrogram with an appropriate method of clustering. In the process of constructing a dendrogram, a cophenetic matrix is computed. I understand that such a cophenetic matrix is used to assess clustering consistency.
How can I use a cophenetic matrix as such to plot the dendrogram?
Comment: A cophenetic matrix would be a distance matrix wherein original pairwise distances between the objects are replaced by the computed distances between their clusters at the time of these clusters' merge. Now, most hierarchical clustering programs do not construct such a matrix (no need for) and they plot dendrogram out of another source (such as agglomeration history protocol).
Comment: P.S. You surely can use that matrix to build the dendrogram, but it is cumbersome to do because a step number is not written there!
Comment: Step number - step of agglomeration in hierarchical clustering. Ordinal number of bars (not branches) on dendrogram.
Comment: @ttnphns what do you mean by step number? Is it height or the merge groups?
Comment: I have a cophenetic matrix derived from an iterative ordering method of clustering. I would like to use that for plotting a dendrogram.
Answer: You can just recreate the plot using hclust on the cophenetic of the object, and it would get you what you want (the method used in hclust doesn't matter).
set.seed(2015-04-26)
dat <- (matrix(rnorm(100), 4, 24))
dat_dist <- dist(dat)
hc1 <- hclust(dat_dist)

dat_dist

hc2 <- hclust(cophenetic(hc1), method = "complete")
hc3 <- hclust(cophenetic(hc1), method = "single")
hc4 <- hclust(cophenetic(hc1), method = "ave")

par(mfrow = c(1,4))
plot(hc1)
plot(hc2)
plot(hc3)
plot(hc4)


Beginner to prediction/statistics: Where do I start?

Question: I sincerely apologize if there is another thread already that will answer this question. I'm so incredibly out of my league here that I don't even know what keywords to search for :-).
I'm a computer programmer by trade, and while I have a basic background in math, statistics was never really my cup of tea.
I currently work at a school and just finished developing a basic set of tools to help automatically collect and analyze data on our student's behaviors (this is a school for children with autism and other disabilities). So, we have a couple of year's worth of data for things like: given Billy, how frequently did he have Aggressions, Self-Injurious Behaviors, Drop, etc. Probably 6 - 10 "inputs" (I think that's the correct term) per student. We'll be adding more as well in the future.
What I'm curious about is this: Are there any beginning tutorials out there that might show me some interesting things to do with this data (besides just graphing it?) For example, it would be interesting to be able to predict when Billy is likely to have a long string of aggressions given that these x other factors have been increasing lately. Or, there is an increasing trend of this behavior which is way out of whack with its previous values, that should raise a big red flag.
I've been doing some basic Googling and this seems to be in the realm of "Statistical Data Mining"—some brief tutorials were found on Andrew Moore's site, but these just aren't detailed enough for me to really learn anything.
I realize that this is akin to someone walking into Stack Overflow and saying "Hey, tell me how to write the next Facebook." So, if these are the sorts of things that I can only do with years and years of statistical experience, just let me know and I'll be on my way. However, I also know that while someone couldn't walk into SO and write the next Facebook in a few weeks, we could probably point them in the right direction to create a basic site for their dad's business, even if it would be a pretty basic site. Likewise, I'm not looking to create a genius AI capable of predicting student behavior down to the millisecond; rather, I'm just curious if there's any low-hanging fruit that a guy like me could pick up in a few weeks or months of diligent reading that might make for some interesting uses of this new data we've unlocked.
I'm open to online tutorials, books, textbooks, videos, open source programs and libraries, etc.
Comment: You may want to take a look at a somewhat similar question: http://stats.stackexchange.com/questions/242/using-time-series-analysis-to-analyze-predict-violent-behavior
Comment: You seem to want to do forecasting using time-series or longitudinal data; presumably modelling, not data mining.
You have data for each student at multiple time points. Are these data collected at regular time intervals? What are your predictors like (the "inputs")? Are the outcome variables aggressions,  self-injurious behaviours counts? Do they account for a given time period? Is drop binary (yes/no)?
Comment: Well, I believe that doing forecasting is probably the more advanced of the two things I'd like to do. I'd be happy to start with just some basica anomaly detection outside of just doing standard deviation. To answer your questions, the data is collected at various time intervals although it is usually aggregated into uniform intervals (e.g. hourly, daily, etc.) Right now the predictors are the behaviors being tracked (aggression, self-injurious behaviors, etc.), although we will be adding more in the future along the lines of sleep, meals eaten, special incidents, medical information...
Comment: I guess in theory I was wondering if the inputs and the outputs can be similar (e.g. can more aggressions predict more self injurious behaviors)? Drop is actually duration, but could be simplified down to frequency as well for these purposes. Again, I'm not at this point as concerned with our specific situation, I Just wanted to give a basic example to make sure I'm on the right track. I'd rather learn how to do this in general with some basic examples then hopefully become more proficient and apply it to our exact circumstances.
Comment: One of my colleagues at StatSoft put this series of videos together. http://www.statsoft.com/textbook/data-mining-techniques/ The textbook links are also helpful. Good luck!!
Comment: I understand that you want to model longitudinal data. A starting point can be this tutorial http://www.ats.ucla.edu/stat/r/examples/alda/ch2.htm, it uses the open source R statistical package.
Answer: "anomaly detection" -- This is usually called detection of outliers. You can find many references via googling.
"can more aggressions predict more self injurious behaviors" -- You can try one of the basic things: correlation between different variables or features (you called them "inputs").
The data will be easier to analyze if they will be in the format, say, "number of xxx incidents per week", i.e., if your variables will be measured on the same timescale.
Answer: It sounds like you have some really wonderful data to work with! One person suggested trying analyses in R, and that's definitely a powerful option. With your background in programming, it may be well-suited for you. I personally prefer a program like SPSS, which is built specifically user-friendly(ish) analysis of social science data. If you're new to the program, I'd suggest Julie Pallant's "SPSS Survival Manual," which has basic how-to instructions for most common analyses.
Regardless of the software, it sounds like using correlations, regressions, and some time-series work could help you investigate your variables. If it seems overwhelming to learn all the stats in a short period of time, I might suggest advertising the fact that you have data to work with. I'm certain that psychology undergrads or grad students at a nearby university would jump at the chance to help you do analysis and possibly publish any useful results. Best of luck!
Comment: Thanks for the great answer. Definitely gives me some specific terms to start Googling to hopefully start making heads and tails of all of this.


Does a Required Restart for Windows Update log an event? If so what is the source/id?

Question: Does anyone happen to know if a required restart in order to apply Windows Updates creates a entry in the event log? If so which log is it under, and what is the source/id?
I have a legacy system that needs to an account, constantly logged into console for applications to function as required (Some old PROCOMS modem software for customers without Internet access but a telephone (Dial-up? Separate issue, don't get me started -.-)).
When an update is applied to this machine that requires a restart (Server 2003) I would like an e-mail alert to be sent.
Comment: How are your WSUS updates being applied? Automatically installed then prompt for a reboot, or automatically downloaded then prompt for install?

You never want to leave a production server in a state where the patches have been installed and it's requesting a reboot. This leaves the server in an 'intermediate' state where it's neither at one patch level or another. Ideally you always want to trigger the patch installation (manually) then reboot the server immediately upon completion.
Comment: Hi Chris, any chance you could change your comment to an answer? I would really like to award you the answer for this question as I agree with your statement.
Comment: Done, thanks Beuy. What approach did you end up taking?
Comment: Thanks Chris, I've marked your question as an answer.
I changed the automated installation to notify but not install, I'll manually check the device at the end of every week to check if it requires an update and install manually.
Comment: WSUS updates are being applied by GPO, the problem with this machine is it will get touched once in a blue moon, and the applications running on it prevent restarts from occurring unless you manually force them using a shutdown -f command or hard-boot them.
Answer: This is the event you are looking for, down the keyword it triggers. I believe it is safe to assume it will be identical on all Windows systems at least as old as Windows 7 or newer.

PS:I hope this answer doesn't get downvoted because the screenshot is from a Windows 7 machine, as opposed to a server product.
Answer: How are your WSUS updates being applied? Automatically installed then prompt for a reboot, or automatically downloaded then prompt for install? You never want to leave a production server in a state where the patches have been installed and it's requesting a reboot. This leaves the server in an 'intermediate' state where it's neither at one patch level or another. Ideally you always want to trigger the patch installation (manually) then reboot the server immediately upon completion.
Answer: Whenever a server reboots there should be an Event ID 6009 from source eventlog stating the product name, version, build number, service pack number, and operating system type.
Comment: Thanks joe but I'm actually after the system notifying that it requires a restart, not that it already has.


PHP-PDO ODBC driver can't connect to MS Access MDB

Question: I am having a really weird issue here.
Here is the context:
I have an old MS Access 97 .mdb file that I would like to use on a internal web page build in HTML, PHP, JQuery running on IIS.
Now I know that odbc drivers for php are already implemented but since I was already using PDO in some other pages linked to this I decided that I would also use PDO for this project.
So, after enabling the extension and all for PDO odbc drivers to work correctly, I copied the .mdb file and named it DBcopy.mdb into the project folder.
I wrote the code and perform some tests (to make sure everything worked as expected) and everything seems fine.
Than I change the path of the .mdb to //myothernetworkdrive/somedirectory/DBreal.mdb which is where the "real" .mdb file is and suddenly I get this message :
SQLSTATE[HY000] SQLDriverConnect: -1032 [Microsoft][Pilote ODBC Microsoft Access] Le moteur de la base de données Microsoft Jet ne peut pas ouvrir le fichier '(Inconnu)'. Il est déjà ouvert en mode exclusif par un autre utilisateur, ou vous devez avoir l'autorisation de visualiser ses données.

For those of you who don't speak french here is a rought translation:
SQLSTATE[HY000] SQLDriverConnect: -1032 [Microsoft][ODBC Drivers Microsoft Access] Microsoft Jet can't open file '(Inconnu)'. It is already open in exclusive mode by another user, or you need permission to access these data.

Since the error message is pretty self explained, I checked if someone was locking the .mdb file by looking for a .ldb file in the same directory but couldn't find one so I presume that the .mdb wasn't locked.
Anyone know why I can access the copy but not the original? The only difference I can see is are the directories there into:
Copy- is in the same folder as project.
Real- is on a network drive that IIS have the access
EDIT:
@Halayem Anis,
I don't use Apache, I am using IIS but since your point could be valid anyway I gave everyone permission to change/write/read/totalcontrol on the .mdb file but still the same error code.
EDIT2:
I am using this connection string:
new \PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=\\\\myothernetworkdrive\\somedirectory\\DBreal.mdb; UID=Admin; PWD=;");

Could it be that my connection string is not good?
EDIT3:
I added a DSN in my ODBC Driver manager in IIS with name 'testDSN' pointing to my .mdb file and I gave the IIS user total control on the .mdb file and the folder its in.
I also changed my connection string to:
new \PDO('odbc:testDSN');

But I still get the same error message.
Answer: The error message can drive you in the wrong way, please do these following steps :

To access to UNC Path via Apache you have to set a required credentials in Apache service (see service **=>** Apache **=>** LogOn)
Verify that the user used by Apache has access for read/write to your MDB file
Comment: Not using Apache but IIS still I gave everyone the permission to access the file. Still the same error message


In the Monty Hall problem, does it matter that the host knows which door the car is behind? If so, why?

Question: If I'm thinking about this correctly, regardless of how the host chooses which door to open, there's a 1/3 chance the player initially picks the door with the car behind it, in which case they shouldn't switch doors and the door opened by the host will have been one of goat doors regardless of whether he was choosing at random or not (assuming he was choosing between the two doors not already chosen by the player).  In the case that the player initially picks one of the goat doors, which has a 2/3 chance, if the host is picking a door randomly, there's a 50% he chooses a goat door, whereas there's a 100% chance of that of he knows where the car is and is purposely avoiding that door.  But the way the problem is usually stated, we already know the door opened by the host was a goat door, so it seems that there should be 2/3 probability of the player choosing the car door if they switch to the unopened door, regardless of how the host decided which of the two unopened doors to open.
And yet, I've heard many people say that the key to understanding this problem is to realize that the host is intentionally opening a door with a goat and that, of he were instead choosing an unopened door at random, it really wouldn't matter if the player switches doors or not. Wikipedia seems to back this up:

For example, assume the contestant knows that Monty does not pick the second door randomly among all legal alternatives but instead, when given an opportunity to pick between two losing doors, Monty will open the one on the right. In this situation, the following two questions have different answers:

What is the probability of winning the car by always switching?
What is the probability of winning the car by switching given the player has picked door 1 and the host has opened door 3?

The answer to the first question is 2/3, as is correctly shown by the "simple" solutions. But the answer to the second question is now different: the conditional probability the car is behind door 1 or door 2 given the host has opened door 3 (the door on the right) is 1/2. This is because Monty's preference for rightmost doors means that he opens door 3 if the car is behind door 1 (which it is originally with probability 1/3) or if the car is behind door 2 (also originally with probability 1/3).

This isn't quite the same distinction as whether the host is choosing randomly or not, but the core thing I'm not understanding is why it matters at all how he chooses which unopened door to open, since we already know which one it is.  I'm trying to figure it out by relating it to other conditional probability scenarios where the prior probability is clearly relevant, such as the textbook example of a medical test with a high accuracy rate where the probability that a positive result is correct depends on the prior probability the patient had the disease. I understand Bayes' theorem and medical test examples and the like fine.  But I'm not seeing a clear way to make an analogy to variations of the Monty Hall problem where the host isn't purposely never choosing the door with the car.
Comment: If Monty opens a random door, does this mean he also has a chance to open the door with the car? What happens in that case?
Comment: *"why it matters at all how he chooses which unopened door to open, since we already know which one it is"* what do you mean with 'we already know'? Who is 'we', the contestant that needs to make the choice?
Comment: @SextusEmpiricus, yes the contestant already sees that a goat had been revealed behind the door opened by the host.
Answer: There are 3 golfers, named A, B, and C. One of them is a master, the others are amateurs. The master will always outgolf the amateurs. You want to guess which one is the master.
Scenario 1: you are told that all 3 of them played a round of golf, and B came last. A and C are clearly equally likely to be the master. This is equivalent to the modified Monty Hall problem where Monty opens one of the goat doors at random and happens to pick B.
Scenario 2: you are told that only B and C played a round of golf, and B came last. The probability that C is the master is 2/3. This is equivalent to the original Monty Hall problem where Monty is only allowed to pick a goat door from among B and C and picks B.
Answer: It is easier to picture with 100 doors.
Scenario 1:
You pick 1 random door and Monty opens 98 doors that he knows have goats behind them.
Scenario 2:
You pick 1 random door and Monty picks 1 random door. (Note that this is the same as him randomly picking 98 other doors to open first, since picking the first 98 doors or last 1 door amounts to the same thing.)
In Scenario 1 there is a 99% chance that the car is behind the doors you did not pick. By eliminating 98 goat doors non randomly that still leaves a 99% chance that the door he did not open has the car and a 1% chance your door has the car. There were always going to be at least 98 doors in the unchosen group that had goats. Opening those doors on purpose does not change the original 99% chance that a car was behind your unchosen 99 doors. You should always switch here since there is a 99% chance it is behind the door you did not choose.
In Scenario 2 there is a 2% chance that your door or Montys door have the car. If you open the other 98 doors and there randomly happened to be goats behind them then there is still an equal chance that your door or Montys door have the car. There is no benefit to switching in this scenario since each door now has a 50% chance of having the car.
One way to help further visualize this is to imagine that you always pick door 99, Monty always picks door 100, and the doors are always opened in order. After doors 1 through 98 are opened with goats you have the option to switch with Monty and take door 100. There was always an equal chance it would be behind 99 or 100, and there is now still an equal chance it will be behind 99 or 100.
Monty choosing randomly is absolutely different from Monty knowing and opening all the goat doors first on purpose.
Answer: The point about Monty's door choices is that it provides additional information, but also that the information interacts with the first choice by the contestant and the place of the true position of the price.
We can have alternative situations where one or both of the interactions are not present.
This question relates to the question: Monty Hall problem and causality where we saw the first diagram on the left below, and relating to this question we can add the adaptations that are made in the second and third diagram:

The images above are directed acyclic graphs that express causal relationships. At the start of the graph are three independent variables, u_door_with_the_prize, u_quizmaster and u_first_choice. The arrows indicate which variables depend on one and another. The first variation has the arrow between the 'u_door_with_the_prize' and the 'door opened by the quizmaster' eliminated. The second variation has an additional relationship between the 'second choice' and the 'u_door_with_the_prize'.
In the situation that you mentioned, Monty opens the doors independently from the the true position of the prize. That would be like the middle graph. Then, the strategy, to switch or not switch can not have any effect, because the final decision, however it is made, is causally independent from the actual position of the prize and therefore the strategy can't have a positive effect.
An exception would be when we allow for the strategy, and the second choice, to be in some way dependent on the position of the prize, and in that case we get the third graph. This would be the case when the strategy is not just to switch to the door that was left unopened by Monty, but when the strategy is also allowed to switch to other doors and in particular a door opened by Monty that might have the prize behind it.
This type of conditional strategy is similar to what is happening in the Wikipedia example where based on the two different type of situations (a plain strategy decided before knowing what Monty opens, or a strategy that relates to what Monty actually opens).
Comment: I don't really understand how to interpret your diagrams.  Would you mind clarifying?


Batch para localizar serviço com caractere especial

Question: Estou tentando fazer uma bat para ligar um serviço do Windows que possui caracter especial "Ç", porém não consegui chegar em nenhum código viável. Sempre me retorna o erro 1060.
Essa é mais ou menos a estrutura da minha bat:
SC QUERY "Serviço Bonjour" > NUL
IF ERRORLEVEL 1060 GOTO MISSING_BONJOUR
ECHO Configurando AutoStart do Bonjour...
sc config "serviço do bonjour" start=auto
sc start "serviço do bonjour"
GOTO END

No exemplo acima já tentei diversos outros mecanismos, inclusive o de substring, mas não tive sucesso
Answer: Conforme seu comando você está pegando pelo "NOME_PARA_EXIBIÇÃO", porém se você pegar pelo "NOME_DO_SERVIÇO" não terá problemas.
Exemplo:
NOME_DO_SERVIÇO: DPS
NOME_PARA_EXIBIÇÃO: Serviço de Diretiva de Diagnóstico
Assim resultando o comando abaixo para iniciar o serviço:
sc config "DPS" start=auto
sc start "DPS"

Comment: Obrigado, era isso!
Answer: Uma vez precisei fazer um bat para configura placa de rede, não manjo nada, mas copio bem hehe.
Tive problema com acentuação e descobri que precisa trocar esses caracteres por outro, segue uma lista.
O caminho é esse.

Citação
á=

à=…
ã=Æ
ä="
â=ƒ
Á=µ
À=·
Ã=Ç
Ä=Ž
Â=¶
é='
è=Š
ë=‰
ê=ˆ
É=
È=Ô
Ë=Ó
Ê=Ò
í=¡
ì=
ï=‹
î=Œ
Í=Ö
Ì=Þ
Ï=Ø
Î=×
ó=¢
ò=•
õ=ä
ö="
ô="
Ó=à
Ò=ã
Õ=å
Ö=™
Ô=â
ú=£
ù=—
ü=
û=–
Ú=é
Ù=ë
Ü=š
Û=ê
ç=‡
Ç=€
§=õ
¹=û
²=ý
³=ü
£=œ
¢=½
¬=ª
º=§
ª=¦
º=ø

Citação


Pass current activity to a service so that the service can manipulate the view

Question: What I want to be able to do is toggle the visibility of an element in my activity FROM a service.
How can I pass the current activity to my service class in order to send back messages/call functions in my activity?
What happens if the user exits the app and the service is still running, but obviously without a running activity to call functions within?
Thank you.
Comment: possible duplicate of [android: notify activity from service](http://stackoverflow.com/questions/4111398/android-notify-activity-from-service)
Answer: I don't think it's a good idea. Here's a good answer about notifying an activity from a service: Notify activity from service.
Comment: ok thanks, will ask a new question on broadcast intents now. :p
Answer: To answer your first question,  you wouldn't be doing anything to the UI from your service.  You have a few options for communicating between an activity and a service.  You can set up a BroadcastReceiver.  You can bind the service to your activity and use Android's AIDL to set up handlers for the communication.  Plus others.
To answer your second question - make sure to stop your service in your onDestroy method.  Alternately, if you've bound the service to an activity, the service will stop once the final activity that the service is bound to stops.
Comment: Ok, I think I'm very confused! I've created a service so that users can leave the app and the service will still run in the background. Users can go back to the app and stop the service themselves manually via buttons in the app. The service downloads information from the interwebs. So before and while its initializing I want a button which says "Start Service" and when its finished initalising and is in full swing (downloading the info) I want to send a message back to the activity to hide the button and show one for stopping the service.


Exchange Online: Incorrect recipient address after SMTP transfer

Question: I have a user who originally had a user account named Bob. This account had a primary SMTP address of firstname.lastname@example.com before any changes were made to it. Now, it turns out that Bob can no longer make use of this account, however, he still needs an account.
The new account should seamlessly function as it did before, which meant that the primary SMTP address had to be removed from the old account and provided for the new one. This leaves me with two user accounts for the same user:
Name: Bob Swanson (old)
SMTP: email@example.com
Auto-forward: email@example.com
State: Disabled/Unused
Name: Bob Swanson
SMTP: firstname.lastname@example.com
State: Enabled/Active
This works just fine most of the time, and almost every email received by the user is indeed addressed to email@example.com, as was intended. Although, once every blue moon, the user receives an email addressed to email@example.com in his new inbox.
This is where my question begins: What exactly may be the cause for this incorrect display of information?
We know that the email does get delivered to the new inbox, no matter which of the two addresses you use (email forwarding is in effect). Yet, sometimes an email will display the old SMTP address in the recipient field.
I suspect that this may have to do with the X500 addresses of the old account being left untouched (Does the address book in Outlook make use of these?). Because, I highly doubt that a user would go out of their way in order to manually type email@example.com in the recipient field.
Thank you kindly for reading,
Mihkel
Answer: Why don't you delete the old account in O365?
Do you mean to see the recipient on Bob's side? I suspect this issue may be caused by autocompleted. You could clear the cache and test again. Besides, could you reproduce this issue on OWA?


Assessing if set of sequences increase or decrease

Question: I have a set of sequences of numbers, each sequence is independent from each other.
I'd like to know if, "in general", these sequences increase, decrease or remain the same.
What I have done so far is a fitted a linear model to each sequence, so that I can use the gradient to determine if the sequence is increasing or not.
I am then using a Wilcoxson U test to test if to compare if the positive gradients are as large as the negative ones (in absolute value, of course).
Is this a good solution to my problems? What are the threats of this solution? What would be a better one?
Comment: Is each component of each sequence uncorrelated with each other? If not, this could be misleading, since you have autocorrelation in the responses.
Comment: I don't know if they are correlated or not. As this comes from a time series, it might well be, but that is one of the things I wish to find out too!
Comment: What's wrong with taking the first difference and performing a test of location (like the t-test)?
Comment: @shabbychef You are assuming the ARIMA filter which will convert an autocorreleated series to a white noise series. Unfortunately a first difference filter an inject structure see the Slutzky Effect http://en.wikipedia.org/wiki/Eugen_Slutsky which teaches us that one can create an autocorrelated series by differencing a white noise series. Assuming a filter,any filter can be quite dangerous. ARIMA model identification http://en.wikipedia.org/wiki/Box%E2%80%93Jenkins is the procedure to follow in order to yield an equation and an error process that is Gaussian. See my comments in my answer .
Answer: It appears that each sequence has a set (equally spaced) of possibly auto-correlated historical values. To answer the question is the sequence expected to increase,decrease or remain the same is at the heart of time series modelling with Intervention Detection. For example each sequence may be described in two possible ways : 1) y(t) = y(t-1) + trend plus etc ARMA structure OR 2 ) y(t)= b0 + b1*t where t=1,2,3,..... . plus ARMA structure. Two possible ways of assessing trend ! Now in general in case (1) there could be multiple differencing operators or in case (2) there could be multiple trend break points . Now just to generalize one step further i.e. make less presumptive specifications about the model sample space, either 1) or 2) could possibly include one or more Level or Step Shifts which are not trend changes but intercept changes. Tons of software confuse i.e. fail to distinguish between trend changes and level changes. Not to make this more complex than it already seems to be, one might have changes in parameters or changes in error variance over time. Thus your problem is solved . Now all you have to is to find out how to implement this in some reasonable time frame. Be careful to challenge a presumed a model-based approach that doesn't verify the Gaussian Assumptions or doesn't adhere to strict tests of necessity and sufficiency of a proposed model. Whew ! This tires me out specifying what you have to do to correctly answer your questions.
Comment: Thanks. Do you know about any tutorial I could use to do this, preferably with R?
Comment: @rafalotufo Sorry, I don't know that one exists as what I laid out is state-of-the-art. If I can help with some examples I would certainly do that. You can post 1 of your sequences and I will analyze it ( not with R ) and post the results.


Yahoo OAUTH Login for website

Question: Friends,
I have implemented yahoo login for website using OAUTH
I am using https://api.login.yahoo.com/oauth/v2/request_auth?oauth_token=j5nyp6 to present the permission screen.
However every time the user needs to allow permission for the application. Ideally if the permission is given one time, further requests need not require permission unless the given permission is revoked. (Google and Twitter login works in this way which I could implement)
Is this the only way Yahoo login can be done or is there any workaround
Answer: Are you storing the Access Token? Or are you forcing the user through the full OAuth flow everytime?
If you are storing the Access Token, then that is all that is needed to access the services after the initial OAuth process.
Comment: I'm struggling to solve same issue. Can you please briefly explain how should I store the access token and how to access the services without going through full OAuth flow everytime? I'll really appreciate that.

Yahoo OAUTH Login for website


Crystal Report Viewer crashing an application when trying to export the report source to disk as a PDF .Net

Question: I'm trying to export the reportsource of a crystal report viewer in .Net 1.1 onto disk as a PDF using
<code>CrystalDecisions.CrystalReports.Engine.ReportDocument cr = (CrystalDecisions.CrystalReports.Engine.ReportDocument)crvView.ReportSource;
cr.ExportToDisk(CrystalDecisions.[Shared].ExportFormatType.PortableDocFormat, @"C:\Temp\Temp.pdf");
</code>
I know it's the "cr.ExportToDisk..." line thats failing, but dont know why.
Ive checked to make sure the Crystal Report versions are the same on the client machines and they are.
Sometime i get the message "Memory could not be read at source...." and the application completely crashes, and other times the app crashes without the message.
Any ideas on why this happens and how to fix it would be greatly appreciated.
Cheers
Comment: Are those "sometimes" "always for the same data", "always for the same machine", or "always for the same data, on the same machine", or a genuine case of "given the same input, the same machine will sometimes work, and sometimes fail"?
Comment: Given the same input, different machines will produce different results (fail or succeed). However the same machine with the same data will always produce the same result (if it fails once, it will always fail and vice versa).
Comment: Do these failing machines have an older version of crystal?
Comment: No, ive checked the versions on each of the machines and both the failing machines and the non-failing machines all have the same version of crystal.
Comment: I've seen cases where having multiple versions of crystal installed can give you crazy errors. Is it possible they also have an older version in addition to the correct version?
Comment: I have the same issue and this is also applicable: "given the same input, the same machine will sometimes work, and sometimes fail". Like if it is a bad today, it will be failing every time. If it is a good day, it will work like a charm :)
Answer: You may check to make sure that the security permissions are the same for the locations that you are trying to export to.
Comment: I've tried exporting to several locations on the clients machine with the same result (including locations that i know the client has full priveladges to).
Answer: Are you able to print these "faulty" reports? If so, have you tried printing to CutePdf which might allow you to at least work around the issue temporarily.


Conplex/real Integration and poles of function

Question: So I am working on the following problem:
Let $\Delta $ be the unit disk centered at origin, and $f$ is holomorphic on $\Delta-\{0\}$. If $$\int_\Delta|f|dxdy<\infty$$ show that $f$ has at most a degree 1 pole at 0.
I start with writting the integral in polar coordinate: $$\int_0^1\int_0^{2\pi} r|f(re^{i\theta})|d\theta dr$$
The inner integral is finite for various value of $r$. So the integral $$\int_{|z|=1}fdz\leq \int_{|z|=1}|f||dz|<\infty$$ So from here where do I go, my goal is show that $zf(z)$ is a holormophic function on $\Delta$. I thought of the function $$F(z)=\int_{|\xi|=1}\frac{\xi f(\xi)}{\xi-z}d\xi"="2\pi izf(z) $$
I put a quotation mark because I want some this equality to come out. This equality does not follow unless $F(z)$ is holormophic and finite. But how can we show that based on what we have?
Thanks
Comment: Why do you go from $|f|$ to $|f|^2$ in your post? Is one of these a typo?
Comment: I edited, thanks for pointing it out
Comment: This reminds me of the mean value property. Perhaps that is of some interest here?
Comment: See my answer i think i got it
Answer: From the previous post we know that $$|\int_{|z|=1}fdz|\leq \int_{|z|=1}|f||dz|$$ The right hand is exactly the integral $$\int_{|z|=1}|f|\cdot |z|dz=\int_0^{2\pi} r|f(re^{i\theta}|d\theta$$, where $r=1$. So $\int_{|z|=1}zf(z)$ is finite. Assume the integral is zero, if not u can subtract the constant on both side. By Morera Thorem, $zf(z)$ is holmorphic on $\Delta$.
Comment: Look, I'm no genius at complex analysis, and in light of this, maybe I'm missing something, but I thought Morera required the integral to vanish along *any* closed path, not just a circular one.  Am I in error here?
Comment: First of all thanks for your dedicated answer. Morera does require any closed path, but can we argue using homotopicity of circle to a closed path? Assume the path does not wind, if it does break the curve into pieces. I dont know if this works. If this is bogus, then my proof is false
Comment: Thanks for the kind words.  Your question is an interesting one; as far as I can see, it *might* work if you can use one of those tricks whereby you connect the circle with an arbitrary closed path in $\Delta$ by yet a third path which is traced each way during the integration process.  Is that clear without a diagram, does it make sense?  Not sure, not sure, worth thinking about!  Cheers!
Comment: @amathnerd: Take a look at my answer.
Answer: Suppose $f(z)$ has a pole of order $n \ge 2$ at the origin.  Then is it not the case that
$g(z) = z^n f(z) \tag{1}$
for some $g(z) \in H(\Delta)$?  It is indeed; see this widipedia entry. Furthermore, $g(0) \ne 0$, whence $\vert g(0) \vert > 0$.  Thus there is a real $\gamma > 0$ with $\vert g(0) \vert > \gamma$, and since $g(z)$, hence $\vert g(z) \vert: \Delta \to \Bbb R$ is continuous,  there exists real $\rho \in (0, 1)$, such that $\vert g(z) \vert > \gamma$ for $z \in \bar D (0, \rho)$, where $D(0, \rho)$ is the disk or radius $\rho$ centered at $0$, and $\bar D(0, \rho)$ is its closure.  In $\bar D(0, \rho) \setminus \{0\}$ we have, from (1),
$f(z) = z^{-n}g(z); \tag{2}$
now writing $z = re^{i \theta}$ so that $z^n = r^n e^{i n \theta}$ in $\Delta$ and $z^{-n} = r^{-n}e^{-i n \theta}$ in $\Delta \setminus \{0\}$, we see from (2) that we may write
$f(z) = r^{-n}e^{-in \theta}g(z) \tag{3}$
in $\bar D(0, \rho) \setminus \{0\}$, whence
$\vert f(z) \vert^2 = f(z) \bar f(z) = r^{-2n} g(z) \bar g(z) = r^{-2n} \vert g(z) \vert^2 \tag{4}$
or
$\vert f(z) \vert = r^{-n} \vert g(z) \vert, \tag{5}$
also holding in $\bar D(0, \rho) \setminus \{0\}$; and since $\vert g(z) \vert > \gamma$ on $\bar D(0, \rho)$, we see that
$\vert f(z) \vert > \gamma r^{-n} \tag{6}$
in $\bar D(0, \rho) \setminus \{0\}$.
Having prepared the estimate (6) for $f(z)$ on $\bar D(0, \rho) \setminus \{0\}$, we may proceed to evaluate the integral
$\int_{\bar D(0, \rho) \setminus \{0\}} \vert f(z) \vert dx dy \tag{7}$
by the usual means:  viz., we begin by picking real $\epsilon$ such that $0 < \epsilon < \rho$ and evaluate the integral over the annular region $A = \bar D(0, \rho) \setminus D(0, \epsilon)$; switching to polar coordinates, we have
$\int_A \vert f(z) \vert dx dy = \int_A \vert f(z) \vert r dr d\theta = \int_0^{2\pi} \int_\epsilon^\rho \vert f(z) \vert r dr d\theta > \gamma \int_0^{2\pi} \int_\epsilon^\rho r^{-n} r dr d\theta, \tag{8}$
where use has been made of (6).  Continuing in this direction,
$\gamma \int_0^{2\pi} \int_\epsilon^\rho r^{-n} r dr d\theta = 2 \pi \gamma \int_\epsilon^\rho r^{1 - n} dr; \tag{9}$
if $n = 2$, then we obtain
$\int_A \vert f(z) \vert dx dy > 2\pi \gamma \int_\epsilon^\rho r^{-1} dr = 2\pi \gamma (\ln r \mid_\epsilon^\rho = 2 \pi \gamma \ln(\dfrac{\rho}{\epsilon}), \tag{10}$
whereas if $n > 2$ we have
$\int_A \vert f(z) \vert dx dy > 2\pi \gamma \int_\epsilon^\rho r^{1 - n} dr = 2\pi \gamma (\dfrac{1}{2 - n} r^{2 - n}\mid_\epsilon^\rho$
$= 2 \pi \gamma \dfrac{1}{2 - n}(\rho^{2 - n} - \epsilon^{2 - n}); \tag{11}$
in either case we see that
$\int_A \vert f(z) \vert dx dy \to \infty \; \; \text{as} \;\; \epsilon \to 0. \tag{12}$
This shows that, with the conventional means of evaluation, $\int_{\bar D(0, \rho)} \vert f(z) \vert dx dy$ is unbounded, but since
$\int_\Delta \vert f(z) \vert dx dy \ge \int_{\bar D(0, \rho)} \vert f(z) \vert dx dy, \tag{13}$
$\int_\Delta \vert f(z) \vert dx dy$ is unbounded as well; thus
$\int_\Delta \vert f(z) \vert dx dy < \infty \tag{14}$
implies we must have $n < 2$; the pole of $f(z)$ at $0$ must be of order at most $1$.  QED.
Hope this helps.  Cheers,
and as always,
Fiat Lux!!!
Answer: Assume that
$$
f(z)=\sum_{n=-\infty}^\infty a_nz^n.
$$
If $a_{k}\ne 0$, for some $k>1$, then
$$
a_{-k}=\frac{1}{2\pi i}\int_{\lvert z\rvert=r}z^{k-1}f(z)\,dz,
$$
and hence
$$
\lvert a_{-k}\rvert\le  r^{k}
\int_{0}^{2\pi}\lvert\, f(r\mathrm{e}^{i\vartheta})\rvert\,d\vartheta
$$
and thus
$$
\frac{\lvert a_{-k}\rvert}{r^k}\le
\int_{0}^{2\pi}\lvert\, f(r\mathrm{e}^{i\vartheta})\rvert\,d\vartheta.
$$
But
$$
\int_{\Delta}\lvert\,f\rvert\,dx\,dy=\int_0^{2\pi}\left(\int_0^1 \lvert f(r\mathrm{e}^{i\vartheta})\rvert \,r\,dr\right)d\vartheta\ge
\int_0^{1}
\frac{\lvert a_{-k}\rvert\,dr}{r^{k-1}}=\infty,
$$
as $\int_0^1 r^{-s}\,dr=\infty$ iff $s\ge-1$


How do I update 3D quiver FuncAnimation from a data in csv file?

Question: I need help on how to update 3D quiver head value from csv
currently, I have a csv file with 3 columns of x, y, z axis that I want to update into u,v,w variable on my python code.
The problem I am facing is that the result animation does not animate properly. It is a static picture shown below.
https://i.stack.imgur.com/Os8FX.png
I'm sure that I must have messed up on how to iterate/read the csv data file.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots(subplot_kw=dict(projection="3d"))

# Reading the data from a CSV file using pandas
repo = pd.read_csv('test.csv',sep=',',header=0)
data = np.array((repo['x'].values, repo['y'].values, repo['z'].values))

def get_arrow():
    x = 0
    y = 0
    z = 0
    u = data[0][:]
    v = data[1][:]
    w = data[2][:]
    return x,y,z,u,v,w

quiver = ax.quiver(0,0,0,0,0,0)

ax.set_xlim(-.5, .5)
ax.set_ylim(-.5, .5)
ax.set_zlim(-.5, .5)

def update(theta):
    global quiver
    quiver.remove()
    quiver = ax.quiver(*get_arrow())

ani = FuncAnimation(fig, update, frames=np.linspace(0,2*np.pi,200), interval=50)
plt.show()

Answer: I'm not sure how the arrows will behave because the data is unknown, but I tried to create them with sample data. I've also included a library for GIF images and jupytert, so you can modify it to suit your environment.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation
import random
from IPython.display import HTML
from matplotlib.animation import PillowWriter

random.seed(20210110)

repo = (pd.DataFrame({'x':np.random.randint(0,5, size=50),
                     'y':np.random.randint(0,5, size=50),
                     'z':np.random.randint(0,5, size=50)}))
data = np.array((repo['x'].values, repo['y'].values, repo['z'].values))

fig, ax = plt.subplots(subplot_kw=dict(projection="3d"))

quiver = ax.quiver([],[],[],[],[],[])

ax.set_xlim(-5, 5)
ax.set_ylim(-5, 5)
ax.set_zlim(-5, 5)

def update(i):
    global quiver
    quiver.remove()
    quiver = ax.quiver(0,0,0,data[0][i],data[1][i],data[2][i])

ani = FuncAnimation(fig, update, frames=50, interval=50)
# plt.show()
ani.save('./quiver_test_ani.gif', writer='pillow')
plt.close()
# jupyter lab
# HTML(ani.to_html5_video())

Comment: Did the animation work as expected? The fix is that the functionized `get_arrow` is now included in the animation function. I changed `frames=50` to match the default settings and the number of data. Please accept this answer.
Comment: Yes, the animation is now working as intended. Sorry about not accepting the answer earlier. I'm still new to this.


Three shooters shoot at the same target, each of them shoots just once.

Question: Three shooters shoot at the same target, each of them shoots just once. The three of them respectively hit the target with a probability of 60%, 70%, and 80%. What is the probability that the shooters will hit the target
a) at least once
b) at least twice

I have an approach to this but I'm not sure if there's just a formula for this type of thing. For part (a) I was thinking of simply adding the probability of all of the valid scenarios. For instance $$[P(A)*(1-P(B))*(1-P(C))]+[(1-P(A))*P(B)*(1-P(C))]+...$$
and so on until I cover all scenarios in which "at least one" hits. Is there a simpler way? (i assume this would also apply to part b)
Comment: Hint for the first part:  it's easier to compute the probability that they all miss.
Comment: i see. are you saying this because there are less probabilities to calculate? duh!
Comment: Yes...and the event "at least one person hits" is the complimentary event to the event "nobody hits".
Comment: thank you for this!
Answer: Let $X$ be the number of times the target is hit. The probability $P(X \ge 1)$ then equals 1 minus the probability of missing the target three times:
$$P(X \ge 1) = 1 - (1 - P(A)) (1 - P(B)) (1 - P(C)) = 1 - 0.4 \cdot 0.3 \cdot 0.2 = 0.976$$
To find the probability $P(X \ge 2)$ of hitting the target at least twice, you can consider two cases: either two people hit the target and one does not, or all people hit the target. We find:
$$P(X \ge 2) = 0.4 \cdot 0.7 \cdot 0.8 + 0.6 \cdot 0.3 \cdot 0.8 + 0.6 \cdot 0.7 \cdot 0.2 +  0.6 \cdot 0.7 \cdot 0.8 = 0.788$$
Answer: "a) at least once".  Writing "H" for a hit and "M" for a miss, and writing hits and misses in the order "ABC" there are 3 possibilities:
HMM: probability is (0.6)(0.3)(0.2)= 0.036
MHM: probability is (0.4)(0.7)(0.2)= 0.056
MMH: probability is (0.4)(0.3)(0.8)= 0.096
The probability of any one of these happening is 0.036+ 0.056+ 0.096= 0.188.
"b) at least twice".  These are
HHM: probability is (0.6)(0.7)(0.2)= 0.084
HMH: probability is (0.6)(0.3)(0.8)= 0.144
MHH: probability is (0.4)(0.7)(0.8)= 0.224
The probability of any one of these happening is 0.084+ 0.144+ 0.224= 0.452.
"c) all three".  This is
HHH: probability is (0.6)(0.7)(0.8)= 0.336.
Comment: for part a i think you are forgetting about the HHM, HMH, MHH, and HHH scenarios. for part b think you are forgetting about the HHH scenario.
Comment: You are right.  I gave "exactly  one" rather than "at least one".  The obvious way to do that is to subtract P(MMM) from 1.
Answer: Consider the polynomial
$$P(x)=(0.4\, +0.6 x) (0.3\, +0.7 x) (0.2\, +0.8 x)$$
The neat thing about $P(x)$ is that when expanded it gives all you could possibly want to know about the probabilities of the number of shooters hitting the target:
$$P(x) = 0.024\, +0.188 x+0.452 x^2+0.336 x^3$$
The coefficient of $x^n$ in $P(x)$ is the probability that exactly $n$ shooters will hit the target, for $n=0,1,2,3$.  I.e., the probability that zero shooters will hit the target is 0.024, that one shooter will hit the target is 0.188, that two shooters will hit the target is 0.452, and that three shooters will hit the target is 0.336.
This method is especially attractive if you have a computer algebra system, but in small examples like this one hand computation is also easy.


Duvida em colisoes em javascript

Question: estou começando a programar agora, e tenho a tarefa de fazer um simples controle com os teclados em um "mapa" que é uma imagem, e o carrinho n pode ultrapassar as ruas, o mapa é a imagem em anexo mas n estou conseguindo em pensar em uma lógica para fazer as colisoes usando as coordenadas x/y as areas em verde, ou seja, tudo que nao for rua o carrinho n podera andar meu carrinho tem tamanho 40x20 pixels.
PS: Nao quero o código pronto, quero um auxilio para pensar na logica ou alguma forma mais facil de fazer que n seja usando x/y
Comment: *Colision Detection* ainda tem bastante ciência por trás, para funcionar com velocidade/aceleração, etc. Por isso depende do realismo da implementação que quer dar. Tem muito material na net sobre isso, tem até [um exemplo simples no próprio MDN para jogos 2D](https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection)
Answer: A partir desta imagem, gere uma nova imagem, onde as ruas são brancas e o resto é preto. A ideia é a seguinte, onde é branco, vc pode ir, onde é preto está bloqueado. Sempre que vc quiser mover o carrinho vc checa nesta imagem, primeiramente, se a nova posição continua na posição branca. Se sim, vc move, caso contrário, vc recusa o movimento (colisão)
Comment: Hmmm, é uma boa também. Obrigado! Mas já entreguei o trabalho, muito obrigado!
Answer: Já fiz algo parecido com isso. Mas eu tive que criar um cenário como esse com quadradinhos, cada quadradinho representava algo que poderia sofrer colisão ou não.
No seu caso, você poderia separar essa imagem em quadrados pequenos, tentando separar ao máximo todo o asfalto. E no seu código você monta a imagem, e cada quadrado com asfalto você atribui um valor. Ao percorrer com o carro na imagem, você verifica se ela está colidindo com o valor que está no asfalto, se não estiver você não deixa se movimentar.
Existem maneiras e ferramentas mais fáceis para fazer isso, mas como é pro seu estudo, essa é uma ótima tarefa.
Boa sorte!
Comment: Entao, eu pensei em fazer assim, dividir todas as quadras em pequenos objetos e verificalar se o carrinho invade o espaço delas, usando matriz, mas o professor pediu necessariamente q fosse utilizando if testando as posicoes x/y. Porem n tenho a minima ideia de como fazer. Na correção me enganei, é pra utilizar x/y. testando toda vez que uma tecla é acionada. cima/baixo/esquerda/direita, se ele estiver proximo n deve andar. Mas obrigado! Caso consiga pensar em algo agradeço

Duvida em colisoes em javascript


change linux process priority

Question: I ran a jar file in Linux and it is running from last 3 days.
How can I change priority of that process? Will it speedup my
application processing?
Comment: 3 days? Are you sure it still processing something?
Comment: I like to use the term **niceness** in the context of **nice/renice** tools. This is because there are also other aspects which affect how much CPU a process can get. For example see scheduling attributes and **chrt**.
Answer:
How can I change priority of that process?

renice priority [-p] pid

Useful priorities are: 20 (the
  affected processes will run only when
  nothing else in the system wants to),
  0 (the ``base'' scheduling priority),
  anything negative (to make things go
  very fast)

Example: renice -5 -p 123, 123 is process PID, -5 is priority

Will it speedup my application processing?

No, if load average less number of CPU core.
Comment: Thanks for your reply. There is no other process running on my computer. Will it make a big diff. to change priority? I checked my process priority and it is 0. What does it mean?
Comment: The default priority will share equally among running processes.  Nicing the process is usually used to allow other processes to run faster, slowing the niced process if other processes are running.  Negative priorities require root privileges, and can halt all other processes.  Avoid them for anything CPU intensive.
Comment: The key to remember is that the number is how nice the process is to others. a big number means it is very nice. a negative number means it is not nice at all and won't let the other processes play.
Answer: You can change priority with renice command. It will speed up processing only if there are other applications actively consuming CPU time.
Answer: By default process priority in Linux is 0. Process priority can have any number between -20 to 19. Process priority can be set by using nice and modified using renice. -20 is the highest priority process and 19 is the lowest priority.
Here you're having a process already running and you want to change its priority. So you can enter the following command
renice -5 pid

where pid is the process id of the process whose priority you want to modify. To increase the priority of a process i.e. to set the priority value to a negative value, you need to be root user or use sudo.
Hope that helps.

change linux process priority


How to get XPath value from nested div

Question: How can I get the value 5000+ by providing key "Installs" to xpath.

Installs

5,000+

I tried this response.xpath('//span/div/span/text()').extract() but it's giving all text.
Can anyone help me with it?
Comment: What do you mean by *"...giving all text"*? What is your desired and current output? Also try `//div[.="Installs"]/following-sibling::span/div/span/text()`
Comment: @Andersson it works for me. Thanks
Answer: I tried this and it worked:
response.xpath('//div[./div/text()="Installs"]/span/div/span/text()').extract_first()

It searches for a div with a div child that has the text()="Installs", then searches for the span containing the value you requested.
Answer: Try this:
response.xpath('./div/span[@class="htlgb"]/text()').extract()

Comment: i don't want to use the class as it may change.
Comment: sure okay, can you give me the website, i'll update my answer accordingly.

How to get XPath value from nested div


Is there something wrong with this problem statement? [Analysis Preliminaries]

Question: The problem seems to be asking the pre-image of $f(B)=[-1,1]$ where $f(x)=x^2$. The solutions manual provided that the pre=image is $f^{-1}(B)=[-1,1]$ which does not seem right to me.
Comment: You can't, but the point is that *you don't need to*.
Comment: Why do you think it is wrong?
Comment: because there's no real number squared is negative.
Comment: B being the image $[-1,1]$ with $f(x)=x^2$. If $f^{-1}(B)=[-1,1]$, how can I find a real number $x\in [-1,1]$ such that $f(x)=-1$?
Comment: You can't, but that's irrelevant. Review the definition of $f^{-1}([-1,1]).$
Answer: The pre-image is $[-1, 1]$. The numbers from that set, squared, will be in $B$, and any number outside of that set, squared, will fall outside $B$.
I am not sure what is confusing you. Perhaps the fact that not every element of $B$ will be an image of something in $[-1,1]$? That is true but not relevant for deciding what the pre-image is. Incidentally, what is true is that $f(f^{-1}(B))\subset B$ where the inclusion is strict in our case (the LHS is $[0,1]$).
Comment: that was really embarassing! I guess I took too long of a break from this.
Answer: Let $B = [-1,1]$, and let $f(x) = x^2$.

Claim $f^{-1}(B) = [-1,1]$.

Proof:
First suppose $x \in [-1,1]$.
\begin{align*}
\text{Then}\;&x \in [-1,1]\\[4pt]
\implies\;&|x| \le 1\\[4pt]
\implies\;&0 \le x^2 \le 1&&\text{[since $x^2 \ge 0$]}\\[4pt]
\implies\;&-1 \le x^2 \le 1\\[4pt]
\implies\;&x^2 \in [-1,1]\\[4pt]
\implies\;&f(x) \in B\\[4pt]
\implies\;&x \in f^{-1}(B)\\[4pt]
\end{align*}
It follows that $[-1,1] \subseteq f^{-1}(B)$.

Next, suppose $x \in f^{-1}(B)$.
\begin{align*}
\text{Then}\;&x \in f^{-1}(B)\\[4pt]
\implies\;&f(x) \in B\\[4pt]
\implies\;&x^2 \in [-1,1]\\[4pt]
\implies\;&x^2 \in [0,1]&&\text{[since $x^2 \ge 0$]}\\[4pt]
\implies\;&0 \le x^2  \le 1\\[4pt]
\implies\;&|x| \le 1\\[4pt]
\implies\;&-1 \le x \le 1\\[4pt]
\implies\;&x \in [-1,1]\\[4pt]
\end{align*}
It follows that $f^{-1}(B) \subseteq [-1,1]$.

Thus, we have both inclusions, hence $f^{-1}(B)=[-1,1]$.


Copy a user directly in database from another database (from production to dev-site)

Question: related to this post for Drupal 6 (Adding a new user directly in database), I wanted to ask for help for my problem:
I have a drupal 7 site which is already online ("in use/production"). Users can register there.
To get an up to date dev-enviroment, I download the files (uploaded files, modules and so on) via ftp from my production server to my dev server.
The DB is migrated by "backup and create"-module (export on production server, import on dev-server and vice versa).
As I develop the features in my dev instances, new users register on my production site. If I now import my new backup of the dev-server to production site, the new users registered are lost because the db has been overwritten by the backup.
How can I copy these new user accounts directly to the dev database? what database tables are involved in Drupal 7?
THX in advance
phil
Answer: Databases shouldn't be copied upstream, they should only be copied downstream, for the exact reason you are seeing.
This is a bit of a problem in Drupal 7.
If you need to move content up from dev -> production, like new nodes or you want to move configuration, then the best way to do it is either manually, or to set up something like the migrate module to migrate your content.
Answer: I'd suggest you take a look at the Deploy module. It allows you to copy and stage content across Drupal sites in a clean way and is designed for use cases like yours. It has support for moving user accounts as well.
NOTE: Always remember to take a backup of either sites before doing any DB surgery :)


entire teaser as link to node

Question: I would like to use the whole tease as a link to the node. I could google (and adapted) the following code but still not working.
following line:
scripts[] = js/new_teaser.js is added in the ".info" file of my theme (Business)
and this code to the "new_teaser.js":
<code>$(document).ready(function(){

    $(".node-teaser").click(function(){
      window.location=$(this).find("a").attr("href"); return false;
    });

    });
</code>
the class of my teaser is ".node-teaser" and the "NoScript" addin of my browser is switched off. I assumes that the problem is in the JS code.
Drupal 7, theme Business
Could someone help me please?
EDIT: as far as I can see, there is no link to the new_teaser.js file in the source code of the page... (even if the file is in the js/ folder and in the theme .info file
Comment: Though I don't think you should do it this way, have you tried clearing cache?
Comment: Of course, cache cleared, cron ran...
Comment: I found that soution here: https://drupal.org/node/606758 but it doesn't work for me...
Answer: Something like this should work. Add it to your template.php file. Using preprocess_node gives you a little more control so you aren't just arbitrarily loading the script on every page.
<code>function THEMENAME_preprocess_node(&$variables) {
  if ($variables['type'] == 'blog' && $variables['view_mode'] == 'teaser') {
    drupal_add_js($theme_path.'/js/new_teaser.js');
  }
}
</code>

entire teaser as link to node


When is it safe to turn open_basedir off?

Question: If I have PHP with Suhosin running as CGI under Apache SuExec, is open_basedir necessary? I've heard it's good to have in a shared hosting environment where the sites are outside of your direct control, but what if the sites are all my own?
Comment: Enabling open_basedir or safe_mode will incredibly slowdown your site.
Please take a look at this https://bugs.php.net/bug.php?id=52312
Answer: I'd suggest that you always want to go with the most restrictive permissions possible. SuExec and Suhosin are a good start, but many files are readable by 'other' (e.g. some logs, possibly your other web files, etc) and some locations (e.g. /tmp) are writeable by all. Furthermore, SuExec is not immune to vulnerabilities - additional precautions are always beneficial.
Consider it from this perspective - even though it is your code that you are running, the possibility of vulnerabilities still exists. If your code is compromised and someone is able to execute other code, you want whatever safeguards possible in place. Each additional safeguard you have in place will help to limit the damage that can be done on a compromised system.
Ideally, each of your sites would be setup in a chroot jail (better performance and security) - however, that tends to be a lot of work to setup and maintain. Using open_basedir is an easy to setup alternative (although, not immune to exploits), which typically has little impact on the functioning of most sites. There has been at least one case where it has been helpful even with SuExec.
open_basedir does have a performance penalty - but if that is a major concern, it may be best to benchmark the performance of your site with and without it, and see if the difference is significant (in which case, you may consider the chroot approach, if your system allows it).
Always expect the worst, even though you may hope for the best.


Understanding r.js, almond, and relative paths

Question: I see this answer but AFAICT it's not working for me. Maybe I'm doing something stupid.
I'm using almond and grunt-contrib-requirejs. I've tried a bunch of stuff
Here's my layout
.
├── Gruntfile.js
├── 3rdparty
│   ├── require.js
├── src
│   ├── lib.js
│   └── main.js
└── node_modules
    └── almond
        └── almond.js

And here's my grunt-contrib-requirejs config
requirejs: {
  full: {
    options: {
      baseUrl: "./",
      name: "node_modules/almond/almond.js",
      include: [ "src/main.js" ],
      out: "dist/app.js",
      optimize: "none",
    },
  },
},

main.js looks like this
requirejs(['./lib',], function(lib) {
  lib.hello();
});

lib.js looks like this
define([], function() {
    return {
      hello: function() {
          console.log("hello from lib");
      },
    };
});

If run a page that uses require.js as in

It runs great. You can see it live it here. Check the console and you'll see it prints hello from lib
So I run grunt. Then I run a page that uses dist/app.js and I get the error
Uncaught Error: undefined missing lib

Here's a live page.
Checking the generated dist/app.js I see lib has been turned into this
define('src/lib',[], function() {
   ...
});

And main is including it like this
requirejs(['./lib'], function(lib) {
  ...
});

In other words, the id that r.js generated src/lib doesn't match the id that main is referencing ./lib.
This seems like a very straight forward example for r.js. Like practically "hello world".
What am I doing wrong?
One thing I've tried is changing the baseUrl to ./src
requirejs: {
  full: {
    options: {
      baseUrl: "./src",
      name: "node_modules/almond/almond.js",
      include: [ "src/main.js" ],
      out: "dist/app.js",
      optimize: "none",
    },
  },
},

But now I get
{ [Error: Error: ENOENT: no such file or directory, open '/Users/gregg/temp/grunt-contrib-requirejs-example/src/node_modules/almond/almond.js'
    at Error (native)
]
  originalError:
   { [Error: ENOENT: no such file or directory, open '/Users/gregg/temp/grunt-contrib-requirejs-example/src/node_modules/almond/almond.js']
     errno: -2,
     code: 'ENOENT',
     syscall: 'open',
     path: '/Users/gregg/temp/grunt-contrib-requirejs-example/src/node_modules/almond/almond.js',
     fileName: '/Users/gregg/temp/grunt-contrib-requirejs-example/src/node_modules/almond/almond.js' } }

So I try fixing the almond path
requirejs: {
  full: {
    options: {
      baseUrl: "./src",
      name: "../node_modules/almond/almond.js",
      include: "main",
      out: "dist/app.js",
      optimize: "none",
    },
  },
},

But that fails as well
{ [Error: Error: ERROR: module path does not exist: ../node_modules/almond/almond.js for module named: ../node_modules/almond/almond.js. Path is relative to: /Users/gregg/temp/grunt-contrib-requirejs-example
    at /Users/gregg/temp/grunt-contrib-requirejs-example/node_modules/requirejs/bin/r.js:30214:35
]
  originalError: [Error: ERROR: module path does not exist: ../node_modules/almond/almond.js for module named: ../node_modules/almond/almond.js. Path is relative to: /Users/gregg/temp/grunt-contrib-requirejs-example] }

What am I not getting?
The entire thing is checked into github here if you'd like to work with it.
Answer: So here's the answer.
r.js prefers module names not paths
requirejs: {
  full: {
    options: {
      baseUrl: "./src",
      paths: {
        almond: "../node_modules/almond/almond",
      }
      name: "almond",
      include: [ "main.js" ],
      out: "dist/app.js",
      optimize: "none",
    },
  },
},


Finding X and Y coordinates from two angles

Question: I have a triangle ABC in the x-y coordinate plane.
Corners A and B lie on x-axis. Length of AB is known. Angles A and B are also known.
Question: Find (x,y) coordinates of corner C.
Comment: You know the three angles, then you can use the law of sines for find the other sides
Answer: Hint:
With law of sines you can find the other sides.
If $A= (x_{1},y_{1})$ and $B=(x_{2},y_{2})$, then $|AB|=\sqrt{(x_{1}-x_{2})^2+(y_{1}-y_{2})^2}$
Now, if $C=(x,y)$ get :
$$|AC| = \sqrt{(x-x_{1})^2+(y-y_{1})^2}$$  $$|BC| = \sqrt{(x-x_{2})^2+(y-y_{2})^2}$$
Remember that you know $|AB|,|AC|,|AB|$.
Now you can find $x,y$
Answer: Another possibility is as follows: this solution to your problem involves using the fact that the slope of a line making an angle $\theta$ with the positive x-axis is $\tan\;\theta$; now, what you have are two lines with slopes $\tan\;A$ and $\tan(\pi-B)$ in one case, and slopes $\tan\;B$ and $\tan(\pi-A)$ in the other. Construct the point-slope form for the two lines through $A$ and $B$, and find their intersection through the usual methods.
Answer: A system of linear equations:
Assume A is at the origin.
You can form basis vectors for AC and BC using the angles A and B
U_{AC} = [cosA  sinA]^T
U_{BC} = [cosB  sinB]^T

Then we know geometrically
w*U_{AC} - x*U_{BC} = [ AB  0 ]^T

This is a 2x2 linear system.  Solve for w and x.
Then
x = w*cosA
Y = w*sinA

best regards.
Answer: $c = || AB ||;$
$\theta_c = 360 - \theta_a - \theta_b;$
$b = {\sin(\theta_b) \over \sin(\theta_c)} c;$
$C.x = b \cos(\theta_a)$
$C.y = b \sin(\theta_a)$
Comment: This is assuming that A is at the origin


Multiple Random Variables Union and Intersection Complement Operation

Question: I'm currently studying probability theory with the textbook Probability and Random Processes for Electrical and Computer Engineers (John Gubner) and had a question regarding multiple random variables.
More specifically, this comes from Example 2.10 of section 2.3 Multiple Random Variables - Independence on page 72.

A webpage server can handle $r$ requests per day. Find the probability that the server gets more than $r$ requests at least once in $n$ days. Assume that the number of requests on day $i$ is $X_i \sim \text{Poisson}(\lambda)$ and that $X_1, \dots , X_n$ are independent.
Solution:
$$
\begin{align}
P\left(\bigcup_{i = 1}^n \{ X_i \gt r \}\right) & = 1 - P\left( \bigcap_{i = 1}^n \{X_i \le r \} \right) \\\
& = 1 - \prod_{i = 1}^nP\big(X_i \le r \big) \\\
& = 1 - \prod_{i = 1}^n \left( \sum_{i = 1}^r \frac{\lambda^k e^{-\lambda}}{k!} \right) \\\
& = 1 - \left( \sum_{i = 1}^r \frac{\lambda^k e^{-\lambda}}{k!} \right)^n
\end{align}
$$

I understand the solution, but what's confusing me is how the first line was derived. That is:
$$ P \left( \bigcup_{i = 1}^n \{X_i \gt r \} \right) = 1 - P\left( \bigcap_{i = 1}^n \{ X_i \le r \} \right)$$
I've tried working it out with a simple example of two random variables, but that's also not really making a lot of sense.
How was this equality derived?
Answer: $P(E)=1-P(E^{c})$. The complement of the set $\bigcup_{i=1}^{n} \{X_i >r\}$ is exactly the set $\bigcap_{i=1}^{n} \{X_i \leq r\}$ .
Comment: Basically $(\bigcup_i S_i)^\complement=\bigcap_i (S_i^\complement)$ as per DeMorgan's Law.  $$\begin{align}x\in(\bigcup_i S_i)^\complement&\iff \neg\exists i~.x\in S_i\\&\iff \forall i~.x\notin S_i\\&\iff x\in\bigcap_i S_i^\complement\end{align}$$ And, of course, the complement of the event of $\{X_i>r\}$ is that $\{X_i\leq r\}$
Comment: Thanks for the quick answer. Is that complement that result of DeMorgan's Law? I'm just having trouble intuitively grasping how that result occurs. For the first example you gave it makes sense that $P(E) = 1 - P(E^c)$, but it doesn't come to me as easily for the case with sets.
Comment: Yes, I am using De Morgan's Laws. See, for example  https://en.wikipedia.org/wiki/De_Morgan%27s_laws


Grails long error message when build an application - BEGINNER

Question: I just created a project with Grails and ran it by typing the command. However, i ended up with a super long error message.
When i googled for a solution i bumped into this thread where they were discussing for a solution. But i have no clue how to solve it.
I think its the Java version. I am using jdk1.8.0_45.jdk. There were several other post that says Grails doesn't support jdk1.8.0_45.jdk. Help. How to resolve this ?
My environment:
OS - MAC OS
Grails - 2.4.4
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1270)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSite.invoke(PogoMetaMethodSite.java:166)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:56)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16.doCall(GantBinding.groovy)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1270)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:207)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.call(PogoMetaMethodSite.java:68)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
    at gant.Gant$_dispatch_closure5.doCall(Gant.groovy:381)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1270)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:207)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.call(PogoMetaMethodSite.java:68)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy:415)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1270)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSite.invoke(PogoMetaMethodSite.java:166)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:56)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:49)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:133)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1270)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:207)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.call(PogoMetaMethodSite.java:68)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
    at gant.Gant.withBuildListeners(Gant.groovy:427)
    at gant.Gant.this$2$withBuildListeners(Gant.groovy)
    at gant.Gant$this$2$withBuildListeners$0.callCurrent(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:49)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:133)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at gant.Gant.dispatch(Gant.groovy:415)
    at gant.Gant.this$2$dispatch(Gant.groovy)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1270)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1207)
    at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1110)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1016)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:809)
    at gant.Gant.invokeMethod(Gant.groovy)
    at groovy.lang.GroovyObject$invokeMethod.callCurrent(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:49)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:133)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:145)
    at gant.Gant.executeTargets(Gant.groovy:591)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1270)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSite.invoke(PogoMetaMethodSite.java:166)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:56)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:49)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:133)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:145)
    at gant.Gant.executeTargets(Gant.groovy:590)
    at org.codehaus.groovy.grails.cli.GrailsScriptRunner.executeWithGantInstance(GrailsScriptRunner.java:781)
    at org.codehaus.groovy.grails.cli.GrailsScriptRunner.executeScriptFile(GrailsScriptRunner.java:573)
    at org.codehaus.groovy.grails.cli.GrailsScriptRunner.executeScriptWithCaching(GrailsScriptRunner.java:472)
    at org.codehaus.groovy.grails.cli.GrailsScriptRunner.callPluginOrGrailsScript(GrailsScriptRunner.java:416)
    at org.codehaus.groovy.grails.cli.GrailsScriptRunner.executeCommand(GrailsScriptRunner.java:380)

Answer: Yes you would have problems the way you are setup now. Grails 2.4.4 can only carry you as far as jdk8u20 or u31 if I remember correctly but not beyond. You can easily switch to Grails 2.5.0 for seamless integration with jdk8u40 and u45.
Also, if you are running them on GGTS, make sure it is v3.6.4, and that you install Groovy 2.4 from the extensions page to get the show on the road. I have the same setup both on Windows 7 and on the Mac OS X Yosemite; all work great. Let me know if you get stuck as I went through the headaches of making them tango together.
Answer: You should uninstall java8 and install the latest java 7 sdk instead.
Alternatively, install java 7 sdk alongside java 8, and set your JAVA_HOME environment variable to point to the location of java 7.
Good luck.