text:
Q: Writing email reply bot using poplib and random emails keep showing up in me re.findall(...) call I'm using poplib to connect to a gmail account and I want it to reply to emails that are sent to it.
However sometimes my regular expression's statement grabs random emails that aren't the one I wanted to reply to.
For example:
5952f967.8543630a.1c70d.283f@mx.google.com
Code below:
def checkEmail():

mail = poplib.POP3_SSL('pop.gmail.com')
mail.user(USER)
mail.pass_(PASS)
numEmails = len(mail.list()[1])
count = 0

if(numEmails>=1):
    for i in range(numEmails):
        for msg in mail.retr(i+1)[1]:
            sender = re.findall(r'[\w\.-]+@[\w\.-]+',msg)
            for s in sender:
                if s and count == 0:
                    count += 1
                    replySender(s)
                    print s
            message = email.message_from_string(msg)
count = 0
mail.quit()


text:
Q: Checking roles for an item How can I check if current user has roles for editing, creating an item in a list in Sequential Workflow ?

A: There isn't anything in SDP workflows that allows for that.  You'd have to make sure that the lists are permissioned appropriately or that those steps are being run under an impersenation step.

A: To check if current user has permissions on item, folder, list or site use DoesUserHavePermission method

redpajama_set_name: RedPajamaStackExchange


text:
Q: Examples of processes that are not Poisson? I am looking for some good examples of situations that are ill-suited to model with a Poisson distribution, to help me explain the Poisson distribution to students.
One commonly uses the number of customers arriving at a store in a time interval as an example that can be modeled by a Poisson distribution. I'm looking for a counterexample in a similar vein, i.e., a situation that can be regarded as a positive count process in continuous time which is clearly not Poisson.
The situation should ideally be as simple and straightforward as possible, in order to make it easy for students to grasp and remember.

A: Do you  mean positive count data? Unbounded?
The negative binomial is popular.
Another good model is the Poisson with inflated 0. That model assumes that either something is happening or it isn't - and if it is, it follows a Poisson. I saw an example recently. Nurses who treated AIDS patients were asked how often they experienced stigmatizing behaviours from others as a result of their involvement with AIDS patients. A large number had never had such experiences, possibly because of where they worked or lived. Of those that did, the number of stigmatizing experiences varied. There were more 0's reported than you would expect from a straight Poisson, basically because a certain proportion of the group under study were simply not in an environment that exposed them to such behaviours.
A mixture of Poisson's would also give you a point process.

A: Number of cigarettes smoked in a period of time: this requires a zero-inflated process (e.g. zero-inflated Poisson or zero-inflated negative binomial) because not everyone smokes cigarettes.

A: Counting processes that aren't Poisson? Well, any finite sample space process like binomial or discrete uniform. You get a Poisson counting process from counting events having independent interarrival times which are exponentially distributed, so a whole host of generalizations fall out of that such as having gamma or lognormal or Weibull distributed interarrival times, or any kind of abstract non-parametric interarrival time distribution.

A: It's unclear if you want counting processes or not.
If I interpret the 'teaching' tag to mean you are teaching the Poisson process then, for teaching about a process in general, the Bernoulli process is an easy random process to explain and visualize and is related to the Poisson process. The Bernoulli process is the discrete analog so it might be a helpful companion concept. Its just that instead of continuous time we have discrete intervals of time.
An example might be a door to door sales man where we are counting successes by homes that make a purchase.

*

*The number of successes in the first n trials, has a binomial
distribution B(n, p) instead of a Poisson

*The number of trials needed to get r successes, has a negative binomial distribution NB(r, p)
instead of a gamma distribution

*The number of trials needed to get one success, the waiting time, has a geometric distribution NB(1, p), which is the discrete analog of the exponential.

That's the approach Bertsekas and Tsitsiklis use in Introduction To Probability, 2nd ed., introducing the Bernoulli process before the Poisson process. In their textbook there are more extensions to Bernoulli process that are applicable to the Poisson process such as merging them or partitioning them, as well as problems sets with solutions.
If you are looking for examples of random processes, and you just want to throw the names out there, there are quite a few.
The Gaussian process is a significant one in applications. The Weiner process in particular, which is a type of Gaussian process, is also called standard Brownian motion and has applications in finance and physics.

A: As an property/casualty actuary, I deal with real-life examples of discrete processes which are non-Poisson all the time. For high-severity, low-frequency lines of business, the Poisson distribution is ill-suited as it demands a variance-to-mean ratio of 1. The negative binomial distribution, mentioned above, is much more commonly used, and the Delaporte distributions is used in some of the literature, though less often in standard North American actuarial practice.
Why this is so is a deeper question. Is the negative binomial so much better because it represents a Poisson process for which the mean parameter is itself gamma distributed? Or is it because loss occurrences fail independence (as earthquake events do under current theory that the longer one waits for the earth to slip, the more likely it is due to the build-up in pressure), is it non-stationary (the intervals cannot be subdivided into sequences, each of which is stationary, which would allow the use of a non-homogeneous Poisson), and certainly some lines of business allow for simultaneous occurrences (e.g. medical malpractice with multiple doctors covered by the policy).

A: Others have mentioned several examples of point process that are not Poisson.  Because the Poisson corresponds to exponential interarrival times if you pick any interarrival time distribution that is no exponential the resulting point process is not Poisson. AdamO pointed out the Weibull.  You could use gamma, lognormal, or beta as possible choices.
The Poisson has the property that its mean is equal to its variance.  A point process which has variance greater than the mean is sometimes referred to as overdispersed and if the mean is larger than the variance it is underdispersed.  These terms are used to relate the process to a Poisson.  The negative binomial is often used because it can be overdispersed or underdispersed depending on its parameters.
The Poisson has a variance that is constant.  A point process that fits the Poisson conditions except for not having a constant rate parameter and consequently a time varying mean and variance is called an inhomogeneous Poisson.
A process with interarrival times exponential but can have multiple events at the arrival time is called a compound Poisson.  Though similar to the Poisson process and having a name with the word Poisson in it, inhomogeneous and compound Poisson processes are different from a Poisson point process.

A: Another interesting example of non-Poisson counting process is represented by the zero-truncated Poisson distribution (ZTPD). ZTPD can fit data concerning the number of languages subjects can speak in physiological conditions. In this instance, Poisson distribution is ill-behaving, because the number of spoken languages is by definition >=1: hence 0 is ruled out a priori.

A: I believe that you could take your customer-arrival Poisson process and tweak it in two different ways: 1) customer arrivals are measured 24-hours a day, but the store is not actually open all day, and 2) imagine two competing stores with Poisson process customer arrival times and look at the difference between the arrivals at the two stores. (Example #2 is from my understanding of the Springer Handbook of Engineering Statistics, Part A Property 1.4.)

A: You might want to reconsider the soccer example. It seems that the scoring rates for both teams increase as the match goes on, & that they change when teams change their attacking/defending priorities in response to the current score.
Or rather, use it as an example of how simple models can perform surprisingly well, stimulating interest in statistical investigation of some phenomenon, & providing a benchmark for future studies that collect more data to investigate discrepancies & propose elaborations.
Dixon & Robinson (1998), "A Birth Process Model for Association Football Matches", The Statistician, 47, 3.

A: Since the question is related to making the Poisson distribution more understandable, I'll give it a go, since I recently looked into this somewhat for call center incoming call patterns (which follow a memory-less, exponential distribution as time goes on).
I think delving into another tangential model that essentially requires knowledge of Poisson to realize how it isn't one may be somewhat confusing, but that's just me.
I think the trouble with understanding Poisson is the continuous time axis it's on --- as every second goes on, the event is no more likely to occur --- but the further out in the future you go, the more certain it is of happening.
Really, I think it simplifies the understanding if you just trade the 'time' axis for 'trials' or 'events'.
Someone can correct me if this is way off base, as I feel it's an easy explanation, but I think you can replace the flip of a coin, or the toss of a dice, with 'time until a phone call arrives' (what I typically use for Erlang C/ call center staffing).
Instead of 'time until a phone calls arrive' ---- you can replace it with ... 'rolls until a dice hits six'.
That follows the same general logic. The probability (like any gambling) is completely independent every roll (or minute) and is memory-less. However, the likelihood of 'no 6' decreases ever slower but surely towards 0 as you increase number of trials. It's easier if you see both graphs (likelihood of call with time, vs. likelihood of six with rolls).
I don't know if that makes sense --- that's what helped me put it together into concrete terms. Now, the poisson distribution is a count rather than 'time between calls' or 'trials until rolling a six' -- but it relies on this likelihood.

A: Number of visits by an individual customer to the grocery store within a given time interval.
After you have been to the grocery store, you are unlikely to return for a while unless you made a planning mistake.
I think the Negative Binomial distribution could be used here, but it is discrete, whereas the visits are in continuous time.


text:
Q: How to prevent insert of duplicate data with nHibernate? I'm building a blog/CMS system (for fun, I know there are a ton out there I could use).
I have a simple Tag entity that only has an Id (int) and a TagName (string) property.  I'd like to configure nHibernate such that I can do something like:
var tag1 = Tag.CreateTag("duplicate tag test");  // Id=0 at this point
var tag2 = Tag.CreateTag("duplicate tag test");  // Id=0 at this point
TagRepository.Save(tag1);  // tag1.Id is non-zero
TagRepository.Save(tag2);  // tag2.Id should be the same as tag1.Id at this point, but it's not

Assert.AreEqual(tag1, tag2);

I envision Save(Tag) doing something like a look-up, and if the tag already exists, somehow replace tag2 with tag1's values. nHibernate works some magic that modifies the parameter's properties even though it's not passed as an out parameter.  Can someone tell me what's happneing here and how to fix ths method to do what I want?  I'm trying to avoid having to use the out keyword on the tag parameter.
    public override void Save(Tag tag)
    {
        Tag existingTag = GetByTagName(tag.TagName);
        if (null == existingTag)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.SaveOrUpdate(tag);
                transaction.Commit();
            }
        }
        else
        {
            tag = existingTag; // obviously doesn't impact the caller
        }
    }

A: I don't think your reference to 'out parameter' makes sense. The object is still the same instance, but NH has updated the ID to the generated one when saved.
I think you just have to fetch the tag first as you are doing in your example. If you want the caller to see the correct id do
tag.id = existingTag.id;

I think your question relates to parameters and how they are handled and not to NHibernate.  Read this article to get a good grounding in how this stuff works.


text:
Q: Where do I get mediastreamsegmenter for http live streaming? I can't seem to find the mediastreamsegmenter or mediafilesegmenter command line utility for OSX Lion.  I have Xcode 4.5 installed and it's not in /usr/bin
Lots of google search results say to go to connect.apple.com and search for "http live streaming" but that only yields this:

Developer tools link on right hand of Apple's Http live Streaming site yields the same result.  Is this a replacement for these command line utilities?

A: Three important thing to follow to see this download available on the page.

*

*You have to be a paid  iOS Developer Program Member

*https://developer.apple.com/downloads/index.action?=http%20live%20streaming%20tools

*You must use Safari Browser

A: My developer subscription had lapsed.  Once renewed I could see the tool.


text:
Q: administration menu for custom module does not appear I am trying to make my own module. I implemented hook_menu and hook_form and I wanted to test it, but the administration page for it does not exists. I am just learning to work with drupal. Could anyone help me please?
Code for testmod.module:
/**
 * Implements hook_menu()
 */
function testmod_menu() {
  $items = array();
  $items['admin/config/content/testmod'] = array(
    'title' => 'Testmod',
    'description' => 'Configuration for testmod module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('testmod_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
);

}
function testmod_form($form,$form_state) {
$form['testmod'] = array(
'#type' => 'textfield',
'#title' => t('Test value'),
'#description' => t('Enter the test value here'),
'#size' => '100',
'#default value' => variable_get('testmod'),
);
return system_settings_form($form);
}

I can't acces this form I have created. When I enter mypage.com/admin/config/content/testmod I will get to admin/config/content
Could anyone tell me what am I doing wrong? Thanks.

A: I don't see anything wrong with the hook_menu() code. It might be related to the actual path (maybe the content path is already pointing to somewhere else and considering testmod as a parameter).
Did you try with a different path, such as admin/config/testmod?


text:
Q: Issues with OR operator in WP functions.php Our Wordpress website requires that some pages are only visible for users with specific roles. Currently the administrator can not access the pages specified in $redaktor_pages and $mod_pages.
add_action( 'template_redirect', 'restrict_access' );
function restrict_access() {
    //pages for admins
    $admin_pages = is_page(array('veiledning-administrator', 'database'));
    //pages for redaktør
    $redaktor_pages = is_page(array('veiledning-redaktor'));
    //pages for moderators
    $mod_pages = is_page(array(''));

    //users forum role
    $forum_role = bbp_get_user_display_role( get_current_user_id() );

    if( (!current_user_can('administrator') && $admin_pages) || ( (!current_user_can('editor') || !current_user_can('administrator') ) && $redaktor_pages ) || ( ($forum_role!='moderator' || !current_user_can('administrator')) && $mod_pages) ) {
        wp_redirect('/');
        exit;
    }
}

Where I use logical operators within an if-statement: (a || b) && c it seems like the function ignores "b".
I would expect the 'administrator' role to also be able to view pages specified within $redaktor_pages and $mod_pages seeing as it is included within the if-statement.
Logically I would expect: (a = false || b = true) = true
What is actually happening is that 'administrator' can not view pages that are listed within the specific variables, unless they are the $admin_pages
This makes it seem as if that part of the if-statement is treated like this: (a = false || b = true) = false

A: So you have 3 sets of conditions here, and if any of them evaluate to true the access is denied.
For your second and third conditions, your question says you're working with (a || b) && c but this is not the case. You're working with (!a || !b) && c which is a very different thing. Think about what the combination of OR and NOT means. Both conditions are evaluated and either one being true results in the condition being true.
So when you check if an administrator is NOT editor OR NOT administrator then the condition evaluates to true because they are NOT an editor. You want to use AND to check that both conditions aren't true. Checking an administrator is NOT editor AND NOT administrator evaluates to false.
function restrict_access() {
    //pages for admins
    $admin_pages = is_page(array('veiledning-administrator', 'database'));
    //pages for redaktør
    $redaktor_pages = is_page(array('veiledning-redaktor'));
    //pages for moderators
    $mod_pages = is_page(array(''));

    //users forum role
    $forum_role = bbp_get_user_display_role( get_current_user_id() );

    if(
        (!current_user_can('administrator') && $admin_pages) ||
        (!current_user_can('editor') && !current_user_can('administrator') && $redaktor_pages) ||
        ($forum_role != 'moderator' && !current_user_can('administrator') && $mod_pages)
    ) {
        wp_redirect('/');
        exit;
    }
}

Note that && has higher precedence than || so the extra parentheses you've got here are implied and unnecessary. But I find it's better to explicitly include them anyway.


text:
Q: Android Combined Date-Time Picker I need to integrate one dialog in my app which asks for Date and Time in single dialog.
Problem is that, natively Android supports this individually, So please suggest me any such library if you know.

A: I found one such library.
Please check here:
https://github.com/florent37/SingleDateAndTimePicker


text:
Q: Data structure to keep count of elements and retrieve elements with count within range I need a data structure to keep count of elements and then retrieve elements within a certain range of counts.
Example:
counter = RangeCounter()
for el in [1, 1, 2, 2, 2, 0]
    counter.add(el)

counter.get(occurence >= 1 and occurence <= 2)
>>> 1, 2 (element 1 is encountered 2 times)
>>> 2, 3 (element 2 in encountered 3 times)

A: with collections.Counter you could do all that:
from collections import Counter

counter = Counter([1, 1, 2, 2, 2, 0])
# Counter({2: 3, 1: 2, 0: 1})

# occurence >= 1 and occurence <= 2
res = {item: count for item, count in counter.items() if 1 <= count <= 2}
# {1: 2, 0: 1}


text:
Q: Get the current Object in its own properties - Anylogic How can you get the currently selected object in its own properties?
In the example bellow I want to send the currently selected StopLine to a function on each vehicle pass.
Using the this fucntion only returns the parent object - main.
I was hoping there is a simple function to return the object without having to directly input the current object.
Thanks,

A: You need to use "self". For such questions, the light bulb is your best friend. Refer to the following article:
https://www.benjamin-schumann.com/blog/2016/2/4/the-magic-lightbulb-and-how-it-can-help-your-anylogic-modelling


text:
Q: create an ID column with randomly generated values in R I am using the package called mtcars and I want to get a randomly generated number for every observations. I have written a function:
mtcars$ID <- NULL
for (i in mtcars){
  mtcars$ID <- runif(1, min=0, max=100)
}

However, this assigns the same number to all cars.
I tried:
mtcars$ID <- NULL
for (i in mtcars){
  mtcars$ID[i] <- runif(1, min=0, max=100)
}

which results in an error. I would like to get two type of results (two functions):

*

*to assign a random number to each observation

*to assign a unique random number to each observation

A: You could use sample on the number of rows in the dataset.
mtcars$ID <- sample(nrow(mtcars))

The range for this would be from 1 to number of rows in data and it would be randomly assigned to every row.
It can also be wrapped in a function if needed :
get_a_unique_id <- function(data) sample(nrow(data))

mtcars$ID <- get_a_unique_id(mtcars)
iris$ID <- get_a_unique_id(iris)

Regarding OP's attempt on for loop. NULL deletes the column whereas NA initializes it with NA.Since there is no column present in mtcars, it results in an error. Also the loop for (i in mtcars){ loops over the column values and not rows. Try
 for (i in mtcars){
    print(i)
 }

Hence, it should be
mtcars$ID <- NA
for (i in seq_len(nrow(mtcars))){
   mtcars$ID[i] <- runif(1, min=0, max=100)
}

However, even this does not guarantee 100% on having a unique value for each row since with runif we can have same numbers.

A: There are of course a plenty of easier ways to assign random values to ID column.
Seems OP is only interested in the solutions with for loop, then here are some examples to make it

*

*to assign a random number to each observation:

for (i in seq(nrow(mtcars))){
  mtcars$ID[i] <- runif(1, min=0, max=100) # assign random value which might be duplicated (but with low probability if you don't have super many rows)
}

*to assign a unique random number to each observation

for (i in seq(nrow(mtcars))){
  repeat {
    r <- runif(1, min=0, max=100)
    if (!r %in% mtcars$ID) break # if generated random number is not in the existing values, then terminate the loop and go to value assignment in the next step
  }
  mtcars$ID[i] <- r
}


text:
Q: CORS headers not showing up in my request/response on Django I've made the following CORS implementation on my Django project using django-cors-headers.
CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOWED_ORIGINS = []

MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
....
]

INSTALLED_APPS = [
   ...
    'corsheaders',
]

For some reason, I don't see the effect of these headers (I don't have Access-Control-Allow-Origin in my headers). I print out the request and response headers in my view. This is my view:
def payment(request, *args, **kwargs):
    print(request.headers)
    params_in = json.loads(request.body.decode('utf-8'))
    headers_in = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer key,
        }
    response = requests.post('https://url.com/v1/endpoint',
            headers=headers_in,
            data=params_in)

    resp_out = Response(response.json()['value'])
    print(resp_out.headers)
    return resp_out

My request headers are ['Host', 'Connection', 'Content-Type', 'Origin', 'Accept-Encoding', 'Cookie', 'Accept', 'User-Agent', 'Referer', 'Accept-Language', 'X-Request-Id', 'X-Forwarded-For', 'X-Forwarded-Proto', 'X-Forwarded-Port', 'Via', 'Connect-Time', 'X-Request-Start', 'Total-Route-Time', 'Content-Length'] and my only resp_out header is 'Content-Type'.
Why could this be? What am I missing?

A: You don't receive the CORS headers as a part of the request rather the Access-Control-Allow-Origin: Your_Origin_Name(if among the allowed ones mentioned in CORS_ALLOWED_ORIGINS = []
) header will be sent back as a response header.


text:
Q: Windows 10 boot is idle for 80 seconds during session init phase I installed windows 10 enterprise from a DVD. Now the boot takes to long. More specific the "Session Init" phase is idling for about 80 seconds. The ETL file for WPA can be downloaded at
https://drive.google.com/open?id=0B3f_WdRCKIHWRmxJU0VjQjM1WFE
I would be very thankful for some help with finding the cause for the 80 seconds because I really don't know how to use the analyzer.
Thanks
Heiner

A: When you look at the services graph, you can see that the LSM ( Local Session Manager) service takes 71s to init:

This is causing the delay.

The svchost.exe (720) is waiting for some WorkerThread. Contact the Microsoft Support and send them the ETL. They can analyze this deeper.

A: Thank you very much. I was able to narrow it down further. It was the ULPS feature of the display driver display driver that caused this. My solution is to disable ULPS as described here: https://community.amd.com/thread/176003
This solution isn't perfect, but it's good enough for me.
As far as I am concerned this is closed.
Bye!


text:
Q: Type conversion and QThreadStorage warning while using QThread? I'm very new to using QThread. I'm using QThread to grab  images from an Axis Ip Camera. In the following snippet of the code I'm moving the camera class to a new thread:
QThread camThread;
camera = new AxisNetworkCamera();
camera->moveToThread(&camThread);
camThread.start();
connect(camera, SIGNAL(imageUpdate(QImage)), this, SLOT(upDateImage(QImage)));
connect(camera, SIGNAL(cameraDisconnected()), this, SLOT(cameraDisconnected()));
connect(&camThread, &QThread::finished, &camThread, &QThread::deleteLater);
connect(camera, &AxisNetworkCamera::destroyed, &camThread, &QThread::quit);

I'm invoking the function that starts the camera:
QMetaObject::invokeMethod(camera, "deviceStartup", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(streamUrl)));

The application runs fine and also closes fine when I close it, but what I'm worried is about a couple of warning messages.
First one is when I start the camera:
Type conversion already registered from type QPair<QByteArray,QByteArray> to type QtMetaTypePrivate::QPairVariantInterfaceImpl

2nd one is when I close the application:
QThreadStorage: Thread 0x7fffb8004da0 exited after QThreadStorage 7 destroyed

Should I be worried about these messages? Do they, specially the second 1, mean any memory mismanagement?
Thanks

A: The code you've posted makes no sense. QThread is not dynamically allocated so you cannot delete it: the deleteLater call will crash. Probably it never gets executed, since you show no code that would stop the thread anyway. There's also no point in destroying the thread after the camera has been destroyed.
The simplest way to do things safely would be to hold the camera and thread by value in your class, and declare them in proper order so that the thread is destroyed before the camera. At that point, the camera becomes threadless and will be safe to destroy in any thread.
There's also a nicer way to invoke methods in remote threads than using invokeMethod:
class Thread : public QThread {
  using QThread::run; // final
public:
  Thread(QObject*parent = 0): QThread(parent) {}
  ~Thread() { quit(); wait(); }
};

// See http://stackoverflow.com/a/21653558/1329652 for details about invoke.
template <typename F> void invoke(QObject * obj, F && fun) {
  if (obj->thread == QThread::currentThread())
    return fun();
  QObject src;
  QObject::connect(&src, &QObject::destroyed, obj, std::forward<F>(fun));
}

class MyObject : public QObject {
  Q_OBJECT
  AxisNetworkCamera camera;
  Thread camThread { this };
  Q_SLOT void updateImage(const QImage &);
  Q_SLOT void cameraDisconnected();
public:
  MyObject(QObject * parent = 0) : QObject(parent)
  {
    connect(&camera, &AxisNetworkCamera::imageUpdate, this, &MyObject::updateImage);
    connect(&camera, &AxisNetworkCamera::cameraDisconnected, this, &MyObject::cameraDisconnected);
    camera.moveToThread(&camThread);
    camThread.start();
  }
  void startCamera(const QString & streamUrl) {
    invoke(&camera, [=]{ camera.deviceStartup(streamUrl); });
  }
};


text:
Q: MongoDB connection to MongoLab timing out in NodeJS on Heroku At first everything works, and I can successfully store data by posting to the /upload route. But after 120 seconds of inactivity, the timeout event fires, and future attempts to store data fail. However the callback isn't called, so there is no "Unable to insert..." message at the log.
var express = require('express');
var bodyParser = require('body-parser');
var winston = require('winston');
var config = require('./config');
var MongoClient = require('mongodb').MongoClient;

var app = express();

app.use(bodyParser.json());

app.post('/upload', function (req, res) {
  req.json({status: 'recieved'});
  req.app.locals.db.collection('data').insertOne(req.body, function(err, result) {
    if (err === null) {
      winston.info('Successfully inserted', {data: req.body});
    } else {
      winston.warn('Unable to insert', {cause: err});
    }
  });
});

const options = {
  server: {
    socketOptions: {
      keepAlive: 1,
      autoReconnect: true,
      connectTimeoutMS: 5000
    }
  }
};

MongoClient.connect(config.databaseURI, function(err, db) {
  if (err !== null) {
    winston.error('Could not connect to database', {cause: err});
    return;
  }

  db.on('timeout', function (err) {
    winston.error('Mongo timed out', {cause: err});
  });

  app.locals.db = db;
  app.listen(config.port, function() {
    winston.info('Listening on port %d', config.port);
  });
});

I based my code loosely off of this example. It has been suggested to me that I open a new connection to the DB after every request, but this is not best practice since internally, MongoClient.connect is managing a pool. I also tried changing some of the options according to this. Still no luck.

A: This solved the problem for me:
var options = {
  server: {
    socketOptions: {
      keepAlive: 300000, connectTimeoutMS: 30000
    }
  },
  replset: {
    socketOptions: {
      keepAlive: 300000,
      connectTimeoutMS : 30000
    }
  }
};

Then put it in here:
if(process.env.MONGODB_URI) {
  mongoose.connect(process.env.MONGODB_URI, options);
} else {

  // Connect to local database

}


text:
Q: Implement a customized Google Calendar with React Js? My website currently runs a react-big-calendar Calendar with data I manually manage with graphql / Apollo
I decided to use Google Calendar for data management using the Google Calendar API instead of managing everything on my own database.
However, I was wondering if there was a way to directly include a custom Google Calendar ( the UI I mean ) in my website, so the Front-End part would be also managed by Google Calendar ( can be in an iframe, or a Google Component directly, if such a thing exists ).
This way I would leave most of the calendar front/back end logic to Google only, instead of having to call the Google API everytime I do a change on my react-big-calendar.
I say custom, because I would still need to edit some component, such as the pop-up opening when you want to create an event:

Most of the information have no use for me, and I would like to add others. I would also like to get rid of "search for people" or the create button on the sidebar, as an exemple.
Is there a way to include such a customized Google Calendar in my website? Or do I need to keep using my own react-big-calendar with data from the Google Calendar API?
Thanks in advance.

A: Unfortunately what you want cannot be achieved as Calendar doesn't offer the possibility of editing/modifying any of its content.
Hence, the only available options in this situation are:

*

*to embed it as explained in this article here;

*make use of the Calendar API and build your own interface for it, just like you mentioned above.


text:
Q: How to get wndproc to handle messages to multiple windows I've been trying to get a wndproc to successfully receive messages from the message queue and process them according to my code but it isn't working the way I want it to, what I'd like it to do is determine which window received WM_DESTROY or WM_CLOSE and call code specific to which window was closed, but for some reason at the moment it's doing nothing. After alot of experimentation I've gotten it to function partially in different ways but it seems like each implementation doesn't function just the right way. Here's my lastest unsuccessful code:
    while (GetMessage (&messages, NULL, 0, 0))
{
    /* Translate virtual-key messages into character messages */
    TranslateMessage(&messages);
    /* Send message to WindowProcedure */
    DispatchMessage(&messages);
}

/* The program return-value is 0 - The value that PostQuitMessage() gave */
return messages.wParam;
}

/*  This function is called by the Windows function DispatchMessage()  */

LRESULT CALLBACK Proc2(HWND mainwin, UINT message, WPARAM wParam, LPARAM lParam )
{
switch (message)                  /* handle the messages */
{
                       case WM_DESTROY:
                       const HWND active_window = GetActiveWindow();
                       if (active_window == mainwin)
                                {
                                   PostQuitMessage(0);
                                }
                                   if (active_window == hwnd2)
                                   {
                                                 PostQuitMessage(0);
                                                EnableWindow (mainwin, true);
                                   }
                                   break;
}
 switch (wParam)                  /* handle the messages */
{
              case ID_2 :
            PostQuitMessage(0);
            break;
              case ID_1 :
               ShowWindow (hwnd2, SW_SHOW);
               break;
                            default:                      /* for messages that we don't deal with */
        return DefWindowProc (mainwin, message, wParam, lParam);
                    break;
}

    return 0;
}

Here is the code I tried with multiple window procedures
while (GetMessage (&messages, NULL, 0, 0))
{
    /* Translate virtual-key messages into character messages */
    TranslateMessage(&messages);
    /* Send message to WindowProcedure */
    DispatchMessage(&messages);
}

/* The program return-value is 0 - The value that PostQuitMessage() gave */
return messages.wParam;
}

/*  This function is called by the Windows function DispatchMessage()  */

LRESULT CALLBACK Proc2(HWND mainwin, UINT message, WPARAM wParam, LPARAM lParam )
{
switch (message)                  /* handle the messages */
{
                       case WM_DESTROY:
                                   PostQuitMessage(0);
                                   break;
}
 switch (wParam)                  /* handle the messages */
{
              case ID_2 :
            PostQuitMessage(0);
            break;
              case ID_1 :
               ShowWindow (hwnd2, SW_SHOW);
               break;
                            default:                      /* for messages that we don't deal with */
        return DefWindowProc (mainwin, message, wParam, lParam);
                    break;
}

    return 0;
}
LRESULT CALLBACK Proc3(HWND hwnd2, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
           case WM_DESTROY:
EnableWindow (mainwin, false);
                break;
case WM_CLOSE:
EnableWindow (mainwin, false);
break;
}
switch (wParam)
{
   default:
           return DefWindowProc (hwnd2, message, wParam, lParam);
           break;
           }
           return 0;
           }

A: You say,

"what I'd like it to do is determine which window received WM_DESTROY or WM_CLOSE"

The simple answer is that the window that's receiving UINT message is HWND mainwin.
If you want to know "yes, but which of my windows is HWND mainwin?" then one way to do that is, when you create a window, you remember what its window handle is, and store it somewhere (e.g. as a global variable).

Apart from that, it isn't clear why you're calling GetActiveWindow(), nor what functionality you want to implement.


text:
Q: SQL Server: calculate all days per month when no orders? Suppose you have orders
   | Order |     Date    |
   -----------------------
   |   1   |   20150101  |
   |   2   |   20150103  |
   |   3   |   20150105  |
   |   11  |   20150211  |
   |   22  |   20150224  |
   |   33  |   20150204  |

and the days when no orders are
   |  Month  | NoOrdersCount |
   ---------------------------
   | 201501  |      28       |
   | 201502  |      25       |

I want to do this in T-SQL. My first idea is to create table for a year where all days per line and left join this with the orders. Now the sum of NULLs gives us the results of no orders.
How can you calculate the number of NoOrders per month from transaction data like the above in SQL Server 2014?

A: You don't need an additional table.  All you need is a way to calculate the number of days in a month.  Here is one method:
select year(date), month(date),
       (datediff(day,
                 dateadd(day, 1 - day(min(date)), min(date),
                 eomonth(date) + 1 -
        count(distinct date)
       ) as NoOrdersCount
from dates
group by year(date), month(date);

As a note:  If you know you will always have one day in the month that is not the 29th, 30th, or 31st, you can use:
select year(date), month(date),
       (datediff(day, min(date), dateadd(month, 1, min(date))) -
        count(distinct date)
       ) as NoOrdersCount
from dates
group by year(date), month(date);

A: One more way to get the day of the month end date and subtracting the number of distinct dates when there were orders.
select distinct year(date),month(date),
day(eomonth(date)) - (select count(distinct date) from orders o2
                      where year(o2.date)=year(o1.date)
                      and month(o2.date)=month(o1.date))
from orders o1

Counting can be done with a window function, but distinct isn't allowed.

A: Looks like this should do it for you.
select convert(char(6), date, 112) as Month,
       day(eomonth(min(date))) - count(distinct date) as NoOrdersCount
from dates
group by convert(char(6), date, 112);


text:
Q: Questions on limits of the sequence $a_{n}=\frac{(-1)^{n}n+1}{n}$
Given $a_{n}=\frac{(-1)^{n}n+1}{n}$, compute
  $$\lim\limits{\inf(a_{n})}$$
  $$\lim\limits{\sup(a_{n})}$$
  $$\inf\{a_{n}\}$$
  $${\sup(a_{n})}$$

My attempt:
I tried taking different values for the sequence and reached the following results:
$$\lim\limits{\inf(a_{n})}=1$$
$$\lim\limits{\sup(a_{n})}=-1$$
$$\inf\{a_{n}\}=3/2$$
$${\sup(a_{n})}=-1$$
The teacher told me to do it more formally, anyone can help me please?

A: Note that you've interchanged '(lim)inf' and '(lim)sup' throughout your question.
It's helpful to note that
$$a_n=\begin{cases}
1+\frac1n,&\text{if }n\text{ is even}\\\\
-1+\frac1n,&\text{if }n\text{ is odd}\;.
\end{cases}$$
Let's look first at $\sup_n a_n$. When $n$ is odd, $a_n\le 0$, and when $n$ is even, $a_n>0$, so in order to find $\sup_n a_n$ we need only look at the even-numbered terms: all of them are larger than any of the odd-numbered terms. But the subsequence $\langle a_{2n}:n\in\Bbb Z^+\rangle$ is clearly decreasing, so for every $n\in\Bbb Z^+$ we have $a_n\le a_2=\frac32$. Thus, $\sup_n a_n=\max_n a_n=a_2=\frac32$.
You can make a similar argument for $\inf_n a_n$.
Now let's look at $\limsup_n a_n$. By definition $$\limsup_n a_n=\lim_{n\to\infty}\sup_{k\ge n}a_k\;,\tag{1}$$ so for each $n\in\Bbb Z^+$ we need to see what $\sup\{a_k:k\ge n\}$ is. For this we can reason just as I did above to find that
$$\sup_{k\ge n}a_k=\begin{cases}
a_n,&\text{if }n\text{ is even}\\
a_{n+1},&\text{if }n\text{ is odd}\;,\tag{2}
\end{cases}$$
but I'll leave the details to you. Once you've shown $(2)$, you just have to evaluate $(1)$, and you should find that it's simply $$\lim_{n\to\infty}a_{2n}=\lim_{n\to\infty}\left(1+\frac1n\right)=1\;.$$ (I doubt that you'll be asked for a formal proof that this limit really is $1$.)
The arguments that you need for $\liminf_n a_n$ are very similar.

A: To make it more formal just use the definitions that you have for lim inf, lim sup, inf, and sup.  Show that your answers meet those definitions.


text:
Q: Series Radius of Convergence (Absolute) $$
\sum_{j=1}^{\infty}(-1)^{n+1}\left(\frac{n+1}{n^2}\right)x^n.
$$
Find the real numbers $x$ for which the series $(i)$ converges and $(ii)$ absolutely converges.
I did the ratio test and found radius of convergence to be $1$. I checked endpoints and I ended up with $x \in (-1,1]$. I believe this is correct but I might be wrong. I know this is the set of values of $x$ for which the series absolutely converges so is the answer to $(ii)$.
So for $(i)$ what would I do. I know if a series is absolutely convergent then it is convergent, so would the answer be the same? My other thought was to when doing $\frac{a_{n+1}}{a_n}$ to drop the absolute values. Either way I end up with the same answer so would this be the difference in working out I would have to show ?

A: For $x = 1$, the series converges by the alternating series test, but does not converge absolutely by comparison with $\sum_n 1/n$.  For $x = -1$, it neither converges nor converges absolutely.  So $(-1,1]$ is the answer to (i) and $(-1,1)$ is the answer to (ii).


text:
Q: Adding more than 64KB to an IBM (Lotus) Notes rich text field, using Lotusscript I use the following code to pull the contents of a .log (text) file into a Notes rich text field, but it fails if the amount of data is > 64 KB:
Dim io As Integer
Dim text As String
Dim fileSize As Single

io = Freefile
fileSize = 0

Open f For Input As io
fileSize = Filelen( f )

If (fileSize > 65536) Then
    Msgbox "Sorry, but the file " + f + " is > 64KB and cannot be rendered in the default rich text field.",, "Can't continue"
    Close #io
    Exit Sub
End If

While Not(Eof(io))
    Line Input #io, text
    Call uid.FieldAppendText("RT1", text + Chr(13) + Chr(10))
Wend

Close #io

I check the file size to avoid the error (which is a complaint that a paragraph can't exceed 64KB).  So how do you add multiple paragraphs, so you can display more than 64KB of data?

A: You insert a line break to create paragraphs larger than 64KB.
But you should be using back-end classes when you manipulate Rich Text fields.

A: Use NotesStream to read one line at a time, and then use NotesRichTextItem's AppendText and AddNewLine(1, True)
The subImportStreamToRT subroutine below is untested, so Murphy's Law says there's a big in here somewhere, but at least it compiles! Good luck!
Option Public
Option Declare
%Include "lserr.lss"

%REM
    Function fstreamOpenFile(sPath As String, bTruncate As Boolean, bConfirmExists As Boolean) As NotesStream

    Arguments

sPath

Filepath of the file to be opened/created.

bTruncate

Boolean. True if file is for output and any existing file should be replaced rather than appended to.

bConfirmExists

Boolean. If True, and the opened file is empty, then an ErrFileNotFound error will be thrown.

%END REM
Public Function fstreamOpenFile(sPath As String, bTruncate As Boolean, bConfirmExists As Boolean) As NotesStream
    Dim bFlag As Boolean
    Dim session As New NotesSession
    Dim stream As NotesStream

    If sPath = "" Then Error 13, "No path supplied."
    Set stream = session.Createstream()
    If Not stream.Open(sPath) Then Error ErrOpenFailed, {Could not open file at "} + sPath + {"}
    If bConfirmExists And stream.Bytes = 0 Then Error ErrFileNotFound, {File at "} + sPath + {" is missing or empty.}
    If bTruncate Then Call stream.Truncate()
    Set fstreamOpenFile = stream
End Function

%REM
    Sub subImportStreamToRT(stream As NotesStream, rt As NotesRichTextItem)
    For each line of text in the stream, appends that text in its own paragraph.
    Assumes that the first line of text can simply be appended without first creating a new paragraph. (e.g. rt is a blank field or you've already added a new line before calling this function)

    Arguments

stream As NotesStream

NotesStream containing text to be imported into a rich text file

rt As NotesRichTextItem

NotesRichTextItem to import stream's text into.

%END REM
Sub subImportStreamToRT(stream As NotesStream, rt As NotesRichTextItem)
    If Not stream.IsEOS Then
        Do
            rt.AppendText stream.ReadText(STMREAD_LINE, EOL_ANY)
            If stream.IsEOS Then
                Exit Sub
            Else
                rt.AddNewLine 1, True
            End If
        Loop
    End If
End Sub

To use,

*

*set a NotesStream variable to fstreamOpenFile(sFilePath, False, True)

*get/create a NotesRichTextItem object

*pass the NotesStream and NotesRichTextItem objects to subImportStreamToRT

*save your NotesDocument

*give it a try and debug the code because, again, subImportStreamToRT isn't tested.


text:
Q: Proving two bindings equal in Nominal Isabelle Consider the following datatypes with bindings in Nominal Isabelle:
theory Example
  imports "Nominal2.Nominal2"
begin

atom_decl vrs

nominal_datatype ty =
    Tvar   "vrs"
  | Arrow x::vrs T::"ty" binds x in T

nominal_datatype trm =
    Var   "vrs"
  | Abs   x::"vrs" t::"trm"  binds x in t

inductive
  typing :: "trm ⇒ ty ⇒ bool" ("_ , _" [60,60] 60)
where
 T_Abs[intro]: "(Abs x t) , (Arrow x T)"

equivariance typing
nominal_inductive typing done

lemma
  assumes "(Abs x t), (Arrow y T)"
  shows "x = y"
  using assms

I want to prove that the two bindings appearing in the relation are equal. I see two ways an Isabelle user could help:

*

*If you know Nominal Isabelle is it possible to do this?

*Otherwise, are the two occurrences of x in the rule T_Abs equal for the assistant or are they sort of bound variable with different identity?

A:

*

*If you know Nominal Isabelle is it possible to do this?

Unfortunately, it is not possible to prove the theorem that you are trying to prove. Here is a counterexample (the proofs were Sledgehammered):
theory Scratch
  imports "Nominal2.Nominal2"
begin

atom_decl vrs

nominal_datatype ty =
    Tvar   "vrs"
    | Arrow x::vrs T::"ty" binds x in T

nominal_datatype trm =
    Var   "vrs"
    | Abs   x::"vrs" t::"trm"  binds x in t

inductive
  typing :: "trm ⇒ ty ⇒ bool" ("_ , _" [60,60] 60)
where
 T_Abs[intro]: "(Abs x t) , (Arrow x T)"

equivariance typing
nominal_inductive typing .

abbreviation s where "s ≡ Sort ''Scratch.vrs'' []"
abbreviation v where "v n ≡ Abs_vrs (Atom s n)"

lemma neq: "Abs (v 1) (Var (v 0)), Arrow (v (Suc (Suc 0))) (Tvar (v 0))"
  (is "?a, ?b")
proof-
  have a_def: "Abs (v 1) (Var (v 0)) = Abs (v (Suc (Suc 0))) (Var (v 0))"
    (*Sledgehammered*)
    by simp (smt Abs_vrs_inverse atom.inject flip_at_base_simps(3) fresh_PairD(2)
        fresh_at_base(2) mem_Collect_eq nat.distinct(1) sort_of.simps trm.fresh(1))
  from typing.simps[of ?a ?b, unfolded this, THEN iffD2] have
    "Abs (v (Suc (Suc 0))) (Var (v 0)) , Arrow (v (Suc (Suc 0))) (Tvar (v 0))"
    by auto
  then show ?thesis unfolding a_def by clarsimp
qed

lemma "∃x y t T. x ≠ y ∧ (Abs x t), (Arrow y T)"
proof(intro exI conjI)
  show "v 1 ≠ v (Suc (Suc 0))"
    (*Sledgehammered*)
    by (smt Abs_vrs_inverse One_nat_def atom.inject mem_Collect_eq n_not_Suc_n
        sort_of.simps)
  show "Abs (v 1) (Var (v 0)) , Arrow (v (Suc (Suc 0))) (Tvar (v 0))"
    by (rule neq)
qed

end

*Otherwise, are the two occurrences of x in the rule T_Abs equal for
the assistant or are they sort of bound variable with different
identity?

I believe that you are thinking along the right lines and, hopefully, the example above will clarify any confusion that you might have. Generally, you could interpret the meaning of Abs x t1 = Abs y t2 as the alpha-equivalence of (λx. t1) and (λy. t2). Of course, (λx. t1) and (λy. t2) may be alpha equivalent without x and y being equal.


text:
Q: Объвление переменной в запросе Выполняю запрос, в котором несколько раз встречается одна и та же функция с одними и теми же параметрами. Например:
SELECT sum($1, $2) AS total, sum($1, $2) AS amount, sum($1, $2) AS result ...

Возможно ли записать результат выполнения в некую переменную, чтобы не выполнять расчёт суммы каждый раз? Например, насколько я знаю, в MSSQL возможно следующее решение:
DECLARE @total INT
SET @total = SUM(1, 2)

Как сделать подобный запрос в PostgreSQL? Функция sum() приведена лишь для примера. На самом деле там каждый раз выполняется более "тяжёлая" функция и хотелось бы оптимизировать этот момент.

A: Я предположу, что в большинстве случаев планировщик PostgreSQL
достаточно умён, чтобы понять, что чистые функции для одних и тех же
данных будут выдавать один и тот же результат.  Но если вам так уж надо,
просто заверните всё в подзапрос:

SELECT n AS total
     , n AS amount
     , n AS result
     , /* … */
  FROM
  (
    SELECT SUM(/* … */) AS n
      FROM /* … */
  ) AS t(n)
;


text:
Q: Dynamically construct querystring behaviour in IE and FF / Chrome This code
function LoadContent(Id) {
        alert('Controls/Network/NetworkDetail.aspx?' + rnd() + '&CtlId=' + Id);
        $.get('Controls/Network/NetworkDetail.aspx?' + rnd() + '&CtlId=' + Id, function(data) {
            $(Id).append(data);
        });
        $(Id).removeClass("Waiting");
}

works perfectly in IE7. the alert displayed intended querystring, and NetworkDetail.aspx page can obtain the CtlId using Request.QueryString["CtlId"]
However, using FF3 and Chrome, Request.QueryString["CtlId"] returns null but the alert displayed the querystring correctly (no difference to IE7).
the Id value is usually '#Tab1', or "#Tab2"
Any idea on how to correctly construct querystring?

A: The # indicates a named anchor in HTML and therefore is not part of the querystring, perhaps you sould correctly URL encode your id's.
e.g. #Tab1 becomes %35Tab1
Try using escape. e.g.
'Controls/Network/NetworkDetail.aspx?' + rnd() + '&CtlId=' + escape(Id)


text:
Q: Need some help with the conditions in CakePHP! I have three models linked in this manner: Item->Order->Payment
Order hasMany Item
Order hasOne Payment
Now, I am paginating Items and want to add a condition in it to find only items of that order which has payment of a particular id. I hope that makes sense :P
I added the condition as:

array('Payment.id'=>$id)

but it doesn't work. Obviously cause Payment is not associated with Item.
So, how can I go about this?

A: I am new to cakephp, maybe I am completily wrong but as I understand it you can use other models in your controller with the $uses variable. First make a query on payment model to get your order id, than you can use this id to find the corresponding items.
$uses=array('Item','Order','Payment');
$order_id=$this->Payment->find('first',array('fields'=>'order_id','conditions'=>array('id'=>$payment_id)));
$items=$this->Item->find('all',array('conditions'=>array('order_id'=>$order_id)));

I hope it help.

A: Why don't you add a condition:
array('Order.payment_id'=>$id)

I think this should work.

A: If you specify that you want two levels of recursion this should work.  Im assuming you have
in Payment.php
//recursion level 1
var $belongsTo = array('Order');

in Order.php
//recursion level 2
var $hasMany = array('Items')

You are right that for paginate to work you must query the model you wish to page and sort the lists by.
in PaymentController.php
//Query two levels deep, so the $payment['Order']['Item'][0-n] will be present
var $paginate = array('recursive' => 2);

Note this method does generate another query for each row to retrieve items.

A: Make sure the debug level in app/config/core.php is set to 2 to see the database calls.
1) You can use Containable behaviour, in which case you need to put this in your Item model:
var $actsAs = array('Containable');

and this into your Items controller:
$items = $this->Item->find('all'
   , array (
      'contain' => array('Order' => array('Payment'))
      , 'conditions' => array('Payment.id' => $paymentId)
   )
)

However I suspect that that will do a left join onto the Payments table (as its a hasMany relationship). So you won't filter Items in any way.
2) If you can't get contains to work then I often use explict joins (read this bakery article by nate on joins)  in my find queries.  So in your Items controller you'd have:
$items = $this->Item->find('all'
   , array (
      , 'joins' => array(
         array(
            'table' => 'payments'
            , 'alias' => 'Payment'
            , 'type' => 'INNER'
            , 'conditions' => array(
                'Option.id = Payment.option_id'
            )
         )
      )
      , 'conditions' => array('Payment.id' => $paymentId)
   )
)

You may also need to specify the join onto the options table.


text:
Q: A Mistake in my Codecademy Codebit, Not Sure What I do NOT have code here, as for it is going to take up too much space. It is an error in JavaScript as for it won't run anything in it, aswell as jQuery.
Click here if you wanna live...

A: Your problem is here I think:
.replace('function mName1()'),('?Method??-Custom?','function')
that comma needs to be a period and I'm guessing replace needs called.
.replace('function mName1()').replace('?Method??-Custom?','function')


text:
Q: Write an async method with Parallel.Foreach loop that does call another async method to pull record I am working on code performance optimizing and need suggestion the best approach in implementing async with parallel.foreach and/ or WhenAll.
The code is split into three main areas.
Code Definition
MethodA pickup the Customer list
MethodB PartA loop through Customers and pick record from database via a Azure Function. this is 1:* relation so 1 customer can have multiple records.
MethodB PartB go through customer records list that picked in method B Part A and look if is there any files attached. If there is file/ files then it process and send `Customer Reference' back to 'MethodA' where it store record in dictionary. Then it send
Method A
public async Task<List<Customers>> MethodA(){

  List<Customer> customers = await GetAllCustomers();
  var inboundCustomerFiles= new List<InboundCustomerFiles>();

   Parallel.ForEach(customer, async customer =>
   {
     var processedCustomer = await MethodB(customer);
     inboundCustomersFiles.AddRange(processedCustomer);

   });
}

Method B
  public static async Task<List<InboundCustomerFiles>> MethodB(Customer customer){
     var customerRecord = await GetCustomerRecord(customerId);

     foreach(var customer in customerRecord){
        var files = await getCustomerRecordFile(customerRecordId)
        //...... remaining code
     }
    return inboundCustomerFiles;
  }

Method 3
public static async Task<List<InboundCustomerFiles>> GetCustomerRecord(int customerId){
     //API call here that further pull `record` from database
return List<Records>();
}

the process in methodB customerRecord takes time. How I ensure that it process the data and return to correct customer thread in MethodA. I have tried to use in methodB but it slow down, further I know Parallel.Foreach does not wait so I tried to add async reference in lambda expression but not sure A is correct or if is work.

A: Well for one thing you can pretend that Parallel.ForEach awaits your async functions, but it doesn't. Instead you want to write something like this:
   await Task.WhenAll(customers.Select(async customer =>
   {
     var processedCustomer = await MethodB(customer);
     inboundCustomersFiles.AddRange(processedCustomer);
   }));

Task.WhenAll behaves like Parallel.ForEach, but it's awaitable and it also awaits every task you pass to it before completing its own task. Hence when your await Task.WhenAll completes, all the inner tasks have completely completed as well.

the process in methodB customerRecord takes time

That is very ambiguous. If you mean it takes server and/or IO time then that's fine, that's what async is for. If you mean it takes your CPU time (ie it processes data locally for a long time), then you should spin up a task on a thread pool and await its completion. Note that this is not necessarily the default thread pool! Especially if you're writing an ASP.NET (core) application, you want a dedicated thread pool just for this stuff.


text:
Q: What i pass the GCKMediaInformation contentID in our code google cast sdk I have passed the same url in GCKMediaMetadata object and GCKMediaInformation object contentID is correct?? I don't know which URL i pass in contentId of GCKMediaInformation please help me I am a  beginner in chromecast SDK. Thanks in Advance.
-(void)startCasting {

GCKMediaMetadata *metadata = [[GCKMediaMetadata alloc] init];
[metadata addImage:[[GCKImage alloc]
                    initWithURL:[NSURL URLWithString:@"https://fbcdn-photos-a-a.akamaihd.net/hphotos-ak-prn2/v/t1.0-0/s180x540/10444708_650079241771730_1270013251658544114_n.jpg?oh=f412367bc9632ed21aaf22bd7c08e3b2&oe=57FE0E19&__gda__=1476770561_aebfdf5d8dc13141e31a5848d8551cdb"]
                    width:480
                    height:360]];

GCKMediaInformation *mediaInformation =
[[GCKMediaInformation alloc] initWithContentID:@"https://fbcdn-photos-a-a.akamaihd.net/hphotos-ak-prn2/v/t1.0-0/s180x540/10444708_650079241771730_1270013251658544114_n.jpg?oh=f412367bc9632ed21aaf22bd7c08e3b2&oe=57FE0E19&__gda__=1476770561_aebfdf5d8dc13141e31a5848d8551cdb"
                                    streamType:GCKMediaStreamTypeNone
                                   contentType:@"image/jpeg"
                                      metadata:metadata
                                streamDuration:0
                                    customData:nil];
[_mediaControlChannel loadMedia:mediaInformation autoplay:YES playPosition:0];

}

A: For chromecast to work as intended, you need to have a web server that is hosting/serving your image and use the URL that the web server provides there. If your images are somewhere in the cloud, that should be trivial; if images are on your phone, then you need to embed a local web server in your phone sender app and use that to serve the images and pass the URL based on what your web server provides.


text:
Q: in vim, how to set "args" to the result of a "grep -l"? To illustrate, here's how to do it from the command-line:
vim `grep "hello" * -Rl`

This opens vim with all the files that have "hello" in them (-l gives the filenames alone). I want to do the same thing, but from within vim.  Conceptually, something like this (which doesn't work):
:args !grep "hello" * -Rl

I'm open to completely different approaches to achieve this; I'd just like it to be on one line (so it's easy to edit and redo).

The answer is to simply use backticks - but with a key proviso!  The below does not work for me, because of the quotes around hello:
:args `grep "hello" * -Rl`

But it works if I remove them or escape the quotes:
:args `grep hello * -Rl`
:args `grep \"hello\" * -Rl`

(this was buried in the comments after chaos' answer - I added them here to make them more visible, in case anyone else had this problem)

A: Well, this works for me:
:args `grep -Rl "hello" *`

Running vim 7.0.305.

A: Try the args command:
:ar[gs] `grep -Rl "hello" .`

If the backticks aren't working for you, are you use you're using a current version of vim?
:version


text:
Q: Trouble dealing with setState async function equivalent with hooks import React from "react";
import { UserContext } from "./../contexts";
import {
  removeStoredAuthData,
  storedAuthIsValid,
  storeNewAuthData,
} from "./../utils/auth";
import { getUserInfos } from "./../api/userAuthentication";

class UserProvider extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: "",
    };
  }

  render() {
    return (
      <UserContext.Provider
        value={{
          user: this.state.user,
          clearUserProfile: () => {
            const user = "";
            removeStoredAuthData();
            this.setState({ user });
          },
          saveUserProfile: (response) => {
            const user = response.data;
            storeNewAuthData(response);
            this.setState({ user });
          },
          populateUserProfile: (displayLoader, hideLoader) => {
            const storedToken = localStorage.getItem("appsante-token");
            const storedId = localStorage.getItem("appsante-id");
            if (storedAuthIsValid()) {
              displayLoader(() => {
                getUserInfos(storedId)
                  .then((response) => {
                    const user = { ...response.data, token: storedToken };
                    this.setState({ user }, hideLoader());
                  })
                  .catch((error) => console.log(error));
              });
            }
          },
        }}
      >
        {this.props.children}
      </UserContext.Provider>
    );
  }
}

export default UserProvider;

Hi everyone !
I trying to convert a React class component into a function component, with hooks.
But I can't find a way to deal properly with that line :
this.setState({ user }, hideLoader());

Unlike setState in class components, useState doesn't take a callback as second parameter, and I can't find how to achieve it with useEffect.
Could anyone help me ? Thanks !

A: Because the loader's presence can't be determined from the value in / change in user alone, you'll need another state variable, maybe one that contains the callback - perhaps call it hideLoader. After getUserInfos resolves, call setHideLoader with the callback, so that a useEffect hook with that function as a dependency can see the change and call the callback:
const [hideLoader, setHideLoader] = useState();
useEffect(() => {
  if (hideLoader) {
    hideLoader(); // or, if this is a HOF: hideLoader()()
    setHideLoader(); // callback done; remove callback from state
  }
}, [hideLoader]);
// ...
  populateUserProfile: (displayLoader, hideLoaderParam) => {
    // ...
    getUserInfos(storedId)
      .then((response) => {
        setUser({ ...response.data, token: storedToken }); // hook version
        setHideLoader(hideLoaderParam);
      })

and the rest of your code can be mostly the same - only call setHideLoader up above, inside getUserInfos.

A: I think you should do this :-
import React, { useState } from 'react';

const [user, setUser] = useState("");

populateUserProfile: async (displayLoader, hideLoader) => {
                const storedToken = localStorage.getItem("appsante-token");
                const storedId = localStorage.getItem("appsante-id");
                if (storedAuthIsValid()) {
                  displayLoader();
                    let  response = await getUserInfos(storedId)
                    const user = { ...response.data, token: storedToken };
                    setUser(user);
                    hideLoader();
                  };
                }


text:
Q: ASP.NET MVC default routh is wrong I got simple web application with 1 default routing:
routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Game", action = "Index", id = UrlParameter.Optional }
        );

My controller contains the following actions:
public class GameController : Controller
{
    public ActionResult Index()
    {
        // some actions
        return View();
    }

    [HttpPost]
    public ActionResult CreateGame(Game game, User user)
    {
        // some actions
            return View("Game");
    }

    [HttpPost]
    public ActionResult JoinGame(User user)
    {
        // some actions
        return View("Game");
    }
}

Also under Views/Game folder I got "Index" and "Game" views.
But when I start application from time to time (NOT ALWAYS!) it requests
http://localhost:55815/Game/Game

instead of
http://localhost:55815 or http://localhost:55815/Game/Index

A: Your application default route is working fine.
The debugger starts url http://localhost:55815/Game/Game  because the file Game.cshtml is currently opened in your Visual Studio.
The solution is on your VisualStudio project configuration.
Choose specific page with empty value instead of current/active Page.

A: Actually,

/Game/Game

and

/Game/Index

are both the same. When you check you default routing file you can see that your main controller is written with predefined controller and action. So the program automatically resolve this url according to that. Mostly try your web application not in visual studio debug but put it under IIS than if you need debugging, debug IIS instance.
Good luck


text:
Q: javax.net.ssl.SSLHandshakeException on spring boot application The spring boot app should send an email after the registration to the user.
When I test the registration with postman, I got this error message..

"message": "Mail server connection failed; nested exception is javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 1025;\n  nested exception is:\n\tjavax.net.ssl.SSLHandshakeException: Remote host terminated the handshake. Failed messages: javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 1025;\n  nested exception is:\n\tjavax.net.ssl.SSLHandshakeException: Remote host terminated the handshake"
**

As mail server I use mailDev in a docker container. The container terminal logs these messages:
MailDev webapp running at http://0.0.0.0:80
MailDev SMTP Server running at 0.0.0.0:25
The Logs sound fine, but despite this I have no access to the web app of the mail-server (I use a MacBook). Is there maybe a fault at the mail server?
The app is running with this properties..
server:
  error:
    include-message: always
    include-binding-errors: always
spring:
  datasource:
    password: password
    url: jdbc:postgresql://localhost:5432/postgres
    username: postgres
  jpa:
    hibernate:
      ddl-auto: create-drop
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect
        format_sql: true
    show-sql: true
  mail:
    host: localhost
    port: 1025
    username: hello
    password: hello
    properties:
      mail:
        smtp:
          auth: true
          socketFactory:
            class: javax.net.ssl.SSLSocketFactory
            fallback: false
            port: 1025
          ssl:
            enable: true

The project is public under my GitHub profile
https://github.com/farmerWhoCode/TrainingBooking
I find some hints here at stackoverflow, that point out wrong properties in my application.yml file. But nothing helps me to solve this problem.


text:
Q: Is there anyway to calculate mean of beta distribution with MATLAB? This is my code for calculate the mean:
syms a b x

f=1/(beta(a,b))*x^(a-1)*(1-x)^(b-1);

int(x*f,x,0,1)

Warning: Explicit integral could not be found.

ans =

int((x*x^(a - 1)*(1 - x)^(b - 1))/beta(a, b), x == 0..1)

How can I fix this?
This is my result for TryHArd's:
syms x a b
f=int(x^(a-1)*(1-x)^(b-1),x,0,1)

Warning: Explicit integral could not be found.
f =

piecewise([0 < real(a) and 0 < real(b), beta(a, b)], [real(a) <= 0 or real(b) <= 0, int(x^(a - 1)*(1 - x)^(b - 1), x == 0..1)])

My result did not show the same gamma(a)*gamma(b)/gamma(a+b) as TryHard did.

A: I assume by beta you mean

beta(z,w) = integral from 0 to 1 of t.^(z-1) .* (1-t).^(w-1) dt.

Then break down the problem:
>> int((x^(a-1))*((1-x)^(b-1)),x,0,1)

ans =

gamma(b)*gamma(a)/gamma(a+b)

The desired integral is equivalent to:
>> bint=int((x^(a-1))*((1-x)^(b-1)),x,0,1);
>> int( x*((x^(a-1))*((1-x)^(b-1)))/bint,x,0,1)

ans =

a/(a+b)

(This was computed with an earlier version of the Matlab SMT (on R14), but should serve as a guide.)

A: The mean of the Beta distritution is 1/(1+b/a). See for example here

A: Wolfram alpha is capable of it.
Computing the definite integral directly exceeds maximum standard computation time, but it can find the indefinite integral. Limiting that expression to x between 0 and 1, means simply equating x to 1. This results in this expression, the alternate form of which is the standard form of the mean of the beta distribution.
Wolfram Mathematica (& Alpha) is simply better at symbolic math than MuPad. I'd advise to use MATLAB only for what it rocks at: numerical math. Other than perhaps some fringe cases, I do not expect MuPad to ever come close to what has been achieved by Wolfram.

A: If you need the result for some specific parameters alpha and beta, you can use betastat. This function can be used also with vectors, like that:
A=[4 4 4];
B=[5 6 7];
[m,v]=betastat(A,B)

This will give you a 3-elements vector for both m (mean) and v (variance). For this example, m will be the means of beta(4,5), beta(4,6) and beta(4,7). (Note that "beta" here denotes the distribution, not the beta-function, like beta function on Matlab).
If you need a general (mathematical) solution, see Rody's answer. Wolfram is much appropriate for this.
EDIT: You can define f (in your code) by the function betapdf instead of the whole formula you wrote over there.


text:
Q: A repeated-measures LMM... Am I understanding this correctly? So I've been reading West et al's book on Linear Mixed Models as I'm trying to figure out how I should analyze my data, and I was wondering if I've correctly understood what I've ready so far. So, I have repeated measures on a response variable: for each subject, a measure under the control condition and under a "treatment." The subjects also differ in sex, which we predict to be an important factor in the response to treatment. Importantly, some subjects (not all) are measured multiple times, because they went through "treatment" multiple times. So, in those cases, I have a new control measure and treatment measure for each individual.
What I think I is a LMM with 3 fixed effects:  my response variable, sex, and treatment condition. In addition, I think I will need 1 random effect: subject identification (to correct for the non-independence of some of my data points because some subjects were included twice).
First of all, am I missing anything? The book lost me a bit when it started including all of these interactions in their models... I'm also working with very small sample sizes (because I work with endangered and long-lived animals), so I worry about trying to cram too many variables into the model. Second, do my data need to follow any particular distribution? Or do the residuals need to follow some particular distribution?
Thanks for taking the time to read...

A: First of all given you are using a standard LMM you definitely look to have normally distributed residuals. ie. $\epsilon \sim N(0, \sigma^2 I)$.
When you are using a LMM you are practically saying that you data have a distribution as : $y \sim  N( X\beta, \sigma^2 I + ZDZ^T)$. So in relation with what we wrote above : $y|u \sim N(  X\beta + Zu, \sigma^2 I)$;
I believe that your response variable is not a fixed effect. It is actually what you try to predict so it is not part of the $X$ model matrix. I would think that a simple interaction between treatment and sex (something like Treatment*Sex will be adequate for first try coupled with a "intercept-only" random effects structure (eg. (1|Subject)). As you importantly identify yourself, if your total number of samples isn't that great, just feeding in a big number of covariates is a bit "insecure". I would also contemplate not using an intercept when starting mostly because that "should" be taken care of by your interaction term but that's a bit of a personal taste thing. :) Good luck.


text:
Q: Reporting a user with suspiciously consistent upvotes Over on Magento SE I was made aware of a user with 3 or 4 upvotes on pretty much every answer. This looks & feels quite exceptional given that our fledgling community suffers from a lack of upvoting in general. Of course, "exceptional" != impossible so I'm hoping someone can help me think about this or get action taken "the right way".

A: The best bet would be to flag one of their answers using a custom "Other" moderator flag explaining your suspicion and asking that they investigate the situation.
A moderator will review the flag, user, etc and take any action if it is needed.
Hmm... I didn't realize you were a mod on Magento. There are tools at your disposal to review this and then take action.  The help center on Magento should have some details on how to proceed, but you should also pop into the moderator chat room and we can help if you have questions.


text:
Q: Access minus symbol of postscript font in textmode Do postscript fonts such as libertine (from the libertine-legacy package) or mathpazo have a minus sign that can be accessed when in text mode? What I am trying to do is substitute the normal dash with a minus symbol, following this answer from David Carlisle.
His solution works perfectly when using open type fonts as most of them have a minus character that can be easily accessed:
\def\yyy{%
  \bgroup\uccode`\~\expandafter`\string-%
  \uppercase{\egroup\edef~{\noexpand\text{\char"2212\relax}}}%
  \mathcode\expandafter`\string-"8000 }

However, my attempts to do something similar with pdfLaTeX and Libertine or Pagella have been futile. Using a symbol like hyphen (\textendash) works perfectly:
\def\yyy{%
  \bgroup\uccode`\~\expandafter`\string-%
  \uppercase{\egroup\edef~{\noexpand\text{\llap{\textendash}\relax}}}%
  \mathcode\expandafter`\string-"8000 }

But is not exactly what I want. How can I access the minus symbol of that font? Or, if that is not possible, is it possible to resize the hyphen to "fake" a minus symbol?
Edit: egreg provided the solution below. Embedded into my framework the code is:
\def\yyy{% Thanks to egreg
  \begingroup\uccode`~=`-
  \uppercase{\endgroup\def~}{\mathbin{\text{\llap{\textminus}}}}
  \mathcode`-="8000 }

A: The en dash is in position "15 in the T1 encoding:
\begingroup\uccode`~=`-
  \uppercase{\endgroup\def~}{\mathbin{\text{\char"15 }}}
\AtBeginDocument{\mathcode`-="8000 }

Alternatively, there's \textminus in the TS1 encoding:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{libertine}
\usepackage{textcomp}
\usepackage{amsmath}
\begingroup\uccode`~=`-
  \uppercase{\endgroup\def~}{\mathbin{\text{\textminus}}}
\AtBeginDocument{\mathcode`-="8000 }

\begin{document}
$-$
\end{document}


text:
Q: Doctest fails when normal output and exception mixed together? Does doctest support that both output and exception mixed together?
One example is:
>>> def foo():
...    print 'hello world!'
>>> foo()
hello world!
>>> def bar():
...     raise Exception()
>>> bar()
Traceback (most recent call last):
    ...
Exception

>>> def foo_bar():
...     foo()
...     bar()
>>> foo_bar()
hello world!
Traceback (most recent call last):
    ...
Exception

I expect all three cases should be successful, but only two of them does, see
$ python -m doctest -v /tmp/1.py
Trying:
    def foo():
       print 'hello world!'
Expecting nothing
ok
Trying:
    foo()
Expecting:
    hello world!
ok
Trying:
    def bar():
        raise Exception()
Expecting nothing
ok
Trying:
    bar()
Expecting:
    Traceback (most recent call last):
        ...
    Exception
ok
Trying:
    def foo_bar():
        foo()
        bar()
Expecting nothing
ok
Trying:
    foo_bar()
Expecting:
    hello world!
    Traceback (most recent call last):
        ...
    Exception
**********************************************************************
File "/tmp/1.py", line 16, in 1
Failed example:
    foo_bar()
Exception raised:
    Traceback (most recent call last):
      File "/usr/lib/python2.7/doctest.py", line 1315, in __run
        compileflags, 1) in test.globs
      File "<doctest 1[5]>", line 1, in <module>
        foo_bar()
      File "<doctest 1[4]>", line 3, in foo_bar
        bar()
      File "<doctest 1[2]>", line 2, in bar
        raise Exception()
    Exception
**********************************************************************
1 items had failures:
   1 of   6 in 1
6 tests in 1 items.
5 passed and 1 failed.
***Test Failed*** 1 failures.

A: The docs say you can't do that:

Examples containing both expected output and an exception are not supported. Trying to guess where one ends and the other begins is too error-prone, and that also makes for a confusing test.

A: Regular output and tracebacks cannot be mixed since they are just indistinguishable text. However you can wrap the block, catching the exception you expect:
>>> try:
...     foo_bar()
... except TheSpecificExceptionYouWant:
...     pass
... else:
...     raise AssertionError('Should have raised an exception')
hello world!


text:
Q: Statistical test of two groups of frequencies I have two groups of frequency data with different sample sizes and want to perform a statistical test on them. Given that the origin is count data is a non parametric test such as Mann–Whitney U test appropriate, or would a T-test or some other frequency specific test be more appropriate here?
Mann–Whitney U test result: statistic=161.0, pvalue=0.00045559069195569816
T-test result statistic=3.4450111759267736, pvalue=0.0008550201339166953

Group one:
       2.88736949e-05, 1.91629064e-04, 8.33259266e-05, 1.25364623e-03,
       5.49663735e-04, 7.36399464e-05, 5.30926467e-04, 1.15539006e-04,
       4.61161792e-04, 2.55944013e-04

Group two:
       1.09393232e-05, 1.59506593e-05, 0.00000000e+00, 3.39931153e-04,
       0.00000000e+00, 0.00000000e+00, 7.47160789e-06, 9.14335754e-04,
       6.37270854e-04, 4.38065997e-04, 4.46014156e-04, 4.33364272e-04,
       4.27734969e-04, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
       0.00000000e+00, 0.00000000e+00, 3.15975733e-06, 2.35208535e-04,
       2.16038714e-05, 1.51515152e-05, 0.00000000e+00, 0.00000000e+00,
       4.52923797e-05, 0.00000000e+00, 0.00000000e+00, 3.94096488e-04,
       1.62733510e-04, 5.32050736e-05, 1.66583845e-04, 1.59014260e-04,
       0.00000000e+00, 2.56678730e-04, 0.00000000e+00, 3.11371279e-05,
       1.75217269e-05, 9.45332757e-05, 2.69473987e-05, 4.04825815e-04,
       0.00000000e+00, 3.45638048e-05, 0.00000000e+00, 3.87837419e-06,
       0.00000000e+00, 4.67709347e-06, 2.42479972e-04, 3.46202847e-06,
       4.12178501e-04, 4.24117093e-04, 1.78833810e-04, 3.35415084e-04,
       0.00000000e+00, 3.27687776e-04, 0.00000000e+00, 0.00000000e+00,
       0.00000000e+00, 0.00000000e+00, 1.88196326e-05, 1.68599946e-05,
       7.08616780e-05, 0.00000000e+00, 1.45213755e-05, 1.87207111e-04,
       3.61039795e-04, 0.00000000e+00, 0.00000000e+00, 1.34105783e-05,
       0.00000000e+00, 5.01465823e-04, 9.99428898e-05, 2.88406076e-04,
       0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
       2.94117647e-04, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
       0.00000000e+00, 1.29346026e-05, 2.29624640e-04, 0.00000000e+00,
       0.00000000e+00, 0.00000000e+00

A: There is probably not one true way to approach this. You can certainly approach these data as numerical values that are left-censored and therefore highly non-normal. You can choose to test these with a rank sum / U test which will yield a significant $p$ value (I get a differnt result somewhere along the lines of .0003 but yours is even smaller - maybe you presented only part of the data).
By choosing the nonparametric test you will not have to discuss whether you should have used an arcsine transform or a logit transform and whether the numbers are high enough to do a t-test in absence of normality.


text:
Q: nth-of-type CSS selector hierarchy issues I want the background color of a div to alternative. Red, black, red, black... It works fine when the elements are in the same hierarchy level, but I can't get it working in this case:

Lorem ipsum dolor sit amet.

Adipisicing elit. A cumque!Lorem ipsum dolor sit amet.

And the CSS
.post-preview:nth-of-type(even) {
    background-color: red;
}

.post-preview:nth-of-type(odd) {
    background-color: black;
}

Any hints how to set up the selector properly? Thanks a lot!

A: http://jsfiddle.net/L6nwC/
You might want to run the nth-child on the container...
.post-preview-wrapper:nth-of-type(even) .post-preview{
    background-color: red;
}

.post-preview-wrapper:nth-of-type(odd) .post-preview {
    background-color: black;
    color: white;
}

A: nth-of-type
Live Demo
.post-preview-wrapper:nth-of-type(even) .post-preview{
    background-color: red;
}

.post-preview-wrapper:nth-of-type(odd) .post-preview{
    background-color: black;
}

nth-child also works
Live Demo
.post-preview-wrapper:nth-child(2n) .post-preview{ /* even*/
    background-color: red;
}

.post-preview-wrapper:nth-child(2n+1) .post-preview{ /* odd */
    background-color: black;
}

A: Fiddle Demo
.post-preview-wrapper:nth-of-type(even) {
    background-color: red;
}

.post-preview-wrapper:nth-of-type(odd) {
    background-color: black;
}


text:
Q: Group Policy is blocking exe files I teach programming in Visual Studio. We want to run it on a terminal server. The problem is that whenever we compile our programs, the Windows refuses to start the created exe file. (I didn't even know the ability to block all exe files exists. And it is not very funny when we do programming.) A message box is shown, saying that running exe files is blocked by group policy. It applies to both .NET and plain Win32 exe programs. The problem is that our IT administrators say they don't know why does this happen and how to turn the blocking off. Can anybody help?

A: First off, I hope your terminal server is a virtual machine. Before you continue, make sure you have a clean snapshot of the VM. One of your students will take advantage of the ability to run arbitrary applications and screw up your server. You should revert to the snapshot periodically, and always revert immediately before applying patches or installing or upgrading software. Then take a snapshot after that's done but before anyone can use the server. That way when some hoses your server, all you have to do is revert the snapshot.
There are a couple of ways to restrict programs from running.

*

*In group policy, there are two areas to look under Policies -> Windows Settings -> Security Settings: Application Control Policies and Software Restriction Policies.

*There is also the RestrictRun registry key.

*And finally, third-party applications can use the registry key Appinit_DLLs.

A: All exe files icluding calc.exe, notepad.exe and explorer.exe or just some exe files?
There are different approaches to this.
If you're trying to block a single executable that you're familiar with you can disable it from a GPO using the setting:
User Configuration/Administrative Templates/System/Don't run specified Windows applications
Another option is to specify only the applications you want to allow Using:
User Configuration/Administrative Templates/System/Run only specified Windows applications
This one would probably take a lot of work to populate for a system with many applications installed or for a corporate environment.
None of the two mentioned settings takes into account that a user can name their exe file what they want so renaming mydangerousapp.exe to explorer.exe would make it a perfectly legitimate executable.


text:
Q: Re-building Linux kernel without "clean" I'm building a custom kernel based off 4.11 (for Mintx64, if it matters). I've already compiled and installed it to prove that it works. Now I've made a few small changes to a couple of files (in the driver and net subsystems, this is why I need to compile a custom kernel in the first place!)
Now I want to build the modified kernel. However when I run
fakeroot make -j5 deb-pkg LOCALVERSION=myname KDEB_PKGVERSION=1

The build system appears to start by "clean"-ing a whole load of stuff, so I stopped it quickly. Unfortunately the computer I'm using is not blessed with a good CPU and takes many hours to build from scratch. Therefore I'd rather avoid doing it again if possible!
Is it possible to make just an incremental build without everything be "clean"d or is this a requirement of the kernel build system?
The output I got was:
CHK      include/config/kernel.release
make clean
CLEAN .
CLEAN arch/x86/lib
...

A: You could try producing those deb packages with a different tool, make-kpkg that is installed by apt-get install kernel-package. Then for example
make-kpkg --rootcmd=fakeroot --initrd --uc --us -j2 kernel_image kernel_headers

This command should not do a make clean each time.

A: The make clean is only for the deb-pkg target. Take a look at scripts/package/Makefile:
deb-pkg: FORCE
        $(MAKE) clean
        $(call cmd,src_tar,$(KDEB_SOURCENAME))
        $(MAKE) KBUILD_SRC=
        +$(call cmd,builddeb)

bindeb-pkg: FORCE
        $(MAKE) KBUILD_SRC=
        +$(call cmd,builddeb)

If you build the bindeb-pkg instead, it won't do a clean. You probably don't need the source packages anyway.
I suspect it does a clean because it doesn't want to tar up build artifacts in the source tarball.

A: I fixed this by going into the makefile for the deb-pkg command and removing "make clean" from the script. This did not seem to cause any ill effects with the build and I have been running the custom kernel for a week or two now without problems. YMMV!


text:
Q: UWP "compound" binding (binding Data.Name instead of Name) I have a simple page with text block and a button. I want to change the text when I press the button. But using a text from a Data.Name property of the Page.
I know I can have this simpler (having just Name instead of Data.Name), but I need Data.Name, don't ask why.
For this I have a class DataType which has the Name property and object named Data of that class. I want to have Data inside this Page, and bind the text to the Data.Name property.
When I click on the button, nothing happens, the question is how canI make this work?
XAML:
<Page
    x:Class="App1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
        </Grid.RowDefinitions>

        <TextBlock Grid.Row="0" Text="{Binding Data.Name, Mode=OneWay}"/>
        <Button Grid.Row="1" Content="Change" Click="Button_Click"/>
    </Grid>
</Page>

Class DataType
public ref class DataType: public INotifyPropertyChanged {
public:
    property String^ Name
    {
        String^ get() {
            return m_Name;
        }
        void set(String^ value) {
            m_Name = value;
            OnPropertyChanged("Name");
        }
    }

    virtual event PropertyChangedEventHandler^ PropertyChanged;

private:
    void OnPropertyChanged(Platform::String^ propertyName)
    {
        PropertyChanged(this, ref new PropertyChangedEventArgs(propertyName));
    }
    String^ m_Name;
};

Class MainPage
public ref class MainPage sealed: public INotifyPropertyChanged
{
public:
    MainPage();

    property DataType^ Data {
        DataType^ get() {
            return m_Data;
        }
        void set(DataType^ value) {
            m_Data = value;
            OnPropertyChanged("Data");
        }
    }

    virtual event PropertyChangedEventHandler^ PropertyChanged;

private:
    void OnPropertyChanged(Platform::String^ propertyName)
    {
        PropertyChanged(this, ref new PropertyChangedEventArgs(propertyName));
    }
    void Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    {
        Data->Name = rand() & 1 ? "Test1" : "Test2";
        OnPropertyChanged("Data");
    }

    DataType^ m_Data;
};

A: In UWP, there are x:Bind and Binding markup extension, they have some differences when you use them. You can learn the details from the document of above two links.
Now we will discuss the reason that caused your above issue.
In your xaml, you use the Binding markup extension to bind the property path, since Binding uses the DataContext as a default source. Simplely to say, when you use Binding property path, you bind the DataContext.Property path, you just need use the Bind source object's property but not need to specify the Source data object on the xaml. As the introduction of Traversing an object graph:
"{Binding Path=Customer.Address.StreetAddress1}"

Here's how this path is evaluated:

*

*The data context object (or a Source specified by the same Binding) is searched for a property named "Customer".

*The object that is the value of the "Customer" property is searched for a property named "Address".

*The object that is the value of the "Address" property is searched for a property named "StreetAddress1".
See the Property-path syntax for the details.
So your code will work just binding the Name property and set the DataContext. (Note that: your MainPage class don't need to implement the INotifyPropertyChanged interface.)
<TextBlock Grid.Row="0" Text="{Binding Name, Mode=OneWay}"/

And
this->DataContext = Data;

Also note: If you're using Visual C++ component extensions (C++/CX) then, because we'll be using {Binding}, you'll need to add the BindableAttribute attribute to the DataType class.
[Windows::UI::Xaml::Data::Bindable]
public ref class DataType sealed : public INotifyPropertyChanged {
...
}

On the other hand, you can use the x:Bind instead of the Binding, since x:Bind don't use the DataContext as a default source—instead, it uses the page or user control itself. So it will look in the code-behind of your page or user control for properties, fields, and methods. To expose your view model to {x:Bind}, you will typically want to add new fields or properties to the code behind for your page or user control. For example: in a page, Text="{x:Bind Employee.FirstName}" will look for an Employee member on the page and then a FirstName member on the object returned by Employee.

A: The issue is that DataType properties isn't visible from XAML, because "DataType.h" isn't included in "pch.h"
Once I included it in precompiled header, everything worked.
BTW, looks like Binding is not checking for type visibility from XAML or whatever, but x:Bind does. Using x:Bind, the compiler complains about unknown Data.Name, and that allowed me to figure out the problem.


text:
Q: Spinner not showing selected item or default item but dropdown list works android spinner is empty by default or when items selected. I tried using the default layout for spinner but still empty. I have checked every question on this website but none helped.
Here is the code:
spinner view on activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:background="@color/background"
    android:orientation="vertical">
   <TextView
        android:id="@+id/showTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Title"
        android:textSize="20sp"
        android:textAlignment="center"
        android:textColor="@color/textColor"
        android:fontFamily="monospace"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
    />
    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:spinnerMode="dropdown"

        >

        </Spinner>

</LinearLayout>

Activity:
public class ShowActivity extends AppCompatActivity {

private List<String> list;
Spinner dropdown;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show);

    TextView titleView = findViewById(R.id.showTitle);
    String title = getIntent().getExtras().getString("title");
    titleView.setText(title);

    list = new ArrayList<>();

    dropdown = findViewById(R.id.spinner);

    FirebaseFirestore.getInstance().collection(title).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    list.add(document.getId());
                }
                Log.d("Success ", list.toString());
            } else {
                Log.d("Failed ", "Error getting documents: ", task.getException());
            }
        }
    });

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(ShowActivity.this, R.layout.spinner_items, list);

    adapter.setDropDownViewResource(R.layout.spinner_items);

    dropdown.setAdapter(adapter);

    adapter.notifyDataSetChanged();

}

}
spinner_items.xml:
<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:id="@+id/spinnerTV"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:textSize="20sp"
    android:text="Text"
    android:gravity="start"
    android:padding="10dp"
    android:textColor="@color/textColor"
    android:layout_marginBottom="3dp"
    android:layout_margin="8dp"
/>

thank you in advance.
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

A: FirebaseFirestore.getInstance().collection(title).get().addOnCompleteListener(...) is an asynchronous call. Your code will continue to execute here:
 ArrayAdapter<String> adapter = new ArrayAdapter<String>(ShowActivity.this, R.layout.spinner_items, list);

    adapter.setDropDownViewResource(R.layout.spinner_items);

    dropdown.setAdapter(adapter);

    adapter.notifyDataSetChanged();

At this time the list is still empty. You need to move this block inside of the OnCompleteListener.

A: After  dropdown.setAdapter(adapter); you have to set up item select/clicked listener, try this:
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//.. do stuff here
   }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
 // do default when nothing is selected
            }
        });
dropdown.setSelection(0) // this makes default selection for dropdown item....

Hope I could help you, best regards,
Csongi


text:
Q: no route between my location an destination i'm using MapWithRoutes code from here [MapWithRoutes][1]
[1]: https://github.com/kadirpekel/MapWithRoutes . it gives me correct location and destination but cannot calculate routes between them i think the
     problem in this  code:
-(NSArray*) calculateRoutesFrom:(CLLocationCoordinate2D) f to:
(CLLocationCoordinate2D) t {
NSString* saddr = [NSString stringWithFormat:@"%f,%f", f.latitude,
f.longitude];
NSString* daddr = [NSString stringWithFormat:@"%f,%f", t.latitude,
t.longitude];

NSString* apiUrlStr = [NSString
stringWithFormat:@"http://maps.google.com/maps?
output=dragdir&saddr=%@&daddr=%@", saddr, daddr];
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
NSLog(@"api url: %@", apiUrl);
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl];
NSString* encodedPoints = [apiResponse stringByMatching:@"points:\\\"
([^\\\"]*)\\\"" capture:1L];

return [self decodePolyLine:[encodedPoints mutableCopy]];
 }

or may be in viewing the route:
-(NSArray*) calculateRoutesFrom:(CLLocationCoordinate2D) f to:
(CLLocationCoordinate2D) t {
NSString* saddr = [NSString stringWithFormat:@"%f,%f", f.latitude,
f.longitude];
NSString* daddr = [NSString stringWithFormat:@"%f,%f", t.latitude,
t.longitude];

NSString* apiUrlStr = [NSString
stringWithFormat:@"http://maps.google.com/maps?
output=dragdir&saddr=%@&daddr=%@", saddr, daddr];
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
NSLog(@"api url: %@", apiUrl);
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl];
NSString* encodedPoints = [apiResponse stringByMatching:@"points:\\\"
([^\\\"]*)\\\"" capture:1L];

return [self decodePolyLine:[encodedPoints mutableCopy]];
}

whats wrong with codes return no routes?

A: Draw Polyline based on route in Mkmapview
check this answer.


text:
Q: Why double slashes front of JSON String I have a JSON string from google, which i can not use it because of the double slashes in front of the JSON string, it returns JSON exception.
How can i escape them before parse?

https://www.google.com/finance/info?q=asels
// [ { "id": "530630671033488" ,"t" : "ASELS" ,"e" : "IST" ,"l" :
  "13.72" ,"l_fix" : "13.72" ,"l_cur" : "TRY13.72" ,"s": "0"
  ,"ltt":"6:10PM GMT+3" ,"lt" : "Jan 20, 6:10PM GMT+3" ,"lt_dts" :
  "2017-01-20T18:10:00Z" ,"c" : "+0.04" ,"c_fix" : "0.04" ,"cp" : "0.29"
  ,"cp_fix" : "0.29" ,"ccol" : "chg" ,"pcls_fix" : "13.68" } ]

A: You need to remove the two double slashes in beginning, then you have a regular JSON String that you can parse.
You can do it like this:
String yourJsonStringFromGoogle = ...
fixedJsonString = yourJsonStringFromGoogle.substring(2);

Here, substring(n) removes n letters from the beginning of the string.


text:
Q: Why would this design (Si8261BCC-IS) blow the chip? I created a design for a simple MOSFET driver using the Si8261BCC-IS. The schematic and Gerber files are available here. The schematic is also shown below. When I connect the input control signal of 3.3V at J1, the chip blows up. There is a proper flash of flame and then blue smoke. The supply voltage on the MOSFET side is 24V. Why would this be happening?

A: I think the troublesome part of the circuit is this:

simulate this circuit – Schematic created using CircuitLab
When the PMOS inside the Si8261 switches on, it connects 24 V across R2 (4.7 ohm) and the 12 V zener diode. So in theory, that means there would be about 12 V across R2 so 12 V / 4.7 ohm = 2.55 A wants to flow. That's much more than that poor PMOS can handle. Check the datasheet to see what it can actually handle.
Even if the PMOS could handle the current, R2 and the zener diode would blow up eventually due to excess power dissipation (the zener and R2 each get: 12 V * 2.55 A = 30 W OUCH!!! the magic smoke will escape in a nano second)
I would give R2 a significantly higher value in the order of 1 kohm or more. Then calculate the maximum current that can flow through R2 and make sure the power dissipation ratings of R2 and D1 are not exceeded. Of course the current must be within the range that the Si8261's internal PMOS can handle.

A: The chip tries to set the output high to 24V. Since the FET gate can't handle 24V, there is a 12V zener to clamp voltage and the 4.7R resistor that limits the current to about 2.5A. The chip is not meant to drive out that much DC current, and it heats up and gets damaged.