text:
Q: TikZ: Drawing an arc between two coordinates? I am up with the following:

Using the code given at the bottom.
Suffice to say, I don't really like the result: I wanted to draw this picture without explicitly calculating the circle and the lines going into and out of it. However, I just don't know how to draw that part-circle to the right (with $\theta$ in it), such that I...

*

*get an arc which is shaped like a circle,

*have it intersect the shown without actually crossing them, and

*have $\theta$ placed between the middle of the actually drawn arc and its center.

How could I achieve this?
\begin{tikzpicture}

\coordinate (a) at (-3,0.5);
\coordinate (b) at (-1,0.5);

\draw[solid,-latex] (a) -- (b) coordinate[at start] (p);

\draw[thin,solid,latex-latex] (p) -- node[left] {$p$} ++(270:0.5);

\draw[thin,dashed] (-3,0) -- (3,0) coordinate[very near end] (angleStart);

\node (interaction) [circle through=(b)
                    , solid
                    , draw
                    , fill=lightgray
                    ]  at (0,0) {interaction};

\draw[solid,-latex] (interaction.north east)  -- ++(45:2) coordinate[near end] (angleEnd);

\draw (angleStart) to[out=50,in=-20] node[below left=2pt] {$\theta$} (angleEnd);
\end{tikzpicture}

A: Just for fun.

\documentclass[pstricks,border=12pt]{standalone}
\usepackage{pst-eucl,pstricks-add}

\begin{document}
\begin{pspicture}[showgrid=false](-3,-1)(3,3)
    \psset{PointName=none,PointSymbol=none}
    \pstGeonode
        (-2.5,+0.0){A}
        (-2.5,+0.5){B}
        (-0.5,+0.5){C}
        (+0.0,+0.0){D}
        (+2.0,+2.0){E}
        (+1.5,+0.0){F}
    \pstLineAB[nodesepB=-1,linestyle=dashed]{A}{F}
    \pstLineAB[arrows=->]{B}{C}
    \pstLineAB[linestyle=dashed,arrows=->]{D}{E}
    \pstMarkAngle[LabelSep=1.15,MarkAngleRadius=1.5,arrows=->]{F}{D}{E}{$\theta$}
    \pstCircleOA[fillstyle=solid,fillcolor=gray]{D}{C}
    \rput(D){\tiny Interaction}
    \ncline[offset=2pt]{<->}{A}{B}\naput{$p$}
\end{pspicture}
\end{document}

A: I suggest that you base everything on the center of the circle in which case the calculations can easily be automated with the additional TikZ library: \usetikzlibrary{calc}

You can set the angle and radius you want via:
\newcommand*{\ArcAngle}{60}%
\newcommand*{\ArcRadius}{2.0}%

Everything else is computed based on these. You can adjust these to get the specific result you desire.
Two other tweaks that I have defined below are to adjust how far the dashed lines extend past the arc, and how far past the arc the label is placed (as percentages):
\newcommand*{\LineExtend}{1.25}%
\newcommand*{\LableExtend}{1.10}%

Code:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}

\newcommand*{\ArcAngle}{60}%
\newcommand*{\ArcRadius}{2.0}%
\newcommand*{\LineExtend}{1.25}%
\newcommand*{\LableExtend}{1.10}%

\begin{document}
\begin{tikzpicture}
\pgfmathsetmacro{\XValueArc}{\ArcRadius*cos(\ArcAngle)}%
\pgfmathsetmacro{\YValueArc}{\ArcRadius*sin(\ArcAngle)}%

\pgfmathsetmacro{\XValueLabel}{\ArcRadius*cos(\ArcAngle/2)}%
\pgfmathsetmacro{\YValueLabel}{\ArcRadius*sin(\ArcAngle/2)}%

\coordinate (Origin) at (0,0);

\draw [thin, dashed] (Origin) -- ($(\LineExtend*\ArcRadius,0)$);% Horizontal

% Extend this past the (\XValue,\YValue)
\draw [thin, dashed] (Origin) -- ($\LineExtend*(\XValueArc,\YValueArc)$);

\node (interaction) [circle, solid, draw, fill=lightgray]
    at (Origin) {interaction};

\draw [<->] ($(Origin)+(\ArcRadius,0)$)
    arc (0:\ArcAngle:\ArcRadius);

\node at ($\LableExtend*(\XValueLabel,\YValueLabel)$) {$\theta$};
\end{tikzpicture}
\end{document}

A: With pgf 2.1 cvs for the node \theta
\documentclass{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}

\coordinate (Origin) at (0,0);
\node (interaction) [circle, draw,
                     fill = lightgray] at (Origin) {interaction};

\draw [thin, dashed] (interaction.0) -- ++(0:1.5)
                     (interaction.60)   -- ++(60:1.5) ;

\draw [<->] (0:2.1)  arc (0:60:2.1) node [right,pos=0.5] {$\theta$};
\end{tikzpicture}
\end{document}

A: The easiest way to draw an arc from the center is
\draw (\CENTERx,\CENTERy) ++( 45 : 1 ) arc ( 45:0:1 );

Draws an arc on a circle of radius 1 centered at (\CENTERx,\CENTERy), from (45 degrees) to (0 degrees).
See here for an example


text:
Q: Upload to database and storage at the same time in Firebase In my android app I am using client side fan-out to upload data to multiple places in database at the same time to avoid problems for example in case of lost internet connection. Here is example code from Firebase blog:
Map updatedUser = new HashMap();
newPost.put("name", "Shannon");
newPost.put("username": "shannonrules");

Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");

Map fanoutObject = new HashMap();
fanoutObject.put("/users/1", updatedUser);
fanoutObject.put("/usersWhoAreCool/1", updatedUser);
fanoutObject.put("/usersToGiveFreeStuffTo/1", updatedUser);

ref.updateChildren(fanoutObject); // atomic updating goodness

But now I would also like to upload image file to storage alongside that data. Is that posiible to do that at the same time?

A: I don't think you can synchronize calls to Firebase Database and storage. The documentation does not mention it anywhere.
But just so you know: Firebase will save any requests made by updateChildren() in the cache if they cannot be sent due to loss of connection. When the user reconnects, Firebase will then dispatch all the cached requests in the same order that they were saved.

A: One way to do these two tasks concurrently would be to first determine your file path in Storage, and kick off the upload, then also use that file path to update the database.  That's about as good as you'll get.
However, most of the time you want to store the "download URL" of the uploaded file in the database, instead of the path in the storage bucket.  This makes it easier for clients to go directly to the content without having to "look up" the download URL first.  In this case, you really do need to wait for the storage upload to complete first, get the download URL from the UploadTask, then update the database with that string.  You can't know the download URL before the upload completes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the scope of a profile attribute in Siebel? In Siebel (7.8 in case it makes any difference), what's the scope of a profile attribute set via TheApplication().SetProfileAttr("name", "value");?
I always have seen them as if they were session variables. However, on second thought, the user profile should depend only on the current user, not on the session. So if somebody accesses the Siebel application from two different computers using the same login, and executes an action which sets a profile attribute... would that attribute be readable from the other computer aswell?
I haven't found anything in the official documentation, and googling about it shows contradictory information. Most of the resources say that they're equivalent to session variables...:

Siebel Unleashed: Siebel server recognises every unique user through session id [...] Profile Attributes are variables that can hold any value during the session of the user
Another blog: Profile attributes are set at the session level
An answer in this thread: getsharedglobal [...] can be viewed as a global attribute set at application level. [...] profile attributes are user and session specific so if the same user logins at 2 place he will be having his own set of profile attributes at each place

...but there are others which imply that actually, attributes are only unique per user, not per session:

Another answer in the same thread: The main difference about [SetProfileAttr and SetSharedGlobal] is that [...] SetSharedGlobal [...] is unique to the user and the user's associated session.

So, which one is it? Are they session variables? Or are they bound only to the user, and shared across all the live sessions from the same user?

A: I have no code to demonstrate this, but from personal experience, a profile attribute is unique to a user's session. Think of it as a global variable which is alive until the user logs out. If a user logins twice to siebel, those are two different siebel sessions. There is no way for siebel users to transfer profile attributes across logins/sessions. Every task run asynchronously on the server will run as a separate SADMIN login, but they will have their own copies of profile attributes. This means that developers can use/set profile attributes without fear of it affecting any other user logged in.


text:
Q: Memory Mapping in Linux Kernel - use of vamlloc() and kmalloc() Considering a 32bit x86 Linux system with 4 GB of RAM memory, So as described in books as well as on many forums that the Memory mapping would be as follows:

*

*Kernel logical address - upto 896 MB  - Which is one to one mapped and can be allocated using kmalloc().

*Kernel virtual address - 128MB (above 896MB - kernel logical address) - allocated using vmalloc() and allocates Virtually contiguous but physically(scattered within RAM) non-contiguous memory pages.

Few points that I am not able to fully understand and need clarity on.

*

*My understanding is that When kmalloc() is used to allocate memory, It always comes from the 0 to 896MB within the RAM and not beyond that.

*When we use vmalloc() to allocate memory, Does that memory allocated anywhere from 896MB to 4GB range within the RAM ? or it is allocated only from 896MB upto 1GB range within RAM?

*When we say that kernel has only 1GB of virtual address space, Does that meant that the kernel can not access the RAM beyond 1GB ?   If it can then how it is done ? Does the 128MB of kernel virtual address space are used for this purpose ?
Please help.

A: In theory there are 3 different "memory managers". One manages physical RAM (mostly keeping track of pages of free physical RAM), one manages virtual space (what is mapped into each virtual address space where, working with fixed size pieces - the page size), and the third manages "heap" (allowing a larger area of the virtual address space to be split up into arbitrary sized pieces).
Originally; the Linux kernel tried to use its kernel "heap" to manage all 3 of these very different things. By linearly mapping "all RAM" into kernel space they bypass the need for managing the kernel's virtual memory and end up with a simple relationship between virtual addresses in kernel space and physical addresses (e.g. "physical = virtual - base"), and by allocating "heap" you also allocate physical memory.
This was fine originally because at the time computers rarely had more than 128 MiB of RAM (and Linus didn't expect the kernel to exist for very long, as GNU were planning to switch to Hurd "soon"), and kernel space was significantly larger than "all RAM". As the amount of RAM increased it became a problem -"all RAM" became larger than kernel space, so "use heap to manage 3 very different things" couldn't work.
Of course once it became a problem a lot of the kernel's code dependent on "kmalloc to allocate physical memory", making it too hard to fix the problem. Instead, they split physical memory into 2 zones - one zone that would be managed by "kmalloc" and another zone that is managed by "vmalloc"; then changed pieces of the kernel to use "vmalloc" instead of "kmalloc" where it's easy make those changes.

*

*My understanding is that When kmalloc() is used to allocate memory, It always comes from the 0 to 896MB within the RAM and not beyond that.

Yes; this is the first zone of physical memory, which fits into the kernel space mapping that "kmalloc" uses.

*When we use vmalloc() to allocate memory, Does that memory allocated anywhere from 896MB to 4GB range within the RAM ? or it is allocated only from 896MB upto 1GB range within RAM?

It would be allocated from any RAM that is not in the first zone (anywhere in "896MB or higher" range).

*When we say that kernel has only 1GB of virtual address space, Does that meant that the kernel can not access the RAM beyond 1GB ? If it can then how it is done ? Does the 128MB of kernel virtual address space are used for this purpose ?

Of the kernel's 1 GiB of virtual space; some (896MB) will be the linear mapping of the physical address space, some will be memory mapped (PCI) devices, and some will be set aside as an area where dynamic mappings can be made. For "vmalloc" the kernel would allocate physical pages of RAM and then map them into the "dynamic mapping area" (and return a pointer to where it was mapped that has nothing to do with its physical address and breaks the "physical = virtual - base" relationship).
Note 1: Exact sizes/limits are variable - e.g. kernel can be compiled for "2 GiB / 2 GiB split" where kernel space is 2 GiB (instead of "3 GiB / 1 GiB split"); and the size of the "kmalloc zone" probably depends on various factors (how much space PCI devices need, how much RAM there is, etc) and may be something other than 896MB.
Note 2: Since introducing "vmalloc" to work around the original problem; computers switched to 64 bit (where "all memory" can/does fit in kernel space again), and "vmalloc" became unnecessary (and probably just falls through to "kmalloc"). However a lot of other changes have occurred (introduction of NUMA, encrypted RAM, non-volatile RAM, ..; plus more security vulnerabilities than any single person can keep track of) so the original design flaw has reached a temporary "bad idea, but still technically not broken if we keep adding work-arounds for security vulnerabilities" stage (until RAM and non-volatile RAM sizes inevitably increase and "vmalloc" becomes needed again at some point in the future - probably in about 30 years).


text:
Q: Moving and resizing JPanels object inside JFrame Continuing my quest of learning Java by doing a simple game, i stumbled upon a little issue. My gameboard extends JPanel as well as each piece of the board. Now, this presents some problems:

*

*Cant set size of each piece, therefore, each piece JPanel ocupy the whole JFrame, concealing the rest of the pieces and the background (gameboard).

*Cant set the position of the pieces.
I have the default flow manager. Tried setbounds and no luck.
Perhaps i should make the piece to extend other JComponent?
Added image:
That's the piece, now the greyed area is also the piece! Checked that by making a mousePressed listener and assigning some stuff to it. Below the grey area, is the gameboard (or at least, should be!), another JPanel.
alt text http://img42.imageshack.us/img42/2227/screenshotvdy.png
Some code:
package TheProject;

import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class GameWindow extends JFrame {
public GameWindow() {
    setSize(800, 600);
    setLocationRelativeTo(null);
    Map map = new Map(800, 600, 2);
    add(map);

    MilitaryUnit imperialRussia = new MilitaryUnit(30, Color.BLACK, Color.YELLOW, Color.WHITE);
    imperialRussia.setPreferredSize(new Dimension(30, 30));
    add(imperialRussia);

}
 }

This happens when i apply the pack() method:
alt text http://img442.imageshack.us/img442/5813/screenshot2ml.png
Packs around the Unit, not the map which is bigger and fills the JFrame.

A: For a game that has random movement of pieces you would probably use a "null layout".
Read the section from the Swing tutorial on Absolute Positioning for more information.

A: Have you tried setPreferredSize(Dimension d)?
Edit: You need to call pack() on your JFrame, after you've added your components:
JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(800,600));
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(200,200));
frame.add(panel);
frame.pack();
frame.setvisible(true);

Also, you add a Map to your JFrame, which has the same dimensions as your JFrame - fine. But then afterwards, you add another component, to the default flowlayout. This cannot fit into your frame, as the Map already occupies 100% of the space.

A: Have you tried NetBeans' visual editor? You can use it to drag, drop, and resize to your convenience Swing objects in Design View, and can then switch to Code View to see the generated code. You can learn that way.

A: I wrote a few games using JPanel. Basically the way I use JPanel is like I'm using a Canvas, viz I draw directly on it by overriding the paint() method. The reason why I use JPanel is because I can determine the size of my game world, then use the setPreferredSize() to set the size of the panel. I then add the panel to a JScrollPane. So this will take care of the panning, etc.
Say I'm writing a 2D game. This is how I use JPanel. I have a logical map (a 2D array) which holds my game map. Say each location is 32x32 pixel. So you start drawing the ground and what is on that ground in that location. eg in x=1, y=2 which is screen location x=32, y=64, you draw the ground first, then draw what is on the ground. So a rough outline of the render loop would be something like this
for (int y = 0; y < map.length; y++)
   for (int x = 0; x < map[y].length; x++) {
      drawGround(map[y][x])
      for very element on on map[y][x] - render them
}

You set a MouseListener listener to the JPanel, so every mouse click you translate back to the map eg. mouse click x=54, y=72 would correspond to x=1, y=2. The calculation is a bit tricky if you have an isometric view.
The thing you have to be careful here is that everytime when you scroll the panel via the scroll panel, paint() will be called. So it is good to render your game board on a BufferedImage and then in the paint() method just draw the BufferedImage otherwise it'll be too slow.


text:
Q: Perform firestore collection group query in cloud functions with admin sdk? The firestore .collectionGroup() method is getting an error when using it with the firebase-admin sdk in a cloud function.  Is it possible to make a collection group query to firestore in a cloud function?
Here is the firestore query method I'm trying to use: https://googleapis.dev/nodejs/firestore/latest/Firestore.html#collectionGroup
But it doesn't seem to be available in the firestore admin SDK: https://firebase.google.com/docs/reference/admin/node/admin.firestore
admin.firestore().collectionGroup('photos').where('id', '==', photoId);

I get this error when running the function:

TypeError: admin.firestore(...).collectionGroup is not a function

Wondering if I'm missing something, or if this something that will be added in the future.

A: This typically means you're using a version of the Admin SDK that doesn't support Collection Group Queries yet.
Support for Collection Group Queries was introduced in version 7.4.0, based on Cloud Firestore client 1.3.0. Check your package.json to ensure you're using these versions or newer.


text:
Q: Is it possible to retrieve access keys from a AWS user using his login information? I'm trying to build a project to help users manage their S3 account. To do this, however, it requires them to manually provide me with their access key. It's complicated though, and I'd like to make it easier for them.
Is there a way that I can retrieve their access keys by using their login information?
I'd prefer if the solution was in PHP, but it's not an obligation.
Thanks!

A: If S3 buckets are for users in your account
If you're talking about access keys associated to users in an account that you countrol, have a look at AWS Identity and Access Management / ListAccessKeys.

IAM [ Identity and Access Management] is a web service that enables
  AWS customers to manage users and user permissions under their AWS
  account

If S3 buckets are for an account that you do not own
If you're talking about an access key associated with someone else's AWS account (as well as per your comment the secret key), according to AWS you can only get the access key from the Access Keys tab on the AWS Security Credentials page.
This makes perfect sense, as the access key is a protected account secret.  Providing an API to retrieve secrets would not make sense.
Additionally, if a user provided you with their account credentials, that would be an enormous security issue.  You could spin up any AWS resources you wanted and they would be liable.  Even if they trusted you 100% not to do that, if you allow that login data to be hacked, the hacker could do the same.  If LinkedIn login data can be hacked, you can be hacked too.

A: Given the the user name you can list the users accesskeys using ListAccessKeys api.
But there seems to a catch in your problem. In order to use the above api you will need to sign the request with an accesskey - secret pair. And I dont think you will have they coz you are building a tool for other other unless the users in your aws account and full permission atleast on s3 and iam.
Then again this will allow you get only the accesskeys not their secret. Asking for the secret is like asking someone for their password so that you can do something on their behalf. So you can't get the secret from the aws through any api, the only way to get it is if the user gives it to you.

A: I found out a way to make it work. Basically, I've set up a Selenium Webdriver server and downloaded all required C# files. I then created this little script:
    static void Main(string[] args)
    {
        IWebDriver driver;
        driver = new FirefoxDriver();

        driver.Navigate().GoToUrl("https://aws-portal.amazon.com/gp/aws/securityCredentials");
        driver.FindElement(By.Id("ap_email")).Clear();
        driver.FindElement(By.Id("ap_email")).SendKeys("USER@EMAILACCOUNT.COM");
        driver.FindElement(By.Id("ap_password")).Clear();
        driver.FindElement(By.Id("ap_password")).SendKeys("HISPASSWORD");
        driver.FindElement(By.Id("signInSubmit")).Click();

        IList<IWebElement> keys = driver.FindElements(By.LinkText("Show"));
        int nbElems = keys.Count;
        System.Console.WriteLine(nbElems+" keys");
        foreach (IWebElement k in keys)
        {
            String toparse = k.GetAttribute("href");
            Regex regex = new Regex(@"'(?<key>.*)','(?<secret>.*)'");

            GroupCollection groups = regex.Match(toparse).Groups;

            System.Console.WriteLine(groups["key"] + " " + groups["secret"]);
        }

        driver.FindElement(By.LinkText("Sign Out")).Click();
        driver.Quit();
    }

Now I just need to find a way to send the user information safely to this script.
Thanks for the help guys!


text:
Q: Blocking operations in URLConnection Running the following code snippet:
URL url = new URL(uri);
URLConnection urlconn = url.openConnection();
urlconn.connect();
urlconn.getContentLength();

I get the dead-lock sometimes, usually at two lines: urlconn.connect() and urlconn.getContentLength(). Also, when I do
InputStream is = urlconn.getInputStream();
// doing some reading
is.close();

I also get blocking at is.close(). I want to ask why such blocking happens. It is clueless to me from the Java API.


text:
Q: How to validate refactoring in Clojure? I found the following code in enlive:
net.cgrand.enlive-html=> (source node-selector?)
(defn node-selector? [selector]
  (not (fragment-selector? selector)))

and thought about refactoring it to the following code:
(def node-selector? (complement fragment-selector?))

How can I validate the completeness of the refactoring so all cases are properly handled with the change?

A: cough tests cough and thinking hard.
You have to ensure that the arguments and results domains haven't changed (special care when dealing with truthy values).
In this case the change seems innocuous BUT you lose something: doc doesn't document the arglist anymore.
Another subtle consequence: when you redefine fragment-selector?, node-selector? still refers to the old fragment-selector?.


text:
Q: How to best handle data models in an an Android App? I have a college project where the idea is to allow gym-goers to record their progress/evolution in several machines/exercises (e.g. first week I ran 6km in the treadmill in 15 minutos; second week I ran 6.5km, and so forth). I want the user to be able to create an activity plan by selecting several machines/exercises from a list, and each machine/exercise has properties (such as repetitions, muscle groups trained, time, weight, distance, etc).
So, my question is: what is the best way to store the different types of machines/exercises on the apk? Is it to create models for each generic type and load them from a local JSON? Define each exercise outside the app and connect it to a database and have the app fetch the list to the user?
In a prior project I created a Truth or Dare game where the questions (truths or dares) where loaded from a local JSON and turned using a factory to actual questions (using a Question model) to display in-game, but I never found out if that's the best/correct approach.
P.S.: there exists both the possibility that the App is solely local OR that it will be connected to a server + db. Unfortunately, due to the nature of the project I cannot give a concrete answer to this question, but would instead appreciate an answer to both cases...
Thanks in advance!

A: Using apk's local storage for data storage/retrieval
In such case you can either use JSON for storage/retrieval or android's SQLiteDatabase . If you use SQLiteDatabase for storage your app will contain db file which is a small database embedded in apk
If your data contains multiple entities related to each other then you have to go for SQLiteDatabase as using a plane JSON in such case would not be simple
Using remote storage for data storage/retrieval in apk
In this case you can setup database server in remote machine for your app.
Or
You can use Firebase
It depends what type of app you are making, if user doesn't have to update its exercise progress to remote machine then local SQLiteDatabase would be sufficient in your case


text:
Q: Array elements changing seemingly arbitrarily [parallel quicksort/prefix sum] So I'm working on an implementation of parallel quicksort in C using Cilk, and I'm running into an odd problem. The relevant portions of my code, for reference (and apologies in advance for length):
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <math.h>
#include <cilk/cilk.h>
#include <cilk/cilk_api.h>

void prefixSum(int* input,int* output, int length){
   if(length == 1){
      output[0] = input[0];
      return;
   }
   int i;
   int nPairs = (int) floor(((double)length)/2);
   int pairs = (int) ceil(((double)length)/2);
   int z[pairs];
   int w[pairs];
   cilk_for(i=0;i<nPairs;i++){
      z[i] = input[2*i]+input[2*i+1];
   }

   if(pairs>nPairs){
      z[pairs-1] = input[length-1];
   }
   prefixSum(z,w,pairs);
   cilk_for(i=0;i<length;i++){
      if(i==0){
         output[i] = input[i];
      }
      else if((i-1)%2==0){
         output[i] = w[(i-1)/2];
      }
      else{
         output[i] = w[(i-2)/2] + input[i];
      }
   }
   return;
}

void prefixScan(int* input, int length){
   int i;
   for(i=length-1;i>0;i--){
      input[i] = input[i-1];
   }
   input[0] = 0;
}

void paraSort(double* array, int length){
   if(length==1){
      return;
   }
   int pivot = rand() % length;
   int lowSet[length];
   int highSet[length];
   int equalSet[length];
   int i;
   cilk_for(i=0;i<length;i++){
      if(array[i]==array[pivot]){
         lowSet[i] = 0;
         highSet[i] = 0;
         equalSet[i] = 1;
      } else if(array[i]<array[pivot]){
         lowSet[i] = 1;
         highSet[i] = 0;
         equalSet[i] = 0;
      } else {
         lowSet[i] = 0;
         highSet[i] = 1;
         equalSet[i] = 0;
      }
   }
   int lowIndex[length];
   int highIndex[length];
   int equalIndex[length];
   prefixSum(lowSet,lowIndex,length);
   int numLow = lowIndex[length-1];
   prefixScan(lowIndex,length);

   prefixSum(highSet,highIndex,length);
   int numHigh = highIndex[length-1];
   prefixScan(highIndex,length);

   prefixSum(equalSet,equalIndex,length);
   int numEqual = equalIndex[length-1];
   prefixScan(equalIndex,length);

   double lowList[imin(numLow,1)];
   double highList[imin(numHigh,1)];
   double equalList[numEqual];

   cilk_for(i=0;i<length;i++){
      if(lowSet[i]==1){
         lowList[lowIndex[i]] = array[i];
      } else if(highSet[i]==1){
         highList[highIndex[i]] = array[i];
      } else if(equalSet[i]==1){
         equalList[equalIndex[i]] = array[i];
      }
   }

   if(numLow>0 && numHigh>0){
      cilk_spawn paraSort(lowList,numLow);
      paraSort(highList,numHigh);
      cilk_sync;
   } else if(numLow==0 && numHigh>0){
      paraSort(highList,numHigh);
   } else if(numLow>0 && numHigh==0){
      paraSort(lowList,numLow);
   }
   cilk_for(i=0;i<length;i++){
      if(i<numLow){
         array[i] = lowList[i];
      } else if(i<numLow+numEqual){
         array[i] = equalList[i-numLow];
      } else {
         array[i] = highList[i-(numLow+numEqual)];
      }
   }
   return;
}

Now, when I run this on a test case of 50 elements (sequentially, for ease of debugging), I get one layer deep into the recursion and then encounter a segmentation fault that seems to be caused by an out-of-bounds index in the line equalList[equalIndex[i]] = array[i];.
Checking further, immediately after allocating equalIndex, the values in it are completely arbitrary. This is to be expected; I haven't assigned anything yet. prefixSum is called on a list of elements which is all zero except for the second-to-last element, which is one. (This is a bitmap marking the elements equal to the pivot.) It puts the results of a prefix sum operation into equalIndex, which I pass in as a pointer to the array so that the results persist outside the call.
After doing this, debug printf commands show that equalIndex is now all zeroes save for the last two elements, which are both one. This is the expected prefix sum result; so far so good. prefixScan is a simple helper function to help me tackle indexing from zero; it moves all the elements in the given array one space to the right, filling in the first element with zero. After passing equalIndex to this, debug statements show that equalIndex is all zeroes except for the last element, which is one.
Where the problem arises is immediately following, in the cilk_for loop that copies each element into its proper array. In the body of this loop, printf statements now display values that don't match the previous ones in the slightest - some are properly zero, others wildly large positive or negative integers of the sort I saw earlier before I had initialized this array with prefixSum. Once it hits one of these extreme values and tries to use it as an array index, the program rightly crashes.
My best guess is that somehow the values in equalIndex aren't being assigned properly (hence the odd behavior as though I hadn't initialized the array), but I'm having a lot of trouble figuring out exactly what's going wrong and where.

A: You contradict yourself.  At one point you say

equalIndex is all zeroes except for the last element, which is one

but later you speculate that

somehow the values in equalIndex aren't being assigned properly

.  You can't have it both ways.
I don't know Cilk, but extrapolating from C, I'm inclined to think you are trashing your own data.  Consider in particular this code, which seems to be the locus of the trouble:
double lowList[imin(numLow,1)];
double highList[imin(numHigh,1)];
double equalList[numEqual];

cilk_for(i=0;i<length;i++){
    if(lowSet[i]==1){
       lowList[lowIndex[i]] = array[i];
    } else if(highSet[i]==1){
       highList[highIndex[i]] = array[i];
    } else if(equalSet[i]==1){
       equalList[equalIndex[i]] = array[i];
    }
}

How long are arrays lowList and highList?  Study their declarations before you answer.  Now what do you suppose might happen if you attempted to assign values to elements of those arrays outside their bounds?


text:
Q: Matching up tables to group properly Im having a lot of trouble counting the amount of vendors per county, per state in our database.  Was hoping someone could help me out.
I have one table called vendors which lists the vendors id (key) and their current assignments.
the next table is called postal codes and the columns i need from it are postalcode, FIPS (this is a code for counties in the US) and state. this is simply a list of possible states, postal codes and fips
my third table is vendoraddresses, which lists the addresses of each vendor but does not have a county or fips column or else this would be very easy. this is linked to the vendor table through the vendorid key
the final table is counties, which has the county name for each fips code lined up in rows (ie: 12345 = county name)
im having trouble working with all of these tables together to accurately count the vendors per county per state.  i feel like this really shouldn't be so hard but i hit a mental block i guess.  Below is what i have so far, but its not what i need. Im wondering if a union or something like that would be a better choice to get all these tables together.
SELECT

va.state
,pc.fips
,count(v.vendorid) as vendors

FROM
Vendors v
join vendoraddresses va on va.vendorid = v.vendorid
join postalcodes pc on pc.postalcode = va.postalcode
group by va.state, fips
order by va.state, fips

so with some help ive tried to make some progress:
SELECT
State1
,County
,COUNT(Vendor) as Vendors
FROM
(
SELECT
c.name as County, pc.State as State1, v.VendorID as Vendor
FROM
Vendors v
join vendorserviceareas vsa on vsa.vendorid = v.vendorid
join vendorserviceareaentries vsae on vsae.vendorserviceareaid =     vsa.vendorserviceareaid
join counties c on c.fips = vsae.fips
join postalcodes pc on pc.fips = c.fips

union

select c.name as county, s.name as state1, vsa.Vendorid as Vendor from states s
join counties c on c.fips = s.fips
join vendorserviceareaentries vsae on vsae.fips = c.fips
join vendorserviceareas vsa on vsae.vendorserviceareaid = vsa.vendorserviceareaid

)a
GROUP BY State1, County
Order BY State1, County

the additional tables i have added have the following columns (using abbreviations from query) vsa column 1 = serviceareaid (numerical ID), column 2 = vendorid (numerical id) column 3 =  description(text to describe area of service) (varchar(50))
the other table vsae has the following columns, column 1 = serviceareaid - same as above table, fips = county code (FK char (5)), and postal code (char (5))
and for some more info each service are could be called "california" or somehting like that, the system then has each state, then county, then postal codes within each county listed for a service area, this is where most of my issue is lying because i can get any number of postal codes per county so im getting a false count for what im trying to do.
My ultimate goal is to find out per county how many vendors i have without taking into account the postal codes of a county.

A: I believe the problem that you are having is that postal codes can be in multiple counties.  You can check this by running the query:
select pc.fips, pc.postalcode, count(*)
from postalcodes pc
group by pc.fips, pc.postalcode
having count(*) > 1
order by 3 desc

This will give you a list of duplicates.  There are even postal codes that span states.
You will need to assign a postal code to a county.  If you have other information, such as population for the intersection of the postal code and county, you can try something like:
from (select pc.*
      from (select pc.*, row_number() over (partition by postal_code order by pop desc) as seqnum
            from postalcodes pc
           ) pc
      where seqnum = 1
     ) pc

This assigns to the postal code to the county where the larger population is.


text:
Q: splitting lemma in $C^*$ algebras In abelian category,there is a splitting lemma. see https://en.wikipedia.org/wiki/Splitting_lemma
I wonder whether the splitting lemma also holds in $C^*$ algebras .Is left split equivalent to right split?

A: No, not even if the C$^*$-algebra is commutative. For instance if you take $A=C_b(\mathbb N)$ (bounded sequences), then $I=c_0(\mathbb N)$ is an ideal that is not complemented.


text:
Q: HttpClient accessing a socket application I started down the path of using HttpClient as I thought the service I was accessing is a REST service.  Turns out it's a JSON service running on port 80 but is a socket application.
The HttpClient opens the remote port but when it sends the JSON request it never gets a response.  I was having the hardest time getting fiddler to get a response back as well.  But I was able to get wget and curl to send/receiving a response.  That's when I talked to the original developer and he mentioned that it wasn't a true "REST" service, but just a socket application that sends/receives JSON.
Is there something I can do to tweak HttpClient to access a socket application or am I going to have to take a step back and use WebSockets?
This is the test code that sends/receives the JSON packet.
        private async Task ProcessZone(string szIPAddress)
    {
        string responseData = string.Empty;

        Uri baseAddress = new Uri(@"http://" + szIPAddress + "/player");

        try
        {
            using (var httpClient = new HttpClient { BaseAddress = baseAddress })
            {
                var _req = new SendRequest();
                _req.id = "rec-100";
                _req.url = "/stable/av/";
                _req.method = "browse";

                var _json = JsonConvert.SerializeObject(_req);

                using (var content = new StringContent(_json,Encoding.UTF8, "application/json"))
                {
                    using (var response = await httpClient.PostAsync(baseAddress, content))
                    {
                        responseData = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }
                }
            }

            var _Response = JsonConvert.DeserializeObject<Response>(responseData);

            var item = new ZoneInfo();
            item.szIPAddress = szIPAddress;
            item.szZoneName = _Response.result.item.title;
            lstZones.Add(item);

        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }

    private async Task ProcessZones()
    {

        foreach (var item in ZoneSearch)
        {
            await ProcessZone(item.IPAddress);
        }
    }

The connection hangs on this line:
using (var response = await httpClient.PostAsync(baseAddress, content))

I should also mention that the code above does work fine on a true rest service...

A:
That's when I talked to the original developer and he mentioned that it wasn't a true "REST" service, but just a socket application that sends/receives JSON.

Knowing the protocol is the first step towards making a working client.

Is there something I can do to tweak HttpClient to access a socket application or am I going to have to take a step back and use WebSockets?

Neither, unfortunately. HttpClient - as the name implies - only works with HTTP services. Since the server is not an HTTP server, it won't work with HttpClient. WebSockets have a rather confusing name, since they are not raw sockets but instead use the WebSocket protocol, which require an HTTP handshake to set up. Since the server is not an HTTP/WebSocket server, it won't work with WebSockets.
Your only choices are to either pressure the developer to write a real REST service (which makes your job orders of magnitude easier), or use raw sockets (e.g., Socket). Correctly using raw sockets is extremely difficult, so I recommend you pressure the developer to write a REST service like the entire rest of the world does today.


text:
Q: What's the best way to integrate Facebook SDK in cross platform libGDX project? Till now I haven't found clarity on how to integrate 3rd party services in a libGDX project.
My project targets Android and iOS both the platforms.
Can someone tell me the best ways to do that?

A: You can try https://github.com/TomGrill/gdx-facebook or write your own platform specific code https://github.com/libgdx/libgdx/wiki/Interfacing-with-platform-specific-code


text:
Q: How to get the view's HTML in the Yaf controller action? I have a problem with Yaf.
I make a view file a.phtml, and the code in a.phtml is:

<?php echo 'abcd';?>

How can I get the HTML code
abcd
 in a controller function?

A: There are multiple ways of doing this.

*

*Inside your controller: file_get_contents( $templatePath . '/a.phtml');

*Configure View. Then Use $tpl = $this->getView()->render(), see Yaf_View_Simple::render(), to render the template content into a buffer variable.


text:
Q: Передать в конструктор класса список аргументов Ребят, помогите разобраться, как передать в конструктор класса список аргументов и пройтись циклом по этому списку?
class A():
    def __init__(self,*name):
        self.name = name

    def func(self):
        if self.name == 'a':
            print ('aaa')
        elif self.name == 'b':
            print ('bbb')
        elif self.name == 'c':
            print ('ccc')

Методом тыка понял, что можно передать туда аргументы ,собственно, через цикл:
letters = ['a','b','c']
for i in letters:
    letters = A(i)
    letters.func()

Но как-то мне кажется это громоздко. Может есть более "правильный" способ?

A: Не очень понятно, чего Вы хотите. Может быть, этого:
class A:
    def __init__(self, *names):
        self.names = names

    def func(self):
        for n in self.names:
            if n == 'a':
                print('aaa')
            elif n == 'b':
                print('bbb')
            elif n == 'c':
                print('ccc')

a = A('a', 'b', 'c')
a.func()


text:
Q: Playbooks that needs to be tweaked depending on the targeted environment In our company we're using ansible to target different environments, about 10 on the development and integration side, and 3 on the production side. Those environments have some differences in terms of the number of resources dedicated. For example let say in production we have a standalone server or vm dedicated to run the jvm, another one for dB... And in certain other environments those applications share the same server or vm. The problem is that some playbooks needs to be tweaked in order to target such an environment, so how could we do to make it as generic and transparent as possible?
Thanks for your advices

A: what you want to achieve is putting good hosts in good groups.
if you're familiar with ansible-inventory --graph, here is what you want to achieve:
@all:
  |--@dev:
  |    |--devel1.domain.org
  |    |--devel2.domain.org
  |--@db:
  |    |--db1.domain.org
  |    |--db2.domain.org
  |    |--dbprod1.domain.org
  |    |--appprod2.domain.org
  |--@app:
  |    |--app1.domain.org
  |    |--app2.domain.org
  |    |--appprod1.domain.org
  |    |--appprod2.domain.org
  |--@dev1:
  |    |--devel1.domain.org
  |    |--db1.domain.org
  |    |--app1.domain.org
  |--@dev2:
  |    |--devel2.domain.org
  |    |--db2.domain.org
  |    |--app2.domain.org
  |--@prod:
  |    |--@prod1:
  |    |    |--dbprod1.domain.org
  |    |    |--appprod1.domain.org
  |    |--@prod2:
  |    |    |--appprod2.domain.org

here the host appprod2.domain.org will inherit from group_vars of app,db, prod,prod2


text:
Q: How to dynamically load several images that are accessed by a curl command? I have a List of Objects (already in a RecyclerView) and in each of the objects there's an image-id (String, could be null) that I can use to form a URL and get an image.
The problem is, I can only get the image with a GET curl command. I need to give an accessToken as a Header.
Is there a service like Glide or Picasso that would allow me to what I need to?

A: In glide you can add custom header, set your access token in header as follows:
GlideUrl glideUrl = new GlideUrl("url", new LazyHeaders.Builder()
 .addHeader("accessToken", "your-access-token-here")).build());

GlideApp.with(this).load(glideUrl).into(yourImageView);


text:
Q: How can registered user can create a new article from joomla front-end in 2.5? How to create a new article from joomla front-end by registered user. I tried a lot but i cant solves the problem.
Only super user can create a new article.
I create a new menu called create article in main menu and its access is gives to registered. But i still got the error
An error has occurred.
The requested page cannot be found.
Home Page
If difficulties persist, please contact the System Administrator of this site and report the error below.
403 You are not authorised to view this resource.
when i will try to create a new article by registered user from front-end.
Please help me for this.
Thanx in advance...

A: By default registered users do not have create rights, you need to be an author for that.
You can do what you want in two ways, change the permission for Registered in com_content for Create to Allowed   or you could change the default user group for new users to Author.  YOu set the default group in the user manager options.

A: The working of user role in joomla is something like this:
$user =& JFactory::getUser();
    //print_r($user);
    //echo $user->get('gid');

    if($user->get('gid') == 25 ){

        //allow user
    } else{

        //disallow or redirect to somewhere

    }

The above code allows for user group 25 only.
What you need to do is:
Find the code for registered user and include the user group code in if condition.
Note: You can find the user group code from jos_users table.


text:
Q: Setting up a Range in txt file with linux commands i have a file containing number ranges
ex.:
12345 00/99
123456 20/80

and i want to translate them into 1234500 and write every number up to 1234599 automatically.
is there a way of doing this with shell?

A: Perl to the rescue!
perl -lne 'if (m{(.*) (.*)/(.*)}) { print $1, $_ for $2 .. $3 }'

*

*-n reads the input line by line

*-l adds a newline to each print

*m{} is the matching operator

*. matches anything except a newline

** means "zero or more times"

*parentheses create "capture groups"

*so, we match anything, space, anything, slash, anything; all the anythings being remembered in $1, $2, and $3 respectively

*.. is the range operator


text:
Q: Show and hide forms with ajax and javascript I am trying to insert value in database through ajax. There rows which are coming in while loop from database. I have added one column in each row which have button. On click of button i am submitting the values in database its working fine. Delete query is also working fine.
I want to hide select form on successful submission and show cancel form.
And when insert query fails want to display error.
Then display select form when delete query is successful on click Cancel button.
Need help. Thanks in advance
PHP Code :
While loop Code :
if($num_rowsslctcncl)
{
    $slctcncldis="<form name='cancel_selection' class='cancel_selection' action=''>
    <input type='hidden' name='crs' class='user_id' value='$coursename'>
    <input type='hidden' name='insertid' class='insertid' value='$insertid'>

    <button class='btn btn-cancel btn-xs' value='Cancel'>Cancel</button>
    </form>";
}

if(!$num_rowsslctcncl)
{
    $slctcncldis="<form name='form_submit_change_status' class='form_submit_change_status' action=''>
    <input type='hidden' name='crs' class='user_id' value='$coursename'>
    <input type='hidden' name='insertid' class='insertid' value='$insertid'>

    <button class='btn btn-warning btn-xs' value='Select Course'>Select Course</button>
    </form>";
}

echo"

$crs
$slctcncldis

Ajax and javascript Code :
Insert Function Code :

Delete function code :

Response.php
Insert query code:
<?php
include_once("db.php");

    $crs = $_POST["crs"];
    $sid = $_POST["insertid"];

    $strscheck="SELECT * FROM add_delete_record where sid='$sid'";
    $resultscheck=mysql_query($strscheck) or die(mysql_error());

    $num_rowscheck = mysql_num_rows($resultscheck);

    if($num_rowscheck < 3)
    {
        $strsreg="insert into add_delete_record  (sno, chcourse, sid) values('', '$crs','$sid')";
        $resultsreg=mysql_query($strsreg) or die(mysql_error());
    }
    else
    {
    }
?>

A: You need to print both forms in loop. Instead of inserting selected form, show and hide the form initially. Try something like this. Compare it with your code you will find the difference.
if($num_rowsslctcncl)
{
    $slctcncldis_Cancel ="<form name='cancel_selection' class='cancel_selection' style="display:block;" action=''>
            <input type='hidden' name='crs' class='user_id' value='$coursename'>
            <input type='hidden' name='insertid' class='insertid' value='$insertid'>
            <button class='btn btn-cancel btn-xs' value='Cancel'>Cancel</button>
        </form>";

} else {
    $slctcncldis_Cancel ="<form name='cancel_selection' class='cancel_selection' style="display:none;" action=''>
            <input type='hidden' name='crs' class='user_id' value='$coursename'>
            <input type='hidden' name='insertid' class='insertid' value='$insertid'>
            <button class='btn btn-cancel btn-xs' value='Cancel'>Cancel</button>
        </form>";
}

if(!$num_rowsslctcncl)
{

    $slctcncldis_Submit ="<form name='form_submit_change_status' class='form_submit_change_status' style="display:block;" action=''>
            <input type='hidden' name='crs' class='user_id' value='$coursename'>
            <input type='hidden' name='insertid' class='insertid' value='$insertid'>
            <button class='btn btn-warning btn-xs' value='Select Course'>Select Course</button>
            </form>";

} else {
    $slctcncldis_Submit ="<form name='form_submit_change_status' class='form_submit_change_status' style="display:none;" action=''>
            <input type='hidden' name='crs' class='user_id' value='$coursename'>
            <input type='hidden' name='insertid' class='insertid' value='$insertid'>
            <button class='btn btn-warning btn-xs' value='Select Course'>Select Course</button>
            </form>";

}

echo"

$crs
$slctcncldis_Cancel.$slctcncldis_Submit

    Ajax and javascript Code :

Insert Function Code :


text:
Q: jQuery: Run function if each tr has class I have a table where trs are being assigned class with js.
I have another div that I want to reflect it on. However, my each() function doesn't seem to be working properly.
I have the following JS:
$("table.result tr").each(function() {
    if($(this).hasClass("red")) {
        $("#color").addClass("red");
        //bunch of other things
    } else {
        $("#color").addClass("green");
        //bunch of other things
    }
});

And this is my markup:

       Name
       Result

       John Doe
       Pass

       Johnathan Doe
       Pass

       Jane Doe
       Fail

What I'm trying to do is, if all the trs have a class of red, only then do I want the div to have the class of red too else it should be green. But the jQuery is only testing it on the last tr whether it has the class or not.
But it doesn't seem to be working. It's probably a very small mistake but I cannot figure it out. Here's a jsfiddle: https://jsfiddle.net/okvv330L/6/
As you can see, since one tr does not have the class red, the div should be green. But it's only checking the last tr and basing it on that.
Thanks!

A: This is because the original styling is overriding the style of the added class.
The easiest solution would be to add higher specficity like
.red, #color.red {
    background: red;
}

Update

What I'm trying to do is, if all tr's have the class red, then give the div a class of red else give it green.

$(function() {
  $("#color").addClass("green");
  $("table.result:not(:has(tr:not(.red))) + #color").addClass("red");
});
#color {
  height: 50px;
  width: 50px;
  background: #ccc;
}
.green,
#color.green{
  background: green;
}
.red,
#color.red {
  background: red;
}

    Name
    Result

    John Doe
    Pass

    Johnathan Doe
    Pass

    Jane Doe
    Fail

A: It's working perfectly as it's adding the class .red in your div but it's just not taking the css as per the css specificity as id has greater specificity than class.
So, you may use:
#color.red{
  background-color: #f00;
}

Or, you may use !important:
.red{
   color: #f00 !important;
}

your jsfiddle

As per your comment, I have updated the fiddle. You may use like this:
$(function() {
    if($("table.result tr.red").length == $("table.result tr").length) {
            $("#color").addClass("red");
        } else {
            $("#color").addClass("green");
        }
});

A: change your css.use important tag
.green {
    background: green !important;
}
.red {
    background: red !important;
}

A: Update: Since your want to assign the class red to #color only if all the trs has the class red
In that case using  a loop will be wrong as it will always use the state of the last tr.
Also you have a problem with css specificity, where you have assigned a background color using ID property then that will have preference over the class rule you are assigning later, so you will have to make the class rule more specific by using a combination of the id rule and class rule.

$(function() {
  var green = $("table.result tr").is(':not(.red)');
  $("#color").toggleClass("green", green);
  $("#color").toggleClass("red", !green);
});
#color {
  height: 50px;
  width: 50px;
  background: #ccc;
}
.green,
#color.green {
  background: green;
}
.red,
#color.red {
  background: red;
}

    Name
    Result

    John Doe
    Pass

    Johnathan Doe
    Pass

    Jane Doe
    Fail

A: I got this working by using the following code:
var $rowCount = $('.result tr').length;
var $rowFill = 0;
$(".result tr").each(function() {
    if($(this).is('.red')) {
        $rowFill = $rowFill + 1;
    }
});
if($rowFill == $rowCount) {
    $('#color').addClass('red');
} else {
    $('#color').addClass('green');
}

Since the each() was only testing the last row; I got it to match the count with the number of rows. So now, it seems to work fine.


text:
Q: ASP.net Web Site referencing code files with dependencies on non-compiled code I have a website that is not utilizing the App_Code folder for jit compiling code files (that is what App_code is for, right?).  Instead developers have to either cram all the necessary classes that they need for a page into the code file, or into an individual .cs file that gets and Assembly Directive src on the page (this is because of dependencies between the source files).
Is there any way for classes with dependencies on each other to be placed in separate files?
For instance Presenter.cs has a dependency on Model.cs.  I would like to just add an assembly directive to my page for Presenter.cs, and make it happy.  But since this does not compile Model.cs, it doesn't work.  Adding Assembly references for both code files also does not work.
Is there a mechanism that I am missing?
EDIT:  I think the answer is that the App_Code folder is exactly created for this task and that there is no other/better way to do it.

A: When you say "CodeBehind" are you actually referring to "CodeFile"? (One of the many reasons I'm not a fan of "ASP.NET Websites" and prefer MVC).
AFAIK, the ASP.NET runtime compiles all of the App_Code files together into their own assembly, however code in each page's CodeFile (not their CodeBehind) can only reference this anonymous assembly and not each others' code.
Can you clarify what you mean by "page assembly reference"? Are you doing <%@ Assembly %> or do you mean a namespace import <%@ Import %> (because as I said, a lot of the code is compiled into an anonymous assembly).
I suggest you just move the common code and classes to *.cs files within App_Code. It should just work.


text:
Q: Is it possible to install macOS and Windows 10 on same external SSD? Is there anyway to install macOS Sierra and Windows 10 on external SSD drive?
I bought a new T3 250GB Samsung external USB 3 drive.
I want to install macOS on 100GB partition and Windows 10 on other 100GB partition for max speed on all OSes .
Bootcamp only offers internal HDD drive of my iMac and Windows 10 can't install on the USB drive without formatting the whole disk and which I will lose all partitions like the macOS partition .


text:
Q: Need help dispalying boolean property state using data binding So i am having trouble trying to get the right data to display in my child form.
I am using the child form to list details about the current object selected in the entry (parent) form.
My issue lies with my Binding object.  I have a boolean property (IsAutomatic) and in the details form i want when it is true, to dispaly "Automatic" and when false "Manual".
I cannot seem to get a string to display to my form, only the word "true" or "false" which in fact is the value, and not what im wanting.
below is the code i've used.
   Binding _transmission = new Binding("Text", _formDataSource.Current, "IsAutomatic");
        //how the hell do i do this?
 _transmission.FormatString = string.Format(//and i've tried a ternary operator here to display literals depending on if _transission is true or false, but this is a binding object and not a bool data type.  I attempted to try a cast on the _transmission object, but the IDE did not like it at all.
        lblTransmission.DataBindings.Add(_transmission);
   // do i want code the ternary here
 (lblTransmission.Text.Equals("true")) ? "Automatic" : "Manual"; //this brought up errors too...

Any help would be greatly appreciated for i have been on this a while now.

A: I was able to accomplish this by using a simple cast...
Vehicle _vehicle;

then later on
_vehicle = (Vehicle)_bindingSource.Current;

And to get the desired output for my label
lblTransmission.DataBindings.Add("Text", _vehicle, "IsAutomatic",true);
lblTransmission.Text = String.Format("{0}",
( _vehicle.IsAutomatic) ? "Automatic" : "Manual")

I hope this winds up helping somebody along the way.  If anyone has suggestions or critiques please feel free to tell me what you think... I'm still just a student ( only 2 terms left !!) .
Thank You.


text:
Q: How to preload WKWebView before pushing its viewcontroller? I ask this question because after some research, I haven't found satisfactory answers on the Web.
My need is simple, I have a UITableViewController, when I click on a cell, I need to display a loader (while loading the WKWebViewContent), THEN push the next UIViewController, with the WKWebView already loaded inside.
I tried this :
class TableViewController: UITableViewController, WKNavigationDelegate {

   var webviewToLoad:WKWebView!

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let htmlString = "some html content"

        webviewToLoad = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
        webviewToLoad.navigationDelegate = self
        webviewToLoad.loadHTMLString(htmlString, baseURL: Bundle.main.resourceURL)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "postview"{
            let destinationController = segue.destination as! ViewController
            destinationController.webView= webviewToLoad
        }
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("Loaded!")
        self.performSegue(withIdentifier: "postview", sender: self)
    }

}

class ViewController: UIViewController, WKUIDelegate {

    var webView: WKWebView!

    override func loadView() {

        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        self.view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

didFinish is called, but the final WKWebView is blank.
Maybe it isn't the right way, any ideas?

A:
didFinish is called, but the final WKWebView is blank

Because you never did anything to make it not blank. Your code says:
var webviewToLoad:WKWebView!
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    webviewToLoad = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
    webviewToLoad.navigationDelegate = self
    webviewToLoad.loadHTMLString(htmlString, baseURL: Bundle.main.resourceURL)
}

So everything you do is about webviewToLoad. But webviewToLoad is not the same webView that appears in the ViewController after the segue:
class ViewController: UIViewController, WKUIDelegate {
    var webView: WKWebView!
}

That is the web view you want to give content to. You are not doing that at all; none of your code touches webView to give it content.
I think the heart of your confusion is here:
if segue.identifier == "postview"{
    let destinationController = segue.destination as! ViewController
    destinationController.webView = webviewToLoad
}

You cannot just substitute one web view for another and expect things to magically work; loadView will still cause the original blank web view to be your view and to appear in the interface.
Instead, what you want is this architecture:
if segue.identifier == "postview"{
    let destinationController = segue.destination as! ViewController
    // make `loadView` run
    destinationController.loadViewIfNeeded()
    let webView = destinationController.webView
    // now load _this_ `webView` with content!
    let htmlString = "some html content"
    webView.loadHTMLString(htmlString, baseURL: Bundle.main.resourceURL)
}

A: As @matt's answer was incomplete, here my solution to wait the webview loading before pushing the next view controller:
class TableViewController: UITableViewController, WKNavigationDelegate, WKUIDelegate {

    var webviewToLoad:WKWebView!
    var destinationController:ViewController!
    var alert:UIAlertController!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        alert = UIAlertController(title: "Alert", message: "Loading", preferredStyle: .alert)

        destinationController = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ViewController") as? ViewController

        destinationController!.loadViewIfNeeded()
        let webView:WKWebView = destinationController!.webView
        webView.navigationDelegate = self
        webView.uiDelegate = self

        self.present(alert, animated: true, completion: nil)

        let htmlString = "my html code"
        webView.loadHTMLString(htmlString, baseURL: Bundle.main.resourceURL)
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

        alert.dismiss(animated: false, completion: nil)
        self.navigationController?.pushViewController(destinationController!, animated: true)
    }

}

And the UIViewController with the webview inside:
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {

    var webView: WKWebView!
    @IBOutlet var viewForWebview: UIView!
    @IBOutlet var heightWebviewConstraint: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

     override func loadView() {

        super.loadView()

        webView = WKWebView()

        if (webView != nil) {
            webView!.frame = viewForWebview.frame

            webView.translatesAutoresizingMaskIntoConstraints = false

            viewForWebview.addSubview(webView!)

            NSLayoutConstraint.activate([
               webView.topAnchor.constraint(equalTo: viewForWebview.topAnchor),
                webView.bottomAnchor.constraint(equalTo: viewForWebview.bottomAnchor),
                webView.leadingAnchor.constraint(equalTo: viewForWebview.leadingAnchor),
                webView.trailingAnchor.constraint(equalTo: viewForWebview.trailingAnchor)
                ])
        }

    }

    override func viewDidLayoutSubviews() {

        super.viewDidLayoutSubviews()

        heightWebviewConstraint.constant = self.webView.scrollView.contentSize.height
        self.view.setNeedsLayout()
        self.view.setNeedsUpdateConstraints()

    }
}

This code displays an UIAlertController during the webview loading, then dismiss the alert controller, and pushing the next controller, with the webview already loaded.


text:
Q: Sending multiples emails with grails mail plugin I am trying to send an email and just after I send the first email. I want to send a second email to a different address. I am using Grails mail plugin.
To send the two emails I use:
mailService.sendMail{
info first email
}
mailService.sendMail{
info second email
}
In development the two emails are sending, but not in production.
Somebody have an idea?


text:
Q: Inline formatting in the Stack Exchange apps and mobile web eats spaces My post contains several lines with inline formatted code. It looks aligned in web:

But it looks like spaces are eaten in the Android app:

Same buggy behavior in iOS app:

And mobile web:

*

*App Version: 1.0.95

*Device Manufacturer: LGE

*Device Model: LG-H860

*OS Version: 7.0 (1710300506712)

*

*App Version: 1.7.0.1

*Device: Unknown (iPad7,3) / iPad Pro 10.5"

*OS Version: Version 10.3.3 (Build 14G60)


text:
Q: MVC call action method from Html.DropDownList _Layout:
@if (User.Identity.IsAuthenticated)
                        {

@Html.DropDownList("User", new List<SelectListItem>
                           {
                               new SelectListItem { Text = User.Identity.Name, Value = "1", Selected = true },
                               new SelectListItem { Text = "Logout", Value = "2" }
                           })

                        }

When the user clicks on the logout option drop down list I need to call the Logout() method like you can with ActionLinks. How do I do this?
Edit:
Signout isn't working with new jquery code. Why is this?
public ActionResult Logout()
        {
            FormsAuthentication.SignOut();

        return View("../Home/Index");
    }

My old code still works though by logging user off though.

@Html.ActionLink("Logout", "Logout", "Users", new { }, new { @class = "nav-link" })

A: You could do something like this, assuming you are using jQuery:

Alternatively you could do unordered list with these items, that would be displayed on click or hover of some other element. Of course you'd have to style it. This way you could use ActionLink. MVC.Authentication.LogOut() is just example Action to logout.

User.Identity.Name

@Html.ActionLink("Log out", MVC.Authentication.LogOut())


text:
Q: Identifying overlapping time intervals with two more criteria in R?

I have to check birds observations made over a longer period for duplicate/overlapping entries.
Observers from different points (A,B,C) made observations and marked them on paper maps. Those lines where brought into a line feature with additional data for the species, the observation point and the time intervals they were seen.
Normally, the observers communicate with each others via phone while observing, but sometimes they forget, so I get those duplicate lines.
I already reduced the data to those lines which touch the circle, so I do not have to make a spatial analysis, but only compare the time intervals for each species and can be quite sure that it is the same individual that is found by the comparison.
I'm now looking for a way in R to identify those entries which:

*

*are made on the same day with an overlapping interval

*and where it is the same species

*and which were made from different observation points (A or B or C or ...))

In this example, I manually found possibly duplicated entries of the same individual. Observation point is different (A <-> B), species is the same (Sst) and the interval of the start and end times overlaps.

I would now create a new field "duplicate" in my data.frame, giving both rows a common id to be able to export them and later decide on what to do.
I searched around a lot for already available solutions, but didn't find any concerning the fact that I have to subset the process for the species (preferably without a loop) and have to compare the rows for 2 + x observation points.
Some data to play around with:
testdata <- structure(list(bird_id = c("20150712_0810_1410_A_1", "20150712_0810_1410_A_2",
"20150712_0810_1410_A_4", "20150712_0810_1410_A_7", "20150727_1115_1430_C_1",
"20150727_1120_1430_B_1", "20150727_1120_1430_B_2", "20150727_1120_1430_B_3",
"20150727_1120_1430_B_4", "20150727_1120_1430_B_5", "20150727_1130_1430_A_2",
"20150727_1130_1430_A_4", "20150727_1130_1430_A_5", "20150812_0900_1225_B_3",
"20150812_0900_1225_B_6", "20150812_0900_1225_B_7", "20150812_0907_1208_A_2",
"20150812_0907_1208_A_3", "20150812_0907_1208_A_5", "20150812_0907_1208_A_6"
), obsPoint = c("A", "A", "A", "A", "C", "B", "B", "B", "B",
"B", "A", "A", "A", "B", "B", "B", "A", "A", "A", "A"), species = structure(c(11L,
11L, 11L, 11L, 10L, 11L, 10L, 11L, 11L, 11L, 11L, 10L, 11L, 11L,
11L, 11L, 11L, 11L, 11L, 11L), .Label = c("Bf", "Fia", "Grr",
"Kch", "Ko", "Lm", "Rm", "Row", "Sea", "Sst", "Wsb"), class = "factor"),
    from = structure(c(1436687150, 1436689710, 1436691420, 1436694850,
    1437992160, 1437991500, 1437995580, 1437992360, 1437995960,
    1437998360, 1437992100, 1437994000, 1437995340, 1439366410,
    1439369600, 1439374980, 1439367240, 1439367540, 1439369760,
    1439370720), class = c("POSIXct", "POSIXt"), tzone = ""),
    to = structure(c(1436687690, 1436690230, 1436691690, 1436694970,
    1437992320, 1437992200, 1437995600, 1437992400, 1437996070,
    1437998750, 1437992230, 1437994220, 1437996780, 1439366570,
    1439370070, 1439375070, 1439367410, 1439367820, 1439369930,
    1439370830), class = c("POSIXct", "POSIXt"), tzone = "")), .Names = c("bird_id",
"obsPoint", "species", "from", "to"), row.names = c("20150712_0810_1410_A_1",
"20150712_0810_1410_A_2", "20150712_0810_1410_A_4", "20150712_0810_1410_A_7",
"20150727_1115_1430_C_1", "20150727_1120_1430_B_1", "20150727_1120_1430_B_2",
"20150727_1120_1430_B_3", "20150727_1120_1430_B_4", "20150727_1120_1430_B_5",
"20150727_1130_1430_A_2", "20150727_1130_1430_A_4", "20150727_1130_1430_A_5",
"20150812_0900_1225_B_3", "20150812_0900_1225_B_6", "20150812_0900_1225_B_7",
"20150812_0907_1208_A_2", "20150812_0907_1208_A_3", "20150812_0907_1208_A_5",
"20150812_0907_1208_A_6"), class = "data.frame")

I found a partial solution with the data.table function foverlaps mentioned e.g. here https://stackoverflow.com/q/25815032
library(data.table)
#Subsetting the data for each observation point and converting them into data.tables
A <- setDT(testdata[testdata$obsPoint=="A",])
B <- setDT(testdata[testdata$obsPoint=="B",])
C <- setDT(testdata[testdata$obsPoint=="C",])

#Set a key for these subsets (whatever key exactly means. Don't care as long as it works ;) )
setkey(A,species,from,to)
setkey(B,species,from,to)
setkey(C,species,from,to)

#Generate the match results for each obsPoint/species combination with an overlapping interval
matchesAB <- foverlaps(A,B,type="within",nomatch=0L) #nomatch=0L -> remove NA
matchesAC <- foverlaps(A,C,type="within",nomatch=0L)
matchesBC <- foverlaps(B,C,type="within",nomatch=0L)

Of course, this somehow "works", but is really not what I like to achieve in the end.
First, I have to hard code the observation points. I would prefer to find a solution taking an arbitrary number of points.
Second, the outcome is not in a format that I can really can resume working with easily. The matching rows are actually put INTO the same row, while my goal is to have the rows be put underneath, and in a new column, they would have a common identifier.
Third, I have to check manually again, if an interval overlaps from all three points (which isn't the case with my data, but generally could)
In the end, I would just like to receive a new data.frame with all candidates identifiable by a group id that I can join back to the lines and export the result as a layer for further examination.
So anyone more ideas how to do this?

A: As some commenters alluded, SQL is a good option for expressing rather complicated sets of constraints. The sqldf package makes it easy to use SQL's power in R without needing to set up a relational database yourself.
Here's a solution using SQL. Before running, I had to rename your data's interval columns to startTime and endTime because the name from is reserved in SQL.
library(reshape2)
library(sqldf)

dupes_wide <- sqldf("SELECT hex(randomblob(16)) dupe_id, x.bird_id x_bird_id, y.bird_id y_bird_id
                     FROM testdata x JOIN testdata y
                          ON (x.startTime <= y.endTime)
                         AND (x.endTime >= y.startTime)
                         AND (x.species = y.species)
                         AND (x.obsPoint < y.obsPoint)")
dupes_long <- melt(dupes_wide, id.vars='dupe_id', value.name='bird_id')
merge(testdata, dupes_long[, c('dupe_id', 'bird_id')], by='bird_id', all.x=TRUE)

To aid understanding, the SQL response dupes_wide ends up looking like this:
                         dupe_id              x_bird_id              y_bird_id
253FCC7A58FD8401960FC5D95153356C 20150727_1130_1430_A_2 20150727_1120_1430_B_1
9C1C1A13306ECC2DF78004D421F70CE6 20150727_1130_1430_A_5 20150727_1120_1430_B_4
1E8316DBF631BBF6D2CCBD15A85E6EF3 20150812_0907_1208_A_5 20150812_0900_1225_B_6
Self-join FROM testdata x JOIN testdata y : Finding pairs of rows from a single dataset is a self-join. We need to compare every row with every other one.  The ON expression lists the constraints for keeping pairs.
Overlapping interval: I'm pretty sure the definition of overlap I used in this SQL (source) differs from what foverlaps was doing for you. You used the "within" type, which requires the observation at the earlier obsPoint to be entirely within the observation at the later obsPoint (but it misses the converse, e.g. if C's observation is entirely within B's).  Luckily it's easy in SQL if you need to encode a different definition of overlap.
Different points: Your constraint that duplicates were made from different observation points would really be expressed (x.obsPoint <> y.obsPoint). If I'd typed that, SQL would return every duplicated pair twice, just with the birds switched order in each row.  Instead I used a < to keep only the unique half of the rows. (This is not the only way to do this)
Unique duplicate ID: As with your previous solution, the SQL itself list the duplicates in the same row.  hex(randomblob(16)) is a hacky (yet recommended) way in SQLite to generate unique IDs for each pair.
Output format: You didn't like the duplicates in the same row, so melt splits them out, and merge assigns the duplicate IDs back to your initial data frame.
Limitations: My solution doesn't handle the case where the same bird is captured in more than two tracks. It's trickier and somewhat ill-defined. For example, if their time ranges look like
    |-- Bird1 --|
             |-- Bird2 --|
                      |-- Bird3 --|
then Bird1 is a duplicate of Bird2, which is a duplicate of Bird3, but are Bird1 and Bird3 duplicates?


text:
Q: character set issue UTF-8 I have a document,in which the word "doesn't" contains apostrophe as shown below.

When i tried to process that via a python program it is showing the word as " doesnÆt" and exiting with the error as mentioned below.
UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 70: invalid start byte

I opened the document in notepad and changed the encoding to UTF-8 from ANSI(found somewhere on the web), now it is working fine.
But can some one throw light on ,what all these things are about and how can i type the kind of apostrophe with my laptop keyboard.

A: MS Word famously converts quotes to "smart-quotes", so that they properly wrap around words or point in the right direction as an apostrophe.
You haven't been exactly faithful with your copy-paste so it's hard to be sure we're talking about the same thing.
For example here's the smart-quotes compared to plain ascii:

Doesn't vs. Doesn't

or

"hello" vs. "hello"

Notice how the smart quotes on the left are curlier. In your screenshot, ' will have been mapped to the Unicode point U+2019 ('RIGHT SINGLE QUOTATION MARK'). You can't easily manually type smart quotes with using a Windows key combination and typing the Unicode value.
You've then likely saved this text as in Windows-1252 (Western Europe) encoding (aka ANSI), which assigned the byte 0x92. Then, you loaded this into Python but passed the incorrect encoding of UTF-8. That's when you saw the exception.
The way to deal with this in the future is to specify the correct encoding when opening the file in Python. E.g.
with io.open("myfile.txt", 'r', encoding="windows-1252") as my_file:
    my_data = my_file.read()


text:
Q: Closing DataSource and Using Cursor I have a method which essentially does the following:
Cursor cursor;
cursor = myCard.queryRandomCard(this);
cursor.moveToFirst();

Within the queryRandomCard method:
DataSource datasource = new DataSource(context);
datasource.open();
Cursor cursor  = (SQL STATEMENT IS HERE AND WORKS);
datasource.close();
return cursor;

The problem lay in that, upon retutn I get an error while executing "cursor.moveToFirst()" which says "the connection pool has been closed". HOWEVER, if I remove the "datasource.close()" call, then it works fine.
My question is, why does closing the database here affect the cursor that is returned? Are these two tied together closer than I had realized?
Thank you

A: A Cursor is nothing more than an iterator that operates on the tables of Database. With a Cursor you don't load the whole table at once, but you load one row each time you need it, so you need an open connection to the database in order that works.


text:
Q: Global class variable vs pointer in c++ Lets assume I have the following class:
class A
{
public:
    A() {}
};

I need to declare a global instance of class A (required by spec.), what works better?
A a; // is the constructor even called here?

or
A* pa; // and allocate later a new instance

Thanks in advance

A: "A a; - is the constructor even called here?" - yes, the constructor is called.
"* pa; - and allocate later a new instance" - if you actually assign something to this pointer variable before using it, then it can work. But do you?
In general I'd say that the need for global variables indicate a flaw in the design. But if you really have to have them, then make sure they are constructed before you use them.

A: If A a is used, there would not be a need to release memory allocated to a. When the main() function exits, the destructor for A will be automatically called.
If A *pa is used, ideally pa should be explicitly deleted at some point in the code with delete pa and care should be taken to not use pa after it has been deleted.


text:
Q: Java: ExecutorService with Callables: Reuse the same Pool in a loop? Shutdown necessary? I got a loop {Loop-1}, where I start Threads. The class which contains the {Loop-1} implements Daemon and Runnable.
In the {Loop-1} the thread, which is started, calls a method coordinate() of a class Coordinate.java where I use the ExecutorService.
When the object of Coordinate.java is created (this happens once BEFORE {Loop-1}), I instantiate a ExecutorService
pool = Executors.newFixedThreadPool(2);
In coordinate() I create two Objects of a class which implements Callable and I start them then and store the result in a List of Future results.
callableResults = pool.invokeAll(threads);
After, I try to get the results in a loop with result = future.get();
Then, I return to {Loop-1} and the whole process starts again (call coordinate(), invokeAll(), future.get()
Now Ive got the following question:
1. Do I need to shutdown the pool of ExecutorService after I got the results in coordinate()?
2. Do I need to recreate the pool everytime my {Loop-1} calls coordinate()?
Thanks for answers! :-)

A: No you do not. The threads in the fixed thread pool can be used until you call shutdown on it. So, you can simply resubmit new tasks to be executed and fetch their results, exactly as you did in the first go-round.

A: You need to shutdown the executorService once you're done processing all your tasks.
The submission of tasks can be in multiple cycles.
Once you call executorService.shutDown(), you can wait until all tasks are completed after calling shutDown() using executorService.awaitTermination(10, TimeUnit.SECONDS).
Alternatively, you can do: while (!executorService.isTerminated()) { }


text:
Q: Firestore read simulation fails, no highlighted line So, I typically don't have problems writing firestore rules but I'm coming up short on why this simulation fails.

If you don't want to follow the image link:
Rules:
service cloud.firestore {
  match /databases/{database} {
    match /server_credentials/{document = **} {
      allow read, write: if false;
    }
    match /users/{user_uid} {
        allow read, write;
        match /signatures/{sig_id} {
          allow read: if request.auth.uid != null  && resource.data.access == "public";
          allow read, write: if request.auth.uid == user_uid;
        }
        match /identity/{credential} {
          allow read, write: if request.auth.uid == user_uid;
        }
    }
    match /signatures/{sig_id} {
        allow read, list;
        allow write: if false;
    }
  }
}

Auth details:
Google as provider and foo as the uid.
I'm testing a simple read to users/foo
Any help would be quite nice.

A: This line is incorrect:
match /databases/{database} {

It should be this:
match /databases/{database}/documents {

This mistake is causing none of your rules to apply at all, and all access is being rejected by default.


text:
Q: Cargar mensaje dependiendo si inicia o cierra sesión Cargo un mensaje el cual depende de si el usuario ingresa o cierra sesión, pero existe el problema, de que solo me muestra el mensaje de inicio de sesion en ambos casos. Uso el método backView(), el cual siempre obtiene la vista anterior a la que se esta estacionada. A continuación el código:
loading.js
angular.module('loadingPage', ['ionic', 'loginApp', 'historialApp'])
    .controller('mostrarMensaje', mostrarMensaje)
    .factory('obtenerVista', obtenerVista);

mostrarMensaje.$inject = ['$scope', 'obtenerVista'];

function mostrarMensaje($scope, obtenerVista) {

    var vista_Anterior, valor_sesion;

    vista_Anterior = obtenerVista.nombreVista();

    if (vista_Anterior.stateName === "login") {
        $scope.mensaje = "Cargando Informacion";
    } else {
        $scope.mensaje = "Cerrando sesion";
    }

}

obtenerVista.$inject = ['$ionicHistory'];

function obtenerVista($ionicHistory) {

    return {

        nombreVista: function() {

            var vista;
            vista = $ionicHistory.backView();
            return vista;

        }

    };

}

Aquí un dibujo para ser mas especifico, si algo nos e entiende

Gracias de antemano por al ayuda.

A: Yo utilizo otro sistema que igual te resulta más sencillo. Se trata de guardar un valor en localStorage para saber si está o no está el usuario logueado.
Basta con añadir en la función de login:
$window.localStorage.logged = true;

y en la función de logout:
delete $window.localStorage.logged;

Así a la hora de mostrar el mensaje:
function mostrarMensaje($scope, $window) {

    if (!$window.localStorage.logged) {
        $scope.mensaje = "Cargando Información";
    } else {
        $scope.mensaje = "Cerrando sesión";
    }
}

A: Bueno pude resolver el problema de la siguiente manera:
Lo que ocurría, era que loading.js varificaba lo que estaba en window.localStorage.logged una sola vez, por eso debía ingresar múltiples veces para que ocurriera
Así que para resolverlo, hice uso de los ciclos de vida de las vistas, en este caso utilice el evento $ionicView.beforeEnter. lo activa al entrar en la página ( carga desde la caché o creado por primera vez ).
$scope.$on('$ionicView.beforeEnter', function () {
  if (!$window.localStorage.logged) {
      $scope.mensaje = "Loading Information";
  } else {
      $scope.mensaje = "Closing Session";
  }
});


text:
Q: d3 donut chart arc retrieves wrong data I have a d3 donut chart with two arcs, the main arc edge retrieves wrong data to d object on mouse over. Rest all areas in the arc shows correct data in log.
The colored area has value 70 and the other arc with 30. The colored main arc edge shows data of the second arc (30).
Fiddle
// data
var dataset = [{
    color: "#5FC5EA",
    value: 70
}, {
    color: "transparent",
    value: 30
}];

// size
var width = 460, z
height = 300,
radius = Math.min(width, height) / 2;

var pie = d3.layout.pie()
.sort(null).value(function(d) {
    return d.value;
});

// thin arc
var arc1 = d3.svg.arc()
.innerRadius(radius - 20)
.outerRadius(radius - 11);

// main arc
var arc = d3.svg.arc()
.innerRadius(radius - 16)
.outerRadius(radius - 17);

// set svg
var svg = d3.select("#d3-setup-donut").append("svg")
.attr("class",'donut-chart')
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
.on('mouseout', function() {
    d3.selectAll('.donut-tooltip').style('display','none');
});

// tooltip
var div = d3.select("body")
.append("div")
.attr("class", "donut-tooltip");

// draw thinner arc
var path = svg.selectAll(".background")
.data(pie([{
    color: "#222427",
    value: 1
}]))
.enter().append("path")
.attr("class", "background")
.attr("fill", function(d, i) {
    return d.data.color;
})
.attr("d", arc1)
.on('click', function(d, i) {
    //
})
.on("mousemove",function(d, i) {
    var mouseVal = d3.mouse(this);
    div.style("display","none");
    div.html(d.data.label+" : "+d.value)
    .style("left", (d3.event.pageX-40) + "px")
    .style("top", (d3.event.pageY-35) + "px")
    .style("opacity", 1)
    .style("display","block");
})
.on("mouseout",function(){
    div.html(" ").style("display","none");
});

// draw main arc
var path = svg.selectAll(".foreground")
.data(pie(dataset))
.enter().append("path")
.attr("class", "foreground")
//.attr("stroke-linejoin", "round")
//.attr("stroke-linecap", "round")
.attr("stroke-width", "20")
.attr("stroke","none")
.attr("stroke", function(d, i) {
    return d.data.color;
})
.attr("fill", "none")
.attr("d", arc)
.on('click', function(d, i) {
    //
})
.on("mousemove",function(d, i) {
    console.log(d)
    var mouseVal = d3.mouse(this);
    div.style("display","none");
    div.html(d.data.label+" : "+d.value)
    .style("left", (d3.event.pageX-40) + "px")
    .style("top", (d3.event.pageY-35) + "px")
    .style("opacity", 1)
    .style("display","block");
})
.on("mouseout",function(){
    div.html(" ").style("display","none");
});

// draw inner text
svg.append("text")
.text('60%')
.attr("class", "donut-inner-val")
//.attr("x", radius/12 - 30)
//.attr("y", radius/12 - 10);

svg.append("text")
.text('in progress')
.attr("class", "donut-inner-text")
.attr("x", (radius/12) - 35)
.attr("y", (radius/12) + 10);

A: Your problem is being caused by the stroke-width attribute. What happens is this: the stroke width doesn't just add pixels to the sides of the arc, it add pixels to its end as well.
We can see this in the following demo, exaggerating the stroke width and colouring the transparent path (I also changed the opacity, so you can see where each path ends):

// data
var dataset = [{
  color: "#5FC5EA",
  value: 70
}, {
  color: "red",
  value: 30
}];

// size
var width = 460,
  z
height = 300,
  radius = Math.min(width, height) / 2;

var pie = d3.layout.pie()
  .sort(null).value(function(d) {
    return d.value;
  });

// thin arc
var arc1 = d3.svg.arc()
  .innerRadius(radius - 20)
  .outerRadius(radius - 11);

// main arc
var arc = d3.svg.arc()
  .innerRadius(radius - 16)
  .outerRadius(radius - 17);

// set svg
var svg = d3.select("#d3-setup-donut").append("svg")
  .attr("class", 'donut-chart')
  .attr("width", width)
  .attr("height", height)
  .append("g")
  .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
  .on('mouseout', function() {
    d3.selectAll('.donut-tooltip').style('display', 'none');
  });

// tooltip
var div = d3.select("body")
  .append("div")
  .attr("class", "donut-tooltip");

// draw thinner arc
var path = svg.selectAll(".background")
  .data(pie([{
    color: "#222427",
    value: 1
  }]))
  .enter().append("path")
  .attr("class", "background")
  .attr("fill", function(d, i) {
    return d.data.color;
  })
  .attr("d", arc1)
  .on('click', function(d, i) {
    //
  })
  .on("mousemove", function(d, i) {
    var mouseVal = d3.mouse(this);
    div.style("display", "none");
    div.html(d.data.label + " : " + d.value)
      .style("left", (d3.event.pageX - 40) + "px")
      .style("top", (d3.event.pageY - 35) + "px")
      .style("opacity", 1)
      .style("display", "block");
  })
  .on("mouseout", function() {
    div.html(" ").style("display", "none");
  });

// draw main arc
var path = svg.selectAll(".foreground")
  .data(pie(dataset))
  .enter().append("path")
  .attr("class", "foreground")
  //.attr("stroke-linejoin", "round")
  //.attr("stroke-linecap", "round")
  .attr("stroke-width", (d,i)=>60 - i*10)
  .attr("opacity", (d,i)=> 1 - i*0.2)
  .attr("stroke", "none")
  .attr("stroke", function(d, i) {
    return d.data.color;
  })
  .attr("fill", "none")
  .attr("d", arc)
  .on('click', function(d, i) {
    //
  })
  .on("mousemove", function(d, i) {
    var mouseVal = d3.mouse(this);
    div.style("display", "none");
    div.html(d.data.label + " : " + d.value)
      .style("left", (d3.event.pageX - 40) + "px")
      .style("top", (d3.event.pageY - 55) + "px")
      .style("opacity", 1)
      .style("display", "block");
  })
  .on("mouseout", function() {
    div.html(" ").style("display", "none");
  });

// draw inner text
svg.append("text")
  .text('60%')
  .attr("class", "donut-inner-val")
  //.attr("x", radius/12 - 30)
  //.attr("y", radius/12 - 10);

svg.append("text")
  .text('in progress')
  .attr("class", "donut-inner-text")
  .attr("x", (radius / 12) - 35)
  .attr("y", (radius / 12) + 10);
$pale-blue: #f6f8fe;
$dark-two:#253644;
$pale-grey: #f0f4f7;
$font-roman:'Helvetica LT W01 Roman';
$font-light:'Helvetica LT W01 Light';
$font-bold:'Helvetica LT W01 Bold';
body {
  background-color:#25333F;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.donut-inner-val{
  text-anchor:middle;
  font-family: $font-light;
  font-size: 24px;
  fill:$pale-blue;
 }
 .donut-inner-text {
  font-family: $font-light;
  font-size: 10px;
  fill:$pale-blue;
 }
 .background {
  z-index:1;
 }
 .foreground {
  z-index:2;
 }
 .foreground, .background {
  cursor:pointer;
 }
  .donut-tooltip{
 line-height: 1;
 font-weight: normal;
 padding: 10px 5px;
 background: #ccc;
 border-color:#ccc;
 //opacity:.5;
 color: #333;
 border-radius: 2px;
 font-size:11px;
 position: absolute;
 text-align: center;
 height: 28px;
 opacity:0;
 z-index:99999;
}

As you can see, the red path is overlapping the blue path.
Solution: change the inner and outer radii, and paint the paths using fill, not stroke:

// data
var dataset = [{
  color: "#5FC5EA",
  value: 70
}, {
  color: "transparent",
  value: 30
}];

// size
var width = 460,
  z
height = 300,
  radius = Math.min(width, height) / 2;

var pie = d3.layout.pie()
  .sort(null).value(function(d) {
    return d.value;
  });

// thin arc
var arc1 = d3.svg.arc()
  .innerRadius(radius - 20)
  .outerRadius(radius - 11);

// main arc
var arc = d3.svg.arc()
  .innerRadius(radius - 30)
  .outerRadius(radius);

// set svg
var svg = d3.select("#d3-setup-donut").append("svg")
  .attr("class", 'donut-chart')
  .attr("width", width)
  .attr("height", height)
  .append("g")
  .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
  .on('mouseout', function() {
    d3.selectAll('.donut-tooltip').style('display', 'none');
  });

// tooltip
var div = d3.select("body")
  .append("div")
  .attr("class", "donut-tooltip");

// draw thinner arc
var path = svg.selectAll(".background")
  .data(pie([{
    color: "#222427",
    value: 1
  }]))
  .enter().append("path")
  .attr("class", "background")
  .attr("fill", function(d, i) {
    return d.data.color;
  })
  .attr("d", arc1)
  .on('click', function(d, i) {
    //
  })
  .on("mousemove", function(d, i) {
    var mouseVal = d3.mouse(this);
    div.style("display", "none");
    div.html(d.data.label + " : " + d.value)
      .style("left", (d3.event.pageX - 40) + "px")
      .style("top", (d3.event.pageY - 35) + "px")
      .style("opacity", 1)
      .style("display", "block");
  })
  .on("mouseout", function() {
    div.html(" ").style("display", "none");
  });

// draw main arc
var path = svg.selectAll(".foreground")
  .data(pie(dataset))
  .enter().append("path")
  .attr("class", "foreground")
  //.attr("stroke-linejoin", "round")
  //.attr("stroke-linecap", "round")
  .attr("stroke-width", "1")
  .attr("stroke", "none")
  .attr("fill", function(d, i) {
    return d.data.color;
  })
  .attr("d", arc)
  .on('click', function(d, i) {
    //
  })
  .on("mousemove", function(d, i) {
    var mouseVal = d3.mouse(this);
    div.style("display", "none");
    div.html(d.data.label + " : " + d.value)
      .style("left", (d3.event.pageX - 40) + "px")
      .style("top", (d3.event.pageY - 55) + "px")
      .style("opacity", 1)
      .style("display", "block");
  })
  .on("mouseout", function() {
    div.html(" ").style("display", "none");
  });

// draw inner text
svg.append("text")
  .text('60%')
  .attr("class", "donut-inner-val")
  //.attr("x", radius/12 - 30)
  //.attr("y", radius/12 - 10);

svg.append("text")
  .text('in progress')
  .attr("class", "donut-inner-text")
  .attr("x", (radius / 12) - 35)
  .attr("y", (radius / 12) + 10);
$pale-blue: #f6f8fe;
$dark-two:#253644;
$pale-grey: #f0f4f7;
$font-roman:'Helvetica LT W01 Roman';
$font-light:'Helvetica LT W01 Light';
$font-bold:'Helvetica LT W01 Bold';
body {
  background-color:#25333F;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.donut-inner-val{
  text-anchor:middle;
  font-family: $font-light;
  font-size: 24px;
  fill:$pale-blue;
 }
 .donut-inner-text {
  font-family: $font-light;
  font-size: 10px;
  fill:$pale-blue;
 }
 .background {
  z-index:1;
 }
 .foreground {
  z-index:2;
 }
 .foreground, .background {
  cursor:pointer;
 }
  .donut-tooltip{
 line-height: 1;
 font-weight: normal;
 padding: 10px 5px;
 background: #ccc;
 border-color:#ccc;
 //opacity:.5;
 color: #333;
 border-radius: 2px;
 font-size:11px;
 position: absolute;
 text-align: center;
 height: 28px;
 opacity:0;
 z-index:99999;
}

This is the same code, but painting the transparent path as red. Now, you can see that it ends at the correct end angle:

// data
var dataset = [{
  color: "#5FC5EA",
  value: 70
}, {
  color: "red",
  value: 30
}];

// size
var width = 460,
  z
height = 300,
  radius = Math.min(width, height) / 2;

var pie = d3.layout.pie()
  .sort(null).value(function(d) {
    return d.value;
  });

// thin arc
var arc1 = d3.svg.arc()
  .innerRadius(radius - 20)
  .outerRadius(radius - 11);

// main arc
var arc = d3.svg.arc()
  .innerRadius(radius - 30)
  .outerRadius(radius);

// set svg
var svg = d3.select("#d3-setup-donut").append("svg")
  .attr("class", 'donut-chart')
  .attr("width", width)
  .attr("height", height)
  .append("g")
  .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
  .on('mouseout', function() {
    d3.selectAll('.donut-tooltip').style('display', 'none');
  });

// tooltip
var div = d3.select("body")
  .append("div")
  .attr("class", "donut-tooltip");

// draw thinner arc
var path = svg.selectAll(".background")
  .data(pie([{
    color: "#222427",
    value: 1
  }]))
  .enter().append("path")
  .attr("class", "background")
  .attr("fill", function(d, i) {
    return d.data.color;
  })
  .attr("d", arc1)
  .on('click', function(d, i) {
    //
  })
  .on("mousemove", function(d, i) {
    var mouseVal = d3.mouse(this);
    div.style("display", "none");
    div.html(d.data.label + " : " + d.value)
      .style("left", (d3.event.pageX - 40) + "px")
      .style("top", (d3.event.pageY - 35) + "px")
      .style("opacity", 1)
      .style("display", "block");
  })
  .on("mouseout", function() {
    div.html(" ").style("display", "none");
  });

// draw main arc
var path = svg.selectAll(".foreground")
  .data(pie(dataset))
  .enter().append("path")
  .attr("class", "foreground")
  //.attr("stroke-linejoin", "round")
  //.attr("stroke-linecap", "round")
  .attr("stroke-width", "1")
  .attr("stroke", "none")
  .attr("fill", function(d, i) {
    return d.data.color;
  })
  .attr("d", arc)
  .on('click', function(d, i) {
    //
  })
  .on("mousemove", function(d, i) {
    var mouseVal = d3.mouse(this);
    div.style("display", "none");
    div.html(d.data.label + " : " + d.value)
      .style("left", (d3.event.pageX - 40) + "px")
      .style("top", (d3.event.pageY - 55) + "px")
      .style("opacity", 1)
      .style("display", "block");
  })
  .on("mouseout", function() {
    div.html(" ").style("display", "none");
  });

// draw inner text
svg.append("text")
  .text('60%')
  .attr("class", "donut-inner-val")
  //.attr("x", radius/12 - 30)
  //.attr("y", radius/12 - 10);

svg.append("text")
  .text('in progress')
  .attr("class", "donut-inner-text")
  .attr("x", (radius / 12) - 35)
  .attr("y", (radius / 12) + 10);
$pale-blue: #f6f8fe;
$dark-two:#253644;
$pale-grey: #f0f4f7;
$font-roman:'Helvetica LT W01 Roman';
$font-light:'Helvetica LT W01 Light';
$font-bold:'Helvetica LT W01 Bold';
body {
  background-color:#25333F;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.donut-inner-val{
  text-anchor:middle;
  font-family: $font-light;
  font-size: 24px;
  fill:$pale-blue;
 }
 .donut-inner-text {
  font-family: $font-light;
  font-size: 10px;
  fill:$pale-blue;
 }
 .background {
  z-index:1;
 }
 .foreground {
  z-index:2;
 }
 .foreground, .background {
  cursor:pointer;
 }
  .donut-tooltip{
 line-height: 1;
 font-weight: normal;
 padding: 10px 5px;
 background: #ccc;
 border-color:#ccc;
 //opacity:.5;
 color: #333;
 border-radius: 2px;
 font-size:11px;
 position: absolute;
 text-align: center;
 height: 28px;
 opacity:0;
 z-index:99999;
}


text:
Q: Intersection and Union of two measurable sets need some help with the following problem in Measure Theory (couldn't find this on the forum)
Q. Prove that if A1 and A2 are measurable then
$$\lambda(A1 \bigcup A2) + \lambda(A1 \bigcap A2) = \lambda(A1) + \lambda(A2) $$

A: Hint. Let $C = A_1 \cap A_2, B_1 = A_1 \setminus C, B_2 = A_2 \setminus C$. Then $C, B_1, B_2$ are disjoint measurable sets. These sets have nice addition properties you can use.

A: $\lambda(A_1) + \lambda(A_2) = \lambda( A_1 \cap A_2 ) + [ \lambda(A_1 - A_2) + \lambda(A_2 - A_1) + \lambda (A_1 \cap A_2)] = \lambda (A_1 \cap A_2) +  \lambda(A_1 \cup A_2) $
You can draw a vent diagram if you have a hard time to see this.