Q: Which is correct (if any): "please let me know what do you think"? or "please let me know what you think"? I find myself unsure which of the following is more correct:

please let me know what do you think

Or

please let me know what you think

My gut feeling tells me that it's the latter...
Or are both incorrect and there is a better way to say the same thing?

A: The latter is correct and the former is definitely wrong.
When you construct questions in English, you follow this pattern: V + S, that's why you have the Helping Verb "Do" there.
But when you construct sentences, it's the opposite, you have to follow: S + V. And if you add any other Noun Clauses or Noun Phrases to your sentence, whether they were originally in question form, they cannot follow the "V + S" question pattern.
Take a look:
What are you thinking? = Question
Please tell me what YOU ARE thinking. = Sentence
Notice that I switched the Verb and the Subject in the original question.
In the same way:
What do you like? = Question
Please tell me what you LIKE. = Sentence
Where did you go? = Question
Please tell me where you WENT.

*

*"Do" and "Did" as Helping Verbs are normally used only in Questions and Negative sentences, not positive sentences

This topic also encompasses Direct and Indirect Questions
http://www.coolelf.net/2011/12/are-you-direct-or-indirect.html

A:
Please let me know what you think

is correct. Even if do were to be included, the correct form would be

Please let me know what you do think

but this should only be used for emphasis (for example, to contrast with don't think).


Q: How to count days between to dates So I would like to count how many days between two datepickers.
So I tried to make two array but it didnt work
any Ideas?
Here my date pickers

A: Convert your calendar string day, month, year to Date class.
More discussion here: Java string to date conversion
e.g.
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date d1, d2;

try {
    d1 = dateFormat.parse(year + "-" + month + "-" + day); //as per your example
    d2 = //do the same thing as above
    long days = getDifferenceDays(d1, d2);
}
catch (ParseException e) {
    e.printStackTrace();
}

public static long getDifferenceDays(Date d1, Date d2) {
long diff = d2.getTime() - d1.getTime();
return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}

A: Create a method getDates()
private static ArrayList<Date> getDates(String dateString1, String dateString2)
{
    ArrayList<Date> arrayofdates = new ArrayList<Date>();
    DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");

    Date date1 = null;
    Date date2 = null;

    try {
        date1 = df1 .parse(dateString1);
        date2 = df1 .parse(dateString2);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    Calendar calender1 = Calendar.getInstance();
    Calendar calendar2 = Calendar.getInstance();
    calender1.setTime(date1);
    calender2.setTime(date2);

    while(!calender1.after(calender2))
    {
        arrayofdates.add(calender1.getTime());
        calender1.add(Calendar.DATE, 1);
    }
    return arrayofdates;
}

then pass the parameter in this method to get array of dates
As you are using DatePicker then
DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
    ArrayList<Date> mBaseDateList = getDates(df1.format(cal1.time), df1.format(cal2.time))

A: Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    Date d1, d2;
     Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    for (int i = 0; i < n; i++) {
        try {
            d2 = sdf.parse(in.next());
            d1 = sdf.parse(in.next());
            long differene = (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24);
            System.out.println(Math.abs(differene));
        } catch (Exception e) {
        }
    }

A: public static int getDaysBetweenDates(Date fromDate, Date toDate) {
    return Math.abs((int) ((toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24)));
}


Q: Time dependent Quantum Generators We know a space-translation generator can be written as:
\begin{equation}
T(\textbf{r}_{0})|\alpha\rangle=e^{-i\frac{\textbf{p}\cdot\textbf{r} _{0}}{\hbar}}|\alpha\rangle=|\alpha'\rangle.
\end{equation}
If the system is space-translation invariant, then
\begin{align}
H|\alpha'\rangle&=i\hbar\partial_{t}|\alpha'\rangle=i\hbar\partial_{t}T|\alpha\rangle=Ti\hbar\partial_{t}|\alpha\rangle=TH|\alpha\rangle=THT^{+} |\alpha'\rangle\\
&\rightarrow THT^{+}=H \rightarrow HT=TH.
\end{align}
If $T^{+}=T^{-1}$ as in this case.

This is the reason why a symmetry needs to have a generator that commutes with the Hamiltonian.
However this makes sense only if the generator itself is indipendente in time, otherwise there should be another term in here:
\begin{equation}
\partial_{t}T|\alpha\rangle=(\partial_{t}T)|\alpha\rangle+T(\partial_{t}|\alpha\rangle)
\end{equation}
And the commutation relation changes.
Does it ever happen or is it proven a generator of a Conservative quantity needs to be time independent?

A: *

*A conserved quantity/constant of motion does by definition not change in time, cf. e.g. this Phys.SE post.

*However, a conserved quantity could depend explicit on time.
Example: A free particle with Hamiltonian $H=\frac{p^2}{2m}$. It is straightforward to check that $$q-\frac{p}{m}t$$ is a conserved quantity with explicit time dependence.


Q: Index keys of an object where the value satisfies a condition I'm trying to write a function that takes two objects and the name of a key that both objects contain, assuming the associated values are both arrays, and compares the length of the two arrays.
The general form of the function is this:
const compareByKeyLength = <T extends Record<string, unknown[]>, K extends keyof T>(
  a: T,
  b: T,
  key: K,
) => {
  return a[key].length < b[key].length ? 1 : -1;
};

However, I want to modify this so that T does not necessarily extend Record<string, unknown[]>. That is, it cannot be assumed that the T can be indexed by any arbitrary string to get an array. Some keys on the object will be other types. What I want is to limit the allowed values for K such that only the keys which are associated with array values can be given as input.
This is my best guess as to how to implement this, but as you can see, the compiler still doesn't accept that the values will be arrays:
// Find all keys in an object whose type is an array.
type ArrayKeys<O> = {
  [K in keyof O]: O[K] extends any[] ? K : never
}[keyof O];

// Example to test if `ArrayKeys` works.
const example = {
  foo: [1, 2, 3],
  bar: "bar",
  baz: ["one", "two", "three"],
};

// Evaluates to: "foo" | "baz"
type ExampleArrayKeys = ArrayKeys<typeof example>;

// Somehow `T[ArrayKeys<T>]` doesn't prove that the value accessed will be an array. Not sure why.
const compareByKeyLength = <T,>(
  a: T,
  b: T,
  key: ArrayKeys<T>,
) => {
  return a[key].length < b[key].length ? 1 : -1; // Error: Property 'length' does not exist on type 'T[ArrayKeys<T>]'.
};

TS Playground
My questions:

*

*What is the reason my attempt doesn't do what I want? Is it a limitation of the compiler to understand that T[ArrayKeys<T>] will always be an array? Or is that actually unsound and I'm just not seeing why?

*Is what I'm trying to do expressible in the type system, or do I need to use runtime checks to verify that the values are actually arrays?

A: Maybe this is what you need:
const compareByKeyLength = <
  A extends Record<Key, any[]>,
  B extends Record<Key, any[]>,
  Key extends keyof A & keyof B
>
(
  a: A,
  b: B,
  key: Key,
) => {
  return a[key].length < b[key].length ? 1 : -1;
};

compareByKeyLength({a: [], b: 123}, {a: [], c: 123}, "a")

I introduce the generic type Key which is both a keyof A and keyof B. Then I specify that the inputs a and b are of the generic types A and B which both have the key Key with an array type any[].
Playground


Q: How to calculate the probability of multiple objects being next to each other? The question is:
Let $F$ be the set of all functions from $\{1..n\} \to\{1..n\}$ where $n \in \mathbb{N}.$ If all the functions in $F$ are laid out randomly in a straight line, what is the probability that at least 3 bijective functions are next to each other (touching), at least once?
I have started this partially, as (if I'm not wrong), there are $n^n$ functions in $F$ and there are $n!$ bijective ones I would assume. So the probability of a randomly selected one being bijective is $\frac{n!}{n^n}$.
Beyond that, I have no idea. Any help is appreciated.


Q: Mac OS /User folder permissions and ownership What is default /Users folder owner and group and permissions?
Yesterday I installed VirtualBox with Homebrew and had some issues with that, but after success, I got some warning in my zsh terminal with some ruby script which was saying after any command that /Users folder has to much privileges.
I have tried fix home folder permissions etc. but my /Users folder owner is my user and group is stuff. In privileges it has read for everyone and staff.
Is it ok ?

A: An old question, but:
The /Users folder should be owned by root:admin and have 755 permissions.
Each /Users/<USERNAME> folder should be owned by <USERNAME>:staff and have 700 permissions.


Q: How to style a photo gallery? I am looking for a method to design a photo gallary, I am currently using table but not sure if its a correct method to do it or not, also not sure about styling.
It has many images, upload is used to upload photos and message is used to show upload messages.
I just need to show the images and allow users to save images on the server, and show the messages, (uploaded / can not upload). I can show the images, save them and send the messages to the message section but not sure how to style it.
Another problem is that I need all images to be in the same size, as each is in different size now.
I need it to be the same on all browsers.

    upload photo btn
    message

    upload photo btn
    message

A: Semantically tables should be used for tabular data.
Check out the answer to this question for some options.
Depending on the age of the browsers you want to support, you could also consider using a flex box layout. Flex box is nice and easy to code but not fully supported in all browsers yet.

A: According to me this shouldn't be accomplished using tables, the better way to do is by using CSS3 column-count property, this way you can cut-split your content to whatever number of columns you want to, this way you don't have to use tables too..
Demo
Demo (Added -webkit support)
html, body {
    width: 100%;
    height: 100%;
}

.wrap {
    column-count: 3;
    -moz-column-count: 3;
    -webkit-column-count: 3;
}

.holder {
    border: 1px solid #f00;
}

img {
    max-width: 100%;
}

Note: column-count CSS3 property is not widely supported, but there
  are many polyfills available out, you can search online and use it for
  cross browser compatibility


Q: Positive Operator on Hilbert Space I am stuck with this problem for a long time.
If $T\geq0$ then show that $T^2\leq$||T||T.
Any help will be appreciated.

A: A positive semidefinite hermitian operator has a positive semidefinite hermitian square root, say $T = S^2$, with $S \geqslant 0$. For positive semidefinite hermitian operators, the norm is the largest eigenvalue, hence $\lVert S\rVert^2 = \lVert T\rVert$, and
$$\begin{align}
\langle T^2x,x\rangle &= \langle Tx,Tx\rangle\\
&= \langle S^2 x, S^2x\rangle\\
&= \lVert S(Sx)\rVert^2\\
&\leqslant (\lVert S\rVert\cdot \lVert Sx\rVert)^2\\
&= \lVert S\rVert^2 \langle Sx,Sx\rangle\\
&= \lVert T\rVert \langle S^2x,x\rangle\\
&= \langle \lVert T\rVert Tx,x\rangle,
\end{align}$$
which means $T^2 \leqslant \lVert T\rVert T$.

A: You can avoid the square root by noting that $(x,y)_{T}=(Tx,y)$ acts as an inner product, except that it may not be positive definite. Because of this, the Cauchy-Schwarz inequality holds:
$$
           |(x,y)_{T}|^{2} \le (x,x)_{T}(y,y)_{T} = (x,x)_{T}(Ty,y) \le (x,x)_{T}\|Ty\|\|y\| \le \|T\|(x,x)_{T}\|y\|^{2}
$$
That is,
$$
          |(Tx,y)|^{2} \le \|T\|(Tx,x)\|y\|^{2}.
$$
Letting $y=Tx$,
$$
   \|Tx\|^{4} \le \|T\|(Tx,x)\|Tx\|^{2}
$$
Whether or not $Tx=0$,
$$
     \|Tx\|^{2} \le \|T\|(Tx,x)
$$
The final result holds by noticing that $(T^{2}x,x)=\|Tx\|^{2} \le (\|T\|Tx,x)$. So $T^{2} \le \|T\|T$


Q: Unable to use DirectX.Capture library I am unable to use DirectX.Capture library because the following code from the example gave me errors:
Capture capture = new Capture(
    Filters.VideoInputDevices[0],
    Filters.AudioInputDevices[0]);

capture.Start();

capture.Stop();

An object reference is required for the non-static field, method, or
property 'DirectX.Capture.Filters.AudioInputDevices'
An object
reference is required for the non-static field, method, or property
'DirectX.Capture.Filters.VideoInputDevices'

Why? What am I doing wrong? How can I fix it?

A: The message is saying that the member AudioInputDevices and the member VideoInputDevices are not declared as static in the type DirectX.Capture.Filters, but you are using them as if they were static.
To reference a member that's not static, you need to instantiate that type, by calling the constructor (directly, or indirectly via some kind of factory method) of that type (DirectX.Capture.Filters).
In other words, you need something like this:
var filters = new DirectX.Capture.Filters(...);
var capture = new Capture(filters.VideoInputDevices[0], filters.AudioInputDevices[0]);


Q: Prevent Wine application from checking for DirectX I am trying to install an application in Wine. The program will only work on Windows 95, so I set this option in winecfg. But when I run the installer, it checks if DirectX 3.0 is installed, and however it does that checking causes Wine to crash. Can I prevent the application from doing this check?


Q: Expectation and convergent Let $X$ be a random variable, and let $A_n=\{\omega: n\leq|X(\omega)|< n+1 \}$.
How I can deduce

*

*$E(X)$ is finite iff $\sum_{n=1}^{\infty} P(|X|\geq n)$ is convergent,

*If $E(X)$ is finite then $n P(|X| \geq n) \to 0$ as $n \to \infty$.
Please hint for this question.

A: Hints: 1. Use the expression $E(|X|)= \int_{0}^\infty \mathbb{P}(|X|\geq t) \text{d} t$ which can be derived by Fubini's Theorem, and the fact that $ \mathbb{P}(|X|\geq n+1) \leq \mathbb{P}(|X|\geq t)\leq \mathbb{P}(|X|\geq n) $ when $ n+1\geq t \geq n $.

*Notice that $|X| 1_{|X|\geq n} \geq n 1_{|X|\geq n}$.


Q: Elasticsearch: Exact multiple match phrases on same field I want the following query to return results where exact phrases separated by OR match in a particular field.
{
  "query": {
    "nested": {
      "path": "positions",
      "query": {
        "bool": {
          "must": [
            {
              "query_string": {
                "default_field": "positions.companyname",
                "query": "microsoft OR gartner OR IBM"
              }
            },
            {
              "query_string": {
                "default_field": "positions.title",
                "query": "(Chief Information Security Officer) OR (Chief Digital Officer)"
              }
            }
          ]
        }
      },
      "inner_hits": {
        "highlight": {
          "fields": {
            "positions.title": {}
          }
        }
      }
    }
  }
}

The results should contain exact Chief Information Security Officer OR Chief Digital Officer,
but not Chief Digital Marketing Officer OR Chief Information Officer as it is currently being returned.
Also, the field may not necessarily have the exact phrase to be searched.
For example:
"CIO Chief Information Officer" -> FALSE
"Head at Digital - Chief Digital Officer" -> TRUE
"Former lead Chief Information Security Officer" -> TRUE
"Chief Information Officer" -> False
I guess the point I am trying to make is those phrases should always be next to each other(proximity).

A: For your use case I would suggest you to use match_phrase query inside a bool query's should clause.
Something like this should work:
GET stackoverflow/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match_phrase": {
            "text": "Chief Information Security Officer"
          }
        },
        {
          "match_phrase": {
            "text": "Chief Digital Officer"
          }
        }
      ]
    }
  }
}

A: This query would do it.
{
  "query": {
    "nested": {
      "path": "positions",
      "query": {
        "bool": {
          "must": [
            {
              "query_string": {
                "default_field": "positions.companyname",
                "query": "microsoft OR gartner OR IBM"
              }
            },
            {
              "bool": {
                "should": [
                  {
                    "match_phrase": {
                      "positions.title": "chief information security officer"
                    }
                  },
                  {
                    "match_phrase": {
                      "positions.title": "chief digital officer"
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }
  }
}

match_phrase makes sure that the exact phrase is being searched. To match multiple phrases on the same field, use bool operator with should condition.


Q: Einstein's relativity of simultaneity train/embankment thought experiment Einstein's thought experiment I'm referring to is this one:
http://www.bartleby.com/173/9.html
briefly: train/embankment experiment is where lightning strikes at either ends of the running train (points A and B) and there's an observer inside the train (call him INSD), and outside the train (call him OTSD). if the observer OTSD sees the lightning strikes to be simultaneous, the observer INSD will see that one happens after the other. detailed explanation can be found in the link above.
anyways, so i get the reasoning. the speed of light is always constant, and from the observer INSD's frame of reference, the lightning strikes happened equi-distance from him, and since lightning on the front (B) reached him before the lightning on the back (A), then the one on the front (B) must have happened first... so what's simultaneous to OTSD is not simultaneous to INSD; i get it.
now, what i'm actually confused is;
assuming lightning stroked not the train, but the embankment outside, also at the same points A and B; and left a mark where it hit.
the observer INSD will still see the lightning strike from B first before A; but this time, observer sees where B actually hit the embankment; so can see the distance it actually traveled; which should be shorter..
that's the part i'm confused about; if the lightning striked on the embankment and left a mark there, can you still make the argument that both traveled equi-distance in INSD's frame of reference?
i know i'm missing something, but i struggled alone on this problem for a full day; and i don't have anyone personally to ask this question (not in school anymore); so please be nice and teach it to me like a little kid :)

A: If we assume that the lightning strikes leave marks on both the train car, and the platform, then both observers can measure the distance independently. And yes, the OTSD observe will judge the marks to be closer together than the INSD observer.
But the key to the lightning-and-train experiment is not whether those distances are the same, but whether the distance from the front to the middle point is the same as the distance from the rear to the middle point. And note that each observer has their own middle point. The OTSD observer judges that the light does arrive at his middle point at the same time. The INSD observer judges that the light does not arrive at her middle point at the same time. That is, the INSD observer, sitting at the middle point of the train car, clearly sees the lightning strike the front of the train car before it strikes the back. The only conclusion that she can draw is that the lightning strikes were not simultaneous.

A: You are mixing up observations from the two frames of reference.
Let's say Bolt A hits the rear of the train and leaves Mark A on the adjacent platform, while Bolt B hits the front of the train and leaves Mark B on the adjacent platform.
As far as the INSD observer at the centre of the train is concerned, the bolts hit the front and rear of the train. According to INSD, the train is stationary, and it is the platform that is moving away. INSD measures distances and times relative to the train. INSD says 'I and the train have been at rest. I have been at the centre of the train. I saw Bolt B before I saw Bolt A, and each has travelled the same distance to meet me, so Bolt B happened first'.
If you ask INSD to start considering what has happened by analysing the marks on the platform, you are effectively asking INSD to put herself in the shoes of OTSD, in other words to view what has happened from the platform frame of reference, in which case she will readily appreciate that if the two bolts were seen at the same instant by OTSD, then they were simultaneous in OTSD's frame. There's no mystery to it- she can see that in her frame the two bolts travelled the same distance and were not simultaneous, while in OTSD's frame they also travelled the same distance and were simultaneous.
The point you have missed is that the two perspectives are equally valid. You cannot say that the platform perspective is 'what really happened' and that INSD needs to come round to that way of thinking

A: This paper discusses the train and embankment though experiment (TETE) in detail and answers your question:
https://arxiv.org/abs/physics/0606135

the correct relativistic analysis of Einstein’s original TETE shows
  that the ‘lightning strokes’ will be judged to be simultaneous by both
  the train and the embankment observers, in contradiction to Einstein’s
  conclusion.


Q: Which IDE should be used for Java Application development? I want to develop applications for Nokia Mobile. I googled and found that J2ME is the language in which app can be developed for the mobile phone.
Please suggest any IDE in which i can develop applications for Android, Blackberry, Nokia (platforms nokia commonly use) etc.
Is it possible to have a single IDE for all types of development described above?
I work on Microsoft.NET technology and am new to Java Development.

A: For Android I'd go with Eclipse see the following for the Android SDK and Eclipse setup

*

*Android SDK

*Eclipse Plugin for Android

*Blackberry

*Nokia S60

A: Have a look at Mobile Tools for Java. It is based on Eclipse and widely used among developers! You can add a large number of plugins to fulfill your needs if necessary.

A: I think there is two main used IDEs for Java. Eclipse and Netbeans. Since for Eclipse there is a better plugin for Android, I would recommend it if you want just use one.

A: There was an eclipse for J2ME (eclipse pulsar). But some people prefer NetBeans.
For Android, eclipse.
This question is not going to live much time, I think XD. Is the kind of 'better' question that gets closed.


Q: Displaying a confirmation message after doing a query with AJAX and PHP I am trying to call a function with Javascript, HTML, AJAX, and PHP.
I am still new to Javascript, AJAX, and PHP.
Background info: I am trying to add a new customer to my database but I am now trying to get a confirmation message on the same page without the page refreshing.
This is what I have:

Suggestions:

            <form action="return addCustomer(this.add_LN, this.add_FN, this.add_PN, this.add_DOB);">
                <input type="text" name="add_LN" id="add_LN" />

                <input type="text" name="add_FN" id="add_FN" />

                <input type="text" name="add_PN" id="add_PN" />

                <input type="text" name="add_DOB" id="add_DOB" />

                <input type="submit" name="add_Customer" id="add_Customer" value="Add Customer" />
            </form>

I get a "This link appears broken"
With:
http://127.0.0.1/cpsc471/return%20addCustomer(this.add_LN,%20this.add_FN,%20this.add_PN,%20this.add_DOB);?add_LN=ee&add_FN=123&add_PN=eee&add_DOB=eee&add_Customer=Add+Customer
in the url bar.
What am I doing wrong? :) I do not want the page to refresh. I am trying to just get the confirmation or non-confirmation to display.
Thanks again for all the help!

A: Your problem is here:
 <form action="return addCustomer(this.add_LN, this.add_FN, this.add_PN, this.add_DOB);">

You don't want the form action to be a javascript call, you need to do this onclick or something.
The arguments above by @thiefmaster and @martin are correct: using jquery is much simpler. You are right about the framework thing, but in this case you need to go and code for a lot of troubles (responses, when is there a successfull AJAX call, different browsers etc)

A: xmlhttp.onreadystatechange=function()
  {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
// put your codes here like
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

//  document.getElementById("show_label").innerHTML='text as you wish like updated enjoy';
}

}
And add a label with the id of show_label


Q: How to change the calendar table end date in power bi?
Here is my problem, I want to change the end date of my
calendar table based on what I have selected in the "Previous 12 Months Dates Table".
I used my "Previous 12 Months Dates Table" as a dropdown slicer filter and get the max date in that table and used it in my calendar table as my end date.
I tried a measure that returns the max date from my "Previous 12 Months Dates Table" and also I try to debug by displaying my measure value in the table chart and selecting a specific date in the dropdown slicer and it works fine.
But when I used that measure in my "Calendar Table" and try to debug it will return the default max date, not the date that I selected in my dropdown slicer.
Here is the behavior I wanted to achieve.
For example, if I select "EOMONTH" Jan 2022, it will return the previous 12 months' view from "EOMONTH" Jan 2022 and also it will calculate 12 months rolling average "EOMONTH" Jan 2022.
The previous 12 Months View and 12 months rolling average is working as I expected when I try to change the Calendar end date manually. that is why my only problem is how to change my calendar end date based on the selected date in the dropdown slicer.
Thanks in advance.


Q: How to resolve this deprected problem in OnActivityCreated? I am getting 'onActivityCreated(android.os.bundle)' is deprecated.
package example.com.fragmentrecycler;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A simple {@link Fragment} subclass.
 */
public class ListFrag extends Fragment {
    RecyclerView recyclerView;
    RecyclerView.Adapter myAdapter;
    RecyclerView.LayoutManager layoutManager;
    View view;

    public ListFrag() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_list, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    public void notifyDataChanged()
    {
        myAdapter.notifyDataSetChanged();
    }

}

This is that java file in which i am getting this error. This code is part of full project.I am not getting what wrong in my code.

A: onActivityCreated() is deprecated in API level 28.
There is no error shown because no error exists. Deprecated means that a newer or better method exists to handle stuff. So you need to change onActivityCreated() to onCreate(). But as I see you don't need to call this a second time if you already have a Fragment with onCreateView(). Keep your project clear and make a new .java file instead. Don't code everything in one single file.

*

*onCreate() is for Activity

*onCreateView() is for Fragment


Q: how to change the default settings for chatter email notifications In my Salesforce org, each users' default frequency for email notification for Chatter groups is set to daily and I need to change this to "on each post". This can be done individually, however I would like to be able to change this for several users in one go. Additionally, I need to change the email notification settings for certain groups to "email on each post", is that possible?

A: I think you can do this using a dataloader update on the user object, I'm pretty sure the field you want is "DefaultGroupNotificationFrequency" with the options:

*

*Email on each post

*Daily digests

*Weekly digests

*Never


Q: EventEmitter memory leak from function within socket.io handler I have a server that requires a dynamic value that's continuously updating from a spawned process. I tried to make a custom listener outside of the scope of the server because I was receiving potential memory leaks errors but I'm still receiving these messages after several connect/disconnects occur on the server. Why arn't the listeners that were added after the initial connect being removed during the disconnect event listener?
var express = require('express');
var http = require('http');
var spawn = require('child_process').spawn;
var util = require('util');
var fs = require('fs');
var EventEmitter = require('events').EventEmitter;
var sys = require('sys');

var app     = express(),
    server  = http.createServer(app),
    io      = require('socket.io').listen(server);

function Looper(req)  {
    this.req = req;
    EventEmitter.call(this);
}
sys.inherits(Looper, EventEmitter);

Looper.prototype.run = function() {
    var self = this;
    var cmd = spawn('./flow',[this.req]); // <-- script that outputs req every second
    cmd.stdout.setEncoding('utf8');
    cmd.stdout.on('data', function(data) {
        self.emit('output',data);
    });
}

Looper.prototype.output = function(callback) {
    this.on('output', function(data) {
        return callback(data.trim());
    });
}

var looper = new Looper('blah');
looper.run();

app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
    res.send(
        "<script src='/socket.io/socket.io.js'></script>\n"+
        "<script>\n"+
        "\tvar socket=io.connect('http://127.0.0.1:3000');\n"+
        "\tsocket.on('stream', function(data) {\n"+
        "\t\tconsole.log(data);\n"+
        "\t});\n"+
        "</script>\n"
    );
});
server.listen(3000);

io.sockets.on('connection', function(webSocket) {
    looper.output(function(res) {
        webSocket.emit('stream',res);
    });

    webSocket.on('disconnect', function() {
        looper.removeListener('output',looper.output); // <- not remove listener added when connection was made
    });
});

A: You add(!) an extra callback function every time you call looper.output to the event 'output'. I don't know what you want to achieve, but to get this call only once use this.once('output', ...) or move the callback setting to the object or remove the old function first...


Q: R segfaults when starting R by opening a source file My R.app (R version 3.3.2, R.app GUI 1.68 (7288) x86_64-apple-darwin13.4.0) on macOS Sierra is odd.
When I start R.app by clicking the app icon, I have no problems.
But if I start R.app by double-clicking a source file (e.g., test.R) in Finder.app or if I type open test.R in Terminal.app, I get a segfault error ("memory not mapped").
 *** caught segfault ***
address 0x18, cause 'memory not mapped'

Possible actions:
1: abort (with core dump, if enabled)
2: normal R exit
3: exit R without saving workspace
4: exit R saving workspace
>
Selection:

It is OK if R.app is already running when test.R is opened.
When R.app segfaults, I am sometimes lucky to have control and can close the app normally. But at other times, R.app halts with the spinning wheel appearing, and I have to Force-Quit the app. After I force-quit R.app, the next time I start R.app, I am permanently stuck (with R.app halting trying to open test.R as soon as I restart R.app), in which case I solve the problem by starting R from Terminal by typing /Applications/R.app/Contents/MacOS/R.
What would be the problem?


Q: Terminal Server does not map Local Drives We have a Windows 2000 Server, running Terminal Services in Application Server Mode.
When I start and RDP session to it, I can select to map my local drives to the server, but they are not available from within the RDP session.   When I connect to other servers, the drives are available.  Now the other servers are Windows 2003/2008 and are running in Administrative Mode, not Application Server Mode, so I'm not sure if either of these are the cause.
Thanks in Advance

A: That was a limitation of Windows 2000 Server.  It's been a while, but I seem to recall there is a resource kit utility called FileCopy (rdpclip).  This doesn't map the drive, but it does allow copy/paste files/folder between local and remote drives.
http://support.microsoft.com/kb/927229


Q: Compare md5 after tftp transfer Because I use the tftp command to transfer an important file, I would like to compare md5 in order to valid the transfer.
Note : The file has been already transfered in the the example below
int main(int argc, char *argv[])
{
    FILE *input_md5_fd;
    FILE *md5_fd;
    size_t md5_length;
    size_t nbr_items;
    char *input_md5 = NULL;
    char *file_md5 = NULL;
    int ret;

    chdir("/tmp");

    system("tftp -g -r INPUT_MD5 192.168.0.1");
    input_md5_fd = fopen("INPUT_MD5", "r");
    if (input_md5_fd != NULL)
    {
       fprintf(stdout,"MD5 transfered\n");
       fseek(input_md5_fd,0L,SEEK_END);
       md5_length = ftell(md5_fd);
       input_md5 = malloc(md5_length + 1);
       fseek(input_md5_fd,0L,SEEK_SET);
       nbr_items = fread(input_md5, 1, md5_length, input_md5_fd);
       input_md5[nbr_items] = 0;
       fprintf(stdout, "length = %lu B\n",md5_length);
       fprintf(stdout, "contains %s\n", input_md5);
       fclose(input_md5_fd);
    }
    else
    {
       return -1;
    }

    system("md5sum IMPORTANT_FILE > /tmp/file_md5.txt");

    md5_fd = fopen("file_md5.txt", "r");
    if (md5_fd != NULL)
    {
       file_md5 = malloc(md5_length +1);
       rewind(md5_fd);
       nbr_items = fread(file_md5, 1, md5_length, md5_fd);
       file_md5[nbr_items] = 0;
       fprintf(stdout, "contains %s\n", file_md5);
       fclose(md5_fd);
    }
    else
    {
       return -1;
    }

    printf("file_md5 = %s\n", file_md5);
    printf("input_md5 = %s\n", input_md5);
    ret = strncmp(file_md5, input_md5, md5_length);
    printf("ret = %d\n", ret);

    free(input_md5);
    free(file_md5);

}

Output :
MD5 transfered
length = 33 B
contains a95ef51ec6b1b06f61c97559ddf4868f

contains a95ef51ec6b1b06f61c97559ddf4868f
file_md5 = a95ef51ec6b1b06f61c97559ddf4868f
input_md5 = a95ef51ec6b1b06f61c97559ddf4868f

ret = 22

The input files contain :
# cat /tmp/INPUT_MD5
a95ef51ec6b1b06f61c97559ddf4868f

 # cat /tmp/file_md5
a95ef51ec6b1b06f61c97559ddf4868f  XXX_XX-XXXX-XX-DD.DDD-DD.DDD.DD.bin

X being char and D decimal values.
Why ret is not equal to 0 ? In addition, I don't know from where 34 comes from
EDIT :
CODE HAS BEEN UPDATED, problem came from md5_length definition. long type has been exchanged to size_t

A: You risk printing out and comparing garbage since you don't ensure the strings are nul terminated.
You need to do
 fread(file_md5, 1, md5_length, md5_fd);
 file_md5[md5_length] = 0;

And similar for input_md5. Or to do it properly, use the return value of fread() to add the nul terminator in the proper place, check if fread() fails, Check how much it returned.
If you also place your debug output inside quotes, it'll also be easier to spot unwanted whitespace or unprintable characters:
fprintf(stdout, "contains '%s'\n", input_md5);


Q: If $Y$ is a function of $x$ , i.e. $y=f(x)$, I am struggling with this problem. If $y=f(x)$, then if $y=3x$. Then if we divide by both sides, then $x=y/3$, and so does it mean $x$ is a function of $y$?
I think changing the order is not allowed. But I am not sure. Please help.

A: In this case, yes. You have to be careful: what you are using here is that $y=3x\color{red}\iff x=\frac y3$.
It is also true that if $y=x^3$, then $x=\sqrt[3]y$ (assuming that we are working on $\Bbb R$ here). However, it is not true that, in $\Bbb R$, we have $x=y^2\iff y=\sqrt x$. Nevertheless, this is true if we are working on $[0,\infty)$ instead. So, on $[0,\infty)$ if $y=x^2$, then $y$ is a function of $x$ and $x$ is a function of $y$ (since $x=\sqrt y$ then).


Q: ocaml mutual recursion error I am new to Ocaml and want help with recursive function defined on a recursive data type. I have defined a data type as follows
    type 'a slist = S of 'a sexp list
    and
    'a sexp = Symbol of 'a | L of 'a slist

The function(subst) I'm writing checks for a symbol a in the defined slist and substitutes it by b. For ex subst 1 10 S[ 1; 4; S[L[3; 1;]; 3];] returns S[10; 4; S[L[S[3; 10;]]; 3;]
. My code is as follows
    let rec subst a b sl = match sl with
    S s -> match s with
          [] -> []
          | p :: q -> match p with
                Symbol sym -> if sym = a then S[b] :: (**subst** a b S[q]) else
                                 S[p] :: (subst a b S[q])
                L l -> (subst a b l) :: (subst a b S[q])
    | L lis -> subst a b lis;;

I am getting the error :
This function is applied to too many arguments; Maybe you forgot a ';'
Please help

A: Your type can be defined in a simpler way, you don't need slist:
type 'a sexp = Symbol of 'a | L of 'a sexp list

Your problem is that subst a b S[q] is read as subst a b S [q], that is the function subst applied to 4 arguments. You must write subst a b (S[q]) instead.


Q: PolicyKit daemon disconnected from the bus. Error when starting services without sudo on the super user account Hopefully this will be a quick fix, but I have been having a consistent error whenever I try and start a service on my machine.
Whether it be ssh, rdp or apache2, whenever I try and launch the service using the basic command service ssh start for example I am greeted by an error message in my terminal saying the following:
PolicyKit daemon disconnected from the bus.
We are no longer a registered authentication agent.
Failed to start ssh.service: Message recipient disconnected from message bus without replying
See system logs and 'systemctl status ssh.service' for details.

Running the command with a sudo in front of it seems to fix this issue for ssh, and it seems to "work" at first for the other services on my machine. However upon trying to connect to my webserver or my remote desktop service I am simply unable to connect to them.
Also upon rebooting I am also greeted by a system program problem prompt, and I am not told any information about the error.
I am fairly new to Ubuntu so I am unsure as to what may be causing this issue. if anyone can give me advice I would greatly appreciate it.
These are the error logs given to me by the syslog file: These errors crop up every time i try to launch a service without the sudo command.
Jun 3 17:12:26 xxxspermmonkey420xxx kernel: [ 1402.059083] polkitd[5560]: segfault at 8 ip 00007f6c77c88e36 sp 00007ffc95a7a5a0 error 4 in libpolkit-backend-1.so.0.0.0[7f6c77c79000+18000]
Jun 3 17:12:26 xxxspermmonkey420xxx systemd[1]: polkitd.service: Main process exited, code=dumped, status=11/SEGV
Jun 3 17:12:26 xxxspermmonkey420xxx gnome-session[4459]: PolicyKit daemon disconnected from the bus.
Jun 3 17:12:26 xxxspermmonkey420xxx gnome-session[4459]: We are no longer a registered authentication agent.
Jun 3 17:12:26 xxxspermmonkey420xxx systemd[1]: polkitd.service: Unit entered failed state.
Jun 3 17:12:26 xxxspermmonkey420xxx systemd[1]: polkitd.service: Failed with result 'core-dump'.
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4188] error requesting auth for org.freedesktop.NetworkManager.reload: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4189] error requesting auth for org.freedesktop.NetworkManager.settings.modify.hos tname: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4190] error requesting auth for org.freedesktop.NetworkManager.settings.modify.own : Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4191] error requesting auth for org.freedesktop.NetworkManager.settings.modify.sys tem: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4191] error requesting auth for org.freedesktop.NetworkManager.wifi.share.open: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4192] error requesting auth for org.freedesktop.NetworkManager.wifi.share.protecte d: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4193] error requesting auth for org.freedesktop.NetworkManager.network-control: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4194] error requesting auth for org.freedesktop.NetworkManager.enable-disable-wimax: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4194] error requesting auth for org.freedesktop.NetworkManager.enable-disable-wwan: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4196] error requesting auth for org.freedesktop.NetworkManager.enable-disable-wifi: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4196] error requesting auth for org.freedesktop.NetworkManager.sleep-wake: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx dbus[1056]: [system] Activating via systemd: service name='org.freedesktop.PolicyKit1' unit='polkitd.service'
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4197] error requesting auth for org.freedesktop.NetworkManager.enable-disable-network: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx systemd[1]: Starting Authenticate and Authorize Users to Run Privileged Tasks...
Jun 3 17:12:26 xxxspermmonkey420xxx polkitd[5609]: started daemon version 0.105 using authority implementation `local' version `0.105'
Jun 3 17:12:26 xxxspermmonkey420xxx dbus[1056]: [system] Successfully activated service 'org.freedesktop.PolicyKit1'
Jun 3 17:12:26 xxxspermmonkey420xxx systemd[1]: Started Authenticate and Authorize Users to Run Privileged Tasks.
Jun 3 17:12:26 xxxspermmonkey420xxx gnome-session[4459]: PolicyKit daemon reconnected to bus.
Jun 3 17:12:26 xxxspermmonkey420xxx gnome-session[4459]: Attempting to re-register as an authentication agent.
Jun 3 17:12:26 xxxspermmonkey420xxx gnome-session[4459]: We are now a registered authentication agent.


Q: Teradata CASE WHEN attribute IN ( Select... from)
I have selected a bunch of IDs and I try to use CASE WHEN to get a column when the IDs which I really want to select are in the IDs I selected earlier.
But it shows Select Failed .3771:Illegal expression in WHEN clause of Case expression.
Any suggestion to get it right?
Please help.
p.s my goal is to select the IDs shown for the first time.


Q: How does changing the characteristic of a field affect irreducible factorization or proofs about irreducible factorization? Let $k$ be an algebraically closed field of characteristic 0 , and let $g(x) \in k[x]$ be a polynomial of degree $d$ which is not a square. Consider
$$
f:=y^2-g(x) \in k[x, y]
$$
Show this polynomial $f$ is irreducible in $k[x, y]$
Proof: contemplate a factorization
$$
y^2-g(x)=f=\left(a_n(x) y^n+\cdots+a_0(x)\right)\left(b_m(x) y^m+\cdots+b_0(x)\right) .
$$
Expanding the right hand side shows $m+n=2$ and that $\lambda:=a_n(x)=b_m(x)^{-1}$ are scalars. So this means if either $m=0$ or $n=0$, one of the factors on the right is a unit, and this gives a trivial factorization. So it remains to rule out the case $m=n=1$. In this case, we have:
$$
y^2-g(x)=\left(\lambda y+a_0(x)\right)\left(\lambda^{-1} y+b_0(x)\right)=y^2+\left(\lambda b_0(x)+\lambda^{-1} a_0(x)\right) y+a_0(x) b_0(x)
$$
Matching coefficients shows that: $b_0(x)=-\lambda^{-2} a_0(x)$ and therefore $g(x)=-\lambda^{-2} a_0(x)^2$. Since we assumed $g(x)$ is not a square, this is impossible! Thus the only factorizations of $f$ involve a unit, so it is irreducible, whence prime, in $k[x, y]$.
My question is whether this proof also works in the case where we change the characteristic of our field. I'm not quite sure, but if $\lambda$ equals the characteristic of our field, would we have problems?


Q: Type mismatch java.io.Serializable and GenTraversableOnce I'm trying to get a parser to take a sequence of colon-seperated words and convert them into an array.
Here's an SSCCE.
import util.parsing.combinator._

class Element {

  def getSuper() = "TODO"

}

class Comp extends RegexParsers with PackratParsers {
  lazy val element: PackratParser[Element] = (
    "foo") ^^ {
    s => new Element
  }

  lazy val list: PackratParser[Array[Element]] = (
    (element ~ ";" ~ list) |
    element ~ ";") ^^
  {
    case a ~ ";" ~ b => Array(a) ++ b
    case a ~ ";" => Array(a)
  }
}

object Compiler extends Comp {
  def main(args: Array[String]) = {
    println(parseAll(list, "foo; foo; foo;"))
  }
}

It's not working and it's not compiling, if it was I wouldn't be asking about it. This is the error message I'm getting. Is there a way to convert from Serializable to GenTraversableOnce?
~/Documents/Git/Workspace/Uncool/Scales$ scalac stov.scala
stov.scala:19: error: type mismatch;
 found   : java.io.Serializable
 required: scala.collection.GenTraversableOnce[?]
    case a ~ ";" ~ b => Array(a) ++ b
                                                    ^
one error found

A: My suspicion goes on the | combinator.
The type of (element ~ ";" ~ list) is ~[~[Element, String], Array[Element]] and the type of element ~ ";" is ~[Element, String].
Thus when applying the | combinator on these parsers, it returns a Parser[U] where U is a supertype of T ([U >: T]).
Here the type of T is ~[~[Element, String], Array[Element]] and the type of U is ~[Element, String].
So the most specific type between Array[Element] and String is Serializable.
Between ~[Element, String] and Element its Object. That's why the type of | is ~[Serializable, Object].
So when applying the map operation, you need to provide a function ~[Serializable, Object] => U where U is Array[Element] in your case since the return type of your function is PackratParser[Array[Element]].
Now the only possible match is:
case obj ~ ser => //do what you want

Now you see that the pattern you're trying to match in your map is fundamentally wrong. Even if you return an empty array (just so that it compiles), you'll see that it leads to a match error at runtime.

That said, what I suggest is first to map separately each combinator:
lazy val list: PackratParser[Array[Element]] =
    (element ~ ";" ~ list) ^^ {case a ~ ";" ~ b => Array(a) ++ b} |
    (element ~ ";") ^^ {case a ~ ";" => Array(a)}

But the pattern you are looking for is already implemented using the rep combinator (you could also take a look at repsep but you'd need to handle the last ; separately):
lazy val list: PackratParser[Array[Element]] = rep(element <~ ";") ^^ (_.toArray)


Q: how to display javascript validation message on html popup Want to display javascript validation messages inside an html popup window which would be a seperate html page.currently it is displayed on the same page from where it has been called.

 $("#getStarted").val('Try xxxx for Free');
 $('#message1').text('User ' + emailID + ' already exists.');
 $("#stRegister").val("");
 document.getElementById("stRegister").focus();
<input name="stRegister" id="stRegister" type="email" class="registerinput" placeholder="Enter your business email ID" onkeypress="$('#message1').text('');">

A: var window = window.open(url, windowName, [windowFeatures]);  moidify the dom on the window object.

A: Not sure if you can do it in a separate window. However, for validation you can use the window.confirm function natively build into the browsers. Here is an example:

// window.confirm returns a boolean based on the user action
let validate = window.confirm('Do you want to continue?');

if (validate) {
  console.log('validated');
} else {
  console.log('not validated');
}

A: You can use in your script something like:
window.alert("what you want here");


Q: Can we use class transitions in jQuery like with CSS3? Do any of you know the answer to the following problem. It's driving me crazy that I cannot find a solution.
I want to animate in jQuery by adding/replacing a class and transitioning between the two, NOT by using inline styling.
This is exactly how CSS3 transition works, and its really great and allows for quick prototyping. But I want to do it in jQuery because I want it to be normalised across all browsers.
I've used jQuery animate for a long time, but I've only used it to add inline-styling. This gets really messy to manage and means I can't have the end result written in CSS and separate the presentation layer from the logic.
Consider the following example. In CSS3 if I want to animate a div height by changing the height of a div I can do this:

*

*A div has a class .object which has an initial height of 100px.

*An event runs, and the div now has the classes .object and .active.

*With the .active class, the CSS now sets the height to 150px

*Using CSS3 transition, I can allow a smooth transition between the two over 2 seconds with easing.

If i want to do the same thing in jQuery:

*

*A div has a class .object which has an initial height of 100px.

*An event runs, and I use .animate to animate the height of the object to 150px

*As a result of this, the CSS now sets the height to 150px using inline styling

*Using parameters I can set the speed in ms with easing.

You may be aware of jQuery UI which allows transition on toggleClass and switchClass:
http://jqueryui.com/demos/toggleClass/
However, annoyingly it won't work for the example above because it only works if the initial class has no specific height set. To test this, inspect the element in the demo and give it a height and watch the demo break.
Hopefully someone can help me with this

A: You could try DOM Mutation Events, which are dispatched eg. when a property of an element is changed.
There are plugins for jQuery, which mimes the behavior of event mutation (although I haven't tried any of those).
But feel free to google about mutation events in jQuery and that should probably help you.

A: You can do it with http://jqueryui.com/demos/switchClass/
(i made a similar question few weeks a go can a .classA styles to .classB styles be animated easly? )


Q: Where to find the size of SQL Server data types I am trying to calculate the size of my database. I will have a table with 3 columns (id, int, money) I will have 26 million rows with all columns being occupied. How big will my database be? Also, where can I find the size of all SQL Server data types?

A: T-SQL has a function for that: DATALENGTH for all SQL Server versions.
Example:
DECLARE @lat DECIMAL(10, 7) = 3.14151415141514151415;

SELECT @lat, DATALENGTH(@lat);

Result:
3.1415142 and 5 (because DECIMAL(10,7) uses 5 bytes to be stored).
Documentation: https://learn.microsoft.com/en-us/sql/t-sql/functions/datalength-transact-sql?view=sql-server-ver15
For example, I have a table called Applications with these columns: (id VARCHAR(32), debug BIT, connectionString VARCHAR(2048), firebaseKey VARCHAR(4096)). As we know, VARCHAR doesn't allocate all the space (just what you need, so 'A' is 1 byte in VARCHAR).
These queries:
SELECT
  SUM(DATALENGTH(id)) AS idSize,
  SUM(DATALENGTH(debug)) AS debugSize,
  SUM(DATALENGTH(connectionString)) AS connectionStringSize,
  SUM(DATALENGTH(firebaseKey)) AS firebaseKeySize
FROM Applications;

SELECT
  SUM(
    DATALENGTH(id) +
    DATALENGTH(debug) +
    DATALENGTH(connectionString) +
    DATALENGTH(firebaseKey)
  ) AS totalSize
FROM Applications;

will return my data size (in my case, with my rows, is 8, 2, 366, 4698 (total: 5074). There are 2 rows in that table.
Notice that this does NOT represent the total size of my database (there are pages, descriptors, indexes, etc. involved.)*
MSSQL has internal stored procedures to tell you the exactly size of your database in disk:

*

*EXEC sp_spaceused; for all database;

*EXEC sp_spaceused N'schema.TableName'; for a specific table;

*EXEC sp_helpdb N'DatabaseName'; if you want details from each file.

A: Your can use below query :
SELECT * FROM sys.types

result of above query is below :
name                 system_type_id user_type_id schema_id principal_id max_length precision scale collation_name    is_nullable is_user_defined is_assembly_type default_object_id rule_object_id is_table_type
-------------------- -------------- ------------ --------- ------------ ---------- --------- ----- ----------------- ----------- --------------- ---------------- ----------------- -------------- -------------
image                34             34           4         NULL         16         0         0     NULL              1           0               0                0                 0              0
text                 35             35           4         NULL         16         0         0     Persian_100_CI_AI 1           0               0                0                 0              0
uniqueidentifier     36             36           4         NULL         16         0         0     NULL              1           0               0                0                 0              0
date                 40             40           4         NULL         3          10        0     NULL              1           0               0                0                 0              0
time                 41             41           4         NULL         5          16        7     NULL              1           0               0                0                 0              0
datetime2            42             42           4         NULL         8          27        7     NULL              1           0               0                0                 0              0
datetimeoffset       43             43           4         NULL         10         34        7     NULL              1           0               0                0                 0              0
tinyint              48             48           4         NULL         1          3         0     NULL              1           0               0                0                 0              0
smallint             52             52           4         NULL         2          5         0     NULL              1           0               0                0                 0              0
int                  56             56           4         NULL         4          10        0     NULL              1           0               0                0                 0              0
smalldatetime        58             58           4         NULL         4          16        0     NULL              1           0               0                0                 0              0
real                 59             59           4         NULL         4          24        0     NULL              1           0               0                0                 0              0
money                60             60           4         NULL         8          19        4     NULL              1           0               0                0                 0              0
datetime             61             61           4         NULL         8          23        3     NULL              1           0               0                0                 0              0
float                62             62           4         NULL         8          53        0     NULL              1           0               0                0                 0              0
sql_variant          98             98           4         NULL         8016       0         0     NULL              1           0               0                0                 0              0
ntext                99             99           4         NULL         16         0         0     Persian_100_CI_AI 1           0               0                0                 0              0
bit                  104            104          4         NULL         1          1         0     NULL              1           0               0                0                 0              0
decimal              106            106          4         NULL         17         38        38    NULL              1           0               0                0                 0              0
numeric              108            108          4         NULL         17         38        38    NULL              1           0               0                0                 0              0
smallmoney           122            122          4         NULL         4          10        4     NULL              1           0               0                0                 0              0
bigint               127            127          4         NULL         8          19        0     NULL              1           0               0                0                 0              0
hierarchyid          240            128          4         NULL         892        0         0     NULL              1           0               1                0                 0              0
geometry             240            129          4         NULL         -1         0         0     NULL              1           0               1                0                 0              0
geography            240            130          4         NULL         -1         0         0     NULL              1           0               1                0                 0              0
varbinary            165            165          4         NULL         8000       0         0     NULL              1           0               0                0                 0              0
varchar              167            167          4         NULL         8000       0         0     Persian_100_CI_AI 1           0               0                0                 0              0
binary               173            173          4         NULL         8000       0         0     NULL              1           0               0                0                 0              0
char                 175            175          4         NULL         8000       0         0     Persian_100_CI_AI 1           0               0                0                 0              0
timestamp            189            189          4         NULL         8          0         0     NULL              0           0               0                0                 0              0
nvarchar             231            231          4         NULL         8000       0         0     Persian_100_CI_AI 1           0               0                0                 0              0
nchar                239            239          4         NULL         8000       0         0     Persian_100_CI_AI 1           0               0                0                 0              0
xml                  241            241          4         NULL         -1         0         0     NULL              1           0               0                0                 0              0
sysname              231            256          4         NULL         256        0         0     Persian_100_CI_AI 0           0               0                0                 0              0
CalculatedCreditInfo 243            257          9         NULL         -1         0         0     NULL              0           1               0                0                 0              1
udt_QoutaDetail      243            258          21        NULL         -1         0         0     NULL              0           1               0                0                 0              1
BeforeUpdate         243            259          22        NULL         -1         0         0     NULL              0           1               0                0                 0              1
udt_StoreInventory   243            260          26        NULL         -1         0         0     NULL              0           1               0                0                 0              1
udt_WKFHistory       243            261          32        NULL         -1         0         0     NULL              0           1               0                0                 0              1
IDTable              243            262          1         NULL         -1         0         0     NULL

you can use max_length for size of each data type.

A: http://msdn.microsoft.com/en-us/library/ms187752.aspx
Money : 8 bytes
int : 4 bytes
id  - depends on what you mean.

A: If the table specified in the where clause contains a nvarchar, this query will give you how many characters there are for that column correctly!
This detects if the column is "wide" and essentially divides by 2. More broad than just nvarchar.
SELECT c.name, (CASE WHEN LEFT(ts.name, 1) = 'n' AND ts.[precision] = 0 AND ts.[scale] = 0 THEN c.max_length / ts.[bytes] ELSE c.max_length END) AS [length]
FROM sys.columns AS c
    INNER JOIN sys.tables AS t
        ON t.object_id = c.object_ID
    INNER JOIN
    (
        SELECT *, (CASE WHEN [bits] = -1 THEN -1 ELSE ([bits] + 7) / 8 END) AS [bytes]
        FROM (
            SELECT *, (CASE WHEN max_length >= 256 THEN (CASE WHEN LEFT(name, 1) = 'n' AND [precision] = 0 AND [scale] = 0 THEN 16 ELSE 8 END) ELSE max_length END) AS [bits]
            FROM sys.types AS iits
        ) AS its
    ) AS ts
        ON ts.user_type_id = c.user_type_id
WHERE t.name LIKE 'tb_tablename' -- LIKE is case insensitive

Of course, you can just divide max_length on sys.columns by 2 if you know the column is an nvarchar. This is more for discovering table schema in a way that seems better for if new sql data types are introduced in the future. And you so-choose to upgrade to it. Pretty small edge case.

Please edit and correct this answer if you find an edge case where
  bytes and bits are incorrect.

Details:
-- ([bits] + 7) / 8 means round up
--
-- Proof:
--   o  (1 bit + 7 = 8) / 8 = 1 byte used
--   o  ((8 + 8 + 1 = 17 bytes) + 7 = 24) / 8 = 3 byes used
--   o  ((8 + 8 + 7 = 23 bytes) + 7 = 30) / 8 = 3.75 = integer division removes decimal = 3
SELECT *, (CASE WHEN [bits] = -1 THEN -1 ELSE ([bits] + 7) / 8 END) AS [bytes]
FROM (
    SELECT *, (CASE WHEN max_length >= 256 THEN (CASE WHEN LEFT(name, 1) = 'n' AND [precision] = 0 AND [scale] = 0 THEN 16 ELSE 8 END) ELSE max_length END) AS [bits]
    FROM sys.types AS its
) AS ts

If someone knows that SQL Server stores the bit and byte sizes for each data type. Or a better way to get sys.columns size, please leave a comment!


Q: Series Summation: $\sum\limits_{k=1}^{N-1}\frac{1}{z-w_k}$ where $w_k=e^{\frac{2\pi i k}{N}}$ I have the series
$$\sum_{k=1}^{N-1}\frac{1}{1-w_k} $$ where $w_k=e^{\frac{2\pi i k}{N}}$, how can I find the summation of this , another question related to this sum
$$\sum_{k=1}^{N-1}\frac{1}{z-w_k}   $$

A: Let $P(z)=z^{N}-1$. Then $$P(z)=\prod_{k=0}^{N-1}(z-w_{k})$$ where $w_{0}=1$.
From here, it is easy to check that
$$
\sum_{k=0}^{N-1}\frac{1}{z-w_{k}}=\frac{P^{\prime}(z)}{P(z)}%
$$
hence
$$
\sum_{k=1}^{N-1}\frac{1}{z-w_{k}}=\frac{P^{\prime}(z)}{P(z)}-\frac{1}{z-1}=\frac{Nz^{N-1}}{z^{N}-1}-\frac{1}{z-1}=\frac{(N-1)z^{N}-Nz^{N-1}+1}{(z^{N}-1)(z-1)}\text{.}
$$
In particular, for $z=1$:
$$
S:=\sum_{k=1}^{N-1}\frac{1}{1-w_{k}}=\lim_{z\rightarrow1}\frac{(N-1)z^{N}-Nz^{N-1}+1}{(z^{N}-1)(z-1)}.
$$
In order to compute the limit, we write is as a limit at $0$, i.e., let
$z=w+1$, $w\rightarrow0$, hence
$$
S=\lim_{w\rightarrow0}\frac{(N-1)(w+1)^{N}-N(w+1)^{N-1}+1}{w((w+1)^{N}-1)}.
$$
Next, recall that
$$
\lim_{w\rightarrow0}\frac{(w+1)^{N}-1}{w}=N
$$
hence
$$
S=\frac{1}{N}\cdot\lim_{w\rightarrow0}\frac{(N-1)(w+1)^{N}-N(w+1)^{N-1}+1}{w^{2}}.
$$
The last step is to apply l'Hopital's rule, hence
\begin{align*}
S  & =\frac{1}{N}\cdot\lim_{w\rightarrow0}\frac{\left(  (N-1)(w+1)^{N}-N(w+1)^{N-1}+1\right)  ^{\prime}}{\left(  w^{2}\right)  ^{\prime}}=\frac{1}{N}\cdot\lim
_{w\rightarrow0}\frac{N(N-1)(w+1)^{N-2}w}{2w}\\
& =\frac{1}{N}\cdot\lim_{w\rightarrow0}\frac{N(N-1)}{2}(w+1)^{N-2}=\frac{N-1}{2}.
\end{align*}

A: $$\frac{1}{1-w^{r}}+\frac{1}{1-w^{n-r}}=\frac{2-w^{r}-w^{n-r}}{2-w^{r}-w^{n-r}}=1$$ where $w=e^{i2\pi/n}$
If you continue cancelling in pairs the sum will turn out to be = $\dfrac{N-1}{2}$
In case you have a middle term ,the term = $\dfrac{1}{1-e^{i\pi/2}}=\dfrac{1}{2}$

A: The answer for the first sum is $$\sum_{k=1}^{N-1}\frac{1}{1-w_k}=\frac{N-1}{2}$$
And for the second:
$$\sum_{k=1}^{N-1}\frac{1}{z-w_k} = \sum_{k=0}^{N-1}\frac{1}{z-w_k}- \frac{1}{z-1}= \frac{N z^{N-1}}{z^N-1} -\frac{1}{z-1}$$
I believe series expansion in $w_k$, sum over $k$ and then summing back the series wll give you the above results.


Q: Why is my java animation taking up my entire CPU I made a program to display interference patterns for light waves. I did this by using the paint method on a JPanel to draw 2 sources and then drawing concentric circles around them. This would be double slit interference, so I allowed one of the sources to move around to experiment with the slit width.
The problem is that when I run this, my computer says it is using 80% of my CPU! There's really not much to it. Circle in the middle, circles around it, and it moves. My code follows.
main class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class main {
static final int UP = -1;
static final int DOWN = 1;
static final int RIGHT = 1;
static final int LEFT = -1;
static final int NOMOVEMENT = 0;

static int verticalMovement = NOMOVEMENT;
static int horizontalMovement = NOMOVEMENT;
public static void main(String[] args) {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

    Point s1 = new Point((int)(screenSize.getWidth()/3), 50);
    Point s2 = new Point((int)(2*screenSize.getWidth()/3), 50);

    JFrame frame = new JFrame("Physics Frame");
    frame.setPreferredSize(screenSize);

    PhysicsPane pane = new PhysicsPane(screenSize, 15, s1, s2);
    pane.setPreferredSize(screenSize);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(pane);
    frame.pack();

    Timer time = new Timer(1000 / 20, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            switch (verticalMovement){
                case UP:
                    s2.changeY(UP);
                    break;
                case DOWN:
                    s2.changeY(DOWN);
                    break;
                default:
                    break;
            }
            switch (horizontalMovement){
                case RIGHT:
                    s2.changeX(RIGHT);
                    break;
                case LEFT:
                    s2.changeX(LEFT);
                    break;
                default:
                    break;
            }
            pane.repaint();
        }
    });

    frame.addKeyListener(new KeyListener() {
        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode()==37){
                horizontalMovement = LEFT;
            } else if (e.getKeyCode()==38){
                verticalMovement = UP;
            } else if (e.getKeyCode()==39){
                horizontalMovement = RIGHT;
            } else if (e.getKeyCode()==40){
                verticalMovement = DOWN;
            }

            if(e.getKeyChar()=='a'){
                pane.setWaveLength(2);
            }
            if(e.getKeyChar()=='s'){
                pane.setWaveLength(-2);
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {
            switch (e.getKeyCode()){
                case 37:
                    horizontalMovement = NOMOVEMENT;
                    break;
                case 38:
                    verticalMovement = NOMOVEMENT;
                    break;
                case 39:
                    horizontalMovement = NOMOVEMENT;
                    break;
                case 40:
                    verticalMovement = NOMOVEMENT;
                    break;
            }
        }
    });
    frame.setVisible(true);
    time.start();

}
}

Panel class. If there's an inefficiency with the drawing method, it would be here.
import javax.swing.*;
import java.awt.*;

public class PhysicsPane extends JPanel {
private Dimension size;
private Point[] pointArray = new Point[2];
private double waveLength;
public PhysicsPane(Dimension size, double wavelength, Point source1, Point source2) {
    this.size = size;
    pointArray[0] = source1;
    pointArray[1] = source2;
    setPreferredSize(size);
    this.waveLength = wavelength;
}

@Override
public void paintComponent(Graphics g){
    for (int i = 0; i < 2; i++) {
        g.setColor(Color.black);
        double x = this.pointArray[i].getX();
        double y = this.pointArray[i].getY();
        g.fillOval((int)x, (int)y, 2, 2);
        for (int j = (int)waveLength; j < 1500; j+=waveLength) {
            g.setColor(Color.red);
            g.drawOval((int)x-(j/2+1), (int)y-(j/2+1), 2 + j, 2 + j);
        }
    }
}

public void setWaveLength(double increment){
    this.waveLength+=increment;
}
}

Point Class: Really just puts x and y coordinates into one construct. Not important particularly
public class Point {
private double x;
private double y;

public Point(double x, double y) {
    this.x = x;
    this.y = y;
}

public double getX() {
    return x;
}

public void setX(double x) {
    this.x = x;
}

public double getY() {
    return y;
}

public void setY(double y) {
    this.y = y;
}

public void changeX(double dX){
    this.x+=dX;
}

public void changeY(double dY){
    this.y+=dY;
}
}

So what is wrong with my program? Why is such a simple animation consuming so much of my processor?
UPDATED CODE SECTION:
@Override
public void paintComponent(Graphics g){
    BufferedImage bi = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
    Graphics graphics = bi.getGraphics();
    for (int i = 0; i < 2; i++) {
        graphics.setColor(Color.black);
        double x = this.pointArray[i].getX();
        double y = this.pointArray[i].getY();
        graphics.fillOval((int)x, (int)y, 2, 2);
        for (int j = (int)waveLength; j < 1500; j+=waveLength) {
            graphics.setColor(Color.red);
            graphics.drawOval((int)x-(j/2+1), (int)y-(j/2+1), 2 + j, 2 + j);
        }
    }
    g.drawImage(bi, 0, 0, new ImageObserver() {
        @Override
        public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
            return false;
        }
    });
}

A: The improvement that I recommend is removal of unnecessary tasks being performed, notably how your code updates the pane being drawn on, even when there aren't changes.
The following update reduced CPU usage from 12% to 0% (static frame):
Timer time = new Timer(1000 / 20, new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {

        boolean refresh = false;

        switch (verticalMovement) {
        case UP:
            s2.changeY(UP);
            refresh = true;
            break;
        case DOWN:
            s2.changeY(DOWN);
            refresh = true;
            break;
        default:
            break;
        }

        switch (horizontalMovement) {
        case RIGHT:
            s2.changeX(RIGHT);
            refresh = true;
            break;
        case LEFT:
            s2.changeX(LEFT);
            refresh = true;
            break;
        default:
            break;
        }

        if (refresh == true) {
            pane.repaint();
        }
    }
});


Q: Use RankX function to calculate date rank per Fiscal Year per Entity ID I would like to use the RankX function (to use the Dense feature for ties) in order to rank the dates in a table per two columns: Fiscal Year and Entity ID.
(I guess it may be easier to concatenate the two columns and just sort by that but I'm having issues with my formula still)
Below is my sample data:

My invalid dax formula which returns all 1's is:
Fiscal Purchase Index =
VAR a = 'Purchases'[Purchase_Date]
VAR b = 'Purchases'[Entity_ID]
var c = 'Purchases'[FISCAL_YEAR]
RETURN
    CALCULATE (
        RANKX ('Purchases', a,,1,Dense ),
        FILTER (all('Purchases'),
            'Purchases'[Entity_ID] = b &&
            'Purchases'[FISCAL_YEAR] = c
        )
    )

Any help in fixing the rank formula would be very much appreciated.
Thank you

A: Use the following dax formula:
Fiscal Purchase Index =

VAR __entity = 'Purchases'[Entity ID]
var __year = 'Purchases'[FISCAL YEAR]
var __table = FILTER ( all('Purchases'), 'Purchases'[Entity ID] = __entity && 'Purchases'[FISCAL YEAR] = __year )

var __result =
RANKX(__table, Purchases[Date] ,, 1, Dense)

RETURN __result

Hope it helps.


Q: Rails ActiveRecord: List parent category and sub category from self-join table I want to return a list like the one below. All category records which have a parent. Displaying parent name and category name.
I'm using a self-join (self-associated?) model 'category' in which categories can be parents of other categories.
It works with the pure SQL just below, but how can I do it with ActiveRecord?
> sql="select p.name parent, s.name category from categories s join categories p on s.parent_id=p.id"
> ActiveRecord::Base.connection.execute(sql)

   (0.4ms)  select p.name parent, s.name category from categories s join categories p on s.parent_id=p.id
=>
[{"parent"=>"Income", "category"=>"Available next month"},
 {"parent"=>"Income", "category"=>"Available this month"},
 {"parent"=>"1. Everyday Expenses", "category"=>"Fuel"},
 {"parent"=>"1. Everyday Expenses", "category"=>"Groceries"},
 {"parent"=>"1. Everyday Expenses", "category"=>"Restaurants"},
 {"parent"=>"1. Everyday Expenses", "category"=>"Entertainment"},
 {"parent"=>"1. Everyday Expenses", "category"=>"Household & Cleaning"},
 {"parent"=>"1. Everyday Expenses", "category"=>"Clothing"},
 {"parent"=>"1. Everyday Expenses", "category"=>"MISC"},
 {"parent"=>"2. Monthly Expenses", "category"=>"Phone"},
 {"parent"=>"2. Monthly Expenses", "category"=>"Rent"},
 {"parent"=>"2. Monthly Expenses", "category"=>"Internet & Utilities"},
 {"parent"=>"2. Monthly Expenses", "category"=>"News Subscriptions"},
 {"parent"=>"2. Monthly Expenses", "category"=>"Car Registration"}]

I've been trying several queries. This appears to replicate my SQL closest, but returns nothing usable.
> Category.select('parents_categories.name as parent, categories.name as category').joins(:parent)

  Category Load (0.7ms)  SELECT parents_categories.name as parent, categories.name as category FROM "categories" INNER JOIN "categories" "parents_categories" ON "parents_categories"."id" = "categories"."parent_id"
=>
[#<Category:0x000055fefee12af0 id: nil>,
 #<Category:0x000055fefee12a28 id: nil>,
 #<Category:0x000055fefee12960 id: nil>,
 #<Category:0x000055fefee12898 id: nil>,
...

This was my other try, but I'm struggling with the syntax, and it just ignores the :parent['name'] phrase
> Category.select(:parent['name'],:name).joins(:parent).first

  Category Load (0.2ms)  SELECT "categories"."name" FROM "categories" INNER JOIN "categories" "parents_categories" ON "parents_categories"."id" = "categories"."parent_id" ORDER BY "categories"."id" ASC LIMIT ?  [["LIMIT", 1]]
=> #<Category:0x000055feff38cd78 id: nil, name: "Available next month">

Schema
  create_table "categories", force: :cascade do |t|
    t.string "name", null: false
    t.integer "parent_id"
    ...
  end

Model
class Category < ApplicationRecord
  belongs_to :parent, class_name: "Category", optional: true
  has_many :subcategories, class_name: "Category", foreign_key: :parent_id
...
end

I can't find a matching example from the Rails guide here: https://guides.rubyonrails.org/active_record_querying.html
And stackoverflow questions like this (Unable to join self-joins tables in Rails) are close but not getting me across the finish line
UPDATE: I've found a convoluted answer from this website: https://medium.com/@swapnilggourshete/rails-includes-vs-joins-9bf3a8ada00
> c = Category.where.not(parent: nil).includes(:parent)
> c_data = [ ]
> c.each do |c|
      c_data << {
         parent: c.parent.name,
         category: c.name
      }
  end

[{:parent=>"Income", :category=>"Available next month"},
 {:parent=>"Income", :category=>"Available this month"},
 {:parent=>"1. Everyday Expenses", :category=>"Fuel"},
 {:parent=>"1. Everyday Expenses", :category=>"Groceries"},
 {:parent=>"1. Everyday Expenses", :category=>"Restaurants"},...]

But there must be a better way.

A: You are really close my friend. Just a little tweak and you will get what you are looking for
Category.select('parents_categories.name as parent_category, categories.name as category').joins(:parent).as_json(except: :id)

Note if you have belongs_to :parent, parent cannot be named as selected key so we need to change it to parent_category


Q: Rails initial page load extremely slow I've got a rails app in development mode (3.1.12 ruby 1.9.2) running on a windows server via fastcgi (with heliconzoo).
If i wait a certain amount of time from page load to page load, it takes 4-6 seconds to load the page. Afterwards it's loading with normal speed independent on which computer and in every browser.
Does the app/service shutdown if nobody visits the page within a while?
What can I do to prevent this behaviour?
e: For the first entry of today the development.log says it took 500ms to load the page which is 10 times faster...But it took 5s to load actually...


Q: Core Data table to NSArray I have the following Array which retrieved from the Core Data  :
NSArray *dataArray = [context executeFetchRequest:request error:&error];

so I wrote this code to get each row data individually to send it to REST API:
for (NSString *str in dataArray) {

        NSString *name =[dataArray valueForKey:@"name"];
        NSString *dob = [dataArray valueForKey:@"dob"];
        int gender =[[dataArray valueForKey:@"gender"]integerValue];
        NSString *childId =[dataArray valueForKey:@"id"];

         int response = [network sendName:name withDateOfBirth:dob andGender:gender forID:childId];

        if (response == 200) {
            // [self performSelectorOnMainThread:@selector(postSuccess) withObject:nil waitUntilDone:YES];
            NSLog(@"Success");

        }
    }

but it's not working, because I couldn't know how data is stored in each index in the array!!
Please help, and if I am not doing this correctly please tell me a better way to do it.
Thanks.

A: NSString *name =[dataArray valueForKey:@"name"];

This doesn't do what you think it'll do. valueForKey:, when sent to an array, returns an array of the values corresponding to the given key for all the items in the array. So, that line will assign an array of the "name" values for all the items in dataArray despite the fact that you declared name as a NSString. Same goes for the subsequent lines.
What you probably want instead is:
for (NSManagedObject *item in dataArray) {
    NSString *name = [item valueForKey:@"name"];
    ...

Better, if you have a NSManagedObject subclass -- let's call it Person representing the entity you're requesting, you can say:
for (Person *person in dataArray) {
    NSString *name = person.name;
    ...

which leads to an even simpler version:
for (Person *person in dataArray) {
    int response = [network sendName:person.name
                     withDateOfBirth:person.dob
                           andGender:person.gender
                               forID:person.id];

although I'd change the name of that method to leave out the conjunctions and prepositions. -sendName:dateOfBirth:gender:id: is enough, you don't need the "with", "and", and "for."


Q: actionListener associated with an h:commandLink/h:commandButton is not invoked I have a 2 forms that contain 4 buttons with each button having a an actionListener property set to call a single method in a request scoped bean. This method checks to determine what button is performing the action and then does a few things based on that information (Create, Read, Update, or Delete). The problem is that, out of these four buttons, three work. The last (update) button isn't calling the action.
This question helped a little bit as, after reading it, I managed to get the fourth button to work once (breakpoints and variable watching determined that) -- but then I stopped the program, made a small change because the page failed to not render a portion of the page (dependent of the 'editing' variable), watched it fail again, and then forgot what I did to make it work. I've determined that the problem is not nested forms, that I'm importing the right event class, that there are no validation errors, that there are no iterating tags, that the buttons are rendering and are not disabled, or any of the other points mentioned in @BalusC 's answer to that question except one -- when I use a <h:commandLink>, JS is rendered on the page that returns false although changing to a <h:commandButton> still fails to invoke the actionListener. But what's weird is that the one time is worked and the action was invoked I was using a <h:commandLink>.
Does anyone see what I'm doing wrong?
Form 1 (create; works):

    <h:head></h:head>

    <h:body>
        <ui:composition template="../../template.xhtml">
            <ui:define name="top">
                New Location View
            </ui:define>

            <ui:define name="left"></ui:define>

            <ui:define name="content">
                <f:view>
                    <h:form>

<h:outputText value="Create a Location"/>

                        <h:panelGrid columns="2">
                            <h:outputLabel for="locationName" value="Name:"/>
                            <h:inputText id="locationName" value="#{locationBean.locationName}"/>
                            <h:outputLabel for="locationDesc" value="Description:"/>
                            <h:inputText id="locationDesc" value="#{locationBean.locationDescription}"/>
                            <h:commandButton value="Add Location" id="createact" actionListener="#{locationBean.doAction}"/>
                        </h:panelGrid>
                    </h:form>
                </f:view>
            </ui:define>
        </ui:composition>
    </h:body>

Form 2 (Read (a details button clicked from a listing page which redirects to this one) works, Update; doesn't work, Delete; works):

    <h:head>

    </h:head>
    <h:body>
        <ui:composition template="../../../template.xhtml">
            <ui:define name="top">
                Location Details View
            </ui:define>

            <ui:define name="left">

            </ui:define>

            <ui:define name="content">
                <c:set var="location" value="#{locationBean.l}"/>

                <h:form>
                    <h:panelGrid columns="2" rendered="#{not locationBean.editing}" >
                        <h:outputLabel value="Name:"/>
                        <h:outputText  id="nameout" value="#{location.locationname}"/>
                        <h:outputLabel value="Description:" />
                        <h:outputText  id="descout" value="#{location.description}"/>
                        <h:commandButton id="delact"  actionListener="#{locationBean.doAction}" value="Delete"/>
                        <h:commandButton id="editact"  actionListener="#{locationBean.doAction}" value="Edit"/>
                    </h:panelGrid>
                    <h:panelGrid columns="2" rendered="#{locationBean.editing}">
                        <h:outputLabel value="Name:" />
                        <h:inputText   id="namein" value="#{location.locationname}" required="true" requiredMessage="There must be a name."/>
                        <h:outputLabel value="Description:" />
                        <h:inputText  id="descin" value="#{location.description}" required="true" requiredMessage="There must be a description."/>
                        <h:commandLink id="cancelact" actionListener="#{locationBean.doAction}" value="Cancel"/>
                        <h:commandLink id="saveact" actionListener="#{locationBean.doAction}" value="Save"/>
                    </h:panelGrid>
                    <h:inputHidden value="#{location.identifier}" id="viewid" />
                    <c:catch var="error">
                        <h:outputLabel value="#{error.message}" />
                    </c:catch>
                </h:form>
                <h:outputText value="will also show location hours and days open and employees at this location."/>
            </ui:define>
        </ui:composition>
    </h:body>

doAction method (called from all four buttons):
public void doAction(ActionEvent e) {
    String callingID = e.getComponent().getId();
    try {
        if (callingID.isEmpty()) {//id is empty
            FacesContext.getCurrentInstance().addMessage(callingID, new FacesMessage(
                    "What are you doing wrong? Actions must have a valid id.",
                    "Empty Strings are not a valid id."));
        } else if (callingID.endsWith("delact")) {//component id is delete
            this.l = lsb.getLocationToView();
            lsb.delete(l);
            FacesContext.getCurrentInstance().getExternalContext().redirect("/EmployeeScheduler-war/webpages/view/locations.xhtml");
        } else if (callingID.endsWith("editact")) {//component id is edit
            this.editing = true;
            this.l = lsb.getLocationToView();
        } else if (callingID.endsWith("saveact")) {//component id is save, usually after an edit action
            this.editing = false;
            lsb.edit(l);
        } else if (callingID.endsWith("cancelact")) {//component id is cancel. usuallys after edit action
            this.editing = false;
        } else if (callingID.endsWith("createact")) {//component id is create. always create a new location
            FacesContext.getCurrentInstance().getExternalContext().redirect("/EmployeeScheduler-war/webpages/view/locations.xhtml");
            lsb.create(l);
        } else if (callingID.endsWith("detailsact")) {//component id is details. alwas from list view
            this.l = lsb.getLocationToView();
        } else {
            FacesContext.getCurrentInstance().addMessage(callingID, new FacesMessage(
                    "What are you doing wrong? Actions must have a valid id.",
                    callingID + " is not not valid."));
        }
        //catch any failures
    } catch (RollbackFailureException ex) {
        FacesContext.getCurrentInstance().addMessage(callingID, new FacesMessage(
                "An error occured trying to rollback the deletion of the location: " + ex.getMessage(),
                "Details: " + ex.getCause().getMessage()));
    } catch (Exception ex) {
        FacesContext.getCurrentInstance().addMessage(callingID, new FacesMessage(
                "An error occured trying to delete the location: " + ex.getMessage(),
                "Details: " + (ex.getCause() == null ? "none" : ex.getCause().getMessage())));
    }
}

Template file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Employee Scheduler</title>
        <link href="resources/styles/main.css" rel="stylesheet" type="text/css"/>
        <ui:insert name="head"/>
    </h:head>

    <h:body style="margin-right:15%;margin-left:15%">

                    Welcome to the BMS Employee Scheduler

                    <h:form id="loginForm">
                        <h:panelGrid columns="2" cellspacing="2px" style="text-align: right">
                            <h:outputLabel for="usernameInput">
                                Username
                            </h:outputLabel>
                            <h:inputText disabled="#{login.loginDisabled}" id="usernameInput" value="#{login.username}"
                                         required="true" />
                            <h:outputLabel for="passwordInput">
                                Password
                            </h:outputLabel>
                            <h:inputSecret disabled="#{login.loginDisabled}" id="passwordInput" value="#{login.password}"
                                           required="true" />
                        <h:commandButton disabled="#{login.loginDisabled}" value="Login" action="#{login.login}" style="float: right"/>
                        </h:panelGrid>
                    </h:form>

                <ui:insert name="top"/>

                    <h:panelGrid columns="1" style="text-align: left">
                        <h:outputLink value="./index.xhtml" >Home</h:outputLink>
                        <h:outputLink value="./webpages/view/users.xhtml">Users</h:outputLink>
                        <h:outputLink value="./webpages/view/locations.xhtml">Locations</h:outputLink>
                        <ui:insert name="left" />
                    </h:panelGrid>

                    <ui:insert name="content" />

    </h:body>


Q: JavaScript document.write is not working Sorry if this seems dumb, i'm new to JavaScript.
This is in menu.js:
document.write("Home");
document.write("News");
document.write("About us");

This is in index.html:

When I load index.html, nothing comes up...

A: The problem is your quotes, you're using " both to delimit your new elements and to set their href attribute, change your code to:
document.write("Home");
document.write("News");
document.write("About us");

Or:
document.write('Home');
document.write('News');
document.write('About us');

Combining single (') and double (") quotes. You could also escape your internal quotes (document.write("Home");
BUT it'd be better to use a single call to document.write(), like this:
document.write('Home'
    + 'News'
    + 'About us');

A: You're not escaping the quotes in your strings.  It should be:
document.write("Home");

Otherwise, JavaScript thinks the string ends after href= and the rest of the line does not follow valid JavaScript syntax.
As @Felix mentioned, the JavaScript debugger tools will be extremely helpful in letting you know what's going on.


Q: turn bootstrap button into link with javascript and ajax I have a bootstrap button, that i have embedded into a form. The form requests a php file with ajax. But i Cant get the button to work like a link?
The html code is for the bootstrap button is :
Login

and the js is :

A: So do I get that correct that the link is supposed to send the form? That will not work, as a link on its own is not able to trigger a submit. You need an input of type submit.
<input type="submit" class="btn btn-success" value="Login">


Q: IE 8 Temporary Internet Files not created when using Windows 7 What would prevent Temporary Internet Files from being created/written in Windows 7 to the:
    C:\Users\<User>\AppData\Local\Microsoft\Windows\Temporary Internet Files\

I have come across a situation and I am not sure where to look for a possible solution, so I will try and best describe what is happening.
Two test machines are as follows:

*

*Windows 7 Enterprise SP1 w/Internet Explorer 8 (ver. 8.0.7601.17514 32 or 64bit)

*Windows XP SP3 w/Internet Explorer 8 (ver. 8.0.6001.18702CO 32bit)

Two Websites are as follows:

*

*Production Website exists in the same Domain as Machine #1 & #2
(http://prod.mysite/myApp/)

*Development Website exists in a Cloud environment with a different domain
(http://dev.cloud/myApp/)

Issue I am seeing is:
Accessing Website #1 from using system #1 (Windows 7) will result in Temporary Internet Files being created in the location below.
    C:\Users\<User>\AppData\Local\Microsoft\Windows\Temporary Internet Files\

However if I access Website #2 from system #1 (Windows 7) NO files are created.
Accessing Website #1 or #2 from system #2 (Windows XP) files are created as expected.
What I am looking or is direction on where I should be looking to find the cause, given that it only happens on Windows 7 with a website in a different domain.  Is it a GPO? an Internet Explorer 8 Privacy or Security setting?

A: Windows creates them in a hidden folder LOW under Temporary Internet Files.

This happens because of the UAC/LowIL (http://technet.microsoft.com/de-de/magazine/2007.06.uac%28en-us%29.aspx). Programs with LOW IL can only write into folder with low IL. Because IE runs with LowIL (Sandbox) there files are created there.


Q: Как определить момент получения данных? Помогите пожалуйста улучшить скрипт.
Есть json-файл. Я подгружаю его и мне нужно точно определить момент когда данные пришли. Вот пример кода. Его слабая сторона в том, что проверка:
  if($scope.news) {
    console.log('OK');
  } else {
    console.log('NOTOK');
  };

выводит в консоль не верную информацию("NOTOK") в то время как данные успешно получены.
для решения проблемы я пробовал обернуть этот код в $timeout (в том же примере соответствующие строки закомментированы).
Но это плохая практика потому что я поставил интервал 1000ms, а при получении json-файла (например с сервера) может случиться задержка и этот интервал будет превышен.
С другой стороны, если с сервера json-файл будет получен быстрее чем за 1000ms, то пользователь будет лишнее время смотреть в экран, на котором ничего не происходит
В общем помогите пожалуйста переписать код по человечески
Привожу полный код:
var app = angular.module('plunker', []);

app.controller('MainCtrl', ['$rootScope', '$scope', '$timeout', '$http',
function($rootScope, $scope, $timeout, $http) {
    $scope.getNews = function() {
      $http.get('news.json')
        .then(function successCallback(resp){
          console.log('success', resp);
          console.log('data', resp.data);
          console.log('status', resp.status);
          console.log('statusText', resp.statusText);
          $scope.news = resp.data.values;
        }, function errorCallback(resp) {
          console.log('error', resp);
          console.log('data', resp.data);
          console.log('status', resp.status);
          console.log('statusText', resp.statusText);
        });
    };

    $scope.getNews();

    //$timeout(function() {
      if($scope.news) {
        console.log('OK');
      } else {
        console.log('NOTOK');
      };
    //}, 1000);
}]);

A: Рекомендую перед $http.get(... написать return чтобы можно было добавлять обработчики успеха и неуспеха цепочкой из then() после $scope.getNews(). Получится вместо
$scope.getNews();

if($scope.news) {
    console.log('OK');
} else {
    console.log('NOTOK');
};

можно будет писать
$scope.getNews().then(function() {
    console.log('OK');
}, function() {
    console.log('NOTOK');
});

A: первый колбэк Promise .then и есть - этот момент. Но здесь вам не нужно его определять. Суть в том, что $news может быть или не быть - это важно для шаблона. Вот и сделайте шаблон, в котором будет ng-repeat по $news, а если $news не определён или пуст - соответствующий текст. А если хотите фильтровать ответ перед отображением, то .then(filterFn).then(otherFilterFn) - отличное место для этих целей, но Angular filter может быть лучше.


Q: Someone is "unable to be reached" On more than one occasion the MTV program Catfish concluded an episode with the following statement about one of the participants to the show -namely the catfish- and whom I will arbitrarily call "John":
"Despite numerous attempts, John was unable to be reached."
In my opinion, as a non-native English speaker, this sentence is somewhat peculiar. It states as a fact that John is currently unreachable, but the only thing we really know is that MTV Catfish tried to contact this person and these attempts failed. It is certainly possible, and in fact very likely, that John communicates with his friends and family as allways.
Therefore in my humble opinion the following sentence is much preferable:
"Despite numerous attempts, MTV Catfish was unable to reach John."
Am I right? Or am I missing some subtlety of modern English?

A: In the passive voice (in this case the passive infinitive "to be reached"), when the subject (or rather what would be the subject in the active voice) is not explicitly named, it has to be inferred from context. In this case, the intended subject is presumably "us," not "anyone."
So the meaning is not "John was unable to be reached by anyone"; it's "John was unable to be reached by us" (or by MTV, or by the show, or by its producers).

A: Both versions provided are fine (the original and your version). It's implied that he was unable to be reached by MTV, given that that's who's presenting the information. So, "Despite numerous attempts, John was unable to be reached," functions the same as "Despite numerous attempts, John was unable to be reached by MTV."