When using a span with attribute role = textbox and contenteditable=true .Then copy-paste of texts inside it, doesnt work properly

Question: consider the span :

with css:
.comment-box2 {
    display: block;
    width: 100%;
    overflow: hidden;
    outline: none;
    min-height: 40px;
    line-height: 20px;
    padding-left: 8px;
    background-color:#F5FFFA;
    border-radius:15px;
    border: 1px solid #708090;
    display:inline-block;
    width:330px;
}

When i copy plain text from a site and paste inside the span with role =textbox ,ie the above span. it creates another span inside it ,when looked through inspect element . the following line of code is seen as the inner span:
Foot on the pedal never ever false metal

here the "Foot on a pedal never ever false metal" is the text i copied from a site .How do i prevent the creation of the span and all of its attribute and only paste the plain text i copied onto the span with role="textbox".
In the case of just typing plain text inside the span everything works fine and no span is generated.when text is pasted it generates the above span and a white background is generated behind it which im trying to remove.
Comment: If the content to copy contains a span, it's included in the content editable element. How the clipboard works, depends on the application copying the content, and the application pasting the content. When you copy from a browser, the selected HTML elements are copied among with the plain text. When you're pasting in a browser, browser selects a suitable content depending on the paste target element.
Comment: Why do you think this is related to the attributes of the span?
Answer: When you copy text from another website/app, the styles associated with the font are also copied. If these styles don't match, a new span is created to accommodate the new styles. The same happens in many other apps as well, for example, Excel, Word, Google sheet,etc.
Comment: Styles might be copied in RTF format, but a content editable element doesn't paste in RTF. A text editor wouldn't know what to paste, when having a tag or plain text on the clipboard. The copied information is saved to the clipboard in multiple formats, the exact formats are application dependent, ex. Excel copies a selected area even as a PNG image, you can paste it directly to a pixel graphic app. The app reading from the clipboard (executing paste) picks a format suitable to the context, and what is actually pasted varies depending on the context and the provided formats on the clipboard.
Comment: No, the styles are not copied as they are, you can't paste a styled text to a (real) text editor. The tag is copied and pasted to a content editables, whereas a textarea element or a real text editor would use the saved plain text.
Comment: The styles are copied but a text editor just doesn't accepts them...if you copy it to the same platform(i.e. Web), then you would see the same styles.
Comment: Thanks for the clarification. Your answers was really helpful for me.


Freeman-halton simple examples?

Question: Does anyone know where I can see a step by step simple example of the Fisher-Freeman-Halton equation? I am a developer so need to build the process from scratch and have already done so for the Fisher part but now need to extend it to x n possibilities. Wikipedia has a good example for the basic version but not the more complex.
I have found https://www.statsdirect.co.uk/help/chi_square_tests/rc.htm but its not particularly clear.
Answer: Hidden away under "Formulas" at the bottom of https://www.danielsoper.com/statcalc/calculator.aspx?id=59 is a good starting point!

Freeman-halton simple examples?


cms start: plone or modx

Question: I'm modelling a new project that will require a CMS solution. I'm a newb in this space ... I'm an old timer with typical enterprise skills of my era: scripting, java/j2ee, plsql. Working with jQuery and nodejs on other learning projects. For the CMS project, I've whittled down the many choices to Plone or Modx. Why? Both are good choices. Plone intrigues me because of the Python base - Python would be a nice add to my toolbox. Kinda wish Plone5 was a little closer. Modx strikes me as the best of my php based CMS solutions for a hands on developer type. I like they just made a big leap forward in their codebase. Concrete5 was a finalist here too. Drupal just sorta bugs me ... don't see me being a Drupal "guy". Joomla? Really ... not sure. Wordpress? Like going to a new restaurant and ordering a burger and fries. Would like to know opinions and reasons: Plone(python) or Modx(php)?
Answer: Haven't used Modx yet, but I can cast my vote for Plone. Especially if your project is not a simple website with one editor user.
Plone excels at powering complex sites with multiple users having different levels of access. Also, it's security track is the best in the area, ensuring you get a good night sleep, every night. On another note, in case your project is international: Plone is translated into more than 40 languages.
Interesting read:

Security Overview of Plone
Plone for Government sites
List of sites running Plone

cms start: plone or modx


Characteristic method for solving a linear PDE $xyz_x-x^2z_y=-yz$.

Question:
Find the solution of the linear PDE
  $$xyz_x-x^2z_y=-yz$$

Chacteristic equations:
$$\frac{dx}{xy}=\frac{dy}{-x^2}=\frac{dz}{-y}$$
from here, I found the characteristic $x^2+y^2=c_1$ and $lnx+z=c_2$.
since $c_2=f(c_1)$, we have $lnx+z=f(x^2+y^2)$ and solution is $z=f(x^2+y^2)-lnx$.
It is right?
if it is wrong, where am I wrong?
Comment: Shouldn't be $\dfrac{dz}{-yz}$.?
Comment: We can write the term for quasi linear. Can't we write it for linear pde? Why?
Comment: Let $f\equiv t^2$. Is your answer valid? check
Comment: It's not valid.  Why doesn't the method work?
Comment: Write it again with true Characteristic equations
Comment: I don't know. Pls help:)
Answer: $$\frac{dx}{xy}=\frac{dy}{-x^2}=\frac{dz}{-yz}$$
then with $\dfrac{dx}{xy}=\dfrac{dy}{-x^2}$ we find $x^2+y^2=C_1$ and with $\dfrac{dx}{xy}=\dfrac{dz}{-yz}$ we have $xz=C_2$ thus
$$z=\frac{f(x^2+y^2)}{x}$$


VB form buttons and their text

Question: looking for help. I want to have a form with up to around 20 buttons. I want their display names to be coming from an access database table of products i sell. I can connect the form to my database and get the first record in the table to display on the first button but when i do the same for the second button it just displays the first record again. Is there a way of pointing the button name to the second record in the table some how? I dolnt want to hardcode the product names into the code as abviously they may change in the future :-)
thanks in advance
<code>Public Class f

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    'TODO: This line of code loads data into the 'LoftDataSet.Services' table. You can move, or remove it, as needed.
    Me.ServicesTableAdapter.Fill(Me.LoftDataSet.Services)

    'Loop through all the rows that are in the dataset
    For Each dr As DataRow In LoftDataSet.Services.Rows

        Dim btn As New Button 'Instantiate a button
        btn.Text = dr("service_name").ToString 'UserName is a field in my Users Table
        btn.Size = New Size(60, 40)
        btn.Tag = dr("ID") 'Here we set the tag to the primary key (ID)

        'Since we're using a flowlayoutpanel, we don't need to worry about setting the location property
        FlowLayoutPanel1.Controls.Add(btn) 'Add the button to the flow layout panel
        AddHandler btn.Click, AddressOf UserClick  'Here we give the button a handler for the click event

    Next
End Sub

'Here we write our method for the click event of the button(s) we created

Private Sub UserClick(ByVal sender As Object, ByVal e As EventArgs)

    'We set a filter to the binding source passing it ID=<and whatever is stored in the tag property>

    ServicesBindingSource.Filter = "ID = " & DirectCast(sender, Button).Tag.ToString

End Sub
</code>
Comment: There is no way to know whats wrong with your code without the code.  Also if it is VB.NET it is not access-vba and vice versa. See [Ask]
Comment: i am using vb studio and i have connected to a .mdb and connection is ok
Comment: You have asked this question already albeit your data in that question was in a text file. You need to show your code.... I assume you are reading in data but not looping through each record to populate your buttons... and so you get the first record in all your buttons...
Comment: ok i have pasted in the code. thanks
Comment: Mych does my code help at all?
Answer: Public Class f
02
03
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
04
        'TODO: This line of code loads data into the 'LoftDataSet.Services' table. You can move, or remove it, as needed.
05
        Me.ServicesTableAdapter.Fill(Me.LoftDataSet.Services)
06
07
        'Loop through all the rows that are in the dataset
08
        For Each dr As DataRow In LoftDataSet.Services.Rows
09
10
            Dim btn As New Button 'Instantiate a button
11
            btn.Text = dr("service_name").ToString 'UserName is a field in my Users Table
12
            btn.Size = New Size(140, 80)
13
            btn.Tag = dr("ID") 'Here we set the tag to the primary key (ID)
14
15
            'Since we're using a flowlayoutpanel, we don't need to worry about setting the location property
16
            FlowLayoutPanel1.Controls.Add(btn) 'Add the button to the flow layout panel
17
            AddHandler btn.Click, AddressOf UserClick  'Here we give the button a handler for the click event
18
19
        Next
20
    End Sub
21
22
    Public Class Product
23
        Public Property ProductName As String
24
        Public Property ProductCost As Decimal
25
26
        Public Overrides Function ToString() As String
27
            Return ProductCost & " " & ProductName
28
            'Here you could build a formatted string to the user to include cost
29
        End Function
30
    End Class
31
32
33
    'Here we write our method for the click event of the button(s) we created
34
    Dim SelectedProduct As New Product
35
36
37
    Private Sub UserClick(ByVal sender As Object, ByVal e As EventArgs)
38
39
        'We set a filter to the binding source passing it ID=
40
41
        ServicesBindingSource.Filter = "ID = " & DirectCast(sender, Button).Tag.ToString
42
43
        SelectedProduct.ProductName = DirectCast(sender, Button).Text
44
        SelectedProduct.ProductCost = DirectCast(ServicesBindingSource(0), DataRowView).DataView(0)(2)
45
        ListBox1.Items.Add(SelectedProduct)
46
47
    End Sub
48
49
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
50
        For i As Integer = ListBox1.SelectedIndices.Count - 1 To 0 Step -1
51
            ListBox1.Items.RemoveAt(ListBox1.SelectedIndices(i))
52
        Next
53
    End Sub
54

VB form buttons and their text


PHP - onClick doesn't seem to be working

Question: I have series of dropdown boxes which can be selected by the user. I then want to have two different submit buttons that will do two different actions with the selected data. I am trying to code the submit button to run the selected php, but when I click the button does nothing. Any help is appreciated, my code is below. AFAIK the only relevant bits are my formSubmit function and the input tag near the bottom of the code.
edit: I have edited out a bulk of the code and left the pieces that I think are relevant. Please let me know if more info is needed.
<!DOCTYPE html>
<?php
require 'config.php';  // Database connection
//////// End of connecting to database ////////
?>

<?Php

//Beginning of Form
echo "<form method=post name='f1' action =''>";
//Dropdown boxes are here

//This line is what is not working:
echo "<input type='submit' value='Careers' onclick=\"submitForm('rt.php')\">";
echo "</form>";
?>

Comment: Sorry, could you please reduce this wall of code to a shortened example that demonstrates the issue?
Comment: This is a lot of code. You should cut it right down so as just to illustrate the problem you're having in isolation. In the process you'll likely see the problem.
Comment: @arkascha You hit return before me!
Comment: Why don't you use regular form submits without JS?
Comment: Can I user the regular form submit to perform two different actions with the same set of data?     Also, I have edited down the bulk of the code.
Answer: Not quite sure what is wrong with the function, xe4me may have the correct answer. However, I just changed my onClick to this and it worked:
onClick=\"document.f1.action='rt.php'; document.f1.submit(); return true;\"

Answer: You're using document.getElementById('f1') in submitForm function
function submitForm(action)
{
    document.getElementById('f1').action = action;
    document.getElementById('f1').submit();
}

But your form doesn't have id attribute because of this line of code
echo "<form method=post name='f1' action =''>";

so the form won't be submitted when you click the Careers button. You need to add id='f1' attribute to the form by changing the above line of code to below
echo "<form id='f1' method='post' name='f1' action =''>";

Answer: Try the jQuery method :
http://api.jquery.com/jquery.post/
with
How to get ID of clicked element with jQuery
Whenever any button is clicked, find its id and based on that, use $.post to post data to the location you want.
Comment: I am willing to look into this, but I do believe my code should work.
Answer: you must add a class to your button and call the onclick based on that class name :
 <?Php

  ....

 echo "<input type='submit' class='submitter' data-action='rt.php' value='Careers' >";
 echo "</form>";
 ?>

//  In Javascript :
 document.getElementByClassName('submitter').onclick = function(){
  var action  = this.data('action');

   document.getElementById('f1').action = action;
   document.getElementById('f1').submit();

}


magnific popup dosen't show buttons

Question: I have installed magnific popup in my wordpress project, but when I open the popup it does not show me the arrows, the close button, in short, all the buttons that should appear! I have inspected the source and the js and css files are inserted correctly , I also initialized the plug in I leave the code below
<code>(function ($) {

  $('.gallery').each(function() {
    $(this).magnificPopup({
        delegate: 'a',
        type: 'image',
        gallery: {
          enabled:true
        }
    });
  });

}(jQuery));
</code>
Comment: Inspect elements, search for the button css classes that magnific popup use, if it doesn't exists then it's js issue, if it exists then check the element style, there should be css conflicts that doesn't show you the buttons.
Comment: when I inspect to see precisely if I find the buttons, I only see the popup image, no trace of any buttons! there are not even errors reported by the inspector! it seems that the CSS is not read
Comment: It's hard to debug this kind of issue without a demo. You won't get any kind of errors in this case. What might be happening is that the buttons are loading, css is loading, but your theme or any other plugin applying some other css on top of popup css hence you can't see the button even if it exists. Just to sure you need to find `mfp-arrow-right` or `mfp-arrow-left` class via inspect element, those are the classes that buttons have.
Comment: I deactivated all the plugins, of which I only have one, I also tried to delete the css file which gives me the same result! it seems that the css is not read! I also tried to download the previous version of the css file and not even that works! I just can't understand why! mfp-arrow-right and mfp-arrow-left are not really displayed even in the inspector
Answer: I managed to solve the problem, you have to make sure that in the worpress gallery created, there is the "gallery" class! in my case it wasn't there and I had to add it!

magnific popup dosen't show buttons


JPanel repaint() method and debugging

Question: So I have created a small window with a ball bouncing around on it in Java and was trying to debug and watch the program work. Heres the important code for the question:
public class Ball {
private static final int SPEED = 2;
private int x = 0, y = 0;
private int xInc = SPEED, yInc = SPEED;

-> public void paint(Graphics2D g) {
    g.fillOval(x, y, 30, 30);
}
}

public class Game extends JPanel {

Ball gameBall = new Ball();

public void paint(Graphics g) {
    super.paint(g); // cleans the panel
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
    gameBall.paint(g2d);

}

public void updateBall() {
    gameBall.move(this.getWidth(), this.getHeight());
}

public static void main(String[] args) {
    JFrame mainFrame = new JFrame("Simple Pong");
    mainFrame.setSize(400, 400);
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Game gamePanel = new Game();
    mainFrame.add(gamePanel);
    mainFrame.setVisible(true);

    while (true) {
        try {
            gamePanel.updateBall();
            gamePanel.repaint();
            Thread.sleep(10);
        } catch (InterruptedException e) {
            System.out.println(e);
            System.exit(1);
        }
      }

    }

  }

I set a method pointer for the entrance of the paint method of Ball, thinking it would cause the program to halt each time the repaint() method is called, since I thought it calls the paint method. Then, I could watch the ball move one increment at a time instead of placing a line pointer where the repaint method is.
When I do this, the program does not halt with each update of the placement of my ball, and instead halts in what seems like random increments. The ball will be close to the edge, then in the middle so many calls to paint had to of occured.
Question: Does the repaint method always call the paint method for my lightweight container? And if so, why does the debugger not halt with each increment of the ball and instead only halt to display the new position sometimes? Obviously if the ball is moving smoothly on the screen while running, something is painting the Ball object onto my Game Panel exactly as I would like it to.
Note: The same thing happens if we place a method breakpoint for the entrance of the paint method for Game, which I have extending JPanel and is what I paint the ball onto.
Answer:
Does the repaint method always call the paint method for my lightweight container?

No.  Calls to repaint are requests for an update.  The repaint manager may optimise the requests and consolidate them down into a single event if it can.
Swing uses a passive painting algorithm which is designed to improve performance for systems which don't need to repainted all the time, painting only when it needs to be done.
On a side note, you should avoid overriding paint of components and instead prefer using paintComponent.  Also beware, the Graphics context passed to your paint methods is shared with everything else been painted, making changes to it might have undesirable side effects.
Instead, you should create a snapshot of the Graphics context's state and modify it...
Graphics2D g2d = (Graphics2D g2d)g.create();
//... Update, modify, transform, do what you want...
g2d.dispose();

Take a look at Painting in AWT and Swing and Performing Custom Painting for more details.
Swing operates in a single thread.  That is, all painting and even notification is done within the context of the Event Dispatching Thread, see Concurrency in Swing for more details.
When you hit your break point, the Event Dispatching Thread is STOPPED, but the while-loop you have running is not, so the x/y position of the Ball is still been updated, meaning that when the program resumes, the ball will appear to "jump" to a new location.
You can test this by placing a breakpoint on gamePanel.updateBall();, the UI will continue to be update (after each request to repaint), but will incrementally update as, as the state of the ball is not been altered.
The debugging process is not stopping the other threads that are running, but only effecting the thread from within which the breakpoint was triggered.
When Java calls you main method, it is doing so from what is known as the "main thread".  When you call setVisible on your mainFrame, a new thread is created (the Event Dispatching Thread), this allows the UI to run independently on the while(true), preventing it from "hanging" the UI.  Check out Initial Threads for more details
Comment: @MadProgrammer I downvoted you for not answering the question, unless I've misinterpreted the question.
Comment: @immibis Sorry, I think I see your point, thanks for the clarification ;)
Comment: @MadProgrammer No problem and thanks for the clarification. My apologies also as I did not see your second response until now. Just reworked my code to use `paintComponent` and am also using a snapshot of my `Graphics` obj and disposing of it at the end of `paintComponent`. Everything seems to work exactly as before which is great, but would you mind explaining a little as to why this is the safer approach for the `Graphics` obj?
Comment: The `Graphics` context is a shared resource, that is, all the components painted during a given paint cycle will receive the same `Graphics` context and on some platforms, the same `Graphics` context is used through the lifetime of the containing window.  Making modifications like, transformations or composites or rendering hints will remain with the `Graphics` context, meaning they will affect everything else painted (and yes, I've watched antialiasing render hints spread across a screen before, really freaky). Generally, you should reverse these changes before you exit the paint method or...
Comment: Yes a temporary copy of the `Graphics` context, where by you can change it's state, without affecting the original `Graphics` context and simply `dispose` of it when you're finished...they still paint to the same target, you're just isolating the changes
Comment: So then how does the program know where to place the ball if my overridden method isn't being called?
Comment: It's an illusion. There is enough of a change between frames to allow the ball to "appear" to move...that's the essence of animation...
Comment: Anyone wish to highlight the cause of the downvote so I might learn from your observations or even maybe fix something I've done wrong?
Comment: But when run the ball moves smoothly across the screen as expected. Debugging, it appears from place to place and NOT IN SMALL INCREMENTS. Why is the paint method...which is the only thing that have instructions for where to place my ball... only occur randomly yet appear to be called every frame.
Answer: repaint does not directly call paint. It just sets a variable so that Swing will, at some point, remember to call paint.
Now, do you know about threads? Because the explanation of what's happening here involves threads.
Everything to do with Swing usually runs on one thread, called the "event thread". In particular, paint gets called on the event thread.
main is called on a thread called the "main thread". The main thread is not the event thread. Your main method moves the ball (indirectly, by calling updateBall). The main thread's code is roughly "move the ball, set the 'repaint me later' variable, repeat".
When your breakpoint is hit, only the thread that hit the breakpoint is paused. That means the event thread is paused. The main thread, which updates the ball's position, continues running. The ball's position keeps getting updated while you think the program is paused (because actually only one thread is paused).
When you unpause the event thread, the event thread will go back to doing what it was doing (i.e. painting). Since, by now, the "repaint me later" variable will have been set, it will paint the game panel again - but the ball will have moved quite far this time.
Comment: Thank you so much! I was getting very aggravated. You really couldn't have answered my question any more clearly.
Comment: @immibis Just one more thing, if the main method is actually still running and only the event thread is paused, what is going on with the methods that run on the event threat located IN the main method such as repaint?
Comment: @bmcentee148 `repaint` will be calling the `RepaintManager` requesting updates to be made, it's possible the the `RepaintManager` may ignore some of them, but it's likely that the repaint requests are been added to the `EventQueue`, waiting for the EDT to become unblocked and process them.  It might be possible for the `RepaintManager` to "remove" pending request, but I don't recall seeing this mechanism the last time I was digging around that part of the code...This could result in your paint methods been hammered in quick succession once the EDT is unblocked...
Comment: @bmcentee148 There is no such thing as a cross-thread method call. `main` gets called on the main thread, and it calls `repaint`, so those particular `repaint` calls run on the main thread. Usually this is a no-no (because it usually works, but sometimes it doesn't, and it can lead to hard-to-track bugs), but `repaint` is one of the functions you're allowed to call on any thread.
Comment: Okay so those calls to repaint in the main thread are not actually displayed on the panel while the event thread is held up. How does that actually work? It seems as they are just passed over because the faster I click the play button, the close the ball appears to its last position. From this I take it the main thread is definitely updating its position just not displaying it even though calls the the repaint method are being made on the main thread.

JPanel repaint() method and debugging


How to make spray-can client follow redirects

Question: When requesting some pages with the following code:
HttpDialog(httpClient, IDN.toASCII(domain)).send(HttpRequest(uri = "/")).end

spray-can client returns responses with redirects to another URLs (e.g. 302 Found). Is there a standard way of telling spray to automatically follow redirects? And if not, what is the best way to implement this behavior myself with akka futures?
Comment: It looks like there's an issue open to implement [redirect following](https://github.com/spray/spray/issues/132), so I guess it doesn't support it presently.
Answer: Update 2: The PR was merged and documentation for redirection following is spray-can can now be found here
Update: I decided to have a crack at implementing this and have sent a PR. Hopefully it will get merged.

There is no way to currently tell spray-can client to follow 3xx redirects. See this thread for more details.
There is an open ticket, so hopefully this will happen in the future. I'm sure a contribution would be welcomed.
Comment: Update: the above referenced PR was merged.  Documentation on redirects in spray-client can be found here:  http://spray.io/documentation/1.2.2/spray-can/http-client/#redirection-following


Firefox Add-on Extension: Homepage override unexpected behavior

Question: This is part of my manifest.json:
...
 "chrome_url_overrides" : {
    "newtab": "index.html"
  },
 "chrome_settings_overrides" : {
  "homepage": "index.html"
}
...

index.html is loaded fine on every new tab.
However new windows, and on startup, all I get is a blank page.
I tried manually just setting the homepage in preferences  as the URL for index.html as the extension itself for example:
moz-extension://1232131-32132131-321312-321321-321321/index.html
The behavior improves, but isn't perfect. When I do this, the new windows load index.html fine but on a fresh start up (from closed application) all I see is a blank page again?
Any ideas what's going wrong? This only happens in Firefox, OK on Tor Browser and Google Chrome.
Comment: Just FYI the extension URLs are unique on each device. So I'm hoping you meant you were just testing by setting the homepage URL manually.
Comment: Did you try ./index.html ?
Comment: @Smile4ever Yes, I don't believe that's the problem
Answer: Turns out, this was happening due to the extension not loading in time during startup when a fresh window is loaded.
The way I first addressed this was in my background.js file:
function loadStart(){
    browser.tabs.update(
        {
            url: "index.html"
        }
    )
}

browser.runtime.onStartup.addListener(loadStart)

However, if the setting to always use private browsing is active, the code above will not do anything as runtime.onStartup does not fire if an incognito/ private browsing profile is loaded.
To counter this:
function pushStart(data) {
    if (data == null) {
        loadStart()
    }
    else {
        console.log("tab is well defined")
    }
}

var currentTab = browser.tabs.getCurrent()

currentTab.then((data)=>(pushStart(data)))

The new window on fresh start up is trying to load the page bundled in the extension, but trips up because the extension itself hasn't loaded and isn't available.
Hence the above code works around that case.
Comment: Also FYI this is a filed bug in Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=1490260


Obtaining all values from a built form

Question: I'm building a form and setting values via
$form = \Drupal::formBuilder()->getForm('My\Module', ['key1' => 'x']);

where I set the passed key1 as the default values for the associated fields : in My\Module\buildForm, you would find
public function buildForm(array $form, FormStateInterface $form_state, $presets = array()) {

    $form['key1'] = [
      '#type' => 'textfield',
      '#default_value' => isset($presets['key1']) ? $presets['key1'] : $query->get('key1')
    ];

    return $form;
}

This takes place in a controller not directly related to the form and I'd like to retrieve all values set, either as defaults or as parameters of the page, something like ['key1' => 'x'] if no parameter is passed to the page or ['key1' => 'v1'] if the page is called with ?key1=v1
How can I get all the values on my form array (besides filtering on the field names)?
Answer: Probably you put the preset values in the default values of form elements. They are at this point only in $form.
The values in $form_state are filled after the form is submitted, as a result of a GET/POST request.
But then your code, that calls the formBuilder, has no longer control. This will be handled by the submit method you have defined for the form.
Comment: `FormState` is  mostly there to illustrate what I am looking for, I don't really need it.  Correct me if I'm wrong, but you mean that there's no helper/method to extract the values of the form? Basically, I'm looking for a way to modify the form values in my controller and get the resulting values.
Comment: Can you put an example in your question, what is in $presets, where this is put in $form and what you want to extract?
Comment: Sure, I hope it's clearer
Comment: There is no helper method. `#default_value` is used to render the form in html. The processing of values only takes place after submit.

Obtaining all values from a built form


Finding the Least amount of the same 20 ball taken

Question: I found this neat question on my test, anyone can solve it? Many solutions with different ways to solve is welcomed and needed.
In a bag there are $200$ marbles consisting of $60$ red marbles, $60$ blue marbles, $60$ green marbles, and the rest are $20$ white marbles and yellow (white and yellow in $1$ marbles). If the marble is chosen without looking, what is the minimum amount that must be taken in order from the selected minimum marbles consists of $20$ marbles of the same color?

A.) $58$
B.) $57$
C.) $68$
D.) $78$
E.) $79$

Please Show Your Work!
Answer: The game is to get $20$ marbles with the same color,  we pick them one by one and we stop as soon as we reach the $20$'s.  There is a worst-case scenario-in terms of number of picks- that will lead to the win.
First, we are so unlucky that we pick all yellows and whites, that is $20$ taken.Worse, we pick $19$ reds, $19$ blues ,and $19$ greens. The next pick is a winning one as we will either have $20$ reds,blues or greens.
Therefore , the number of picks in the worst case scenario that leads to the win is
$$20+19*3+1=78$$


ParseControl in Dotnetnuke ASP.NET changing onclick to javascript instead of c# method provided, strange behavior

Question: Having some strange behavior here. I have some XSLT which generates some html with a few ASP.NET Link Button Controls
 String mstring = sw.ToString();
 var myctrl = Page.ParseControl(mstring);

      foreach (Control Control in myctrl.Controls)
              {
                  if (Control is LinkButton)
                      {
                         LinkButton lb = (LinkButton)Control;
                         lb.OnClientClick = "LoadPromo";

                       }
                          Panel1.Controls.Add(myctrl);
               }

  protected void LoadPromo(object sender, EventArgs e)
        {
            Console.Write(e.ToString());

        }

now it takes this control:
<asp:LinkButton ID="LinkButton2" runat="server" OnClick="LoadPromo" Text="Get your Free 2" />

and changes it to this when I add an event:
Get your Free 2 a>

Now as you can see, it changes the onclick to like javascript instead of the asp.net control.It changes "LoadPromo" to "LoadPromo;". What can i do to get around this?
Thanks In Advance
Things I have tried:
 lb.Click += LoadPromo;

I get this output:
Get your Free 2

Answer: OnClientClick is the name of the property of a server control that eventually renders to an "onclick" attribute.  This is meant to invoke a javascript function on the client side.  So in this case, it looks fine.
For the OnClick property, you need to have that match the name of a server-side function in your Page.aspx.  I'm not sure why it would even be rendering the onclick attribute for this - perhaps you don't have a function named "LoadPromo" with the right signature?
You should have a C# method like this:
protected void LoadPromo(object sender, EventArgs e)
{

}

Then you can wire this up to your button by doing
myLinkButton.Click += LoadPromo;

Comment: Yes, that's what it should do. WebForm_DoPostBackWithOptions() is the javascript function that causes a post back that will execute LoadPromo() in your codebehind.
Comment: Tried this too and it doesxn't work. When I try that  I get this:

a id="dnn_ctr954_ViewPromotions_LinkButton2" href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("dnn$ctr954$ViewPromotions$LinkButton2", "", true, "", "", false, true))">Get your Free 2
Comment: I also need to apply on post back also and this fixed problem:

 if (Page.IsPostBack || !Page.IsPostBack)


Pythonic way of switching nested dictionary keys with nested values

Question: In short I'm working with a nested dictionary structured like this:
nested_dict = {'key1':{'nestedkey1': 'nestedvalue1'}}

I'm trying to find a pythonic way of switching the keys with the nested values, so it would look like this:
nested_dict = {'nestedvalue1':{'nestedkey1': 'key1'}}

I'm also trying to rename the nested key values, so ultimately the dictionary would look like this:
nested_dict = {'nestedvalue1':{'NEWnestedkey1': 'key1'}}

This is closer to what I'm working with:
original_dict = {
    'buford': {'id': 1},
    'henley': {'id': 2},
    'emi': {'id': 3},
    'bronc': {'id': 4}
}

I want it to look like this:
new_dict = {
    1: {'pet': 'buford'},
    2: {'pet': 'henley'},
    3: {'pet': 'emi'},
    4: {'pet': 'bronc'}
}

Is there a way to do this in one line using a dictionary comprehension? I'm trying to get the very basics here and avoid having to use things like itertools.
Comment: That's a lot of restrictions.  Just a note, one-liners are not particularly better.
Comment: A weird set of resitrictions, you don't want to use something like "itertools", but a dictionary comprehension is OK? Itertools should always be your first thought. Putting everything on one line isn't something that you should strive for generally.
Comment: I'm new to python so just trying to get a handle of how dictionary comprehensions work with nested dicts. So seeing the structure laid out like it is below is super helpful for me, but I get that using itertools might be more efficient
Answer: You can use a dictionary comprehension to achieve this, 'swapping' things round as you build it:
new_dict = {v['id']: {'pet': k} for k, v in original_dict.items()}

To expand it to a for loop, it'd look something like:
new_dict = {}
for k, v in original_dict.items():
  new_dict[v['id']] = {'pet': k}

Note that both cases obviously rely on the 'id' value being unique, or the key will be overwritten for each occurrence.
Comment: this is great, exactly what I was looking for. thanks for your help!
Comment: I think this is the right answer, but the it all really depends on the data that you have. I'd also argue that when you're getting into a nested dict like this, it might be more pythonic to pull it out into a for loop for clarity.
Comment: Could you show me what this would look like with a for loop?
Comment: awesome, thanks again! this makes learning/absorbing a lot smoother for me
Answer: For a more generic solution, you can try this:
def replace(d, change_to = 'pet'):
  return {b.values()[0]:{change_to:a} for a, b in d.items()}

Output:
{1: {'pet': 'buford'}, 2: {'pet': 'henley'}, 3: {'pet': 'emi'}, 4: {'pet': 'bronc'}}

Comment: Bear in mind that since dictionaries are unordered, using an index on `values()` doesn't guarantee you will get the same item each time (if you have more than one of them).


How to calculate required switch speed based on network usage?

Question: I have a 48 100Mbit/s port HP Procurve Switch 2610 (J9088A) that can handle 13.0 million PPS (packets per second) and features wire speed switching capacity at 17.6Gbps.
First off, what does that REALLY mean?
Where do I start when trying to figure out if my office (with 70 employees) will be well setup with this switch? How to calculate through-put based on a user average load of X MB per day?
90% of the folks will only be sending email, access random websites, etc... the other 10% will be conducting heavier tasks like moving image files (10 MB) across network shares, constant external FTP streams through the switch to a server etc...
Is this switch good enough?
Comment: are there more than 48 machines that need to be plugged in?  if so, what is the other switch?  and, what is the connection between the two switches?
Answer: Let's assume absolute worst-case scenario for estimation here:
You said 10%, or 7 employees, would be moving image files across network shares. That is an absolute max of 1GBps per connection, but will most likely max out around 300Mb/s depending on storage hardware. If they're doing it across the Internet, it's going to cap out at the lower of either your uplink bandwidth or the remote server's bandwidth.
Even estimating that they use all 1Gbps for those 7 employees, that leaves 63 employees to share 10Gbps. In order to use that up with email and websites, your Internet connection would have to be 10Gbps, and each employee would have to be using 158 Mbps. Continuously. That's not even remotely feasible through web browsing and email, by about 3 orders of magnitude.
The above is all calculated with the assumption that every employee is doing all they can to use up all your switch's capacity at the same time for an extended period.
Yes, the switch would be more than good enough.
EDIT: For reference, We have over 100 employees and over 100 servers. Our core switch has never registered more than 450,000 packets per second. Even if every single packet was 1,500 bytes, that's still only around 5.3 Gbps.
Comment: You find me a user who is pushing the back end of a switch so hard that it can't keep, this person is probably editing the Lord of the Rings over iSCSI. Great answer!
Comment: Sorry, forgot to mention that it's NOT a GBit switch, only 100MBs with 4 GB uplinks.
Comment: It says "...features 17,6 Gbit/s switching speed...". How is that possible when the ports are only 100 Mbits?
Comment: That's likely the capability of the ASIC in the switch.
Answer:
How to calculate through-put based on a user average load of X MB per day?

It's pretty much irrelevant to base effective bandwidth of real world usage on the averaged bandwidth of users across a whole day with this number of users.
What's not clear is how you intend connecting 70 users to a 48 port switch.

90% of the folks will only be sending email, access random websites, etc

Even an un-switched lan is going to have latency times several hundred times smaller than the latency of the internet connection - and the bandwidth discrepancy will be almost as large. So using using ports from an expensive switch has very little value.
Note that unless you are planning to add multiple switches - and need to think about spanning trees for multiple paths, high end switches have little performance benefits over cheapo basic ones (yes there maybe differences in build-quality/longevity - but IME, they don't justify the price differential). The other place where expensive switches make good sense is where you need really low latency switching. You're not going to see the beneifts for remote web/email access and large local transfers.
Comment: You're right. I'm just hesitant about these two alternatives: use this single switch and then add smaller 8 port switches in star topology setup, say per department, OR, use two 48 port switches with direct connection from users. Which is better? The first I guess if it can handle the traffic as it would mean less hops.


Recursão para Inversão de Lista em Python

Question: Estou tentando criar uma função recursiva que inverta a ordem de uma determinada lista. Como sou iniciante, acredito que esteja cometendo erros durante a construção da função.
    def inverter(lista, size):
        clone = []
        if size == 0:
            clone = lista
            return clone
        else:
            inverter(lista, size-1)
            clone.append(lista[size])
            return clone

l = [1,2,3,4,5]
s = len(l) - 1
#[5]

Ao printar o size, percebi que ele não se altera durante a execução, retornando assim apenas o ultimo elemento da lista original, vide código acima. Realmente fiquei sem saída aqui.
Answer: Só lembrando que recursão não é a melhor maneira de inverter uma lista, e ao longo da resposta entenderemos os motivos.

A ideia básica de recursão é você resolver um problema resolvendo instâncias menores do mesmo problema e combinando os resultados (exceto se for recursão em cauda, que não precisa combinar nada). No caso de inverter uma lista, o raciocínio seria:

pegar o último elemento da lista e colocá-lo no início
juntar isso com o inverso do restante da lista

para inverter o restante da lista, pegue do primeiro ao penúltimo elemento e volte ao primeiro passo

Existem alguns casos básicos nos quais não é preciso do passo 1 e nem do 2: quando a lista for vazia, por exemplo.
Traduzindo isso para código, fica assim:
def inverter(lista):
    if not lista: # lista vazia, retorna ela mesma
        return lista
    return lista[-1:] + inverter(lista[:-1])

lista = inverter([1, 2, 3, 4, 5])
print(lista) # [5, 4, 3, 2, 1]

Primeiro eu testo se a lista é vazia, com if not lista - isso funciona porque uma lista vazia é considerada um valor falso. Então se a lista for vazia, eu retorno a própria lista, pois não há o que inverter.
Se a lista não for vazia, eu faço o passo 2 descrito acima. No caso, eu usei a sintaxe de slice para construir sub-listas:

lista[-1:] constrói outra lista contendo apenas o último elemento de lista
lista[:-1] constrói outra lista contendo do primeiro ao penúltimo elemento de lista

Sendo assim, eu pego o último elemento da lista e junto com o inverso do restante da lista.

Para exemplificar, suponha que eu chame inverter([1, 2]):

a lista [1, 2] não é vazia, não entra no if not lista
lista[-1:] retorna [2], e é concatenada com o resultado de inverter(lista[:-1])

como lista[:-1] retorna [1], é feita uma chamada recursiva para inverter([1])
a lista [1] não é vazia, não entra no if not lista
lista[-1:] retorna [1], e é concatenada com o resultado de inverter(lista[:-1])

como lista[:-1] retorna [], é feita outra chamada recursiva para inverter([])
a lista [] é vazia, retorna ela mesma

[1] é concatenada com uma lista vazia, o resultado é [1]

[2] é concatenada com [1], o resultado é [2, 1]

Repare que são criadas várias sub-listas, o que torna esse algoritmo bem ineficiente. Outro detalhe é que se a lista for muito grande, isso pode causar um estouro de pilha (e nem precisa ser uma lista tão grande assim).

Até dá para eliminar a última chamada recursiva, testando se a lista tem um elemento (pois neste caso não precisa inverter também, basta retornar a própria lista):
def inverter(lista):
    if len(lista) <= 1: # lista vazia ou com um elemento, retorna ela mesma
        return lista
    return lista[-1:] + inverter(lista[:-1])

Mas ainda sim temos os problemas de criar várias sub-listas e poder ter estouro de pilha quando a lista é suficientemente grande.
Mas repare que em nenhum dos casos eu preciso passar o tamanho da lista como parâmetro da função. Ele não é necessário, e mesmo que fosse, você precisaria testar se ele está na faixa de valores correta para que não ocorra um IndexError.

Um detalhe do algoritmo acima é que ele retorna outra lista, contendo os elementos invertidos. Mas se quiser alterar os elementos da própria lista, basta fazer:
def inverter(lista, first=0, last=-1):
    if first >= len(lista) / 2:
        return
    lista[first], lista[last] = lista[last], lista[first]
    inverter(lista, first + 1, last - 1)

lista = [1, 2, 3, 4, 5]
inverter(lista)
print(lista) # [5, 4, 3, 2, 1]

A ideia é trocar o primeiro elemento de lugar com o último, depois o segundo com o penúltimo, e assim por diante, até chegar ao meio da lista (len(lista) / 2). Aqui não temos o problema de criar várias sub-listas, mas ainda há o problema do estouro de pilha.
Uma curiosidade deste algoritmo é que dá para escolher os índices a partir dos quais ocorrerá a inversão:
lista = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
inverter(lista, 2, -3)
print(lista) # [1, 2, 8, 7, 6, 5, 4, 3, 9, 10]

Ou ainda:
lista = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
inverter(lista, 2)
print(lista) # 1, 2, 10, 9, 8, 6, 7, 5, 4, 3]

Se o segundo e terceiro parâmetros não forem passados, a função assume que a inversão será feita do primeiro elemento (índice 0) ao último (índice -1).

Enfim, apesar de ser possível, recursão não é a melhor solução para inverter uma lista. Para ver formas melhores, leia aqui.
Comment: obrigado pela ajuda. Após ler seu comentário e testar, consegui fazer o código funcionar. Obrigado.
Answer: Um primeiro problema do seu código é que o clone será sempre resetado a cada execução porque dentro da função existe a linha clone = []. Dessa forma, todos appends que você fez serão apagados. Para corrigir isto, eu criei uma função mais externa para inicializar uma única vez a lista clone.
Um outro problema é na condicional if size == 0. Lembre-se que no Python, os elementos começam a partir de 0. Então se você quiser criar uma condicional para parar ao chegar no último elemento, você deverá substituir 0 por -1.
Já no bloco else, você colocou a chamada da função inverter antes do clone.append. Você deveria fazer o contrário para que o elemento de maior index fosse acrescentado à lista clone e depois disso ser acrescentado o de menor index.
Veja esse código abaixo que eu fiz (Funciona):
def inverter(lista):
    clone = []

    def adiciona(lista, index):

        # Enquanto não chegar no último elemento, o index receberá o
        # valor dele -1 e o elemento do index atual será adicionado à lista clone.

        if index > -1:
            clone.append(lista[index])
            adiciona(lista, index-1)

    # Adiciona à lista clone os elementos da lista original só que invertido.
    adiciona(lista,len(lista)-1)
    return clone

lista = [1,2,3,4,5]
lista = inverter(lista)

print(lista) # A saída é [5,4,3,2,1]

Comment: Agradeço Jean, realmente ajudou bastante e esclareceu algumas dúvidas!
Comment: @zangado Vc chegou a testar o código acima? Ele nem sequer funciona: https://ideone.com/Ibzwi2
Comment: @hkotsubo o código de fato não funciona, o que me ajudou foram as pontuações e explicações que ele fez. Acredito que o código tenha sido uma ideia de como fazer.
Comment: Funciona sim pessoal e sim @hkotsubo, eu testei o código. O problema é que quando eu escrevi a resposta, eu troquei o nome da função diversas vezes para ficar bonito e esqueci de trocar o nome da função na chamada. Já corrigi o código na resposta. Peço perdão a todos, e se clicou em "Essa resposta não é útil" por causa do código, peço para que reavaliem a minha resposta.


Javascript: Object have keys, but Object.keys returns empty

Question:
I have an object, as you can see in picture, when i console.log() it, in first row it says course is an array of 0 length. when i expand it, it says length is 1, when i do course.length it says 0. Object.keys(course).length also says 0.
What i do in my app is, I have a listview. each item on listview is expandable. each item is a container, and each container have courses. i got containers and courses from remote server. everything was working perfectly. now i'm trying to load data from local database. it's not working anymore...
Please see my simplified code :

export default class Main extends Component{
  constructor(props) {
    super(props);
    this.state = {
      dataSource: new ListView.DataSource({
              rowHasChanged: (row1, row2) => row1 !== row2,
            })
    };
  }

  componentWillMount(){
    this.fetchData();
  }

  fetchData(){
    let data = fetch..... //// fetches data
    let dsource = {};

    for(let i=0; i < data.containers.length; i++){
      let container = data.containers[i];
      dsource[i] = {
        containerId: containder.id,
        course: [],
      }
      for(let x=0; x < container.courses.length; x++){
         let course = container.courses[x];
        dsource[i].course.push({
          courseId: course.id,
          courseName: course,name
        });
      }
     }

    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(dsource)
    });

  }

I read lots of questions on stackoverflow, many articles, but no successs :( Object.keys(Obj).length Obj.length all returns 0.
Some says because Obj.length will only show enumerable properties. i tried adding enumerable properties to object with Object.defineproperty but no changes.
any solutions? any help is highly appreciated.
The whole code (react native) :

"use strict";

import React, {Component, PropTypes} from 'react';
import {
  ActivityIndicator,
  ListView,
  StyleSheet,
  Text,
  View,
  Image,
  NetInfo,
  AlertIOS,
  TouchableOpacity,
  ScrollView,
  Dimensions,
} from 'react-native';

let SQLite = require('react-native-sqlite-storage');
let Loading = require("./Loading");
let Accordion = require('react-native-accordion');
let DeviceInfo = require('react-native-device-info');
import Icon from 'react-native-vector-icons/Ionicons';
import { Actions } from 'react-native-router-flux';
import I18n from 'react-native-i18n';
import translations from './translations';
I18n.fallbacks = true;
let LOADING = {};
import CodePush from "react-native-code-push";
let { width, height } = Dimensions.get('window');
let db = SQLite.openDatabase({name : "oc.db", location: 'default'});

export default class Courses extends Component {
  constructor(props) {
        super(props);
        this.state = {
            isLoading: false,
            dataSource: new ListView.DataSource({
              rowHasChanged: (row1, row2) => row1 !== row2,
            }),
            isConnected: true,
            dataLoaded: 0,
            restartAllowed: true
        };
    }

    toggleAllowRestart() {
      this.state.restartAllowed
        ? CodePush.disallowRestart()
        : CodePush.allowRestart();

      this.setState({ restartAllowed: !this.state.restartAllowed });
    }

    sync() {
    CodePush.sync(
      {
        installMode: CodePush.InstallMode.IMMEDIATE,
        updateDialog: false
      },
    );
  }

  componentWillMount() {
    NetInfo.isConnected.fetch().then(isConnected => {
      this.setState({
        isConnected: isConnected
      });
    });

    NetInfo.isConnected.addEventListener(
      'change',
      isConnected => {
        this.setState({
          isConnected: isConnected
        });
      }
    );

    this.fetchData();
    this.sync();
  }
    componentWillReceiveProps() {
      this.fetchData();
      this.setState({
        keyForCourse: Date()
      });
      if(this.props.goto == 'register'){
        Actions.register({type: 'reset'});
      }
    }

  fetchData() {
    console.log('Courses: fetchData running');
    if(this.state.isConnected == 'wifi' || this.state.isConnected == 'cell' || this.state.isConnected == 'true' || this.state.isConnected){
        this.setState({
          isLoading: true,
        });
        db.transaction((tx) => {
            tx.executeSql("SELECT * FROM users WHERE active=?",['yes'], (tx, results) => {
                let len = results.rows.length;
                let row = results.rows.item(0);
                let userName = row.userName;
                let userMail = row.userMail;
                let userId = row.userId;
                ///// Getting courses list
                db.transaction((tx) => {
                      tx.executeSql("SELECT * FROM containersC WHERE userId=?",[userId], (tx, results) => {
                          let dsource = {};
                          let len = results.rows.length;
                          if(len > 0){
                            for(let ind = 0; ind < len; ind++ ){
                              let cntr = results.rows.item(ind);
                              dsource[ind] = {
                                  nid: cntr.nid,
                                title: cntr.title,
                                course: [],
                                courses: {},
                              };
                              //// Get courses for each container
                              db.transaction((tx) => {
                                    tx.executeSql("SELECT * FROM courses WHERE userId=? AND container_nid=?",[userId, cntr.nid], (tx, results) => {
                                        let lenc = results.rows.length;
                                        if(lenc > 0){
                                            for(var j=0; j < lenc; j++){
                                              let crs = results.rows.item(j);
                                              console.log('Course:', crs);
                                              dsource[ind].course.push({
                                                course_id: crs.course_id,
                                                title: crs.title,
                                                cost: crs.cost,
                                                status: crs.status,
                                                period: crs.period // .time_sys
                                              });

                                              dsource[ind].courses[j] = {
                                                course_id: crs.course_id,
                                                title: crs.title,
                                                cost: crs.cost,
                                                status: crs.status,
                                                period: crs.period // .time_sys
                                              };
                                            }
                                            dsource[ind].total = lenc;
                                          }
                                        }, function(){
                                        console.log('Courses: Something went wrong Line 142');
                                      });
                                  });
                              //// End getting courses for containers
                            }
                            this.setState({
                              dataSource: this.state.dataSource.cloneWithRows(dsource),
                              isLoading: false,
                              dataLoaded: len
                            });
                          }
                        }, (err)=>{
                          console.log('Courses: Something went wrong', err);
                        });
                    }
                );
                //// End getting courses list
              }, function(){
                console.log('Courses: Unable to select users from database');
              });
          });
      } else {
        AlertIOS.alert(
          I18n.t("no_connection_title"),
          I18n.t("no_connection_desc")
        );
      }
    }

  selectRow(d, n) {
    Actions.cdetails({cid: d, tit: n});
    //Actions.rdetails({cid: d, tit: n});
  }

  renderRow(data) {
    let header = (
      <View style={{ backgroundColor: '#fff', margin: 7, marginBottom: 0 }}>
          <View style={styles.rowContainer}>
            <View  style={styles.textContainer}>
              <Icon name="ios-arrow-up" color="#00a2dd" size={30}></Icon>
              <Text style={styles.title}>{data.title}</Text>
            </View>
          </View>
    </View>
    );
    let headerOpen = (
      <View style={{ backgroundColor: '#fff', margin: 7, marginBottom: 0 }}>
          <View style={styles.rowContainer}>
            <View  style={styles.textContainer}>
              <Icon name="ios-arrow-down" color="#00a2dd" size={30}></Icon>
              <Text style={styles.title}>{data.title}</Text>
            </View>
          </View>
          <View style={styles.separator}></View>
    </View>
    );
///////////
    let cid = [];
    let content = [];
    let cll = data.total;
    console.log('Data to render :', data);
    console.log('Courses to render :', data.course);
    for(let x=0; x < cll; x++){
      cid[x] = data.course[x].course_id;
      let courseCost;
      switch(data.course[x].cost){
        case 0:
        courseCost = I18n.t("course_fee_free");
        break;
        case 1:
        courseCost = data.course[x].cost;
        break;
      }
      content.push(
        <TouchableOpacity key={cid[x]} onPress={()=>{this.selectRow(data.course[x].course_id, data.course[x].title)}} >
        <View style={[styles.cardContainer, {marginBottom: 5}, x == 0 ? { paddingTop: 6, } : {}, x == (cll+1) ? { marginBottom: 3} : {}]} key={cid[x]} >
          <View style={styles.card}>
            <View resizeMode="cover" style={styles.cardTitleContainer}>
              <Text style={styles.cardTitle}>{data.course[x].title}</Text>
            </View>
            <View
            style={{
                padding : 15,
              }}
              >
              <Text style={styles.cardContent}>
                <Icon name="ios-calendar" color="#00a2dd" size={10}> {data.course[x].period}</Icon>{'\n'}
                <Icon name="ios-pricetag" color="#00a2dd" size={10}> {courseCost}</Icon>
              </Text>
            </View>
          </View>
        </View>
        </TouchableOpacity>
      );
    }
    let clist = (
      <ScrollView style={styles.scrollView}>
      <View style={{
        padding: 6,
        paddingBottom: 0,
        borderTopColor: '#fff',
        backgroundColor: '#fff',
        margin: 7,
        marginTop: 0,
      }}>{content}</View>
      </ScrollView>
    );
////////////
  return (
    <Accordion
      header={header}
      headerOpen={headerOpen}
      content={clist}
      easing="easeOutCubic"
      underlayColor="#ebebeb"
    />
  );
  }

  render() {
    let content= null;
    if(this.state.isLoading){
      content = <Loading/>;
    } else {
      if(this.state.dataLoaded < 1){
      content = <View style={styles.errorContainer}>
     <View style={styles.error}>
     <Text style={styles.Errortext}>
      {I18n.t("courses_no_course_available")}
      </Text>
      </View>
     </View>;
      } else {
      content = <View style={{
        flex: 1
      }}>
      <ListView
        dataSource={this.state.dataSource}
        renderRow={this.renderRow.bind(this)}
      />
      </View>;
    }
    }

    return (
      <View style={styles.container}>
      {content}
      </View>
    );
  }
}

let styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "white",
    flexDirection: "column",
    justifyContent: "center",
    backgroundColor: '#e4e7ea',
  },
  separator: {
    height: 1,
    backgroundColor: "#d0d1d3",
  },
  scrollSpinner: {
    marginVertical: 20,
  },
  cardContainer:{
    flex: 1,
    alignItems: 'stretch',
    paddingLeft: 6,
    paddingRight: 6,
    borderColor: '#d0d1d3',
    borderWidth: 1,
    borderRadius: 5
  },

  card:{
    flex: 1,
    backgroundColor: '#ffffff',
    borderRadius: 2,
    borderColor: '#ffffff',
    borderWidth: 1,
    /*shadowColor: 'rgba(0, 0, 0, 0.12)',
    shadowOpacity: 0.8,
    shadowRadius: 2,
    shadowOffset: {
      height: 1,
      width: 2,
    },
    */
  },
  cardTitleContainer:{
    flex: 1,
    height: 35,
  },
  cardTitle:{
    position: 'absolute',
    top: 5,
    left: 5,
    backgroundColor: 'transparent',
    padding: 10,
    fontSize: 12,
    color: '#4c4b4b',
    fontWeight: 'bold',
  },
  rowContainer: {
    flexDirection: 'column',
    padding: 5,
  },
  textContainer: {
    flexDirection: 'row',
    flex: 1,
    padding: 5
  },
  title: {
    paddingTop: 7,
    paddingLeft: 5,
    color: '#00a2dd'
  },
  errorContainer: {
    flex: 1,
    flexDirection: "column",
    backgroundColor: '#e4e7ea',
    alignItems: 'center',
  },
  error: {
    marginTop: 75,
    width: width -150,
    height: 100,
    borderRadius: 15,
    backgroundColor: '#ecebeb',
    alignItems: 'center',
    justifyContent: 'center',
  },
  Errortext: {
    color: '#757575'
  },
});

Courses = CodePush(Courses);
Comment: What is clearly your need, show us your what is wrong for you in your code ?
Comment: Did you try Object.keys(array) then get the key by the index? https://jsbin.com/huqojefiti/1/edit also some more code would help
Comment: `course` is an array of length 1 and your object is at position 0
Comment: I have updated the question with whole code. please take a loot at.
Answer: There are 3 factors that can cause the general behavior you describe. In your case, I think it's the first:

When you invoke console.log(x), the Chrome console will show a summary of the object x at the time. However, when you expand the object, the value is obtained again. The detailed object you see may have changed since the call to console.log(), and changes will appear in the detail.
Properties may belong to an object's prototype (as opposed to "own" properties):
> x = {a:1}
{ a: 1 }
> y = Object.create(x)
> y.a
1
> y
{}
> Object.keys(y)
[]

Properties may be non-enumerable, and won't show up in key listings. length is a non-enumerable property.
Comment: so its possible that my code is not running consequently, and before its fetched and puts all data to array , its trying to show content and it's length. right? i will try to use async / await to see what happens. thanks for your answer
Answer: Try this,
 const keys =[];
    const person = {
    name : 'Jobelle',
    age :22,
    mob :8547391599
    }

    Object.getOwnPropertyNames(tempObj).forEach(prop => {
              keys.push(prop);
            });

Answer: As you said, Object.keys refers to enumerable properties. The "length" property of an array (which is also an object) is simply not enumerable.
Comment: @frontend_dev as i was testing, i tried both. i added one course and courses , one array and other one object. tried length and Object.keys.length on both of them, none work as expected.
Comment: So what do you suggest? how can i know how many items are inside array or object?
Comment: I don't think the OP is logging an array, although his wording could be understood this way. What's being logged is an object, whose property `course` shows an empty array but when expended shows a full array. *Note*:  downvote isn't from me.
Comment: First of all, explain your downvotes, so that we all can learn! Maybe I just understood something incorrectly regarding the question, but what I said IS correct in general. @Ataomega: Use `length` for determining the number of items in an *array*. Use `Object.keys` for determining the number of (enumerable) properties in an *object*. At least this is how I do it.
Comment: @frontend_dev thanks for your comment. since length was returning zero, i tried Object.keys().length , that also returned zero
Comment: @Ataomega, was it "course" or "courses" that did this? If I see this correctly from your console output, "course" is an array with one item in it. So here `Object.keys` should be zero, and `length` should be "1". But "courses" is apparently an object with one property "0". That is not the same! Here, `Object.keys().length` should indeed be "1". (Except for the case if you define this property as non-enumerable)
Comment: Sure you did the right thing? Otherwise that would be really strange. The behavior absolutely should be as I described. Maybe you have overlooked something else?
Answer: I ran into a similar problem. I had what I thought was an empty object (printing the object printed {}). But doing Object.keys() on it return a length of 2.
// problem
const myObject = "{}"
console.log(myObject); // prints {}
console.log(Object.keys(myObject).length); // prints 2

The problem was that I was receiving a stringified object from the backend. Doing a JSON.parse on the returned string solved my issues.
// solution
const myObject = JSON.parse("{}")
console.log(myObject); // prints {}
console.log(Object.keys(myObject).length); // prints 0

Comment: IMO this is not at all similar to the question. You forgot to parse a JSON string, they did not know the behaviour of `console.log()`. OK you both got a .log() result that you did not expect, but for totally different and unrelated reasons.


Interpretation of quadratic term in Poisson regression

Question: I fit a Poisson regression model where I used $x$ and $x^2$ to predict $y$.
Let's say the coefficients of $x$ and $x^2$ are $\beta_1 = 0.8$ and $\beta_2 = -0.1$.
Exponentiating the coefficient (${\beta_1}$) gives us the multiplicative factor by which the mean count changes when we increase $x$ by one unit: $e^{\beta_1}$ = 2.23. So increasing x by one unit changes the mean of $y$ by a factor of 2.23. This factor is constant over all $x$.
According to this answer, "$e^{\beta_2}$ would be called a ratio of ratio of rates comparing groups differing by 1 unit differing by 1 unit of $X$."
I tried this out with a toy example below with the parameters from above (${\beta_1} = 0.8$ and ${\beta_2} = -0.1$) and indeed the ratio is not constant because of the nonlinear term but the ratio of the ratio is constant. But the ratio of ratios is not equal to $e^{\beta_2}$ but to $e^{(2\beta_2)}$. I think this relates to this part of the referenced answer above "But if you do a difference in differences for $(E[Y|X=x+2] - E[Y|X=x+1]) - (E[Y|X=x+1] - E[Y|X=x]) = 2\beta_2$. So basically the $\beta_1$ is the tangent slope of the quadratic curve at the origin, and $\beta_2$ is a quadratic slope."
With all this, I am not quite sure how to interpret a one-unit change of $x$ on the mean of $y$. Would it be correct to say that for each unit increase in $x$, the linear term ${\beta_1}$ changes the mean of $y$ by a factor of 2.23 while the nonlinear term ${\beta_2}$ leads to a decrease of this factor by $e^{(2\beta_2)}$ = 0.8187 for each increase in $x$. I don't think this is correct because the effect is dependent on the value of $x$.
Is there a way to express the effect on a one-unit increase in $x$ on the mean of $y$ that is independent of $y$ or is this not possible?
And if this is not possible, what is the correct way to specify a change from let's say $x = 1$ to $x = 2$ for this toy example? "Increasing $x$ from 1 to 2 increases the mean of $y$ by a factor of 1.6487"?

x
predicted y
ratio
ratio of ratio

0
1

1
2.01375271
2.01375271

2
3.32011692
1.64872127
0.81873075

3
4.48168907
1.34985881
0.81873075

4
4.95303242
1.10517092
0.81873075

5
4.48168907
0.90483742
0.81873075
Comment: "[Thar be dragons!](https://en.wikipedia.org/wiki/Here_be_dragons)"  Yes, interpretations with polynomial terms are fraught with difficulties.  I recommend you interpret all functions of $X$ together (see: [Does it make sense to add a quadratic term but not the linear term to a model?](https://stats.stackexchange.com/a/28750/7290)).
Answer: You can assemble two useful pieces of information to arrive at the interpretation of the linear and quadratic term in a Poisson GLM:

As you already stated, $\exp(\beta)$ for any first-order coefficient $\beta$ in a Poisson model can be interpreted as a relative rate of the Poisson process comparing groups differing by 1 in the corresponding variable being modeled.

In a linear model with identity link, like OLS, the interpretation of the quadratic term $\beta_2$ is readily seen as the rate of change of the effect, that is for every unit difference in $X$ the slope relating $X$ and $Y$ changes by a factor of $\beta_2$. Similarly, the linear term $\beta_1$ can be seen as the instantaneous rate of change relating $X$ and $Y$ when $X=0$. That is to say, since the shape of the predicted trend between $X$ and $Y$ is quadratic, $\beta_1$ is the slope of the tangent curve at $X=0$.

So, in your model with $\beta_1 = 0.8$ and $\beta_2 = -0.1$, comparing groups differing by 1 unit "near 0" (ignoring the issue of prediction at the means), has a relative rate ratio of 2.22, and groups differing by 1 unit have a ratio of relative rate ratios of 0.91
Comment: Thanks! But groups differing by 1 unit have a ratio of relative ratios of 0.81 ($e^{(2\beta_2)}$) and not 0.91 ($e^{(\beta_2)}$), right? Since $e^{(2\beta_2)}$ is the second derivative of the relative rate of change with respect to $x$?
Comment: Thanks for your patience! I did, and my result was $e^{2\beta_2}$... I also double-checked with WolframAlpha. $e^{2\beta_2}$ is also consistent with the ratio of ratios I calculated in the table for the toy example I provided. What am I missing?
Comment: @Ahorn you're not showing any work.
Comment: I also get $2\beta_2$, Showing some work, using $a,b$ for $\beta_1, \beta_2$ for simplicity in reading and typing: the crucial step is resolving: $ax +bx^2 + a(x+2) + b(x+2)^2 - 2\cdot (a(x+1) + b(x+1)^2)$, Here everytihng cancels except you get $4b$ from $b(x+2)^2$ and only $2b$ from $2\cdot (b(x+1)^2)$


How to handle cache metadata in a cacheable response?

Question: I have a custom controller action that returns the HTML for a search result. The action is invoked via AJAX on the search page and the results are inserted into the page body.
The problem is that a dynamic page cache entry is created for this controller action and it's not "busted" when the query string changes, so old results are always returned:
<code>  public function basicPeopleSearch(Request $request) {
    $search = $request->query->get('search');
    $build = [];
    if (!empty($search)) {
      // Get search results and add them to the render array.
      $results = \Drupal::getContainer()->get('pu_search.people_search')->basicSearch($search);

      foreach ($results as $result) {
        $build[] = [
          '#theme' => 'pu_search_person',
          '#person' => $result,
        ];
      }
    }

    // The results will differ based on the "search" query string parameter.
    $build['#cache'] = [
      'contexts' => [
        'url.query_args:search',
      ],
    ];

    $rendered = \Drupal::service('renderer')->renderRoot($build);
    return new CacheableResponse($rendered);
  }
</code>
I suspect this has something to do with how I'm actually returning the response or rendering the output?
Answer: You have to add the cacheable metadata from the render array to the response:
<code>use Drupal\Core\Cache\CacheableMetadata;

  $rendered = \Drupal::service('renderer')->renderRoot($build);
  $response = new CacheableResponse($rendered);
  $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));
  return $response;
</code>


Creating a "Jump Pad" in Unity3D

Question: So I've been going through the internet searching for a way to make me automatically jump when I walk/jump over/onto an object like a cylinder that has been minimized. All I find is tutorials on how to make an object pass through another object that is standing still. What I'm basically asking for is help with OnTriggerEnter and how to actually code the cylinder to make me automatically jump when I walk/jump over/onto it. I've tried a few things out but none seem to be working.
Comment: You want a thing to throw you up when you enter the thing's area?
Comment: Basically, yes. I should be able to adjust the force it pushes me up.
Comment: Something like addForce? https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html
Comment: If you know how to detect collisions using Triggers and how to apply a force to a rigidbody, it should be a piece of cake to do what you want. Please, provide the code you have tried so far, and explain "what does not work"
Comment: I do apologise Hellium, but I just started working with c# yesterday. I have no idea how to make a code that detects collision, but I have seen tutorials on it and it doesn't help because I have no idea what to do after that. I apologise for my lack of knowledge in this matter.
Comment: @Enigma check out the official site https://unity3d.com/learn/tutorials
You will find more than enough to start with and it starts with the absolut basics.
Comment: @Zibelas I appriciate the website link, but since this is a school project I'll be needing to be finished with my assignment and won't have the time to learn the basics. I know enough to make the idea I've got in my head. All I really need is this code
Comment: @Enigma If you have one hour to cut a tree, 50min of sharpening the tools are not wasted time
Comment: @Zibelas I know the "basics" all the tools and stuff, settings and all that. I've made my "map" and I've made a character, mountains, objects, all that. I know the "basics" all I really need is the advanced stuff that won't find it's path to me for some reason. And I've looked into addforce but isn't that just a code to make your character able to jump? I might be wrong though
Comment: If you don't have time to look at tutorials that explain how to do what you want, then you shouldn't be asking questions on Stack Overflow. Stack Overflow isn't where you come to ask people to do your homework for you. You need to make a real attempt at solving your problem, do research, explain what your issue with your code is, and show your work by providing a [MCVE].
Comment: Since I have explained my issue, and I've been through the website and I've even asked the same question there, I think I'm qualified  to ask a question here, don't you?
Comment: I just read your comments under the answer below and I think you need to watch Unity tutorials. You are asking the most basic Unity questions and can't even implement what's in the answer. Please go to Unity's website and learn basic Unity before making your own game.
Comment: If you did read my comment you'd know that I also started yesterday. Not to mention this isn't a "game" it's just a school assignment. I appriciate your thought, wanting me to learn the "basics", but since I haven't yet had an answer to something I've tried to get in about 15 hours I don't think you're qualified to tell me to go and do this on my own. Now, if you have nothing helpful to say, please don't say anything at all. That would be appriciated. Thank you.
Answer: What you can use to throw your player is Rigidbody.AddForce
Using it with an object that is a trigger:
A trigger object:
How can you use it? Like this:
private void OnTriggerEnter(Collider other)
{
    other.GetComponent<Rigidbody>().AddForce(Vector3.up * jumpForce);
}

How to make it throw you up only if you press space?
private void OnTriggerStay(Collider other)
{
    if(Input.GetKeyDown(KeyCode.Space))
        other.GetComponent<Rigidbody>().AddForce(Vector3.up * jumpForce);
}

Using it with an object that isn't a trigger:
A non-trigger object:
How can you use it? Like this:
private void OnCollisionStay(Collision other)
{
    other.collider.GetComponent<Rigidbody>().AddForce(Vector3.up * 300);
}

How to make it throw you up only if you press space?
private void OnCollisionStay(Collision other)
{
    if (Input.GetKeyDown(KeyCode.Space))
        other.collider.GetComponent<Rigidbody>().AddForce(Vector3.up * 300);
}

What AddForce does?
AddForce will add a force to the direction you specify
More info on AddForce: https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html
Comment: Is this all the code that is needed? If I use this code I should be able to walk over an object and said object will make me jump like my space button (jump button)?
Comment: now it will make you jump if you press space. Just put it in the jump Pad and it should work
Comment: I put this on the object I wanted to walk over. I put the second one in as Chi3k3r told me to do. Nothing happened. Am I doing something wrong?
Comment: Check the code now, use the first one for an object with a Trigger, and the second one for a non-Trigger object.
Comment: What do you mean by an object having a "trigger". Apologies, I'm fairly new to c#. I'll put both of these into object (dragging them into the object under the "add component" spot). And let you know if it worked.
Comment: Check the edit I made to my answer
Comment: First, let me inform you about my character. I took my character from the asset store so I actually don't know a lot about the coding the person did with it. Secondly, I tried both of these and it didn't seem to be working. I made a cylinder and minimized it to a platform style thing, jumped on it, stood on it for a few secs, nothing. And then I used the other code that requires me to jump, tried it, and it didn't work. I'm probably screwing this up somehow. I don't have "Is trigger" on in my platform. Should I?
Comment: Don't use "on trigger", instead try the code that doesn't require "On Trigger"
Comment: Oh, I see. So, for the one the requires "On trigger" I didn't have it on, but for the ones that required them off, I had them off and it didn't work. So what I'm going to do now is toggle on trigger and try out the two above yet again. Appriciate all of this, I really do. Thank you for trying to help me with this.
Comment: Also, make sure the character has a Rigidbody
Comment: A rigidbody, got it. I have yet to put a rigidbody in the object, that might be the problem. I'll be back when I've done so
Comment: There is some progress. I have now added a rigidbody and I used the non-trigger using script and the first one of them. I can move the object, but when i jump ontop of it for it to shoot me away, it just shakes and doesn't do anything more than that. And yes, the character has a rigidbody.

Creating a "Jump Pad" in Unity3D


Eclipse Glassfish 3.1 adapter - SEQUENCE already exists error

Question: I have some problems with Eclipse server adapter for Glassfish 3.1. I am using the JPA auto generated identifiers. If the server is running and I have a create-and-drop policy for JPA, than each time the hot redeploy occurs I've got a big fat Eclipse error message thrown in my face:

cannot Deploy MyWebApp Deployment Error for module: MyWebApp:
PER01003: Deployment encountered SQL Exceptions:
PER01000: Got SQLException executing statement "CREATE TABLE SEQUENCE (SEQ_NAME
VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(38), PRIMARY KEY (SEQ_NAME))":
org.postgresql.util.PSQLException: ERROR: relation "sequence" already exists

I am aware that this is just a Glassfish warning (damn old...: http://java.net/projects/glassfish/lists/persistence/archive/2006-11/message/221) and is not dangerous (it's because the drop.ddl is deleting just one sequence-table row instead of the whole table).
It's just a PITA to see this error popup each time I save a resource. Any ideas how to get rid of it without loosing create-and-drop functionality? At least to make it not disturbing while developing...
My persistence.xml
<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0">
    <persistence-unit name="JPATestsCascadePU" transaction-type="JTA">
        <jta-data-source>jdbc/myDB</jta-data-source>
        <properties>
            <property name="eclipselink.ddl-generation"
                              value="drop-and-create-tables" />
        </properties>
    </persistence-unit>
</persistence>
</code>
Exemplary entity using auto generated ID:
<code>@Entity
public class Website {

    @Id
    @GeneratedValue
    private long id;

    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}
</code>
Answer: You won't like this answer: turn off the create-and-drop functionality after you do your initial Run on Server.
To be honest, create-and-drop seems like it will slow down redeployment... which is what is happening when you save a resource.
You can make the message appear less often by turning off automatic publishing...
Note: this issue applies to GlassFish integration plugins for Eclipse released before 2011-10-24 when they interact with GlassFish Server 3.1.1 and younger.
Comment: Thanks @vkraemer! You're probably right about the slowdown of redeployment. However, I used this setup to dynamically test JPA mappings, validation and interaction with transactions. These kind of applications are really small - I treat them just as a smoke-test and therefore I really liked this clean-recreate feature along with automatic publishing on each 'save'. It allows me to hit ctrl+s on changed class and forget about the rest.

I will eagerly for Monday :-) Thanks once again!
Comment: After your addition, the plugin works like a charm. Thanks a lot Vince!
Comment: I am using Glassfish 3.1.2 together with ant, to deploy and then redeploy my classes, so this error also seems to apply to the latest version of Glassfish.


Thread.join not working

Question: A call to join() Guaranteed to cause the current thread to stop executing until the thread it joins with
(in other words, the thread it calls join() on) completes.
However, in my program both the threads are executing simultaneously. Thread1 is not waiting for Thread2 to finish its execution.
What is wrong with my program?
public class Launcher1 {

    public static void main(String[] args) {
        JoinExample runnable=new JoinExample();

        Thread thread1=new Thread(runnable);
        Thread thread2=new Thread(runnable);

        thread1.start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        thread2.start();
        try {
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}

public class JoinExample implements Runnable{
    public void run(){
        for(int i=0;i<10;i++){
            System.out.println("i:"+i+" "+Thread.currentThread().getName());

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

Output:
i:0 Thread-0
i:1 Thread-0
i:0 Thread-1
i:2 Thread-0
i:1 Thread-1
i:3 Thread-0
i:4 Thread-0
i:2 Thread-1
i:3 Thread-1
i:5 Thread-0
i:4 Thread-1
i:6 Thread-0
i:7 Thread-0
i:5 Thread-1
i:8 Thread-0
i:6 Thread-1
i:7 Thread-1
i:9 Thread-0
i:8 Thread-1

i:9 Thread-1
Answer:
However, in my program both the threads are executing simultaneously. Thread1 is not waiting for Thread2 to finish its execution.

No, and it wouldn't - because thread 1 isn't calling join. Look at the docs you quoted again:

A call to join() Guaranteed to cause the current thread to stop executing until the thread it joins with

To put it another way: the join() method doesn't finish until the thread it's called on has finished.
You've got three threads in your program - two that are running JoinExample.run, and the "main" thread that starts the other two. You're telling that main thread to wait for thread 2 to finish, but that's all. Your two JoinExample threads are entirely independent.
Answer: There are three threads in question here.
1st thread - main thread, which runs the main method and spawns the 2 child threads.
2nd thread - thread1
3rd thread - thread2
When you say thread2.join(), the main thread will block until thread2 finishes,thread1 and thread2 will continue to run.

Thread.join not working


Why is the equation for Intra-class correlation aligned with design effect of cluster sampling?

Question: The design effect definition (link) is:
$$
DEFF = 1+ (m-1)*ICC
$$
It is also the relationship between the variance of estimating the mean with the cluster sampling divided by the variance if the sample was a simple random sample.
ICC is defined as (link):
$$ICC = \frac{\sigma_\alpha^2}{\sigma_\alpha^2+\sigma_\varepsilon^2}. $$
However, I cannot find a clear proof showing why the relationship between DEFF and ICC are the ones provided above.
Either a proof or (open access!) reference will be much helpful.
Thanks.
Answer: It took a while, especially because the original Kish's (1965) book is unavailable online for free, and strangely enough in most publications, the ICC is defined by simply rearranging elements from the DEFF formula, instead of using within- and between-variance terms.
However, this handout from the John Hopkins School of Public Health appears to shed some light on the relationship between the ICC as defined in your post and the DEFF formula. Please navigate to the bottom of page 5, which starts with the notion of the Inter-class correlation. Page 6 shows how to rearrange the ICC formulae, and also derives variance for cluster sampling. Then on page 7, you will see its similarity with the DEFF formula.
Comment: Thanks, that is helpful.


Solve a system of 4 equations

Question: How do you find the value of $729a+81b+9c+d-(1000e+100f+10g+h)$
if:
\begin{cases} a+b+c+d=8e+4f+2g+h \\ 27a+9b+3c+d=64e+16f+4g+h \\ 125a+25b+5c+d=216e+36f+6g+h \\ 343a+49b+7c+d=512e+64f+8g+h+13 \end{cases}
This system looks like a system from an AIME problem, but I'm not entirely sure how to approach this because the coefficients are exponents. I am pretty sure there is a way to manipulate these such that you can get rid of many variables, such as $d$ and $h$, but I'm not sure how. A hint to how to start would be appreciated!
I'm sorry I didn't mention what I knew, but I don't really know how to work matrices. Are there any other ways?
Comment: clearly need $1000e$ in the title
Comment: Just from the shape of the problem, I would immediately assume that there is some linear combination of the four equations that gives $729a+81b+9c+d=100e+100f+10g+h$, or something damned close (the $13$ in the last equation is probably there just to give us a non-zero answer at the end), and I would begin to look for said linear combination.
Comment: The exponential coefficients make it hard to know which ones to combine. Any hint for where to combine or maybe get rid of the 13? Or do I just ignore that last equation?
Comment: sorry, my bad! You're right :)
Comment: https://en.wikipedia.org/wiki/Vandermonde_matrix
Answer: The coefficients to multiply the four equations are $-1,4,-6,4$. Then you get your expression as a linear combination of the four equations, and the result is 52
I looked which linear combination of the four equations gives us the right coefficients for $a,b,c,$ and $d$, then I solved the system. Then I verified that I get the right coefficients for $e,f,g,h$ and I have 52 left from multiplying the free term (13) by 4
Comment: I'm sorry, but I'm confused. There are 8 coefficients in total...? Also, how'd you get there? Thanks!
Comment: I only worried about the LHS. Like [this](http://www.wolframalpha.com/input/?i={{1,27,125,343},{1,9,25,49},{1,3,5,7},{1,1,1,1}}^-1*{{729},{81},{9},{1}}). Then, I verified for the RHS.
Comment: Ok, thanks! Is this a Vandermonde Matrix?
Comment: Looking at it, the matrix of a system is a Vandermonde matrix. But I just solved the system using Wolfram Alpha, and I didn't worry about its structure.

Solve a system of 4 equations


Computing the covariance between residuals

Question: I'm doing some self-studying of some modules about using R in linear regression. We were given data for a multiple linear model with two independent variables , $y = X\beta + \epsilon$ where $\epsilon ∼ N(0,2)$:
<code>y        x1  x2
-3.09   3.6 4.4
-2.57   4.2 6.2
-6.19   3.2 6.0
-7.21   5.0 4.3
-0.97   5.3 4.6
-5.70   3.1 3.8
-4.40   5.7 4.9
-4.75   4.2 5.1
-2.21   4.7 5.3
-4.95   4.4 6.0
-7.61   2.5 5.7
-6.70   3.2 6.0
-1.65   4.7 4.5
-2.50   4.1 4.9
</code>
We were first asked to compute the variance of the first residual. I obtained 3.207 (which turned out to be the correct value) after doing the following in R:
<code> mod <- lm(y~x1+x2)
 h <- hatvalues(mod)
 var_e1 = 4 * (1 - h[[1]])
</code>
Then we were asked to obtain covariance between the first and third residual. The answer given to us was -0.1449218, however, I'm stumped about how this is obtained. Having no idea how to start computing this, what's the intuition behind computing the covariance between residuals?
Comment: Are you referring to [autocovariance](https://en.wikipedia.org/wiki/Autocovariance#:~:text=In%20probability%20theory%20and%20statistics,of%20the%20process%20in%20question.)?
Comment: @Dayne I'm not sure if it's that what is being asked since the modules don't even mention time series. The exact wording is "What is the covariance between the first and third residual?".
Comment: Yes, I just wanted to confirm. I have posted an answer. Hope that is what you are looking for.
Answer: Assume model is:
$$y=X\beta+\epsilon$$ where $\epsilon \sim N(0,\sigma^2I)$
The residuals, $\hat{\epsilon_i}$ are estimates of true errors, $\epsilon_i$
The are related to each other by the residual-maker matrix, $M \equiv I-P=I-X(X'X)^{-1}X'$
Therefore,
$$Var(\hat{\epsilon})=Var(My)=MVar(y)M'=\sigma^2MM'$$
Since $M$ is idempotent and symmetric this becomes:
$$Var(\hat{\epsilon})=\sigma^2M$$
So $Cov(\hat{\epsilon_1},\hat{\epsilon_3})=\sigma^2m_{13}=\sigma^2m_{31}$, where $m_{ij}$ is element of Matrix $M$ corresponding to row $i$ and column $j$.
Comment: which is equal to the same element of the hat matrix


Why are nodes and nodal sets called this way?

Question: Nodes of standing waves are points where they are zero. Generally, nodal sets of Laplacian eigenfunctions are the sets of points where they are zero.
Why is this the name for them (that is, why is the English word "node" used)?
Comment: Why the downvote?
Comment: Seems to me simply because such points look like nodes. We say "knopen" in Dutch and Google finds that "nodes" is the English translation of that. What is you native language?
Comment: My native language is Hebrew. What do you mean by that they "look like nodes"? What does a node look like?
Answer: What does a node look like? Let Google be your friend and search for
Pictures of nodes in waves or more general: Pictures of nodes, and find some waves between these.


What does the W value in Wilcoxon test mean

Question: I carried out a wilcoxon test (using wilcox.test in R) in 2 sample groups of size 135 and 48.
My results in r where:
wilcox.test(raj_reps.a, raj_reps.b)

Wilcoxon rank sum test with continuity correction

data:  raj_reps.a and raj_reps.b
W = 2359.5, p-value = 0.005217
alternative hypothesis: true location shift is not equal to 0

My H0 was that the groups are equal in means, the alternative hypothesis was that the values in group a are different (lower) than in group b.
Can I accept H0? as the p-value is lower than 0.05?
What exactly means the W value? I read about it and found out its the number of ranks and used as critical value which I can look up in tables. Unfortunately most of the tables are not covering such huge sample sizes.
Can anyone tell me if this high W means, that I can accept H0 or do I have to reject it?
Comment: The output gives you a [p-value](https://en.wikipedia.org/wiki/P-value#Overview_and_controversy) (see the first sentence of the linked section). You [compare it with your significance level](https://en.wikipedia.org/wiki/P-value#Definition_and_interpretation), rejecting the null if $p\leq \alpha$. Note that it's only a comparison of means if you add additional assumptions
Answer: The Wilcoxon test does not test for equality of means, rather it tests
$$H_0: P(X_a > X_b) = 0.5$$
namely that a randomly drawn observation of group a has 50% chance of being larger than a randomly drawn observation from group b. Only if you see location-shift (i.e. distributions in both groups have the same shape but different mean (location)) than you can formulate your conclusion in terms of means. With the P-value you have you can reject $H_0$ on the 5% significance level. The $W$ is the Wilcoxon test statistic and is, as the name says, the sum of the ranks in one of both groups. You could enumerate the exact distribution of $W$ under $H_0$ by typing
    wilcox.test(raj_reps.a, raj_reps.b, exact=TRUE)

This is very computer-intensive, so usually for such large sample sizes the asymptotic normality of $W$ is used for calculating the p-value, see ?wilcox.test


How to integrate Google + in my android application?

Question:
Possible Duplicate:
Android integrate google+ in app

How to make google + integrate in android application?
And i also saw the post something in my wall...
Thanx.
Comment: http://code.google.com/p/google-plus-java-starter/
Comment: see also http://stackoverflow.com/questions/6518150/is-there-already-a-google-api
Comment: What do you mean "add google+ integration". Can you please expand on what exact functionality you'd like to add?
Answer: You can try http://code.google.com/p/google-plus-java-api/ (haven't tried it on android though)