text:
Q: Create entity from 3 different mono I am new in reactive programming. I saw that two monos could be zipped to generate a result:
Mono<Info> info = Mono.just(id).map(this::getInfo).subscribeOn(Schedulers.parallel());

Mono<List<Detail>> detail= Mono.just(petitionRequest).map(this.service::getDetails)
                    .subscribeOn(Schedulers.parallel());

Flux<Generated> flux = Flux.zip(detail, info, (p, c) -> {
            Generated o = Generated.builder().info(c).detail(p).build();
            return o;
        });

As I have understood this paralelizes the two call and generate the object Generated when I call to flux.blockFirst()
How can I merge another mono to the existing two ones to generate a result? Flux.zip only accepts two monos.
Thanks in advance.

A: First of all, since you are zipping Monos, it would make sense to use zip operator from Mono instead of Flux.
It has multiple overloaded versions which can accept any number of Monos.
Also, if this.service::getDetails and this::getInfo are blocking IO operations (HTTP request, database call, etc.) then you should use elastic Scheduler instead of the parallel one, the latter is intended for CPU intensive operations.
Sample code:
    Mono<Info> info = Mono.just(id)
                          .map(this::getInfo)
                          .subscribeOn(Schedulers.elastic());

    Mono<List<Detail>> detail= Mono.just(petitionRequest)
                                   .map(this.service::getDetails)
                                   .subscribeOn(Schedulers.elastic());

    Mono<Description> description = Mono.just(id)
                                        .map(this::callService)
                                        .subscribe(Schedulers.elastic());

    Mono.zip(info, detail, description)
        .map(this::map);

    private Generated map(Tuple3<Info, List<Detail>, Description> tuple3)
    {
        Info info = tuple3.getT1();
        List<Detail> details = tuple3.getT2();
        Description description = tuple3.getT3();

        // build output here
    }


text:
Q: Is this query secure from sql injection? Is this query secure from sql injection ?
And a must in every function to write $connection->close();?
function insert_mytable() {
    global $connection;

    $text = 'bla bla';
    $hashtag = 'bla bla';

    // Prepare the statement
    $stmt = $connection->prepare("INSERT INTO my_table (text, hashtag) VALUES (?, ?)");
    $stmt->bind_param('ss', $text, $hashtag);

    // Execute the statement
    $stmt->execute();

    // Close the statement
    $stmt->close();
    $connection->close();
}

A: To answer your first question: Yes*
*Since you are using prepared statements, your code is safe from SQL injection attacks in most cases. It is likely the case that, for your purpose, the above code is all the defense you require against SQL injection; however, if you wish to know in what cases prepared statements are not sufficient, you should look at the first answer to this question as Joel Coehoorn explains it far better than I.
As far as your second question, as ac.freelancer and Charlotte Dunois have already pointed out, the connection does not need to be closed, especially not if you intend to use the connection again.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Elasticsearch wait for index status Cluster health API has parameter wait_for_status that (according to documentation) waits for specified cluster status. However, I would like to wait for specific index to reach some status.
If I use cluster health request with level=indices and index=myindex will the wait still operate on cluster level? I guess polling the status and continuing after status is reached would have the same effect but is there better way to do this?

A: It is possible to use the health api for specific indices, as well:
GET /_cluster/health/index_name?wait_for_status=green&timeout=10s


text:
Q: dice rolling in C# console application giving incorrect totals I am writing dice roller program in C# console. I am giving two input

*

*Enter the size of the dice and

*Enter how times you want to play.

Suppose dice size is 6 and 10 times i have played.
Output is coming:
1 was rolled  2 times
2 was rolled  7 times
3 was rolled  8 times
4 was rolled  7 times
5 was rolled  4 times
6 was rolled  5 times

Total: 33 (its not fixed for every execution this no will be changed)
But my requirement was this total always should be number of playing times. Here I am playing 10 times so the total should be 10 not 33. It should happen for every new numbers... If I play 100 times sum or total should be 100 only not any other number. rest all will be remain same, in my programing not getting the expected sum. Please somebody modify it. Here is my code:
Dice.cs:
public class Dice
{
    Int32 _DiceSize;
    public  Int32 _NoOfDice;
    public Dice(Int32 dicesize)
    {
        this._DiceSize = dicesize;
    }
    public string Roll()
    {
        if (_DiceSize<= 0)
        {
            throw new ApplicationException("Dice Size cant be less than 0 or 0");
        }
        if (_NoOfDice <= 0)
        {
            throw new ApplicationException("No of dice cant be less than 0 or 0");
        }
        Random rnd = new Random();
        Int32[] roll = new Int32[_DiceSize];
        for (Int32 i = 0; i < _DiceSize; i++)
        {
            roll[i] = rnd.Next(1,_NoOfDice);
        }
        StringBuilder result = new StringBuilder();
        Int32 Total = 0;
        Console.WriteLine("Rolling.......");
        for (Int32 i = 0; i < roll.Length; i++)
        {
            Total += roll[i];
            result.AppendFormat("{0}:\t was rolled\t{1}\t times\n", i + 1, roll[i]);
        }
        result.AppendFormat("\t\t\t......\n");
        result.AppendFormat("TOTAL: {0}", Total);
        return result.ToString();
    }
}
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter no of dice size");
        int dicesize = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("How many times want to play");
        int noofplay=Convert.ToInt32(Console.ReadLine());
        Dice obj = new Dice(dicesize);
        obj._NoOfDice = noofplay;
        obj.Roll();
        Console.WriteLine(obj.Roll());
        Console.WriteLine("Press enter to exit");
        Console.ReadKey();
    }
}

A: It looks to me like you're getting the math backwards... shouldn't it be:
// to capture just the counts
int[] roll = new int[_DiceSize];
for (int i = 0; i < _NoOfDice; i++)
{
    roll[rnd.Next(roll.Length)]++;
}

Or if you want the actual rolls:
// to capture individual rolls
int[] roll = new int[_NoOfDice];
for (int i = 0; i < _NoOfDice; i++)
{
    roll[i] = rnd.Next(_DiceSize) + 1; // note upper bound is exclusive, so +1
}

A: You are creating a new Random instance on each iteration. This is not a good thing as it will affect the uniform distribution of results. Keep the Random instance in a field instead of creating a new one every time.
public class Dice {
    private Random rnd = new Random();

    // ... don't create a new random in `Roll` method. Use `rnd` directly.
}

A: First of all, the following for-loop is wrong:
for (Int32 i = 0; i < _DiceSize; i++)
{
   roll[i] = rnd.Next(1,_NoOfDice);
}

Obviously you switched _DiceSize and _NoOfDice. The correct loop would look like
for (Int32 i = 0; i < _NoOfDice; i++)
{
   roll[i] = rnd.Next(1,_DiceSize);
}

Because of that, the line
Int32[] roll = new Int32[_DiceSize];

has to be changed to
Int32[] roll = new Int32[_NoOfDice];

Maybe you should think about renaming these variables, so it's more clearly, which means what.
If you modify your code that way, you will mention that your analisys won't work that way you implemented it. Actually, what you are showing is the result of each throw, which is not what you want, if I understood you right.
UPDATE:
Sorry, I misunderstood you. You do want to show the result for every roll. So, why don't you just move the StringBuilder.AppendFormat to your "rolling-for-loop"?
UPDATE #2:
For me, the following Die-class works exactly the way you want it:
public class Die
{
    private int maxValue;
    private int numberOfRolls;
    private Random random;

    public Die(int maxValue, int numberOfRolls)
    {
        this.maxValue = maxValue;
        this.numberOfRolls = numberOfRolls;
        this.random = new Random();
    }

    public string Roll()
    {
        StringBuilder resultString = new StringBuilder();

        for (int i = 0; i < this.numberOfRolls; i++)
        {
            resultString.AppendFormat("Roll #{0} - Result: {1}" + Environment.NewLine, i + 1, this.random.Next(1, maxValue + 1));
        }

        return resultString.ToString();
    }
}

Hope I could help you.

A: This is the full code you have to use, according to Mehrdad and Marc Gravell.
Have fun.
  public class Dice
  {
    private Random rnd = new Random();

    Int32 _DiceSize;
    public Int32 _NoOfDice;
    public Dice(Int32 dicesize)
    {
      if (dicesize <= 0)
      {
        throw new ApplicationException("Dice Size cant be less than 0 or 0");
      }

      this._DiceSize = dicesize;
    }
    public string Roll()
    {

      if (_NoOfDice <= 0)
      {
        throw new ApplicationException("No of dice cant be less than 0 or 0");
      }
      // to capture just the counts
      int[] roll = new int[_DiceSize];
      for (int i = 0; i < _NoOfDice; i++)
      {
        roll[rnd.Next(roll.Length)]++;
      }
      StringBuilder result = new StringBuilder();
      Int32 Total = 0;
      Console.WriteLine("Rolling.......");
      for (Int32 i = 0; i < roll.Length; i++)
      {
        Total += roll[i];
        result.AppendFormat("{0}:\t was rolled\t{1}\t times\n", i + 1, roll[i]);
      }
      result.AppendFormat("\t\t\t......\n");
      result.AppendFormat("TOTAL: {0}", Total);
      return result.ToString();
    }
  }
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Enter no of dice size");
      int dicesize = Convert.ToInt32(Console.ReadLine());
      Console.WriteLine("How many times want to play");
      int noofplay = Convert.ToInt32(Console.ReadLine());
      Dice obj = new Dice(dicesize);
      obj._NoOfDice = noofplay;
      Console.WriteLine(obj.Roll());
      Console.WriteLine("Press enter to exit");
      Console.ReadKey();
    }
  }


text:
Q: Django IntegrityError - NOT NULL constraint failed: learning_logs_topic.owner_id The Problem
Hi, I'm making a project called "learning_log", where you can make new topics and add entries associated with that specific topic. I have a problem; when I try to add a new topic, an IntegrityError pops up on the screen. It keeps highlighting the code: form.save() in my views.py, after I set up a User authentication and registration system.
This is the traceback I get:
    Exception Type: IntegrityError at /new_topic/
Exception Value: NOT NULL constraint failed: learning_logs_topic.owner_id

The Code
My views.py looks like this:
from django.shortcuts import render
from django.http import HttpResponseRedirect, Http404
from django.urls import reverse
from django.contrib.auth.decorators import login_required

from .models import Topic, Entry
from .forms import TopicForm, EntryForm

def index(request):
    """The Home Page for Learning Log."""
    return render(request, 'learning_logs/index.html')

@login_required
def topics(request):
    """Show all topics."""
    topics = Topic.objects.filter(owner=request.user).order_by('date_added')
    context = {'topics': topics}
    return render(request, 'learning_logs/topics.html', context)

@login_required
def topic(request, topic_id):
    """Show a single topic and all its entries."""
    topic = Topic.objects.get(id=topic_id)
    # Make sure the Topic belongs to the current user.
    if topic.owner != request.user:
        raise Http404

    entries = topic.entry_set.order_by('-date_added')
    context = {'topic': topic, 'entries': entries}
    return render(request, 'learning_logs/topic.html', context)

@login_required
def new_topic(request):
    """Add a new topic."""
    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = TopicForm()
    else:
        # POST data submitted; process data.
        form = TopicForm(data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('learning_logs:topics'))

    context = {'form': form}
    return render(request, 'learning_logs/new_topic.html', context)

@login_required
def new_entry(request, topic_id):
    """Add a new entry for the particular topic."""
    topic = Topic.objects.get(id=topic_id)

    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = EntryForm()
    else:
        # POST data submitted; process data.
        form = EntryForm(data=request.POST)
        if form.is_valid():
            new_entry = form.save(commit=False)
            new_entry.topic = topic
            new_entry.save()
            return HttpResponseRedirect(reverse('learning_logs:topic',
                                                args=[topic_id]))

    context = {'topic': topic, 'form': form}
    return render(request, 'learning_logs/new_entry.html', context)

@login_required
def edit_entry(request, entry_id):
    """Edit an existing entry."""
    entry = Entry.objects.get(id=entry_id)
    topic = entry.topic
    if topic.owner != request.user:
        raise Http404

    if request.method != 'POST':
        # Initial request; pre-fill form with the current entry.
        form = EntryForm(instance=entry)
    else:
        # POST data submitted; process data.
        form = EntryForm(instance=entry, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('learning_logs:topic',
                                                args=[topic.id]))

    context = {'entry': entry, 'topic': topic, 'form': form}
    return render(request, 'learning_logs/edit_entry.html', context)

My forms.py looks like this:
from django import forms

from .models import Topic, Entry

class TopicForm(forms.ModelForm):
    class Meta:
        model = Topic
        fields = ['text']
        labels = {'text': ''}

class EntryForm(forms.ModelForm):
    class Meta:
        model = Entry
        fields = ['text']
        labels = {'text': ''}
        widgets = {'text': forms.Textarea(attrs={'cols': 80})}

my models.py looks like this:
from django.db import models
from django.contrib.auth.models import User

class Topic(models.Model):
    """A topic the user is learning about."""
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        """Return a string representation of the model."""
        return self.text

class Entry(models.Model):
    """Something specific learned about a topic."""
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'entries'

    def __str__(self):
        """Return a string representation of the model."""
        # Add an ellipsis ONLY if the entry,
        # is more than 50 characters long.
        if self.text > self.text[:50]:
            return self.text[:50] + "..."
        elif self.text <= self.text[:50]:
            return self.text[:50]

Any help is appreciated. Thanks in advance!

A: Here's my answer to the problem, that I had.
Django returns an IntegrityError because you haven't associated the new topic, with any particular user. It's saying that you can't create a new topic without specifying a value for the topic's owner field.
There's a straightforward fix for this problem, because you have access to the current user that's logged in through the request object. To fix the problem, I simply save the new_topic to a variable, and associates it with the current user logged in, and save the changes to the database.
update for new_topic() in views.py:
@login_required
def new_topic(request):
    """Add a new topic."""
    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = TopicForm()
    else:
        # POST data submitted; process data.
        form = TopicForm(data=request.POST)
        if form.is_valid():
            new_topic = form.save(commit=False) # Save topic in a variable.
            new_topic.owner = request.user # Set topics owner attribute to current user.
            new_topic.save() # Save the changes to the database.
            return HttpResponseRedirect(reverse('learning_logs:topics'))

A: I had this problem too, but a bit further they have the answer in the book:
Associating New Topics with the Current UserCurrently, our page for adding new topics is broken, because it doesn't associate new topics with any particular user. If you try adding a new topic, you'll see the error message IntegrityError along with learning_logs_topic .user_id may not be NULL. Django's saying you can't create a new topic without specifying a value for the topic's owner field.There's a straightforward fix for this problem, because we have access to the current user through the request object. Add the following code, which associates the new topic with the current user:
views.py
@login_required
def new_topic(request):
    """Add a new topic."""
    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = TopicForm()
    else:
        # POST data submitted; process data.
        form = TopicForm(request.POST)
        if form.is_valid():
            new_topic = form.save(commit=False)
            new_topic.owner = request.user
            new_topic.save()
            return HttpResponseRedirect(reverse('learning_logs:topics'))

    context = {'form': form}
    return render(request, 'learning_logs/new_topic.html', context)

A: And for Django 2.2:
@login_required
def new_topic(request):
    """Add a new topic."""
    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = TopicForm()
    else:
         # POST data submitted; process data.
        form = TopicForm(data=request.POST)
        if form.is_valid():
            new_topic = form.save(commit=False)
            new_topic.owner = request.user
            new_topic.save()
            return redirect('learning_logs:topics')

    # Return an empty or invalid form.
    context = {'form': form}
    return render(request, 'learning_logs/new_topic.html', context)


text:
Q: Log QUERIES not using INDEX - MySQL I'm using MySQL Server version: 5.5.8-log MySQL Community Server (GPL)
I want to log queries which are not using INDEX and is slow too !
I'm copying here my my.ini settings.
[mysqld]
port=3306
log = "E:/wamp/logs/genquery.log"
log_slow_queries
long_query_time = 1
slow_query_log = 1
slow_query_log_file = "E:/wamp/logs/slowquery.log"
what change i need to do ?

A: Maybe useful for Linux user. (Testet: Ubuntu 16.04)
Get root in terminal and edit mysql configuration
su
vim /etc/mysql/conf.d/mysql.cnf

[mysqld]
slow_query_log=1
slow_query_log_file=/var/log/mysql/slow-query.log
long_query_time=1
log_queries_not_using_indexes=1

Add log file and restart mysql server
touch /var/log/mysql/slow-query.log
chown mysql:adm /var/log/mysql/slow-query.log
chmod 640 slow-query.log
service mysql restart

Test slow logging with SQL queries
/* Activate query log - Maybe useful to show errors (not necessary) */
SET GLOBAL SLOW_QUERY_LOG=ON;

/* Check if slow query log is working */
SELECT SLEEP(2);

A: log_queries_not_using_indexes
Command-Line Format --log-queries-not-using-indexes
Option-File Format  log-queries-not-using-indexes
Option Sets Variable    Yes, log_queries_not_using_indexes
Variable Name   log_queries_not_using_indexes
Variable Scope  Global
Dynamic Variable    Yes
    Permitted Values
Type    boolean

Whether queries that do not use indexes are logged to the slow query log. See Section 5.2.4,

A: log_queries_not_using_indexes =1 //(or Yes) (From mysql)

A: In addition to a1ex07's answer you can use the shell command mk-query-digest to output a report of your running queries without using the log.
See the full methodology: http://www.xaprb.com/blog/2009/08/18/how-to-find-un-indexed-queries-in-mysql-without-using-the-log/
As mentioned in the article it is also possible to group the queries by tables doing --group-by tables --report-format profile
Useful to fast detect unindexed queries.


text:
Q: GMM regression and instruments count with xtabond2 I have to perform a difference GMM regression on my panel data. It's not important that it works, but if it does not I need robust motivation for why not.
My panel data is divided in two bigger groups, say A and B. Group A is the one I'm interested in, but I can also use group B in order to have more observations.
I'll report the analysis for group A here.
Group A has the following structure:
Time range: 2000 - 2017
Countries: 46
Total Observation: 855
I have run the following command:
xtabond2 y L(1/2).y L(1/5).x1 L(1/5).x2 x3 x4 x5 i.year x6 x7 , gmm(y, laglimits(3 17)) level(95) robust nolevel
See below for the output. My question is about the interpretation of the test results.

*

*Number of instruments = 114, where does this number come from? I have counted 17-3 = 14 instruments using gmm(y, laglimits(3 17)).

*My interpretation of the Sargan and Hansen test to be so extremely different is that I have too many instruments. Is this correct? What would be a correct amount of instruments for this panel data frame?

*Following my guess in "Second" I have collapsed the instruments, with the result of not having enough of them for all the independent variables. Reducing the variables (using only L(1/2).y L(1/5).x1 L(1/5).x2 x3 x4 x5), I get Sargan and Hansen test both 0. I interpret this result as not enough instruments for the GMM to work (see also that the confidence intervals are huge!). Is this correct?

Thank you very much in advance for the help!
Best,
Al
Results without collapse:
    Warning: Number of instruments may be large relative to number of observations.
    Warning: Two-step estimated covariance matrix of moments is singular.
    Using a generalized inverse to calculate robust weighting matrix for Hansen test.
    Difference-in-Sargan/Hansen statistics may be negative.

    Dynamic panel-data estimation, one-step difference GMM

------------------------------------------------------------------------------
    Group variable: rec_num Number of obs = 421
    Time variable : year Number of groups = 38
    Number of instruments = 114 Obs per group: min = 1
    Wald chi2(0) = . avg = 11.08
    Prob > chi2 = . max = 12
    ----------------------------------------------------------------------------------------
    | Robust
    y | Coef. Std. Err. z P>|z| [95% Conf. Interval]
    ---------------------------------------------------------------------------------------
    y |
    L1. | 1.036468 .1018369 10.18 0.000 .8368714 1.236065
    L2. | -.0963504 .0962006 -1.00 0.317 -.2849002 .0921994
    |
    x1 |
    L1. | .089542 .0441289 2.03 0.042 .003051 .176033
    L2. | .0393409 .0382197 1.03 0.303 -.0355683 .1142501
    L3. | .0478129 .0426604 1.12 0.262 -.0358 .1314258
    L4. | .0198056 .039333 0.50 0.615 -.0572856 .0968968
    L5. | .0234038 .0162282 1.44 0.149 -.0084029 .0552104
    |
    x2 |
    L1. | .2041297 .4241463 0.48 0.630 -.6271818 1.035441
    L2. | -1.406561 .9287444 -1.51 0.130 -3.226867 .4137444
    L3. | 1.443707 1.04289 1.38 0.166 -.6003206 3.487735
    L4. | -.8051038 1.117525 -0.72 0.471 -2.995412 1.385205
    L5. | .1804152 .6355273 0.28 0.777 -1.065195 1.426026
    |
    x3 | -.0055827 .0121747 -0.46 0.647 -.0294446 .0182793
    x4 | -.8350265 .5592689 -1.49 0.135 -1.931173 .2611204
    x5 | -.0019361 .0019381 -1.00 0.318 -.0057347 .0018624
    |
    year |
    2005 | .2457214 .9466613 0.26 0.795 -1.609701 2.101143
    2006 | .1571051 .7962133 0.20 0.844 -1.403444 1.717655
    2007 | .2607094 .7426875 0.35 0.726 -1.194931 1.71635
    2008 | .0978737 .6215058 0.16 0.875 -1.120255 1.316003
    2009 | .0229705 .5160136 0.04 0.964 -.9883975 1.034338
    2010 | -.0131881 .4455538 -0.03 0.976 -.8864576 .8600813
    2011 | -.0884742 .3828411 -0.23 0.817 -.838829 .6618805
    2012 | -.1563695 .3273156 -0.48 0.633 -.7978962 .4851573
    2013 | -.1322291 .2503104 -0.53 0.597 -.6228286 .3583703
    2014 | -.0865552 .1865422 -0.46 0.643 -.4521712 .2790608
    2015 | -.0423805 .1207112 -0.35 0.726 -.2789701 .1942091
    2016 | -.019548 .0672854 -0.29 0.771 -.151425 .1123291
    |
    x6 | -544.3496 737.4712 -0.74 0.460 -1989.767 901.0674
    x7 | 543.7989 737.9421 0.74 0.461 -902.541 1990.139
    ----------------------------------------------------------------------------------------
    Instruments for first differences equation
    GMM-type (missing=0, separate instruments for each period unless collapsed)
    L(3/17).hiv_inf
    ------------------------------------------------------------------------------
    Arellano-Bond test for AR(1) in first differences: z = -1.49 Pr > z = 0.137
    Arellano-Bond test for AR(2) in first differences: z = 1.34 Pr > z = 0.180
    ------------------------------------------------------------------------------
    Sargan test of overid. restrictions: chi2(85) = 142.00 Prob > chi2 = 0.000
    (Not robust, but not weakened by many instruments.)
    Hansen test of overid. restrictions: chi2(85) = 7.86 Prob > chi2 = 1.000
    (Robust, but weakened by many instruments.)

Result with collapse:
Dynamic panel-data estimation, one-step difference GMM
------------------------------------------------------------------------------
Group variable: rec_num Number of obs = 422
Time variable : year Number of groups = 38
Number of instruments = 15 Obs per group: min = 1
Wald chi2(0) = . avg = 11.11
Prob > chi2 = . max = 12
----------------------------------------------------------------------------------------
| Robust
y | Coef. Std. Err. z P>|z| [95% Conf. Interval]
-----------------------+----------------------------------------------------------------
y |
L1. | -1.547281 17.0422 -0.09 0.928 -34.94939 31.85483
L2. | 1.268705 14.11864 0.09 0.928 -26.40332 28.94073
|
x1 |
L1. | .5364254 5.925459 0.09 0.928 -11.07726 12.15011
L2. | 1.118569 8.584004 0.13 0.896 -15.70577 17.94291
L3. | -.9398232 12.59783 -0.07 0.941 -25.63112 23.75147
L4. | 1.369626 8.409769 0.16 0.871 -15.11322 17.85247
L5. | -.3716305 2.506262 -0.15 0.882 -5.283814 4.540553
|
x2 |
L1. | 13.32372 169.2516 0.08 0.937 -318.4034 345.0508
L2. | -1.634898 59.74055 -0.03 0.978 -118.7242 115.4544
L3. | -20.85329 226.6722 -0.09 0.927 -465.1226 423.416
L4. | 22.77116 243.3968 0.09 0.925 -454.2778 499.8201
L5. | -7.901386 52.83028 -0.15 0.881 -111.4468 95.64406
|
x3 | .2881728 3.929217 0.07 0.942 -7.412952 7.989297
x4 | -13.31332 99.59179 -0.13 0.894 -208.5096 181.883
x5 | .0391301 .1761786 0.22 0.824 -.3061737 .3844339
----------------------------------------------------------------------------------------
Instruments for first differences equation
GMM-type (missing=0, separate instruments for each period unless collapsed)
L(3/17).hiv_inf collapsed
------------------------------------------------------------------------------
Arellano-Bond test for AR(1) in first differences: z = 0.11 Pr > z = 0.910
Arellano-Bond test for AR(2) in first differences: z = 0.13 Pr > z = 0.899
------------------------------------------------------------------------------
Sargan test of overid. restrictions: chi2(0) = 0.00 Prob > chi2 = .
(Not robust, but not weakened by many instruments.)
Hansen test of overid. restrictions: chi2(0) = 0.00 Prob > chi2 = .
(Robust, but weakened by many instruments.)


text:
Q: Jquery Tooltip inside Scrollable I'm working on a tooltip based on this tutorial which uses jquery .offset() for position. page with tooltip
When I place a tooltip inside a scrollable it is incorrectly positioned for all but the first scrollable item due to overflow (I think).
Any ideas for fixes?
Thanks

A: If I am not mistaken, the tooltip uses fixed coordinates to display. So there is no easy fix. You could have the possison modified based on the amount you scroll. Say if you scroll 50px in the scrollable, you move the tooltip 50px y axis. This would require modifying the properties directly, and it might cause some weird problems.
Thats my 2 cents on how you would fix your problem.


text:
Q: Loading store data with rest proxy from server in Sencha Touch 2 I have searched around on the forums and read some other posts. However, I'm not sure how exactly to go about this. I have a store with a proxy that I'm trying to load with data from a server. I have tried both jsonp and rest for the type of proxy without luck. In both cases I get a 403 forbidden error. followed by an XMLHTTPRequest cannot load error.
Here's the error that I see in the Chrome console:

Here's my code:
Ext.define('EventsTest.store.Venues', {
    extend: 'Ext.data.Store',

    requires: [
        'Ext.data.proxy.Rest',
    ],

    config: {
        storeId: 'venuesStore',
        model: 'EventsTest.model.Venue',
        proxy: {
            type: 'rest',
            url: 'http://leo.web/pages/api/',
            headers: {
                'x-api-key': 'senchaleotestkey'
            },
            limitParam: false,
            pageParam: false,
            enablePagingParams: false
            /*
            extraParams: {
                latitude: 45.250157,
                longitude: -75.800257,
                radius: 5000
            }
            */
        }
    }
});

A: You're running your app on a local domain "sencha.test", but you're trying to access data on "leo.web" - the error is that you're trying to load data across domains, which isn't allowed via AJAX.
You say that JSONP doesn't work... why not? Does your server return valid JSONP?

A: Security policy in browser and desktop is different so even if it fails in browser it can work in phone. But now the question is how to manage while you are developing the app, for that have a look at this similar question :
How to use json proxy to access remote services during development
Regarding that OPTION request which is getting 403 response, try setting withCredentials : false and useDefaultHeader : false. Details here
http://docs.sencha.com/touch/2-1/#!/api/Ext.data.Operation-cfg-withCredentials
http://docs.sencha.com/touch/2-1/#!/api/Ext.data.Connection-cfg-useDefaultHeader
I would suggest you to read more about CORS if you want to use remote services, you may choose to enable CORS on your server.


text:
Q: ListFragment onListItemClick strange behaviour In my CustomList fragment I want to show an image inside item layout each time item is clicked:
public class CustomList extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
  ...

  @Override
  public void onListItemClick(ListView list, View view, int position, long id) {
    super.onListItemClick(list, view, position, id);

    ImageView imageToShow = (ImageView) view.findViewById(R.id.myImageId);
    if (imageToShow != null) {
      if (imageToShow.getVisibility() == View.INVISIBLE) {
        imageToShow.setVisibility(View.VISIBLE);
      }
    }
  }

  ...
}

The row item layout has an ImageView with visibility attribute set to "invisible"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tooth="http://schemas.android.com/apk/res/pl.vmcard"
  <!-- ... -->
  <ImageView
    android:id="@+id/myImageId"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:contentDescription="@string/image"
    android:src="@drawable/ic_action_event"
    android:visibility="invisible" />
</LinearLayout>

The problem is, when row item is clicked, the image appears for it, but also it appears for other item from the bottom of the list. So if I click item on position 0, the image appears also on item with position 7. I can't figure out what is the reason for that behaviour.
Edit - CustomAdapter.getView() method:
public class CustomAdapter extends SimpleCursorAdapter {
  ...
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    final View row = super.getView(position, convertView, parent);
    if (position % 2 == 0)
      row.setBackgroundResource(R.drawable.list_item_background_even);
    else
      row.setBackgroundResource(R.drawable.list_item_background_odd);
    return row;
  }
  ...
}

A: The reason is that ListView pools views. You do not get a number of views equal to the adapter.getSize() but you get the number of views that fit the screen. This is made for performance reasons. What you should do is to change your dataset accordingly to the action you perform in onListItemClick , and let the getView managing the view's visibility


text:
Q: delphi xmlchildnode gets attribute from parent I am trying to write an xML in Delphi.
If I gife a node a xmlns attribute, the child node of that node shows the attribute also but then empty. How can I prefent that the child node shows the attribute?
I tested with the following code
procedure TForm2.Button1Click(Sender: TObject);
var
  RootNode, CurNode, PmtNode, PmtDetNode : IXMLNODE;
  I:Integer;
begin
   SepaDoc := Newxmldocument;
   SepaDoc.Encoding := 'utf-8';
   SepaDoc.Options := [doNodeAutoIndent];
   RootNode := SepaDoc.AddChild('Document');
   CurNode := RootNode.AddChild('Child1');
   CurNode.Attributes['xmlns'] := 'apenootje';
   CurNode := CurNode.AddChild('Child2');
   CurNode := CurNode.AddChild('Child3');
   SepaDoc.SaveToFile('D:\indir\testsepa.xml');
end;

This result in the following XML
<?xml version="1.0" encoding="UTF-8"?>
-<Document>   -<Child1 xmlns="apenootje">
    -<Child2 xmlns="">
       <Child3/>
     </Child2>
    </Child1>
  </Document>

Thanks
Rob Nowee

A: Since the child elements of Child1 don't carry the same namespace, it must be undeclared and that's the reason that Child2 is holding the empty (default) namespace.
This is known as Namespace undeclaration

When an element carries the attribute xmlns="", the default namespace for that element and its descendants reverts to "no namespace": that is, unprefixed names are considered not to be in any namespace.
XML Namespaces 1.1 also introduces the option to undeclare other namespace prefixes. For example, if the attribute xmlns:p="" appears on an element, the namespace prefix p is no longer in scope (and therefore cannot be used) on that element or on its descendants, unless reintroduced by another namespace declaration

That being said, the fix is simple; include the namespace on all subsequent child nodes:
program SO20424534;

{$APPTYPE CONSOLE}

uses
  ActiveX,
  XMLdom,
  XMLDoc,
  XMLIntf,
  SysUtils;

function TestXML : String;

var
  RootNode,
  CurNode    : IXMLNODE;
  Doc        : IXmlDocument;
  ns         : String;

begin
 Doc := Newxmldocument;
 ns := 'apenootje';
 Doc.Encoding := 'utf-8';
 Doc.Options := [doNodeAutoIndent];
 RootNode := Doc.AddChild('Document');
 CurNode := RootNode.AddChild('Child1');
 CurNode.DeclareNamespace('', ns);
 CurNode := CurNode.AddChild('Child2', ns);
 CurNode := CurNode.AddChild('Child3', ns);
 Result := Doc.XML.Text;
end;

begin
  try
   CoInitialize(nil);
   try
    Writeln(TestXML);
   finally
    CoUninitialize;
   end;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
 Readln;
end;

Output:
<?xml version="1.0"?>
<Document>
  <Child1 xmlns="apenootje">
    <Child2>
      <Child3/>
    </Child2>
  </Child1>
</Document>

A: You have to declare a namespace before you can use it. It is not enough to simply add an xmlns attribute manually, which is not the correct way to let the DOM know about the existence of the namespace. Use IXMLNode.DeclareNamespace() for that instead, eg:
CurNode := RootNode.AddChild('Child1');
CurNode.DeclareNamespace('', 'apenootje');


text:
Q: Allowing views and template content to certain groups I am working on a project where i need to distinguish between two groups (and admin):

*

*Therapists

*Patients

When the users login, i want to easily set the views according to what they have permission to see and able to do, also in the templates. What is the best-practice in this particular use-case? I have read about the PermissionMixin which is proposed in this question. So far i have considered using that method proposed along with a method to inside my template to change the content according to the group. Is this the way to go?

A: Once you create the matching permission groups, it's as easy as decorating your view like :
from django.contrib.auth.decorators import permission_required

@permission_required('foo.doctor')
def patients_registry_view(request):
    ...

If you create a larger project where most of the views are somehow restricted, mixins are the way to go.
The documentation gives in-dept coverage of this topic, I strongly recommend taking a look.


text:
Q: repository pattern in asp. net mvc3 I have recently started teaching myself C# and Asp.net. I am trying to build a simple blog application. I am confused about repository pattern usage. I have seen few tutorials and the implementation varies.
For my blog application, I have two database tables (models) - blogs and comments. Currently, I have a IDbContext which looks like this:
    public interface IDBContext
    {
        IQueryable<Blog> FindAllBlogs();
        IQueryable<Blog> FindBlogsInMonth(int month);
        Blog GetBlog(int id);
        void Add(Blog blog);
        void Update(Blog blog);
        void Delete(Blog blog);

        void Add(Comment comment);
        //void Remove(Comment comment);
    }

and I have repository which looks like this:
    public class BlogRepository : IDBContext
    {
        private BlogDb db = new BlogDb();

        public IQueryable<Blog> FindAllBlogs()
        {
            return db.Blogs.OrderByDescending(b => b.PublishDate);
        }

        public Blog GetBlog(int id)
        {
            return db.Blogs.Single(b => b.BlogID == id);
        }
...
}

The other implementation of repository pattern is something like this:
public interface IDbContext
{
    IQueryable<Blog> Blogs { get; }
    IQueryable<Comments> Comments { get; }
    int SaveChanges();
    T Attach<T>(T entity) where T : class;
    T Add<T>(T entity) where T : class;
    T Delete<T>(T entity) where T : class;
}

which calls a repository and there is separate class for queries.
What is the best method to do it?

A: The easiest method is to use Entity Framework directly, particularly the new DbContext functionality that showed up in Entity Framework 4.1 and later.
The context will contain DbSet properties - each is an implementation of the repository pattern that accomplishes all of the goals you described above. IDbSet can be used if unit testing support is required.
I've seen a lot of demos for the ASP.NET MVC repository patterns online that end up wrapping Entity Framework with a custom repository. It's a waste of time - it's code that wraps other code and doesn't serve any direct purpose aside from adding needless complexity.


text:
Q: $\int dx \; f(\sqrt{x^2+a^2})$ by substitution $u=\sqrt{x^2+a^2}$ I need to calculate the following integral:
$I = \int  x\arctan(\frac{a}{x}) \; K_0(\sqrt{x^2+a^2})dx$,
where $K_0$ is a Modified Bessel Function of the Second Kind. I think there is a good chance to be able to calculate it using integration by parts because quite a lot is known about integrals of both $\arctan(x)$ and $K_0(x)$ (see http://personalpages.to.infn.it/~zaninett/pdf/abramovitz2.pdf, page 248).
I started by doing the substitution $u = \sqrt{x^2 + a^2}$, but then I realized that $x(u)= \pm \sqrt{u^2-a^2}$, so there is no function $x(u)$, which I need in $arctan(\frac{a}{x})$.
So how does one deal with integrals of the kind $\int dx \; f(\sqrt{x^2+a^2})$?
Of course, it would AMAZING if someone knows how to actually calculate this integral?

A: With $u=\sqrt {x^2+a^2}\;$ and $0\leq x=\sqrt {u^2-a^2}$ and $a>0$ we have $K_0(\sqrt {x^2+a^2}\;)=K_0(u)$. And $x\cdot dx=x\frac {u}{\sqrt {u^2-a^2}}du=u\cdot du$. And $\arctan (a/x)=\arcsin (a/u)$. So the integral in the Q is $$\int uK_0(u)\arcsin (a/u)\;du$$.
This is all I can say. I dk if this will help.


text:
Q: My image slideshow code won't work I'm trying to create an image cycle (or slideshow, as I've heard it called), in Javascript and HTML. I programmed this code bit, but it doesn't seem to work. What is stopping it from working? Someone asked to add the HTML. I also added the equal sign to the imageset, because that didn't fix the problem.

<button id = 'Change' onclick = ChangeImage()>Change</button>

function ChangeImage() {

    var ImageOne = new Image();
    ImageOne.src = 'http://images.visitcanberra.com.au/images/canberra_hero_image.jpg';
    var ImageTwo = new Image();
    ImageTwo.src ='http://upload.wikimedia.org/wikipedia/commons/b/b6/Image_created_with_a_mobile_phone.png';
    var ImageThree = new Image();
    ImageThree.src = 'http://imageswiki.com/wp-content/uploads/2014/11/images-ImageVaultHandler.jpg';
    var ImageFour = new Image();
    ImageFour.src = 'http://www.wonderplugin.com/wp-content/plugins/wonderplugin-lightbox/images/demo-image2.jpg';
    var ImageSet=[ImageOne.src, ImageTwo.src, ImageThree.src, ImageFour.src];
    var CallImage = document.getElementById('HeaderPhotoImage').innerHTML;
    CallImage.src = ImageSet[0];
}


text:
Q: what is ? What is <spring:message> tag?What is its use?
I tried to Google it but could not find any useful content.

A: You can change the text According to the language using Those Tags. Simply using
<spring:message code="some_name"/>

tag you can populate the text into your JSP using relevant .properties file after configured it.
For Tutorial you can use below link
http://www.mkyong.com/spring-mvc/spring-mvc-internationalization-example/

A: It is used during internationalization, Google is full of tutorials... One of them: http://viralpatel.net/blogs/spring-3-mvc-internationalization-i18n-localization-tutorial-example/


text:
Q: imap_fetchstructure () doesn't retrieve attachments (parts) I'm trying to retrieve and read attachments from my IMAP account via imap_fetchstructure() but while it reads general attachments such as PDF, Images etc, the specific attachment which I want to read (a name.bin file) doesn't get captured in the code. As you can see in the attached screenshot there is an attachment in the mail.

This is the response I get;
    stdClass Object
(
    [type] => 3
    [encoding] => 3
    [ifsubtype] => 1
    [subtype] => OCTET-STREAM
    [ifdescription] => 0
    [ifid] => 0
    [bytes] => 58
    [ifdisposition] => 0
    [ifdparameters] => 0
    [ifparameters] => 0
    [parameters] => stdClass Object
        (
        )

)

A: The sender sent you a 58-byte attachment with content-type application/octet-stream and without such details as a suggested filename, so that's all the information you get from retrieving bodystructure, which is about the bodystructure, as the name implies. If you want the attachment content, not just its structure, itself you have to retrieve it.


text:
Q: Problems with boundary conditions I am new to mathematica and I have doubts with my code, I probably have errors with the boundary conditions
If you could help me I would appreciate it very much
my code is the following
NDSolve[{\[Alpha]*(D[T[x, y, t], {x, 2}] +2.5*D[T[x, y, t], {y, 2}]) == D[T[x, y, t], {t, 1}],
T[x, y, 0] == to, Derivative[1, 0, 0][T][0, y, t] == 0,Derivative[0, 1, 0][T][x, 0, t] == 0, -k*D[T[L, y, t], {x, 1}] ==h*(T[L, y, t] - tam), -2.5*k*D[T[x, L, t], {x, 1}] ==h*(T[x, L, t] - tam)}, T[x, y, t], {x, y, t}]

I was careful with the double problem =


text:
Q: How to manage my own reviews and ratings in Mac App Store? Is there such an option in Mac App Store? I know in iTunes Store we can manage reviews and ratings in personal account.

A: Open the Mac App Store. On the Featured tab, in the right sidebar, there is a link called Account. Under Settings > Reviews and Ratings, click Manage. You can edit / delete your reviews there.

A: On macOS Mojave and later this is managed in the Account area that can be accessed at the bottom of the left sidebar. Once in the Account area, click on View Information and under Manage > Reviews and Ratings there will be a Manage link button.


text:
Q: Numeric function for log of sum in Python Given log(a) and log(b), I want to compute log(a+b) (in a numerically stable way).
I wrote a little function for this:
def log_add(logA,logB):
    if logA == log(0):
        return logB
    if logA<logB:
        return log_add(logB,logA)
    return log( 1 + math.exp(logB-logA) ) + logA

I wrote a program where this is by far the most time-consuming piece of code. Obviously I could try to optimize it (eliminate the recursive call, for instance).
Do you know of a standard math or numpy function for computing log(a+b) from log(a) and log(b)?
If not, do you know of a simple way to make a single C++ hook for this function? It's not a complicated function (it uses floats), and as I said, it's taking up the majority of my runtime.
Thanks in advance, numerical methods ninja!

A: Note: Best answer until now is to simply use numpy.logaddexp(logA,logB).
Why exactly do you compare with log(0)? This is equal to -numpy.inf, in this case you come to log(1 + math.exp(-inf-logB) ) + logB Which reduces itself to logB. This call always will give an warning message which is extremely slow.
I could come up with this one-liner. However you'll need to really measure to see if this is actually faster. It does only use one 'complex' calculation function instead of the two that you use, and no recursion is happening, the if is still there but hidden (and maybe optimized) in fabs/maximum.
def log_add(logA,logB):
    return numpy.logaddexp(0,-numpy.fabs(logB-logA)) + numpy.maximum(logA,logB)

edit:
I did a quick timeit() with following results :

*

*Your original version took about 120s

*My version took about 30s

*I removed the compare with log(0) from your version and it came down to 20s

*I edited my code to keep the logaddexp but also worked with your recursive if and it went down to 18s.

Updated code, you could also switch the recursive call with an inline updated formula but this made little difference in my timing tests:
def log_add2(logA, logB):
    if logA < logB:
        return log_add2(logB, logA)
    return numpy.logaddexp(0,logB-logA)+logA

Edit 2:
As pv noted in comments, you could actually just do numpy.logaddexp(logA, logB) which comes down to calculating log(exp(logA)+exp(logB)) which is of course equal to log(A+B). I timed it (on the same machine as above) and it went further down to about 10s. So we've come down to about 1/12, not bad ;).

A: def log_add(logA, logB):
    return math.log(math.exp(logA) + math.exp(logB))

is too slow? or inaccurate?


text:
Q: How does EnumerateFiles() work? I am writing a program that, when given a date, folder path, and file extension, will look into the folder and will go find all files that had a last access time from the beginning of the month to the current date, and only files with the file extension that was passed.
The files that I am looking for are always in the same level in the folder tree so I can code into the program how far to dig to find the files.
Currently my program takes about a minute for a day so today (The 16th) takes about sixteen and a half minutes.
I want to make a program that fill find all files for a date range in a folder path and will extract information from the file.  I just don't want to code how deep the program has to look in case my business changes how they store their files.
I managed to make code that, if given a folder, the program will display the names of all the files for the date range but that took 25 minutes.  Here is the code
TimeSpan BeginningTime = DateTime.Now.TimeOfDay;
DateTime BeginningDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
DateTime EndingDate = DateTime.Now;
string[] FoldersToLookAt = { @"e:\", @"e:\Kodak Images\", @"e:\images\", @"e:\AFSImageMerge\" };
foreach (string FolderPath in FoldersToLookAt)
{
    for (DateTime Date = BeginningDate; Date <= EndingDate; Date = Date.AddDays(1))
    {
        string DateString = Date.ToString("yyMMdd");
        string FilePath = (FolderPath + DateString);
        DirectoryInfo FilesToLookThrough = new DirectoryInfo(FilePath);
        if (FilesToLookThrough.Exists)
        {
            foreach (var MyFile in FilesToLookThrough.EnumerateFiles("*.dat", SearchOption.AllDirectories))
            {
                if (MyFile.LastAccessTime >= BeginningDate)
                {
                    Console.WriteLine(MyFile.FullName);
                }
            }
        }
    }
}

From what I see this first obtains all the files, then goes through all files and prints out
all files that have a last access time greater than the beginning date.
Is their a way in C# that will extract information from a file and NOT store it in a list?  Or am I going to have to build the program from scratch?

A: Your question is not very clear, but looking at your code, and what you state you want to achieve, I would recommend that you get rid of the loop that takes you through the date folders. Just use the "AllDirectories" option, under each of the top-level folders. It is recursive, so it will go down through as many levels as there are.
TimeSpan BeginningTime = DateTime.Now.TimeOfDay;
DateTime BeginningDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
DateTime EndingDate = DateTime.Now;
string[] FoldersToLookAt = { @"e:\", @"e:\Kodak Images\", @"e:\images\", @"e:\AFSImageMerge\" };
foreach (string FolderPath in FoldersToLookAt)
{
    FilesToLookThrough = new DirectoryInfo(FolderPath);
    if (FilesToLookThrough.Exists)
    {
        foreach (var MyFile in FilesToLookThrough.EnumerateFiles("*.dat", SearchOption.AllDirectories))
        {
            if (MyFile.LastAccessTime >= BeginningDate)
            {
                Console.WriteLine(MyFile.FullName);
            }
        }
    }
}

EDIT: The other answer makes a good point, since you're going through "e:\", you probably don't need to go through the other "FoldersToLookAt", since they will all be searched anyway. What you might end up with here is multiple listings of the same file. If you take those out, it will run quite a bit faster.
You see, your code was pretty close in the first place. Using this approach you cut out a whole loop, and the "AllDirectories" search option will make sure that you look through all the sub-folders recursively. You are also protected against your organisation deciding not to store stuff in folders named by date etc, and now the runtime of your program is proportional only to the number of files.
Now, for extra credit, another big performance improvement can be made by not using Console.WriteLine for each item. A faster way would be to use a StringBuilder, and then spit the results out at the end.
// At the top of your program
StringBuilder sb = new StringBuilder();
// BeginningTime, BeginningDate, etc...

// Before the first loop
Console.WriteLine("Working...");

// Inside the very inner if, where your Console.WriteLine was
sb.AppendLine(MyFile.FullName);

// After the end of the outer loop
Console.WriteLine(sb.ToString());

Why does this make it better? Writing to the console is notoriously slow, it actually involves sending Windows into kernel mode and back, it's really, really slow. Doing it once, event with a much larger chunk of text, is much, much quicker, than doing it lots. Now, why use a StringBuilder instead of just doing a good old:
string output;

for(...)
{
     output += filename + Environment.NewLine;
}

In C# adding two strings to eachother creates a new string. Doing this over and over again is also slow, especially as the new string gets larger. StringBuilder just maintains a list of all the strings, and creates a new buffer and copies them all in, once, when you call ToString().

A: Your program looks far more complex than what it has to, considering your requirements.
string[] FoldersToLookAt = { @"e:\",
                             @"e:\Kodak Images\",    // do you really need these,
                             @"e:\images\",          // since you're already
                             @"e:\AFSImageMerge\" }; // going through e:\ ?
DateTime BeginningDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

foreach (string FolderPath in FoldersToLookAt)
{
    DirectoryInfo FilesToLookThrough = new DirectoryInfo(FolderPath);
    foreach (FileInfo MyFile in FilesToLookThrough.EnumerateFiles("*.dat",
                                                    SearchOption.AllDirectories))
    {
        if (MyFile.LastAccessTime >= BeginningDate)
        {
            Console.WriteLine(MyFile.FullName);
        }
    }
}

This code does not loop through days, so it should have a constant runtime in regards to BeginningDate, meaning regardless of what date you choose, it will always take the same amount of time.

A: It sounds like, given a list of directories to search, find all files in certain subdirectories of the directories to be searched that match a particular pattern and have have been touched within the current month. Given that problem statement, something like this should do you:
static IEnumerable<FileInfo> FindFiles( IEnumerable<string> directories , string searchPattern )
{
  DateTime     dtNow       = DateTime.Now.Date                ; // current date
  DateTime     dtFrom      = dtNow.AddDays( dtNow.Day - 1 )   ; // compute the first of the month @ start-of-day
  DateTime     dtThru      = dtFrom.AddMonths(1).AddTicks(-1) ; // compute the last of the month @ end-of-day
  string       childPattern = dtFrom.ToString( "yyMM*") ;

  return directories.Select( x => new DirectoryInfo( x ) )
                    .Where( x => x.Exists )
                    .SelectMany( x => x.EnumerateDirectories( childPattern , SearchOption.TopDirectoryOnly )
                                       .Where( subDir => {
                                           int dd ;
                                           int.TryParse( subDir.Name.Substring(4,2) , out dd ) ;
                                           return dd >= dtFrom.Day && dd <= dtThru.Day ;
                                         })
                    )
                    .SelectMany( subDir => subDir.EnumerateFiles( searchPattern , SearchOption.TopDirectoryOnly )
                                                 .Where( file => file.LastAccessTime >= dtFrom && file.LastAccessTime <= dtThru )
                    )
                    ;

}

An explanation of what this code does:
directories.Select( x => new DirectoryInfo( x ) )

Takes the supplied enumerable list of string directory paths and converts it into an enumerable list of DirectoryInfo objects representing the specified directories
.Where( x => x.Exists )

Excludes any non-existent directories
This gives use the set of root directories to be searched.
The next clause is a little more complicated. SelectMany() takes an enumerable list of things. Each item in the list is converted into an enumerable list of things (which might or might not be the same type of object as the original. However, each such sublist must be of the same type.)
The resulting "list of lists" is then flattened to produce a single enumerable list.
With that in mind,
.SelectMany( x => x.EnumerateDirectories( childPattern , SearchOption.TopDirectoryOnly )
                   .Where( subDir => {
                     int dd ;
                     int.TryParse( subDir.Name.Substring(4,2) , out dd ) ;
                     return dd >= dtFrom.Day && dd <= dtThru.Day ;
                   })
                )

Converts each root directory into a list of subdirectories, whose name starts with the year and month specified (yyMM*) and whose 4th & 5th characters are the day of the month. That list of lists of subdirectories is then flattened into a single list of subdirectories.
The last SelectMany()
.SelectMany( subDir => subDir.EnumerateFiles( searchPattern , SearchOption.TopDirectoryOnly )
                             .Where( file => file.LastAccessTime >= dtFrom
                                          && file.LastAccessTime <= dtThru
                                   )
 )

goes over the list of subdirectories resulting from the first SelectMany(), searching each for files whose names match the specified name pattern (*.dat in your example) and whose last access time is within the specified time frame.
The resulting list of lists of FileInfo objects is then flattened into a single list of FileInfo objects representing the files in which you're interested.
You can then access them directorly, something like
string[] searchDirs =
{ @"e:\"              ,
  @"e:\Kodak Images\" ,
  @"e:\images\"       ,
  @"e:\AFSImageMerge\"
} ;

foreach ( FileInfo fi in FindFiles( searchDirs , "*.dat" )
{
  do_something_with_interesting_file( fi ) ;
}


text:
Q: Android XML: Style TabHost to have lowercase text I am implementing a tag layout for my Android application. I tried setting each of the tags to a certain style that has textAllCaps set to false (app:tabTextAppearance="@style/MyCustomTextAppearance")-however, that did not work for me. This question is not a duplicate because I am not using a TabLayout, I am using TabHost. Below is my code:
The style in styles.xml:
<style name="MyCustomTextAppearance" parent="TextAppearance.Design.Tab">
    <item name="textAllCaps">false</item>
</style>

content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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_width="match_parent"
    android:layout_height="match_parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        tools:context=".MainActivity"
        app:tabTextAppearance="@style/MyCustomTextAppearance"
        tools:showIn="@layout/activity_main">

        <TabHost
            android:id="@+id/tab_host"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:background="#ffffff"
            app:tabTextAppearance="@style/MyCustomTextAppearance"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                app:tabTextAppearance="@style/MyCustomTextAppearance"
                android:orientation="vertical">

                <FrameLayout
                    android:id="@android:id/tabcontent"
                    app:tabTextAppearance="@style/MyCustomTextAppearance"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content">

                    <LinearLayout
                        android:id="@+id/tab1"
                        app:tabTextAppearance="@style/MyCustomTextAppearance"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal" />

                    <LinearLayout
                        android:id="@+id/tab2"
                        app:tabTextAppearance="@style/MyCustomTextAppearance"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal" />

                    <LinearLayout
                        android:id="@+id/tab3"
                        app:tabTextAppearance="@style/MyCustomTextAppearance"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal" />
                </FrameLayout>

                <TabWidget
                    android:id="@android:id/tabs"
                    app:tabTextAppearance="@style/MyCustomTextAppearance"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content" />
            </LinearLayout>
        </TabHost>

        <com.anychart.AnyChartView
            android:id="@+id/piechart"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            app:layout_constraintTop_toBottomOf="@+id/tab_host"
            />

    </androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>

Below is what my app looks like (the text of the tabs are still capitalized):

A: Apply below style on tabLayout
 app:tabTextAppearance="@android:style/TextAppearance.Widget.TabWidget"

A: Use this and change style same as color
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
            View v = tabHost.getTabWidget().getChildAt(i);
            v.setBackgroundResource(R.drawable.tabs);

            TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
            tv.setTextColor(getResources().getColor(R.color.white));
}

A: for (int i = 0; i < tabhost.getTabWidget().getChildCount(); i++) {
            View v = tabhost.getTabWidget().getChildAt(i);

            TextView tv = (TextView) tabhost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);

            tv.setAllCaps(false);
}


text:
Q: What is wrong with Http security header (X-XSS-Protection, X-Content-Type-Options) on my website/server? I really do not know what is wrong but https security headers works wel with http but not with https on my site. I have set via htaccess:
<IfModule mod_headers.c>
Header always append X-XSS-Protection "1; mode=block"
Header always append X-Frame-Options SAMEORIGIN
Header always append X-Content-Type-Options nosniff
</IfModule>

and when i test my website this is result:

http://www.mywebsite.com

> --------------------------------------------
> 301 Moved Permanently
> --------------------------------------------
Status: 301 Moved Permanently
Code:   301
Date:   Thu, 30 Dec 2021 12:33:49 GMT
Server: Apache
X-XSS-Protection:   1; mode=block
X-Frame-Options:    SAMEORIGIN
X-Content-Type-Options: nosniff
Location:   https://www.www.mywebsite.com/
Ip: 162.252.xx.xx
Cache-Control:  max-age=2592000
Expires:    Sat, 29 Jan 2022 12:33:49 GMT
Content-Length: 242
Connection: close
Content-Type:   text/html; charset=iso-8859-1

https://www.mywebsite.com

> --------------------------------------------
> 200 OK
> --------------------------------------------
Status: 200 OK
Code:   200
Date:   Thu, 30 Dec 2021 12:33:49 GMT
Server: Apache
Connection: close
Content-Type:   text/html

So you can see that security headers X-XSS-Protection, X-Frame-Options and X-Content-Type-Options are set and sent by accessing url via http://www.mywebsite.com but with https://www.mywebsite.com not.
Why it works via http protocol and not via https protocol? Where is issue? What to do?

A: Try using these lines ....
Header always set X-Frame-Options SAMEORIGIN
Header set X-XSS-Protection "1; mode=block"
Header set X-Content-Type-Options nosniff


text:
Q: Flate rate shipping is not showing I am using magento 2.1.7. I have enable the Flat rate shipping but still it is nit showing.
Kindly can somebody help me for that

A: Did you install any one-page checkout extension, try to disable that extension and check,
or check by clearing the Magento cache (php bin/magento cache:flush),
or if you have a multistore website, then check the store level shipping method configuration.


text:
Q: Is the copy constructor called when an object is passed by reference? When a class object is passed by value to any function, the copy constructor is called to create a local object and the destructor is called when the object is returned.
But, will copy constructor be called if the object reference is passed?

A: Nope, it won't be called.
A reference is an alias, that is, another name for an already existing variable and not for a copy.
Take a look at this example:
class Line {
public:
   int getLength( void ){}
   // simple constructor
   Line(  ){
      cout<<"constructor"<<endl;
   }
   // copy constructor
   Line( const Line &obj){
      cout<<"copy cts\n";
   }
};

void callR(Line& l){
   cout<<"call by ref\n";
}
void callC(Line l){
   cout<<"call by copy\n";
}

int main() {

   Line line;
   cout<<"before call by reference\n";
   callR(line);
   cout<<"before call by copy\n";
   callC(line);
}

which produces the following output:
constructor ->  Line line;
before call by reference
call by ref
before call by copy
copy cts
call by copy

As you can see copy constructor is not called when an object is passed by reference. Think of a reference as a pointer.


text:
Q: c++ string not getting reset if i enter the first command as create it should print incomplete command... and then when i again enter create file as the command it should print Hello. But it is only printing incomplete command... but not printing the output Hello the second time. Please help. I think the global string command is not getting reset every time although i have set it to empty every time the function accept_command is called. I might be wrong.
enter code here
#include<iostream>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<conio.h>
#include<stdio.h>
using namespace std;

struct node
{
    string details;
    int shirtnumber;
    struct node* next;
};
struct node* head=NULL;
struct node1
{
    string details;
    int shirtnumber;
    struct node1* row;
    struct node1* column;
};
struct node1* head1=NULL;
string command="";
string command_words[5]="";

void validate_command()
{
    void command_words_calculate();
    void accept_command();

    command_words_calculate();

    if(command_words[1]=="")
    {
       cout<<"incomplete command...\n"<<endl;
       accept_command();
    }
    if(command_words[0].compare("create")==0)
    {
        cout<<"Hello\n"<<endl;
        accept_command();
    }
}

void command_words_calculate()
{
    int i,k=0;
    char ch,ch1;
    string duplicate="";
   for(i=0;i<command.length();i++)
    {
        ch=command.at(i);
        if(ch==' ')
            continue;
        else
            break;
    }

     command=command.substr(i,command.length());

    for(i=0;i<command.length();i++)
    {
        ch=command.at(i);
        if(i!=command.length()-1)
            ch1=command.at(i+1);
        if(ch==' ')
        {
            if(i!=command.length()-1&&ch1!=' ')
            {
            k++;
            continue;
            }
            else if(i==command.length()-1)
            {
                break;
            }
            else
                continue;
        }
        else
            command_words[k]=command_words[k]+ch;
    }

}

void display()
{
    void accept_command();
    cout<<"O.S"<<endl;
    accept_command();
}

void accept_command()
{
   command="";
   void validate_command();
   cout<<"root\\:>";
   getline(cin,command);
   validate_command();

}

int main()
{
    void display();
    display();
    return 0;

}

A: Well as you say the global string is not getting reset each time. But why should it, global variable don't work that way. You could explcitly reset the global variable but the correct way to do this is to use local variables instead. Generally you should avoid global variables.
How about this, I deleted the global variables command and command_words and replaced them with local ones.
void accept_command()
{
   string command="";                     // local variable
   void validate_command(string command);
   cout<<"root\\:>";
   getline(cin,command);
   validate_command(command);
}

void validate_command(string command)
{
    void command_words_calculate(string command, string* command_words);
    void accept_command();

    string command_words[5]={""};                     // local variable
    command_words_calculate(command, command_words);

    if(command_words[1]=="")
    {
       cout<<"incomplete command...\n"<<endl;
       accept_command();
    }
    if(command_words[0].compare("create")==0)
    {
        cout<<"Hello\n"<<endl;
        accept_command();
    }
}

void command_words_calculate(string command, string* command_words)
{
    int i,k=0;
    char ch,ch1;
    string duplicate="";
   for(i=0;i<command.length();i++)
    {
        ch=command.at(i);
        if(ch==' ')
            continue;
        else
            break;
    }

     command=command.substr(i,command.length());

    for(i=0;i<command.length();i++)
    {
        ch=command.at(i);
        if(i!=command.length()-1)
            ch1=command.at(i+1);
        if(ch==' ')
        {
            if(i!=command.length()-1&&ch1!=' ')
            {
            k++;
            continue;
            }
            else if(i==command.length()-1)
            {
                break;
            }
            else
                continue;
        }
        else
            command_words[k]=command_words[k]+ch;
    }

}

This is how you should work, with local variables which use parameters and return values to pass data to each other.


text:
Q: Gluon javafx with netbeans error android install Error while trying to to do android install
  Execution failed for task ':mergeClassesIntoJar'.

Cannot expand ZIP 'C:\Users\Path..\AppData\Local\Android\sdk\extras\android\support\multidex\library\libs\android-support-multidex.jar' as it does not exist.

Can any one pleas help am fed up of this issue no proper solution below is my code
buildscript {
    repositories {

        jcenter()
    }
    dependencies {
        classpath 'org.javafxports:jfxmobile-plugin:1.0.9'

    }
}

apply plugin: 'org.javafxports.jfxmobile'

repositories {
    jcenter()
    maven {
        url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
    }
}

mainClassName = 'com.netbeansdemo.NetbeansDemo'

dependencies {
    compile 'com.gluonhq:charm:3.0.0'

    androidRuntime 'com.gluonhq:charm-android:3.0.0'
    iosRuntime 'com.gluonhq:charm-ios:3.0.0'
    desktopRuntime 'com.gluonhq:charm-desktop:3.0.0'
}

jfxmobile {
    android {
        manifest = 'src/android/AndroidManifest.xml'
        androidSdk = 'C:/Users/ee209275/AppData/Local/Android/Sdk'
    }
    ios {
        infoPList = file('src/ios/Default-Info.plist')
        forceLinkClasses = [
                'com.gluonhq.**.*',
                'io.datafx.**.*',
                'javax.annotations.**.*',
                'javax.inject.**.*',
                'javax.json.**.*',
                'org.glassfish.json.**.*'
        ]
    }
}

A: You need to update the Gluon plugin for your IDE, so you can generate a project with updated dependencies. Current versions of the plugin are 2.5.0 for NetBeans and IntelliJ, 2.4.0 for Eclipse.
For a single view project, this will be the build.gradle file you will get:
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'org.javafxports:jfxmobile-plugin:1.3.6'
    }
}

apply plugin: 'org.javafxports.jfxmobile'

repositories {
    jcenter()
    maven {
        url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
    }
}

mainClassName = 'com.gluonhq.testplugin.GluonTestPlugin'

dependencies {
    compile 'com.gluonhq:charm:4.3.5'
}

jfxmobile {
    downConfig {
        version = '3.3.0'
        // Do not edit the line below. Use Gluon Mobile Settings in your project context menu instead
        plugins 'display', 'lifecycle', 'statusbar', 'storage'
    }
    android {
        manifest = 'src/android/AndroidManifest.xml'
    }
    ios {
        infoPList = file('src/ios/Default-Info.plist')
        forceLinkClasses = [
                'com.gluonhq.**.*',
                'javax.annotations.**.*',
                'javax.inject.**.*',
                'javax.json.**.*',
                'org.glassfish.json.**.*'
        ]
    }
}

You have an issue with the Android SDK path. This question shows how to solve it.
Basically:

*

*Open the Android SDK Manager and make sure you have installed Extras/Google Repository and Extras/Android Support Repository.

*Remove the androidSdk line from the android block on your build.gradle file and move it to a properties file. For that, just create a properties file under C:\Users\<user>\.gradle\gradle.properties, and add the ANDROID_HOME variable: ANDROID_HOME=C:/<path.to.Android>/sdk.
Then reload your project, see that it works on desktop, and then deploy to mobile.


text:
Q: Rails: Multiple layouts with Devise How can I have a completely different layout depending on wether a user is logged in or not?

A: Follow the instructions at
https://github.com/plataformatec/devise/wiki/How-To%3a-Create-custom-layouts
and make the check be if the user is logged in, which for devise means checking
user_signed_in?, which is a devise helper.
Specifically:
class ApplicationController < ActionController::Base
  layout :layout_by_resource

  protected

  def layout_by_resource
    if user_signed_in?
      "special_layout_name_for_logged_in"
    else
      "application"
    end
  end
end

and put the special_layout_for_logged_in.html.erb view file in the layouts directory.


text:
Q: Commuting diagonalisable matrices are simultaneously diagonalizable
Possible Duplicate:
Simultaneous diagonalization

If $A$ and $B$ are diagonalisable matrices such that $AB=BA$, prove that there exists an invertible matrix $P$ such that $P^{-1}AP$ and $P^{-1}BP$ are diagonal matrices.

If such $P$ exists, the columns of $P$ must be eigenvectors of $A$ and $B$, right? So we need to prove that $A$ and $B$ have exactly the same eigenvectors. If $x$ is an eigenvector of $A$ associated to an eigenvalue $\lambda$, then $ABx=BAx=B\lambda x=\lambda Bx$. So $Bx$ is also an eigenvector of $A$. I'm not sure how to continue from here.


text:
Q: Find an example of a continuous function and open (closed) A such that f(A) is not open(closed) for a continuous function and open A such that f(A) is not open. I think $f:R \rightarrow R$, and $f(A)=0 $ for $A \in (0,1)$ works. since a singe point in $R$ is closed.
I have no idea to find a continuous function and closed A such that f(A) is not closed.

A: Let $f(x) = e^{-x^2}$ and $A= \mathbb{R}$.
Then $f(\mathbb{R}) = (0,1]$ which is neither open nor closed.
$A$ is both open and closed.


text:
Q: WARNING:tensorflow:Model was constructed with shape (None, ....) I have a classification problem (0 or 1) with 78 features.
Let's say I have that data in a dataframe with 78 columns and 202 rows, each cell value holding an integer in the range [0, infinity).
Trying to achieve prediction with TensorFlow, when I fit my model I get the following warning:
WARNING:tensorflow:Model was constructed with shape (None, 101, 78) for input Tensor("input_2:0", shape=(None, 101, 78), dtype=float32), but it was called on an input with incompatible shape (101, 78).

I would have thought my shape definition was correct, so why am I getting this warning? Perhaps I'm misunderstanding how to use the framework.
X_train, X_test, y_train, y_test = train_test_split(df_x, series_y, random_state=1, test_size=0.5)
numpy_x_train = X_train.to_numpy()
numpy_y_train = y_train.to_numpy()
numpy_x_test = X_test.to_numpy()

shape_x = len(X_train)
shape_y = len(X_train.columns)
inputs = keras.Input(shape=(shape_x, shape_y))

x = Rescaling(scale=1.0 / 255)(inputs)

num_classes = 1
outputs = layers.Dense(num_classes, activation="softmax")(x)

model = keras.Model(inputs=inputs, outputs=outputs)
processed_data = model(numpy_x_train)

optimiser = keras.optimizers.RMSprop(learning_rate=1e-3)
loss = keras.losses.CategoricalCrossentropy()

model.compile(optimizer=optimiser, loss=loss)

history = model.fit(numpy_x_train, numpy_y_train, batch_size=32, epochs=10)

A: here a full example based on your problem. you have 2D data so in the input layer you have to specify only the feature dimension and not also the sample dimension. you also are carrying out a binary classification task so the best choice is to use a final dense layer with 1 dimension, a sigmoid activation function, and binary crossentropy as a loss. the predicted class will be 1 if the prob are > 0.5 otherwise it is 0
from tensorflow import keras
import numpy as np

# create dummy data
train_size, test_size = 101, 101
n_features = 78
num_classes = 2 # 0 or 1

numpy_x_train = np.random.uniform(0,256, (train_size,n_features))
numpy_y_train = np.random.randint(0,num_classes,train_size)
numpy_x_test = np.random.uniform(0,256, (test_size,n_features))
numpy_y_test = np.random.randint(0,num_classes,test_size)

# rescaling data
numpy_x_train = numpy_x_train / 255
numpy_x_test = numpy_x_test / 255

# define model
inputs = keras.layers.Input(shape=(numpy_x_train.shape[1],))
outputs = keras.layers.Dense(1, activation="sigmoid")(inputs)

optimiser = keras.optimizers.RMSprop(learning_rate=1e-3)
loss = keras.losses.BinaryCrossentropy()

model = keras.Model(inputs=inputs, outputs=outputs)
model.compile(optimizer=optimiser, loss=loss)

history = model.fit(numpy_x_train, numpy_y_train, batch_size=32, epochs=10)

# get test predictions
test_prob = model.predict(numpy_x_test).ravel()
test_class = (test_prob>0.5)+0 # if prob > 0.5 is 1 else is 0


text:
Q: Why are my identifiers marked as not CLS-compliant? I have a some class, which contains three fields:
protected bool _isRunning = false;

protected readonly ParameterCollection _parameters = null;

protected readonly ParameterCollection _defaultParameters = null;

The assembly it is in is marked as CLS-compliant (it is needed), and Visual Studio 2010 says that those three fields' identifiers are not CLS-compliant. What is wrong with them?
P.S.: ParameterCollection is a class, derived from KeyedCollection, if it is important information.

A: Here is the answer from Microsoft, from Name <membername> is not CLS-compliant:

To correct this error
If you have control over the source code, change the member name so that it does not begin with an underscore.
If you require that the member name remain unchanged, remove the CLSCompliantAttribute from its definition or mark it as . You can still mark the assembly as <CLSCompliant(True)>.

A:
what's wrong with them?

They start with an underscore.
For more details, see here:
According to MSDN:

CLS-compliant language compilers must follow the rules of Annex 7 of
  Technical Report 15 of the Unicode Standard 3.0, which governs the set
  of characters that can start and be included in identifiers. This
  standard is available at
  http://www.unicode.org/unicode/repor...5/tr15-18.html. For two
  identifiers to be considered distinct, they must differ by more than
  just their case.

from Unicode Standard 3.0 Technical Report 15, Annex 7:
That is, the first character of an identifier can be an uppercase letter,
lowercase letter, titlecase letter, modifier letter, other letter, or letter
number. The subsequent characters of an identifier can be any of those, plus
non-spacing marks, spacing combining marks, decimal numbers, connector
punctuations, and formatting codes (such as right-left-mark). Normally the
formatting codes should be filtered out before storing or comparing
identifiers.

A: To be CLS compliant, identifiers must follow the guidelines in Annex 7 of Technical Report 15 of the Unicode Standard (MSDN). This includes the requirement that the first character be a letter (source).


text:
Q: Use distinct in php MongoDB query In my cars_positions database and positions collection I have this kind of data :
db.positions.find()
{ "_id" : ObjectId("536a5cd9e9df25cd8609d286"), "car" : { "type" : "sport", "ref" : "nameOfTheCar1" }, "position" : { "dateTime" : "2014-05-06T06:42:10", "latitude" : "0000.1111", "hemesphere" : "S", "longitude" : "05563.1254"}}
{ "_id" : ObjectId("536a5cd9e9df25cd8609d287"), "car" : { "type" : "sport", "ref" : "nameOfTheCar2" }, "position" : { "dateTime" : "2014-05-06T06:43:11", "latitude" : "0000.1111", "hemesphere" : "S", "longitude" : "05563.1254"}}

I'm trying to use a distinct into my mongodb query. Here is my current query where I need to iterate all the data to create a proper array with only the last position:
    $pipeline =
        [
            [
                '$match' =>
                    [
                      'car.ref' => ['$in' => $cars],
                      'position.dateTime'  =>
                            [
                                '$gte' => $period['start'],
                                '$lte' => $period['end'],
                            ],
                    ],
            ],
            [
                '$sort' =>
                    [
                      'position.dateTime' => 1,
                    ],
            ],
            [
                '$group' =>
                    [
                      '_id' => ['car.ref'],
                      'lastposition' => ['$last' => '$position'],
                    ],
            ],
        ];

        $command = new \MongoDB\Driver\Command($pipeline);
        $cursor = $mongo->executeCommand('mybase.positions', $command);

Original post with the original query : http://pastebin.com/BEC7nUa7
What I would like to achieve is to have a distinct on the car.ref and only get the latest location of any car in the $cars array with the date range.
So I could have a final array like this :
array (size=1)
  car1 =>
    array (size=8)
      'car.ref' => string 'car1' (length=7)
      'dateTime' => string '2017-01-18T00:00:09' (length=19)
      'latitude' => string '0000.1111' (length=9)
      'hemesphere' => string 'S' (length=1)
      'longitude' => string '05563.1254' (length=10)
   car2 =>
   car3 =>

Any idea ? Thanks !

A: You will need aggregation. Try something like below.
<?php

    $mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017");

    $cars = ['nameOfTheCar1', 'nameOfTheCar2'];

    $start = new \MongoDB\BSON\UTCDateTime(strtotime('2012-05-06T06:42:10') * 1000);
    $end = new \MongoDB\BSON\UTCDateTime(strtotime('2014-05-06T06:42:10') * 1000);

    $pipeline =
        [
            [
                '$match' =>
                    [
                      'car.ref' => ['$in' => $cars],
                      'position.dateTime'  =>
                            [
                                '$gte' => $start,
                                '$lte' => $end,
                            ],
                    ],
            ],
            [
                '$sort' =>
                    [
                      'position.dateTime' => 1,
                    ],
            ],
            [
                '$group' =>
                    [
                      '_id' => '$car.ref',
                      'lastposition' => ['$last' => '$position'],
                    ],
            ],
        ];

    $command = new \MongoDB\Driver\Command([
        'aggregate' => 'positions',
        'pipeline' => $pipeline
        ]);

    $cursor = $mongo->executeCommand('mybase', $command);

    foreach($cursor as $key => $document) {
        var_dump($document);

    }
?>


text:
Q: Resize blob image without creating tmp file I have a scenario where i need to resize thousands of images. I am using MiniMagick to do this.
image = MiniMagick::Image.read(<blob>)
image.resize "100x100"
Image.create(:img => image.to_blob)

But the above code takes too long to process large number of images since it creates a tmp image file for each image it processes.
Is there a way to resize the image without creating the tmp file? I am also open to suggestions on other libraries that can speed up the processing.

A: Try using convert command available from imagemagic directly on the image as :
`convert source.jpg -resize 120x120 thumbnail.jpg`

Hope this helps you :)


text:
Q: Doesn't the non-commutivity of $x$ and $p$ complicate the measurement of a quantum system's (e.g.) Energy? A classical system is parameterized by $x$ and $p$ coordinates, and so any other observable -- such as energy -- is some function $E(x,p)$ of them.  I assume, then, that to measure the energy one must measure $x$ as well as $p$ and then place them into the formula.
Nothing analogous can hold for a quantum system's energy.  As is well known, I can measure $x$ and then I can measure $p$, but I cannot construe those values as having jointly obtained at any common time.  It would be nonsense to put them both into any formula.
Quantum "measurement" is hopelessly idealized in the standard undergrad treatment, and so I try to imagine the actual procedure someone would make use of to learn the energy.  Yet I cannot.  The argument above would show (if it succeeds) that a measurement of energy would have to access it "directly" (whatever that means), instead of as a function of other non-commuting quantities.
Does this make energy a more fundamental thing in QM than it was in CM?  In CM you can just say "Oh energy is some conserved function, and obviously it's handy to know conserved functions.  That's all it is."

A: In QM, performing a measurement perturbs the system with the probe you're measuring with. The state of the system before and after the measurement are different.
For example, you want to measure the energy of the system using a photon. Before the measurement the system was in the ground state. You probe the system with a single photon, say from a laser source, which is absorbed by the system. The system is now in an excited state. After some time, the system returns to the ground state, releasing a photon, which is then detected by your detector.
Your measurement data is then whether a photon is detected at the detector (which confirms that the excited state was available to the system), the energy of the photon that was detected (which can be different from your probe, in the case of phosphorescence and fluorescence), and the time elapsed between the photon you sent out and the photon you detect. All three measurements are limited by your experimental setup (for instance, sensitivity of the detector).
Say, instead of measuring the energy, you want to measure the momentum using electron scattering. You shoot an electron beam to the system (because using a single electron might not be enough due to the finite cross-section). The electron beam is then scattered by both the ions and electrons in the system, which at the same time also perturbs the electronic density of the system. You then use an analyzer to separate the scattered electrons with different momenta. Your measurement data is then the number of electrons that are scattered at a specific solid angle (where you place your analyzer), and the magnitude of the momentum of the analyzed electron (higher momentum = higher deflection in the analyzer). From there, you can analyze the composition of the system. This measurement technique is in common use in experimental condensed matter to investigate atomic structures, known as low-energy electron diffraction (LEED).
Furthermore, if the system was in an entangled state before the measurement, the measurement collapses the system into a single eigenstate. The fact that measurement is a non-reversible process is one of the basic tenets of quantum information.


text:
Q: How to read data faster in Qt? Does Qt read database slower than C#? I think I am missing something! To compare reading speed I have written folllowing in Qt
QElapsedTimer t;
t.start();
int count = 0;
QString cs = "Driver={SQL Server}; Server=EMON;Database=FAODB;User=Test;Password=Test";
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC",cs);
db.setDatabaseName(cs);
db.open();
QSqlQuery query(db);
query.setForwardOnly(true);
query.exec("SELECT * FROM FAOCropsLivestock");
while(query.next()){
    if(query.value("Country").toString() == "\"Bangladesh\"")
        count++;
}
db.close();
qDebug()<< QString::number(count) + " elapsed ms " + QString::number(t.elapsed());

and in C#
Stopwatch s = new Stopwatch();
s.Start();
int count = 0;
string cs = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
string query = "SELECT * FROM FAOCropsLivestock";
using(SqlConnection con = new SqlConnection(cs)){
      using(SqlCommand cmd = new SqlCommand(query, con)){
            con.Open();
            SqlDataReader rd = cmd.ExecuteReader();
            while (rd.Read()){
                  if(rd["Country"].ToString() == "\"Bangladesh\"")
                        count++;
            }
      }
}
s.Stop();
Console.WriteLine(count + " elapsed ms " + s.ElapsedMilliseconds);

Both C# and Qt are for x86 and on Release mode.
In Qt's case the result was "63653 elapsed ms 68213"
and in C# "63653 elapsed ms 14210"

For Qt version I have replaced
QString cs = "Driver={SQL Server}; Server=EMON;Database=FAODB;User=Test;Password=Test";
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC",cs);
db.setDatabaseName(cs);

by
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC" /*QODBC3*/);
db.setDatabaseName("Driver={SQL Server Native Client 11.0};"\
                   "Server=EMON;Database=FAODB;Uid=Test;Pwd=Test;");

Results were in between 58s - 71s.

A: For your C# version, you don't show your connection string. Are you using the same drivers for both? I'm not an expert on this, but my colleague who is says that the "SQL Server" driver is very, very old and slow. You probably want to try "SQL Native Client" or something along those lines. Either way, be sure that the test is using the same SQL driver.


text:
Q: What is the dual of the stable infinity category of perfect complex on smooth proper variety? Fix a commutative ring $R$.
Lurie proved that smooth proper $R$-linear stable infinity categories are dualizable in $\text{Cat}^\text{perf}_{R,\infty}$.
For a smooth proper variety $X$ over $R$, what is the dual of the category of perfect complexes on $X$ in $\text{Cat}^\text{perf}_{R,\infty}$?

A: It is self-dual. In general the dual of a smooth proper $R$-linear $\infty$-category $C$ is always $C^{\operatorname{op}}$, but for a scheme $X$ we have $\operatorname{Perf}(X) = \operatorname{Perf}(X)^{\operatorname{op}}$ via the monoidal duality.
An alternative perspective is the following: For a general qcqs scheme $X$ over $R$, $\operatorname{QCoh}(X)$ is self-dual in $\operatorname{Pr}^{\operatorname{L}}_R$ via the pairing $(\mathcal F,\mathcal G) \mapsto \Gamma(\mathcal F\otimes \mathcal G)$ (in other words, $\operatorname{QCoh}(X)$ is a commutative Frobenius algebra in $\operatorname{Pr}^{\operatorname{L}}_R$, see SAG Corollary 9.4.3.4). The assumption that $X$ is smooth resp. proper over $R$ guarantees that the coevaluation resp. the evaluation preserves perfect complexes, so when it is smooth and proper the self-duality restricts to one in $\operatorname{Cat}^{\operatorname{perf}}_R$.
ETA: Let me be more precise about the last sentence, since the geometric properties "smooth" and "proper" by themselves do not exactly correspond to the categorical ones. For the global section functor $\Gamma\colon \operatorname{QCoh}(X)\to \operatorname{Mod}_R$ to preserve perfect complexes, one needs $X$ to be proper, of finite presentation and of finite Tor-amplitude. On the other hand, the coevaluation is given by pushing forward the structure sheaf along the diagonal $\delta\colon X\to X×_R X$. If $X$ is smooth and separated over $R$ then $\delta$ is proper, of finite presentation and of finite Tor-amplitude, so that $\delta_*$ preserves perfect complexes.


text:
Q: PHP - Getting wrong result when selecting from two tables I have been trying to get some results when selecting combo boxes.
here is my query:
$strSQL = "SELECT * FROM studentresult,student where studentresult.studentid=student.id and student.class='$classes' and term='$term'and studentresult.studentid=student.id and year='$year' ";

This query is returning all the studentresult.id = 2 where studentresult.id is primary.
This is the php code:

<?=$objResult["id"];?>

<?=$objResult["studentid"];?>

    <?=$objResult["subjectid"];?>
    <?=$objResult["marks"];?>

<?=$objResult["term"];?>

    <?=$objResult["year"];?>
    <?=$objResult["rank"];?>

The id is taken from student table rather than being taken from studentresult table. Can someone help me with this.
EDIT 1:
The id is present in both tables

EDIT 2:
Student result:
id| StudentID| SubjectID| Marks| Rank| Term| Year

Student:
id| Roll Num| class| Name| Surname

Thanking You In Advance
Bhaamb

A: $strSQL = "SELECT *,studentresult.id as stid FROM studentresult,student where studentresult.studentid=student.id and student.class='$classes' and term='$term'and studentresult.studentid=student.id and year='$year' ";

Then

<?=$objResult["stid"];?>

A: You Better specify the column names instead of (*) from both the tables alias the column names to avoid column name conflicts if both are same and also try to use Join(Inner or Left) based on the need.
for example, some thing like this:
SELECT S.id AS student_id, SR.id as StudentResultId, S.class, s.year
FROM studentresult AS SR
INNER JOIN student AS S
WHERE SR.studentid=S.id and S.class='$classes' and s.term='$term'and SR.studentid=s.id and s.year='$year'

A: First of all, why do you use this twice in the where clause?
studentresult.studentid=student.id
Please define all needed columns explicitly while joining tables having the same column names, e.g.
SELECT studentresult.id as sr_id, student.id as s_id ... FROM ...
and change it in your php code:
<?=$objResult["sr_id"];?>


text:
Q: How to use GOOGLE_APPLICATION_CREDENTIALS with gcloud on a server? What is the simplest way to use the gcloud command line non-interactively with a Service Account outside of GCE? Preferably without littering the file system with credentials files, which is what gcloud auth activate-service-account --key-file=... does.
There are many use cases for using gcloud with a service account. For example, on a server, I would like to test that the GOOGLE_APPLICATION_CREDENTIALS is correctly set and has the required permissions before running my application. Or, I would like to run some setup scripts or cron scripts that perform some check with the gcloud command line.
Google Cloud libraries (e.g. python, java) automatically use the environment variable GOOGLE_APPLICATION_CREDENTIALS to authenticate to Google Cloud. But unfortunately, this command line seems to have no effect on gcloud. What is a clean way to use gcloud while leaving the filesystem intact?
$ GOOGLE_APPLICATION_CREDENTIALS=/etc/my-service-account-4b4b6e63aaed.json gcloud alpha pubsub topics publish testtopic hello
ERROR: (gcloud.alpha.pubsub.topics.publish) You do not currently have an active account selected.
Please run:

  $ gcloud auth login

to obtain new credentials, or if you have already logged in with a
different account:

  $ gcloud config set account ACCOUNT

to select an already authenticated account to use.

A: 1) Create a ServiceAccount in GCP IAM. Check the box to "Furnish a new private key", and select JSON as the file type.
2) Download the JSON file to your server, and type:
gcloud auth activate-service-account --key-file serviceaccount.json
3) Verify credentials were applied by running gcloud auth list.

A: gcloud generally does not use GOOGLE_APPLICATION_CREDENTIALS environment variable. It only has some commands to facilitate setting up these application default credentials in gcloud auth application-default [login|revoke|print-access-token...].
By default gcloud stores its configuration in ${HOME}/.config/gcloud. It is possible to override that location by setting CLOUDSDK_CONFIG environment variable.
Also it is possible (though more tedious) to override most setting so that they do not need to be preconfigured via gcloud config set ... and/or gcloud auth activate-service-account. For each setting one can specify environment variable.
For example the equivalent command you tried to use service account key file would be:
$ CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE=/etc/my-service-account-4b4b6e63aaed.json \
    gcloud alpha pubsub topics publish testtopic hello

Note that this will still cache credentials in CLOUDSDK_CONFIG since it needs to cache access-token, so that it wont have to refresh it on each invocation.
For your use case best option in my view would be

*

*Set CLOUDSDK_CONFIG to some temp directory

*gcloud auth activate-service-account --key-file=...

*... use gcloud to do your work ...

*Remove temp CLOUDSDK_CONFIG directory.

A: Have you look at the --account option? Like
$gcloud --account="foo" ...

(Reference)
Regarding "Preferably without littering the file system with credentials files", I am not sure if it possible to achieve.

A: if you already have the env-var and json key, just run:
gcloud auth activate-service-account --key-file=$GOOGLE_APPLICATION_CREDENTIALS

this will activate the service account for gcloud/gsutil