text:
Q: List that contains list that contains list and so on in c# This is code:
  public class Comment
  {
    public DateTime CreateAt { get; set; }
    public Comment ParentComment { get; set;}
    public List<Comment> SubComments { get; set; }
    public string Text { get; set; }
  }

I'am trying to do something like on facebook. You can comment every single comment, so there will be like a tree of comments.. I'am having trouble with trying to display all the comments, precisely text. I can't figure out how to do that. If anyone could help I'll appreciate it!

A: You can use recursion for process each comment and their sub comments for example:
    public void checkComment(Comment comment)
    {
        //Check if the comment is valid
        if (comment != null)
        {
            //Do whatever you want to do with your comment for example print to console
            Console.WriteLine(String.Format("Comment: {0}", comment.Text));
            //Check if i have any sub comments
            if (comment.SubComments.Count > 0)
            {
                //Process each sub comment (recursive)
                comment.SubComments.ForEach(x => checkComment(x));
            }
        }
    }


text:
Q: How to make aside next to content in flexbox? I'm new to web development, and I tried using flexbox for the second time, as I was doing my layout for the website I ran into an issue with floating aside. Basically, I want aside being next to content, but trying to float it, it just disappears. (all the colours are just for recognizing different elements).
Here is an image of my layout idea:

*,
*::after,
*::before {
  box-sizing: border-box;
}

body {
  margin: 0;
}

header {
  display: flex;
  justify-content: center;
  align-items: center;
  max-width: 135em;
  height: 7em;
  background: rgb(68, 100, 155);
}

section {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  background: chocolate;
  max-width: 100em;
  height: 50em;
}

aside {
  display: block;
  background: chartreuse;
  float: right;
  max-width: 20em;
  height: 50em;
}

footer {
  display: flex;
  justify-content: center;
  align-items: center;
  background: crimson;
  max-width: 135em;
  height: 22em;
}

A: You need to wrap your code in a div and set that to display: flex; like this:

Then in your CSS:
.flex-container {
  display: flex;
}

.flex-container section {
  flex: 1; // By your image example it looks like you want this element to stretch
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Integration googleDrive in ios application I use DropBox and SkyDrive in my applications and they work like a charme with a very good documentation, but GoogleDrive is really hard to integrate (to be polite :) ).
I'm not talking about coding but integration in xcode.
i follow this tutorial.
In step 3 i have 8 point to do, the problem is in point n°7, there's no Sources path, i search in the svn folder i download and it's not there. and of course without linking headers i have this issue "GTMOAuth2ViewControllerTouch.h no such file or directory"(i think that compiler stop there but there's more error).
what can i do ?

A: I know this is really old, but I had this problem and found a solution.
When you add the "User Header Search Paths" to the source directory, you need to make sure you set it to recursive so it gets all of the contents of that directory. Hope that helps.

A: The Source directory is immediately under the trunk that you checked out.
There is a Google Developer video (embedded at the bottom of the tutorial) that shows all the steps listed in the tutorial. Unfortunately the presenter does skip some troubleshooting and the steps he's following are very slightly different to the current version of the tutorial, but it is still helpful.


text:
Q: Find or Replace for text area (selection) I can't use the Find or Replace feature with text selection in my Android Studio.

The result always shows No occurrences of 'xxx' found in Selection.
My Android Studio version is 1.2.2. Even today I updated the Android Studio into the newest 1.3.0, it still doesn't work. But my friend's one works.
My computer OS is Windows 8.1. My friend's one is Windows 7.
I had tried to re-install Android Studio without removing the user settings. Still doesn't work.
Any idea ?

A: I don't know if it's working in windows, but in mac cmd + R, try ctrl + R

A: Are you trying to find the phrase _camera in the current selection? If so just use find and replace (ctrl + F) on the whole java file rather than Find in files and limiting the scope to the selection.


text:
Q: The word "royal" I noticed this because of the Youtube videos about the to-be-released Pokemon game. There is a new battling style called "Battle Royal" and in those videos they pronounce royal as "roi-aww," putting the stress at the 2nd syllable.
Is this a non-English word or does it have other meanings? I went online but there is only info about the royal I familiar with. Thanks.
For your kind reference, you may want to check out the video at https://www.youtube.com/watch?v=OvSgH-48kXs at 5:03 on Youtube.


text:
Q: Помогите с протоколом передачи данных Имеется на руках teltonik FMB920.
Настроил его на отправку TCP пакетов на сервер через GPRS.
На сервере написан PHP скрипт на сокетах.
Удаётся считать только IMEI код устройства, который приходит первым пакетом.
Далее трекер не принимает команд и не отвечает больше никак.
Попытка прочитать несколько раз
$sock = socket_create(AF_INET,SOCK_STREAM, 0 );
if (!socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1)) {
    echo socket_strerror(socket_last_error($sock));
    exit;
}
socket_bind($sock, "0.0.0.0", 12345);
$res = socket_listen($sock);
while (1) {
        if ($res) {
                echo "start listening\n";
        }
        $client = socket_accept($sock);
        echo "get client\n";
        for ($i = 0; $i<10; $i++) {
                $responce = "";
                echo "start_reading\n";
                $response = socket_read($client, 100);
                echo "readed \n***\n$response\n***\n";
                sleep (1);
        }

}

А это попытка отправить команду после прочтения первого пакета
for ($i = 0; $i<10; $i++) {
                $responce = "";
                echo "start_reading\n";
                $response = socket_read($client, 100);
                echo "readed \n***\n$response\n***\n";
                sleep (1);
                socket_write($client, "getver");
                sleep (1);
                $response = socket_read($client, 100);
                echo "readed \n***\n$response\n***\n";
        }

A: В общем.
Суть была в незнании протокола teltonika.
https://wiki.teltonika.lt/index.php?title=RUT955_Protocols
Ежели кому лень читать,
На первый пакет трекера в виде IMEI кода нужно ответить бинарной строкой "01"
socket_write($client, hex2bin("01"));

и далее уже трекер спокойно отдал мне gps данные в виде AVL пакета.


text:
Q: Inno-Setup ask once install two times Using InnoSetup I want to prompt a user if they wish to install an additional piece of software - think of it as a plug-in. My issue is that the additional software package I wish to install is broken up into two MSI files. I want to only prompt the user once to install the package but have each file in the [Run] section check the same value. How do I go about doing this?
[Code]
function InstallSomething:Boolean;
begin
   if (MsgBox('Do you want to install something?', mbInformation, mb_YesNo) = idYes) then
      Result:=True
   else
      Result:=False;
end;

[Run]
Filename: {sd}\Software\MyAppA.msi; Check: InstallSomething;
Filename: {sd}\Software\MyAppB.msi; Check: InstallSomething;

So the user should only get the message once but each file should install if true or skip if false.

A: Can you not store the result of your function call in a boolean variable and use that boolean value in your [Run] section?
It seems that this is possible after reading the following documentation: http://www.jrsoftware.org/ishelp/index.php?topic=scriptcheck


text:
Q: Set axis properties after plot is created I am using seaborn and trying to create and then edit plots. I'm somewhat new to Python and what I'd like to do is something like this:
1) Create plot: g = sns.lmplot(x, y, df, hue=z); #with seaborn imported as sns
2) g.style = "whitegrid" #I know this cannot be done as written, but how?
3) g.Font = "times new roman" #Same comment...
Anyway, I hope this makes sense. I appreciate the help.

A: Can you not just set style prior to creating your plot e.g. after loading the package
import seaborn as sns
sns.set(style="whitegrid", font='Times New Roman')

Link to seaborn documentation

A: You can modify the attributes for sns as you go from one plot to other.
x = np.random.randint(0, 10, size=10)
y = np.random.randint(0, 10, size=10)
z = np.random.randint(0, 2, size=10)
df=pd.DataFrame({
    'x':x,
    'y':y,
    'z':z
})
sns.set(style="whitegrid", font='Times New Roman')
g = sns.lmplot('x', 'y', df, hue='z')
plt.show()

sns.set(style="dark", font='Arial')
g = sns.lmplot('x', 'y', df, hue='z')
plt.show()

Output:


text:
Q: Let V-card QR-code auto fill in html form I have made a little registration web application for the visitors in our company. Every time a person comes in he or she has to register him- or herself by putting in all of their data and details into the registration application.
However a lot of people nowadays have a business card with a V-card QR-code on it.
When i scan that V-card with a 2D scanner this is what inside almost every V-card
BEGIN:VCARD
VERSION:2.1
N:Lou Bega
FN:Bega Lou
ORG:Number five
TITLE:Voice trainer
TEL;CELL:+32 45+32 455 32 36 98
ADR;WORK:;;Abclaan 345;Roeselare;;8800;Belgium
EMAIL;WORK;INTERNET:lou@bega.be
URL:www.loubega.be
END:VCARD

I am able to filter the unwanted data by PHP
i.e.
using preg_match(); funtion

But is it possible if they scan the V-card in the first input field it filters all of the unwanted data and fills in the input fields so the visitor can check if everything is present? Perhaps with some Javascript?
N: equals input field name="visitorname"
ORG: equals input field name="visitorcompany"
TELL or CELL: equals input field name="visitornumber"
and so on ...


text:
Q: Compose React app based on the value of a flag Problem Statement:
I want to compose my react app to use a specific set of components based on the value of a flag.
For Eg:
I have an App component consisting of three components by default:
ComponentA, ComponentB and ComponentC.
<App>
    <ComponentA />
    <ComponentB />
    <ComponentC />
<App/>

Now, if my flag is equal to ShowC, the I want my App to render ComponentA, ComponentB and ComponentC.
If the flag is equal to ShowD, then instead of ComponentC I want to render ComponentD instead.
<App>
    <ComponentA />
    <ComponentB />
    <ComponentD />
<App/>

Solution:
I have used a config object that has the respective imports in as key-value pairs:
{
    showC: {
        pos1: ComponentA,
        pos2: ComponentB,
        pos3: ComponentC,
    },
    showD: {
        pos1: ComponentA,
        pos2: ComponentB,
        pos3: ComponentD,
    }
}

Now, in my main App.js:
render() {
    const {
        pos1: FirstComponent,
        pos2: SecondComponent,
        pos3: ThirdComponent
    } = config[<flag>];

    <App>
        <FirstComponent />
        <SecondComponent />
        <ThirdComponent />
    </App>
}

I have created a simple example on stackblitz illustrating this.
https://stackblitz.com/edit/react-app-components-config?file=index.js
I want to understand if composing components in this way is considered an anti-pattern in React? Or if there is a better solution to this problem?

A: you can create  a HOC which would decide what to render based on the flag
const DynamicComponent = ({type,children}) => (

  { // you can have any condition here.
    type === 'a'?
    children[0]:
    children[1]
  }

)

// your main component
render() {

    <App>
        <FirstComponent />
        <SecondComponent />
        <DynamicComponent type={config.type}>
           <ThirdComponent />
           <FourthComponent />
        </DynamicComponent>
    </App>
}

you should always try to create a new HOC for any such composition, it follows functional programming composition pattern.


text:
Q: Type of printfn in F#, static vs dynamic string I just began toying around with F# in Mono and the following problem arose that I cannot quite understand. Looking up information on printfn and TextWriterFormat didn't bring enlightenment either, so I thought I'm going to ask here.
In FSI I run the following:
> "hello";;
val it : string = "hello"
> printfn "hello";;
hello
val it : unit = ()

Just a normal string and printing it. Fine. Now I wanted to declare a variable to contain that same string and print it as well:
> let v = "hello" in printfn v ;;
let v = "hello" in printfn v ;;
---------------------------^
\...\stdin(22,28): error FS0001: The type 'string' is not compatible with the type 'Printf.TextWriterFormat<'a>'

I understood from my reading that printfn requires a constant string. I also understand that I can get around this problem with something like printfn "%s" v.
However, I'd like to understand what's going on with the typing here. Clearly, "hello" is of type string as well as v is. Why is there a type problem then? Is printfn something special? As I understand it the compiler already performs type-checking on the arguments of the first string, such that printfn "%s" 1 fails.. this could of course not work with dynamic strings, but I assumed that to be a mere convenience from the compiler-side for the static case.

A: This is only somewhat related to your question, but I think it's a handy trick. In C#, I often have template strings for use with String.Format stored as constants, as it makes for cleaner code:
String.Format(SomeConstant, arg1, arg2, arg3)

Instead of...
String.Format("Some {0} really long {1} and distracting template that uglifies my code {2}...", arg1, arg2, arg3)

But since the printf family of methods insist on literal strings instead of values, I initially thought that I couldn't use this approach in F# if I wanted to use printf. But then I realized that F# has something better - partial function application.
let formatFunction = sprintf "Some %s really long %i template %i"

That just created a function that takes a string and two integers as input, and returns a string. That is to say, string -> int -> int -> string. It's even better than a constant String.Format template, because it's a strongly-typed method that lets me re-use the template without including it inline.
let foo = formatFunction "test" 3 5

The more I use F#, the more uses I discover for partial function application. Great stuff.

A: I don't think that it is correct to say that the literal value "hello" is of type String when used in the context of printfn "hello". In this context the compiler infers the type of the literal value as Printf.TextWriterFormat<unit>.
At first it seemed strange to me that a literal string value would have a different inferred type depending on the context of where it was used, but of course we are used to this when dealing with numeric literals, which may represent integers, decimals, floats, etc., depending on where they appear.
If you want to declare the variable in advance of using it via printfn, you can declare it with an explicit type...
let v = "hello" : Printf.TextWriterFormat<unit> in printfn v

...or you can use the constructor for Printf.TextWriterFormat to convert a normal String value to the necessary type...
let s = "foo" ;;
let v = new Printf.TextWriterFormat<unit>(s) in printfn v ;;

A: As you correctly observe, the printfn function takes a "Printf.TextWriterFormat<'a>" not a string. The compiler knows how to convert between a constant string and a "Printf.TextWriterFormat<'a>", but not between a dynamic string and a "Printf.TextWriterFormat<'a>".
This begs the question why can't it convert between a dynamic string and a "Printf.TextWriterFormat<'a>". This is because the compiler must look at the contents of the string to and determine what control characters are in it ( i.e. %s %i etc), from this is it works out the type of the type parameter of "Printf.TextWriterFormat<'a>" (i.e. the 'a bit). This is a function that is returned by the printfn function and means that the other parameters accepted by printfn are now strongly typed.
To make this a little clear in your example "printfn "%s"" the "%s" is converted into a "Printf.TextWriterFormat unit>", meaning the type of  "printfn "%s"" is string -> unit.

A: Good question.  If you look at the type of printfn, which is Printf.TextWriterFormat<'a> -> 'a, you'll see that the compiler automatically coerces strings into TextWriterFormat objects at compile time, inferring the appropriate type parameter 'a.  If you want to use printfn with a dynamic string, you can just perform that conversion yourself:
let s = Printf.TextWriterFormat<unit>("hello")
printfn s

let s' = Printf.TextWriterFormat<int -> unit>("Here's an integer: %i")
printfn s' 10

let s'' = Printf.TextWriterFormat<float -> bool -> unit>("Float: %f; Bool: %b")
printfn s'' 1.0 true

If the string is statically known (as in the above examples), then you can still have the compiler infer the right generic argument to TextWriterFormat rather than calling the constructor:
let (s:Printf.TextWriterFormat<_>) = "hello"
let (s':Printf.TextWriterFormat<_>) = "Here's an integer: %i"
let (s'':Printf.TextWriterFormat<_>) = "Float: %f; Bool: %b"

If the string is truly dynamic (e.g. it's read from a file), then you'll need to explicitly use the type parameters and call the constructor as I did in the previous examples.


text:
Q: Reflection of the chain-condition: clarifying a suspected typo In  the 2002 paper Reflecting Lindelöfness in Topology and its Applications, J. Baumgartner and F. Tall state that "by an easy  Löwenheim–Skolem argument," an uncountable (say $T_2$ or $T_3$) ccc topological space has a ccc subspace of cardinality $\aleph_1$.
My question is: Is this (reflection statement) actually true?
(Of course, I can see for example that indeed, "by an easy (ramification) argument," this is true for the linearly orderable topological spaces).

A: The reflection statement is dramatically false at least for Hausdorff spaces.
Theorem 1. For any infinite cardinal $\kappa$ there is a Hausdorff ccc space $X$ with no uncountable ccc subspace of cardinality less than or equal than $\kappa$.
Proof. Let $X=2^\kappa$ with the topology $\tau$ generated by sets of the form $P \cap C$ where $P$ is basic clopen on the product topology and $C\subseteq X$ with $|X \setminus C|<2^\kappa$. Note that the generating set is closed under finite intersections so it is in fact a base for $\tau$.
Clearly $\tau$ contains the product topology on $X$ so $(X,\tau)$ is a Hausdorff space. Moreover since any clopen in the product topology has size $2^\kappa$ we have that for any two basic open sets $P_1 \cap C_1$ and $P_2 \cap C_2$, $$(P_1 \cap C_1) \cap (P_2 \cap C_2) \neq \emptyset \iff P_1 \cap P_2 \neq \emptyset.$$
It follows that $(X,\tau)$ is ccc (since the product topology is ccc).
Finally if $Y$ is a subspace of $X$ with $|Y|<2^\kappa$ (in particular if $|Y|\leq \kappa$) then $Y$ is discrete. To see this just note that given $y \in Y$ we can take $C=(X \setminus Y) \cup \{y\}$ and since $|X \setminus C|=|Y \setminus \{y\}|<2^\kappa$, we have that $\{y\}=Y \cap (X \cap C)$ is open in $Y$. Hence $Y$ is not ccc unless $Y$ is countable. $\square$
However there are some positive results.
Theorem 2. If $(X,\tau)$ is an uncountable ccc topological space and $\chi(X) \leq \aleph_1$ then $X$ contains a ccc subspace of size $\aleph_1$.
Proof. Fix $M$ an elementary submodel of $H_\theta$ (with $\theta$ large enough) such that $\omega_1 \subseteq M$, $(X,\tau) \in M$ and $|M|=\aleph_1$. By elementarity the space $(X \cap M, \tau \cap M)$ is ccc and $|X \cap M|=\aleph_1$ (because $\omega_1 \subset M$). But since $\chi(X) \leq \aleph_1$, again by elementarity and the fact that $\omega_1 \subset M$, we have that $\tau \cap M$ generates the subspace topology in $X \cap M$. $\square$
Theorem 3. If $(X,\tau)$ is an uncountable ccc compact Hausdorff topological space then $X$ contains a ccc subspace of size $\aleph_1$.
Proof. Fix $M$ an elementary submodel of $H_\theta$ (with $\theta$ large enough) such that $\omega_1 \subseteq M$, $(X,\tau) \in M$ and $|M|=\aleph_1$. Define a relation on $X$ by $x\sim y$ if and only if $f(x)=f(y)$ for all $f \in C(X)\cap M$. It is fairly well known that this is an equivalence relation for which the quotient space $X/M$ is Hausdorff (in fact $X/M$ is Tychonoff whenever $X$ is Tychonoff, even if $X$ is not compact), the quotient map $\rho:X \to X/M$ is inyective when restricted to $X \cap M$ (so $|X/M| \geq \aleph_1$) and $\rho(X \cap M)$ is dense in $X/M$ (so $d(X/M) \leq \aleph_1$).
Fix a closed $Z \subseteq X$ such that the restriction $\rho:Z \to X/M$ is suryective and irreducible. Since $X/M$ is ccc being a continuous image of the ccc space $X$, we get by irreducibility that $Z$ is also ccc. Since $d(X/M) \leq \aleph_1$ we can find $Y \subseteq X$ with $|Y|=\aleph_1$ such that $\rho(Y)$ is dense in $X/M$. By irreducibility $Y$ is dense in $Z$ and therefore $Y$ is the ccc space we were looking for. $\square$
A combination of the ideas in the proofs of Theorems 2 and 3 can be used to prove that the reflection statement is true for $T_3$ spaces of pointwise countable type ($h(X) \leq \aleph_1$ is enough). In particular it is true for locally compact Hausdorff spaces.
I don´t know what happens for $T_3$ spaces in general (note that the space described in the proof of Theorem 1 is not regular).

A: This is meant to flesh out a claim made in a previous comment and clear up a point of confusion about what the topology on $X \cap M$ is normally assumed to be when trying to reflect properties of $X$ using elementary submodels.
Proposition:  Assume $(X,\tau)$ is Tychonoff. If $M\prec H(\theta)$ is an elementary sub-model with $X,\tau \in M$. Then, $(X_M, \tau_M)$ where $X_M = X \cap M$ and $\tau_M$ is the topology generated by $\{ U \cap X_M: U \in \tau \cap M \}$, is homeomorphic to a dense subset of a continuous image of $X$.
In particular, if $(X,\tau)$ is c.c.c., then so is $(X_M, \tau_M)$
Proof: Without loss of generality assume $X \subset [0,1]^{\lambda}$ ($\lambda$ a cardinal) with the topology on $X$ taken to be the topology induced by $[0,1]^{\lambda}$.
Let $\mathcal{B} = \cup \{ \{ [0, q), (q,p), (p,1] \}: q < p \text{ and } p,q\in (0,1)\cap \mathbb{Q}\}$ and $\mathbb{P} = \mathsf{Fn}(\lambda, \mathcal{B})$ (the set of finite partial functions $p\subset \lambda\times \mathcal{B}$); moreover for each $p \in \mathbb{P}$ define $$[p] = \{ a \in [0,1]^{\lambda}: (\forall \gamma \in dom(p))(a(\gamma) \in p(\gamma))\}.$$  Noting that $\{ [p]:p \in \mathbb{P} \}$ is a base for the product topology on $[0,1]^{\lambda}$, we readily have that $\mathcal{B}_X=\{ [p] \cap X: p \in \mathbb{P} \}$ is a base for the relative topology on $X$.
Claim: For any elementary submodel $M\prec H(\theta)$:

*

*$\mathcal{B} \in M$, $\mathcal{B} \subset M$, and $M \cap \mathbb{P} = \mathsf{Fn}(\lambda \cap M, \mathcal{B})$.

*Assuming $X \in M$: the set $Y_0 = \{ x_0 \cap M: x_0 \in X \cap M \} \subset [0,1]^{\lambda \cap M}$ is a dense subset of the space $Y=\pi_M[X]$ (the image of $X$ under the projection $\pi_M:[0,1]^{\lambda} \rightarrow [0,1]^{\lambda \cap M}$.)
Proof of Claim: For the first portion, simply note that $\mathcal{B}$ is a definable and countable family of subsets of $[0,1]$; in addition to see that $p \in \mathbb{P} \cap M \iff p \in \mathsf{Fn}(\lambda \cap M, \mathcal{B})$. First note that the set $dom(p)$ is definable from $p$ by a $\Delta_0$ formula. As such, it follows that $p \in M $ implies $dom(p) \in M$ which, since $p$ is finite, also entails $dom(p) \subset M$. For the second portion, it is enough to observe that by elementarity, for every $p \in \mathbb{P} \cap M$, if $[p] \cap X \neq\emptyset$ then, there is some $x \in [p] \cap X \cap M$ serving as a witness. This is enough to establish the second portion (and the proposition) since for each relevant $p$, we have $dom(p) \subset M \cap \lambda$ and the projection $\pi_M$ does not effect indices laying within $M$.
Edit:
Theorem: Assume $(X,\tau)$ is Tychonoff and c.c.c. and $M \prec H(\theta)$ with $X \in M$, then  $X_M = X \cap M$ (as a subspace of $X$) is c.c.c.
Proof: As before assume $X \subset [0,1]^\lambda$ and $M\prec H(\theta)$ are such that $X\in M$. Next, suppose $X$ has the c.c.c., then

*

*$Y = cl(X)\in M$ is compact and c.c.c.,

*The compact space $Z = cl(Y_M)$ contains $X_M$, and

*The restriction of the projection $\pi_M(x)=x\vert_M$ to $Z$ is irreducible and maps $Z$ onto $\pi_M[ Y ]\subset [0,1]^{\lambda \cap M}$ (this follows from the proof of the previous claim, combined with the observation that for any proper closed  $Z_0\subset Z$, we have $\emptyset \neq Y_M \cap (Z\backslash Z_0) \subset M$)

With that setup, for any $p \in \mathbb{P}$, define $U_p = \pi_M[Z] \backslash \pi_M[Z \backslash [p]] \subset [0,1]^{\lambda \cap M}$. Then each $U_p \subset \pi_M[Z] \subset [0,1]^{\lambda \cap M}$ is (relatively) open. Moreover, for any $p, q \in \mathbb{P}$, $$X_M \cap [p] \cap [q] = \emptyset \implies U_p \cap U_q \cap \pi_M[X_M] = \emptyset. $$
It follows that if $X_M$ is not a c.c.c. subspace of $X$, then $\pi_M[X_M]$ is not a c.c.c. subspace of $\pi_M[Z]$; however, noting that $\pi_M[X_M]$ is a dense subset of $\pi_M[X]$, which is in turn a dense subset of $\pi_M[Z] = \pi_M[Y]$, we have that $\pi_M[Y]$ is not c.c.c. (a contradiction.)
Remark: I guess I should have been more clear in the Proposition, the space $(X_M, \tau_M)$ is homeomorphic to $\pi_M[X_M] \subset \pi_M[X]$, which is a dense subset of $\pi_M[X]$. Moreover, since the original Proposition applies to all Tychonoff spaces, it applies to any compact space within which $X$ embeds as a dense subset.


text:
Q: Why does this code not compile in typescript? Why does this piece not compile in the following example?
"|| this.greeting != "test2""
class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    setGreeting(g) {
        this.greeting = g;
    }
    test() {
        if(this.greeting != "test" || this.greeting != "test2"){
            //this.greeting cound still be test3
        }
    }
}

Link to example

A: It's actually a valid error, and prevented you from making a mistake.
if (this.greeting != "test" || this.greeting != "test2") {

Since you're using ||, the second condition will not be executed unless this.greeting == 'test'.
Now, typescript is smart enough to automatically type this.greeting as 'test' when it enters the second conditional block.
Clearly, 'test' != 'test2' will never be false, and it's probably a mistake to check for that condition, since your entire if statement will always return true.
You probably wanted to write:
if (this.greeting != "test" && this.greeting != "test2") {

A: By the time you have reached the || this.greeting != "test2" part, the compiler knows for certain that this.greeting must be "test", and therefore it narrows the type of this.greeting to the literal type "test", which cannot be compared to "test2".


text:
Q: Standard way to combine States in scalaz Consider, you have the Nel of states (Nel stands for NonEmptyList, to make things shorter),
and you want to combine the States to one State, using some function f, for left part of the state and
g for the right part of the state.
So you want something like this:
def foldStatesG[S, A](in: NonEmptyList[State[S, A]])(f: (A, A) => A)(g: (S, S) => S): State[S, A] = {
    in.foldLeft1((s1, s2) => State(e => {
      val ss1 = s1(e)
      val ss2 = s2(e)
      g(ss1._1, ss2._1) -> f(ss1._2, ss2._2)
    }))
  }

I am sure, that I am inventing the bicycle, and such thing already exists, probably in a more general way. But, looking through scalaz I failed to find or recognize it. Would appreciate of any help on this topic.

The second question, describes how I came to such problem. I wanted to make a small simulation, when you have an Enemy (consider it's just a Double), and all possible spells which might hit him Nel[Spell]. So basically I want to generate all possible sequences. For example, if Nel[Spell] = ($, #), then given an enemy E, progression would look like
E -> (), then Nel(E -> $, E -> #), then Nel(E -> $$, E -> ##, E -> $#, E-> #$) etc.. (pseudo code)

Without going too much into details I need something like this:
def combineS(variations: NonEmptyList[Spell]): State[NonEmptyList[(Enemy, List[Spell])], Boolean]

In other words, you provide it with all possible moves, and it simulates all possible states. You can consider it as a kind of decision tree, which branches off every step.
Hence I defined, how to proceed with one spell.
def combineS1(spell: Spell): State[(NonEmptyList[(Enemy, List[Spell])]), Boolean]
    // some logic

The problem is, that I can not implement it via simple traverse:
def combineS(variations: NonEmptyList[Spell]): State[NonEmptyList[(Enemy, List[Spell])], Boolean] = {
    val x = variations traverse combine1 // State[Nel[..], Nel[Boolean]
    x map { _.suml1(conjunction)}
}

Because in traverse, the Nels are not appended to each other, but discarded.
That's why I came up with this solution:
  def combineS(variations: NonEmptyList[Spell]): State[NonEmptyList[(Enemy, List[Spell])], AllDead] = {
    val x: NonEmptyList[State[NonEmptyList[(Enemy, List[Spell])], Boolean]] = variations map combineS
    foldStates(x)(_ && _)(append)
  }

That code is actually working, but I feel like there's a way to traverse it, without additional foldState.
What would be other functional approaches to do such simulations (in terms of concepts at least). I can write it simply functional, without using high level concepts, but the purpose of this exercise was exactly to learn advanced stuff.
(May be it is exactly the job for Writer Monad? or Comonad?)
Also, if stackoverflow is not the best place for such questions, please, point out, where such questions are supposed to be asked?

A: Well, to answer the first part of that, if we were in an alternative universe where Scalaz already had a Biapplicative type class, we could use it as follows:
def foldStatesG[S, A](states: NonEmptyList[State[S, A]], s: (S, S) ⇒ S, a: (A, A) ⇒ A): State[S, A] =
  states.foldLeft1(IndexedStateT.indexedStateTBiapplicative[Id, S].bilift2(s, a))

But we don't, so we'd need something like the following (n.b. I haven't ensured this does anything sane law-wise):
trait Biapplicative[F[_, _]] extends Bifunctor[F] {
  def bipure[A, B](a: ⇒ A, b: ⇒ B): F[A, B]
  def biapply[A, B, C, D](fab: ⇒ F[A, B])(f: ⇒ F[A ⇒ C, B ⇒ D]): F[C, D]
  def bilift2[A, B, C, D, E, G](fab: (A, B) ⇒ C, fde: (D, E) ⇒ G): (F[A, D], F[B, E]) ⇒ F[C, G] =
    (fad: F[A, D], fbe: F[B, E]) ⇒
      biapply(fbe)(bimap[A, D, B ⇒ C, E ⇒ G](fad)(fab.curried, fde.curried))
}

object Biapplicative {
  implicit def indexedStateTBiapplicative[F[_], S1](implicit F: Applicative[F]) =
    new Biapplicative[IndexedStateT[F, S1, ?, ?]] {
      def bipure[A, B](a: ⇒ A, b: ⇒ B) =
        StateT.constantIndexedStateT(b)(a)
      def biapply[A, B, C, D]
          (fab: ⇒ IndexedStateT[F, S1, A, B])
          (f: ⇒ IndexedStateT[F, S1, A ⇒ C, B ⇒ D]) =
        new IndexedStateT[F, S1, C, D] {
          def apply(initial: S1): F[(C, D)] =
            F.ap(fab(initial))(F.map(f(initial)) {
              case (a2c, b2d) ⇒ Bifunctor[Tuple2].bimap(_)(a2c, b2d)
            })
        }
    }
}


text:
Q: chained select_related from many tables in django Here I have the following models:
class GenericUserData(AbstractUser):
    username = None
    id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
    email = models.EmailField(max_length=100, unique=True)
    date_joined = models.DateTimeField(auto_now_add=True)
   ....

class NormalSellerDetails(models.Model):
    userid = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True,db_column='UserID', unique=True)  # from table user.
    mobileauthenticationenabled = models.IntegerField(db_column='MobileAuthenticationEnabled', default=0)  # Field name made lowercase.
   .....

class UserBan(models.Model):
    user_id =  models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True,db_column='UserID', unique=True)  # from table user.
    from_date = models.DateField(null=False)

and I want to perform a select like the following:
SELECT * FROM genericuserdata, normalsellerdetails, userban
WHERE genericuserdata.id = normalsellerdetails.UserID AND genericuserdata.id = userban.UserID

I also have there seializers:
class GenericUserRetrievalSerializer(serializers.ModelSerializer):
    class Meta:
        model = GenericUserData
        fields = [ "email", "first_name", 'last_name', 'is_seller', 'is_normal', 'is_emp', 'is_male', 'bdate']

class AccountNormalSerializer(serializers.ModelSerializer):
    userid = GenericUserRetrievalSerializer(many=False)
    class Meta:
        model = NormalSellerDetails
        fields = ['mobileauthenticationenabled',
                'emailauthenticationenabled',
                'mobilephone',
                'profilepiclink',
                'userid',
                'userban'
                ]

I could link between GenericUserData, and NormalSellerDetails by doing so:
class NormalAccountList(generics.ListAPIView):
    serializer_class = AccountNormalSerializer

    def get_queryset(self):
         queryset = NormalSellerDetails.objects.all().select_related('userid')
         return queryset

but I couldn't link between all three into one query, noting model NormalSellerDetails relates to GenericUserData which in turn has an inverse relation to UserBan
My question is:
1- how to do that link?
2- userban table has rows for users who only are banned, How do create an output field having true when a row exists, and False when row doesn't exist?
also I tried to link by doing so, but didn't work
class NormalAccountList(generics.ListAPIView):
    serializer_class = AccountNormalSerializer
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsEmpReadAllUsersOrPost]

    def get_queryset(self):
        queryset= NormalSellerDetails.objects.select_related('userid').select_related('userid__userban_set').all()

        return queryset

class AccountNormalSerializer(serializers.ModelSerializer):
    userid = GenericUserRetrievalSerializer(many=False)
    userban = UserBanSerializer(many=False, read_only=True)
    class Meta:
        model = NormalSellerDetails
        fields = ['mobileauthenticationenabled',
                'emailauthenticationenabled',
                'mobilephone',
                'profilepiclink',
                'userid',
                'userban'
                ]

it was telling me " Invalid field name(s) given in select_related: 'userban_set'. Choices are: linkcounter, normalsellerdetails, permissions, userban"
and when I remove the keyword set it doesn't actually return anything from userban table.

A: Your queryset should look something like this:
queryset = NormalSellerDetails.objects.select_related('userid', 'userid__userban').all()

Note here that as indicated by the error you get, userban is the field you'll look for and not userban_set.
Regarding your second question, in order to have a field indicating if user is banned or not, you can annotate this field on the queryset like:
from django.db.models import Case, When, BooleanField

queryset = NormalSellerDetails.objects.select_related(
    'userid', 'userid__userban').all().annotate(
     is_banned=Case(
         When(userid__userban__isnull=False, then=True),
         default=False,
         output_field=BooleanField()
     )
)

You can then add this field in your serializer fields and it should appear in your API response.
Note here that ideally you should name your attribute in NormalSellerDetails model as user instead of userid. Of course, on the SQL level these relationships are by the foreign key which is essentially an ID, however, referring it as user means you're going to the user table and then doing something with the attributes within that table. This would make your Django code more readable.


text:
Q: Latex - Try to muster a Bode plot I'm trying to set up a plot with two y-axis, a Bode plot with amplitude and phase in the same diagram. I use the tikzpicture package with \begin{axis} and \addplot to overlay two graphs. Well, at least that's the idea... The issue I have is that it seems I don't have control over the graphs. I can't set fix intervals for the axis, can't control color/style of plot lines. Please point out if there's something wonky in my try to make a Bode plot. In particular, how do I set style on the lines, one dashed and one solid?
    \begin{figure}[H]
\centering
\begin{minipage}{0.9 \textwidth}

\begin{tikzpicture}

%%% AMPLITUDE
\begin{axis}[
    width=340pt,
    height=180pt,
    xlabel=Frequency,
    xmode = log,
    ylabel=Amplitude [dB],
    axis x line=bottom,
    axis y line=left,
%   xmin=10, xmax=1000000,
%   ylabel near ticks,
    legend pos= south west,
    font=\scriptsize,
    legend style={font=\scriptsize,draw=none,fill=none}
    ]

\addplot table [color=black, mark=none,dotted,y=$amp$, x=freq, font=\scriptsize]{amp.dat};
\addlegendentry{$Amplitude$ }

\end{axis}

%%% PHASE
\begin{axis}[
    width=340pt,
    height=180pt,
%   xmin=10, xmax=1000000,
    hide x axis,
    axis y line=right,
    xmode = log,
    ylabel=Phase [deg],
%   ymin=-300, ymax=-120,
%   ylabel near ticks,
    legend pos= north east,
    font=\scriptsize,
    legend style={font=\scriptsize,draw=none,fill=none}
    ]

\addplot table [mark=none,dashed, y=$phase$, x=freq]{phase.dat};
\addlegendentry{$Phase$ }

\end{axis}

\end{tikzpicture}

\caption{A Bode-plot of the common source gain stage.}
\label{fig:cg_sweep}
\end{minipage}
\end{figure}

Here's some test data for the plot, if needed: https://dl.dropboxusercontent.com/u/43498716/cg_sweep.dat
Thanks!

A: Is this what you are trying to achieve?

Here is a pgfplots solution.
Example for setting the intervals:
xmin=10, xmax=1000000, ymin=10, ymax=35, ...
Example for setting the plot line color and style:
\addplot[red, dashed] ...
\documentclass[border=10pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.9}

\begin{document}

\begin{tikzpicture}
\pgfplotsset{set layers}
\begin{axis}[
    xmode=log,
    xmin=10, xmax=1000000,
    ymin=10, ymax=35,
    scale only axis,
    axis y line*=left,
    xlabel=Frequency,
    ylabel={Amplitude [dB]},
]
    \addplot[blue, solid] table[x=freq,y=$amp$] {cg_sweep.dat};
    \label{aplot}
\end{axis}
\begin{axis}[
    xmode=log,
    xmin=10, xmax=1000000,
    ymin=-290, ymax=-140,
    scale only axis,
    axis y line*=right,
    axis x line=none,
    ylabel={Phase [deg]},
]
    \addlegendimage{/pgfplots/refstyle=aplot}\addlegendentry{$Amplitude$}
    \addplot[red, dashed] table[x=freq,y=$phase$] {cg_sweep.dat};
    \addlegendentry{$Phase$ }
\end{axis}
\end{tikzpicture}

\end{document}


text:
Q: Determine the minimum distance between lines If anyone got time. Me and my friends appreciate the help
We got a problem with the following task:
Determine the minimum distance between lines
Line 1:
$$\begin{eqnarray*}
x &=&1+t \\
y &=&2+2t.
\end{eqnarray*}$$
Line 2:
$$\begin{eqnarray*}
x &=&2-s \\
y &=&1-2s.
\end{eqnarray*}$$
Both of these lines intersect the line $x + y = 0$. Determine the respective intersection point and cutting angle.
Thanks for taking your time to read this and we hope you could help us out.

A: 1) Distance between the two lines.
The lines are parallel and distinct, so this makes sense.
Let us pick the point $P_2=(2,1)$ on line $2$. What you want is the orthogonal projection of $P_2$ on line $1$. There is a formula for that (see other answers), but let's do it as if we didn't know that.
First, you need to determine an equation of the line orthogonal to line $1$ pasing by $P_2$. Since the direction of line $1$ is given by the vector $(1,2)$, the direction of this orthogonal line can be given by $(2,-1)$ (that's a natural way to get an orthogonal vector to $(1,2)$). Then recall this orthogonal line passes through $P_2$ and write the corresponding parameterization.
Now find the intersection of line $1$ and the new orthogonal line you have just determined. Call it $P_1$. The distance between line $1$ and line $2$ is the distance bete
ween the points $P_1$ and $P_2$. I assume you know how to compute this given their coordinates.
2)Intersections with $x+y=0$.
Just plug the parameterized coordinates of line $1$ and line $2$ in this equation. Then solve for the parameter.
3) Angle.
A vector perpendicular to the line $x+y=0$ is $w=(1,1)$. A vector perpendicular to line $1$ is $u_1=(2,-1)$. The angle $\theta_1$ between line $1$ and the former is the angle between $w$ and $u_1$. You can use
$$
\cos\theta_1=\frac{(u_1,w)}{\|u_1\|\|w\|}.
$$

A: You can make a function $d(t)$ which measures the distance from line1 to line2 at a given time. By taking the derivative and setting it equal to 0 you can find a $t$ where the distance is minimal.


text:
Q: How to sum values in array from different columns + EXCEL VBA I need to calculate this in excel vba ,using array loop only :
round 0   round 1
9         28
65        84
28        47
84        103
41        60
66        85
115       134

I need to sum values in round 0 in loop so the sum result (408) must be divided by 7 , if not I WANT to sum one value from the round 1 (in this case 84 instead of 65 ) to the rest of values in round 0 so the sum result can divided by 7 . There will be so many round up to 7 . I need VBA code to accomplish this..
Notes :
round 0 and round 1 all in one two-dimensional array
My Question is : is there a way to sum values from different columns in multi-dimensional array ??
there is an image attached .
I appreciate any help or idea .
Thanks in advance
Excel VBA Array Model:
http://im56.gulfup.com/8rDErI.png
Here an example file contains macro "Question1.xlsm"
http://www.gulfup.com/?TKAAYM
Notes : click the link under the big green down arrow to download the file.
UPDATE :
here another macro to the file "Question1.xlsm" :
Sub A1()

Dim arrTemp1() As Integer
Dim sum1 As Integer

arrblkTable1 = Sheets("Sheet1").Range("blkTable1").Value

ReDim Preserve arrTemp1(0 To 1, 1 To 7)
    For a = 0 To 1
        sum1 = 0
        For c = 1 To 7

                arrTemp1(a, c) = arrblkTable1(c, 1) + (a * 19)
                text6 = text6 & arrTemp1(a, c) & vbCrLf

                Worksheets("TEST3").Cells(a + 1, c).Value = arrTemp1(a, c)

                sum1 = sum1 + arrTemp1(a, c)

        Next c
        If XLMod(sum1, 7) = 0 Then
            MsgBox "Yes  " & sum1
        Else
            MsgBox "No  " & sum1
        End If
    Next a
        MsgBox text6

End Sub

Function XLMod(a, b)
    ' This replicates the Excel MOD function
    XLMod = a - b * Int(a / b)
End Function

UPDATE : here a new update to the previous macro :
Sub A1()

Dim arrTemp1(), arrTemp2(), arrSUMs() As Integer
Dim sum1 As Integer

arrblkTable1 = Sheets("Sheet1").Range("blkTable1").Value
arrblkTable2 = Sheets("Sheet1").Range("blkTable2").Value

'-------------------------------- arrTemp1 ------------------------------

ReDim Preserve arrTemp1(0 To 1, 1 To 7)
    For a = 0 To 1
        sum1 = 0
        For c = 1 To 7
            arrTemp1(a, c) = arrblkTable1(c, 1) + (a * 19)
            text6 = text6 & arrTemp1(a, c) & vbCrLf
            Worksheets("TEST3").Cells(a + 1, c).Value = arrTemp1(a, c)
            sum1 = sum1 + arrTemp1(a, c)
        Next c
        If XLMod(sum1, 7) = 0 Then
            MsgBox "Yes  " & sum1
        Else
            MsgBox "No  " & sum1
            For c = 1 To 7
                sum1 = sum1 - arrTemp1(a, c)
                arrTemp1(a, c) = arrblkTable1(c, 1) + ((a + 1) * 19)
                sum1 = sum1 + arrTemp1(a, c)
                If XLMod(sum1, 7) = 0 Then
                    MsgBox "Yes  " & sum1 & " " & arrTemp1(a, c)
                End If
            Next c
        End If
    Next a
    For x = 0 To UBound(arrTemp1)
        For y = 1 To UBound(arrTemp1)
            text7 = text7 & arrTemp1(x, y) & vbCrLf
        Next y
    Next x
    MsgBox text7
End Sub

Function XLMod(a, b)
    ' This replicates the Excel MOD function
    XLMod = a - b * Int(a / b)
End Function

I need now to put each sum1 in one array , how I can do that ??

A: If I understood it correctly you want something similar to this:
Sub p()

v = Range("A2:A8")
v1 = Sheets("Sheet1").Range("B2:B8")
s = Application.WorksheetFunction.Sum(v)
b = False

Count = 0
For i = 1 To 7

temp = v
temp(i, 1) = v1(i, 1)
s = Application.WorksheetFunction.Sum(temp)
b = s Mod 7 = 0

If b = True Then
Count = Count + 1
End If
Next

MsgBox Count

End Sub

A: It may help tremendously if you can give more detail about what problem you're trying to solve, instead of focusing on how to solve it this way. There is a possibility that there's another way of doing it that hasn't occurred to you that will be much simpler.
This isn't an answer. Yet. But it will take more space than is allowed in a comment to ensure we've got this right.
For your sample data:
round 0   round 1
9         28
65        84
28        47
84        103
41        60
66        85
115       134

You want to:

*

*Sum all the values in Round 0 (9 + 65 + 28 + 84 + 41 + 66 + 115) = 408

*Take that sum (408) mod 7 and see if the result is 0

*

*408 / 7 = 58.28, so (408 mod 7) <> 0

*If the result isn't 0 (as in this case)

*

*Start substituting numbers from round 1 for numbers in Round 0

*

*Sum (28 + 65 + 28 + 84 + 41 + 66 + 115) = 427

*427 / 7 = 61 (427 mod 7) = 0

*This is now your valid result set.

*Had the first number in Round 1 been 29

*

*Sum (29 + 65 + 28 + 84 + 41 + 66 + 115) = 428

*428 / 7 = 61.14 so (428 mod 7) <> 0

*Substitute the next number from round 1 for the next number from round 0

*Sum (9 + 84 + 28 + 84 + 41 + 66 + 115) = 427

*This is now your valid result set.

*Is that the logic you're after?

*What happens if you get to the end of round 1 and you don't find a total that (mod 7 = 0)?


text:
Q: TypeError: 'MapResult' object is not iterable using pathos.multiprocessing I'm running a spell correction function on a dataset I have. I used from pathos.multiprocessing import ProcessingPool as Pool to do the job. Once the processing is done, I'd like to actually access the results. Here is my code:
import codecs
import nltk

from textblob import TextBlob
from nltk.tokenize import sent_tokenize
from pathos.multiprocessing import ProcessingPool as Pool

class SpellCorrect():

    def load_data(self, path_1):
        with codecs.open(path_1, "r", "utf-8") as file:
            data = file.read()
        return sent_tokenize(data)

    def correct_spelling(self, data):
        data = TextBlob(data)
        return str(data.correct())

    def run_clean(self, path_1):
        pool = Pool()
        data = self.load_data(path_1)
        return pool.amap(self.correct_spelling, data)

if __name__ == "__main__":
    path_1 = "../Data/training_data/training_corpus.txt"
    SpellCorrect = SpellCorrect()
    result = SpellCorrect.run_clean(path_1)
    print(result)
    result = " ".join(temp for temp in result)
    with codecs.open("../Data/training_data/training_data_spell_corrected.txt", "a", "utf-8") as file:
        file.write(result)

If you look at the main block, when I do print(result) I get an object of type <multiprocess.pool.MapResult object at 0x1a25519f28>.
I try to access the results with result = " ".join(temp for temp in result), but then I get the following error TypeError: 'MapResult' object is not iterable. I've tried typecasting it to a list list(result), but still the same error. What can I do to fix this?

A: The multiprocess.pool.MapResult object is not iterable as it is inherited from AsyncResult and has only the following methods:

*

*wait([timeout])
Wait until the result is available or until timeout seconds pass. This method always returns None.

*ready() Return whether the call has completed.

*successful() Return whether the call completed without raising an
exception. Will raise AssertionError if the result is not ready.

*get([timeout]) Return the result when it arrives. If timeout is not
None and the result does not arrive within timeout seconds then
TimeoutError is raised. If the remote call raised an exception then
that exception will be reraised as a RemoteError by get().
You can check the examples how to use the get() function here:
https://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers
from multiprocessing import Pool, TimeoutError
import time
import os

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=4)              # start 4 worker processes

    # print "[0, 1, 4,..., 81]"
    print pool.map(f, range(10))

    # print same numbers in arbitrary order
    for i in pool.imap_unordered(f, range(10)):
        print i

    # evaluate "f(20)" asynchronously
    res = pool.apply_async(f, (20,))      # runs in *only* one process
    print res.get(timeout=1)              # prints "400"

    # evaluate "os.getpid()" asynchronously
    res = pool.apply_async(os.getpid, ()) # runs in *only* one process
    print res.get(timeout=1)              # prints the PID of that process

    # launching multiple evaluations asynchronously *may* use more processes
    multiple_results = [pool.apply_async(os.getpid, ()) for i in range(4)]
    print [res.get(timeout=1) for res in multiple_results]

    # make a single worker sleep for 10 secs
    res = pool.apply_async(time.sleep, (10,))
    try:
        print res.get(timeout=1)
    except TimeoutError:
        print "We lacked patience and got a multiprocessing.TimeoutError"


text:
Q: Import Error with @react-three/drei / react-three-fiber I'm trying to use @react-three/drei. I've successfully installed and used @react-three/fiber but when I installed @react-three/drei. I get the following error:
./node_modules/three-stdlib/lights/RectAreaLightUniformsLib.js
Attempted import error: 'DataUtils' is not exported from 'three'.

Getting the error when I use this import for @react-three/drei-
import { Preload, ScrollControls, Scroll, useScroll, Image, useFBO, PerspectiveCamera } from '@react-three/drei'

App.jsx
import * as THREE from 'three'
import { Suspense, useRef, useState } from 'react'
import { Canvas, useFrame, useThree } from '@react-three/fiber'
import { Preload, ScrollControls, Scroll, useScroll, Image, useFBO, PerspectiveCamera } from '@react-three/drei'

import SiteNav from "./components/Nav/Nav"
import MainContainer from "./pages/MainContainer";

function App() {
  return (
      <div className="App">
        <SiteNav />
        <MainContainer />
      </div>
  )
}

export default App;

Any help would be appreciated! Thanks

A: I think the problem here is react-three/drei uses stand alone three-stdlib npm i three-stdlib should solve the problem.
https://github.com/pmndrs/drei  react-drei docs says the following:

A growing collection of useful helpers and abstractions for react-three-fiber.
npm install @react-three/drei  this package is using the stand-alone
three-stdlib instead of  three/examples/jsm.


text:
Q: Is it possible to mock a function called from inside module in jest? I have a TypeScript module with two functions: foo() calls bar(). I want to mock bar() and call foo() from the unit test. I tried this:
foo.ts:
export function bar(){
  throw 'not implemented'
}

export function foo(){
  return bar();
}

foo.test.ts:
import * as foo from './foo'

test('TODO', () => {
  jest.spyOn(foo, 'bar').mockReturnValue('quux')
  expect(foo.foo()).toBe('quux')
});

But I got an error:
 FAIL  ./foo.test.ts
  ✕ TODO (4 ms)

  ● TODO

    thrown: "not implemented"

      1 | import * as foo from './foo'
      2 |
    > 3 | test('TODO', () => {
        | ^
      4 |   jest.spyOn(foo, 'bar').mockReturnValue('quux')
      5 |   expect(foo.foo()).toBe('quux')
      6 | });

      at Object.<anonymous> (foo.test.ts:3:1)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)

It appears that foo() is somehow bypassing the mock. How can I make it use the mock instead of the real bar()?

A: To fix this change foo() to call exports.bar() instead of bar():
export function foo(){
  return exports.bar();
}

foo() in your example is bypassing the mock because there are two namespaces: the module and the exports object. When the reference to bar() is resolved JavaScript and TypeScript search for it in the module namespace but Jest can only spy on the exports object and can't change the contents of the module.
One possible solution is to explicitly lookup the identifiers you want to mock via the exports object as demonstrated above.
I found this approach here: https://medium.com/welldone-software/jest-how-to-mock-a-function-call-inside-a-module-21c05c57a39f#576f

A: try this refactor:
foo.ts:
const fn = {
  bar(): unknown | void {
    throw "not implemented";
  },

  foo() {
    return fn.bar();
  },
};

export default fn

foo.test.ts:
import functionsUnderTest from "./foo";

beforeEach(() => {
  jest.spyOn(functionsUnderTest, "bar").mockReturnValue("quux");
});

test("TODO", () => {
  expect(functionsUnderTest.foo()).toBe("quux");
});

issue with namespaces is solved in this way


text:
Q: GADT vs Existentially quantified types (*forall*) One can use GADT to express Existentially quantified types.
I see that GADT is more generic - data-type-extensions, paragraph section 7.4.7
When it's better to use Existentially quantified types then GADT? Are there any drawbacks using GADT compared to Existentially quantified types?

A: If you use the newest version of GHC, then there are no drawbacks I'm aware of. But in older versions you could combine GADTs and GeneralizedNewtypeDeriving in a type-unsafe way. I don't think the same was possible with ExistentialQuantification.

A: GADTs came along later than existentials, and they generalise them. I'm not aware of any drawbacks and would always use GADT syntax in new code as it's much clearer.
The documentation confirms this:

Notice that GADT-style syntax generalises existential types.


text:
Q: My magento automatically invoices my customers? When a customer places an order on my website. My Magento is automatically invoicing my customers.
We are a wholesale company and have various customer options. Some customers we will not invoice until the end of the month.
I am confused as to why this is automatically doing it.
We also have the EasyPDF plugin installed. I am not sure if this is causing the issues.


text:
Q: Toolbar in Navigation Controller I am creating a toolbar in a Navigation Controller using the following code:
 [self.navigationController setToolbarHidden:NO];

 //Create a button
     NSArray *toolbarItems = [NSArray arrayWithObjects:
                              [[UIBarButtonItem alloc] initWithTitle:@"Help" style:UIBarButtonItemStyleBordered target:self action:@selector(helpButton:)]
                              ,nil];

The only problem is that the toolbar is visible whenever there is a navigation controller(multiple other views). Is there a way to only restrict the toolbar to a single view?
Thanks

A: To quote the UINavigationController Class Reference:

The navigation toolbar is hidden by default but you can show it for your navigation interface by calling the setToolbarHidden:animated: method of your navigation controller object. If not all of your view controllers support toolbar items, your delegate object can call this method to toggle the visibility of the toolbar during subsequent push and pop operations.

So, set a delegate for your navigation controller.  In your delegate's navigationController:willShowViewController:animated:, do something like this:
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    BOOL shouldShowToolbar = (viewController == theViewControllerThatNeedsAToolbar);
    [navigationController setToolbarHidden:shouldShowToolbar animated:animated];
}

A: If you slightly modify the above example you can easily make it so the toolbar will automatically show when toolbar items are set in the current view controller's viewDidLoad method:
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    BOOL shouldHide = [viewController.toolbarItems count] == 0;
    [navigationController setToolbarHidden:shouldHide animated:animated];
}


text:
Q: Make gcc coloring the default Is there a way to automatically make gcc color its output?
I am looking to avoid an alias as the the command is commonly used in makefiles (where it will not be used).
Is there an easy way to do this?
Note: this does require gcc/g++ 4.9, which is currently available via svn. I am willing to recompile if the change is something small (in a config file or something).
I know that the GCC_COLOR environment variable is used, but I am not sure how to set it, or what to set it to.

A: Add to your .bashrc:
export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'

But note that GCC 4.9 is under heavy development, so the defaults may change.


text:
Q: prediction error when using BMA package: newdata is missing variables I am tring to use BMA package to implement out of sample forecast.
Here is my code:
out.3m<-bic.glm(x3,y3vec,strict = FALSE,OR = 50,glm.family=binomial(link = "probit"))

yfitout3=predict(out.3m,newdata=tail(x,1)) #where x has one more observation than x3.

I got:

Error in predict.bic.glm(out.3m, newdata = tail(x, 1)) :
    newdata is missing variables

However, when I use
yfitout3=predict(out.3m,newdata=tail(x,2))

It works.
Could you please tell me where is wrong?


text:
Q: Can't install node-xmpp-client with npm on centos 6.5 64bit I always get this "gyp ERR! stack Error: spawn EACCES" when installing node-xmpp-client in node 0.10.30
gyp ERR! configure error
gyp ERR! stack Error: spawn EACCES
gyp ERR! stack     at errnoException (child_process.js:1001:11)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:792:34)
gyp ERR! System Linux 2.6.32-504.3.3.el6.x86_64
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /usr/local/lib/node_modules/node-xmpp-client/node_modules/node-xmpp-core/node_modules/ltx/node_modules/node-expat
gyp ERR! node -v v0.10.30
gyp ERR! node-gyp -v v0.13.1
gyp ERR! not ok
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /usr/local/lib/node_modules/npm-debug.log
npm ERR! not ok code 0

And the last lines of the npm-debug.log
3444 verbose lock tar:///root/.npm/async/0.9.0/package.tgz /root/.npm/3975aa3c-root-npm-async-0-9-0-package-tgz.lock
3445 error Error: ENOENT, chown '/usr/local/lib/node_modules/node-xmpp-client/node_modules/node-xmpp-core/node_modules/ltx/node_modules/sax/LICENSE'
3446 error If you need help, you may report this *entire* log,
3446 error including the npm and node versions, at:
3446 error     <http://github.com/npm/npm/issues>
3447 error System Linux 2.6.32-504.3.3.el6.x86_64
3448 error command "/usr/local/bin/node" "/usr/local/bin/npm" "install" "node-xmpp-client" "-g"
3449 error cwd /usr/local/lib/node_modules
3450 error node -v v0.10.30
3451 error npm -v 1.4.21
3452 error path /usr/local/lib/node_modules/node-xmpp-client/node_modules/node-xmpp-core/node_modules/ltx/node_modules/sax/LICENSE
3453 error fstream_path /usr/local/lib/node_modules/node-xmpp-client/node_modules/node-xmpp-core/node_modules/ltx/node_modules/sax/LICENSE
3454 error fstream_type File
3455 error fstream_class FileWriter
3456 error fstream_finish_call chown
3457 error code ENOENT
3458 error errno 34
3459 error fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/writer.js:305:19
3459 error fstream_stack /usr/local/lib/node_modules/npm/node_modules/graceful-fs/polyfills.js:143:7
3459 error fstream_stack Object.oncomplete (evalmachine.<anonymous>:107:15)
3460 verbose exit [ 34, true ]

after npm cache clean I got the same gyp rebuild error and in npm-debug.log the last lines are:
2138 info preuninstall node-xmpp-client@1.0.0-alpha19
2139 info uninstall node-xmpp-client@1.0.0-alpha19
2140 verbose true,/usr/local/lib/node_modules,/usr/local/lib/node_modules unbuild node-xmpp-client@1.0.0-alpha19
2141 info postuninstall node-xmpp-client@1.0.0-alpha19
2142 error node-stringprep@0.5.4 install: `node-gyp rebuild`
2142 error Exit status 1
2143 error Failed at the node-stringprep@0.5.4 install script.
2143 error This is most likely a problem with the node-stringprep package,
2143 error not with npm itself.
2143 error Tell the author that this fails on your system:
2143 error     node-gyp rebuild
2143 error You can get their info via:
2143 error     npm owner ls node-stringprep
2143 error There is likely additional logging output above.
2144 error System Linux 2.6.32-504.3.3.el6.x86_64
2145 error command "/usr/local/bin/node" "/usr/local/bin/npm" "install" "node-xmpp-client" "-g"
2146 error cwd /usr/local/lib/node_modules
2147 error node -v v0.10.30
2148 error npm -v 1.4.21
2149 error code ELIFECYCLE
2150 verbose exit [ 1, true ]

The Python version installed is 2.7.6

A: I found the problem :
as states here : http://node-xmpp.github.io/doc/nodestringprep.html all I have to insall is:
yum install libicu-devel

And after that because of broken attempts to install the node-xmpp-client I got some
npm ERR! EEXIST, mkdir

which fixed as stated here :NPM wont run due to EEXIST error
by removing the ~/.npmrc


text:
Q: iPhone 5 - Table View Header height not correct I have a CustomView for a Table View Header.
The height of the label within the Header is dynamic. For all simulators other than iPhone 5, it works. The Label text  works for any number of lines. The height increases changes to the correct required height.
But for iPhone 5 simulator, the header does not increase to appropriate height.
Is this an issue with iPhone 5 simulator? Don't have a real iPhone 5 device to test this out.

A: Try using autolayout to set the header height. You need to set the header height after the view has layout all the subviews.
  override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    self.tableView.layoutHeaderView()
  }

Use this extension, it will adjust the header height to the required space:
extension UITableView {
  public func layoutTableHeaderView() {
    guard let headerView = self.tableHeaderView else { return }

    headerView.translatesAutoresizingMaskIntoConstraints = false

    let headerWidth = headerView.bounds.size.width;
    let temporaryWidthConstraints = NSLayoutConstraint.constraints(withVisualFormat: "[headerView(width)]", options: NSLayoutFormatOptions(rawValue: UInt(0)), metrics: ["width": headerWidth], views: ["headerView": headerView])

    headerView.addConstraints(temporaryWidthConstraints)

    headerView.setNeedsLayout()
    headerView.layoutIfNeeded()

    let headerSize = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
    let height = headerSize.height
    var frame = headerView.frame

    frame.size.height = height
    headerView.frame = frame

    self.tableHeaderView = headerView

    headerView.removeConstraints(temporaryWidthConstraints)
    headerView.translatesAutoresizingMaskIntoConstraints = true
  }
}

Each time that you need to resize the height view call
self.tableView.layoutHeaderView()

It will adjust the table height view to the minimum space required, but it won't cut anything.
P.S: If you use autolayout to set the header height you need to define the distance between the label, the top of the headerView and the Bottom.


text:
Q: Create a program that constructs a Rectangle object (java.awt.Rectangle) I'm using Dr. Java and the language is java ...i'm a beginner
* just a basic rectangle
Problem:
Create a program that constructs a Rectangle object (java.awt.Rectangle). The object should have a getWidth(5) and a getHeight(8)
 compute and System.out.println() the area of the Rectangle object. Then compute the perimeter and print it as well.
what i have so far
//finding the area
int Width = 5;
int Height = 8;
Rectangle bob = new Rectangle(0,0,5,8);
double area = bob.getWidth()*bob.getHeight();
System.out.println("area = " + area);

 // Find the perimeter
double perimeter = 2*(bob.getHeight()) + 2*(bob.getWidth());
System.out.println("get the perimeter = " + perimeter);`

A: Have you tried this tutorial? It covers the basics of Java 2D and can help you with your problem.

A: You are on the right track, but you need to read up a little on how System.out.println(...) works.
Rectangle bob = new Rectangle(10,20,5,8);
double area = bob.getWidth()*bob.getHeight();
System.out.println("area = + area");

While you do have a variable named area, you do not reference it in your println statement.  What you have in your println statement is one string that happens to have two continuous series of characters that spell "area", but neither one is a reference to the variable name.
System.out.println("area = " + area);

Is quite different.  There is one string, "area = " and a concatenation operator which joins the string to the variable area (which will be automatically converted to a String type.  It is a fine point of "moving" the terminating quotation mark of the string, but the meaning is quite different.
"area = + area"

one string, with a few funny characters
"area = " + area

one string, a concatenation operator, and a second name which will be "converted" to a string.


text:
Q: How to launch email client from FireMonkey on Windows/Mac? Is there a cross-platform way of launching an email client from FireMonkey so that it will work on both Windows and OS/X.  Under windows I can do the following:
ShellExecute(0, 'OPEN', 'mailto:somebody@somewhere.com', '', '', SW_ShowDefault);

Is there a cross-platform equivalent to launch an email client (preferably with attachments, recipient, subject, body etc.)?

A: As far i know there is not a cross-platform way to send a mail, but using the ShellExecute function in the windows side and the NSWorkspace.openURL for the OSX you can write your own implementation.
Try this OSX implementation.
uses
  Macapi.Foundation,
  Macapi.AppKit,
  System.SysUtils;

Procedure SendMail(const Mailto,Subject, Body:string);
var
  URL : NSURL;
  AWorkspace : NSWorkspace;
  encodedSubject,
  encodedTo,
  encodedBody    : NSString;
begin
  //NSString *encodedSubject = [NSString stringWithFormat:@"SUBJECT=%@", [subject stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  encodedSubject :=NSSTR(Format('SUBJECT=',[Subject])).stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding);
  //NSString *encodedBody = [NSString stringWithFormat:@"BODY=%@", [body stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  encodedBody    :=NSSTR(Format('BODY=',[Body])).stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding);
  //NSString *encodedTo = [to stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  encodedTo      :=NSSTR(Mailto).stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding);
  //NSString *encodedURLString = [NSString stringWithFormat:@"mailto:%@?%@&%@", encodedTo, encodedSubject, encodedBody];
  //NSURL *mailtoURL = [NSURL URLWithString:encodedURLString];
  // [[NSWorkspace sharedWorkspace] openURL:mailtoURL];
  URL := TNSURL.Create;
  URL.initWithString(NSSTR(Format('mailto:%s?%s&%s',[ encodedTo.UTF8String, encodedSubject.UTF8String, encodedBody.UTF8String])));
  AWorkspace := TNSWorkspace.Create;
  AWorkspace.openURL(URL);
end;


text:
Q: StreamEx.parallel().forEach() does not run in parallel after .map() I noticed that if I use StreamEx lib to parallel out my streams with a custom ForkJoinPool as below - the subsequent actions do run in parallel threads from that pool. However, if I add a map() operation and parallel the resulting stream - only one thread from the pool is used.
Below is the full code (without all imports) of a minimal working example that demonstrates this problem. The only difference between the executeAsParallelFromList() and the executeAsParallelAfterMap() methods is addition of .map(...) call before the .parallel() .
import one.util.streamex.StreamEx;

public class ParallelExample {

private static final Logger logger = LoggerFactory.getLogger(ParallelExample.class);
private static ForkJoinPool s3ThreadPool = new ForkJoinPool(3);

public static List<String> getTestList(){
    int listSize = 10;
    List<String> testList = new ArrayList<>();
    for (int i=0; i<listSize; i++)
        testList.add("item_" + i);
    return testList;
}

public static void executeAsParallelFromList(){
    logger.info("executeAsParallelFromList():");
    List<String> testList = getTestList();
    StreamEx<String> streamOfItems = StreamEx
            .of(testList)
            .parallel(s3ThreadPool);
    logger.info("streamOfItems.isParallel(): {}", streamOfItems.isParallel());
    streamOfItems.forEach(item -> handleItem(item));
}

public static void executeAsParallelAfterMap(){
    logger.info("executeAsParallelAfterMap():");
    List<String> testList = getTestList();
    StreamEx<String> streamOfItems = StreamEx
            .of(testList)
            .map(item -> item+"_mapped")
            .parallel(s3ThreadPool);
    logger.info("streamOfItems.isParallel(): {}", streamOfItems.isParallel());
    streamOfItems.forEach(item -> handleItem(item));
}

private static void handleItem(String item){
    // do something with the item - just print for now
    logger.info("I'm handling item: {}", item);
}

}

Unit test to execute both methods:
public class ParallelExampleTest {

@Test
public void testExecuteAsParallelFromList() {
    ParallelExample.executeAsParallelFromList();
}

@Test
public void testExecuteAsParallelFromStreamEx() {
    ParallelExample.executeAsParallelAfterMap();
}

}

Results of the execution:
08:49:12.992 [main] INFO  marina.streams.ParallelExample - executeAsParallelFromList():
08:49:13.002 [main] INFO  marina.streams.ParallelExample - streamOfItems.isParallel(): true
08:49:13.040 [ForkJoinPool-1-worker-1] INFO  marina.streams.ParallelExample - I'm handling item: item_6
08:49:13.040 [ForkJoinPool-1-worker-2] INFO  marina.streams.ParallelExample - I'm handling item: item_2
08:49:13.040 [ForkJoinPool-1-worker-3] INFO  marina.streams.ParallelExample - I'm handling item: item_1
08:49:13.041 [ForkJoinPool-1-worker-2] INFO  marina.streams.ParallelExample - I'm handling item: item_4
08:49:13.041 [ForkJoinPool-1-worker-1] INFO  marina.streams.ParallelExample - I'm handling item: item_8
08:49:13.041 [ForkJoinPool-1-worker-3] INFO  marina.streams.ParallelExample - I'm handling item: item_0
08:49:13.041 [ForkJoinPool-1-worker-2] INFO  marina.streams.ParallelExample - I'm handling item: item_3
08:49:13.041 [ForkJoinPool-1-worker-1] INFO  marina.streams.ParallelExample - I'm handling item: item_9
08:49:13.041 [ForkJoinPool-1-worker-3] INFO  marina.streams.ParallelExample - I'm handling item: item_5
08:49:13.041 [ForkJoinPool-1-worker-2] INFO  marina.streams.ParallelExample - I'm handling item: item_7

08:49:13.043 [main] INFO  marina.streams.ParallelExample - executeAsParallelAfterMap():
08:49:13.043 [main] INFO  marina.streams.ParallelExample - streamOfItems.isParallel(): true
08:49:13.044 [ForkJoinPool-1-worker-1] INFO  marina.streams.ParallelExample - I'm handling item: item_0_mapped
08:49:13.044 [ForkJoinPool-1-worker-1] INFO  marina.streams.ParallelExample - I'm handling item: item_1_mapped
08:49:13.044 [ForkJoinPool-1-worker-1] INFO  marina.streams.ParallelExample - I'm handling item: item_2_mapped
08:49:13.044 [ForkJoinPool-1-worker-1] INFO  marina.streams.ParallelExample - I'm handling item: item_3_mapped
08:49:13.044 [ForkJoinPool-1-worker-1] INFO  marina.streams.ParallelExample - I'm handling item: item_4_mapped
08:49:13.044 [ForkJoinPool-1-worker-1] INFO  marina.streams.ParallelExample - I'm handling item: item_5_mapped
08:49:13.044 [ForkJoinPool-1-worker-1] INFO  marina.streams.ParallelExample - I'm handling item: item_6_mapped
08:49:13.044 [ForkJoinPool-1-worker-1] INFO  marina.streams.ParallelExample - I'm handling item: item_7_mapped
08:49:13.044 [ForkJoinPool-1-worker-1] INFO  marina.streams.ParallelExample - I'm handling item: item_8_mapped
08:49:13.044 [ForkJoinPool-1-worker-1] INFO  marina.streams.ParallelExample - I'm handling item: item_9_mapped

As you can see, all three threads are being used when executing the executeAsParallelFromList(), but only one thread is used when executing the executeAsParallelAfterMap().
Why?
thanks!
Marina
NOTE: the example is deliberately simplistic - I tried to make it as minimal as possible to demo the issue. Obviously in real life there is much more going on in the map(), handleItem() , etc., and the input data is much more interesting (I'm trying to process AWS S3 buckets/prefixes in parallel).

A: Simple answer: it's a bug. I filed and fixed it. This was overlooked by tests as tests only check that all the operations are executed in the specified pool, but don't check whether different threads of pool are used (sometimes it's ok if parallelization does not work, e.g. for a stream of one element only).
A fix is available in 0.6.4 release. In previous releases to work-around the problem you may consider using .parallel().parallel(fjp): it should parallelize correctly.
Please consider reporting StreamEx problems to official StreamEx issue tracker. I visit StackOverflow only occasionally these days, so may overlook the problems reported here.

A: The problem is that as soon as you call the map(...) method, StreamEx creates the underlying Java 8 stream with the sequential/parallel configuration as of that point, (i.e. sequential), and calling parallel(...) after that does not appear to update the underlying Java 8 stream.
The solution depends on what you are trying to achieve. If you're happy for your map(...) operation to be run in parallel as well, then just move the parallel(...) operation up so that it is the first thing after the of(...).
However, if you want some operations to be carried out sequentially, before some parallel operations, then you'd be better using two streams. For example, following the style of your sample code:
public static void executeAsParallelAfterMapV2() {
    logger.info("executeAsParallelAfterMapV2():");
    List<String> testList = getTestList();
    StreamEx<String> sequentialStream = StreamEx
            .of(testList)
            .map(item -> {
                logger.info("Mapping {}", item);
                return item + "_mapped";
            });
    logger.info("sequentialStream.isParallel(): {}", sequentialStream.isParallel());

    List<String> afterSequentialProcessing = sequentialStream.toList();
    StreamEx<String> streamOfItems = StreamEx.of(afterSequentialProcessing)
            .parallel(s3ThreadPool);
    logger.info("streamOfItems.isParallel(): {}", streamOfItems.isParallel());
    streamOfItems.forEach(item -> handleItem(item));
}

This gives something like:
20:43:36.835 [main] INFO scott.streams.ParallelExample - executeAsParallelAfterMapV2():
20:43:36.883 [main] INFO scott.streams.ParallelExample - sequentialStream.isParallel(): false
20:43:36.886 [main] INFO scott.streams.ParallelExample - Mapping item_0
20:43:36.886 [main] INFO scott.streams.ParallelExample - Mapping item_1
20:43:36.886 [main] INFO scott.streams.ParallelExample - Mapping item_2
20:43:36.886 [main] INFO scott.streams.ParallelExample - Mapping item_3
20:43:36.886 [main] INFO scott.streams.ParallelExample - Mapping item_4
20:43:36.886 [main] INFO scott.streams.ParallelExample - Mapping item_5
20:43:36.886 [main] INFO scott.streams.ParallelExample - Mapping item_6
20:43:36.886 [main] INFO scott.streams.ParallelExample - Mapping item_7
20:43:36.886 [main] INFO scott.streams.ParallelExample - Mapping item_8
20:43:36.886 [main] INFO scott.streams.ParallelExample - Mapping item_9
20:43:36.886 [main] INFO scott.streams.ParallelExample - streamOfItems.isParallel(): true
20:43:36.889 [ForkJoinPool-1-worker-1] INFO scott.streams.ParallelExample - I'm handling item: item_6_mapped
20:43:36.889 [ForkJoinPool-1-worker-2] INFO scott.streams.ParallelExample - I'm handling item: item_2_mapped
20:43:36.890 [ForkJoinPool-1-worker-3] INFO scott.streams.ParallelExample - I'm handling item: item_8_mapped
20:43:36.890 [ForkJoinPool-1-worker-1] INFO scott.streams.ParallelExample - I'm handling item: item_5_mapped
20:43:36.890 [ForkJoinPool-1-worker-2] INFO scott.streams.ParallelExample - I'm handling item: item_4_mapped
20:43:36.890 [ForkJoinPool-1-worker-3] INFO scott.streams.ParallelExample - I'm handling item: item_9_mapped
20:43:36.890 [ForkJoinPool-1-worker-1] INFO scott.streams.ParallelExample - I'm handling item: item_1_mapped
20:43:36.890 [ForkJoinPool-1-worker-2] INFO scott.streams.ParallelExample - I'm handling item: item_3_mapped
20:43:36.890 [ForkJoinPool-1-worker-3] INFO scott.streams.ParallelExample - I'm handling item: item_7_mapped
20:43:36.890 [ForkJoinPool-1-worker-1] INFO scott.streams.ParallelExample - I'm handling item: item_0_mapped

An Aside...
Out of interest, if you create a Java 8 stream directly, (not using StreamEx), and put the parallel() operation below the map(...), then it does update the type of the (whole) stream to be parallel:
public static void executeAsParallelAfterMapJava8Stream() throws InterruptedException {
    logger.info("executeAsParallelAfterMapJava8Stream():");
    List<String> testList = getTestList();

    s3ThreadPool.submit(() -> {
        Stream<String> streamOfItems = testList.stream()
                .map(item -> {
                    logger.info("Mapping {}", item);
                    return item + "_mapped";
                })
                .parallel();
        logger.info("streamOfItems.isParallel(): {}", streamOfItems.isParallel());
        streamOfItems.forEach(item -> handleItem(item));
    }).join();
}

If you create a similar unit test then you get something similar to:
20:36:23.469 [main] INFO scott.streams.ParallelExample - executeAsParallelAfterMapJava8Stream():
20:36:23.517 [ForkJoinPool-1-worker-1] INFO scott.streams.ParallelExample - streamOfItems.isParallel(): true
20:36:23.520 [ForkJoinPool-1-worker-1] INFO scott.streams.ParallelExample - Mapping item_6
20:36:23.520 [ForkJoinPool-1-worker-2] INFO scott.streams.ParallelExample - Mapping item_2
20:36:23.520 [ForkJoinPool-1-worker-3] INFO scott.streams.ParallelExample - Mapping item_8
20:36:23.520 [ForkJoinPool-1-worker-1] INFO scott.streams.ParallelExample - I'm handling item: item_6_mapped
20:36:23.520 [ForkJoinPool-1-worker-2] INFO scott.streams.ParallelExample - I'm handling item: item_2_mapped
20:36:23.520 [ForkJoinPool-1-worker-3] INFO scott.streams.ParallelExample - I'm handling item: item_8_mapped
20:36:23.520 [ForkJoinPool-1-worker-1] INFO scott.streams.ParallelExample - Mapping item_5
20:36:23.520 [ForkJoinPool-1-worker-2] INFO scott.streams.ParallelExample - Mapping item_4
20:36:23.520 [ForkJoinPool-1-worker-3] INFO scott.streams.ParallelExample - Mapping item_9
20:36:23.520 [ForkJoinPool-1-worker-1] INFO scott.streams.ParallelExample - I'm handling item: item_5_mapped
20:36:23.520 [ForkJoinPool-1-worker-2] INFO scott.streams.ParallelExample - I'm handling item: item_4_mapped
20:36:23.520 [ForkJoinPool-1-worker-3] INFO scott.streams.ParallelExample - I'm handling item: item_9_mapped
20:36:23.520 [ForkJoinPool-1-worker-1] INFO scott.streams.ParallelExample - Mapping item_1
20:36:23.520 [ForkJoinPool-1-worker-2] INFO scott.streams.ParallelExample - Mapping item_3
20:36:23.520 [ForkJoinPool-1-worker-3] INFO scott.streams.ParallelExample - Mapping item_7
20:36:23.521 [ForkJoinPool-1-worker-1] INFO scott.streams.ParallelExample - I'm handling item: item_1_mapped
20:36:23.521 [ForkJoinPool-1-worker-2] INFO scott.streams.ParallelExample - I'm handling item: item_3_mapped
20:36:23.521 [ForkJoinPool-1-worker-3] INFO scott.streams.ParallelExample - I'm handling item: item_7_mapped
20:36:23.521 [ForkJoinPool-1-worker-1] INFO scott.streams.ParallelExample - Mapping item_0
20:36:23.521 [ForkJoinPool-1-worker-1] INFO scott.streams.ParallelExample - I'm handling item: item_0_mapped


text:
Q: memory leakage when main is empty - Ubuntu/C++ I'm using an Ubuntu 14.04 image with VmWare,
I'm writing a program in C++ & whenever I check the memory with Valgrind,
I get a message that I have 1 alloc, with 0 free.
The thing is, that I noticed that it happens when my main is empty.

Now the interesting thing is, when I try it on a different version of Ubuntu (12), there are no allocs whatsoever.

A: As long as I know iostream has some global stuff which is initialized once you include this library. Also it is a known issue that STLs don't release their memory immediately.
Check this link about mem leakage on STL with valgrind.
Also this link from SO.


text:
Q: Remove vertical split bar of a termincal multiplexer, vacating the space instead of hiding it For the last decade I usually work in a full-screen mode terminal emulator (often xterm), and often with vertical split. The recent GNU Screen offers vertical split with ctrl-a |.
1280×720 offers 160 columns for typical 16px font (8px wide), just enough for two 80-column session. The same way, 1440x960 offers 160 columns for 18px fonts (9px wide). The larger one: 1920×1080 offers 240 columns, just enough for three 80-column session.
But in reality GNU Screen put a vertical bar to separate the sessions. The bar can be hidden or colored as background, but the space is taken. That leaves my console 79-columns, just one column short for daily work (e.g. coding convention requires each line less than 80 columns¹; auto-generated email reports assumed 80-column).
Is there a way to vacate the space of the vertical split bar? Or, if this can't be done, is any of the alternatives to GNU Screen, like Dvtm / Tmux, support vertical splict without a bar's space? An X terminal emulator that can do multiplex would fit the purpose as well, but such thing perhaps doesn't exist.
Note 1:  Even Python programming language explicitly suggests 79 columns exactly for the purpose of unremovable marker at the 80th column, there are still other occassions that can take advantage of full 80-columns.

A: None of the multiplexer in the known universe, such as gnu screen, tmux, dvtm, allows configuring vertical split to none at all.
Marc André Tanner, current dvtm maintainer, was kind enough to offer a patch to do so on request, tested appliable to latest dvtm-0.10, making dvtm the only multiplexer in the known unverse that can be patched to do so. Marc said this patch won't go to main branch and get released.
diff --git a/tile.c b/tile.c
index 43a7166..b166a56 100644
--- a/tile.c
+++ b/tile.c
@@ -25,9 +25,6 @@ static void tile(void)
                    ny = way;
                    nx += mw;
                    nw = waw - mw;
-                   mvvline(ny, nx, ACS_VLINE, wah);
-                   mvaddch(ny, nx, ACS_TTEE);
-                   nx++, nw--;
                }
                /* remainder */
                if (m == 0 && i + 1 == n)   /* no minimized clients */
@@ -40,8 +37,6 @@ static void tile(void)
                nh = 1;
                ny = way + wah - (n - i);
            }
-           if (i > 1 && nm > 1)
-               mvaddch(ny, nx - 1, ACS_LTEE);
        }
        resize(c, nx, ny, nw, nh);
        if (n > 1 && th != wah)


text:
Q: Logic for a parsed JSON list? Is it possible to have logic on a parsed JSON list? I have my entire list saved into a variable 'info' and and want to look at the parsed information and write a conditional for it. My end goal is to put a 'hr' line break in between the changed priority numbers. Because it is dynamically creating the list as the Agent Emails are updated...I am not sure where or how to put the line break logic. I hope I am just overlooking something super simple.

My thought was that I can loop through the 'info' list and write an if statement in a method. Then in my VFP, I could loop through the method. But the code I was trying does not know what what PriorityNumber is. This leads me to believe that because of the formatting of the data, I can not put conditional statements on it.
for (Integer i = 0; i < Info.AgentInfoList; i++)
    {
        if (Info.AgentInfoList.PriorityNumber == 0)
        {
            return Info.AgentInfoList.PriorityNumber;
        }

My Controller:
//https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_json_jsonparser.htm
public class WSController {
    public JSON2Apex info { get; set; }

String jsonStr = '{"DateModifiedUtc":"2016-09-07T20:12:47.1519119Z",' +
    '"AgentInfoList":[{"Username":"Agent00@gmail.com","PriorityNumber":0}, ' +
    '{"Username":"Agent01@gmail.com","PriorityNumber":0},{"Username":"Agent02@gmail.com","PriorityNumber":0},' +
    '{"Username":"Agent03@gmail.com","PriorityNumber":0},{"Username":"Agent04@gmail.com","PriorityNumber":0},' +
    '{"Username":"Agent05@gmail.com","PriorityNumber":0},{"Username":"Agent06@gmail.com","PriorityNumber":0},' +
    '{"Username":"Agent11@gmail.com","PriorityNumber":2}]}';

//wrapper class
public class JSON2Apex
{
    public String DateModifiedUtc { get; set; }
    public List<AgentInfoList> AgentInfoList { get; set; }
}
public class AgentInfoList
{
    public String Username { get; set; }
    public String PriorityNumber { get; set; }
}
public static JSON2Apex parse(String json)
{
    return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
}

public WSController()
{
    info = (JSON2Apex)parse(jsonStr);

}

public void priorityFilter()
{
    //loop through the info.AgentInfoList and pull out all of the records with a Priority number of 0.
    for (Integer i = 0; i < Info.AgentInfoList + 1; i++)
    {
        if (Info.AgentInfoList.PriorityNumber == 0)
        {
            return AgentInfoList.PriorityNumber;

        }
    }
}
}

visualforce page pulling out the priority and email:
<apex:page controller="WSController" >

Agent Call Distribution

Below is the current priority that Five9 will attempt to distribute new inbound phone mail leads. Loan Specialists high on the list are more likely to be offered a new sales call.

List last updated: {!info.DateModifiedUtc}

<apex:pageBlock >
    <apex:pageBlockTable value="{!info.AgentInfoList}" var="AgentInfo">
        <apex:column headerValue="Priority">

            <apex:outputField value="{!AgentInfo.priorityNumber}"/>
        </apex:column>
        <apex:column headerValue="Agent Email">
            <apex:outputText value="{!AgentInfo.Username}" />
        </apex:column>
    </apex:pageBlockTable>
</apex:pageBlock>

A: My suggestion here is to add a styleClass conditionally to your <apex:outputField> tags, and define a class that sets the background-color. Something like:

<apex:outputText styleClass="{!IF(MOD(agentInfo.priorityNumber, 2) = 0, 'grey', '')}" />


text:
Q: Why CPU usage of my Asp.net often is about 25% I have a ASP.Net project and many reports.Some of my reports have heavy calculation that I calculate them in memory using Linq. When I test this reports on my client CPU usage is about 25%.

My question is why cpu usage does not increase to 80% or more?
When I publish this project on the server does it has this behaviour?

A: You have 4 cores (or 2 hyper-threader cores), meaning each single thread can take up to 25% of the total computing power (which is shown as 25% CPU in the Task Manager).
Your calculation is probably single threaded.

A: Can you possibly break your calculation into several threads? That'll spread the load across the cores of your CPU a little more evenly.


text:
Q: overheating problem with ubuntu, lubuntu and point mate in my netbook medion akoya e1222 Hello my name is Alex and I have a medion netbook a E1222 with a intel Atom N450 and 2gb of ddr2 ram and a intel Gma 3150 and when I installed ubuntu 10.04, 12.04, 13.04, lubuntu 13.04 and point linux mate it overheats to 78° c. I tried everything cleaning fans, installed mate, I installed google chrome and desinstalled firefox. I installed lubuntu the forums tell my that is a low resources OS but every time I have overheating problems. What can I do. I want to use linux i hate windows. Please help me.

A: 78 C is not overheating. According to the Intel thermal guidelines for the chip, 100 C is the maximum allowed temperature. If 78 C is the highest you are seeing, you are fine.
These netbooks are great, but have limitations. Low-power chips will generate heat, especially if you are doing a lot of intensive things that can add up: having lots of browser tabs open, downloading large files or a lot of small files in a row, watching a lot of YouTube videos in a row without a break, etc. Expect the temperature to go up when more tasks are given to the processor. Browser tabs in particular use way more resources than many people think.
I run several distros on a Lenovo S-10 with an N450 and 2 GB ram. Performance has been great with Unity through 12.10. Unity on 13.04 ran well enough, but was a little slow; so for 13.04 I use Lubuntu on that machine. My boot temperatures are in the low-60's, but going up to the 70's or even the 80's is normal. Try to close things and give the processor a break when that happens.


text:
Q: require_once works without include path I have file 1.php having a require_once for 2.php (both of them are in different folders). The issue I am having is that 1.php seems to magically include 2.php since the path for 2.php is not in 1.php. Just to be sure, I even added a set_include_path('.') before the require_once '2.php', but it still works... Is there something obvious I am missing or is this plain weird??
Edit:
//-- file 1.php
//-- long list of requires...
set_include_path('.');
echo get_include_path();
require_once '2.php';

The above works fine while 1.php and 2.php are in different folders.

A: There is some include magic in PHP, i've met it before.
Something autoload related, I believe.
It always looks in the folder where file with running class resides

A: Try echo get_include_path() after you set your empty include path, it may be set somewhere else (like in the web server config file).

A: Long shot but maybe one of the other included files changed the current working directory:
<?php
echo 'cwd at the beginning of 1.php: ', getcwd(), "\n";
//-- file 1.php
//-- long list of requires...
set_include_path('.');
echo 'include_path: ', get_include_path(), " \n";
echo 'cwd: ', getcwd(), "\n";
require_once '2.php';

A: For the sake of argument, if you put a 2.php in the same location as 1.php does the new file get included instead of the old one?
Can you tell use what the value of your open_basedir is?

A: Perhaps you have a file with the same name as file 2 in the path of file 1.


text:
Q: Unable to overwrite the session variable in express I am using a ajax call to set a session variable, like:
 $.ajax({
           url: "url", -- a call to node layer
           type: 'GET',
           success: function (response) {

           }

       });

In node layer , i am doing an API call to set the new session value , like:
getxxx:function (req, res){

        var options = {};
        var self=this;
        options.headers = {};
        options.headers['Authorization'] = req.session.Authorization;
        options.headers['loginId'] = req.session.userName;
        var data={};

        proxyAPI.getData(common.getEndpointURL("XXX", req.session.userName), {}, options, function(err, response, statusCode){
            data.xxx = response;
            if(data.xxx && data.xxx.count) {
                req.session.count = data.xxx.count;
                req.session.save();

            }
        });

    },

My App.js looks like this:
app.use(sessionexpress({
        secret: 'secretKey',
        cookie: {
            maxAge: config.timeout,
            secure: config.sslEnabled
        },
        rolling: true,
        saveUninitialized: true,
        resave: true,
        store: new MemcachedStore({
            hosts: [config.sessionStore.uri],
            secret: config.sessionStore.secret
        })
    }));

Scenario:
In the call back function, I need to set the updated value from the API layer to the session variable.
Purpose is to use the value (req.session.count) in another page.
The problem is :
When i try to access the req.session.count variable in another page , the value doesn't show the updated value instead shows the value assigned at app startup.
What Am I doing wrong in this?
Note:
If i change the session variable without any API calls , like this :
req.session.count = 100;
req.session.save();

I am able to get the new session value (i.e 100) in other pages !


text:
Q: Drawing a line segment on a space that wraps toroidally I have a 2D space of angles [0, 2pi] x [0, 2pi] which wraps around, with toroid like topology (the horizontal edges correspond to each other, as do the vertical ones). I have two points in this space, and I would like to draw a line segment between those two points.
In some cases, this line segment is the obvious line segment, from one point to the other. In other cases, the line segment is supposed to "go around the edge" instead of going "the long way, through the middle":
+--------+
|        |
|  A--B  |
|        |
+--------+

+--------+
|        |
|-A    B-|
|        |
+--------+

While these cases are moderately easy to handle, there is one case that is really vexing for me and which my code so far does not handle correctly:
+-----------+
|        /  |
|       B   |
|           |
|  A       /|
| /       / |
+-----------+

I.e. if the line wraps around both directions, it sometimes wraps around the opposite corner. I'm not entirely sure if there are more of these tricky cases.
The only algorithm I've come up that works reliably so far is to calculate the midpoint as (A + B) / 2 while making appropriate use of the modulo arithmetics, draw a dot at this position, and then recursively subdivide the left and right intervals similarly, until the distance between the dots is less than a single pixel. Obviously, this is not going to be very fast.
My other approach was to detect (separately for x and y) whether the short distance is direct or around the edge, and then either draw one line segment or two. This does not handle the third case correctly, unless the line is divided in two and the midpoint lies on the segment that is in the lower-right corner in the example image. I'm not sure how to detect this efficiently, or how to calculate the position of the midpoint, as simply the point in the half does not always work, it might end up at the edge together with one of the endpoints, if their respective distance from the edge is not equal.
Is there a better algorithm? Is there an obvious solution that I'm not seeing? I'm not even sure how to google for this problem. I don't want to implement my own line rasterization algorithm, I would just like to break this problem to Euclidean straight lines and draw these using OpenGL or GDI or whatever.
My code so far is:
void Draw_WrappedSegment(float f_x0, float f_y0, float f_x1, float f_y1)
{
    const float s = 2 * f_pi;
    f_x0 = fmod(fmod(f_x0, s) + s, s);
    f_y0 = fmod(fmod(f_y0, s) + s, s);
    f_x1 = fmod(fmod(f_x1, s) + s, s);
    f_y1 = fmod(fmod(f_y1, s) + s, s);
    // make sure the coordinates end up being positive and modulo 2pi

    float f_ydist0 = fabs(f_y0 - f_y1);
    float f_ydist1 = fabs(fmod(f_y0 + s - f_y1, s));
    float f_ydist2 = fabs(fmod(f_y1 - f_y0 + s, s));
    float f_xdist0 = fabs(f_x0 - f_x1);
    float f_xdist1 = fabs(fmod(f_x0 + s - f_x1, s));
    float f_xdist2 = fabs(fmod(f_x1 - f_x0 + s, s));
    //     0                        2pi                       4pi
    //p1'' |     p0             p1   |     p0'            p1'  |
    //            <---f_dist0--->
    //                           <-f_dist1->
    // <-f_dist2->

    const float f_epsilon = 1e-3f; // sometimes the modulo causes an error and even though the díst 0 and dist 2 should equal, dist 2 is slightly smaller
    if(f_xdist0 <= f_xdist1 + f_epsilon && f_xdist0 <= f_xdist2 + f_epsilon) {
        if(f_ydist0 <= f_ydist1 + f_epsilon && f_ydist0 <= f_ydist2 + f_epsilon) {
            MoveTo(f_x0, f_y0);
            LineTo(f_x1, f_y1); // the "short" way in both directions
        } else {
            float f_sign = (f_y0 < f_y1)? 1 : -1; // swap the lower and upper edge if the points are not sorted by y
            MoveTo(f_x0, f_y0);
            LineTo(f_x1, f_y1 - f_sign * s); // from point 0 to the lower edge
            MoveTo(f_x1, f_y1);
            LineTo(f_x0, f_y0 + f_sign * s); // from point 1 to the upper edge
        }
    } else {
        if(f_ydist0 <= f_ydist1 + f_epsilon && f_ydist0 <= f_ydist2 + f_epsilon) {
            float f_sign = (f_x0 < f_x1)? 1 : -1; // swap the left and right edge if the points are not sorted by x
            MoveTo(f_x0, f_y0);
            LineTo(f_x1 - f_sign * s, f_y1); // from point 0 to the left edge
            MoveTo(f_x1, f_y1);
            LineTo(f_x0 + f_sign * s, f_y0); // from point 1 to the right edge
        } else {
            float f_sign_x = (f_x0 < f_x1)? 1 : -1; // swap the left and right edge if the points are not sorted by x
            float f_sign_y = (f_y0 < f_y1)? 1 : -1; // swap the lower and upper edge if the points are not sorted by y
            MoveTo(f_x0, f_y0);
            LineTo(f_x1 - f_sign_x * s, f_y1 - f_sign_y * s); // from point 0 to one edge
            MoveTo(f_x1, f_y1);
            LineTo(f_x0 + f_sign_x * s, f_y0 + f_sign_y * s); // from point 1 to the other edge
        }
    }
}

A: Instead of working with just the square [0, 2pi] x [0, 2pi], try tiling the space [-2pi,4pi] x [-2pi,4pi] with nine copies of this square (like a tic-tac-toe board).  Place A in the center square, and then place copies of B (translating the coordinates by ±2pi as required ) in each of the nine squares.  Choose the copy of B that is closest to A, and then draw the line from A to that copy of B.  This line may have more than one segment as it travels through the squares.  Just "untranslate" these segments back to the central square and you will have the diagram you want.