How should I secure a corporate wireless network?

Question: We are implementing a new WiFi network at my work, and I am trying to think through a design of the security for the network.
Use case 1: guests. We will have a captive portal setup, guests will accept an acceptable use policy and will be restricted to only the Internet, no access to LAN. Simple enough, we will let the firewall block dangerous ports and not much to worry about since they can't touch our primary network.
Use case 2: employees with BYOD and company owned laptops that might spend months offsite before being brought in to the office. Mix of Windows and OSX. They will authenticate with WPA2-Enterprise to our AD/RADIUS. Is there a good way to give these folks secure LAN access to internal servers?
My thought was that just giving these folks unrestricted access to the LAN is problematic. If they are domain-joined, they will eventually receive security updates from WSUS, but not necessarily before they connect. Anti-Virus is also not guaranteed. With the wired network we have in place now, this is minor, but I can see BYOD growing with the addition of a wifi network, particularly for our large crop of summer interns.
I have looked into Microsoft Network Access Protection to enforce security settings and quarantine non-compliant devices, but I am not sure how it will work with OS X (the only agent I could find, the UNET one, has some broken links on the website and pricing is unclear). It also seems to be pretty complex.
Is this overkill? In the real world, how do others handle this scenario? Is there a simpler Network Access Control solution folks like?
Comment: I've got an answer for this, but it'll have to wait till I get home tonight.
Comment: Hi @Tom O'Connor, I'd still be happy to hear your thoughts on this.
Comment: Ahh.  I forgot.  I'll have a think tonight.  I do think the accepted answer is pretty much spot on, but I'll see if there's anything missed.
Answer: I have a School District Customer who has a similar setup to what you're talking about.

Public access is run over a separate VLAN with dedicated Linux-based DHCP and DNS and no access to the corporate network except thru the edge firewall (effectively putting the public wifi "outside" the firewall-- so VPN access, and access to DMZ-hosted servers works from the public wifi). The "Child Internet Protection Act" requires that we heavily filter this connection, so the public gets the most restrictive policy. (If I could run this over a dedicated physical LAN and separate Internet connection I would. Money says otherwise.)
Student-owned devices authenticate to WPA-RADIUS and have access to the Internet. DHCP and DNS are provided by LAN-based servers. AP-based firewall rules (we are running Ruckus ZoneFlex APs, which have a Linux-based iptables firewall in each AP) prevent access to the LAN except for specific services (HTTP to the "learning management system" and a few other web servers). There is a default deny policy for access to the LAN subnets.

I feel like there is a strong distinction between Employee-owned and District-owned devices, from a management policy perspective, so I reflected that in the operational configuration.

Employee-owned devices are exactly the same as student, except that there's a different Internet filtering policy and employees get RDP access to the LAN subnets where desktop PCs live. There is still a default deny policy for access to the LAN subnets. The number of services offered to employee-owned devices by LAN-based servers is very limited and, frankly, I want to keep it that way. I will try my hardest to insure that we keep a default deny policy w/ exceptions between the "BYOD" subnets and the LAN subnets. I've had some disagreements with people about this, but I am of the opinion that "BYOD" devices can't ever be trustworthy to the degree that District-owned devices can.
District-owned devices, including laptop computers, get their own SSID with WPA-RADIUS authentication for members of the "Domain Computers" group only. There is a wide open policy of access to the LAN. No users have Administrator rights on their computers, and I'm reasonably happy in deluding myself into thinking that the devices are mostly trustworthy. If I were a bit more paranoid I'd deploy Bitlocker using the TPMs on all the laptop computers to prevent offline modification of the OS by the users. That last bit w/ full disk encryption, would be all that I would need to make me feel reasonably certain that the district-owned devices are at least somewhat trustworthy. We have only Windows clients but, for a Mac environment, I believe suitable similar capabilities to guarantee integrity of the trusted computing base from boot are available.

We don't have machines that stay off-site for months. If I did, I'd host an Internet-facing WSUS server and have the clients look there for updates even when they're off-site. Depending on your anti-virus software you may be able to get it to function this way, too.
It's not that I think NAC / NAP is "overkill"-- I think it's a fundamentally flawed idea. Some people argue belt-and-suspenders as being a reason to use NAC / NAP, but I have a hard time trusting an untrusted client to assess its own "health". I'm all for performing vulnerability scans against machines from a trusted host, but asking an untrustworthy host to make a trustable statement about itself seems very flawed to me.
Comment: That's interesting. I hadn't thought of configuring RADIUS to only allow authentication for Domain-joined devices, I did not know that was possible. We might be able to get away with just a guest network and a network for domain-joined computers.
Comment: I love using RADIUS to restrict devices / users to given SSIDs. Our Ruckus APs let us use a RADIUS attribute to allow us to handle this using plain-vanilla IAS on Windows Server. It's nice.
Answer: Why should the BYOD be any different for users when inside your premises than outside? If it were me I'd set up the WIFI as it's own network with internet access and use VPN to access the restricted stuff.
Comment: Biggest reason is complexity. It would make users log in twice. I'm not sure what security we would gain above a VLAN and putting the BYOD devices in a restricted firwall zone, either. Both are encrypted tunnels from an untrusted network to ours, and to lock down access we would need to put in place firewall rules for either the VPN or the WiFi APs.


How to match a tag not containing another one?

Question: I want to style a ul/li differently when it does not contain another tag ul/li.
UPDATED as I understand my question was misleading, I added the full scope explicitly (sorry about that).
The fiddle is http://jsfiddle.net/stephanedeluca/v7nxB/
The html is as follows:
Two-level nesting:

Grain :

Baisse du rendement

Sénescence plus rapide la plante

Sensibilisation accrue à la fusariose des tiges

Baisse du rendement

Sénescence plus rapide la plante

One level:

Baisse du rendement

Sénescence plus rapide la plante

Sensibilisation accrue à la fusariose des tiges

The current CSS (lessCSS code actually) is as follows:
ul {
    &>li {
        &:after {
            content: " ;";
        }
        &:last-child:after {
            content: ".";
        }

        &>ul {
            li:after {
                content: " (end)";
            }
            li:last-child:after {
                content: " (final end)";
            }
        }
    }
}

The result it produces is as follows:
Two-level nesting:

   o Grain
    — Baisse du rendement (end)
    — Sénescence plus rapide la plante (end)
    — Sensibilisation accrue à la fusariose des tiges (final end)
    ;
   o Baisse du rendement ;
   o Sénescence plus rapide la plante.

One level:
   o Baisse du rendement ;
   o Sénescence plus rapide la plante ;
   o Sensibilisation accrue à la fusariose des tiges.

One level is ok, but the two-level is not what I want.
Two-level should be as follows while one-level stays still:
   o Grain
    — Baisse du rendement ;
    — Sénescence plus rapide la plante ;
    — Sensibilisation accrue à la fusariose des tiges.
    (final end)
   o Baisse du rendement ;
   o Sénescence plus rapide la plante.

As you may understand, I'll replace (final end) by empty string once the CSS works.
Any idea?
UPDATE 2: I just found an interim work around with the help of a class (not great, but it works) (the fiddle)
Comment: `&:last-child:after { content: ". (final end)";}`?
Comment: Will there be arbitrary levels of nesting? If not, you should be able to just [swap the top-level `content` styles with the nested ones](http://jsfiddle.net/BoltClock/Qup9s/2).
Comment: @BoltClock: In my very case, I won't go into more additional level. So the two-level ul is what I need to solve.
Comment: OK, I've posted it as an answer.
Comment: I saw my question was not that good, I have updated it (including the fiddle).
Comment: Could you post a new fiddle?
Comment: Sure, I've just updated it.
Comment: I don't think there's any other workaround besides the one you have (adding a class).
Answer: You need something like this,
Check this demo jsFiddle
Result
o Grain
    — Baisse du rendement ;
    — Sénescence plus rapide la plante ;
    — Sensibilisation accrue à la fusariose des tiges.
    (final end)

CSS
ul {
    &>li {
        &:after {
            content: " ;";
        }
        &:last-child:after {
            content: "(final end)";
        }

        &>ul {
            li:last-child:after {
                content: " .";
            }
        }
    }
}

100% Worked
Comment: Nope. Compare your result with the question.
Comment: @BoltClock i update my answer check now this is worked.
Comment: Now I'm on the fence - the `content: " (end)"` part seems to be missing completely. It might be important; I wouldn't recommend throwing away arbitrary values unless absolutely necessary.
Answer: There is an interim work around I've found which takes advantage of a separate class as follows:
Two-level nesting:

Grain :

Baisse du rendement

Sénescence plus rapide la plante

Sensibilisation accrue à la fusariose des tiges

Baisse du rendement

Sénescence plus rapide la plante

The class I named "compact" is there to tell not to apply the rules that handle ul/li suffix.
The CSS becomes as follows:
ul {
    &>li {
        &:after {
            content: " ;";
        }
        &:last-child:after {
            content: ".";
        }

        &.compact:after {
            content: "";
        }
    }
}

The inconvenient comes from the fact you need to add information to your data source which does not bear true semantic. But it works for now.
Hope someone might found a better way to proceed


Custom JSON fields with Jackson in response

Question: I have some RESTful WS created with Spring Boot and one of some endpoint's methods returns instance of some class which will be converted then into JSON using embedded Jackson library. Jackson converts to JSON every field, even if some fields are null. So in the output it will look like:
{
    "field1": "res1",
    "field2": "res2",
    "field3": null
}

I want to ignore some field it the output in particular cases. Not everytime, at some cases. How to do it?
Comment: put `@JsonInclude(Include.NON_NULL) ` on the class
Answer: To suppress serializing properties with null values using Jackson >2.0, you can configure the ObjectMapper directly, or make use of the  @JsonInclude annotation:
mapper.setSerializationInclusion(Include.NON_NULL);

or:
@JsonInclude(Include.NON_NULL)
class Foo
{
  String field1;
  String field2;
  String field3;
}

Alternatively, you could use @JsonInclude in a getter so that the attribute would be shown if the value is not null.
Complete example available at How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson
Answer: To exclude null values you can use
@JsonInclude(value = Include.NON_NULL)
public class YourClass {
}

And to include customised values you can use
public class Employee {
  private String name;
  @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = DateOfBirthFilter.class)
  private Date dateOfBirth;
  @JsonInclude(content = JsonInclude.Include.CUSTOM, contentFilter = PhoneFilter.class)
  private Map<String, String> phones;
}

public class DateOfBirthFilter {

  @Override
  public boolean equals(Object obj) {
      if (obj == null || !(obj instanceof Date)) {
          return false;
      }
      //date should be in the past
      Date date = (Date) obj;
      return !date.before(new Date());
  }
}

public class PhoneFilter {
  private static Pattern phonePattern = Pattern.compile("\\d{3}-\\d{3}-\\d{4}");

  @Override
  public boolean equals(Object obj) {
      if (obj == null || !(obj instanceof String)) {
          return false;
      }
      //phone must match the regex pattern
      return !phonePattern.matcher(obj.toString()).matches();
  }
}

Took reference from https://www.logicbig.com/tutorials/misc/jackson/json-include-customized.html
Answer: At the top your class add the NON_NULL Jackson annotation to ignore null values when receiving or sending
@JsonInclude(value = Include.NON_NULL)
public class SomeClass {
}


power of a matrix that has a very "big" entry on a column

Question: Given a matrix $A = (a_{i,j}) \in \mathbb{Z}^{n,n} $. We say the entry $a_{r,k} $ on the $k$-th column is big if $a_{r,k} >  \frac{1}{2} \sum_{i=1}^n\left|a_{i,k}\right| + 1$ (so that $|a_{r,k}|$ is larger than the sum of the remaining column entries' absolute values plus $1$).
For example, take $A = \begin{pmatrix}1&1\\0&1\end{pmatrix}$, then the first column of $A^m$ does not have a big entry for any $m$, while the second column of $A^m$ will have a big entry if $|m|>3$.
I am looking at the following matrix, $M = \left(\begin{array}{cccc}
0 & 0 & 0 & -1 \\
1 & 0 & 0 & 2 \\
0 & 1 & 0 & 0 \\
0 & 0 & 1 & 2
\end{array}\right)$.
I am trying to show that there exists an $m \in \mathbb{Z} $ such that the last column of $M$ has a big entry. I tried to use Matlab (and other matrix calculators) to compute the power of this matrix, but the number got really big very quickly. I was wondering if there is a way to show this without computing the power of the matrix. Has something like this been studied before?
Any insight/alternative approach for this question will be really appreciated. Thank you.
Comment: How about using eigenvalue decomposition(Diagonalization), $A^m=SJ^mS^{-1}$, then calculating $A^m$ in terms of $m$, get the last column where each entry will be in terms of $m$, and see/analyze to check presence of big entry?
Comment: The matrix is a companion matrix. Perhaps that helps computing its powers.
Comment: Thank you both. Unfortunately, the entries of $S^{-1}$ are quite long, so it is a bit messy to do calculations with it
Comment: Thank you for checking this.
Answer: As @lhf mentioned that this is a Companion Matrix, we can use it to simplify calculations so that we can only compute only the last column(or any column) only. This will save us from computing power of matrix.
For a Companion matrix $A$, if matrix $A$ is diagonalizable then $A = V^{-1}DV$ where,
$$
D = \begin{bmatrix}
    \lambda_1 & 0 & \dots & 0 \\
    0 & \lambda_2 & \dots & 0 \\
    0 & 0 & \dots & \lambda_n \\
\end{bmatrix},
V = \begin{bmatrix}
    1 & \lambda_1 & \lambda_1^2 & \dots & \lambda_1^{n-1} \\
    1 & \lambda_2 & \lambda_2^2 & \dots & \lambda_2^{n-1} \\
    \vdots & \vdots & \vdots & \ddots & \vdots \\
    1 & \lambda_n & \lambda_n^2 & \dots & \lambda_n^{n-1} \\
\end{bmatrix}
$$
Here, $V$ is Vandermonde matrix, $L=V^{-1}$ is the inverse vandermonde matrix and $\lambda_i$ are eigen values of $A$. There are analytical ways to compute $L$, and there seems to be packages/implementations available for that in MATLAB and other languages.
The $k^{th}, 0\le k<n$ column of $A^{m}$ can be directly computed as:
$$
C_{k} = \begin{bmatrix}
L_{1,1}\space \lambda_1^{m+k} + L_{1,2}\space \lambda_2^{m+k} + \space \dots \space + L_{1,n}\space \lambda_n^{m+k} \\
L_{2,1}\space \lambda_1^{m+k} + L_{2,2}\space \lambda_2^{m+k} + \space \dots \space + L_{2,n}\space \lambda_n^{m+k} \\
\vdots \\
L_{n,1}\space \lambda_1^{m+k} + L_{n,2}\space \lambda_2^{m+k} + \space \dots \space + L_{n,n}\space \lambda_n^{m+k} \\
\end{bmatrix}, \quad
c_{r,k} = \sum_{i=1}^{n}L_{r,i}\lambda_i^{m+k}
$$
In MATLAB pseudocode, this would look something like
<code>% E is n-by-1 vector of eigen values
% L is the inverse vandermonde matrix
% k (0 <= k < n) is column id

Ck = L * (E.^(m+k))
Clast = L * (E.^(m+n-1))  % last column
</code>
Comment: Thank you for your time looking into this!


What does "gliss 2x" mean here?

Question:
What does "gliss 2x" mean here?
Answer: I can just barely see the "common time" symbol at the left of your image, which denotes 4/4. The 2x is followed by parentheses which encapsulate the last rhythmic figure in the bar. This figure is an alternate version of playing beat 4 (otherwise the bar would have five beats in it).
This means, assuming there are repeats elsewhere in this excerpt, that the first time you play this measure, you play beat 4 as a quarter note with a gliss as indicated. The second time (2x), instead of playing that quarter note with gliss, you play the s s e figure marked in parentheses. There is no gliss indicated on this figure.
Answer: Two seperate things.  "Gliss" applies to the octave B in normal size notes.  The smaller notes, in brackets, are to be played as an alternative on the second pass.  We assume the section is repeated.

What does "gliss 2x" mean here?


CSV-like data in script to Pandas DataFrame

Question: I've got a list of cities with associated lon,lat values that I'd like to turn into a DataFrame, but instead of reading from a CSV file, I want to have the user modify or add to these city,lat,lon values into a cell in an IPython notebook.  Right now I have this solution that works, but it seems a bit ugly:
import pandas as pd
sta =  array([
        ('Boston',          42.368186, -71.047984),
        ('Provincetown',    42.042745, -70.171180),
        ('Sandwich',        41.767990, -70.466219),
        ('Gloucester',      42.610253, -70.660570)
        ],
        dtype=[('City','|S20'), ('Lat','<f4'), ('Lon', '<f4')])

# Create a Pandas DataFrame
obs = pd.DataFrame.from_records(sta,index='City')
print(obs)
                    Lat        Lon
City
Boston        42.368187 -71.047981
Provincetown  42.042744 -70.171181
Sandwich      41.767990 -70.466217
Gloucester    42.610252 -70.660568

Is there a clearer, safer way to create the DataFrame?
I'm thinking that folks will forget the parenthesis, add a closing ',' on the last line, etc.
Thanks,
Rich
Comment: "add a closing ',' on the last line": if you mean the `Gloucester` line, then that's okay.  In fact, sometimes it's even recommended!
Answer: You could just create a big multiline string that they edit, then use read_csv to read it from a StringIO object:
x = """
City, Lat, Long
Boston, 42.4, -71.05
Provincetown, 42.04, -70.12
"""

>>> pandas.read_csv(StringIO.StringIO(x.strip()), sep=",\s*")
           City    Lat   Long
0        Boston  42.40 -71.05
1  Provincetown  42.04 -70.12

Of course, people can still make errors with this (e.g., inserting commas), but the format is simpler.


How do I control bar colors in plot_ly with reactive data in shiny

Question: I am creating an R shiny dashboard and data is being filtered. Reactive data is processed. When different selections are made, the colors in the bar chart change and aren't consistent. The colors signify Good, Neutral, Bad, and not available so the order matters. Full shiny app is at: https://stoltzmaniac.shinyapps.io/medicare_data/ and the code is at: https://github.com/stoltzmaniac/Medicare/tree/master/shinyApp (both server.R and ui.R) Plotly portion looks like:
plot_ly(df_filtered, x = ~Score, y = ~Hospital.Name,
        type = "bar", color = ~Compared.to.National, colors = FORMAT_CHART_COLOR_LIST,
        hoverinfo = 'text', text = ~paste('State: ', State,
                                          '
 City: ', City,
                                          '
 Score: ', Score))

Answer: The plotly help says it here (scroll down a bit). Define a named color vector:
global_colors <- setNames(rainbow(nrow(data)), data$brand) # this maps brand to color

I suppose your data is
data <- head(mtcars)
data$brand <- rownames(data)

Then, the plot is created as
plot_ly(data, x = ~brand, y = ~hp, type = "bar", color = ~brand, colors = globalcolors)

(Note there's no ~ before globalcolors because that's the global color vector)
Hope this helps :)
Comment: Thanks @shosaco , I placed `global_colors` as the `reactiveVal` like you mentioned within the global.R file. However, when I used it within plot_ly I received this error: "Error: no applicable method for 'toPaletteFunc' applied to an object of class "AsIs" and I have tried several methods to fix but can't seem to get it to work. The rest of the app still works
Comment: So, just to be clear, with my prior syntax this would be it?    `global_colors <- reactiveVal(setNames(rainbow(nrow(df)), df$Compared.to.National))`   And then the:  `df_filtered$color <- global_colors()[df_filtered$Compared.to.National]`  Then finally:
`plot_ly(df_filtered, x = ~Score, y = ~Hospital.Name,
        type = "bar", color = ~Compared.to.National, colors = ~I(color),
        hoverinfo =`
  Correct?
Comment: try `color = ~I(color)` (and no `colors` argument, which only tells plotly which variable it should use to determine different colors. You already did that by filling the color column).
Comment: Thanks, seems like it may be one step closer... however, now it all simply shows up as one color (bright red in my case) - `plot_ly(df_filtered, x = ~Score, y = ~Hospital.Name, type = "bar", color = ~I(color)` - The legend also disappears when I do that. If I was able to setup the `Compared.to.National` and create a new column right out of the gate with an exact color column `color` would that work and there's perhaps just a way to change the legend text? Obviously, not a great solution but could get the job done
Comment: Sorry for the confusion, the plotly helpt says it very clear, I updated my answer accordingly (is was even a bit easier)


Integrate RestKit pod or source into project that has another framework with AFNetworking baked in

Question: I have a framework that has AFNetworking baked into it... I would love to be able to use RestKit but there are obvious duplication problems for the linker because the RestKit source uses AFNetworking too...
Does anyone want to present to me a nice method to allow the two to coexist? Since I can't do much about the other framework I would like to have a walk through of how to get Restkit rockin... thanks!
Answer: The typical method in the ObjC realm is to distribute your framework using http://cocoapods.org to manage the dependency chain for you (and eliminate potential duplication of something like AFNetworking).
Here's a nice read: http://blog.chariotsolutions.com/2012/07/using-cocoapods-to-manage-private.html
Answer: You can use the following Cocoapods
pod 'RestKit', '~> 0.20.0'

Check the following link for more info
Answer: The RestKit framework in turn depends on AFNetworking also.
So, you don't have to install that separately, just install RestKit using pods like this:
platform :ios, '7.0'

pod 'RestKit', '~> 0.24.0'


XNA StreamReader/Writer how to read/write in different lines?

Question: I'm trying to write a simple .txt via StreamWriter. I want it to look like this:

12
26
100

So simple numbers. But how do I tell the Reader/writer in which line to write or read.
http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx
Here it says that ReadLine() reads a line of current the Stream. But how do I know which line it is. Or is it always the first one?
I want to read the numbers, modify them and then write them back.
Any suggestions?
Thanks in advance!
Answer: A reader is conceptually a unidirectional thing, from the start (or more accurately, the current position in the stream) to the end.
Each time you read a line, it is simply buffering data until it finds a new line; it doesn't really have the concept of a current line (or moving between lines).
As long as the file isn't massive, you should be OK reading the entire file, working on a string (or string array), then saving the entire file; inserting/removing text content is otherwise non-trivial (especially when you consider the mysteries of encodings).
File.ReadAllLines and File.WriteAllLines may be easier in your scenario.
Answer: I think the only way is to read all lines in array (or any other data structude, i.e. list), modify and write it back to file.
Maybe xml will be better for your purposes?


Number of Regions formed in a circle- Planar graphs, Euler's formula

Question: There are n ≥ 4 points on a circle. Each pair of them is connected by a chord such that no three of these chords intersect at the same point inside the circle. What is the number of regions formed inside the circle?
I am a little confused on how to even begin with this problem. How exactly am I supposed to find where and how many intersections there are between the chords? This will allow me to split up the circle into regions. Along with this, how exactly will we find the number of vertices. I will need this information to apply Euler's formula and get the number of faces. But I am a little confused on how to do that.
Any help?
Answer: This is OEIS $A000127$: $$a_n={n\choose 4}+{n\choose 2}+1={n^4 - 6n^3 + 23n^2 - 18n + 24\over24}$$
It starts surprisingly by powers of $2$ ($1$, $2$, $4$, $8$, $16$), but this is treacherous.
I particularly like the proofs given here, one of which relies precisely on Euler's formula (you can count the number of vertices and edges of the picture, and hence obtain the desired number of faces).


Javascript syntax using await Promise.all

Question: I am trying to understand the below code/syntax which uses await Promise.all;
How is the array getting assigned from the endpoint response ?
const getState = async (code) => {
    try {
      const [
        {data: dataResponse},
        {data: stateDistrictWiseResponse},
        {data: statesDailyResponse},
        {data: stateTestResponse},
        {data: sourcesResponse},
        {data: zonesResponse},
      ] = await Promise.all([
        axios.get('https://example.org/data.json'),
        axios.get('https://example.org/state_district_wise.json'),
        axios.get('https://example.org/states_daily.json'),
        axios.get('https://example.org/state_test_data.json'),
        axios.get('https://example.org/sources_list.json'),
        axios.get('https://example.org/zones.json'),
      ]);
      console.log(stateTestResponse.states_tested_data);
    }
}

Comment: Array destructuring assignment
Comment: What exactly is the thing you cannot understand? Cause there's a lot going on here.
Comment: array + object destructuring
Comment: I am trying to understand how the JSON is finally being getting assigned within that array const []
Not trying to understand Promise.all
Answer: Promise.all converts an array of promises into an array of results.
axios.get returns a promise that, when resolved, returns an object with the shape { data: <result goes here>
Your code is destructuring those objects within the returned array.
Comment: Thanks a lot...We are pretty close. All I am trying to understand is once we get { data: }
then how exactly does it get assigned to the array...

Specifically, if you look at the next line, there is
console.log(stateTestResponse.states_tested_data)

I am confused as how stateTestResponse gets the value since it is on the right hand side  in the line {data: stateTestResponse}
Comment: That's exactly how destructuring works. Try looking at the MDN documentation for it?


How to load content depending on screen size without hiding using CSS?

Question: I have a responsive site.
Lots of content is hidden depending on screen size.
This slows down page speed. And on slow devices has a lot of content shifting whilst content is hidden/shown.
In drupal 7 I used browser cap, to detect whether the browser was mobile or desktop and was able to not show blocks/content without having to hide them via CSS.
Is there a way in Drupal 9 to only have content loaded for certain devices, rather than use breakpoints and css to hide content?
Thanks
Comment: This may be an exercise for your design and writing department, to find the right design so as not to be dependent on screen size, and the right amount of text to keep the user reading. I would avoid trying to tie this to every possible screen size, [that's will just be a maintenance nightmare](https://youtu.be/tzfHlEFd2Fk?t=1252).
Answer: https://github.com/serbanghita/Mobile-Detect/ lists a few Drupal modules in its README, one of the being Drupal 8/9 ready: Mobile Detect. Nice sets of features and even cacheability been taken care of.

PHP
<code>$md = \Drupal::service('mobile_detect');
$is_mobile = $md->isMobile();
$is_tablet = $md->isTablet();
</code>
Twig Extensions
<code>{% if is_mobile() %}
{% if is_tablet() %}
{% if is_device('iPhone') %}
{% if is_ios() %}
{% if is_android_os() %}
</code>
About the cache contexts:
By design, the "Internal Page Cache" core module assumes that all pages served to anonymous users will be identical, regardless of the implementation of cache contexts.
If you want to use the mobile_detect cache contexts to vary the content served to anonymous users, "Internal Page Cache" must be disabled, and the performance impact that entails incurred.
More info: https://www.drupal.org/docs/drupal-apis/cache-api/cache-contexts


Two dice throw probability

Question: We throw two conventional dice, and ask the probablity of the following event:

The main probability $p_m$ to compute is composed of two sub-events: first sub-event, having either of the two dice with a value of 1 or 4, and second sub-event: the two taking values 1 and 4 at the same time.

So I'm trying to compute the probability of either of these two sub-events occuring. My attempt:

First subevent: for a single die, the probability of either 1 or 4 is 1/6. For two dice, we have 36 outcomes, 6 ways (1,x) can occur, x can be any value, similarly 6 ways (4,x), and because we have two dice, both are multiplied by two, so finally the probablity of subevent one is: $$p_1=\frac{2*6+2*6}{36}\approx 0.66$$
For the second subevent: there are two ways 1 and 4 can occur at the same time, that is, (1,4) or (4,1) so $p_2 = 2/36 \approx 0.05$
Finally for the main event, $p_m = p_1+p_2 \approx 0.71.$ Is the estimation correct? Have I gone wrong somewhere with the composition of probabilities?

Note: we assume the two dice are indistinguishable.
Answer: You're counting event 2 in your event 1.
You are also double counting the cases where the 2 dice have the same value.
In your calculation for event 1 you said dice 2 can have any value (6 possible) after choosing 1 value for dice 1, this includes the cases where they are both equal.
By adding these probabilities twice (for 2 dice), you've doubly counted the probability that they are equal.
Note that letting dice 2 have any value in your calculation for event 1 means you also include the cases where one dice is 1 and the other is 4.
You can either subtract the intersection, or you can make up new independent events. Or you can split the events up into the possible cases.
I'll show you a solution using the classic definition of probability: satisfactory cases/total amount of possible cases
Event 1:
4 cases where dice 1 has value 1 and dice 2 has a value that isn't 1 nor 4.
4 cases where dice 1 has value 4 and dice 2 has a value that isn't 1 nor 4.
These 8 cases go both ways (swap the values of the 2) thus you have 2*8 = 16 cases like this.
There's also 2 cases where these dice share values. (both are 4 or both are 1)
In total 18 cases to satisfy the condition for event 1.
Note that none of these cases include the event that both values 1,4 are present at the same time.
Event 2:
1 case where dice 1 has value 1 and dice 2 has value 4
1 case where dice 1 has value 4 and dice 2 has value 1.
So you have 2 cases for event 2.
Note that these 2 cases can't possibly happen at the same time as the previous counted ones, they are disjoint cases, so now to get the total probability, you add all the cases that satisfy these conditions and divide by total amount of possible cases.
Divide by total amount of possible cases (6^2) and you get (18+2)/36 = 20/36.
Comment: Thanks for the answer, Im reading it now, to be clear:  I do not care which dice is 1 or 4 in event one, as long as one is either. That's why I thought I should double count.
Comment: By double counted I mean you counted the cases (1, 1), (4, 4) four times. there  are only 2 such cases. Your calculation double counts this because (2 * 6) already includes both these cases and then you add 2 * 6 together, giving you a count of 4 for those cases.
Comment: ah yes, by the way, in the second line of Event 1:, you meant to write: 4 cases where dice 1 has value 4 and .... , right?
Comment: Yes, oops. Fixed that now.
Comment: With two dice with 6 sides, you have 6 possible matching pairs (1, 1), (2, 2), (3, 3), (4, 4), (5,5), (6,6). The answer is thus simply 36-6 = 30.
Comment: To count the number of possible outcomes? You have 6 choices of a value for dice 1. Combine this with 6 choices of a value for dice 2. You can combine every value on dice 1 with all 6 values on dice 2. Thus you get 6*6=36 combinations. See the multiplication rule. If you wanted it with binomials you can simply do (6 choose 1) * (5 choose 1) = 6*5 = 30. (excluding 1 value from the choice for dice 2).
Comment: Thanks again. By the way, third line of Event 2:, why do we have 4? there are only two cases no? (1,4) and (4,1)
Comment: You're right, my bad, I messed up there. I forgot to think about the fact that those cases are identical if you reverse them. So I was double counting that.
Answer: The two events are not independent, and hence you cannot just add the probabilities of the two events; you also need to subtract the probability of the intersection of the two events.
Comment: +1. Moreover, you double counted several cases when calculating $p_1$ (namely (1,1) and (4,4))
Comment: Write alle possible outcomes in both events and find alle outcomes which are in both. This will be the intersection of the two events.

Two dice throw probability


What is the mechanism used to control how Drupal pages are rendered?

Question: I'm a Java programmer trying to get started with Drupal.  Specifically, I want to be able to create custom pages.  More specifically, I want to understand the nuts and bolts of how this is done (I'm an engineer; it's just my nature)  I have a little PHP experience and I've configured Drupal installations for years.  I'm aware of many of the modules that help make this process easier (such as the Views module), but again--I'm interested in working through the nuts and bolts myself.
I'm not specifically interested in creating new Drupal modules, unless that is the only way to create new pages in Drupal.  My primary interest is in being able to create a custom page.  Let me give a few examples:

I have a db of funny quotes.  I'd like to be able to use Drupal to display a selected quote AND HAVE COMPLETE CONTROL OVER THE PAGE LAYOUT (and again--not using an existing module; I want to understand the inner workings).  Don't ask why I'd want to use Drupal for this, or suggest alternate methods of accomplishing it.  It's a made up example to illustrate what I'm wanting to learn. :-)
This is a less made up example.  I'd like to create a "newsletter" where the site editors can select submitted content and customize layout (all in a custom UI) and then create a page with that content, one suitable for either viewing in a browser or printing.  Sort of a "desktop publishing" concept for Drupal.  Again, don't suggest ways of accomplishing this.  It's an example to illustrate what I'm wanting to learn.

Basically, I like Drupal's permissioning, modularity, and content management but I'd like to learn how to control display (as complete control over display as possible).  The problem is that I don't even know what topics to start learning.  Creating modules?  Themeing?  Something else?  What is the mechanism or system that I need to learn to be able to completely control how Drupal pages are rendered?
Corollary question: does such control (not limited to just a block or region, but including menus, headers, footers, and everything visible on the page) require modifying the Drupal code directly or can it all be done in the theme/module systems?
Answer: Aaron is right that you'd likely want to handle much of this at the theme layer. You'd want to familiarize yourself with how drupal handles templates.
As for the actual creation of a page in code, this page does a pretty good outline of a method. I've not done this myself, but it reads correctly.
You'll first want to understand how to build a module. The basics are, you need a mymodule folder, and a mymodule.module file and mymodule.info file. Anywhere you see a resource that says to use hook_some_function, you're going to replace hook with mymodule.
The nuts and bolts of the page above outline:
-- Implementing of hook_menu (in this instance, the module's name is starting_drupal_dev)
/**
* Implements hook_menu().
*/
function starting_drupal_dev_menu() {
  $items['starting_drupal_dev/custom'] = array(
    'title' => 'Custom page',
    'page callback' => 'starting_drupal_dev_custom',
    'access arguments' => array('access content'),
  );

  return $items;
}

-- Using the custom function starting_drupal_dev_custom to define how the page renders
/**
* Custom callback function.
*/
function starting_drupal_dev_custom() {
  $content['raw_markup'] = array(
    '#type' => 'markup',
    '#markup' => '
Hello world
',
  );

  return $content;
}

You could then assign your various database queries to variables in order to render them within #markup.
Again, I've not used this particular method myself, but it seems to me that you could at least use this as a starting point for what you're trying to do. Not sure whether or not you could combine this method with theme templates for layout or not. Maybe somebody else could chime in with regard to that.
As for your final question, NEVER (usually) HACK CORE. Handle everything in modules and themes.
Comment: To add to that, you can use your own modules to generate blocks/views with your own database queries by implementing things like hook_block_views and hook_block_info, as described at: http://drupal.stackexchange.com/questions/5582/easy-way-to-create-blocks-programmatically. You can also use hook_menu to build menus: http://drupal.stackexchange.com/questions/41570/create-a-menu-programmatically-in-drupal-7. In a really introductory sense, for your purposes, modules are for content/data and themes/theme templates are for presentation of that data.
Comment: I appreciate the link, but even the screenshot on the page shows the content appearing on a page created by Drupal.  It has the headers, menus, and the layout rendered by the system.  I'm wanting to render a page--not a block or region or any sub-element of a page.  I want to use Drupal's permissioning, modules, management systems, but I want to control *EVERYTHING* that's displayed.
Comment: That's simply a misunderstanding of how developing with Drupal works. The reason everything else on the page is rendered is because that is simply how they have their environment set up. They have a theme which is set to render regions, and blocks are assigned to them. You'd want to create your own theme, and I suppose define a single region for content. This markup would then be rendered within said region. I think that you are simply out of luck if you don't want to look into them development. Building a theme is exactly how you control the rendering of the overall page markup.
Comment: The sum total of these answers gives me a good starting point, I think. To clarify my previous comment: I meant I don't want to render *JUST* a block or region on a pre-defined form--I don't have some kind of prohibition on using blocks and regions, I just want more control over the UI than merely rearranging a limited palette of pre-defined elements.
Comment: So, to make sure I understand (because it seems I had a previous misconception): the themeing system is not limited to merely rearranging and reconfiguring existing elements like blocks and regions, but can also *define* them. So, if I want a page with a completely different structure, say no header/footer or menus for example, I can create a theme to do that?
Comment: You're close. The theming system doesn't, for the most part, rearrange/configure anything, or really define them. The hooks I discussed go in modules. The theme contains your base template, css, js, etc. The base outline of content/header/etc is defined with the theme's page.tpl.php file, and then you can have override templates for pages (if you don't want header on a page, for some reason), blocks, fields, views -- most things, really. There's also php included to conditionally display things like sidebars. You should really read through https://www.drupal.org/documentation/theme.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/38425/discussion-between-mrweiner-and-allen).
Answer: control over the layout is intended to be accomplished through the theme layer, so you'll want to learn theming to control display. Drupal.org provides a good starting place for learning theming (https://www.drupal.org/documentation/theme), though other resources may be found through learning services like https://drupalize.me.
This is a question with a very lengthy answer and the best thing I can do is point you towards the right resources. Best of luck and welcome to the Drupal community!
Comment: To be clear: the vast majority of the themeing resources that appear at the top of search results center around more of what I'd call "configuration".  Changing colors, configuring blocks, specifying which menus should show and where--in essence configuring the elements of an existing layout.  But does the themeing interface allow me to create an entire page from scratch?
Comment: Yes, though that is an unusual avenue to theming. You can either dig deeper into the core theming api and override page.tpl.php templates, or you could explore the Panels module family. Panels Everywhere in particular is something that you'll likely find useful.
Comment: I literally don't have enough characters on Stack Exchange to explain how to do this. The learning curve is STEEP (but worth it IMO).
Comment: I appreciate your comments, but I have a nagging feeling in the back of my head that we're speaking two different languages.  I'm not asking about modules that I'd find useful...


T-SQL WHERE clause - comparing column to itself fails on null columns

Question: I usually use a construct like this to apply filters to columns:
CREATE TABLE test(a int NOT NULL, b int NULL)
--insert some data
INSERT INTO test(a,b) values (1,1)
INSERT INTO test(a,b) values (1,NULL)

declare @a int
declare @b int
set @a = 1
--@b is null at this time

select * from test
  where a = @a
    and b = isnull(@b,b)

This only selects the first row.
For example, if this was a stored procedure and argument @b was null, I could specify its value to 'enable' it in the where clause, and specify NULL value to select where b=b, which would be true for each column, BUT if there is a NULL value in b column, it does not get selected. Is there a standard way to deal with this? So what should I use in the above example query to select all rows even if b column has null values?
Answer: For checking NULL values you need to do it as b is null
You can change query as -
select * from test
  where a = @a
    and b = isnull(@b,b)
    or (@b is null and b is null)

Comment: thanks, but that works if @b is NULL, but if @a = 1, @b = 1 the query should only return the first row (with your fix it returns both of them)
Comment: OK, changing it to     select * from test
      where a = @a
        and (b = isnull(@b,b)
   or (b is null and @b is null)) did the trick! thanks again
Comment: @Axarydax - Aaaah.. Just in time. You got the answer before my edit.


is ANCOVA with a CATEGORICAL covariate legit? Two Way Anova a potential alternative?

Question: I have a dependent continuos variable and two independent variables, both categorical. The first independent variable is the "gender" of respondents (two levels), the second one is their "first language" (5 levels: english, french, ... and other 3).
I would like to test whether the dependent continuos variables is significantly different between male and females, controlling also for their "first language". On some tutorials I found that ANCOVA could be a solution as an extended version of ANOVA, controlling for a covariate. However, I also read that ANCOVA requires covariate to be CONTINUOS variable and not Categorical, such as is my case with the Categorical variable "first language".
Is there any other solution available? Is SPSS (i'm using this software) working the same if I use a CATEGORICAL covariate instead of a continuous one? What do you suggest could be the best option to pursue? Maybe a Two-Way Anova could work? But in the case of a Two-Way Anova I already know the design would be unbalanced (= without having the same number of cases for each group). What would be then the implications?
Answer: You might like to have a look at this post asking the exact same question about categorical covariates.
"Is SPSS (i'm using this software) working the same if I use a CATEGORICAL covariate instead of a continuous one?"
The answer to this I have from Baguley (2012). He says that different softwares implement it differently. Probably different commands also results in different results. He reccommends to create one's own syntax unless one is sure what the software does. With his guide I created a repeated ANOVA and multilevel models in R. I'm not a statistician, mathematician or econometrician, hence I like to draw on people with more knowledge.
Regarding your unbalanced design question, I did a quick search on this forum and discovered a wealth of answers. I guess this is why your question hasn't been answered until now.


Replace image with iframe

Question: I am trying to replace an img tag with a specific src tag with an iframe using JQuery.
This is part of an external widget script implementation. This is the code I'm using to replace the image with a specific src with an iframe:
function main() {
jQuery(document).ready(function($) {
  var img = $("img[src='http://fc01.deviantart.net/fs17/f/2007/129/7/4/Stock_032__by_enchanted_stock.jpg']")[0];
  var width;
  var height;
  var id = 47;
  $("")
      .attr("src", $(img).attr("src"))
      .load(function() {
          width = this.width;
          height = this.height;
          var widgetReplace = "";
          this.replaceWith(widgetReplace);
      });
   });
  }
})();

I am getting an error "Undefined is not a function" at the this.replaceWith(widgetReplace) line.
Comment: "an error" — **What** error?
Answer: EDIT: Hmm, after i posted saw the error was not what I beleived it was, guess I'm wrong then.
I may be completely wrong due to the formatting of the iframe but from looking at it for a minute or two it appears you are missing a &quot.
 Here is the line in question, i cut alot of it off to be easier to read
var widgetReplace = "<iframe src=&quothttp://localhost:5000/app/#/widget" + id + "?height="

After the id or ? I believe should be the end quote to complete the src. E.G.
"<iframe src=&quothttp://localhost:5000/app/#/widget" + id + "?&quotheight="

Of course depending on the fromatting the &quot could be in a different place, I have no way to know.
Answer: The method replaceWith() is a jQuery function, so you should use:
$(this).replaceWith(widgetReplace);

Replace image with iframe


JavaScript - Executar Dados de uma array sempre na mesma ordem

Question: Bom/Boa Dia/Tarde/Noite, Gostaria de uma ajuda em JavaScript, como faço para executar dados de uma array sempre na mesma ordem, exemplo:
var teste = ["valor1", "valor2"];
document.getElementById("id").innerHTML =

Como faco pra quando eu clicar um botao o valor do texto seja o valor um, depois quando clicar de novo seja o valor dois, e depois reinicie.Obrigado, desculpe-me pela pergunta enorme ;)
Answer: Tens de criar uma variável que guarde a informação de qual elemento da array foi mostrado. Uma flag do indice. E depois cada vêz que clicares no elemento aumentas essa variável de valor.
Um exemplo seria assim:
var arr = ['Olá', 'hoje', 'esteve', 'um', 'lindo', 'dia!'];
var index = 0;
var btn = document.querySelector('button');
var div = document.querySelector('div');

btn.addEventListener('click', function() {
    div.innerHTML = arr[index];
    index++;
    if (index == arr.length) index = 0;
});

jsFiddle: https://jsfiddle.net/r8d787d8/
Comment: Muito Obrigado De Novo!


Getting started with Rally REST webservice API

Question: Was after some help on getting started with calling the Rally REST webservice from a .NET MVC webclient.
I've been given the web service info here:
https://rally1.rallydev.com/slm/doc/webservice/
So I can see that I can use a URL to access information from Rally - Similar to:
https://rally1.rallydev.com/slm/webservice/1.39/task?query=((Owner.Name
= email@example.com) and (State != Completed))&order=Rank&fetch=true&stylesheet=/slm/doc/webservice/browser.xsl

However what I'm not clear on is how to authenticate before making my request?
I'm new to REST web services (have done the SOAP/WSDL awhile back) - so it doesn't seem like with REST you're supposed to add a reference to something to get client classes created?  Is this correct?  That you just create a HTTPRequest using a URI - and make the call, getting back a HTTPResponse (which I can hopefully do something with).
A lot of examples seem to have specific service/api classes that they're calling methods on or accessing properties - so I'm not sure if that's because they're using SOAP rather than REST - or that they created them themselves.
Maybe I'm looking at the wrong documentation as it seems assumed you know how to be authenticated. Or I'm missing a reference?
Answer: I know the question is old, but this might help someone else. You need to pass a Basic Authentication header with your base64-encoded username and password as part of your get() request. I found this information on an Atlassian documentation page and successfully applied it with Rally API 3.0 (should also work with 2.0). So in your get() request, include a header similar to the following:
auth_header = 'Authorization : Basic ' + base64_encode('username:password')


KVM bridged network cannot connect to the server

Question: I installed KVM on my Ubuntu Server 14.04 LTS on OVH dedicated server.
I cannot connect to my virtual host over ssh.
My server IP: AAA.AAA.AAA.AAA
My Failover IP: BBB.BBB.BBB.BBB

My config on the server
ifconfig
br0       Link encap:Ethernet  HWaddr 00:25:90:dd:35:6e
          inet addr:AAA.AAA.AAA.AAA  Bcast:AAA.AAA.AAA.255  Mask:255.255.255.0
          inet6 addr: fe80::225:90ff:fedd:356e/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:3856 errors:0 dropped:0 overruns:0 frame:0
          TX packets:303 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:248725 (248.7 KB)  TX bytes:38262 (38.2 KB)

eth0      Link encap:Ethernet  HWaddr 00:25:90:dd:35:6e
          inet6 addr: fe80::225:90ff:fedd:356e/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:3922 errors:0 dropped:5 overruns:0 frame:0
          TX packets:323 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:308221 (308.2 KB)  TX bytes:39990 (39.9 KB)
          Memory:fb720000-fb740000

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:76 errors:0 dropped:0 overruns:0 frame:0
          TX packets:76 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:9066 (9.0 KB)  TX bytes:9066 (9.0 KB)

cat /etc/network/interfaces
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet manual

auto br0
iface br0 inet static
    address AAA.AAA.AAA.AAA
    netmask 255.255.255.0
    network AAA.AAA.AAA.0
    broadcast AAA.AAA.AAA.255
    gateway AAA.AAA.AAA.254
    bridge_ports eth0
    bridge_fd 9
    bridge_hello 2
    bridge_maxage 12
    bridge_stp off

vm is created using
sudo ubuntu-vm-builder kvm trusty \
                  --domain test \
                  --dest test \
                  --arch amd64 \
                  --hostname test \
                  --mem 256 \
                  --user john \
                  --pass doe \
                  --bridge=br0 \
                  --ip BBB.BBB.BBB.BBB \
                  --mask 255.255.255.0 \
                  --bcast BBB.BBB.BBB.BBB \
                  --gw AAA.AAA.AAA.254 \
                  --dns 22.214.171.124 \
                  --components main,universe \
                  --addpkg acpid \
                  --addpkg openssh-server \
                  --addpkg avahi-daemon \
                  --addpkg linux-image-generic \
                  --addpkg bridge-utils \
                  --libvirt qemu:///system

brctl showmacs br0
port no mac addr        is local?   ageing timer
  1 00:00:0c:07:ac:02   no         2.50
  1 00:05:73:a0:00:01   no         1.84
  1 00:25:90:22:ad:82   no        17.36
  1 00:25:90:7d:18:b8   no        25.91
  1 00:25:90:dd:30:87   no         2.98
  1 00:25:90:dd:35:6e   yes        0.00
  1 00:ff:ff:ff:ff:fd   no         0.07
  1 00:ff:ff:ff:ff:fe   no         0.00
  1 00:ff:ff:ff:ff:ff   no         2.24
  1 a8:0c:0d:01:69:45   no         0.60

virsh edit test
<domain type='kvm'>
  <name>test</name>
  <uuid>27dcd092-9770-47f7-b613-2e0f94adcced</uuid>
  <memory unit='KiB'>262144</memory>
  <currentMemory unit='KiB'>262144</currentMemory>
  <vcpu placement='static'>1</vcpu>
  <os>
    <type arch='x86_64' machine='pc-i440fx-trusty'>hvm</type>
    <boot dev='hd'/>
  </os>
  <features>
    <acpi/>
  </features>
  <clock offset='utc'/>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>restart</on_reboot>
  <on_crash>destroy</on_crash>
  <devices>
    <emulator>/usr/bin/kvm</emulator>
    <disk type='file' device='disk'>
      <driver name='qemu' type='qcow2'/>
      <source file='/root/test/tmp342OQf.qcow2'/>
      <target dev='hda' bus='ide'/>
      <address type='drive' controller='0' bus='0' target='0' unit='0'/>
    </disk>
    <controller type='usb' index='0'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x2'/>
    </controller>
    <controller type='pci' index='0' model='pci-root'/>
    <controller type='ide' index='0'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>
    </controller>
    <interface type='bridge'>
      <mac address='52:54:00:18:ea:57'/>
      <source bridge='br0'/>
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
    </interface>
    <input type='mouse' bus='ps2'/>
    <input type='keyboard' bus='ps2'/>
    <graphics type='vnc' port='-1' autoport='yes' listen='127.0.0.1'>
      <listen type='address' address='127.0.0.1'/>
    </graphics>
    <video>
      <model type='cirrus' vram='9216' heads='1'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
    </video>
    <memballoon model='virtio'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
    </memballoon>
  </devices>
</domain>

virsh edit default
<network>
  <name>default</name>
  <uuid>a962a950-17f3-48eb-b91b-9e71ef8a1247</uuid>
  <forward mode='nat'>
    <nat>
      <port start='1024' end='65535'/>
    </nat>
  </forward>
  <bridge name='br0' stp='on' delay='0'/>
  <mac address='52:54:00:4d:b5:0d'/>
  <ip address='AAA.AAA.AAA.AAA' netmask='255.255.255.0'>
    <dhcp>
      <range start='BBB.BBB.BBB.1' end='BBB.BBB.BBB.23'/>
    </dhcp>
  </ip>
</network>

ip route
default via AAA.AAA.AAA.254 dev br0
AAA.AAA.AAA.0/24 dev br0  proto kernel  scope link  src AAA.AAA.AAA.AAA

cat /etc/sysctl.conf
net.ipv4.ip_forward=1

net.ipv6.conf.all.autoconf = 0
net.ipv6.conf.default.autoconf = 0
net.ipv6.conf.eth0.autoconf = 0
net.ipv6.conf.all.accept_ra = 0
net.ipv6.conf.default.accept_ra = 0
net.ipv6.conf.eth0.accept_ra = 0

net.bridge.bridge-nf-call-ip6tables = 0
net.bridge.bridge-nf-call-iptables = 0
net.bridge.bridge-nf-call-arptables = 0

arp -n
Address                  HWtype  HWaddress           Flags Mask            Iface
AAA.AAA.AAA.250           ether   00:25:90:22:ad:82   C                     br0
AAA.AAA.AAA.254           ether   00:ff:ff:ff:ff:ff   C                     br0

Answer: You need to generate a Virtual MAC address for the failover IP in your OVH manager, and then assign that MAC address to the virtual machine's NIC. OVH does not allow devices with arbitrary MAC addresses to communicate on its network.

The virtual machine should use a bridged network, not the "default" NATted network (such VMs can talk to the Internet but cannot be reached from outside).
    <interface type='bridge'>
      <mac address='00:50:56:04:bc:ce'/>
      <source bridge='br0'/>

Comment: Thank you for your reply, I have created virtuam MAC addresses do you mean to attach it to test machine (52:54:00:18:ea:57 is the server mac should I replace it?) and should I change forward mode='nat' to forward mode='bridge'?
Comment: You should completely ignore the "default" network entirely, and change the MAC address of the VM.
Comment: how can I ignore default network?
Comment: Close your eyes. Don't use it. Pretend it isn't there.
Comment: I understood from your comment that I am actually using it and should not
Comment: Your "test" VM is _not_ using the default network. It is bridged correctly (but again with the wrong MAC address). But for some reason you posted the default network anyway. Thus the warning.
Comment: Ok thank you, I have entered the MAC address created in OVH panel (type ovh) and updated entry in test.xml however still cannot access the machine :(
Comment: Did you actually assign the failover IP to your server? It should not say Parked.


Can I compare a just-identified model and an overidentified model?

Question: As far as I understand, a just-identified model has zero degrees of freedom and its model fit indices do not make much sense. On the contrary, overidentified models have a meaningful chi-square, CFI, etc. Some researchers compare just-identified models to overidentified ones using these fit indices.
Is it justifiable to compare fit indices (such as CFI, root mean square error of approximation (RMSEA), standardised root mean square residual (SRMR), and chi-square) between just-identified and overidentified models given these models are nested?
I know I can do it using AIC and BIC. But what about CFI and other ones?
Comment: Could you give an example of "Some researchers compare just-identified models to overidentified ones using these fit indices."
Answer: Most model fit indices for just-identified SEMs are not useful, such as CFI and TLI of 1.0 or $\chi^2$ and RMSEA of 0.0, so obviously for those measures it makes no sense at all to use them for comparing a just-identitied model to an over-identified model.
Comment: Thank you. Do you know by any chance any paper I can refer to in this regard?
Comment: You're welcome. Any book on SEM should go into this. Apart from books a good resource is the Stata documentation for `sem`/`gsem` which is availble for free. Also, David Kenny's website has lots of good info, such as [this](http://www.davidakenny.net/cm/fit.htm)
Comment: Thanks, I checked several books as well as Kenny's website, they never discussed this exact issue of comparing just-identified and overidentified models.
Comment: Does this answer your question ? If so please consider marking it as the accepted answer, and if you haven't already please consider upvoting it. If not, please let us know why ?
Answer: The just identified model has 0 df - it is also called the saturated model.
It has a chi-square of zero, SRMR of zero and RMSEA of zero. Chi-square explicitly compares the fitted model with the just identified model.
It can make sense to compare the AIC and BIC of the fitted and saturated models. If they are not higher in the saturated model, you have a problem.


Why D7 creates two tables when i add one custom fields in user registration?

Question: I created few custom fields for user registration in Drupal 7.
When I add the "First name" field, two tables are created: field_data_field_first_name, and field_revision_field_first_name.
Why are there two tables, if they contain the same data?
Answer: You can find the answer on your question on Duplicate data in field_data* and field_revision* tables. In particular, see this comment:

The field_revision tables store the revision id, which never changes in these tables. The field_data tables store the node's current revision id and does not store old revision data. Basically the field_data tables only ever contain 1 entry per node. The field_revisions table will contain the number of revisions you've created, preserving the revision data. So if you never use revisions, then yes, the tables will contain identical data.
Since revisions are a core part of Drupal I don't think there's anything you can do about this. You can probably delete the contents of the field_revision tables (please test first, don't take my word for it!), but as soon as you start creating/editing nodes the field_revision tables will repopulate.


XCode 4.6.3 crash everytime I open it on OS X 10.9.3

Question: I updated Mavericks 10.9.2 to 10.9.3 and downloaded Xcode 6 beta. One of my project is still in Xcode 4.6.3. So now whenever I open this project Xcode crashes with the following pop up.

It was working fine in OS X 10.9.2. Is it OS related issue? Please help
Comment: Try it from a different account; if it works there then Xcode's preferences are messed up on the original account. You can ether deleted them  ('/Library/Preferences/com.apple.Xcode.plist') or try to fix them via an XML editor.
Comment: Any solution for this trouble? I have the same problem :(
Answer: I had similar issue. This can be fixed using
<code>`sudo mv /System/Library/PrivateFrameworks/MobileDevice.framework{,-saved}`
</code>
This will ask for system component installation and then Xcode starts working.
I recommend to use latest version of Xcode 6.x.
Answer: Try this:
sudo mv /System/Library/PrivateFrameworks/MobileDevice.framework{,-saved}
Answer: Javi Campana's answer and Iron Eagle's (
Xcode 4.6.3 crashing after installing xcode 6 beta )
worked for me.
I believe the missing key point is running Xcode 4.6.3 directly after renaming the MobileDevice.framework.
Xcode 4.6 will then prompt you to install "Device Support" component.
Once installed, my Xcode 4.6.3 and Xcode 6 beta 2 worked again with MobileDevice.framework version 555.43 created Dec 21, 2014.
Answer: So it turns out Xcode 4.6 does not work with iTunes higher than 11.4.
Instructions how to downgrade you may find here: http://osxdaily.com/2014/10/26/downgrades-itunes-12/
Comment: Thanks for saving!!


Evaluate $\frac{1}{m_1} +\frac{1}{n_1} +\frac{1}{m_2} +\frac{1}{n_2}+...+\frac{1}{m_{2011}} +\frac{1}{n_{2011}}$

Question: When $a=1,2,3,...,2010,2011$ the roots of the equation $x^2 -2x-a^2-a=0$ are $(m_1,n_1 ), (m_2,n_2 ), (m_3,n_ 3),..., (m_{2010},n_{2010} ), (m_{2011},n_{2011 }) $ respectively. Evaluate $\frac{1}{m_1} +\frac{1}{n_1} +\frac{1}{m_2} +\frac{1}{n_2}+...+\frac{1}{m_{2010}} +\frac{1}{n_{2010}} +\frac{1}{m_{2011}} +\frac{1}{n_{2011}}$
**My attempt **$$$$
$ \frac{1}{m_a} +\frac{1}{n_a}$can be manipulated to give
$$\frac{m_a+n_a}{m_an_a}$$then w.l.o.g $m_a\ge n_a$
And since$$m_a=2\frac{2+2\sqrt{a^2+a+1}}{2}$$
And $$n_a= 2\frac{2-2\sqrt{a^2+a+1} }{2}$$
We get
$$\frac{m_a+n_a}{m_an_a}=\frac{-2}{a(a+1)}$$
But I dont know what to do next,
Suggestions and solutions would be appreciated
Taken from the 2011 IWYMIC
Answer: Hint:
$$
\frac{-2}{a(a+1)} = \frac2{a+1} - \frac 2a
$$
Answer: You don't need to compute the roots $n_a, m_a$. Just note that: $\dfrac{1}{n_a}+\dfrac{1}{m_a}=\dfrac{n_a+m_a}{n_am_a}=\dfrac{S_a}{P_a}$ where $S_a$ and $P_a$ denote the sum and the product of those two roots. And:
$\dfrac{S_a}{P_a}=\dfrac{-b}{c}=-\dfrac{2}{a(a+1)}=2\left(\dfrac{1}{a+1}-\dfrac1a\right)$. Finally:
$$\sum_{a=1}^{2011}{\dfrac{S_a}{P_a}}=2\sum_{a=1}^{2011}{\left(\dfrac{1}{a+1}-\dfrac1a\right)}=2\left(\dfrac{1}{2012}-\dfrac11\right)$$


Implementing the randomized set class with O(1) operation

Question: This is related to the leetcode - question here, which asks:
Implement the RandomizedSet class:

RandomizedSet() Initializes the RandomizedSet object.
bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.

You must implement the functions of the class such that each function works in average O(1) time complexity.
I am able to pass some of the test cases but it fails one of the test cases (where in some places, my program returns undefined). What is it that I am doing wrong here? I am unable to find my mistake.
var RandomizedSet = function() {
    this.map = new Map();
    this.vector = [];
};

/**
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.insert = function(val) {
    if(this.map.has(val)) return false;
    else {
        let position = 0;
        if(this.vector.length > 0)
            position = this.vector.length-1;

        this.map.set(val, position);
        this.vector.push(val);
        return true;
    }
};

/**
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.remove = function(val) {
    if(this.map.has(val)) {
        const index = this.map.get(val);
        const lastVal = this.vector[this.vector.length-1];
        this.vector[index] = lastVal;
        this.vector.pop();
        this.map.delete(val);
        return true;
    }else {
        return false;
    }
};

/**
* @return {number}
*/
RandomizedSet.prototype.getRandom = function() {
    const randIndex = Math.floor(Math.random() * this.vector.length);
    return this.vector[randIndex];
};

/**
* Your RandomizedSet object will be instantiated and called as such:
* var obj = new RandomizedSet()
* var param_1 = obj.insert(val)
* var param_2 = obj.remove(val)
* var param_3 = obj.getRandom()
*/

Answer: When moving the last element into the place of the removed element, you forgot to update the moved element's index in the map:
RandomizedSet.prototype.remove = function(val) {
    if(this.map.has(val)) {
        const index = this.map.get(val);
        const lastVal = this.vector[this.vector.length-1];
        this.vector[index] = lastVal;
        this.vector.pop();
        this.map.set(lastVal, index); // ADDED
        this.map.delete(val);
        return true;
    }else {
        return false;
    }
};

Be aware of the case index == this.vector.length-1; the order of operations shown above will handle this case correctly without additional code.
Comment: Yes, missed that! But looks like it is still failing.
Comment: If you see this here https://ibb.co/kG4cBc0 .. there is a mismatch  for some of the values.
Comment: It shows the exact input, so you can reproduce and debug the problem yourself.


WCF timeout exception detailed investigation

Question: We have an application that has a WCF service (*.svc) running on IIS7 and various clients querying the service. The server is running Win 2008 Server. The clients are running either Windows 2008 Server or Windows 2003 server. I am getting the following exception, which I have seen can in fact be related to a large number of potential WCF issues.
System.TimeoutException: The request channel timed out while waiting for a reply after 00:00:59.9320000. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout. ---> System.TimeoutException: The HTTP request to 'http://www.domain.com/WebServices/myservice.svc/gzip' has exceeded the allotted timeout of 00:01:00. The time allotted to this operation may have been a portion of a longer timeout.

I have increased the timeout to 30min and the error still occurred. This tells me that something else is at play, because the quantity of data could never take 30min to upload or download.
The error comes and goes. At the moment, it is more frequent. It does not seem to matter if I have 3 clients running simultaneously or 100, it still occurs once in a while. Most of the time, there are no timeouts but I still get a few per hour. The error comes from any of the methods that are invoked. One of these methods does not have parameters and returns a bit of data. Another takes in lots of data as a parameter but executes asynchronously. The errors always originate from the client and never reference any code on the server in the stack trace. It always ends with:
 at System.Net.HttpWebRequest.GetResponse()
  at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

On the server:
I've tried (and currently have) the following binding settings:
maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferPoolSize="2147483647"

It does not seem to have an impact.
I've tried (and currently have) the following throttling settings:
<serviceThrottling maxConcurrentCalls="1500"   maxConcurrentInstances="1500"    maxConcurrentSessions="1500"/>

It does not seem to have an impact.
I currently have the following settings for the WCF service.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single)]

I ran with ConcurrencyMode.Multiple for a while, and the error still occurred.
I've tried restarting IIS, restarting my underlying SQL Server, restarting the machine. All of these don't seem to have an impact.
I've tried disabling the Windows firewall. It does not seem to have an impact.
On the client, I have these settings:
maxReceivedMessageSize="2147483647"

<system.net>
    <connectionManagement>
    <add address="*" maxconnection="16"/>
</connectionManagement>
</system.net>

My client closes its connections:
var client = new MyClient();

try
{
    return client.GetConfigurationOptions();
}
finally
{
    client.Close();
}

I have changed the registry settings to allow more outgoing connections:
MaxConnectionsPerServer=24, MaxConnectionsPer1_0Server=32.

I have now just recently tried SvcTraceViewer.exe. I managed to catch one exception on the client end. I see that its duration is 1 minute. Looking at the server side trace, I can see that the server is not aware of this exception. The maximum duration I can see is 10 seconds.
I have looked at active database connections using exec sp_who on the server. I only have a few (2-3). I have looked at TCP connections from one client using TCPview. It usually is around 2-3 and I have seen up to 5 or 6.
Simply put, I am stumped. I have tried everything I could find, and must be missing something very simple that a WCF expert would be able to see. It is my gut feeling that something is blocking my clients at the low-level (TCP), before the server actually receives the message and/or that something is queuing the messages at the server level and never letting them process.
If you have any performance counters I should look at, please let me know. (please indicate what values are bad, as some of these counters are hard to decypher). Also, how could I log the WCF message size? Finally, are there any tools our there that would allow me to test how many connections I can establish between my client and server (independently from my application)
Thanks for your time!
Extra information added June 20th:
My WCF application does something similar to the following.
while (true)
{
   Step1GetConfigurationSettingsFromServerViaWCF(); // can change between calls
   Step2GetWorkUnitFromServerViaWCF();
   DoWorkLocally(); // takes 5-15minutes.
   Step3SendBackResultsToServerViaWCF();
}

Using WireShark, I did see that when the error occurs, I have a five TCP retransmissions followed by a TCP reset later on. My guess is the RST is coming from WCF killing the connection. The exception report I get is from Step3 timing out.
I discovered this by looking at the tcp stream "tcp.stream eq 192". I then expanded my filter to "tcp.stream eq 192 and http and http.request.method eq POST" and saw 6 POSTs during this stream. This seemed odd, so I checked with another stream such as tcp.stream eq 100. I had three POSTs, which seems a bit more normal because I am doing three calls. However, I do close my connection after every WCF call, so I would have expected one call per stream (but I don't know much about TCP).
Investigating a bit more, I dumped the http packet load to disk to look at what these six calls where.
1) Step3
2) Step1
3) Step2
4) Step3 - corrupted
5) Step1
6) Step2

My guess is two concurrent clients are using the same connection, that is why I saw duplicates. However, I still have a few more issues that I can't comprehend:
a) Why is the packet corrupted? Random network fluke - maybe? The load is gzipped using this sample code: http://msdn.microsoft.com/en-us/library/ms751458.aspx - Could the code be buggy once in a while when used concurrently? I should test without the gzip library.
b) Why would I see step 1 & step 2 running AFTER the corrupted operation timed out? It seems to me as if these operations should not have occurred. Maybe I am not looking at the right stream because my understanding of TCP is flawed. I have other streams that occur at the same time. I should investigate other streams - a quick glance at streams 190-194 show that the Step3 POST have proper payload data (not corrupted). Pushing me to look at the gzip library again.
Comment: @JasonKealey - In contrast to many other questions, you cannot be accused of not trying for yourself before posting the question :) I love that your question is so detailed, and includes all the important details. The symptoms you describe looks very much like mine, so I hope the solution is the same as well :)
Comment: Jason - did you ever solve this problem? Was it the DefaultConnectionLimit setting?
Answer: If you are using .Net client then you may not have set
//This says how many outgoing connection you can make to a single endpoint. Default Value is 2
System.Net.ServicePointManager.DefaultConnectionLimit = 200;

here is the original question and answer WCF Service Throttling
Update:
This config goes in .Net client application may be on start up or whenever but before starting your tests.
Moreover you can have it in app.config file as well like following
<system.net>
    <connectionManagement>
      <add maxconnection = "200" address ="*" />
    </connectionManagement>
  </system.net>

Comment: It only took a year, but I finally ran another stress test on the application with this flag set. The issue appears solved, so I am giving you the best answer. I would not be surprised that this was the last piece of the puzzle that was required but that all the other elements needed to be in place to ensure the error did not happen. Thanks very much!
Comment: @Aris: In .net client applicaiton, on startup or where ever you set your global configuration, if you want to keep it configurable you can add it in config file as well like this
Comment: @Jason: If you are server programmer you know how much important to maintain the scalability of server in your hands and also one who is currently suffering the concurrency problem even after using above. Please if you can look into the following question http://stackoverflow.com/questions/2637175/wcf-network-cost in short i am suffering with 31ms latency between client and server and need to reduce it.
Comment: This looks promising. I've included this to be tested during my next scalability test. It looks exactly like the kind of random setting that would make it crash :) Thanks for the pointer.
Answer: If you havn't tried it already - encapsulate your Server-side WCF Operations in try/finally blocks, and add logging to ensure they are actually returning.
If those show that the Operations are completing, then my next step would be to go to a lower level, and look at the actual transport layer.
Wireshark or another similar packet capturing tool can be quite helpful at this point. I'm assuming this is running over HTTP on standard port 80.
Run Wireshark on the client. In the Options when you start the capture, set the capture filter to tcp http and host service.example.com  - this will reduce the amount of irrelevant traffic.
If you can, modify your client to notify you the exact start time of the call, and the time when the timeout occurred. Or just monitor it closely.
When you get an error, then you can trawl through the Wireshark logs to find the start of the call. Right click on the first packet that has your client calling out on it (Should be something like GET /service.svc or POST /service.svc) and select Follow TCP Stream.
Wireshark will decode the entire HTTP Conversation, so you can ensure that WCF is actually sending back responses.
Comment: I have logging on the server - there is no error on that end.

I am running WireShark right now to see what I can find. Given the high volume of traffic, it is going to be a pain to analyze but I will report back if I can find anything.
Comment: I ran WireShark over the past six hours and collected some 60k frames. Only one exception was reported by this client today. I did see a TCP connection marked as RST (reset), apparently after sending the error email, which is probably WCF that is terminating the connection.

I saved the payload (525k) to disk. I verified that there were 87 other invocations with similar sized payloads.

I did see a few TCP retransmissions, but saw some in other calls as well (that did not fail). Starting to wonder about my networking hardware + cables.
Comment: Even on a local network, the presence of a TCP Retransmits isn't necessarily bad.

If it's possible to physically connect two of the end points to a single switch, then that might be worth a shot, but I wouldn't hold out hope that will fix it.

If you can - create a very basic client application that just passes some traffic back and forth to your server, and nothing else. This can help eliminate any issue in your application that might be causing timeouts.
Comment: Also, you mention seeing the TCP Reset packet -- had the server delivered any kind of response at that point (or perhaps was it waiting for more data)? Was there an appreciable delay between the RST and the previous packet?
Comment: The server is remote. I am planning on creating a test environment locally to see if that helps. As for the RST, it was sent 34 seconds after the last of five TCP Retransmission. (1 to 8 second intervals between retransmissions). Does that give you any clues?
Comment: So, if the server is sending a RST packet after 5x consecutive retransmissions with no Acknowledgements - then it seems your client is (for some reason) dropping packets.

I'd definitely create a stand-alone client, even if it talks directly to the regular server. There could be any number of issues causing the clients to drop packets (other threads blocking execution, other apps hogging resources, failing hardware, network, firewalls, etc).
Answer: from: http://www.codeproject.com/KB/WCF/WCF_Operation_Timeout_.aspx

To avoid this timeout error, we need
  to configure the OperationTimeout
  property for Proxy in the WCF client
  code. This configuration is something
  new unlike other configurations such
  as Send Timeout, Receive Timeout etc.,
  which I discussed early in the
  article. To set this operation timeout
  property configuration, we have to
  cast our proxy to IContextChannel in
  WCF client application before calling
  the operation contract methods.
Comment: I have tried this. Regardless of the timeout I put, it still times out but this makes no sense because the operation is not that long and because all the other clients that do the same queries function during this time.
Comment: My tests proved that OperationTimeout simply overrides ReceiveTimeout from the config.  Thus, it's of no use whatever.
Answer: I'm having a very similar problem.  In the past, this has been related to serialization problems.  If you are still having this problem, can you verify that you can correctly serialize the objects you are returning.  Specifically, if you are using Linq-To-Sql objects that have relationships, there are known serialization problems if you put a back reference on a child object to the parent object and mark that back reference as a DataMember.
You can verify serialization by writing a console app that serializes and deserializes your objects using the DataContractSerializer on the server side and whatever serialization methods your client uses.  For example, in our current application, we have both WPF and Compact Framework clients.  I wrote a console app to verify that I can serialize using a DataContractSerializer and deserialize using an XmlDesserializer.  You might try that.
Also, if you are returning Linq-To-Sql objects that have child collections, you might try to ensure that you have eagerly loaded them on the server side.  Sometimes, because of lazy loading, the objects being returned are not populated and may cause the behavior you are seeing where the request is sent to the service method multiple times.
If you have solved this problem, I'd love to hear how because I'm stuck with it too.  I have verified that my issue is not serialization so I'm at a loss.
UPDATE: I'm not sure if it will help you any but the Service Trace Viewer Tool just solved my problem after 5 days of very similar experience to yours.  By setting up tracing and then looking at the raw XML, I found the exceptions that were causing my serialization problems.  It was related to Linq-to-SQL objects that occasionally had more child objects than could be successfully serialized.  Adding the following to your web.config file should enable tracing:
<sharedListeners>
    <add name="sharedListener"
         type="System.Diagnostics.XmlWriterTraceListener"
         initializeData="c:\Temp\servicetrace.svclog" />
  </sharedListeners>
  <sources>
    <source name="System.ServiceModel" switchValue="Verbose, ActivityTracing" >
      <listeners>
        <add name="sharedListener" />
      </listeners>
    </source>
    <source name="System.ServiceModel.MessageLogging" switchValue="Verbose">
      <listeners>
        <add name="sharedListener" />
      </listeners>
    </source>
  </sources>

The resulting file can be opened with the Service Trace Viewer Tool or just in IE to examine the results.
Answer: Are you closing the connection to the WCF service in between requests? If you don't, you'll see this exact timeout (eventually).
Answer: I'm not a WCF expert but I'm wondering if you aren't running into a DDOS protection on IIS.
I know from experience that if you run a bunch of simultaneous connections from a single client to a server at some point the server stops responding to the calls as it suspects a DDOS attack.
It will also hold the connections open until they time-out in order to slow the client down in his attacks.
Multiple connection coming from different machines/IP's should not be a problem however.
There's more info in this MSDN post:
http://msdn.microsoft.com/en-us/library/bb463275.aspx
Check out the MaxConcurrentSession sproperty.
Comment: I feel that this is what is happening, from everything I have seen, however I have (on the server):

Would there be any performance monitor or IIS log that I could monitor to see if this is happening?
Answer: Did you check the WCF traces? WCF has a tendency to swallow exceptions and only return the last exception, which is the timeout that you're getting, since the end point didn't return anything meaningful.
Comment: I tried SvcTraceViewer and the only exception it reported was the timeout (on the client). Nothing was reported on the server.
Comment: Open all the options on the trace, you might not have all the trace options open. Also, check both the event trace and message trace files.
Answer: Did you try using clientVia to see the message sent, using SOAP toolkit or something like that? This could help to see if the error is coming from the client itself or from somewhere else.
Comment: Do you know of any tools more recent than the deprecated SOAP toolkit that would make it easier for me to log this information in WCF calls?
Comment: ***SOAP Toolkit*** is *`deprecated`*
Answer: You will also receive this error if you are passing an object back to the client that contains a property of type enum that is not set by default and that enum does not have a value that maps to 0. i.e enum MyEnum{ a=1, b=2};
Answer: I've just solved the problem.I found that the nodes in the App.config file have configed wrong.
<client>
<endpoint name="WCF_QtrwiseSalesService" binding="wsHttpBinding" bindingConfiguration="ws" address="http://cntgbs1131:9005/MyService/TGE.ISupplierClientManager" contract="*">
</endpoint>
</client>

<bindings>
    <wsHttpBinding>
        <binding name="ws" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text">
            <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
            <**security mode="None">**
                <transport clientCredentialType="None"></transport>
            </security>
        </binding>
    </wsHttpBinding>
</bindings>

Confirm your config in the node <security>,the attribute "mode" value is "None". If your value is "Transport",the error occurs.
Comment: Does this not affect security ? If so this may not be a solution for most real applications
Answer: Looks like this exception message is quite generic and can be received due to a variety of reasons. We ran into this while deploying the client on Windows 8.1 machines. Our WCF client runs inside of a windows service and continuously polls the WCF service. The windows service runs under a non-admin user. The issue was fixed by setting the clientCredentialType to "Windows" in the WCF configuration to allow the authentication to pass-through, as in the following:
      <security mode="None">
        <transport clientCredentialType="Windows" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>


Alternate definition of bijection: If $f$ and $g$ are both injective, then $f$ is bijective.

Question: Suppose $f: A \to B$ and $g: B \to A$ where $g(f(a))=a$ for all $a \in A$, and $f(g(b))=b$ for all $b \in B$.
We know that since $f$ has a left inverse, it is injective. But notice that $g$ also has a left inverse and thus it is also injective.
Does this reasoning show that $f$ is bijective?
Answer: You're partway there, but not quite there, yet.
Take any $b\in B.$ Since $g(b)\in A$ and $f(g(b))=b,$ then $f:A\to B$ is....
Alternately, since $f$ has a left inverse, then it is injective, and since $f$ has a right inverse, then it is....
Comment: Well, knowing only that you have two injective functions $f:A\to B$ and $g:B\to A$ certainly isn't enough in general to show that $f$ is bijective. Cobsider $A=B=\Bbb Z$ and $f(x)=g(x)=2x.$
Comment: We know that $f$ is surjective since for all $b \in B$, $b=f(g(b))$. But, I was curious as to whether we can discard the definition of surjective, and only use the fact that $f$ and $g$ are injective.


How to write in a ckdeditor textarea with Cypress?

Question: i'm trying to create a new node in Drupal 9.
But all my attempts so far have failed when it comes to writing the body text.
The body text is a Ckeditor5 field. I can't write there with Cypress.
I tried the following line with the following error: "Cannot read properties of undefined (reading 'instances')"
  cy.window().then(win => {win.CKEDITOR.instances["html_body"].setData("
HTML body
");});

After several attempts, i tried the jQuery way, so far this solution wont raise any error, but the textarea remains in blank without any text:
cy.get('.ck-editor__editable').then($editable => {$editable.focus().html('
HTML body
');});

how can i set text into this field with Cypress?
Comment: Pretty sure I remember reading cke5 doesn't use iframes any more
Comment: I have searched on the internet for the issue and everyone says that ckeditor uses an iframe, but I cannot find any iframe anywhere. :-(
Comment: Never heard of Cypress
Comment: You probably have to wait for the page to be ready, its possible the actual editor hasn't finished loading yet.
Comment: Isn't [Cypress](https://www.cypress.io/) a JavaScript component testing framework? Are you testing the node creation form?
Comment: yessir to both questions
Answer: Drupal keeps a list of the active CKEditor 5 instances in JS, you can get them from there. For example to fill all the editors on the page:
cy.window().then(win => {
  win.Drupal.CKEditor5Instances.forEach(editor => editor.setData('
Test
'))
})


ideas for presenting data from multiple conditions

Question: I have some data from an experiment that has 7 variables that have two levels to generate the conditions for the experiment. Consequently there are 128 (2^7) different combinations of variables. I've seen some data presented in lattice style panel plots that look good, but I've only come across ones that do this for 2 different variables. However, I was wondering if anyone had any ideas for presenting data where there are more than 2 variables (i.e. a contingency table doesn't work!)
I've provided some example data to explain what my data looks like if it wasn't clear:
cond1 <- c(1,2)
cond2 <- c(1,2)
cond3 <- c(1,2)
cond4 <- c(1,2)
cond5 <- c(1,2)
cond6 <- c(1,2)
cond7 <- c(1,2)
conditions <- expand.grid(cond1,cond2,cond3,cond4,cond5,cond6,cond7)
conditions <- sapply(conditions, rep.int, times=10)
data <- runif (nrow(conditions))
df1 <- cbind(conditions, data)

Answer: You can still use a lattice by adding nested labels. If your software doesn't support nesting, you can make synthetic variables to simulate the nesting. For example, I think that would be cond123 = paste(cond1, cond2, cond3) in R.
The result can be a table of numbers or a graphical representation such as a heat map:

This data is not completely random to show that some patterns can be noticed from this kind of display. I'll mark the formula as a spoiler in case you want to see what you can see from the images without knowing.

 data value = random uniform(0, 1) + cond3 + cond4 + cond2 * cond5

If you're looking for particular patterns, you can use a graphical representation that will make those patterns more evident (at the expense of other patterns). For instance, a grid of one plot per variable will highlight any 1-dimensional effects.

And a grid of contour plots will highlight 2-dimensional effects.

Diagonal contours suggest some kind of combined effect.
Comment: Yes, the function name is from the SAS JMP scripting language -- I was hoping it was be clear enough to serve as pseudo-code. And the graphs are made with JMP's Graph Builder feature.
Comment: Presumably the spoiler code is SAS code.
Comment: great, really nice plots!