Android: How to populate a spinner from saved openFileOutput Mode_PRIVATE?

Question: What i want to achieve is populating a spinner with previously created openFileOutput files.
This is the code for creating the files:
<code>save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FILENAME = filename.getText().toString();
                COMMENTS = comments.getText().toString();
                try {
                    FileOutputStream f = openFileOutput(FILENAME,
                            Context.MODE_PRIVATE);
                    f.write(COMMENTS.getBytes());
                    f.close();
                    Toast.makeText(getBaseContext(),
                            "Saved",
                            Toast.LENGTH_SHORT).show();
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

        });
</code>
So for example: I create these 3 files with the code above:
File1
File2
File3
I want my spinner to look like this:
File1
File2
File3
The problem i'm having is that i have no clue to how this is done.
I google searched it, but unfortunately no results.
Can someone explain to me how to achieve this, preferably with sample code?
Thanks!
Answer: I got it working.
It's really simple just use fileList ().
Populate an array with fileList (). And use that array as third argument of the arrayadapter.


Prove the set $S_{\mu}$ is convex

Question: Given the set $S_{\mu}=\{x\in\mathbb{R}^n:||x-a||\leq\mu||x-b||\}$ prove for which $\mu$ $S_{\mu}$ is convex $(a\neq b)$.
I'm not sure if my way was good.
let $x,y\in S_{\mu}$ and $0\leq\lambda\leq1$.
$||\lambda x+(1-\lambda)y-a||=||\lambda(x-a)+(1-\lambda)(y-a)||\leq \lambda||x-a||+(1-\lambda)||y-a||\leq\mu(\lambda||x-b||+(1-\lambda)||y-b||)$.
and this is only possible if $\mu>0$.
Comment: How does this prove convexity? You need to show $\|\lambda x+(1-\lambda)y-a\|\le\mu\|\lambda x+(1-\lambda)y-b\|$. If $\mu<0,S_\mu$ is empty and hence convex. If $\mu=0,S_\mu=\{a\}$ so still $S_\mu$ is convex.
Comment: but $a\neq b$ so any hint?
Answer: A warm thank to Shubham Johri who has pointed a big error of mine.
Two parts 1) and 2):

Where your argumentation is flawed.

You have to prove that
$$x,y\in S_{\mu} \implies \forall \lambda \in [0,1], x,y\in S_{\mu}$$
$$\iff \ \|\lambda x+(1-\lambda)y-a\|\le\mu\|\lambda x+(1-\lambda)y-b\| \tag{0}$$
What you do is to write the LHS of (0) in this way:
$$||\lambda(x-a)+(1-\lambda)(y-a)||$$
and then use majorations:
$$\leq \lambda||x-a||+(1-\lambda)||y-a||\leq\mu(\lambda||x-b||+(1-\lambda)||y-b||)$$
(nothing false ; but under the condition that $\mu>1$ !?).
But now, you are in the wrong position to apply triangle inequality and get the majoration of the RHS of (0).

A proof.

A first remark is that $\mu<0$ corresponds visibly to an impossible case when you see the definition, whereas the locus is surely nonvoid when $\mu \ge 0$ because considering points $x$ close enough to $a$ warrants the inequality.
Result: the convexity occurs for $0 \le \mu \le 1$.
We are going to prove explicitly that the locus is

a ball if $0<\mu<1$,

a point is $\mu=0$,

a hyperplane is $\mu=1$.

Here is why. Let us start from :
$$x \in S_{\mu} \ \iff \ ||x-a||^2\leq\mu^2||x-b||^2 \tag{1}$$
Let us treat the case $n=2$, for the sake of simplicity (the general case is straightforward). (1) can be written with evident notations:
$$(x-a_1)^2+(y-a_2)^2\le \mu^2((x-b_1)^2+(y-b_2)^2)$$
$$(x^2+y^2)(1-\mu^2)-2(a_1-\mu^2b_1)x-2(a_2-\mu^2b_2)y+(a_1^2-\mu^2b_1^2+a_2^2-\mu^2b_2^2) \leq 0\tag{1}$$
Consider now 3 cases.

If $0 \leq \mu \leq 1$, dividing (1) by $1-\mu^2>0$ gives an inequation of the form:

$$x^2+y^2-2x_cx-2y_cy+k \le 0$$
which is the interior of a disk with center $(x_c,y_c)$. Therefore, we have a convex set.

If $\mu > 1$, dividing (1) by $1-\mu^2>0$ gives an inequation of the form (take care to the reversal of the inequality sign):

$$x^2+y^2-2x_cx-2y_cy+k \ge 0$$
which is the exterior of a disk with center $(x_c,y_c)$. Therefore, we do not have a convex set.

if $\mu=1$**: the first term in (1) is cancelled, yielding a first degree equation, which is in a natural manner the perpendicular bissector of line segment $[a,b]$, a convex set.

Remark: the center of the disk is given by:
$$x_c=\dfrac{a_1-\mu^2b_1}{1-\mu^2}, \ \ y_c=\dfrac{b_1-\mu^2b_2}{1-\mu^2}$$
naturally situated on line segment $[a,b]$ (interior of a so-called "apollonian circle").

Here is a little graphical aid for the case $a=(0,0),b=(6,0),0\le\mu\le3$ (realized by
@Shubham Johri):
Comment: @Shubham Johri You are perfectly right! Sorry for having so persistent in the error. A warm thank.
Comment: Can you say if this presentation such as I have corrected is now convenient for you ?
Comment: Ok I will do it
Comment: @Shubham Johri. Thanks. Yes, edit it in my answer.
Comment: Wouldn't it be the exterior of a disk when $\mu>1$?
Comment: @Shubham Johri It is not possible because in this case it wouldn't be convex...
Comment: The given set is not convex for all $\mu$. I think the question is about finding those values of $\mu$ for which the set is convex. So we need to state that $\mu\le1$, no?
Comment: No, let us take the case $\mu=2$. Let us take $a=(0,0)$ and $b=(6,0)$. The locus is the closed disk with center $C=(-3,0)$ and radius $3$.
Comment: The locus of the **boundary** of the region is a circle but whether the feasible region is the interior or exterior of the circle is decided by the sign of $1-\mu^2$. I have [graphed](https://i.stack.imgur.com/dGwD6.png) the feasible region for your example and it is indeed non-convex.
Comment: hey @JeanMarie can you join the chat?
https://chat.stackexchange.com/rooms/115523/prove-the-set-s-is-convex
Comment: @Shubham Johri  Could you place your nice graphics as a (partial )answer ? I would be happy to upvote it. I think it would be of some help to people who do not know that one can easily manipulate inequations with Desmos.
Comment: Jean, I made a little animation [here](https://i.stack.imgur.com/htJl5.gif) for the case $a=(0,0),b=(6,0),0\le m\le3$. I would be more than happy to edit it into your answer if you are okay. Or you can edit it with the link.
Comment: @Shubham Johri Thanks again. I appreciate very much. Have you seen this article: https://en.wikipedia.org/wiki/Circles_of_Apollonius ?
Comment: @JeanMarie No, I haven't. I will go through it, looks interesting. Any specific section of interest?
Comment: @Shubham Johri In fact, this one is more precise: https://en.wikipedia.org/wiki/Apollonian_circles. One of the interests of this article is to show that to the first family (associated with distances' ratios) a dual family exists of (orthogonal) circles, this one associated to a preservation of angles. What is not said is that there exists a very nice complex function interpretation: take $Z=f(z)=\tfrac{z-1}{z+1}$. Then $\{z| \Re(Z)=\mu\}$ is the first family of circles and  $\{z| \Im(Z)=\nu\}$ is the second one, naturally orthogonal due to the fact that f is differentiable (holomorphic).

Prove the set $S_{\mu}$ is convex


A rigorous proof of continuous differentiability

Question: This small step comes from my reading on saddle point approximation: suppose
$$
w=\text{sign}(s)\sqrt{2(s K'(s)-K(s))}\tag{*}
$$
where $K$ is a convex and infinitely differentiable function on some open interval $I$ containing $0$. Moreover, $K(0)=0$. I would like to show that $w$ is a continuously differentiable function of $s$ on an interval around $0$.

Things I tried:

(*) implies: $\frac{w^2}{2}=sK'(s)-K(s)$ so that by "differentiating" both sides with respect to $s$, we get $w\frac{dw}{ds}=sK''(s)$ and so for $s\neq 0$, $\frac{dw}{ds}=\frac{s}{w}K''(s)$.
$\lim_{s\to 0}(\frac{s}{w}K''(s))=\lim_{s\to 0}\frac{s}{w}\lim_{s\to 0}K''(s)=\frac{1}{\sqrt{K''(0)}}K''(0)=\sqrt{K''(0)}.$ "Therefore", $w'(0)=\sqrt{K''(0)}$.
Consider $f(s,w)=-\frac{w^2}{2}+sK'(s)-K(s)$ hoping I could use the Implicit Function Theorem but $\frac{\partial f}{\partial w}$ is $0$ at $w=0$.

I put the words "differentiating" and "therefore" in quotations because they aren't justified until I can prove that $w$ is indeed a continuously differentiable function of $s$.
Answer: For $s>0$ or $s<0$, we have $w=+\sqrt{2(sK'(s)-K(s))}$ or $w=-\sqrt{2(sK'(s)-K(s))}$, respectively. In either case, $w$ is differentiable with $\frac{dw}{ds}=\frac{sK''(s)}{w}$.
Now, consider the derivative of $w$ at $s=0$. The right limit of the difference quotient is
$$
\lim_{s\downarrow 0}\frac{\sqrt{2(sK'(s)-K(s))}-\sqrt{2(0-0)}}{s-0}=\lim_{s\downarrow 0}\frac{\sqrt{2(sK'(s)-K(s))}}{s}.
$$
By Taylor's Theorem,
$$
sK'(s)=\sum_{n=1}^{\infty}\frac{K^{(n)}(0)}{(n-1)!}s^n,\quad K(s)=K(0)+\sum_{n=1}^\infty\frac{K^{(n)}(0)}{n!}s^n=\sum_{n=1}^\infty\frac{K^{(n)}(0)}{n!}s^n.
$$
Thus,
$$
sK'(s)-K(s)=\sum_{n=1}^\infty\left(\frac{1}{(n-1)!}-\frac{1}{n!}\right)K^{(n)}(0)s^n=\sum_{n=2}^\infty\left(\frac{1}{(n-1)!}-\frac{1}{n!}\right)K^{(n)}(0)s^n.
$$
It follows that
$$
\lim_{s\downarrow 0}\frac{\sqrt{2(sK'(s)-K(s))}}{s}=\lim_{s\downarrow 0}\sqrt{2\left(\frac{1}{2}K''(0)+\sum_{n=3}^\infty\left(\frac{1}{(n-1)!}-\frac{1}{n!}\right)K^{(n)}(0)s^{n-2}\right)}.
$$
Moving the limit inside the square root, we recognize the RHS above is just $\sqrt{K''(0)}$.
The left limit of the difference quotient at $s=0$ can be dealt with similarly and also yields $\sqrt{K''(0)}$. Thus, $w$ is differentiable at $0$ with the derivative equals $\sqrt{K''(0)}$.
Finally, to show that $w'$ is continuous, we need to show $\lim_{s\to 0}\frac{w}{s}=\sqrt{K''(0)}$. But this is done already because $\frac{w}{s}$ is just the difference quotient already considered above.


Want to ask if my answer is correct

Question: Okay, this started out as a question on what the questions mean, but I found out the answer midway while typing, not wanting to waste my keystrokes, I'm asking if my answers are correct instead.
(b)
You are in a project group of 4 persons which needs to complete 20 tasks. Each task is assigned to one person; hence, each person is assigned 5 tasks.
i) How many possible ways of assigning all tasks are there? ($3$ marks)
$$\frac{\frac{20!}{5!5!5!5!}}{4!} = 488,864,376$$
ii) There are two tasks which you particularly dislike. How many possible ways of assigning tasks are there where you are assigned both of there tasks? ($3$ marks)
$$\frac{\frac{18!}{3!5!5!5!}}{3!} = 102,918,816$$
iii) The project group randomly decides - with equal probability among all the possible ways - on one way of assigning the tasks. What is the probability that you are assigned both of the tasks which you dislike in Q1.(b)(ii)? ($4$ marks)
$$\frac{102,918,816}{488,864,376} = 0.211$$
iv) The project group decides that, instead of the method in Q1.(b)(iii), they will repeatedly choose a task at random and assign it to a member, until all the tasks are chosen. Each task has the same probability of being chosen at each time, and a task that has been chosen is removed from the set of tasks to choose from the set of tasks to choose from.
Given this method of assigning tasks, what is your probability of being assigned both of the tasks which you dislike? ( $4$ marks)
\begin{align*}
P & = \frac{2}{20}\\
Q & = \frac{18}{20}\binom{20}{2} \cdot \left(\frac{2}{20}\right)^2 \cdot \left(\frac{18}{20}\right)^{18} = 0.285
\end{align*}
Comment: In i) why did you divide by $4!$?
Comment: Actually, the "hence" in the problem statement ought to read "and", because what follows is not a consequence of what precedes it
Answer: (i) You already had the correct result, but then you divide by $4!$ for an unknown reason ...
(ii) The same, i.e., the division by $3!$ is uncalled for
(iii) Would be right if you had parts (i) and (ii) right
(iv) Why would this be different from (iii)?
Comment: Well, I actually follow this: http://www2.math.ou.edu/~amiller/2513/review/CountingProblemsAnswer.pdf  see Q32 and 33. And for the last one, I figure it is a discrete random variable.
Comment: Okay, I did an experiment, and the 4! and 3! are not needed.

Want to ask if my answer is correct


Append date to table name and create data frame iteratively

Question: My goal is to query data from redshift view where the view name is appended by monthdt like view_name_202009 and to query this view month by month for 13 months back, create dataframe and perform transformation. After the first dataframe(df1) is created the previous months transformed data should be appended to df1.
As a step by step approach:

Query current month dataframe
create dataframe (df1)
Perform transformation
Date decrement to previous month (repeat until 13 months back)

Below is the function I wrote to create the sql statements for 13months but I'm failing on passing them to the read_sql squetnailly and create dataframe.
def last_n_months(num_of_months, start_date=datetime.now(), include_curr=True):
    f = "%Y%m"
    curr = datetime.now()
    if include_curr:
        yield curr.strftime(f)
    for num in range(num_of_months):
        curr = curr.replace(day=1) - timedelta(days=1)
        sql = """select col1, col2,
                 from schema.view_name"""+str(curr.strftime(f))+"""  where col1 in ('01','02','1ST','2ND')"""
        # df = pd.read_sql(sql, con)
        yield sql

m_lst = [sql for sql in last_n_months(13, include_curr=False)]

df = pd.DataFrame()
for i in m_lst:
    df = df.append(pd.read_sql(m_lst, con))

I printed out the m_lst and it looks like below:
["select col1, col2 from schema.view_name_202010 where col1 in ('01','02','1ST','2ND')",["select col1, col2 from schema.view_name_202009 where col1 in ('01','02','1ST','2ND')",["select col1, col2 from schema.view_name_202008 where col1 in ('01','02','1ST','2ND')"]

I am getting an error as below:
pandas.io.sql.DatabaseError: Execution failed on sql : argument 1 must be a string or unicode object: got list instead

Can anyone help me where I'm doing wrong and if there is a better way of doing this?
Answer: Change this code bellow
df = pd.DataFrame()
for i in m_lst:
    df = df.append(pd.read_sql(i, con))

Comment: But that will only pass the first item in the list. What about the remaining 12?
Comment: My bad, I thought you had only one item in your list, I'll edit the answer.
Comment: I changed the answer, just delete what I said before and change this


Air filter stacking

Question: The idea of stacking air filters is a tricky proposition. With all these HEPA filters on the market , one may think a better flow can be achieved and better quality of air as a result of finer air-filtration in an existing system. Not unless you have a clean duct system that includes a clean return duct to the furnace/Air blower unit. You can over heat the motor and blow a circuit if you're not doing it properly.
My question is : why are there so many systems with so poor return ductwork ?
The filter at the blower exchange on the system picks up all the crap in the walls ! Cobwebs, dust bunnies, insects, hairs, plaster powder, you name it !
You can't improve air quality by just putting a HEPA filter in that Return environment! What are these installers thinking . Just as long as the Mfg. unit has its filter in place , that meets the warranty requirement ?
The HEPA filter is going to clog up , like tomorrow !
With a closed system, wouldn't it be a whole lot cleaner ? The mfg required particle filter size at the unit could be maintained while a second closer monitored HEPA filter could be at the register upstairs. Wouldn't that be efficient and cleaner air all around ?
My friend said her installer poopahed that and said she's jeopardizing the system. Meanwhile the return filter gets all this dirt from inside her open wall duct channeled through her house ? That's a pretty powerful blower too. I say this because we put a filter upstairs and it's cleaner than the filter at the unit downstairs. The problem was the unit filter clogged anyway and the breaker blew !
Comment: The system needs a clean return channel to make it efficient so all the return air is actually only from the inside living area of the house and not it's walls. That way a series of filters can be put in place, with the smaller particle filter being the one needing monitored and changed the most frequently. ( every 3 months)
Comment: I think air filters are also used for the occupants comfort. As you stated there's alot of air-born irritants floating around. Rather than having them endlessly recycled through the system the filters trap them keeping them from offending eyes and noses.
Comment: Really short answer: Laziness and apathy.
Comment: I thought there would be some codes regarding air quality on these install; but, it seems it's only about the units functional warranty . The mfg. can't depend on the various installers to protect their product, so they require the filter attached on the unit itself to be changed. That filter is about 3 micron to10 micron. Nothing sub micron or HEPA level is recommended because it would clog very quickly and affect the system's function. That submicron dust etc that gets through 3 microns gets blown out into the living space via the room registers.
It's like someone sneezing on you !
Comment: If the filter is not on the intake side preventing debris from entering the heat exchanger and turning into ash / shortening the exchanger life the filters don't d much good. When a filter is plugged the fan speed increases because there is not much load on the motor the high speed can damage some motors but not normally squirrel cage motors. HEPA filters on most air handlers actually leave the air dirtiest because of less exchanges some HVAC techs don't have this training but understand higher density do more harm than good unless the system is designed for it.
Comment: There is a lot of rambling and speculation in your question. Please feel free to [edit] it to clarify exactly what your situation is and what you're asking. Noting that your friends installer is a "poopahed" isn't really helpful or useful and doesn't add anything to the question. Stick to facts and you'll get a better answer.
Answer: Filtering is not only a science but a big cost impact on system design.
I install filters at the entrance to the trunk duct then add electrostatic at the furnace entrance, some put high MERV or even HEPA at the furnace and here are the reasons;
The problem with HEPA filters is the pressure drop across them if used at the entrance trunk ductwork will oil can or pop because of the pressure, flex duct will pull away from the vents so it is not lazy that they are not put at the entrance it is for system performance and longevity at the furnace location, High MERV filters change the load on the fan motor by not moving air the speed actually increases the speed and reduces motor life.
HEPA is almost as good as electrostatic but after installing the electrostatic is much cheaper and will take even smoke particles out that HEPA can not.
Electrostatic / fiberglass entrance equals a lower combined pressure drop a simple fiberglass filter at the entrance and electrostatic at the furnace provides the cleanest air especially if the system fan is left on for constant cleaning. Allowing the fan unit to move air efficiently more exchanges per hour.
To maintain a electrostatic filter the elements need to be rinsed off I do mine monthly or any time I hear popping in the filter (dirt bridging the insulators)
I mentioned after install the electrostatic is less expensive but the cost is higher up front it takes a few years of replacing high end filters for the electrostatic to be less expensive and this cost is the reason the best filtration is not installed in all systems.
Making a opening in the duct at the furnace is simple and cost almost nothing for the filter 1" to 4" no difference (Installing the electrostatic is just as easy on a new system). So again it comes down to cost.
Where lazy or a lack of knowledge comes in is not knowing the air handlers "flow" curves. Installing a filter with a higher pressure drop can reduce the motor life as suggested above but locating filters close to the fan filter reduces the high pressure on the trunk line, to maintain dust & dust bunny free trunk lines the inexpensive fiberglass filters at the entrances work quite well without the negative effect of a high pressure drop.
Comment: All that said, would you not want a cleaner pathway to the return of the unit ? My furnace unit is under my house in a crawl space. I'm not going to crawl down under the house to change filters because of proximity placement to the exchanger. It seems logical that cleaner filtered air coming through the return is going to give cleaner air back to the living areas.
Comment: Electrostatic feature seems like an excellent idea especially for heated air and for those of us who have wall to wall carpets too.
Comment: Gerry a high MERV filter at the inlet in your case may collapse the ducts if metal trunks they will buckle and "oil can" with each cycle creating quite a racket. If flex duct the ducts usually break away because the vacuum deforms and pulls the duct cutting the plastic covering then the air from that space is pulled in. I know of 1 person that was a clean room operator that did just this in an attic, less than a year later the heat exchanger failed and although a top brand it was not covered by warranty because of the fiberglass was the cause of the failure all from a HEPA filter on flex duct.

Air filter stacking


Meteor-angular: Add logic to retrieved collection before returning $scope.variable

Question: I have a branches collection, in which every document store lat and lng values. I need to find all the branches that are within a fixed circular range from a specific point (which gets read from the url after a post form). To perform such calculation I'm using geolib
As I'm new to Meteor, I'm having issue in understanding where to put such logic. As far as I understood I should use Meteor.methods, however the find() within my method does not retreive any results.
Here is my code:
// client/search/controllers/searchRestaurants.ng.js
angular.module("MyApp").controller("SearchRestaurantsCtrl",
    function($scope, $stateParams, $meteor){

        $meteor.subscribe('branches');

        $scope.branches = $meteor.call('findNearestBranch', $stateParams.lat, $stateParams.lng);
    }
);

// model/branches.js
Meteor.methods({
    findNearestBranch: function(lat, lng) {

        var branches = {};

        // Branches.find().count(); returns 0; so the following does not get fired

        Branches.find().forEach(function(branch) {

            distance = geolib.getDistance(
                { latitude: lat, longitude: lng },
                { latitude: branch.lat, longitude: branch.lng }
            );

            if ( distance < 5000 ) {
                branches.push(branch);
            }
        });

        return branches;
    }
});

// client/search/views/search-restaurants.ng.html

        {{branch.name}}

// client/routes.ng.js
angular.module("MyApp").config(
    function($urlRouterProvider, $stateProvider, $locationProvider){

        $locationProvider.html5Mode(true);

        $stateProvider
            .state('searchRestaurants', {
                url: '/search/:lat/:lng',
                templateUrl: 'client/search/views/search-restaurants.ng.html',
                controller: 'SearchRestaurantsCtrl'
            });
    }
);

Answer: I think methods are generally used for operations that create, modify or delete data, since those are the operations that you really need to protect. For finding and getting data, you typically just use methods on the collection object (like .find(...)) and use a publication to limit what documents are available in said collection (on the client).
That said, I would let the publication limit my results to only those that are applicable, which in you case would be those within a certain distance of the specified lat and lng coordinates. Additionally, I would use mongo's $near operator instead of geolib.
Here is a pseudo-coded example of what I would do:
// in controller: assuming collection is called Branches
$meteor.subscribe('branches', {lat:$stateParams.lat, lng: $stateParams.lng});
$scope.branches = $meteor.collection(function() { return Branches.find(...); });

// in publication: assuming collection is called Branches and docs in the collection have a property called location.
Meteor.publish("branches", function (opts) {
   var lat = opts.lat, lng = opts.lng;

   return Branches.find({
      location: {
        $near: {
          $geometry: {
            type: "Point",
            coordinates: [lng, lat]
          },
          $maxDistance: 5000
        }
      }
    });
});

Answer: Great, thank you GPicazo. I didn't know about mongodb $near.
I ended up doing just this:
// Controller
angular.module("MyApp").controller("SearchRestaurantsCtrl",
    function($scope, $stateParams, $meteor){

        $meteor.subscribe('branches');

        $scope.branches = $meteor.collection(function() {
            return Branches.find({
                loc: {
                    $near: {
                        $geometry: {
                            type: "Point",
                            coordinates: [ $stateParams.lng, $stateParams.lat]
                        },
                        $maxDistance: 5000
                    }
                }
            });
        });
    }
);

// View

    {{branch.name}}

Comment: Your solution is fine, just keep in mind that by filtering you collection on client as opposed to the server (in the publication), you are sending more data than what is needed to the client. Either way, I'm glad I could help.
Comment: Weirdly, if I try to implement your solution it errors: `$near requires a point, given { type: "Point", coordinates: [ "-121.88355687", "37.44609999" ] }`
Comment: If I tried the query directly on the db it was returning an error due to the lack of a index, so I've created it with `db.branches.ensureIndex({coordinates:"2dsphere"});` and now it works if querying directly mongo; however using meteor from server-side still does return the same error
Comment: Are the coordinate values quoted (strings)? I believe they may need to be floats.
Comment: Yep, that was it: `coordinates: [ Number(opts.lng), Number(opts.lat)]` thank you!
Comment: No problem. If you ended up implementing the solution I suggested in my original answer, please mark it as accepted.


Why can't I force Football Manager 2017 to use the Nvidia graphics card?

Question: I have a problem with Football Manager 2017. The text looks blurry when I'm starting it on my laptop (Windows 10). The resolution on my laptop is 1360x768 (In game it is 1366x768). I have 2 video cards

Intel(R) HD Graphics 4000
Nvidia GeForce 610m 2GB

I don't know that much about video cards but I read that the normal approach is to use Nvidia for your games and the intel driver for normal usage. Correct me if I'm wrong.
When I checked my Football Manager it was using the intel driver (I got 1/5 stars for the 3D strength of my laptop):

So I tried to force my game to use the nvidia driver (using the Nvidia configuration screen). It's in Dutch but you'll understand it.

But no success. The text of the game remains blurry + the driver did not chance.
Can someone tell me what I'm doing wrong?
I checked with a friend and his Football Manager game was using his Nvidia card by default (other intel + nvidia card).
I updated my drivers.
Comment: Just for clarification, you only have 1 "video card" (the 610m - and its not really a card in the case of a laptop but people still call it that).  The Intel graphics are integrated with your Intel processor.  What you really have are two GPUs.
Comment: Did you make sure to reboot/shut the game down first?  It seems like you've followed the correct steps based on the developer's own page: https://community.sigames.com/faq/football-manager-2017/84_how-to/89_pc/how-to-configure-my-laptop-to-run-football-manager-with-optimal-settings-pc-r226/
Answer: Give what LeonMordecai said in this post a shot:

Right click on the desktop and open nvidia control panel (or you can go find the nvidia icon on the taskbar)
Navigate to "manage 3D settings" drop down under 3D settings.
Under the global settings tab, underneath preferred graphics processor, change it from auto detect to high performance graphics processor.

This will make is so your laptop will always use the 610m GPU (instead of just for the specific .exe). If that doesn't work, try disabling your integrated graphics completely (you'd rather be using the 610m over the integrated anyway).


Remove lines which contain 'logging'

Question: I have the following codes:
class Solution:
    def three_sum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        output_set: set = set() #Notice
        if len(nums) < 3:
            return []

        for i in range(len(nums)-2): #at least 2 element left
            sub_nums = nums[i+1:]
            sub_target = 0 - nums[i]
            logging.warning(f"sub_target: {sub_target}")

            two_sum_output = self.two_sum(sub_nums, sub_target)
            logging.warning(f"two_sum_output: {two_sum_output}")
            if two_sum_output != None:
                temp = { (nums[i],) + tuple(l) for l in two_sum_output }
                output_set.update(temp)
        output = [ list(t) for t in output_set] #conver to list
        logging.warning(f"final output count: {len(output)}:\n {output}")

        return output

I want to delete lines with logging,
grep could them
$ grep "logging" twoSum.py
import logging
# logging.disable(level=CRITICAL)
logging.basicConfig(level=logging.debug,
logging.info(f"Start of twoSum Process {os.getpid()}")
# logging.debug(f"{ps.stdout.decode('utf-8')}")
            logging.info(f'find: {find} ')
            logging.info(f"j: {j}")

How could delete them?
Comment: Beware that the line containing `basicConfig` seems to continue on the next line and removing just the first line probably brakes your code.
Answer: use grep -v and copy to another file
grep -v logging twoSum.py > logging-new

Notes:

this does what you ask for, removing the physical lines containing
"logging". That might be a bad idea, as noted by PerlDuck
if there is no space or strange char in the grepped text, you don't need " or '.

Remove lines which contain 'logging'


Is there need for social media plugins on an established ecommerce website

Question: The ecommerce retailer I work for is national market leader in its respective branche and even in some other surrounding countries. It's SEO is amazing and they already have an established position within Google only having Wikipedia above them with generic search terms. They're very active on social media and produce a fair amount revenue from that. Therefor one can argue the use of social media plugins they still have on their site. That they've become unnecessary.
They have the facebook plugin showing people how many people liked their FB page and if you're automatically logged in to your facebook account it shows how many of your friends like the page. They also have a Twitter feed showing all their tweets.
In my opinion it has no place on the front page anymore.
The front page is cluttered and I want to cut away a lot of elements. But I got to have solid arguments for doing so, because some other people from certain departments will hate to see it go, because maintaining the social feed is a big part of their daily activities.
Right now I can only come up with arguments concerning the aesthetic value.

It tacky
It's an eye sore
It's not 2014 (not even 2013!)

The argument of it being unnecessary at this point in time won't stick because it has no visible negative effect. Their positive effects however have satiated, no new leads are being created because of the social plugins on the front page. At least, no where near what it used to be. Only the possibility of it creating more leads is keeping it afloat.
So I'm in search of negative influences these social plugins might have on the user experience, conversion rate or some other value.
Comment: Worth reading:  http://ia.net/blog/sweep-the-sleaze/
Answer:
If plugin breaks (temporary outage, deprecation, whatever) it is your site whose reputation is damaged, not FB's
Extra resources to load => slower site
Prominence of other brands dilutes your own
if you were to write a list of stack-ranked goals for each page of your site I doubt that "send people to our Twitter" would make the cut, yet I assume its prominence on your site indicates otherwise. Any pixels used for social are pixels not used for revenue-generating activities. It would be reasonable to actually quantify the % of visual space given to these and see how it compared with, say, the size of a Checkout button.

To anyone supporting the plugins I would ask them to empirically define goals. It's unlikely that they'll be able to weave a story that begins at those buttons and ends in a transaction. Bottom line bottom line bottom line.
Comment: Loadtime, ofcourse. The FB plugin alone take 400ms to load. A big ass banner we have takes 40ms. Your other points I haven't thought of and I will surely include those. Let's keep the question open for more suggestions.
Comment: +1 for "ask them to empirically define goals... transaction". Well said.
Answer: You said in your question,

some other people from certain departments will hate to see it go, because maintaining the social feed is a big part of their daily activities.

That tells me this is politically charged so you will need to listen to their concerns while countering with your need for justification of everything that makes it to the home page. If you opt to include social in a mega-footer, you will be able to minimize the visual impact of these elements. Or, create a social dashboard and link to it off the home page, in effect giving social more space but taking the content off the home page. That will further justify the social team's existence without alienating them. If your home page is approaching "horror vacui", it's time to have this conversation.
As far as negative influences, how about looking dated? My kids (in their 20s, all), have largely abandoned Facebook and have embraced Tumblr mostly because their parents aren't on it. ;-). In six months, a prominent FB logo may well say "This site is for old people".
Comment: The matter will certainly will be discussed with the social media people who are concerned with this too. I was already thinking about social icons linking to the respective social enviroments. Is that what you meant by including social in a (mega-)footer?
Comment: Yes, small versions of the icons in a mega-footer was my thought.
Answer:
"no new leads are being created because of the social plugins on the front page"
"I'm in search of negative influences these social plugins might have on... conversion rate"

As this topic is potentially politically charged and you are dealing with a larger company (presumably with a marketing team) your argument should include numbers. What analytics have you done to prove no new leads are being generated from the social plugins? I would track the number of users that actually click on the social media button. Gather statistics and show charts (with numbers) to support your hypothesis. A quick look at Google Trends does not support your argument. What is your target age demographic? What is your actual age demographic (w/ evidence from Google Analytics). If you are targeting a younger audience prove that Facebook is being abandoned by youth statistically. You do have an argument that additional page load time lowers SEO. Most of these social plugins rely on iframes from third party sites, meaning social plugins equals more HTTP requests (a big bottleneck in page load speed). Most importantly prove the buttons are no longer being used. You're dealing with a marketing team, so your intuition as a designer will not cut it. You need to back up your reasoning with statistics and graphical analysis.


Cargo.toml for lib

Question: I want to create a library for rust. This is the Cargo.toml file for my project :
[package]
name = "binary_tree"
version = "0.0.1"
authors = ["Guillaume Bersac <firstname.lastname@example.com>"]

[lib]
test = true
plugin = false

This is the file of my repository :
Cargo.toml
README.md
src
|_node.rs

When I run the command "cargo run" or "cargo build" or "cargo test", I get the following error message :

Cargo.toml is not a valid manifest
expected a value of type array, but found a value of type table
  for the key lib

How to format my Cargo.toml so that it compile correctly ?
Comment: What Cargo and Rust versions are you using? It sounds to me like you're using an old version of Cargo.
Answer: Are you running the latest rustc and cargo? If not, I think you used to need [[lib]], which creates a table array in TOML.
Comment: Cargo does not use `[[lib]]` any more, hasn't for a couple of months. `[lib]` is correct.
Answer: This is the correct Cargo.toml :
[package]
name = "binary_tree"
version = "0.0.1"
authors = ["Guillaume Bersac <firstname.lastname@example.com>"]

[[lib]]
name="binary_tree"
test = true
plugin = false

It looks like I am running an old version of cargo. It is strange because I installed it yesterday following the official guide and using this command :
$ curl -s https://static.rust-lang.org/rustup.sh | sudo sh

My rustc version is : rustc 0.13.0-nightly (40b244973 2014-10-14 23:22:20 +0000)
My cargo version is : cargo 0.0.1-pre-nightly (9788700 2014-10-15 20:14:53 +0000)
Comment: In the future, it would be courteous of you to leave a comment asking the answerer to expand with a full example.
Comment: I'm not sure why you unaccepted my answer. My answer included a guess that you were using an old `cargo` and that you probably needed to use `[[lib]]`. Indeed, that's precisely what you have here.
Comment: Your answer is right, I defined my answer as beeing the right answer because my answer is more precise than yours (example of the solution). It is better for any user who come on this page to see the most detailed answer. Sorry for the 15 reputation point you lose because of that changement.

Cargo.toml for lib


How to kill the enemy soldier in the bathroom in Battlefield 3?

Question: The bigger question is how to actually fight with the hands in Battlefield 3?
I am stuck at the part where you have to clear that top floor and you climb the back of the building with another soldier. When the 2 of you enter the bathroom an enemy soldier attacks your mate and you have to get him off your partner. You do this by pressing "o". Then the screen tells you to press something real fast, it just flashes on the screen for a millisecond so I can't tell what it is.
I keep having to repeat this part because I don't know what to press to kill the guy. What do you have to press after pressing the "o"?
Comment: possible duplicate of [How to defeat the Bank ambush in Battlefield 3](http://gaming.stackexchange.com/questions/34172/how-to-defeat-the-bank-ambush-in-battlefield-3)
Comment: @agent86 it's not because that question is targeted towards PC users. I am on a PS3, sorry should have mentioned it. I need to know which button to press on a PS3 controller.
Answer: I think it could be a fire button, the one you shoot with, R1 probably?
Comment: Yeah thats it, now I'm having trouble at the part where I have to toss the guy onto the tracks. It doesn't tell me which button to press after o, r1 and x. It's so annoying!


How to optimize the jquery animate code

Question: Hi I am doing a zoom in & out using jquery animate. The problem is it is too slow and takes too much of time. The animate function is going to zoom approximately 100's of divs. Can some one please tell me what should be done to make it optimized. Here is the code below
        //Zoom In by clicking the plus button
        $("div#explanation .plus").click(function(){
        jsPlumb.repaintEverything();
/*              var strongFont = parseFloat($("div.window strong").css('font-size'));
            var newStrongFont = strongFont + 2;
            //alert("the new font is"+strongFont);
*/
            $("div#demo1").animate({'height':'+=20', 'width':'+=20'});
            $("div.window ").animate({
                    'height':'+=20px', 'width':'+=20px'
                },0,function(){
                    jsPlumb.repaintEverything();
            });

    /*              $("div.window strong").animate({
                    fontSize:newStrongFont
            },0,function(){
                jsPlumb.repaintEverything();

            });
                    */
        });

I am having similar to zoom out. Please guide me. Thanks!
Comment: Where is the code for `repaintEverything()`? Could be needed.
Comment: 100's of divs at the same time? That is going to be a redraw nightmare.
Comment: jsPlumb.repaintEverything() is an library function provided by jsPlumb.
Comment: @epascarello: i know redrawing is going to be nightmare. But when i open the firebug and did a zoom, i saw it also takes a lot of time to calculate new height and window for the div.
Comment: Add break point in firebug script tab at the jQuery animate function and go inside each step you'll able to see where it's taking more time.
Answer: First off, you have to realize that you're almost certainly not going to get good performance aniating hundreds of elements.  It's just too much for the browser to handle.  I would try to animate a single container element to achieve whatever effect you're going after.
That said, you might want to take a look at the animate-enhanced plugin.  In browsers that support CSS animation, the plugin automatically translates .animate(...) calls into CSS animations, which are usually hardware-accelerated.  This gives much better performance than animate's usual method of changing an element's properties on a set interval.
You might also try using CSS animation directly if the plugin doesn't help.  I'm not sure whether you're really trying to animate the size of the box or if you're trying to animate an actual zoom (where the box and all of its contents get bigger), but here's an example that animates the latter:
div {
    width:200px;
    height:200px;
    background:red;
    color:white;
    margin:20px 50px;
    padding:5px;

    -webkit-transform-origin: 50% 50%;
    -moz-transform-origin: 50% 50%;
}

div:hover {
    -webkit-transform: scale(1.4);
    -moz-transform: scale(1.4);
    -webkit-animation-name: popin;
    -moz-animation-name: popin;
    -webkit-animation-duration: 350ms;
    -moz-animation-duration: 350ms;
}
@-webkit-keyframes popin {
    from {
        -webkit-transform: scale(1);
    }
    to {
        -webkit-transform: scale(1.4);
    }
}
@-moz-keyframes popin {
    from {
        -moz-transform: scale(1);
    }
    to {
        -moz-transform: scale(1.4);
    }
}

Answer: The time for the animation to complete is something you can specify as the second argument to .animate().  You have not specified it so the default is 400ms.  You can set it to whatever you want.  The animation will always complete in approx the time that you set, but if there is too much work for the computer to do in that time to show you a smooth animation, you will get a jumpy one.
The only way to make an animation less jumpy is to optimize what you are animating or how you are animating it.  Animating 100s of divs at the same time is probably more than anything but a very, very fast computer can do smoothly.
You will probably want to rethink what you are animating.  One possible work-around in cases like this to animate an outline rather than the entire contents when the contents are really complex to animate with good performance.
If you want further help, you will have to show us more of the problem.   We need to see the HTML you have so we can see what you're really trying to animate and we probably need to see the repaintEverything() function to see what it's doing.
Comment: Thanks that was helpful. Can you please tell me how to animate only the outline? As well repaintEverything() method is a built-in defined function which comes with jsPlumb library. All the 100 divs are actually the rectangular windows linked one another.
As well one question: Is jsPlumb.repaintEverything() method is getting called after every animate call or at the last animate call? I need to call that method at the very end when all the divs have changed their height and width.
Answer: If you're not too concerned about older browsers, you might be able to use css transform properties for this. They usually work quite quickly, allowing you to efficiently zoom in on a complicated section of the document. Here's a contrived example, which uses jQuery to zoom in on something whenever it's clicked. Animating would get more complicated: I don't believe jQuery's animate works with transform, but in theory you could repeatedly adjust the scale on a small level using timeouts.

How to optimize the jquery animate code


Python swig - create swig wrapped instance from ctypes pointer

Question: I have C++ code with a class wrapped with swig. I cannot modify the code or the wrapping.
In python, I have, using ctypes, a pointer to an instance of said C++ class.
How can I create a swig wrapper around this pointer?
I know that swig objects hold a 'this' attribute which internally points to the wrapped object, but I couldn't find a way to set it to the pointer that I have on hand.
Thanks for the help!
Answer: You can do this, but it's rather a lot of work and it would be much simpler to fix the underlying problem of making either the ctypes or the SWIG interface complete and usable than force interchangeability. (It's also worth noting that it's easier to create a ctypes object from a SWIG one than it is to do what you're trying to do, which is to create a SWIG object from a ctypes one).
To illustrate this I've created the following header file that we'll wrap with SWIG:
struct Foo {
  double d;
  char msg[20];
};

Then I wrapped it with the following interface:
%module test

%{
#include "test.h"
%}

// Prove I'm not cheating here - we can't even instantiate this class
%nodefaultctor;

%include "test.h"

I also added a test function for us to call from ctypes, that isn't SWIG wrapped:
#include "test.h"

// This function returns a Foo, but is only accessible to ctypes
extern "C" Foo *fun1() {
    static Foo f = { 1.234, "Hello" };
    return &f;
}

Your guess about this this attribute of SWIG wrapped classes is a good starting point, but it's not as simple as just changing that - the type of the object you slot in has to match what SWIG expects. It's more than just a pointer represented as an int:
repr(test.Foo().this) # You'll need to drop the nodefaultctor directive to see this
"<Swig Object of type 'Foo *' at 0x7f621197d1e0>"

If we inspect the source code that SWIG generates we can see that there is a function which takes a pointer, some type information and creates these objects for us:
SWIGRUNTIME PyObject *
SwigPyObject_New(void *ptr, swig_type_info *ty, int own);

Let's ignore the fact that SWIGRUNTIME is defined as static by default for now, to get us started experimenting with this runtime we can redefine it to extern. Later we'll look at workarounds for when we can't do that.
So our goal is to take the output of the "ctypes only" function and pass it, via more ctypes calls into SwigPyObject_New to create something we can swap around for with the this attribute of our SWIG module.
In order to call that we'd normally call SWIG_TypeQuery to lookup the correct swig_type_info to use. However this is actually a macro, which expands to pass in some static variables that are always static. So instead we'll be using this function:
SWIGRUNTIME swig_type_info *
SWIG_Python_TypeQuery(const char *type)

(with the same SWIGRUNTIME proviso).
At this point we've got enough that we could swap the this attribute of a surrogate object and be done if we were able to construct donors. (Although that would leak). There are two ways we can make this nicer:

Monkey patch __init__ inside test.Foo to work. This is best if you really have %nodefaultctor inside the SWIG interface you don't want to recompile:
def patched_init(self, ptr):
    self.this = ptr
test.Foo.__init__ = patched_init

Create a new class that only has an __init__ which sets the this attribute before modifying the __class__ attribute and use that instead:
class FooCtypesSwigInterop(object):
    def __init__(self, ptr):
        self.this = ptr
        self.__class__ = test.Foo

this option makes most sense when you don't want to break test.Foo's existing __init__ implementation.

With that said we can now achieve our initial goal with something like this:
import ctypes
import test

# This *must* happen after the import of the real SWIG module
# 0x4 is RTLD_NOLOAD which ensures that we get the same handle as the Python
# import did, even if it was loaded with RTLD_LOCAL as Python is prone to.
swig_module = ctypes.PyDLL('./_test.so',ctypes.RTLD_LOCAL|0x4)
# Note that we used PyDLL instead of CDLL because we need to retain the GIL

# Setup SWIG_Python_TypeQuery to have the right argument/return types
# (Using void* as a substitute for swig_type_info*)
SWIG_Python_TypeQuery = swig_module.SWIG_Python_TypeQuery
SWIG_Python_TypeQuery.argtypes = [ctypes.c_char_p]
SWIG_Python_TypeQuery.restype = ctypes.c_void_p

# Likewise SwigPyObject_New, using ctypes.py_object though for return
SwigPyObject_New = swig_module.SwigPyObject_New
SwigPyObject_New.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int]
SwigPyObject_New.restype = ctypes.py_object

# Actually do the type query for the type our ctypes function returns:
SWIGTYPE_p_Foo = SWIG_Python_TypeQuery('Foo*')
print(hex(SWIGTYPE_p_Foo))

# Now the ctypes function itself that returns the type we want SWIG managed
fun1 = swig_module.fun1
fun1.argtypes = []
fun1.restype = ctypes.c_void_p

# Make the actual ctypes call we care about here
result = fun1()
print(hex(result))

# And then create a SwigPyObject for it from the void* return type
# Note that 0 means not owned by SWIG
sresult = SwigPyObject_New(result, SWIGTYPE_p_Foo, 0)
print(repr(sresult))

# This is how we jimmy it back into the this attribute of a SWIG type
class FooCtypesSwigInterop(object):
    def __init__(self, ptr):
        self.this = ptr
        self.__class__ = test.Foo

c = FooCtypesSwigInterop(sresult)

# Finally a usable SWIG object from the ctypes call
print(c.msg)

This all compiles and works with:
swig3.0 -python -c++ -Wall test.i
g++ -shared -o _test.so test_wrap.cxx fun1.cc -Wall -Wextra -fPIC -I/usr/include/python2.7/ -std=c++11 -DSWIGRUNTIME=extern
LD_LIBRARY_PATH=.  python run.py

And gives us:
0x7fb6eccf29e0
0x7fb6eccf2640
<Swig Object of type 'Foo *' at 0x7fb6ee436720>
Hello

To work around the problem of having SWIGRUNTIME defined as static you'll need to do one more step. Either use debug symbols or reverse engineer the SWIG binary module you've got but can't modify to find the addresses of the two functions we need that aren't exported relative to an exported symbol. You can then use those to construct ctypes function pointers instead of looking them up by name. Of course it would be easier to buy/find/re-write the SWIG module, or add the missing features to the ctypes interface probably.
(Finally it's worth noting that although it doesn't seem to apply here if SWIG runs with -builtin some substantial changes will need to be made for this answer to work).
Comment: I can add more details on the reverse engineering needed for Windows or Linux. There is probably another way of doing this, which would be more hacky, but possible using ctypes itself to layout the SWIG Python object itself directly.
Comment: Thanks a lot, this is a very detailed and helpful answer. I've been working on this most of today and got quite close, with a similar concept. I still have a small problem with the swig_type_info, I can't use your suggestions, since I got multiple versions of the library. I opted to reconstruct the swig_type_info and fill it using based on the wrapper class names (somewhat nasty, but seems to work). Again, thanks for the help.
Comment: Yeah that's a good way to do it also, but harder than just using the lookup helper functions.


pandas dataframe grouping by class and timestamp

Question: I have a dateframe that looks like this:
timestamp               class
2019-07-01 00:59:56     A
2019-07-01 11:24:19     B
2019-07-01 12:41:34     B
2019-08-01 05:22:11     A
2019-08-01 07:05:06     A

now I need to know how many rows of each class do I have on a particular day.
So the final result should look like this:
timestamp       class    count
2019-07-01      A        1
2019-07-01      B        2
2019-08-01      A        2

I'm not sure how I should even start to approach the problem.
Thanks in advance!
Answer: Use GroupBy.size with Series.dt.date:
#if necessary
df['timestamp'] = pd.to_datetime(df['timestamp'])

df1 = df.groupby([df['timestamp'].dt.date,'class']).size().reset_index(name='count')
print (df1)
    timestamp class  count
0  2019-07-01     A      1
1  2019-07-01     B      2
2  2019-08-01     A      2

Or GroupBy.count with specify column after groupby:
df1 = df.groupby([df['timestamp'].dt.date,'class'])['class'].count().reset_index(name='count')
print (df1)
    timestamp class  count
0  2019-07-01     A      1
1  2019-07-01     B      2
2  2019-08-01     A      2

Difference is count exclude missing values, size not. But because here is also passed class column to groupby in by parameter then it working same - both solutions exclude missing values.


What is the use of HeaderedContentControl in wpf?

Question: I am working on WPF but the UI is localized for the  Gujarati language. In my window.xaml I have 2 rows and 2 columns.
I could not get use of the HeaderedContentControl tag.  The code is here:
<Border
            Grid.Row="1" Grid.Column="1"
            Style="{StaticResource MainBorderStyle}"
            Padding="0"
            BorderThickness="0,0,0,1"
            Background="#f9f9f9">
            <HeaderedContentControl
                VerticalContentAlignment="Stretch"
                Content="{Binding Path=CurrentWorkspace}"
                Style="{StaticResource MainWorkspaceStyle}"
                ContentTemplate="{StaticResource WorkspaceTemplate}"/>
        </Border>

Please explain it and also explain role of content template.
Answer: A HeaderedContentControl is a control that displays other controls, but also provides a header for that (like a GroupBox or window title).
The HeaderedContentControl is bound to a set of data-- in this case "CurrentWorkspace".
The ContentTemplate describes how that data should be displayed.  In this particular case, it is something called "WorkspaceTemplate", which will be defined as a Static Resource somewhere in the project-- either in a resource XAML file, or, perhaps in your window, under <Window.Resources> at the top of the XAML.
No matter where it is, if you search through your entire solution for WorkspaceTemplate you should eventually see where it is defined.
Comment: To add on to an already great answer: another example of a HeaderedContentControl is a tab page within a TabControl.  You can put whatever you want in the tab's header (often a string and a small graphic) in addition to displaying some content.
Comment: You can also use HeaderedControlControl directly in cases where you want a label positioned next to a control. This is one way to make the positioning of labels more consistent through an application.


Ubuntu boot problem, I think it's partition

Question: After I chose Ubuntu in grub 2.06 I saw this error:
Comment: Does it eventually boot afterwards?
Comment: What do you think is wrong with the partition?
Comment: ACPI errors are not normally a problem. https://askubuntu.com/questions/1333069/acpi-error-on-every-boot

Your root partition reports as clean. If your system boots and works normally there is nothing to worry about.
Comment: The problem is system doesn't boot eventually and don't work normally, and stay at this screen.
Comment: Glad you found a solution. This may also be helpful, to get it to boot. Edit grub GRUB_CMDLINE_LINUX_DEFAULT="rhgb acpi_enforce_resources=lax pcie_ports=compat" as this partly ignores ACPI and should get you to boot.
Answer: I'm finally find the solution.
Ubunto's shell can't match by my graphic cart.
I set it on my graphic cart "rtx3050ti" in recovery mood,and problem solved.


declare component to all routes react-router

Question: i have a header and inside it i have Link components to navigate for any pages, and the header need show on all routes, i put Header component inside switch method because i have  component inside it. but the header componet is render alone, the other components not are rendered, only the header component.
class App extends Component {
    render() {
        return (

                <BrowserRouter>
                    <Switch>

                        <Route path={'/'} exact={true} component={Main}/>
                        <Route path={'/cursos'} exact={true} component={Cursos}/>
                        <Route path={'/forum'} exact={true} component={Forum}/>
                        <Route path={'/login'} exact={true} component={Login}/>
                    </Switch>
                </BrowserRouter>

        );
    }
}

Answer: Try something like this:

class App extends Component {
    render() {
        return (

                <BrowserRouter>
                  <React.Fragment>

                    <Switch>
                        <Route path={'/'} exact={true} component={Main}/>
                        <Route path={'/cursos'} exact={true} component={Cursos}/>
                        <Route path={'/forum'} exact={true} component={Forum}/>
                        <Route path={'/login'} exact={true} component={Login}/>
                    </Switch>
                  </React.Fragment>
                </BrowserRouter>

        );
    }
}

Switch is designed to render only one child (the first that matches).
Comment: Its works, i will study more about React.Fragment, Thank you very much


A difficult logarithmic integral ${\Large\int}_0^1\log(x)\,\log(2+x)\,\log(1+x)\,\log\left(1+x^{-1}\right)dx$

Question: A friend of mine shared this problem with me. As he was told, this integral can be evaluated in a closed form (the result may involve polylogarithms). Despite all our efforts, so far we have not achieved anything, so I decided to ask for your advice.
$$\int_0^1\log(x)\,\log(2+x)\,\log(1+x)\,\log\left(1+x^{-1}\right)dx$$
I found some similar questions here on MSE:
(1),
(2),
(3), (4),
(5),
(6),
(7),
(8), (9), (10),
(11), (12),
(13), (14).
Comment: It can be represented as a difference of 3-factor integrals (with powers): ${\Large\int}_0^1\ln(x)\,\ln(2+x)\,\ln^2(1+x)\,dx - {\Large\int}_0^1\ln^2(x)\,\ln(2+x)\,\ln(1+x)\,dx$, that makes it more similar to other integrals you mentioned.
Comment: $$I=4\log^2(2)-2\log^3(2)-\frac74 \zeta(3)\log(2)-2\sum_{n,m=1}^{\infty}\frac{(-1)^{m+n}H_m}{2^nn(m+1)(m+n+2)^2}-2\sum_{n,m=1}^{\infty}\frac{(-1)^{m+n}}{2^nnm(m+n+1)^3}$$                    These double series has me stumped...
Answer: \begin{align}
& \int_0^1\ln(2+x)\,\ln(1+x)\,\ln\left(1+x^{-1}\right)\ln x\,dx\\
& \quad=\frac{71}{36}\,\ln^42+2\ln^32\cdot\ln3+4\ln2\cdot\ln^33-7\ln^22\cdot\ln^23-\frac23\,\ln^32-\frac23\,\ln^33-\ln^22\cdot\ln3\\
& \quad \quad +6\ln^22+3\ln^23-12\ln2-\frac{\pi^4}{216}+\pi^2\!\left(\frac{49}{36}\,\ln^22-2\ln2\cdot\ln3-\frac{\ln2}3+\frac{\ln3}3-\frac16\right)\\
& \quad \quad+\left(6-2\ln2-2\ln^22\right)\operatorname{Li}_2\!\left(\tfrac13\right)+(2-12\ln2)\left[\operatorname{Li}_3\!\left(\tfrac13\right)+\operatorname{Li}_3\!\left(\tfrac23\right)\right]-\frac23\,\operatorname{Li}_4\!\left(\tfrac12\right)+3\operatorname{Li}_4\!\left(\tfrac14\right)\\
& \quad \quad +\left(\frac54+\frac{221}{12}\ln2\right)\zeta(3).
\end{align}
Answer: The main ingredient here is the integral representation
$$\operatorname{Li}_n(z)=\frac{(-1)^{n-1}}{(n-2)!}\int_0^1
\frac{\ln\left(1-zx\right)\ln^{n-2}x\,dx}{x},\tag{$\spadesuit$}$$
valid for $|z|<1,n\in\mathbb{N}_{\ge 2}$.
The derivation goes as follows:

Rewrite the initial integral as
\begin{align*}
\mathcal{I}&=\int_0^1\ln(x+2)\underbrace{\left[\ln x\ln^2(1+x)-\ln^2x\ln(1+x)\right]}_{=\frac13\left(\ln x-\ln(x+1)\right)^3-\frac13\ln^3 x+\frac13\ln^3 (x+1)} dx=\\
&=\frac13\biggl[\underbrace{\int_0^1\ln(x+2)\ln^3(x+1)dx}_{\mathcal{I}_1}-\underbrace{\int_0^1\ln(x+2)\ln^3x\,dx}_{\mathcal{I}_2}-\underbrace{\int_0^1\ln(x+2)\ln^3\frac{x+1}{x}dx}_{\mathcal{I}_3}\biggr].
\end{align*}
The integrals $\mathcal{I}_{1,2}$ have antiderivatives that can be expressed in terms of polylogarithms  (say, with Mathematica), therefore we concentrate on $\mathcal{I}_3$. After the change of variables $t=\frac{2x}{x+1}$, we obtain
\begin{align*}\mathcal{I_3}&=-2\int_0^1\frac{\ln\frac{4-t}{2-t}\ln^3\frac t2\,dt}{(2-t)^2}=\\&=-2\int_0^1\frac{\ln\frac{4-t}{2-t}\ln^3 t\,dt}{(2-t)^2}+
6\ln 2 \int_0^1\frac{\ln\frac{4-t}{2-t}\ln^2 t\,dt}{(2-t)^2} \tag{$\clubsuit$}\\&\quad -6\ln^22\int_0^1\frac{\ln\frac{4-t}{2-t}\ln t\,dt}{(2-t)^2}+
2\ln^32\int_0^1\frac{\ln\frac{4-t}{2-t}dt}{(2-t)^2}.
\end{align*}
Now let me explain how these integrals can be computed. Consider, for instance, the first term in ($\clubsuit$):
\begin{align*}
2\int_0^1\frac{\ln\frac{4-t}{2-t}\ln^3 t\,dt}{(2-t)^2}&=\int_0^1\ln\frac{4-t}{2-t}\ln^3 t\,d\left(\frac{t}{2-t}\right)=-
\int_0^1\frac{t}{2-t}d\left(\ln\frac{4-t}{2-t}\ln^3 t\right)=\\
&=-
\int_0^1\frac{t}{2-t}\left[\color{red}{-\frac{\ln^3 t}{4-t}+\frac{\ln^3 t}{2-t}}+\frac{3}{t}\ln\frac{4-t}{2-t}\ln^2 t\right]dt
\end{align*}
The terms shown in red lead to integrals computable with the help of ($\spadesuit$) (e.g. differentiate it with respect to $z$ and see what happens). The remaining nontrivial piece is thus
$$\int_0^1\frac{\ln\frac{4-t}{2-t}\ln^2 t}{2-t}dt=
\int_0^1\frac{\ln(4-t)\ln^2 t}{2-t}dt-\int_0^1\frac{\ln(2-t)\ln^2 t}{2-t}dt$$
The second part again has again a polylogarithmic antiderivative computable with Mathematica, so it remains to compute
$$\mathcal{I}_4=\int_0^1\frac{\ln(4-t)\ln^2 t}{2-t}dt.$$
Note that the same procedure applied to the other three terms in ($\clubsuit$) leads to easily computable integrals (as instead of $\ln^2t$ in the analog of $\mathcal{I}_4$ we have $\ln t$ or $1$).
Thus it remains to compute $\mathcal{I}_4$. And this is the only place where a certain miracle takes place, which indicates that there should be an easier way to do the initial integral. Making the change of variables $s=2-t$, we get
\begin{align*}
\mathcal{I}_4&=\int_1^2\frac{\ln(2+s)\ln^2(2-s)\,ds}{s}=\\
&=\frac16\int_1^2\frac{\left[\ln(2+s)+\ln(2-s)\right]^3+\left[\ln(2+s)-\ln(2-s)\right]^3-2\ln^3(2+s)}{s}ds=\\
&=\frac16\int_1^2\frac{\ln^3(4-s^2)}{s}ds+\frac16\int_1^2\frac{\ln^3\frac{2+s}{2-s}}{s}ds-\frac13\int_1^2\frac{\ln^3(s+2)}{s}ds.
\end{align*}
Each of these three pieces again has polylogarithmic antiderivatives that can be computed by Mathematica. This becomes obvious after change of variables $u=s^2$ in the first integral (the miracle is here: due to special parameter values we don't have an additional linear term under logarithm which would spoil the things)  and $u=\frac{2+s}{2-s}$ in the second.

So the conclusion is that indeed, the integral $\mathcal{I}$ can be expressed in terms of polylogarithms (up to $\operatorname{Li}_4$), but I was too lazy to type the answer. Fortunately, for that we have Cleo.

Added: As suggested by Vladimir Reshetnikov, the integration bounds $(0,1)$ are not really important: the above approach yields an explicit antiderivative which I posted at https://gist.github.com/anonymous/4c35e5617cf846e8f517
Comment: Simplified from 1924 down to 720 nodes: https://goo.gl/rNPLj9
Comment: So, it looks like the integrand in the question has a closed-form antiderivative in terms of elementary functions and polylogarithms, right?
Comment: @VladimirReshetnikov Maybe, but not necessarily - see for instance my red terms where the integration bounds look essential.
Comment: _Mathematica_ can find antiderivatives for the red terms.
Comment: @VladimirReshetnikov You were right, now I have the antiderivative explicitly, but it takes the whole screen and does not seem to simplify.
Comment: @VladimirReshetnikov Here is the link: https://gist.github.com/anonymous/4c35e5617cf846e8f517 Please tell me if this does not work, I never used this service before.
Comment: Great job, @VladimirReshetnikov ! I wish I could save your efforts by suggesting a more clever way to compute the antiderivative, but so far I have not found it.


Get time sensitive specific data from SQL db in .Net

Question: I need help to change one of my API's methods.
I have DB with few events like this:
EventName: Event 1 EventDate: 2013-08-15 00:00:00:00.000 isActive: true

EventName: Event 2 EventDate: 2013-08-16 00:00:00:00.000 isActive: true

EventName: Event 3 EventDate: 2013-08-17 00:00:00:00.000 isActive: true

Now, I have this method:
public IQueryable<Event> allActiveAndToday(){
     return this.Where(e => e.IsActive)
}

This method return all the events above and I want to change it to return only events in the same date between 8:00AM & 8:00AM next day.
For example:

if the method get called at 7:00AM at 08/16/2013 the result will be Event 1.
if the method get called at 9:00AM at 08/16/2013 the result will be Event 2.
if the method get called at 7:00AM at 08/17/2013 the result will be Event 2.
if the method get called at 9:00AM at 08/17/2013 the result will be Event 3.

let say that it's like the day start & end in 8:00AM every day..
I can't find a way to do it, because i'm not familiar with the options and context I have in .net.
Answer: I think this should do it:
public IQueryable<Event> allActiveAndToday(){
    DateTime currentDt = DateTime.Now;
    DateTime start = new DateTime(currentDt.Year, currentDt.Month, currentDt.Day, 8, 0, 0);
    DateTime end = start.AddDays(1);

    // This will check if the the current date/time falls between 8AM and 8AM (the following day)
    // If not then set the currentDt to yesterday's date.
    if (!(currentDt >= start && currentDt <= end))
    {
        currentDt = currentDt.AddDays(-1);
    }

    // Then do your query here...
    var events = this.Where(x => x.IsActive && x.EventDate.Date == currentDt.Date).ToList();

    return events;
}

Comment: So great !! checking your answer and coming back to mark it ! Thanks!
Comment: This is mostly a good answer, but you may want to consider excluding the end date:  `currentDt < end` since that is usually implied with these sort of ranges.  Also, if this is a web application, you haven't addressed the problem of "whose now is it?".  Using `DateTime.Now` will give you the *server's* time.  That might not be the user's time at all.
Comment: i think that this is my problem because im nor getting the result i wanted i will check it again and let you now.


External microphone not working

Question: gnome-volume-control does not recognise external hardware.  My headphones work nonetheless, but an external microphone does not.  External microphones used to work, but at times were temperamental - I would have to login or logout with or without microphone plugged in.
I am running Ubuntu 10.04 LTS (Lucid Lynx) on an mSi U100 wind notebook with one Intel soundcard and trying to use a jack microphone which has worked previously.  USB microphones have also been problematic.
I have done the basics:

Installed upgrades.
Checked nothing is muted.
Looked for the device on gnome-volume-control.
Tried using a different microphone that works on a friends computer.
Tested my microphone works when using a different computer.
Checked my soundcard can be seen (cat /proc/asound/cards).

I have done more complicated things:

I have tried playing around with settings in alsamixer.  Nothing is
muted.  I can adjust "mic" and "internal mic" regardless of whether
an external microphone is plugged in.  I have the choice of input
source from "mic", "front mic", "line" and "CD".  I've played around
changing this and it hasn't helped.  I only have one CAPTURE option.

In gnome-sound-recorder I have the choice of line, microphone 1 and microphone 2. I have played around changing this option.  None of
these pick up sound from the external microphone. Microphone 2 is the
microphone on my laptop which is bad quality.
In gnome-sound-recorder I have the choice of different profiles, and changing this has not helped either.
I have looked at gstreamer-properties but none of that seemed helpful.

I don't know if there a way to check if these external devices are being picked up.  I would like to make an external microphone work.  Please help!
Answer: My computer, compaq CQ45-118A, intel sound card.
Since ubuntu 10.04 to 11.04, I have added to /etc/modprobe.d/alsa-base.conf the following lines and worked for me:
options snd-pcsp index=-2

alias snd-card-0 snd-hda-intel

alias sound-slot-0 snd-hda-intel

options snd-hda-intel model=dell-m4-1

options snd-hda-intel enable_msi=1

options snd-hda-intel position_fix=1 enable=yes

Comment: You just made me very happy!!
Answer: I found a solution, and uploaded a screencast to YouTube.

Install alsa-tools-gui package.
Run hdajackretask.
At the top, the Realtek analog codec will be already selected. In my case, it was Realtek ALC270.
Pay attention to the left panel (Pin configuration). In my case, it showed only 3 connected pins: Internal Mic, Internal speaker, Headphone. Note that it is missing a pin for the external microphone.
Check: ☑ Show unconnected pins.
Several new pins will show up at the left panel. For each one that is Not connected:

Check ☑ Override.
Look for a Microphone option at the drop-down box.
If there no Microphone in that box, then uncheck ☐ Override and try the next pin.
If there is a Microphone option, select it, and go to step 7.

You should now have one pin that was previously unconnected but now is overridden as a microphone. Click on Apply now and enter your password.
If you receive an error message about Device or resource busy, close any applications that are using the sound card (e.g. close alsamixer).
If you receive a success message: Ok, now go ahead and test to see if it actually worked!, do what it says and test it!
If it worked, click on Install boot override and enter your password again. If it did not work, uncheck ☐ Override and go back to step 6.

In my case, overriding pin 0x18 to Microphone fixed the issue for me.
Comment: I tried it but it didn't worked for me :(
Comment: Didn't worked on Linux Mint 19.1, in Acer Aspire E 15.
Comment: @MattMello I have the same device+OS configuration. were you able to get it working?
Comment: @vijayvithal Yes! Check out my answer below. It worked for me in the first time, following the mentioned video.
Answer: Had the same issue with Kubuntu 20.4. Tried unmuting it on alsamixer but tht didn't quite solve the problem.
As it turned out, Pulse Audio wasn't identifying the front panel because of the audio controller profile, so i googled a little bit and found this post and was able to solve the problem. Here goes a TL;DR:

First open up Pulse Audio Volume Control by typing in a terminal: pavucontrol (if you don't have it installed, just do a: sudo apt install pavucontrol)
On the Configuration tab, change the audio controller device to Analog Stereo Duplex.
Go to the desired input/output device tab, plug your device into the front panel and identify wether your device is recognized or not. If it isn't, then the next steps might not solve your problem.
As changes made in Pulse Audio's GUI aren't permanent, we have to make them this way by editing a pulse audio config file.
In a terminal, type sudo vim ~/.config/pulse/default.pa. If you are not familiar with vi or vim, replace it with a text editor you are familiar with.
Append the following strings to the configuration file:

### Set Built-in Audio (HDA Intel) profile to Analog Stereo Duplex
set-card-profile 1 output:analog-stereo+input:analog-stereo

Save the file, reboot and enjoy you system!
Answer: The only solution to make microphone work is to install linux-backports-modules-alsa-generic.
Just go to:
Menu > System > Administration > Synaptic Package Manager
And search and mark for installation:
linux-backports-modules-alsa-generic

Tip: if you have multiple versions click on the first and read the description which should inform what name to install.
If after the reboot and mic mute is off, still does not work, just go to terminal and type:
sudo nano /etc/modprobe.d/alsa-base.conf

and add or change the following:
options snd-hda-intel model=auto enable=yes

Then Ctrl+X, type Y to write and exit, reboot and mic will work.
Answer: Since the other answers didn't work for my Acer Aspire E5-574-592S,
I've tried another way, following this video.
It has been tested on:

Linux Mint 19.1 (Cinnamon)
Manjaro 5.8.6-1 (Gnome)

Steps:

Locate the /etc/modprobe.d/alsa-base.conf file

if it doesn't exist, create it by running in a terminal: sudo touch /etc/modprobe.d/alsa-base.conf;

Edit it:

By terminal: sudo nano /etc/modprobe.d/alsa-base.conf
By graphical interface: sudo gedit /etc/modprobe.d/alsa-base.conf. (Note: if you don't have gedit try xed or simliar in your distro.)

Add the following lines:

# Fix External microphone connected via combo jack on Ubuntu 16.04+ (video)
options snd-hda-intel model=dell-headset-multi
options snd-hda-intel position fix=1

I've tested it on Linux Mint 19.1 and Manjaro 5.6.8-1.
On Manjaro, that is the window that pops up when I plug an external mic:
Comment: I have ES1 523 49c0, This did not work for me :(
Microphone used to work when I had centos 7 on this laptop. So it looks like a mint/ubuntu issue
Comment: Not sure why this was downvoted, it actually worked for me, on Fedora 35. Thank you @MattMello A question, do you know why the model has to be `model=dell-headset-multi`? I'm using HyperX Cloud Stinger headset, so no idea why `dell-headset` fixes this issue for me.
Comment: @vijayvithal I've added my alsabase.conf to help you get a solution. Hope it helps you!
Comment: @DarkoTasevski I suppose the reason is the module/driver name present in linux kernel... By the way, some weeks ago when using Linux Mint 20, it stopped working again ¬¬ . Then, the Emanuel Tav's answer worked incredibly well ¯\\_(^.^)_/¯.

External microphone not working


How do I declare a type where I pick a property from an Interface and make the picked property's properties optional?

Question: Like in this example, I don't want to pick a property and make the entire thing optional.   But instead, I want to make the picked property's properties optional.
Currently I am solving this problem by explicit writing {items: Partial<Item>[]}.
Is there a smarter way?

interface Item{
    id: number
    name: string
}

interface User{
    id: number
    name: string

    items: Item[]
}

type UserWithOptionalItemsItself = Pick<User, "id" | "name"> & Partial<Pick<User, "items">>
const x:UserWithOptionalItemsItself = {
    id: 1,
    name: "user name",
    // items is optional.. this is not what I want
}

type UserWithOptionalItems = Pick<User, "id" | "name"> & {items: Partial<Item>[]}
const y:UserWithOptionalItems = {
    id: 1,
    name: "user name",
    // you have to have items, but the properties are optional
    items: [{
        id: 123
    }]
}

TypeScript playground example
Answer: Here, id and name are mandatory, where items is optional. If not provided, they will return undefined.
You can also provide default value to items:
interface User{
    id: number
    name: string

    items?: Item[] | undefined
}


How to print all values in a dynamically resizing struct? C++

Question: I have a dynamically resizing struct[]. I ask the user for how many records he wants then make that many struct.Then I store the name and age info in the struct. The problem is when printing out that data i am only printing the last name and age the user input. I would like to print all the values.
struct Records
{
    char name [32] ;
    int age;
};
void program2()
{
    Records rec;
    int size;
    cout << "How many record would you like?";
    cin >> size;
    cout << "\n" << size;
    Records* a = new Records[size];
    for (int i = 0; i < size; i++)
    {
        cout << "Whats the name for the Record: ";
        cin >> rec.name;
        cout << rec.name;
        cout << "What is the age for this record: ";
        cin >> rec.age;

    }
    for (int i = 0; i < size; i++)
    {
        cout << "\n" << rec.name << rec.age;
    }
}

Comment: There is no such thing as a "resizing struct".
Comment: You never store `rec` in your dynamically allocated array.
Comment: You're not utilising your `struct[]` at all. On the other hand, why not use std::vectors?
Comment: "I have a dynamically resizing struct[]" nope. Did you mean "dynamically sized" ? because there is nothing dynamically resizing in your code. c-arrays cannot change their size dynamically
Answer: In your code, the variable rec has nothing to do with the array. To access the element at position i of your array, you'll need to use a[i].
For example:
cin >> a[i].name;

or
cout << "\n" << a[i].name << " " << a[i].age;

Comment: or `Records& rec = a[i];` as first line in the loop, not worth an answer, but thats probably the fix that requires least changes
Answer: No surprise - you are actually printing repeatedly the last record that you created (rec). Your last loop is not actually traversing the array.
Also, the first loop only creates a struct, but does not actually add it to the array.
What you are trying to do is actually easier and cleaner if you use vectors instead of arrays, adding each record to the vector using push_back(). This is the closest thing to the "dynamically resized array" that you are referring to (such a thing does not actually exist in C++, that's what vectors are for, amongst other things).
Have a look into doing it this way, and if you get stuck feel free to ask again, happy to help.


I need help with my Blizzard Login

Question: So apparently, I don't have a Blizzard login but I play Overwatch. I'm not sure if its because I play on a Playstation because I know you must have to login to play on a PC.
How can I get access to my Blizzard login?
Comment: Accounts aren't shared across platforms for Overwatch.
Comment: This seems to be missing a question.  Are you asking how you can log into the same account on a PC as you use on a PlayStation?  What is the actual problem that you are trying to solve?
Answer: You don't need to have a Blizzard (battle.net) account to play Blizzard games on a console. You can link your PSN/Xbox account to your existing battle.net account if you want to.
Blizzard Site

Log in to your Blizzard Account.
Manage your Connected Accounts and click the Connect button next to
the account you want to link.

In-Game

While in the game, open the main menu and choose Link Account. Note:
This will temporarily disconnect you from Overwatch while you link
your accounts.
Choose Log In and fill in all necessary information. Choose Create
Free Account if you don't have a Blizzard account.
After your accounts are connected, choose Return to Connected
Accounts.
(Optional) Select the Redeem Digital Goodies button to claim your in-game
goodies on your Blizzard account. Note: In-game goodies can only be
claimed once, and cannot be undone.

More info

I need help with my Blizzard Login


how to enable to location?

Question: Hi in the below code i am connecting devices via bluetooth and location.
For first time is it asking for permission to turn on the location but it is not enabling the location.
can any one please help me how to enable the location automaticatically like buetooth in the below code
for example:In bluetooth, it is asking for the permission and turning it on.
but for location for first time it is asking for permission but it is not enabling the location.
<code>protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_device);
        ButterKnife.bind(this);
        mProgressDialog = new ProgressDialog(this);
        mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        initToolBar();
        mBleDevices = new ArrayList<>();
        mAdapter = new DeviceListAdapter(this);
        mDeviceListView.setAdapter(mAdapter);
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mDeviceListView.setLayoutManager(manager);
        mDeviceListView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                showProgressDialog();
                List<BluetoothDevice> bluetoothDevices = mAdapter.getBluetoothDevices();
                if (bluetoothDevices != null) {
                    if (bluetoothDevices.size() > position) {
                        BluetoothDevice bluetoothDevice = bluetoothDevices.get(position);
                        if (bluetoothDevice != null) {
                            String address = bluetoothDevice.getAddress();
                            mBleService.connect(address);
                        }
                    }
                }
            }
        }));
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BleService.ACTION_DEVICE_FOUND);
        intentFilter.addAction(BleService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BleService.ACTION_GAT_CONNECTING);
        intentFilter.addAction(BleService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BleService.ACTION_GAT_SERVICE_DISCOVERED);
        registerReceiver(mGattUpdateReceiver, intentFilter);

        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.BLUETOOTH,Manifest.permission.ACCESS_FINE_LOCATION
                        , Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
            }
        } else {
            if (mServiceConnection != null) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 101);
            }

            Intent intent = new Intent(this, BleService.class);
            bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        }
    }
    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
        }
        mProgressDialog.setMessage(getString(R.string.loading));
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.show();
    }
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mBleService = ((BleService.LocalBinder) iBinder).getLeService();
            if (mBleService != null) {
                mBleService.scanLeDevice(true);
                mScanStatus.setVisibility(View.VISIBLE);
                mScanStatus.setText(R.string.scanning_device);
            }
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };
    @Override
    protected void onResume() {
        super.onResume();
    }
    @Override
    protected void onStart() {
        super.onStart();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 101) {
            if (mBleService != null) {
                mBleService.scanLeDevice(true);
            }
        }
    }
    private BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case BleService.ACTION_DEVICE_FOUND:
                    BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BleService.EXTRA_DEVICE);
                    if (mBleDevices != null) {
                        if (!mBleDevices.contains(device)) {
                            mBleDevices.add(device);
                            mAdapter.udpateBluetoothDevices(mBleDevices);
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                    break;
                case BleService.ACTION_GATT_CONNECTED:
                    Log.d(TAG, "!Action gat connected...");
                    mBleService.scanLeDevice(false);
                    mScanStatus.setVisibility(View.VISIBLE);
                    mScanStatus.setText(getString(R.string.connected));
                    break;
                case BleService.ACTION_GAT_CONNECTING:
                    mScanStatus.setVisibility(View.VISIBLE);
                    mScanStatus.setText(getString(R.string.connecting));
                    Log.d(TAG, "!Action Gat Connecting..");
                    break;
                case BleService.ACTION_GATT_DISCONNECTED:
                    mScanStatus.setVisibility(View.VISIBLE);
                    mScanStatus.setText(getString(R.string.disconnected));
                    mScanningProgress.setVisibility(View.GONE);
                    mRefresh.setVisibility(View.VISIBLE);
                    if (mProgressDialog != null) {
                        mProgressDialog.dismiss();
                    }
                    Log.d(TAG, "!Action Gat Disconnected..");
                    break;
                case BleService.ACTION_GAT_SERVICE_DISCOVERED:
                    boolean isOperator = mPref.getBoolean(Constants.IS_OPERATOR, false);
                    if (mProgressDialog != null) {
                        mProgressDialog.dismiss();
                    }
                    if (isOperator) {
                        Intent homeIntent = new Intent(DeviceScanActivity.this, HomeScreenActivity.class);
                        startActivity(homeIntent);
                        finish();
                    } else {
                        Intent lightControllIntent = new Intent(DeviceScanActivity.this, LightConfigurationActivity.class);
                        startActivity(lightControllIntent);
                        finish();
                    }
                    mScanStatus.setText(getString(R.string.discoveringService));
                    Log.d(TAG, "!Action Gat Discovering..");
                    break;
            }
        }
    };
    private void initToolBar() {
        mRefresh.setVisibility(View.VISIBLE);
    }
    @OnClick(R.id.refresh)
    public void onClick() {
        mScanStatus.setVisibility(View.VISIBLE);
        mRefresh.setVisibility(View.GONE);
        mScanningProgress.setVisibility(View.VISIBLE);
        mBleDevices.clear();
        mAdapter.udpateBluetoothDevices(new ArrayList<BluetoothDevice>());
        mAdapter.notifyDataSetChanged();
    }
    @Override
    protected void onDestroy() {
        if (mServiceConnection != null) {
            unbindService(mServiceConnection);
        }
        if (mGattUpdateReceiver != null) {
            unregisterReceiver(mGattUpdateReceiver);
        }
        super.onDestroy();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_COARSE_LOCATION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (mServiceConnection != null) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, 101);
                }
                Intent intent = new Intent(this, BleService.class);
                bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
            } else {
                finish();
            }
        }
    }
</code>
Comment: you can do this with google play services ... question was already asked here multiple times
Comment: can you please tell me
Answer: You can't enable location programmatically if device is not rooted.
Here is code how to ask user to enable location in Fragment:
<code> override fun checkLocationSettings() {
    if (activity != null) {
        locationSettingsTask.addOnFailureListener(activity!!) { exception ->
            if (exception is ResolvableApiException) {
                try {
                    exception.startResolutionForResult(activity,
                            REQUEST_CODE_CHECK_LOCATION_SETTINGS)
                } catch (ignore: Exception) {
                    // Empty
                }
            }
        }
    }
}

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == REQUEST_CODE_CHECK_LOCATION_SETTINGS) {
        if (resultCode == RESULT_OK) {
            presenter.resolveCurrentLocation()
        }
    }
}
</code>

how to enable to location?


necessary and sufficient condition of a trace equation $\operatorname{diag}(AXA^\dagger)=0$

Question: Consider the following matrix equation:
\begin{equation}
\operatorname{diag}(AXA^\dagger)=0
\end{equation}
where $\operatorname{diag}(.)$ represent the diagonal elements. with $X$ being the variable matrix and $A$ being an arbitrary matrix with constant elements and $A^\dagger=(A^*)^T$. Assuming they both have complex entries,
what is the sufficient and necessary condition that the answer to the above equation be
\begin{equation}
X=0
\end{equation}
Update: if there is not a necessary and sufficient condition, is there a necessary condition?
meaning is there a condition on entries of $A$ such that $\operatorname{diag}(AXA^\dagger)=0$ implies $X=0$ ?
Comment: @Jason I'm quite sure the answer is that no specific value of $A$ can imply that $X = 0$. I'm currently busy at the moment, but the basic idea is to note that the desired quantity is equal to $Tr(A^\dagger A X)$, and that $A^\dagger A = Q D Q^\dagger$ for some diagonal $D$ and orthogonal $Q$. Then you just simply have to set $X = QE Q^\dagger$ for an $E$ where $Tr(DE) = 0$, which is always possible without forcing $E = 0$. I'll be back to write a more complete answer if no one does in the meantime.
Comment: Not an answer, but considering that the trace is cyclic, if $A$ is Unitary, then the expression reduces to $Tr(AXA^{\dagger}) =Tr(A^{\dagger}AX) =  Tr(X) =0$.
Comment: on one hand, this is not a general case, on the other hand, you cant conclude that X=0 if Tr(X)=0 @RyanK
Comment: @paulinho thank you for your comment I have updated the question a little bit regarding your comment, I have also noticed a mistake that I made so the question is a bit changed now
Answer: Your notation is very confusing. I suppose that $A^\dagger$ means $A^\ast=\overline{A}^{\,T}$ (the conjugate transpose of $A$) rather than $(A^\ast)^T=\overline{A}$ (the complex conjugate of $A$). In this case, the statement
$$
\forall X,\ \operatorname{diag}(AXA^\dagger)=0\Rightarrow X=0\tag{1}
$$
holds if and only if $A$ is a nonzero column vector.
Let $A$ be $m\times n$. When $n>1$, $f:X\mapsto \operatorname{diag}(AXA^\dagger)$ is a linear map from $M_n(\mathbb C)$ to $\mathbb C^n$. Since $\dim M_n(\mathbb C)=n^2>n=\dim\mathbb C^n$, $\ker f$ is always nonzero regardless of the value of $A$.
When $n=1$, $X$ is a scalar and $\operatorname{diag}(AXA^\dagger)=X(|a_1|^2,|a_2|^2,\ldots,|a_m|^2)^\top$. Therefore $(1)$ holds if and only if $A\ne0$.
Comment: Sorry, I don't fully understand it in what part of your statement you conclude A should be a  nonzero "column vector"? @user1551
Comment: @Jason In the second paragraph, I've shown that if $n>1$ (i.e. if $A$ is **not** a column vector), statement $(1)$ cannot possibly hold because there always exists a nonzero $X$ such that $AXA^\ast$ has a zero diagonal. In the third paragraph, I've shown that if $n=1$ (i.e. if $A$ **is** a column vector), then $(1)$ holds iff $A\ne0$ (i.e. iff $A$ is a nonzero column vector).
Comment: Got it, just one question, based on your argument there is no way that A be a row vector instead of a column vector, is that correct? @user1551
Comment: @Jason Not exactly. It is true that $A$ cannot be a row vector with two or more elements, but $A$ can be $1\times1$ (i.e. a scalar). In this case $A$ is both a column vector and a row vector and statement $(1)$ holds if and only if $A$ is a nonzero scalar.
Comment: I see the core of your arguments depend on the fact that the matrices are finite dimension, but what if instead of finite-dimensional matrices the question be asked for infinite-dimensional matrices i.e., operators on some vector space, can we use the same argument?
Comment: @Jason In this case you may need to clarify what $diag(AXA\dagger)$ means.


MySQL Nested query formatting

Question: I have a database with 3 tables, A VOLUNTEER table, a TRAINING_EVENTS table, and a TRAINING_INSTRUCTOR table.
The VOLUNTEER table contains in formation about a person marked by a auto incremented Vol_ID.
The TRAINING_EVENTS table contains dates and times for an event marked by a auto incremented Event_ID. It also assigns each event an Hours_Credited field, which indicated how many credit hours a volunteer receives for being an instructor for that particular event.
The TRAINING_INSTRUCTOR table contains the Vol_ID and Event_id. (Indicating which volunteer is the instructor for an event).
I would like to have a query that finds which particular event a volunteer was an instructor at and then add up the credited hours for those events
The following code is what I attempted to use, but results in an error.
SELECT SUM(Hours_Credited)
FROM TRAINING_EVENTS AS TE, TRAINING_INSTRUCTOR AS TI
WHERE TE.EVENT_ID = TI.EVENT_ID AND TI.EVENT_ID IN
    (SELECT TI.EVENT_ID
    FROM VOLUNTEER AS V, TRAINING_INSTRUCTOR AS TI
    WHERE V.VOL_ID = TI.VOL_ID AND V.VOL_ID = 3);

Comment: You used `TI` as alias twice: One in the outer, one in the inner query
Answer: You are re-using the alias TI inside the IN query.
Try this with the TI2 alias...
SELECT SUM(Hours_Credited)
FROM TRAINING_EVENTS AS TE, TRAINING_INSTRUCTOR AS TI
WHERE TE.EVENT_ID = TI.EVENT_ID AND TI.EVENT_ID IN
(SELECT TI2.EVENT_ID
FROM VOLUNTEER AS V, TRAINING_INSTRUCTOR AS TI2
WHERE V.VOL_ID = TI2.VOL_ID AND V.VOL_ID = 3);

Answer: Edited to remove redundant join to TI and to pull for all VOL_IDs.
SELECT TI.VOL_ID, SUM(TE.Hours_Credited) as HOURS_CREDITED
FROM TRAINING_EVENTS AS TE,
(SELECT TI.EVENT_ID, TI.VOL_ID
    FROM VOLUNTEER AS V, TRAINING_INSTRUCTOR AS TI
    WHERE V.VOL_ID = TI.VOL_ID) AS TI
WHERE TE.EVENT_ID = TI.EVENT_ID
GROUP BY TI.VOL_ID
ORDER BY TI.VOL_ID;

Comment: You could also use the proper `join` syntax for a good answer
Comment: Thank you. This was very helpful.
Answer: You can do it using JOIN:
SELECT v.NAME, SUM(Hours_Credited) as 'Hours_Credited'
FROM TRAINING_INSTRUCTOR TI
join TRAINING_EVENTS TE
on TI.Event_ID = TE.Event_ID
join VOLUNTEER V
on TI.VOL_ID = V.VOL_ID
group by V.VOL_ID

You can try it here http://sqlfiddle.com/#!9/b9694a/4
Answer: If you have the input VOL_ID and you want to output the sum of HOURS_CREDITED by a volunteer, this query will resolve:
SELECT SUM(TE.Hours_Credited)
 FROM
TRAINING_EVENTS AS TE, TRAINING_INSTRUCTOR AS TI
 WHERE
TE.EVENT_ID = TI.EVENT_ID AND TI.VOL_ID = 3;

MySQL Nested query formatting