Synthetic datasets for concept drifting data

Question: Is there any synthetic / artificial datasets for concept drifting data? I want to visualize the performance of some clustering algorithm when data experiences concept drift and changes over time.
Comment: As a question about *synthetic* datasets to illustrate or investigate a statistical phenomenon, this is more suitable for CV than OpenData in my opinion.
Comment: Apologies: CV = CrossCalidated, this site. Questions about data sets are usually considered off topic here and encouraged to go to another site like [OpenData.SE] instead. My contention was that this question seemed suitable here, though other people may disagree with me.
Answer: This is a tough question. "Concept drift" is a highly abstracted term that assumes a well developed methodological protocol of text-based constructs temporal evolution. This protocol does not exist, yet.
Standard time series solutions are very well-developed for continuously distributed information, are focused on the analysis of HAC residuals and, obviously, include the variants of Holt-Winters decompositions, exponential smoothing, Box-Jenkins, ARCH, GARCH, HARCH functional forms, spectral decompositions, and so on. Take your pick.
Nonstandard approaches to longitudinal clustering of principal components originated in the 70s with guys working in the (then) hot area of multidimensional scaling and were based on higher order tensor ranks and SVD decompositions such as CANDECOMP and PARAFAC or Pieter Kroonenberg's three-mode approaches:
http://three-mode.leidenuniv.nl/
Time series clustering has been getting a lot of attention in recent years. One excellent overview is Aggarwal and Reddy's book, Data Clustering. However, temporal clustering of conceptual constructs is not a well developed topic in their collection of essays.
Andreas Brandmaier's Permutation Distribution Cluster (PDC) approach to clustering aperiodic time series is well developed conceptually as well as offering routines that can be run in R.
https://cran.r-project.org/web/packages/pdc/pdc.pdf
Your challenge is different from so-called "off the shelf" methods like these. The problem is that even cross-sectional, text-based analysis is a wild, wild west of competing solutions -- without even introducing a temporal component.
Honestly though, I think some of the most interesting solutions aren't strictly focused on concept "clustering," which implies a mostly statistical answer, but are more involved with dimension reduction and the longitudinal evolution of core constructs. For instance, computational sociologists interested in the drift of concepts fundamental to American political history have done some terrific work building on social network-type analyses that include some stunning visuals. Visit this paper by Peter Bearman, at Columbia's INCITE Center which is an analysis of over 200 years of US Presidential State of the Union addresses and the evolution of core constructs underlying them, Lexical shifts, substantive changes, and continuity in State of the Union discourse:
http://www.pnas.org/content/112/35/10837.full.pdf
Bearman also has a paper on Big Data and Historical Social Science which raises concerns about, e.g., "answering previously largely intractable questions about the timing and sequencing of events, and of event boundaries...based on accounts which rest on narrative sentences."
http://bds.sagepub.com/content/spbds/2/2/2053951715612497.full.pdf
Given all of that as background, is there data which presumes concept drift? One possible source are the Large Scale Hierarchical Text Classification Challenges"
http://lshtc.iit.demokritos.gr/
DMOZ is another possible source since it has text metadata with a temporal component, although it likely the case that you may have to define and build the constructs yourself.
http://www.dmoz.org/about.html
Goggle's GDELT project might be another option:
http://gdeltproject.org/#intro
I've always liked the Million Song Database which has millions of pop song features dating back to the 1960s:
http://labrosa.ee.columbia.edu/millionsong/
Here's a paper on the evolution of genres of pop music that is based on that data:
http://www.armandmarieleroi.com/wp-content/uploads/2015/02/dopdyn_10.02.15.pdf
And here's a paper on music and aesthetic analysis called *cantometrics":
http://research.culturalequity.org/psr-history.jsp
Yelp just released 13T of research data that may work for you:
https://www.yelp.com/academic_dataset
And, here's a laundry list of data sources in Github that may have something useful:
http://www.datasciencecentral.com/profiles/blogs/great-github-list-of-public-data-sets?utm_content=buffer484a2&utm_medium=social&utm_source=linkedin.com&utm_campaign=buffer
Apologies for the lack of canned, easy solutions. Good luck!
Comment: On a separate but related thread, @whuber cites Mosteller and Wallace's book Applied Bayesian and Classical Inference, urging the OP to read it. Needless to say, it's a $50 purchase on Amazon, even used. So, I looked it up in Google Books. Whuber is absolutely right, it is a treasure trove in text analysis...terrific read.  https://books.google.com/books?id=LJXaBwAAQBAJ&printsec=frontcover&dq=applied+bayesian+and+classical+inference&hl=en&sa=X&ved=0ahUKEwjCu9-F6IPLAhWMWz4KHcmpBNYQ6AEIJjAA#v=onepage&q=applied%20bayesian%20and%20classical%20inference&f=false
Comment: Here's an additional, related paper that looks at the historic origins of modern mathematics. Lots of useful metrics and analyses of concepts, paradigms, drift, etc.  http://arxiv.org/pdf/1603.06371v1.pdf


Synchronize data between 2 sites dynamically

Question: I currently have two Drupal sites and I would like to synchronize in a specific way the data of each one.
More precisely, the first one contains detailed informations and the other only has the main data necesary for its work. I would like to refresh (create/update) the data of the second one when the first one is modified and also would like to refresh (create/update) the first one when the second one is modified, taking into account the content types and field names are not the same in both. In my case, the data that should be manipulated are nodes and users.
I have already tried to find solutions through web services or feed import, but I didn't succeed to build a correct one. Moreover, I also studied the possibility to schedule periodic import from web services but it would be slow the site performance, due to the very important amount of data contained in each site.
Can someone help me?
Comment: **Domain Access** allows for sharing content among sites hosted within a same drupal install. It might be worth a look : https://www.drupal.org/project/domain
Comment: Well, in fact, the two sites don't have the same drupal install. There are really independent and each one has its own database, so I think I can't use this module to do what I want. Thanks for the answer :)
Comment: Agreed. If going for a multi-site in a single drupal instance is not an option Domain Access won't do.
Answer: You need to work on the database a little bit.
I think it is impossible to make it work if you just write php. Because it will generate a lot of database login errors.
There might be a lot of ways to do that, but the only way I know is to:
First, Combine two database into one, two different databases with two different prefix.
Second, delete all the attributes you want to synchronize in the second database.
Third, link the synchronized field in the second database to the first database, you can do this in the settings.php in the second drupal site.
But there might be some dependency problems when you do step 2. Don't forget to backup at first.
This link might be helpful How to connect to multiple databases within Drupal


Python exercise TypeError: 'str' object is not callable

Question: When trying to run this Python exercise:
s = 'azcbobobegghakl'
num = 0

for i in range (len(s)):
    if s[i:i+3]== 'bob':
    num +=1
print('Number of times bob occurs is: ' + str(num))

I get this error, TypeError: 'str' object is not callable, on the last line. I'm a bit confused because I already turned it in at the site I'm learning from, and it was signed as correct. Can anyone here give me a hint?
Comment: If I were to guess, you're using 'str' as a variable name (instead of 's' in your real code)?
Comment: That code works fine.
Comment: Yup. I "third" that. It works fine.
Comment: Yeah your code runs fine.
Comment: Just to add to the chain of messages saying 'it works fine': tested in both python 3.6 and python 2.7 and works fine.
Answer: You code works fine. Like a user mentioned in the comments, you have probably assigned a string to a variable named str. Here is an example of why you would get this error:
str = "test"
s = 'azcbobobobegghakl'
print (s.count("bob"))
num = 0

for i in range (len(s)):
    if s[i:i+3]== 'bob':
        num +=1
print('Number of times bob occurs is: ' + str(num))

If you execute this, you get:
Traceback (most recent call last):
  File "Untitled.py", line 2197, in <module>
    print('Number of times bob occurs is: ' + str(num))
TypeError: 'str' object is not callable

This is because you have defined str as variable and assigned it to a string "test". Therefore, python thinks you are trying to call this variable on the variable num and since a string object is not callable, it returns an error. Therefore, you should look through any code you have not posted here and find any variables named str and change the name of it to something else. Never use words like int, len, or str for your variable names. It messes with python real bad.
P.S. If this is not the case and you do not have any variables named str, then I'm happy to delete my answer.
Comment: @SmoothLeggedWookie that's no problems. It always happens to new users of python. Anyway, Good luck with whatever you are trying to accomplish.
Comment: Guilty! thank you very much :p *deep shame*


Is intuitionist logic two-valued?

Question: On this page https://en.wikipedia.org/wiki/Principle_of_bivalence :

Intuitionistic logic is a two-valued logic but the law of excluded middle does not hold.

On this page https://en.wikipedia.org/wiki/Truth_value :

In intuitionistic logic, and more generally, constructive mathematics, statements are assigned a truth value only if they can be given a constructive proof. It starts with a set of axioms, and a statement is true if one can build a proof of the statement from those axioms. A statement is false if one can deduce a contradiction from it. This leaves open the possibility of statements that have not yet been assigned a truth value. Unproven statements in intuitionistic logic are not given an intermediate truth value (as is sometimes mistakenly asserted). Indeed, one can prove that they have no third truth value, a result dating back to Glivenko in 1928.[3]
Instead, statements simply remain of unknown truth value, until they are either proven or disproven.

Could you explain to me what does it mean ? Is intuitionist logic two-valued and there is a subtlety, or is the first quote wrong as asserted by the second ?
Comment: If a statement gets a value, its value is either "true" of "false". No statement can get both values (non-contradiction holds). However, unlike classical logic, not every statement gets a value (excluded middle doesn't hold).
Comment: As I understand these words, intuitionistic logic is not necessarily two-valued. It can be, though.
Comment: > Is intuitionist logic two-valued and there is a subtlety, or is the first quote wrong as asserted by the second ?

The former. Statements have one of two values; just sometimes we don't know which. There is no third truth value.
Comment: There are models of intuionistic models which have, from the external perspective, more than two truth values, but this applies equally to classical logic and has nothing to do with the LEM or anything. How many truth values your model has can not be recognised from the inside (i guess you can add extra constants and axioms to force such an interpretation)
Answer: First, give us a definition of what it means for a logic to be $n$-valued; then, we'll be able to tell whether intuitionistic logic is 2-valued or not.
Since there is no standard, widely-accepted notion or definition of "$n$-valued logic" at all, discussion regarding whether a given logic is $n$-valued or not tend to be very confused at best. The discussion on Wikipedia is no exception in this regard.
One could define many different notions of $n$-valuedness. Below, I consider four possible such definitions.

In algebraic logic, one has a notion of $n$-valued semantics. This is not the definition we have in mind when we say that classical logic is 2-valued, since, while classical propositional logic has a complete 2-valued semantics, it also has a complete 4-valued semantics, where the four possible truth values are the sets $\emptyset, \{1\}, \{2\}, \{1,2\}$, conjunction is interpreted as intersection, and the negation of $x$ is interpreted as the relative complement $\{1,2\} \setminus x$. Saying that classical logic is therefore a 4-valued logic would be weird and confusing, to say the least. On the other hand, intuitionistic logic cannot have a complete $n$-valued semantics for any natural number $n$.

We could also try to pin down the notion of $n$-valuedness internally, without committing to a particular semantics. E.g. one could say that a subsystem of classical logic has no more than $n$ truth values if $$\bigvee_{0 \leq i \leq n} \bigvee_{0 \leq j < i} (A_i \leftrightarrow A_j)$$ is a tautology, i.e. out of every $n$ formulas, at least two are logically equivalent. Then, as expected, classical logic has no more than 2 truth values since $(A_1 \leftrightarrow A_0) \vee (A_2 \leftrightarrow A_0) \vee (A_2 \leftrightarrow A_1)$ is a classical tautology, and is not $1$-valued since $A_1 \leftrightarrow A_0$ is not a classical tautology. However, using the disjunction property, one can again show that intuitionistic logic is not $n$-valued in this sense for any $n \in \mathbb{N}$.

The Wikipedia page links a Stanford Encyclopedia of Philosophy article, which implicitly uses another ad-hoc definition of truth value. The basic story is as follows: we can say that a logic "admits $n$ truth values" if we can find $n$ formulas $f_1(P),\dots,f_n(P)$ in one free propositional variable $P$, so that we can prove $f_i(P) \rightarrow \neg f_j(P)$ for all $i \neq j$, and for each $f_n$ we can find some formula $X_n$ for which $f_n(X_n)$ has a proof in our logic. In this sense classical logic admits at least 2 truth values: we can take $f_1(P) = P$, $X_1 = P \vee \neg P$,  $f_2(P) = \neg P$ and $X_2 = P \wedge \neg P$. Using a result from Glivenko's 1928 paper, one can show that it's not possible to extend this set $f_1,f_2$ with any third $f_3$ and $X_3$, even in intuitionistic logic: no "third truth value" is ever taken. Using later results of Rieger and Nishimura, one can prove a much stronger statement: for any 3 formulas $A_1,A_2,A_3$ in one free propositional variable $P$, at least one of $A_i \rightarrow A_j$ with $i \neq j$ is always an intuitionistic tautology. In this sense, intuitionistic logic admits only two truth values, as does classical logic.

There are, of course, systems that people traditionally call systems of many-valued logic, such as Łukasiewicz's 3-valued logic, or Belnap's four-valued logic. But these are just traditional names, and do not fall under any general definition of $n$-valued logic. In particular, intuitionistic logic is not usually included at all in the study of "many-valued logic".

Again, none of these definitions are standard or widely used across logic. This should answer your main question: there is a subtlety, namely that since "$n$-valuedness of a logic" doesn't actually have a standard definition, whether intuitionistic logic is two-valued or not will depend on the definition you choose to adopt.

Is intuitionist logic two-valued?


Evaluating $(1+x)(1+x^2)\ldots (1+x^{p-1})$ at pth roots of unity for odd primes p

Question: As part of a combinatorics question I was able to simplify it into evaluating $(1+x)(1+x^2)\ldots (1+x^{p-1})$ at pth roots of unity for odd primes p.
I have guessed and checked with a computer that this product is always $1$ except for when we use the root of unity $1$, in which case it's $2^{p-1}$ (the latter case is trivial)
I'm not sure how to prove that the product is $1$ for non $1$ pth roots of unity.
What I've tried:
Let $z$ be a pth root of unity that isn't equal to $1$.
Hence the product equals
$$ \prod_{k=1}^{\frac{p-1}2}(1+z^k)(1+z^{-k}) \quad\quad\text{(pairing opposite factors)}$$
$$ = \prod_{k=1}^{\frac{p-1}2}\left(2\cdot\cos\left(\frac{k\pi}{p}\right)\right)^2$$
However I see no way to go forward from here and prove the product equals $1$.
Comment: Maybe [this](https://math.stackexchange.com/questions/2095330/product-identity-multiple-angle-or-sinnx-2n-1-prod-k-0n-1-sin-left) helps.
Answer: First note that since $p$ is prime for any p-th root of unity $x$ we know that $-x$ is a p-th root of $-1$. Furthermore we know $X^p-1=\prod_{i=0}^{p-1}(X-x^i)$, thus we have $X^p+1=\prod_{i=0}^{p-1}(X+x^i)$ as by the above mentioned we know all roots of $-1$ hence we know how the polynomial factors(alternatively multiply the equation with $-1$ to obtain $-X^p+1=-\prod_{i=0}^{p-1}(X-x^p)=-(-1)^p\prod_{i=0}^{p-1}(-X+x^i)=\prod_{i=0}^{p-1}(-X+x^i)$ as p is odd, and presume as below with the only difference evaluating at $-1$ and adjusting the sign of $X$). Now we observe that $x^0=1$ hence we have $X^p+1=(X+1)\prod_{i=1}^{p-1}(X+x^i)$. Hence evaluating at $X=1$ yields $2=1^p+1=2\prod_{i=1}^{p-1}(1+x^i)$ i.e. $1=\prod_{i=1}^{p-1}(1+x^i)$.
Comment: I don't really understand how you went from the $X^p-1$ equation to the $X^p + 1$ equation by multiplying by $-1$.
Comment: I edited the post to make it more clear.
Comment: Thank you, but how come the sign of $x^i$ in the second product isn't alternating?
Comment: Made another edit , hopefully that answers your question.
Comment: If it is still unclear feel free to ask :)
Comment: No it all makes sense now. Thanks :)


uniformly continuous functions and measures

Question: Consider  a sequence of measures for which $\int f \, \mathrm{d}\mu_{n} \to \int f \,  \mathrm{d}\mu$ for all uniformly continuous functions $f$. Is it true that $\mu_n \to \mu$ strongly?
Answer: Consider $\mu_n$ an approximation to the identity; e.g. $$\mu_n = \frac n 2 \chi_{[-1/n, 1/n]} \lambda$$ for $\lambda$ the Lebesgue measure. Then $\int f\ d\mu_n \to \int f\ d\delta = f(0)$ for all continuous $f$; but $\mu_n({0})=0\to0\ne1=\delta({0})$.
Comment: i know this condition is almost that of weak convergence...but this condition is stated in a paper


Table with dynamic number of columns

Question: I have a table in which I display in the first line the current month
and I want to change the number of td in the second line whith ng-click function.
(if I click into a next button I get the next month and the number of td in the second tr become exactly the number of the day of this month(next month)
what I ve done :
$scope.nextMonth=function(month){
  var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
  var numMonth = months.indexOf(month);
  console.log(numMonth);
    if(numMois == 11){
      $scope.month= months[0];
    }
    else {
      $scope.month=months[numMonth+1];
    }
    $scope.nbrJrs = NbJourByMonth(numMonth,2016);
};

This is a screenshot of what I actually have :

Edit
and when I click next button I get this :

As you can see the month change but the number of td which refers to the number of day in the month doesn't change !! :(
In the view i have this :

<
{{month}}
>

  {{$index+1}}

and this is the range function :
  $scope.range = function (count) {
        var ratings = [];

        for (var i = 0; i < count; i++) {
            ratings.push(i)
        }
        return ratings;
    }

When I click into next flech I can change the name of the month and also I get the number of day in this month but the number of td doesn't change (I get 31 td I don't know how I can redraw the table.)
Can someone help me please ?
Comment: Having worked with angular recently, the best way to get help in this community is to build what you have so far in Plunker so we all can tinker with it - https://plnkr.co/
Answer: @Akino
One option, you could make the colspan of the TH to be (number of days in a month) -2 and bind that dynamically using Angular.

  <!- Placeholder for Left Nav Button -->
  {{currentMonth}}
  <!- Placeholder for Right Nav Button -->

    {{$index+1}}

Hope this helps!
Comment: thanks so much @user1461064 for your replay but this is exactly what I ve done in the Th which contain the name of the month (I ve edited my question)
Comment: you ve not understood my question I wasn't so clear .. I have just add a picture to explain the problem can you please look at **Edit** part ?
Comment: Ok sorry I misunderstood the question. Instead of using function "range" in the ng-repeat, what you can do is on click, when you call previousMonth or nextMonth, set the dates in scope.
`previousMonth = function() {
 ....
 $scope.currentMonthDays = [...];
 $scope.currentMonthName = '';
}

{{currentMonthName}}

{{$index+1}}

`
Comment: Ok @user1461064 thank you sooo much for your unswer . I worked with angular directives .. I put my DOM code in a template and  when I click next or previous button  I reload the DOM .. even if  the application has become slow in loading data from the BD but this resolve my problem.

Table with dynamic number of columns


Difference between stances in training acceleration for soccer

Question: To train acceleration for (American) football, I would start in the usual wide receiver stance and do 10, 20 yard runs, and up to perhaps 1 or 2 30 yard runs at the end.
However, for soccer, we don't start in the usual WR stance when we start running. We are usually jogging already or we will be at a stop/walking. Then when the ball comes our way, we start sprinting.
I am wondering if it is optimal to train acceleration starting in the WR stance. I am thinking of changing to the two point stance as shown in the picture below. The problem is that I do not know if it is optimal. I think that if I train in the WR stance, I will have a slow acceleration due to not being in the right position when I start running. However, I am sure I am much faster beginning in this stance. I am not sure, and I come to ask.
So, the question in short: Should I train acceleration starting in the WR stance or the two point stance as shown below (look at the white jerseys)
EDIT A third option I just thought about is to do the WR stance and emphasize one-legged exercises when weight-lifting.
Answer: I played Soccer for many years and the way that we always trained acceleration is to lay on your stomach with your arms out at the side of you. On the blow of a whistle, or even a mental "Go" push up from the ground and sprint for 10m or so.
The reason that this is a good starting point instead of positioning your feet like a sprinter is because in a game you are not going to be starting in any one position. There is a good chance you will either be mid turn or have to turn to sprint in the direction that you wish to go.
To make this even more effective try and use Mud or Sand to train on. Yeah, you won't play on either all that much, but if your trying to get up to speed then its all about the power of the push off with your legs, if you can do that easily then its not as good as if its really hard.
Answer: I dont't think the starting stance is essential for training acceleration.
As Martyn mentioned in his answer in soccer there're to many different situations to start a sprint from.
So we train acceleration/pace with different starting options:
1. lay on your stomach and push up from the ground (Martyn's answer)
2. lay on the back, turn around and push up
3. with your back in the direction of the run, so turn 180° and run
4. jump up with pulling your knees to your chest, then run
the distance should be about 10m.
Espacially for accenleration (and less for pace) set up tow markers at a distance of 10m. In between you're sprinting back and forth (3-6 times). So at each marker you have to slow down, turn around the marker, and start again with small fast steps.
This small fast steps after the markers are essential for acceleration in soccer. Not your starting position.


Error Parsing Data java.lang.IllegalStateException: Not on the main thread when trying to add a marker

Question: I am trying to update markers on Google map using a service, but when I use the "setParkingSpotMarker" function that add a marker to every item at the list I get an error "java.lang.IllegalStateException: Not on the main thread"
The function "setParkingSpotMarker" is called in the loop inside the service -DataUpdateService.
I don't know how to change my code so it will update the markers on the main thread.I have read some posts about that but didn't understand how to change it in my code.
this is the service:
 package com.example.sailon;
    import android.app.Service;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Binder;
    import android.os.IBinder;
    import android.util.Log;
    import java.util.ArrayList;
    import java.util.Timer;
    import java.util.TimerTask;

import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;

public class DataUpdateService extends Service {
    Timer myTimer = new Timer();
    MyTimerTask myTask = new MyTimerTask();
    MyMap mymap;
    String teamID;
    static LatLng teamLocation;
    ArrayList<TeamsList> teamsList= new ArrayList<TeamsList>() ;
    public ArrayList<UnitInHeatForMap> unitswithteam= new ArrayList<UnitInHeatForMap>();
    String action;
    Context fromContext;
   String CompName;
   String heatNum;
   boolean isSailor;
   String usermail;
   GPSTracker gps;

    private final IBinder mBinder = new LocalBinder();

    @Override
    public void onCreate() {
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("PS", "DataUpdateService onStartCommand");
        return Service.START_NOT_STICKY;
    }

    @Override
    // return thee instance of  the local binder to the activity
    public IBinder onBind(Intent intent) {
        Log.d("PS", "DataUpdateService onBind");
        return mBinder;
    }

    public class LocalBinder extends Binder {
        DataUpdateService getService() {
            Log.d("PS", "DataUpdateService LocalBinder onBind");
            return DataUpdateService.this;
        }
    }

    public class MyTimerTask extends TimerTask {
        @Override
        public void run() {
            String unitToUpdate= mymap.getUnitToUpdate (CompName,heatNum,usermail);
            Log.d("NY","CompName " +CompName);
            Log.d("NY","heatNum " +heatNum);
            Log.d("NY","usermail " +usermail);

            Log.d("NY","unitToUpdate" +unitToUpdate);

            Log.d("NY","isSailor" +isSailor);
            if (isSailor){
                gps = new GPSTracker(DataUpdateService.this,unitToUpdate );
                if( ! (gps.canGetLocation())){
                     gps.showSettingsAlert();
                 }
            }

            unitswithteam=mymap.refresh (CompName,heatNum);

            int j= unitswithteam.size();
            for (int i=0; i<j;i++){
                teamID=unitswithteam.get(i).getTeamID();
                Log.d("NY","teamID "+i+teamID);
                UnitsInHeats us=unitswithteam.get(i).getUnit();
                teamLocation = new LatLng(us.getLat(),us.getLng() );
                Log.d("NY","team location "+i + " "+us.getLat());
                mymap.setParkingSpotMarker(teamLocation,teamID);

                if (i==(j-1)){
                    CameraPosition secound =new CameraPosition.Builder()
                    .target(teamLocation)
                    .zoom(15.5f)
                    .bearing(300)
                    .tilt(50)
                    .build();
                    mymap.moveMyMapCamera(secound);
                 }
        }

        }
    }

    // called from the activity
    public void MapUpdateFromService(Context context, MyMap map, final String action,
                                String CompName, String heatNum, boolean isSailor , String usermail) {
        Log.d("PS", "DataUpdateService MapUpdateFromService");
        this.mymap = map;
        this.action = action;
        this.CompName=CompName;
        this.heatNum=heatNum;
        this.isSailor=isSailor;
        this.usermail=usermail;

        // this command activate the run function from the inner class MyTimerTask every 5 seconds.
        myTimer.schedule(myTask,0,5000);
    }

    public void onDestroy() {
        super.onDestroy();
        // cancel the scheduler.
        myTimer.cancel();
    }
}

this is the activity that calls the service:
package com.example.sailon;
import java.util.ArrayList;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import android.app.ActionBar;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

public class Map extends Activity {
    Bundle extras;
//  private GoogleMap map;
    static LatLng teamLocation;
    //public static ArrayList<Teams> teams;
    ArrayList<TeamsList> teamsList= new ArrayList<TeamsList>() ;
    Marker mark;
    double lat;
    double lng;
    GPSTracker gps;
    String Location ;
    String teamID;
    String CompName;
    MyMap mymap;
    String heatNum;
    String CompID;
    boolean isSailor;
    String usermail;
    static LatLng BeerSheva = new LatLng(31.250919, 34.783916);
    public ArrayList<UnitInHeatForMap> unitswithteam= new ArrayList<UnitInHeatForMap>();
//  ArrayList<LatLng> List= new ArrayList<LatLng>() ;
    DataUpdateService dbuService;
    boolean dbuBound=false;// when service connected get true

    @Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        mymap= new MyMap(this,((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap());
        //map=((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();

        extras = getIntent().getExtras();
        CompName=extras.getString("CompName");
        heatNum=extras.getString("heatNum");
        isSailor=extras.getBoolean("isSailor");
        usermail=extras.getString("usermail");
        Log.d("CompName",CompName);
        Log.d("heatNum",heatNum);
        // get action bar
        ActionBar actionBar = getActionBar();
        // Enabling Up / Back navigation
        actionBar.setDisplayHomeAsUpEnabled(true);

        if (mymap!=null){
            Log.d("PS", "map isnt null");
            mymap.setMapType();
            mymap.setMyLocationEnabled(true);
            CameraPosition firstZom =new CameraPosition.Builder()
            .target(BeerSheva)
             .zoom(15.5f)
             .bearing(300)
            .tilt(50)
            .build();

            mymap.moveMyMapCamera(firstZom);
        }

    }

        // serviceConnerction is an interface that must be implemented when using bound service
        private ServiceConnection sConnection=new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.d("PS", "Map onServiceConnected");
                DataUpdateService.LocalBinder binder=(DataUpdateService.LocalBinder)service;
                dbuService=binder.getService();
                Log.d("PS", "Map callupdate");
                dbuService.MapUpdateFromService(Map.this,mymap,"ActionSearch",CompName,heatNum, isSailor,usermail);
                dbuBound=true;
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.d("PS", "Map onServiceDisconnected");
                dbuBound=false;
            }
        };

        @Override
        protected void onStart() {
            super.onStart();
            // Bind to DataUpdateService
            Log.d("PS", "Map onStart");
            Intent intent= new Intent(this,DataUpdateService.class);
            bindService(intent,sConnection, Context.BIND_AUTO_CREATE);
        }

        @Override
        protected void onStop() {
            super.onStop();
            // Unbind from the service
            Log.d("PS", "Map onStop");
            if(dbuBound){
                unbindService(sConnection);
                dbuBound=false;
            }
        }
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_main_actions, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Take appropriate action for each action item click
        switch (item.getItemId()) {
        case R.id.logoutAction:
            Intent i = new Intent(Map.this, MainActivity.class);
            startActivity(i);
            return true;
        case R.id.VideoAction:
            Intent intent = new Intent("android.media.action.VIDEO_CAMERA");
            startActivity(intent);
            return true;
        case R.id.CallAction:
           Intent call = new Intent(Intent.ACTION_DIAL);
           startActivity(call);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

}

this is the calss of the map:
    package com.example.sailon;
import android.content.Context;

import android.util.Log;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;

import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;

import com.google.android.gms.maps.model.MarkerOptions;
import com.parse.ParseException;

import java.util.ArrayList;

/**
 * Created by Evyatar.m on 21/02/2015.
 */
public class MyMap {

    private GoogleMap map;
    static LatLng BeerSheva = new LatLng(31.250919, 34.783916);
    String CompID;
    String teamID;
    String CompName;
    String heatNum;
    ArrayList<TeamsList> teamsList= new ArrayList<TeamsList>() ;
    public ArrayList<UnitInHeatForMap> unitswithteam2= new ArrayList<UnitInHeatForMap>();
    static LatLng teamLocation;
    Model DB;

    public MyMap(Context context, GoogleMap map) {
        Log.d("PS", "MyMap builder");
        DB = Model.getInstance(context);
        this.map = map;

    }

    public String getUnitToUpdate (String CompName,String heatNum, String usermail){
        String unit=null;
        try {
            CompID= DB.getCompIDByName(CompName);
        } catch (com.parse.ParseException e) {
            e.printStackTrace();
        }
        try {
            unit= DB.getUnitToUpdateFromDB (CompID,heatNum, usermail);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return unit;
    }
    public void setMyLocationEnabled(boolean b){
        Log.d("PS", "MyMap set location enable");
        map.setMyLocationEnabled(true);
    }

    public void setParkingSpotMarker(LatLng teamLocation,String teamID) {
        Log.d("PS", "ParkingMap setParkinSpotMarker");
        map.addMarker(new MarkerOptions()
                .position(teamLocation)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.iconsmall))
                .title("Team " +teamID)).showInfoWindow();

    }

    public void setMapType(){
        Log.d("PS", "MyMap setType");
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    }

    public void moveMyMapCamera(CameraPosition firstZom) {
        Log.d("PS", "MyMap moveParkingMapCamera");
        map.moveCamera(CameraUpdateFactory.newCameraPosition(firstZom));
    }
  //updates all points on map

    public ArrayList<UnitInHeatForMap> refresh (String CompName,String heatNum){
        Log.d("PS", "MyMap refresh");
        try {
            CompID= DB.getCompIDByName(CompName);
        } catch (com.parse.ParseException e) {
            e.printStackTrace();
        }

        try {
            DB.setUnitInHeatForMap (new Model.CallbackModel () {
                @Override
                public void done (ArrayList<UnitInHeatForMap> unitswithteam){
                    if (unitswithteam.size() >0){
                        unitswithteam2=unitswithteam;
                    }

                }
            }, CompID, heatNum,this);

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return  unitswithteam2;

 }

}

please help me
thanks !!!**
Answer: The run method of the TimerTask runs on background thread, and you can only update the map on the main thread.
So you have to wrap the following Map UI update codes into runOnUiThread()
        mymap.setParkingSpotMarker(teamLocation,teamID);

        if (i==(j-1)){
            CameraPosition secound =new CameraPosition.Builder()
            .target(teamLocation)
            .zoom(15.5f)
            .bearing(300)
            .tilt(50)
            .build();
            mymap.moveMyMapCamera(secound);
         }

You need to have an Activity to apply runOnUIThread, so you need to put your
fromContext = ((Map)context);
inside the first line of your MapUpdateFromService method. Then you can call runOnUiThread() in your TimerTask's run() method.
((Map)fromContext).runOnUiThread(new Runnable() {
    @Override
    public void run() {
       //run your Map UI update code
    }
});

This is also a similar issue of this problem.


Is is possible to use WSUS to update sufrace pro devices from sbs2011

Question: We have surface pros in SBS2011 environment is it possible to use wsus in sbs2011 to manage update for surface pro devices? additional notes: so far surface pro devices shows up in sbs server console, and also in the correct OU in Ad administrative center. Just doesn't show up in the wsus client computer listing.

I already checked the wsus is updated to 3.0 and sp2
started and stoped wsus service
restarted server
restarted surface pros
Comment: http://social.technet.microsoft.com/Forums/windowsserver/en-US/17c66847-c2a9-4418-8a21-3d5270b99a3f/surface-pro-firmware-update?forum=winserverwsus
Answer: The Surface Pro isn't any different than a Windows laptop in this example. You probably don't have Windows 8 or 8.1 patches synchronized to WSUS, so there are no updates for them on your server.
Comment: Thanks for your response and I completely agree about the os of surface pro and laptop. I joined the surface pro to the domain as far as basic communication with wsus server everything looks fine and under Options> Products and classifications I have win 8 checked. main issue at this point is that the surface pro doesn't show up in the "update services client computers"
Comment: Has the Surface pro checked for updates since then? The check-in is entirely client driven
Comment: During the domain join surface pro joined the domin correctly and in the right OU as well
Comment: checked in for updates = manually check for updates form surface pro? yes that works
Comment: http://social.technet.microsoft.com/Forums/windowsserver/en-US/17c66847-c2a9-4418-8a21-3d5270b99a3f/surface-pro-firmware-update?forum=winserverwsus
Comment: That is specific to firmware, it seems.
Comment: This technet article explains that not only is WSUS supported for Surface, *it's recommended* http://technet.microsoft.com/en-us/library/ee692078(v=surface.10).aspx
Comment: Within next day or two I will install win 8 pro on a vm and see If i face the similar Issue. Can't think of anything else to check
Comment: Thanks Finally worked needed WSUS-KB2734608-x64                                         http://support.microsoft.com/kb/2734608


Não aparece todos os tipos de dados do SQLite Studio

Question: está limitando as opções de tipos de dados disponíveis. Como pode ser alterado o tipo de dado de uma coluna específica no meu banco de dados SQLite usando o SQLite Studio?
Answer: O SQLite possui apenas os tipos de dados exibidos no SQLite Studio, BLOB, INTEGER, NUMERIC, REAL e TEXT.
Qualquer outro tipo, é apenas uma abstração desses tipos, por exemplo, BOOLEAN ou DATE são do tipo NUMERIC.
Veja mais sobre esse assunto na documentação do SQLite:
https://www.sqlite.org/datatype3.html


Please explain me this code?

Question: rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]

I am not able to understand how it will print the transpose when we use it in for loop . Can someone explain the working thoroughly ?
Comment: what is `m`? a numpy array?
Comment: M is an array of 3*2 order
Answer: @Parakh, you did not specify what m is, so I made it a 2d array:
m = [[6, 2],
     [3, 4]]

rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]
print(rez)

[[6, 3], [2, 4]]
This is the same as:
```
m = [[6, 2],
     [3, 4]]

rez = []
for i in range(len(m[0])):
    temp = []
    for j in range(len(m)):
        temp.append(m[j][i])
    rez.append(temp)
print(rez)
```

This is producing column 0, row 0 (6) and column 0, row 1 (3) as the first new list,
then column 1, row 0 (2) and column 1, row 1 (4) as the second new list.
j is the row index, i is the column index.
i[0], j[0] = 6
i[0], j[1] = 3
i[1], j[0] = 2
i[1], j[1] = 4

Please explain me this code?


How high will the water rise

Question: I need to know where I am going wrong since I am getting the wrong answer

12 litres of water are poured into an aquarium of $50$ cm length , $30$ cm breadth and $40$ cm Height.How high in cm will the water rise. (Ans 8 cm)

Edit:
So I was making some very illogical assumptions however according to advice given which suggested that I keep the changing dimension value variable I got the answer which is
$1000cm^3$ = $50 \times 30 \times x$
so $x = \frac{1000}{1500}$. so $1$ litre has height $\frac{1000}{1500} = \frac {2}{3}$ so $12$ litres will give $12 \times \frac{2}{3} = 8 cm$
Comment: Which dimension (length, breadth, height) changes when you pour in the water? This is where the $x$ should go. The other two stay constant, so you have $x\cdot C_1 \cdot C_2$, which should match $12\;l$. To make the match, you have to convert litres to $cm^3$...
Comment: I think a good start would be to ask whatever led you to write $50\times30\times40=5\times3\times4$ when it's patently not so.
Comment: I agree that does not make sense
Comment: Tips on solving this problem ?
Comment: how did you get $12l$ ?
Comment: Just some advice: I guess everybody here knows the answer but we want you to somehow get it yourself. Right now there are just so many things going wrong in your question. Where do the zeros go? In which units do you work? What is $x$? Why do you multiply $5x\cdot 3x\cdot 4x$? How do you conclude from $x=200$  that the height is $800$? First try to correct all those and I am sure somebody will help you then.
Comment: @SimonMarkett I agree some assumptions were illogical I was treating the multiplicants  as if they were ratios .. Though I fixed it thanks to draks
Comment: @MistyD I put it as answer, so that you can accept it (if you like). This will prevent your questions from been bumped by the automatic system. Cheers...
Answer: Congratulation: your answer is correct!
Comment: You should have posted this as a CW answer, there is no real content in this and it only serves as a verification to the OP.
Comment: @AsafKaragila Ok, but maybe you missed part of the story. Have a look at the comments and the revisions of the question. After alll, I'm still young and need the reputation...;-)
Comment: draks, I saw that, and this is indeed what you should do when you solve something like that in the comments. However protocol suggests that if you didn't really answer beyond that, it's in good faith to make your answer CW.
Comment: @AsafKaragila I'll promise I'll do next time...

How high will the water rise


Lower the I/O priority for backups

Question: I have a job that nightly runs a backup of all attached databases however it can bog the server down if someone is connected during that time. I have TONS of CPU overhead to work with (I am barely above 5% in use, 8 cores total the highest is maybe 30% the rest are at idle), my issue is I am pegging my I/O. Looking at resource monitor I noticed that the I/O priority in Resource Monitor of the reads to the mdf and to the .bak file have a priority of Normal.
Is there a way to make my backups run at Background priority?
Answer: You can backup databases to a UNC path (manually or by creating a backup device) so you could try that, but you'll be trading disk I/O for network I/O.
Comment: Hmm, I do immediately just transfer the files anyway to another computer. This may be my solution, but I will leave this open for a day or two if there comes better suggestions.
Comment: There are all sorts of memory problems that go with streaming large database backups to a remote server.  Basically this causes all the memory to be assigned to the system cache and taken away from SQL Server.  I highly recommend never doing this.
Comment: If I mounted a iSCSI device? do the same issues apply?
Comment: If Windows sees it as a local disk on the SQL Server it doesn't apply (mapped drives do not count as local disk).  Only when going to a network path (or a mapped drive).
Answer: This doesn't actually answer the question (how to tweak I/O priority for a backup operation) but may help significantly speed up backups and reduce their affect on other activity:
If you can write your backups to drives that are not holding the database's data and log files. With spinning disk based drives this improve performance considerably because the backup operation is not constantly causing the heads to flip between the area holding the live data (to read pages) to the area the backup is being written to (to store those pages).
This may mean adding an extra physical drive (or multiple drives so you can use RAID for redundancy) to the machine for the backups to go to, particularly if you only have one drive or array that holds everything. If you have your data and log files on different disks/arrays but don't have a third drive/array to write the backups to and are unable to add one, writing the backups to the drive with the logs is usually faster than writing them to the drive with the data files (as the active pages in the log files are far fewer except in unusual cases).
Comment: Unfortunately this is a 1U server and all the bays are full and used in a RAID configuration. there is also a issue with the USB controller not showing up in hardware devices (that is the reason it is running on the same disk, it used to go to a external drive, now it gets backed up locally then FTPed to another machine.)
Comment: Is there another machine it can see over the local network to backup to? That would seperate the source and destination of the backup process to a different spindle set, and if the network is only 100Mbit it will also artificially reduce the I/O load imposed by the operation in any given second.
Comment: Doing it over the network looks like the solution I will end up doing.
Answer: No, there is no supported way of changing one thread to a different priority level.  You can try using something like LiteSpeed and/or HyperBac to compress the backups which will reduce the write IO requirements.
Comment: Would using windows file and folder compression free up I/O resources at the expense of CPU resources, or would it not make a difference?
Comment: I'm not sure if NTFS compression is supported for SQL Backups.  I know that NTFS compression isn't very good, so it probably wouldn't help much.  HyperBac isn't that expensive and has a very good ROI on it.  Here's a real world post I wrote up about it. http://itknowledgeexchange.techtarget.com/sql-server/how-hyperbac-worked-for-me/
Comment: I just ran it by the higher-ups and they rather have it go slow than spend money on making the backups run faster :(
Comment: Really, they can't fork over $795?  Ouch.
Comment: For a batch job running at 2 AM that maybe inconveniences one person a week, yea.
Comment: ok, I can see that. Would be hard pressed to spend money for one person, unless that person's time being wasted was more than the software cost.
Answer: Upgrade to SQL Server 2008 Enterprise or SQL Server 2008 R2 Standard or higher, make use of native backup compression - and trade some of those CPU cycles in for a potentially much reduced backup time.
Comment: Unfortunately I can not upgrade this instance, I have two instances this one and a R2 instance, on the R2 I do use native compression.
Comment: Or update to 2014 which now has compression for Standard edition

Lower the I/O priority for backups


When does the Bertrand paradox apply?

Question: Link to Wikipedia article on the Bertrand paradox
There's another question asked recently that superficially looks like Bertrand's paradox. Both involve picking random points/chords and then calculating a property. Yet one leads to a not-well-defined situation, while the other apparently has a well-defined answer of 0.25.
Why? How does one tell if a question is well-defined or if Bertrand's paradox will apply?
Answer: The point of Bertrand's paradox is that you must properly specify the probability model for a "random" object in order to get a unique correct answer.  In the "other" question you refer to, although the model is not
quite explicitly specified there is an obvious choice: $X$ and $Y$ with joint distribution uniform on the square $[0,1]\times[0,1]$.  Therefore there is no paradox here.  But if somebody wanted, say, $X^2$ and $Y^2$ rather than $X$ and $Y$ to be uniform, they would get a different answer.

When does the Bertrand paradox apply?


Can you change the boot order of a VMware ESXi EFI guest in a config file?

Question: For VMware ESXi guests that are booted with a BIOS boot firmware it is possible to configure the boot order directly in the .vmx file of the guest, according to this VMware kb article, by specifying these options:
bios.bootOrder = "ethernet5,ethernet2,hdd,cdrom,floppy"
bios.hddOrder = "scsi2:2,scsi0:1,ide1:0"

Q: Is something similar possible if the guest is booted with an EFI firmware?
I know I can change the boot order by accessing the EFI setup screen, but I would like to have something that can be automated.
Answer: Although I haven't found a way to directly change the EFI boot order, a workaround is to configure the EFI boot order from the GUI, and then create a backup of the vm.nvram file.
Later you can restore the vm.nvram file from a backup that has the EFI boot order you need.


Variation or variance

Question: R-squared, is it an explanation of variation or variance? In most of the articles, it is written r-squared is the proportion of variance explained,however, in some articles, it is written as the proportion of total variation explained by the regression. Now, I am pretty confused, actually which one is correct and which one should I write in my thesis?
Answer: Variation is a general term which express the dispersion. Variation is not precisely defined, it talks only about the quality of some process which produces imprecise results and express the imprecision. Variance is a measure for variation, which is defined as the second central moment. There are many measures of variation like range, standard deviation and so on. However in the context of r squared variation could be only variance.
[Later edit to address the comment]

You mean that actually we measure variation by using variance like we measure weight by using kilogram or ounce or pound.If I am wrong please correct me.

Well, it's not quite right. The kilograms, ounce or pounds are measurement units, all of them have a precise meaning which is the weight. Staying closer to your example I would say that variance is to variation like the weight of your object is to how big an object is. In this case an object can be big because it has many kilograms, a big volume, a large surface area, an so on. Notice that in "how big an object is?" the notion of big is not precise, and can be understand slightly different, depending on what you are interested in.
Going back to variation, the point is that you can interpret that variation in different ways. Consider a sample which comes from a distribution. The variation of the values from the sample is talking about how the values are spread. Depending on your context the characteristics of that spreading which interests you can be different. You might use variance because you perhaps suppose a normal distribution and you want to compare with a statistical test if two samples have a significantly different mean. You also can use their range (maximum value minus minimum value) because perhaps you want to display them on a screen. Also you might use variance to compute R-squared for linear models to have an idea about how well the model fits the data. Obviously variance and standard deviation are prevalent due to their statistical meaning which helps in conducting inferences.
Comment: Thanks for your answer. You mean that actually we measure variation by using variance like we measure weight by using kilogram or ounce or pound.I fI am wrong please correct me.

Variation or variance


Notation to return from piano or forte to regular intensity

Question: With ppp, pp, p, mp, mf, f, ff, fff, sfz one denotes the transition from 'regular' intensity to pianississimo, pianissimo, etc.
If I understand correctly placing one of those indicates playing with that intensity from that point of the score onward.
How to denote returning to what was before the regular intensity?
Comment: It's probably noteworthy that NinSheetMusic, a video game theme arranging website I contribute to, refuses to publish any transcriptions that do not start off with an initial dynamic marking (the pp-ff kind, not a crescendo/piu piano/sfz/etc.).
Answer: There is no 'regular intensity' in music notation, and no 'regular speed'.   You need to specify both at the outset.
But I know what you mean.  A DAW, unless instructed otherwise, will probably give MIDI notes a velocity of 100 (or another fixed value) and default to a tempo of 120 b.p.m.  (ever noticed how MUCH sequenced music has that tempo? :-)   MIDI velocity 100 is probably about 'mf'.  And if a lazy composer neglects to specify a dynamic when writing for live players, he'll probably get about mf.
So, OK, I give in.   mf.
Comment: 100 is not at all a common default velocity across DAWs, but it is true that each DAW has a default velocity for MIDI note on messages entered in the piano roll or in any way that doesn't have velocity data attached to it. Some other default velocity numbers I've seen are 70, 90, and 120(!!). Most DAWs I use have a way to choose what you want the default velocity to be going forward. The 120 BPM default tempo does seem to be essentially universal.
Answer: I would have said: These dynamics are always relative to the preceding signs. If a composer writes dynamics at all, he seldom gives in a forte in somewhere in the middle of a piece without having started it in a probably  lesser loudness.
Your link says:

Mezzo forte Moderately loud; softer than forte. If no dynamic
  appears, mezzo-forte is assumed to be the prevailing dynamic level.

I wouldn't fully agree with the statement in the link of your answer:
If no dynamic appears, mezzo-forte is assumed to be the prevailing dynamic level.
It means to me, that it's up to me which dynamic I will choose. It could be different from verse to verse or from performance to performance.
Comment: I remember being shocked that the sheet music for one of Beethoven's Bagatelles in C Minor has no dynamic indications at all. Both of the interpretations of that bagatelle I listened to have plenty of dynamics slapped on, especially crescendos and decrescendos.
Comment: yes! I could even add that the dynamic is a question of the motives and the phrases. And another point is that e.g. the keyboard music of Bach is written for instruments that didn't have great dynamic possibilities. So purists will play baroque music with only little dynamic and I prefer this music played slowly and in a romantic style, as I am not a purist.
Answer: I think the clearest option would be to put your intended "base" dynamic at the very start of the score (as you said mf or mp would probably be good options) then you simply put the same marking in whenever appropriate.
I would personally find it a little confusing if there was no dynamic indications at all for the start of the piece and then a "p" or "f" or whatever after that, so I'd try to be explicit from the very start.
Answer: Oh! I think I got my answer. I should use mf, is it?
In that page it says.

If no dynamic appears, mezzo-forte is assumed to be the prevailing dynamic level.
Comment: Can't agree with this assumption. There are too many factors, all movable, that come into play with these dynamics. There is nothing which correlates mp, mf, ff with a number of Decibels! It's all relative, and also rather personal.If it *is* indeed 'mf', then how loud should that be??
Comment: The funny part is that Musescore indeed plays back your music as mezzo forte if you don't put in any dynamics.
Comment: @Dekkadeci - Aha. I wondered what to use for 'go back to normal' on Musescore. I take it from the answers here that there is no dynamic level between mf and mp so no need for a symbol. I find this odd.  . .


Does it make sense to play folk music by yourself on the violin?

Question: I played the violin as a child, and now I'm trying to pick it up again. However, most of the music and notes I have are for classical music, which is what I played back then. So for instance I have been working on Franz Wohlfahrt's "Sixty Studies for the Violin" under the assumption that it is useful no matter what I will end up playing.
However, I really like the sound of bands like Pentangle and Ygdrassil, usually described as folk with jazz/rock/blues influences. These two groups don't use the violin a lot, but for example in Open the Door of the Pentangle the violin is somewhat prominent.
I'm definitely not ready to play with others yet, and we're quarantined due to COVID-19 now anyway, so my question is: is there any way I could learn to play this kind of music on the violin that makes sense to do on my own? Or is the violin simply not suited for this and should I stick to another genre / try the guitar (for example) instead / wait for times to improve to join a band where I could have a more supporting role?
Answer: Personally, I think there's a lot of fun to be had playing folk music solo on the violin - a lot of British/European folk music contains double-stops, and melodies with a strong emphasis on chord tones, that mean the violin part carries the chord progression — and likewise the rhythmic feel of folk violin means that you can play up a storm in the kitchen on your own (or with the people you are self-isolating with!)
Answer: Of course.  Get tabs and practice what kind of double stops on a lower string make for a good fit with the chord symbols written above the melody line (which you also play).  That's way what contributes to a folksy sound and much material to play from will be in the form melody+chords.  So it's a pretty useful skill to not need written-out double stops for that kind of thing.
Answer: There's a huge tradition of violin (often aka fiddle) music in the various British folk musics and in many other traditional musics worldwide. Pentangle and Ygdrassil are as good a starting point as any, and you'll be preparing yourself for a lifetime of happy & & fulfilling playing if you put the starting work in now.
Comment: I found out about the 'aka fiddle' bit (and the fact that I should refer to songs as 'tunes') earlier today, and this has indeed opened a whole new world :)
Answer: I think it's a great idea! And there are tons of public domain tune books online. One thing to consider is some folk music uses alternate tunings. Maybe some of the music you like uses such tunings. Or, you might be curious to try it out. I can't play violin, but I get by on guitar. I've tried alternate guitar tunings and it's a nice way to get a fresh view on the instrument. Helps you think a bit deeper about standard tuning.


An array of objects as well as their subclasses in Java

Question: I am trying to figure out how to define an array of a certain type of objects that will include the subclasses as well. This is what I have :
Property[] list = new Property[100];

I believe this will define an array of 100 properties, but is it possible for this array to include SubProperty as well. SupProperty is an extension of the Property class.
Thanks very much.
Comment: It can include `SubProperty` as well, but while retreiving, you'll have to cast it as `SubProperty sub = (SubProperty) list[10]`. Assuming, `list[10]` is an instance of `SubProperty` and not `Property`
Comment: what kind of subproperty
Comment: what problem you are facing..?
Comment: Read - http://docs.oracle.com/javase/tutorial/java/concepts/inheritance.html
Answer: Yes it is possible for the array to include the SubProperty as well. Please find the code below -
class SubProperty extends Properties{
}

and
Properties[] obj = new Properties[100];
obj[1] = new SubProperty();

you can get back your Object, like -
for(Properties prop: obj){
    if(prop instanceof SubProperty){
        SubProperty subProp = (SubProperty)prop;
        System.out.println(subProp);
    }
}

Answer: If you have
Animal[] list = new Animal[100]

Would you be able to add a Dog to that array?, If a Dog is an animal, you will be able to do Animal dog = new Dog(); That's what inheritance is, if you want to know more about it go here
Answer: Yes, it is. A SubProperty object is a Property object. You can always swap a subclass for its parent.
Answer: You can use a subclass wherever its superclass can be used. This is OOP substitution principle. It also applies in this situation.


Azure AD Connect installation error 0x800708C5

Question: Installing Azure AD Connect 1.1.647.0 in express or custom mode fails with the following error:
The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements. (Exception from HRESULT: 0x800708C5)

This error prompts when the AADC installer tries to create its service account.
Answer: I contacted Office 365's technical support and, between us, we discovered that there seems to be a bug / incompatibility between Azure AD Connect 1.1.647.0 and Active Directory domain controllers running Windows Server (2012 R2) Essentials or Standard with Essentials, possibly due to an Essentials-implemented password filter.
We've worked around the problem by installing Azure AD Connect 1.1.443.0. Auto upgrades shouldn't be a problem because the credentials are already set.
The engineer said that he's going to contact the development team to get this fixed in a future release.

Update 2017/10/31:
Installing Azure AD Connect 1.1.647.0 and 1.1.443.0 on a Domain Controller server running Windows Server 2012 R2 Standard with Windows Server Essentials (not the same as Windows Server 2012 R2 Essentials) failed with a very similar error.
Again, I contacted Office 365's technical support and, ultimately, we had to create and use a dedicated service account. https://blog.kloud.com.au/2014/12/18/aadsync-ad-service-account-delegated-permissions/ | Password Synchronisation was very helpful in doing so - all you need to do is replace the down-level username.

Update 2017/11/01:
Installing Azure AD Connect 1.1.649.0 (released on 2017/10/27) on a server running Windows Server 2012 R2 Standard but in a Windows Server 2012 R2 Essentials Active Directory environment encountered the same errors so the problem still isn't fixed.


booting straight into xen VM

Question: I have a need to convert a bare-metal machine to a virtual-machine (via VMware converter). This part has been done successfully. I have then been asked to convert the vmware image to a XEN hvm.
The client wants to install their brew of xen hypervisor on the physical machine, and then have their virtual machine boot straight away (like its not a VM running on the machine).
So basically, I would image the original OS, install XEN, and then run the virtualized OS on top of XEN. But ideally, the fact that the OS is a VM or running on XEN would be transparent to any user of that machine.
Is such a thing even possible? From my understanding of the hypervisor layer, you'll always need a domain0, and that always has to be a physical machine, and trying to bypass domain0 and boot straight into a VM would not be feasable.
Thanks
Answer: You can set up Dom0 to auto-start specific virtual machines when the server boots up. Domain0 will still be available, but the users using the virtual machine will not see this.
I assume this is what the client wants. The phrases "Wants to install hypervisor" and "Like its not a VM" are contradictory and don't really make sense.
Comment: They do for this case, because the client wants to run the OS as a VM, but doesn't want anyone to know that the machine that they are using, is actually a VM installed on a physical device.

The more specific question is, say I'm sitting at Dom0. But my OS is VM1 (hosted on Dom0). Can I have the machine that is Dom0, boot VM1 so that it is transparent to the user?

booting straight into xen VM


Primitive proof of the integral of sine and cosine?

Question: Does anyone know of any "primitive" proofs of the integrals of sine and cosine, i.e. ones not making use of the fundamental theorem of calculus?
EDIT: Since apparently people believe I have not provided enough "context" here is an attempt of re-stating the question. Does anyone know of any first principles proof of the fact that:
$$
\int_a^x\cos(t) \,dt = \sin(x) + C
$$
without relying on the FTC or derivates? Ideally this proof would use a suitably simple definition of $\sin$ and $\cos$, for instance the unit circle definition.
Comment: That "primitive" proof relies on how *you* define *formally* the sine and cosine functions.
Comment: The fact that $\sin$ is an antiderivative of $\cos$ does not use the fundamental theorem of calculus. The fundamental theorem of calculus tells us that for all $a\in\mathbb{R}$$$\frac{d}{dx}\int_{a}^{x}\cos t \, dt = \cos x \, ,$$and also that for all $a,b\in\mathbb{R}$$$\int_{a}^{b}\cos x \, dx = \sin(b)-\sin(a) \, .$$
Comment: $$h\sum_{k=0}^{n-1}e^{ikh}=\dfrac xn\dfrac{e^{inh}-1}{e^{ih}-1}\to\frac{e^{ix}-1}i$$
Comment: @azif00 That is true, and I should have made clear in my post which one I was using. Considering I'm asking for a primitive proof of the result, I thought it was clear that using a rather simple (i.e. unit circle) definition of sine and cosine was what I was doing.
Comment: @Joe Every single proof I've seen uses the fundamental theorem of calculus, either directly or indirectly. How else do you propose to use the fact that d/dx sin(x) = cos(x) means that the integral of cos(x) is sin(x)?
Comment: @Peatherfed: If you are talking about *indefinite* integrals, then by definition$$\int \cos x \, dx$$refers to the set of functions $F$ such that $F'=\cos$. Since $\sin'=\cos$, and the set of antiderivatives differ by a constant, we write$$\int \cos x \, dx = \sin x + C \, ,$$(Although a more pedantic notation would be$$\int \cos x \, dx = \{F:F(x)=\sin x + C \text{ for all $x$}, C\in\mathbb{R}\} \, .)$$The fundamental theorem of calculus tells us the link between antiderivatives (or indefinite integrals) and definite integrals. I don't see any reason to invoke it here.
Comment: @Joe $\int \cos x \, dx = \{F : F(x)=\sin x + C \text{ for } \color{red}{\rm some} \text{ $C \in\mathbb{R}$ and all $x \in\mathbb{R}$}\}$.
Comment: @Joe Except that definition is informed by the FTC, otherwise, it would be a completely useless definition. I agree that the anti-derivative of e.g. cos(x) is sin(x), but I am not asking for the anti-derivative in my question, I'm asking for the integral. And before you protest that they are in this case the same, since I am implicitly asking for an indefinite integral, I reiterate that they are the same by definition, since the definition is informed by the FTC. Perhaps I was being unclear in my question, but I think this was readily understood.
Comment: @Peatherfed: I agree that the power of antiderivatives is only understood when the Fundamental Theorem of Calculus has been proven. So, to be clear, you are asking for a 'first principles' way of working out$$\int_{a}^{x}\cos t \, dt \, ? \tag{*}\label{*}$$And this method shouldn't rely on the fact that $\eqref{*}$ is an antiderivative of $\cos$. Is that correct?
Comment: @Joe Yes, that is correct.
Comment: @Peatherfed: In the body of your question, you might want to change the variable inside the integrand to '$t$' or something similar.
Comment: @azif00: Are you saying that I should have put a quantifier over $C$ because I am introducing this variable within the set builder notation itself?
Comment: @Joe Yeah I blanked on that one, the question is now edited with a proper variable inside the integral. Regardless, for some reason, the question was deemed to "not have enough context". I'm not sure how much more context I could possibly provide. It was a straightforward question. I feel like a lot of the people voting to close it just didn't know of any such proof, and as such the question must be bad.
Comment: Yes, "not have enough context" is what is the problem. First, you did not define what you mean by integral. Only when I asked for one you mentioned upper and lower Riemann sums. Also you are still not completely precise on exactly how you define sine and cosine. Usually these issues do not arise because all definitions should be essentially equivalent, but when you want a "primitive" proof, you have to be precise about what is allowed to be assumed. Also, the question is not that great to begin with.
Comment: @Somos The question has been edited so that my question should be more clear. The only way to provide more context would be to list literally every definition, and that is ridiculous. It's a soft question. The way I define integral is the standard way, so I'm not sure why you think it was necessary for me to explicitly mention upper and lower Riemann sums. Second, I am being precise in how I define sine and cosine while leaving options open for other definitions as long as they are in the spirit of the question.
Comment: The Wikipedia article [Riemann integral](https://en.wikipedia.org/wiki/Riemann_integral) mentions several variations of definition of an integral. You need to be precise about which variations you want to allow to be used. You can refer to standard sources of definition such as Wikipedia. The actual definition of sine and cosine is not important in **this** context. I think it is not important here which definition is used. So the question is how to prove $\int_0^x \cos(t)dt = \sin(x)$ with a suitable variation of integral.
Answer: One approach is to directly use Riemann sums. Using the result from
MSE question 17966
("How can we sum up $\sin$ and $\cos$ series when the angles are in arithmetic progression?") let
$$ S_n := \sum_{k=0}^{n-1} \sin\left(a+\frac{(b-a)k}n\right)\frac{b-a}n \\
= \sin\left(\frac{b-a}2\right)\sin\left(\frac{b+a}2-\frac{b-a}{2n}\right)
\frac{\frac{b-a}n}{\sin(\frac{b-a}{2n})}$$
be the left Riemann sum over $\,n\,$ subintervals of $\,[a,b].\,$
Given that $\,\sin\,$ is continuous and that
$\,\lim_{x\to 0} \frac{\sin x}x = 1,\,$ check that
$$ \lim_{n\to\infty} S_n = 2\sin\left(\frac{b-a}2\right)\sin\left(\frac{b+a}2\right). $$ This agrees with the value of
$$ \int_a^b \sin(x)dx = \cos(a)-\cos(b) $$ using a standard
trigonometric identity for difference of two cosines.
Comment: @Peatherfed How are you going to define integrals without limits? It is possible but you have to tell us how **you** define integrals.
Comment: @Peatherfed Thanks for that clarification. However, proving anything about infimum and supremum involves epsilon arguments which is morally equivalent to taking limits.
Comment: This is a good start. Ideally, I'd like to drop reliance on limits altogether, but perhaps this is something I can work out in my own time.
Comment: Like anyone else defines integrals without limits. Take the set of lower Riemann sums, and take its supremum, and then take the set of upper Riemann sums and take its infimum. If these are equal, then that real number is the integral. I prefer this over involving limits, since if you do limits you have to involve annoyances such as mesh size of your partitions.
Comment: No, you can prove things about infimum and supremum without epsilon arguments, and without using limits.


Is it advisable to use for comprehensions with yield to return a huge number of items?

Question: I am working on a little program that generates combinations and I am using for comprehensions. Something like this:
def posibilities2(n: Int): Seq[List[Int]] = {
  val maxValues = (1 to 3).map(i => n / i).toList
  for {
    n1 <- 0 to maxValues(0)
    n2 <- 0 to maxValues(1)
    n3 <- 0 to maxValues(2)
    if n1 * 1 + n2 * 2 + n3 * 3  == n
  }
    yield List(n1, n2, n3)
}

posibilities2(1000).foreach(doSomething)

For bigger values of n it can lead to lots of items.
My question is this: Is this the way to do it, given that, for each item generated, I have to do some additional processing? I am not concerned about the program taking a long time to run, I am concerned about running out of memory.
Thank you
Comment: Are you asking if the `for` expression in particular needs more memory than other solutions that do the same thing, or are you asking how not to run out of memory when creating large collections in general? These problems are two entirely different things.
Comment: @JFo: I was asking whether using the yield pattern as I coded it above is suitable for returning lots of items. pamu's answer fits what I wanted to do. However, I am new to Scala and I have to admit I don't know the inner workings and the fine details of different choices - for instance using the iterator vs. the form I used. I still have to do a lot of reading.
Answer: As amount of values for-comprehension produces is very high its better to go for iterator or stream implementation.
The below function will generate values on demand basis thus not risking out of memory errors.
  def posibilities2(n: Int): Iterator[(Int, Int, Int)] = {

    val maxValues = (1 to 3).map(i => n / i).toList
    for {
      n1 <- (0 to maxValues(0)).toIterator
      n2 <- (0 to maxValues(1)).toIterator
      n3 <- (0 to maxValues(2)).toIterator
      if n1 * 1 + n2 * 2 + n3 * 3  == n
    } yield (n1, n2, n3)

  }

Comment: Thanks. That is what I was looking for.


Bounce Email Query

Question: I wanted to check if there is a way to differentiate between bounced emails and auto-responses (out of office replies,etc..)?
-Ashish
Comment: Can you elaborate?  You can always tell by reading what the message contains.. but I don't think that's what you're really trying to do.
Answer: No, not without reading them.  Both use the null sender <> as the sender.  Some auto-replies use a faked bounce, but deliver the email anyway.  Some bounces are faked, and the message is delivered or quarantined.
You can tell whether the bounce was done during or after delivery by looking at the received header.  Bounces and auto-replies may be generated in either case.
You may be able to somewhat reliably filter messages based on message content.  This depends on the auto replies using standard messages which are unlikely to occur in a bounce message.
The bounce reason will appear in the headers, and you might be able to somewhat reliably filter some messages based on the added header(s).

Bounce Email Query


Como fazer um array de objetos ter apenas valores únicos?

Question: Se eu tenho uma coleção com o mesmo objeto em um array, como eu poderia fazer para tornar essa coleção com apenas objetos de instâncias únicas?
Exemplo:
$a = new stdClass;

$a->id = 1;

$b = $a; // mesmo objeto

$c = new stdClass;

$c->id = 2;

$colecao = [];

$colecao[] = $a;
$colecao[] = $b;
$colecao[] = $c;

Quero retornar apenas os objetos que não sejam o mesmo (porque $a nesse caso tem o mesmo hash (id interno no php) de $b).
Se eu tentar fazer isso, eu terei um erro:
$unicos = array_unique($colecao);

Object of class stdClass could not be converted to string

Parece que array_unique só serve para valores do tipo scalar.
Como poderia fazer com que o resultado acima fosse semelhante abaixo?
[$a, $c]

Comment: Já posso prever respostas com `spl_object_hash` e `SplObjectStorage` :) :) :) :)
Answer: Experimenta assim:
$unicos = array_unique($colecao, SORT_REGULAR);

A função array_unique() recebe como argumentos dois parâmetros (o segundo parâmetro é opcional):
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

array: O array que pretendes ordenar.
sort_flags: este parâmetro é opcional mas é importante pois permite alterar o comportamento por defeito da função. Ele pode assumir um dos seguintes valores:

SORT_REGULAR - comparação "normal" (sem alteração de tipos)
SORT_NUMERIC - comparação numérica
SORT_STRING - compara os items como strings (opção por defeito)
SORT_LOCALE_STRING - compara os items como strings (dependente do LOCALE)

Por defeito, a função irá tentar converter os objectos para string para efectuar a comparação, daí veres a mensagem:

Object of class stdClass could not be converted to string

Podes verificar em acção aqui: http://3v4l.org/3O810
Comment: Quase isso, porém ele removeu as "instâncias diferentes". Você sabe que o PHP considera automaticamente passado por referência uma atribuição da instância a um objeto. Logo, deveria retornar 2 elementos, e não 1.  Mas dei +1 pois a resposta foi interessante (só carece de explicações)
Comment: E o manual do php em português não fala nada que o `array_unique` aceita um segundo parâmetro, porém funcionou aqui no meu teste!
Comment: Incluí na resposta um "fiddle". Parece estar a funcionar pois retorna dois elementos. Podes verificar?
Comment: Isso porque os objetos têm valores diferentes. Mas, se eu tivesse duas instâncias do mesmo objeto, eu teria problemas se elas tivessem os mesmos valores. Veja a resposta que eu dei e entenderá o que eu quis dizer com "coleção de objetos da mesma instância, porém instâncias unicas - excluíndo referências"
Answer: Com certeza a resposta do @bruno é melhor, mas como já fiz irei postar assim mesmo, para didática.
Poderias criar uma função:
function ClearArray($arr, $KeepKey = FALSE){
    if (!is_array($arr)) return FALSE; // Se não for array retorna FALSE
    if (count($arr) == 0) return $arr; // Se estiver vazio retorna-o
    $narr = Array(); // Array de Retorno
    $c = 0; // Novos indices
    foreach($arr as $k => $v){
        // Se mantém o índice original usa-o senão usa o novo
        $k = ($KeepKey ? $k : $c);
        $keep = TRUE; // Mantém o item

        foreach($narr as $k2 => $v2){ // Percorre o novo array
            // Verifica se já foi adicionado um item igual
            if ($v === $v2){
                $keep = FALSE; // Não mantém o registro
                break;
            }

        }

        if($keep){ // Se mantém o item
            $narr[$k] = $v; // Adiciona-o no novo array
            $c++;
        }

    }

    return $narr; // Retorna
}

Uso:
$a = new stdClass;
$a->id = 1;

$b = $a; // mesmo objeto

$c = new stdClass;
$c->id = 2;

$colecao = Array();

$colecao[] = $a;
$colecao[] = $b;
$colecao[] = $c;

// Array Original
var_dump($colecao);

// Array com itens unicos
$arr = ClearArray($colecao, true);

echo '-------------------------'.PHP_EOL;

var_dump($arr);
$unicos = array_unique($colecao, SORT_REGULAR);

Saída:
array(3) {
  [0]=>
  object(stdClass)#1 (1) {
    ["id"]=>
    int(1)
  }
  [1]=>
  object(stdClass)#1 (1) {
    ["id"]=>
    int(1)
  }
  [2]=>
  object(stdClass)#2 (1) {
    ["id"]=>
    int(2)
  }
}
-------------------------
array(2) {
  [0]=>
  object(stdClass)#1 (1) {
    ["id"]=>
    int(1)
  }
  [2]=>
  object(stdClass)#2 (1) {
    ["id"]=>
    int(2)
  }
}

Answer: Agradeço a todos pelas respostas, mas, nesse caso, vou dar minha resposta, para prestar alguns esclarecimentos.
Como funcionam os objetos no PHP?
Primeiro, vamos reforçar alguns termos:

Objeto é uma instância de uma classe.

Segundo, vamos esclarecer algo: no PHP, eu posso ter duas instâncias de stdClass ($a e $b), porém se eu igualar $c a $a, os dois serão o mesmo objeto trabalhando na mesma instância (o que é alterado em $c implica em alteração em $a).
Ou seja:
$a, $b e $c são instâncias de stdClass, porém $c e $a é o mesmo objeto, já que $c faz referência a $a - no php os objetos atribuidos são automaticamente passados por referência, de acordo com o manual.
Suponhamos o seguinte cenário:
$a = new stdClass;

$b = new stdClass;

$c = $a;

Isso:
[$a, $b, $c]

Seria a mesma coisa que isso:
[$a, $b, $a]

Pois para $c se tornar uma nova instância de stdClass, independente da instância guardada em $a, teriamos que usar a palavra chave clone.
Assim:
$c = clone $a

SplObjectStorage - A Solução
Então, para retornar um array de objetos com instâncias únicas (instâncias do mesmo objeto, porém não repetindo esses objetos), poderiamos fazer assim:
$a = new stdClass;

$a->id = 1;

$b = $a;

$b->id = 2;

$c = new stdClass;

$c->id = 3;

$storage = new SplObjectStorage();

$storage->attach($a);
$storage->attach($b);
$storage->attach($c);

print_r(iterator_to_array($storage));

O resultado seria:
Array
(
    [0] => stdClass Object
        (
            [id] => 2
        )

    [1] => stdClass Object
        (
            [id] => 3
        )

)

Notem que o id que era 1, passou a ser 2.
Para entenderem o que eu digo, veja o que ocorre nesse exemplo:
$a = new stdClass;

$a->id = 1;

$b = $a;

$b->id = 2;

var_dump($a->id, $b->id); // int 2 e int 2

http://3v4l.org/nCG4J
Porque isso aconteceu?
Porque, internamente, o SplObjectStorage, utiliza o hash do objeto como a índice para atribuí-lo a um array.
Isso é feito através de uma função chamada spl_object_hash:
Veja esse exemplo:
var_dump(spl_object_hash($a));
var_dump(spl_object_hash($b));
var_dump(spl_object_hash($c));

var_dump(spl_object_hash($a) === spl_object_hash($b));

var_dump(spl_object_hash($a) === spl_object_hash($c));

var_dump(spl_object_hash($b) === spl_object_hash($c));

O resultado é:
string '0000000076e70b6400007fac140b77fd' (length=32)

string '0000000076e70b6400007fac140b77fd' (length=32)

string '0000000076e70b6500007fac140b77fd' (length=32)

boolean true

boolean false

boolean false

Isso deixa claro que $c e $a, são os mesmos.
Deixo então aí minha pequena contribuição. Obrigado pelas respostas!
Por que não array_unique?
Porque ele não usa a mesma regra de "unicidade" que o SplObjectStorage usa.
Veja esse exemplo:
$a = new stdClass;

$a->id = 2;

$b = new stdClass;

$b->id = 2;

$case1 = array_unique([$a, $b], SORT_REGULAR);

$storage = new SplObjectStorage();

$storage->attach($a);
$storage->attach($b);

$case2 = iterator_to_array($storage);

var_dump($case1, $case2);

Veja os resultados:
#array_unique
   array (size=1)
      0 =>
        object(stdClass)[6]
          public 'id' => int 2
#SplObjectStorage com iterator_to_array
    array (size=2)
      0 =>
        object(stdClass)[6]
          public 'id' => int 2
      1 =>
        object(stdClass)[7]
          public 'id' => int 2

Exemplo: http://3v4l.org/hQKL5
Parece que o array_unique levou em consideração o fato de id ter o mesmo valor nos dois casos, porém, como dito anteriormente, SplObjectStorage levou em consideração a identificação interna do objeto.
Se eu estiver errado em alguma coisa, podem me corrigir :). Mas é o que entendo por objetos no PHP!


Löwenheim-Skolem and proper class models of ZFC.

Question:
Let $N$ be a proper class model of ZFC and $x \subset N$ a set. Show that  there is a set $y \in N$ such that $x \subset y$.

If $x \subset N$, I think that by the downward's part of Löwenheim-Skolem, we can find an elementary submodel $y$ of $N$ such that $x \subset y$. But how would I conclude that $y \in N$? It seems like I'm missing something trivial but I can't figure out what exactly.
Note: A hint to point me to the right direction would be more appreciated than a complete answer.
Comment: Use foundation.
Comment: (And you cannot use the Lowenheim-Skolem theorem.)
Comment: @AndrésE.Caicedo Thanks! I'll try. Small question: why cannot we use LST for proper classes?
Comment: @CarlMummert I made I mistake while typing. We are trying to show that there is a set $y \in N$ such that $x \subset y$. Also, the question means that $(N,\in)$ is a model of ZFC, or at least that's how I interpret it. Hope this clarifies some stuff.
Comment: Is $x\subset y$ in the claim meant to be evaluated with the model's $\in$ relation? Or is the model implicitly supposed to be standard?
Comment: @HenningMakholm I think so, yes. Maybe I am missing some context but I would say that $x \subset y$ has to be evaluated with the $\in$ relation.
Comment: If we could use the LS theorem like this for proper classes, then we could prove the consistency of ZFC. Instead we have reflection theorems, which have a somewhat smaller scope than 'elementary submodel'.
Comment: @AndrésE.Caicedo I think I haven't done much progress though. Using the Reflection Principle, for each $x \subset N$ I can pick a transitive set $y$ with $x \subset y$ and such that $y$ reflects foundation. But how can I go from here to the claim in the problem? Thank you.
Comment: @spaceisdarkgreen Thanks for the comment! I didn't thought about using the Reflection Principles!
Comment: @user313212 I was just explaining how to see LS doesn't apply for proper classes, not so much suggesting the use of reflection theorem in this particular problem. I think what Andres was suggesting was to take $y$ to be $N$'s version of $V_\alpha$ for some sufficiently large $\alpha.$ Similar to Henning's suggestion below for $H_\kappa.$
Comment: @user313212 I think that properly addressing the issue of why Lowenheim-Skolem doesn't apply deserves some room. Why don't you ask about it as a separate question? In particular, it may help clarify the relation between the reflection theorem and your suggested approach.
Answer: Without loss of generality $x$ is transitive, at least relative to $N$ (that is, $\bigcup x\cap N\subseteq x$).
Because $N$ is a proper class model, it contains elements of arbitrarily large cardinalities. In particular it contains a cardinal number $\kappa$ that does not inject into $x$ at the metalevel, and therefore cannot inject into any subclass of $x$ in $N$.
But then $N$'s $H_\kappa$ must contain all of $x$.
Answer: This is a slight twist on Henning's answer:
Fix, working in $V$, an ordinal $\alpha$ such that $x \subseteq V_{\alpha}$. By the absoluteness of $\mathrm{rank}_{\in}$, we have $V^N_\alpha = V_\alpha \cap N$ and hence
$$y = x \cap N \subseteq V_{\alpha} \cap N = V^N_\alpha.$$


Is $C(\Omega)$ complete with the metric $\sum_{i=i_0}^\infty \frac{2^{-i}p_i(f-g)}{1+p_i(f-g)}$?

Question: Let $\Omega$ be an open set in $\mathbb{R}^n$. For $i\ge1$ define
$$K_i=\overline{B(0,i)}\cap\Big(\bigcup_{y\in\Omega^c}B\Big(y,\frac{1}{i}\Big)\Big)^c.$$
One can show that $K_i$ is compact, $K_i\subset K_{i+1}$ and $\Omega=\bigcup_{i=1}^{\infty}K_i$. Choose $i_0\in\mathbb{N}$ such that $K_{i_0}$ is not empty. Then, it is easy to verify that
$$p_i(f)=\sup_{x\in K_i}|f(x)|,\qquad\text{for}\qquad f\in C(\Omega), \qquad i\ge i_0$$
is a semi-norm on $C(\Omega)$. Using this, it can also be shown that
$$d(f,g)=\sum_{i=i_0}^\infty \frac{2^{-i}p_i(f-g)}{1+p_i(f-g)},\qquad\text{for}\qquad f,g\in C(\Omega)$$
is a metric on $C(\Omega)$.

Is $C(\Omega)$ complete with the metric $d(f,g)$?

My approach was to show that this metric is equivalent to the usual supremum metric which we may define as
$$p(f-g)=\sup_{x\in \Omega}|f(x)-g(x)|,\qquad\text{for}\qquad f,g\in C(\Omega).$$
So, I tried to find lower and upper bounds for $d(f,g)$ in terms of $p(f-g)$. I started with the fact that since $K_i\subset \Omega$ then
$$p_i(f-g)\le p(f-g).$$
Then it can be concluded that
$$\frac{p_i(f-g)}{1+p_i(f-g)}\le\frac{p(f-g)}{1+p(f-g)}.$$
With this in mind, I could find an upper bound as follows
\begin{align*}
d(f,g)&=\sum_{i=i_0}^\infty \frac{2^{-i}p_i(f-g)}{1+p_i(f-g)} \\
&\le\frac{p(f-g)}{1+p(f-g)}\sum_{i=i_0}^{\infty}2^{-i}=\frac{p(f-g)}{1+p(f-g)}2^{-i_0+1} \\
&\le \frac{p(f-g)}{1+p(f-g)} \\
& \lt p(f-g).
\end{align*}
However, I couldn't find a way to make a lower bound. Can someone help me with this? Also, any other way to show that the metric space $(C(\Omega),d)$ is complete is welcome.
Comment: You can't get a lower bound, a continuous function on $\Omega$ can be unbounded, then $p(f) = +\infty$, but $d(f,0) < 1$. Even for bounded $f$ you can make $\frac{d(f,0)}{p(f)}$ as small as you want. To show completeness, note that if $(f_n)$ is a $d$-Cauchy sequence, then $(f_n\lvert_{K_i})_{n \in \mathbb{N}}$ is a uniform Cauchy sequence for every $i$. Thus $(f_n)$ converges uniformly on every $K_i$. Show that these limits (in $C(K_i)$) fit together to define a function $g \in C(\Omega)$ and that $d(f_n,g) \to 0$.
Comment: As an alternative viewpoint, you can identify $C(\Omega)$ with a closed subspace of $$\prod_{i = i_0}^{\infty} C(K_i).$$ If you're familiar with ways of endowing a countable product of (nonempty) metric spaces with a metric inducing the product topology (and in such a way that the product is complete iff each factor is), that may be more straightforward. (Though it is in fact essentially the same way.)
Comment: @DanielFischer: Oooops! So, indeed my upper bound is also useless as it can be $+\infty$! :) Thanks, will think on that.
Answer: As suggested by Daniel in the comments, let $(f_n)$ be a Cauchy sequence in $(C(\Omega),d)$. Then, by definition, we have
$$\forall \epsilon>0,\quad\exists N\in\mathbb{N},\quad\forall n,m,\quad n,m\ge N\quad \implies d(f,g)=\sum_{i=i_0}^\infty \frac{2^{-i}p_i(f_n-f_m)}{1+p_i(f_n-f_m)}\lt\epsilon.$$
This in turn results in
$$\forall \epsilon>0,\quad\exists N\in\mathbb{N},\quad\forall n,m,\quad n,m\ge N\quad \implies \tilde d_i(f_n,f_m)=\frac{2^{-i}p_i(f_n-f_m)}{1+p_i(f_n-f_m)}\lt\epsilon,\quad i=i_0,\dots$$
since
$$\frac{2^{-i}p_i(f_n-f_m)}{1+p_i(f_n-g_m)}\le \sum_{i=i_0}^\infty \frac{2^{-i}p_i(f_n-f_m)}{1+p_i(f_n-f_m)}\lt\epsilon,\quad i=i_0,\dots$$
According to the definition of $p_i$, one can replace $f_n$ and $f_m$ with $f_n|_{K_i}$ and $f_m|_{K_i}$ since $\sup_{x\in K_i}|f(x)|=\sup_{x\in K_i}|f|_{K_i}(x)|$ or equivalently $p_i(f)=p_i(f|_{K_i})$. This means that $(f_n|_{K_i})$ is Cauchy in $(C(K_i),\tilde d_i)$. According to this post, being Cauchy and convergent is equivalent for $\tilde d_i$ and $p_i$. Consequently, $(f_n|_{K_i})$ is Cauchy in $(C(K_i),p_i)$. But $(C(K_i),p_i)$ is complete so $(f_n|_{K_i})$ converges to some $g_i$ in $(C(K_i),p_i)$. Now, we introduce the following candidate $g:\Omega\to\mathbb{R}$
$$g|_{K_i}:=g_i=\lim_{n\to\infty} f_n|_{K_i}\quad\text{in}\quad(C(K_i),p_i),\quad i=i_0,\dots$$
$g$ is well defined since for every $i\ge j$, it is readily verified that $g|_{K_i}|_{K_j}=g|_{K_j}$ (See the comment below this answer for more details on this). Note that $g|_{K_i}$ is continuous over $K_i$ as it is the uniform limit of $f_n|_{K_i}$. This implies that $g\in C(\Omega)$ because for every $x\in\Omega$ there is an $i$ such that $x\in \text{int} K_i$. Now, we are ready to go on. As the convergence with respect to $p_i$ implies convergence with respect to $\tilde d_i$, $(f_n|_{K_i})$ converges to $g|_{K_i}$ in $(C(K_i),\tilde d_i)$. This essentially means that
$$\forall \tilde\epsilon>0,\quad\exists \tilde N\in\mathbb{N},\quad\forall n,\quad n\ge \tilde N\quad \implies \tilde d_i(f_n,g)=\frac{2^{-i}p_i(f_n-g)}{1+p_i(f_n-g)}\lt\tilde\epsilon,\quad i=i_0,\dots$$
and we want to show that
$$\forall \epsilon>0,\quad\exists N\in\mathbb{N},\quad\forall n,\quad n\ge N\quad \implies d(f,g)=\sum_{i=i_0}^\infty \frac{2^{-i}p_i(f_n-g)}{1+p_i(f_n-g)}\lt\epsilon.$$
and this can be done since
\begin{align*}
\sum_{i=i_0}^\infty \frac{2^{-i}p_i(f_n-g)}{1+p_i(f_n-g)}&=
\sum_{i=i_0}^{j_0} \frac{2^{-i}p_i(f_n-g)}{1+p_i(f_n-g)} +
\sum_{i=j_0+1}^\infty \frac{2^{-i}p_i(f_n-g)}{1+p_i(f_n-g)} \\
&\le \sum_{i=i_0}^{j_0} \frac{2^{-i}p_i(f_n-g)}{1+p_i(f_n-g)}+
\sum_{i=j_0+1}^\infty 2^{-i}  \\
&= \sum_{i=i_0}^{j_0} \frac{2^{-i}p_i(f_n-g)}{1+p_i(f_n-g)}+
2^{-j_0}.
\end{align*}
Comment: One small point first: you need to say why the candidate $g$ is well-defined. That is because restriction commutes with taking the limit (given the existence of the limit); if $f_n\lvert_{K_m} \to g_m$ uniformly (for this, pointwise convergence is sufficient, by the way), and $A\subset K_m$, then $f_n\lvert_{K_m}\lvert_A = f_n\lvert_A$ converges uniformly (resp. pointwise) to $g_m\lvert_A$, hence $g_m\lvert_{K_i} = g_i$ for $i \leqslant m$. Also you need to show that $g \in C(\Omega)$. That's easiest by showing that $g$ is continuous at an arbitrary $x \in \Omega$, and that follows from the…
Comment: …continuity of $g_m$ at $x$ if $x \in \operatorname{int}(K_m)$. Now to the last step. Given $\epsilon > 0$, choose $m$ such that $\sum_{i = m+1}^{\infty} 2^{-i} = 2^{-m} < \epsilon/2$. Now find an $N$ such that $$\sum_{i = 1}^m \frac{2^{-i}p_i(f_n - g)}{1 + p_i(f_n - g)} < \frac{\epsilon}{2}$$ for all $n \geqslant N$. (For that, it suffices to look at $p_m(f-g)$. Why?)
Comment: @DanielFischer: Hi again! :) I am stuck at the very last step. Can you help me with this?


Storing external API key in AWS Elastic Beanstalk


Showing R output and code using R package details

Question: I want to use R package details for Create Details HTML Tag for Markdown and Package Documentation. My working example is below:
---
title: "Customizing Details"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{custom}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

```{r setup, echo = FALSE}
library(details)
```

### Open

```{r ch1, echo = TRUE}
seq(from = 1, to = 10, by = 2) %>%
  details::details(
    summary = "Output",
    open = TRUE
  )
```

```{r}
details(
  plot(x=mtcars$mpg,y=mtcars$wt),
  summary = "Output",
  imgur = FALSE,
  open = TRUE
  )
```

It works fine. However, I want to show output first and then the hidden code without the additional code of details package. Any thoughts, please.
Comment: copy your code chunk. The first one hast `echo = FALSE` and the second one `eval= FALSE`. Is this the desired output?
Answer: I think you just need to change the chunk opts:
ch1 has echo = FALSE, so the code isn't shown, only the object.
ch2 has echo = TRUE and results = 'hide', so the results are hidden but the output shows.
Same with ch3 and ch4.
```{r ch1, echo = FALSE}
var <- seq(from = 1, to = 10, by = 2) %>%
  details::details(
    summary = "Output",
    open = TRUE
  )
var
```

Here is where you're showing the code:
```{r ch2, echo = TRUE, results = 'hide'}
seq(from = 1, to = 10, by = 2) %>%
  details::details(
    summary = "Output",
    open = TRUE
  )
```

Here is where you're plotting your graph:
```{r ch3, echo = FALSE}
p <- details(
  plot(x=mtcars$mpg,y=mtcars$wt),
  summary = "Output",
  imgur = FALSE,
  open = TRUE
  )
p
```

Here is where you're showing the code:
```{r ch4, results = 'hide'}
details(
  plot(x=mtcars$mpg,y=mtcars$wt),
  summary = "Output",
  imgur = FALSE,
  open = TRUE
  )

```


Proxy to remote proxy?

Question: One of our partners require us to use one of their proxies in order for us to reach various services there. What I would like to achieve is to set up a local proxy at which I point the domains, so that we internally can connect without adding/removing proxy servers or use separate browsers.
Our partner allows us to connect to http:// 10.20.20.10:8080, to reach https://application-x.theirinternal.domain. The proxy request therefor is "CONNECT https://application-x.theirinternal.domain", to http:// 10.20.20.10:8080.
I figure I should be able to setup a local squid, at which I point *.theirinternal.domain. A stunnel in front of it should deal with the https schema for the clients. No user authentication on the proxy host needed.
Is this a feasible solution, and how would I then instruct squid to always further proxy to the proxy 10.20.20.10 (as opposed to doing a real http connect against the destination domains)?
Comment: Can't you VPN to their network?  That's what I'd ask them to do for access to their services...
Comment: Tom: we use a vpn, and the proxy sits on their side. Policies and what not.
Comment: So you VPN in and they still want to proxy it? Strange people.
Answer: Set the remote proxy as cache_peer, using port 0 for ICP (squid only?).
cache_peer 192.168.3.75 parent 8080 0 no-query no-digest

Add an acl that matches the remote domain(s)
acl companycorp dstdomain .company.corp

never connect directly when going towards the company.corp.
never_direct allow companycorp

allow everything towards the remote proxy
cache_peer_access 192.168.3.75 allow all

Proxy to remote proxy?