offsetWidth and offsetHeight adding an extra 10px+ on every other window resize

Question: I have a parent element and a child element. On window resize event, the child element has its width and height set to the parents' offsetWidth and offsetHeight, however on every other resize both the width and height are off by 12px on Firefox and 15px on Edge.
Here's the code, when you resize the page, there's a white gap on the right:

const parent = document.getElementById("parent");
const child = document.getElementById("child");

const matchDimensions = () => {
    child.style.width = parent.offsetWidth + "px";
    child.style.height = parent.offsetHeight + "px";
};

matchDimensions();
window.addEventListener("resize", matchDimensions);
html, body, #parent {
    width: 100%;
    height: 100%;
    margin: 0;
}

#child {
    background: red;
}

Weirdly, it only happens if I scale the page down but not if I scale it up. Also, removing margin: 0 stops this from happening but I need it in order to have the parent fill the entire page.
The reason I'm using JS to match the child to the parent is because in reality the child is a canvas which doesn't automatically resize with the parent with just CSS.
Comment: The gap you see corresponds to the width of the scrollbar of the browser you are using. So, either set overflow of **#parent** to hidden or calculate the scrollbar width via JavaScript and add the result to child.style.width ...
Answer: Referring to my comment, i updated your Javascript code to calculate the srollbar width, add the result to child.style.width and so get rid of the gap.

const parent = document.getElementById( "parent" );
const child = document.getElementById( "child" );

/* Create a temporary element to calculate
   the scrollbar width; then delete it.
*/
const scrollBarWidth = () => {
  let el, width;
  el = document.createElement( "div" );
  el.style.cssText = "position:absolute; visibility:hidden; overflow:scroll;";
  document.body.appendChild( el );
  width = el.offsetWidth - el.clientWidth;
  el.remove();
  return width;
}

const matchDimensions = () => {
  child.style.width = parent.offsetWidth + scrollBarWidth + "px";
  child.style.height = parent.offsetHeight + "px";
};

matchDimensions();
window.addEventListener( "resize", matchDimensions );
html, body, #parent {
    width: 100%;
    height: 100%;
    margin: 0;
}

#child {
    background: red;
}

Answer: Possible the browser has some default styling getting in the way since it changes behavior with the size of the viewport.
You could try a css reset (one example) or normalize to see if that solves the issue.
Comment: I tried both and neither of them worked.
Answer: I think I figured it out. The simple fix is adding overflow: hidden to the parent, which actually makes some sense. Since the child has a fixed width, when the page is resized the first thing to change is the parent, however because of the fixed width the child can't move and so it overflows outside the body which adds a scrollbar. The event then gets triggered with the scrollbar and because the width of the parent is now much less, the child inherits it which stops it from overflowing so the scrollbar disappears. Obviously, this happens very quickly which is why it's not noticeable. It also explains why it only happens when shrinking the window and not expanding it, since expanding wouldn't cause an overflow.
Answer: The issue here is most likely caused by how browsers handle subpixel rendering, which can result in minor fluctuations in element size. To solve this problem, use the Math.round() function to round the width and height values to the nearest whole number. Here's how to change the matchDimensions() function to accomplish this:
JavaScript:

const matchDimensions = () => {
  child.style.width = Math.round(parent.offsetWidth) + "px";
  child.style.height = Math.round(parent.offsetHeight) + "px";
};

This should help to eliminate the white gap on the right that appears in Firefox and Edge. Additionally, if you need to maintain the margin on the parent element, you can add a box-sizing rule to include the margin in the calculation of the element's total width and height:
CSS:

html, body {
  margin: 0;
  height: 100%;
}

#parent {
  width: 100%;
  height: 100%;
  margin: 0;
  box-sizing: border-box;
}

#child {
  background: red;
  width: 100%;
  height: 100%;
}

With these modifications, the child element should resize dynamically to match the parent element's dimensions without any gaps or off-by-pixel issues.


What actions are permitted in an Audio Output Unit's input callback

Question: I am using an Audio Output Unit to capture mic data. I get notified that there is data to read via a callback I have set using the kAudioOutputUnit_SetInputCallback property, and in the callback I read the data by calling AudioUnitRender().
Ultimately, I will be updating the user interface of my app on the basis of some information extracted by analysing this data. I will therefore need at some stage to do a dispatch_async onto the main queue. The analysis is moderately time consuming, and is done in chunks rather larger than those I get from AudioUnitRender(), so the load is bursty.
My question is: what operations are considered acceptable in the implementation of the input callback itself? I've found plenty of sources stating strict restrictions on render callbacks (no memory allocations, no i/o, no synchronisation with other threads, etc), but no information at all about input callbacks.
If I follow the same rules as for render callbacks, I have a bit of a challenge. dispatch_async() itself is undesirable as it allocates memory, and the load is bursty anyway (could easily be longer than one render cycle on some turns, and practically zero on others). It therefore seems necessary to send my data off to a worker thread for processing and for the dispatch_async() calls to be made. However, I still need to manage the passing of the data over to this worker thread. The simplest way (in C++) would be with a circular buffer, plus a mutex and condition variable to signal when data is available. However, that would require the input callback to lock the mutex, which the guidelines on render callbacks explicitly discourage.
Avoiding this mutex lock will take me to lock-free circular buffers, semaphores (POSIX or GCD), spinlocks and the like, and I'm wondering if that is overkill for simply listening to a microphone. There's a shocking lack of documentation for this stuff and I have no idea what's really going on behind the scenes. Do I really need to be concerned about waiting on a mutex (only briefly and rarely locked by another thread) in my input callback implementation?
Answer: I use a circular buffer from: https://github.com/michaeltyson/TPCircularBuffer
The description states:

As long as you restrict multithreaded access to just one producer, and just one consumer, this utility should be thread safe.

So you can both render (produce) and process (consume) from the circular buffer safely without worrying about locks.
Update:
Do I really need to be concerned about waiting on a mutex (only briefly and rarely locked by another thread) in my input callback implementation?
To that I say yes. "Rarely locked" is all you need for an input callback to fail. And "briefly" is already too long. I had input callbacks fail simply for NSLogging something.
Comment: Yeah, as I mention at the end, in order to avoid the mutex lock it looks like I'll need a lock-free circular buffer and something other than a std::condition_variable to get the worker thread to wake up when there's data (GCD semaphore looks most promising for that). This circular buffer implementation is helpful and it's nice that it actually has a *documented* threading guarantee, unlike CARingBuffer, so thanks for that. However, the question still stands as to whether avoiding the mutex is actually necessary in an input callback.


Injective and / or surjective: factorial

Question: I would like to know if my reasonment are correct, so thank you in adavance for every critic or missing detail you will point out.
The question is: consider $f: \mathbb{N}\to \mathbb{N}$ definied by $f(n) = n!$, hence the factorial.
I was thinking about this in some terms: function, injection, surjection.
So first of all, I would indeed say $f(n) = n!$ is a function.
Due to lack of self confidence, I searched over here for the correct definition and I found this one in an answer: "The definition of a function is: $f: A\to B$ is a function if every $x\in A$ is in relationship with at least one $y \in B$"
I didn't really get why "at least one", since for a function I would say just exacly one...
Anyway: due to this, I hence conclude $f(n) = n!$ is indeed a function.
Now, about the injectivity I say: no.
Indeed it's not true that $\forall n_1, n_2 \in\mathbb{N}$ we have $n_1! = n_2! \iff n_1 = n_2$: just take $n_1 = 0$ and $n_2 = 1$.
About the surjectivity: no again.
Indeed the codomain of $f$ is $\mathbb{N}$ which is ways larger than its image (or range).
But I thought: can I say it becomes surjective if the codomain becomes its range like?
$$C = \{ 1; 2; 6; 24; 120; \ldots \}$$
Also I was thinking: If we cut off $\{ 0 \}$ from the domain, then $f(n) = n!$ becomes injective too.
But this means it's bijective, hence invertible.
So then what is the inverse of $f(n) = n! \qquad $??
Comment: Note:  many people do not consider $0$ to be a natural number.  It's fine if you do, but you should clarify that point.  Makes a difference here, since $f(0)=f(1)$ is the only failure of injectivity in the non-negative integers.
Comment: If you include $0$ in $\mathbb{N}$ your argument for non-injectivity is correct.
Comment: And yes, every function becomes surjective if you restrict its codomain down to its image.  That's trivially true.
Comment: @lulu You're right! I have been taught $\mathbb{N}$ with Peano Axioms, where $0$ is in $\mathbb{N}$
Comment: @Randall Thank you so much! Can you please clarify the "at least one" part in the definition of function I rewrote here? It made me to think...
Comment: In that case the inverse function $g$ is just the function $g(n)= m$ where $m$ is the unique element with $m!=n$.
Comment: @Numb3rs my only guesses are that (a) the source has the wrong definition of function or (b) that isn't the end of the definition:  there's more that follows.  Not having the source, I don't know.
Comment: @Randall Unfortunately I lost the page, ugh. But in the case there is something else, would you be able to "guess" (or know) what could be said to make that definition well posed?
Answer: First, let's define $\mathbb{N}=\{0, 1, 2, ...\}$ to be unambiguous. Then we will denote $\mathbb{N}^+$ to be $\mathbb{N}\setminus\{0\}$.
You have a correct argument for the non-injectivity of $f$ with domain $\mathbb{N}$. $f$ is injective on $\mathbb{N}^+$, since for all $j>k\geq 1$, $j!>k!$ (why?). $f$ is not surjective on $\mathbb{N}$ or $\mathbb{N}^+$ (for example, there does not exist $n\in\mathbb{N}$ or $n\in\mathbb{N}^+$ such that $n!=3$). If you restrict the codomain to the image, then it is trivially surjective, and its inverse is directly related to its preimage. That is, define $f:\mathbb{N}^+\to C$ by $f(n)=n!$. Then $g:C\to\mathbb{N}^+$ is the two-sided inverse of $f$, with $g(m) = n$ where $n$ is the only element in $f^{-1}(m)$ (the preimage of $m$).


Android: Using LayoutParams to set width of View object

Question: I have a UI element that I am working with in my Android app that has a custom width.  The UI element essentially is a block with two green circles - one circle on the left of the block, and the other circle on the right of the block.
I want to be able to set the width of the whole UI element programmatically.  The circles should always have a constant size, and then the block sitting in the middle should size itself to fill up the rest of the space.
Here is what I currently have:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <View
        android:background="@drawable/green_circle"
        android:id="@+id/left_green_circle"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_weight="1"
        android:layout_gravity="center_horizontal"
    />

    <View
        android:background="@drawable/blue_rectangle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_gravity="center_horizontal"
    />

    <View
        android:background="@drawable/green_circle"
        android:id="@+id/right_green_circle"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_weight="1"
        android:layout_gravity="center_horizontal"
    />

</LinearLayout>

I then set the layout parameters of the View in code like this:
int layoutLeft = block_x_position - green_circle_width;
int layoutWidth = block_width + (green_circle_width * 2);

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(layoutWidth, block_height);
layoutParams.setMargins(layoutLeft, block_y_position, 0, 0);
this.setLayoutParams(layoutParams);

this.requestLayout();

I am using a RelativeLayout in the code above because the parent of this whole View element is a RelativeLayout.  Unfortunately, I am not getting the results that I would expect.  My "block_width" variable is "40dp", and my "green_circle_width" variable is "20dp".  Here is what I am getting:

I have tried using "wrap_content" instead of "match_parent" in my View XML, but that doesn't have any affect at all.  Any idea why my block is getting extended past the width that I would like it to be extended?
Thanks for any help.
Comment: how about some padding to the right?
Answer: You are seeing cut off circles because (I'd imagine) the width of the green circle images (jpg or png) is greater than 20dp. If you want to scale the green circles use an imageView and set the scaleType attribute.
Otherwise you're getting exactly what you want. By forcing the circle views to be 20dp, you're creating a lot of extra space for the block to fill up. Set the circle width correctly or use a scaleType and it will work.
As an aside, you probably shouldn't use match_parent as the width of the block (which implies it will take up the whole width, including the space that is supposed to be occupied by the circles). Instead use some arbitrary width (0dp for example) and set the layout_weight to 1.
Comment: I'm more worried about the extra width I am seeing in the rectangular block than the fact that the circles are cut off.  The circles are being cut off simply because the rectangular block is pushing them off the boundaries of the measured width.  I simply want the blue block to take up all the space the green circles don't take up.
Comment: Sorry, one more comment: The green circles aren't images.  They are separately defined XML drawable shapes, defined as such:

So I define the shape independently, and then I use that shape in the XML I posted previously, and I give it a size there.
Comment: Ahh got it, thanks for the correction. You don't want to set all three views to have layout weight of 1, that implies that you want them all to be of equal width. Just set the block to layout_weight of 1, and the circles to be whatever size with no weight. Try that (and setting the block width to something other than fill_parent).


Expected area of rectangle

Question: This question is taken from Rice - Mathematical statistics.
A random rectangle is formed in the following way: The base, X, is chosen
to be a uniform [0, 1] random variable and after having generated the base,
the height is chosen to be uniform on [0, X]. Use the law of total expectation,
Theorem A of Section 4.4.1, to find the expected circumference and area of the
rectangle.
I have trouble understanding the answer for finding the expected area of rectangle.
Let H be the height of the rectangle. The area is XH, so
$E(XH) = E(E(XH|X)) = E(XE(H|X)) = 1/2 E(X^2)$
Can someone kindly explain how do you derive the 3rd part from the 2nd part of the equation ?
Comment: It's a basic property of conditional expectation. Haven't you encountered that in the book yet?
Comment: You may check this [wikipedia page](https://en.wikipedia.org/wiki/Conditional_expectation#Basic_properties). "_If $X$ is $\mathcal{H}$-measurable, then $E(XY\mid\mathcal{H})=XE(Y\mid\mathcal{H})$._"
Comment: No. which property are you referring to?
Answer: Do you know what $E(XH|X)$ means? It is expected value of $XH$ if we know $X$. So X is a constant, and $E(cH)=cE(H)$ - this is a common property of expectation.

Expected area of rectangle


How to render a template declared in hook_theme directly in a twig template without preprocess?

Question: Lets say I have a hook_theme like this :
<code>/**
 * Implements hook_theme().
 */
function mytheme_theme($existing, $type, $theme, $path) {
  return [
    'partial' => [
      'variables' => ['current_url' => NULL],
      'template' => 'partial'
    ]
  ];
}
</code>
Then in a node.html.twig, I want to call the template.
Currently I'm doing this :
<code>{% include '@mytheme/partials/partial.html.twig' {'current_url': url('<current>')} %}
</code>
But the problem with this is that I never go into my
<code>function mytheme_preprocess_partial(&$variables) {}
</code>
Also I can't benefit from the TWIG DEBUG mode.
Is there any way to do something like this :
<code>{{ theme('partial', {'current_url': url('<current>')}) }}
</code>
Thanks for helping.
Answer: In D8 there is no theme() function, so if you want to render a template you use a render array for it. Put it in a twig variable and print it:
<code>{% set partial = {
  '#theme': 'partial',
  '#current_url': url('<current>'),
} %}

{{ partial }}
</code>
As a side note, because of a security issue for Twig in Views you might be no longer be able to do this in Drupal 8.6 and are forced to use PHP in the near future. There is an ongoing discussion what to do about the code execution vulnerability without (hopefully) preventing such valid use cases, see https://www.drupal.org/project/drupal/issues/2860607
Comment: Thank you for that very clear and documented answer. I'll keep an eye on that topic :-)


Drupal path wildcard but not on all levels

Question: I have created a view page which shows all the work project thumbnails by default and then there is a block included on the page which filters the view (but not using ajax) it just added the company name into the url and it filters using contexual filters. The thumbnails in the grid take you to the project node page. I would like to include the filter sidebar block on all of the urls under www.sitename.com/work, so work & work/companyname/ but not on the node page which is www.sitename.com/work/companyname/projectname.
I have tried all possible ways of doing it within the path field.
work
work/*
work/*/~
work/*/~/
work/*/~/~

Is there anyway to include this block on all paths work/companyname but not any deeper?
Comment: Have you tried the [context](https://drupal.org/project/context) module? It allows you to display blocks according to numerous aspects of your Drupal site.  Therefore, you can make a condition specific to the pages you want it to show on - and attach it to that context...
Answer: You could enable the core PHP Filter module. Then you can use php to set the block visibility e.g. using preg_match().
If you're not sure about regex take a look at http://www.regextester.com/.
EG to show block in admin and admin/structure but not admin/structure/blocks etc:
<?php
  return preg_match('/^admin(\/structure)?(\/)?$/', $_GET['q']);;
?>

Comment: You could do it this way, but I've heard the PHP Filter module can create some vulnerability to the site.
Comment: That's poss of course if you add it to a text format (don't). Or if you do silly things in your PHP snippets. But I don't see a problem adding php to a block filter. e.g.
Orr you could try [Extended Block Visibility](https://drupal.org/project/extended_block_visibility), but it requires you to implement a custom module.
Answer: What you are looking for is support for globbing (https://github.com/begin/globbing#wildcards). Unfortunately, Drupal does not support globbing out of the box.
In modern globbing implementation, * would match on any character but /, and ** would match on any character, including /.
In order to implement this support, one would need to:

Look how PathMatcher (core/lib/Drupal/Core/Path/PathMatcher.php) service matches the path.
Extend it into own custom service where only matchPath() will be overridden.
Replace the content of matchPath() with the code below (this is a copy of the original matchPath() with some alterations).
Alter included service to use your custom path matching (for block only or whole site).
Update configuration of blocks to use ** for full path matching and * for subpath only.

/**
 * {@inheritdoc}
 */
public function matchPath($path, $patterns) {

  if (!isset($this->regexes[$patterns])) {
    // Convert path settings to a regular expression.
    $to_replace = [
      // Replace newlines with a logical 'or'.
      '/(\r\n?|\n)/',
      '/\\\\\*\\\\\*/',
      // Quote asterisks.
      '/\\\\\*/',
      // Quote <front> keyword.
      '/(^|\|)\\\\<front\\\\>($|\|)/',
    ];
    $replacements = [
      '|',
      '.*',
      '[^\/]*',
      '\1' . preg_quote($this->getFrontPagePath(), '/') . '\2',
    ];
    $patterns_quoted = preg_quote($patterns, '/');
    $this->regexes[$patterns] = '/^(' . preg_replace($to_replace, $replacements, $patterns_quoted) . ')$/';
  }
  return (bool) preg_match($this->regexes[$patterns], $path);
}

Note that this code only adds additional token replacement ** and alters what * token does (any character but /).


Two right triangles with known hypotenuses and two known points

Question: I'm trying to write formula for calculating some movement paths for a two servo "leg", first servo being $\alpha$, and second servo being $\beta$, and distance from first servo to second servo is 7 cm, and the distance from the second servo to the end of the leg is 10 cm. End of the leg has to be 7 cm right and 4 cm down from the first servo (See the geometry from the image).
Calculating the needed movement paths requires essentially figuring out a formula to calculate lengths for AC (+ BC) and ED (+ BE) OR $\alpha$ and $\beta$.
I was able to calculate the values with Wolfram alpha's system of equations solver, but I was unable to figure out the formulas I could use in my program to calculate the needed values (Wolfram alpha functions)
the geometry:
Answer: $$7\sin\alpha-10\cos\beta=-4$$$$7\cos\alpha+10\sin\beta=7$$
square them and add to each other
$$49-140(\sin\alpha\cos\beta-\cos\alpha\sin\beta)+100=65$$
$$140\sin(\alpha-\beta)=84$$
$$\alpha-\beta=\arcsin\frac{84}{140}=\arcsin\frac{3}{5}$$
Now you can turn back to image

You can see that $|BF|=\frac{21}5$ and $|AF|=\frac{28}5$
So $|AG|=\frac{28}{5\cos\beta}$
Then you have $7-\frac{28}{5\cos\beta}=4\tan\beta$ from the triangle GDD'
$$7\cos\beta-4\sin\beta=\frac{28}5$$
Divide this by $\sqrt{7^2+4^2}=\sqrt{65}$
$$\frac7{\sqrt{65}}\cos\beta-\frac4{\sqrt{65}}\sin\beta=\frac{28}{5\sqrt{65}}$$
$$\beta+\arccos\frac7{\sqrt{65}}=\arccos\frac{28}{5\sqrt{65}}$$
So $\beta=\arccos\frac{28}{5\sqrt{65}}-\arccos\frac7{\sqrt{65}}$ and $\alpha=\arccos\frac{28}{5\sqrt{65}}-\arccos\frac7{\sqrt{65}}+\arcsin\frac{3}{5}$
Comment: I just remembered a better keyword for the issue, inverse kinematics. After studying for a while, I realized that my approach was not optimal. Here is a similar situation, that is solved more efficiently: https://oscarliang.com/inverse-kinematics-and-trigonometry-basics/
Comment: @user3439124 Great, didn't know for this. That has some real purpose


how to change alphabetic order to descending order in drupal 7

Question: I have a accordion menu in left side and the menu list come as alphabet order but i want newest come first. how can i change the sorting of that list.

Comment: How you've added accordion to menu?
Comment: i have create the menu first named Event and then create the content under this menu like Abc, New Event and all. In the accordion menu configuration change the menu source to event and choose the position left sidebar
Answer: Drupal menu items are manually ordered. You can drag and drop into the correct order here: /admin/structure/menu/manage/navigation
Comment: i am not talking about admin menu, i need to sort the accordion menu list according to the descending order


Filter a list based on a selection

Question: Given the data below, I have two select lists, the first select list is to display the name of each person... the second select list is two display the name of the children of the selected person. Using lodash what is the easiest way to do this?
const people = [{
    id: "1",
    name: "bob",
    gender: "male",
    children: [{
      id: "1",
      name: "sarah"
    }]

  },
  {
    id: "2",
    name: "tom",
    gender: "male",
    children: [{
      id: "1",
      name: "lisa"
    }]

  },
  {
    id: "3",
    name: "sue",
    gender: "female",
    children: [{
      id: "1",
      name: "larry"
    }]

  }
]

Answer: Please find the solution as below:
import map from "lodash/map";
import partialRight from "lodash/partialRight";
import pick from "lodash/pick";
import find from "lodash/find";

const test = [
  {
    id: "2",
    name: "tom",
    gender: "male",
    children: [
      {
        id: "1",
        name: "lisa"
      }
    ]
  },
  {
    id: "3",
    name: "sue",
    gender: "female",
    children: [
      {
        id: "1",
        name: "larry"
      }
    ]
  }
];

// Person selection list
const persons = map(test, partialRight(pick, ["id", "name", "gender"]));
// Replace selected person value in `persons[0]`.
const childrens = find(test, item => item.id === persons[0].id).children;

Filter a list based on a selection


jQuery - When looping out additional data from database, looped button doesnt work

Question: Initially, I'm looping out 10 comments from the database. Then, with the SHOWMORE button I'm looping out 4 more comments each time clicked. However, as from the 14th comment, the looped button, CONSENT THIS doesnt work(sort of a vote button)

ideas.php

<?php
$postshow = "SELECT * FROM ideas_1 ORDER BY consents DESC LIMIT 10";
$done = mysqli_query($conn, $postshow);
?>

    <?php
while ($show = mysqli_fetch_assoc($done)) {
    $postid = $show['postid'];
    $userid = $show['userid'];
    $consents = $show['consents'];?>

    <?php echo$show['post'];?>

   <?php echo$show['consents'];?> Consents

     <?php $asd = "SELECT * FROM consents WHERE dept = 'ideas' and task = '1' and postid = '$postid' and voterid = '$id'";
      $doit = mysqli_query($conn, $asd);
      $exist = mysqli_num_rows($doit);
      if ($exist == 0){ ?>
    <button class = 'consents' data-postid = '<?php echo$postid;?>' data-posterid ='<?php echo$userid;?>'
    data-voterid = '<?php echo$id;?>' data-consents = '<?php echo$consents;?>' >Consent This</button>
     <?php } ?>

<?php }
?>

<?php
     $more = "SELECT * FROM ideas_1";
     $more1 = mysqli_query($conn, $more);
     if (mysqli_num_rows($more1)>10) {
     ?>
     <button id = 'showmore'>Show more</button>
     <?php }?>

load-ideas.php

<?php
include ('header.php');
if (isset($_SESSION['id'])){
    $id = $_SESSION['id'];
} else {
    header("Location: index.php");
}
include('dbh.php');
$commentNewCount = $_POST['commentNewCount'];

$postshow = "SELECT * FROM ideas_1 ORDER BY consents DESC LIMIT $commentNewCount";
$done = mysqli_query($conn, $postshow);

while ($show = mysqli_fetch_assoc($done)) {
    $postid = $show['postid'];
    $userid = $show['userid'];
    $consents = $show['consents'];?>

    <?php echo$show['post'];?>

   <?php echo$show['consents'];?> Consents

     <?php $asd = "SELECT * FROM consents WHERE dept = 'ideas' and task = '1' and postid = '$postid' and voterid = '$id'";
      $doit = mysqli_query($conn, $asd);
      $exist = mysqli_num_rows($doit);
      if ($exist == 0){ ?>
    <button class = 'consents' data-postid = '<?php echo$postid;?>' data-posterid ='<?php echo$userid;?>'
    data-voterid = '<?php echo$id;?>' data-consents = '<?php echo$consents;?>'>Consent This</button>
     <?php } ?>

<?php }
?>

What am I doing wrong?
Comment: @classifyed98, Roko already answered what i meant to say.
Comment: You need to bind `click` event to the new buttons.
Comment: Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) prepared statements with bound parameters as described in [**this post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php).
Comment: @doutriforce Isn't the click event already binded with the button? I'm confused
Answer: Since you populate your document dynamically with more .consents buttons -
 you need to dynamically delegate your click to those elements by using the jQuery .on() method with delegated events

$(staticParent).on(eventName, dynamicChild, callbackFn)

or in your case:
$(document /*or rather a static parent selector*/ ).on("click", ".consents", function) {

same goes for any other element that is dynamically generated.
Also don't use fetch_assoc, rather use prepared statements with PDO
Additionally don't trust input values without sanitization filtering using filter_input, filter_var etc.
Comment: it is the first time im seeing this delegation code. Could you tell me how to use this or give me a link? Sorry, i'm relatively a newbie! @Roko C. Buljan
Comment: @classifyed98 I posted both a link and how you should use it in my answer.
Comment: Thanks bro! @Roko C. Buljan


Jest/Enzyme | Cannot destructure property on null or undefined

Question: I am trying to test my function for ComponentDidMount. But I get this error:Cannot destructure property params on null or undefined.
The function I want to test is this one:
  componentDidMount() {
    this.fetchUser();
  }

And it is depended on this one:
  fetchUser = () => {
    getUser(this.getUserUsername()).then(username => {
      this.setState({
        user: username.data
      });
    });
  };

which in return is depended on this one:
  getUserUsername = () => {
    const { match } = this.props;
    const { params } = match;
    console.log(params, 'params'); // return an object { username: "john" }
    console.log(match, 'match');
    **// return an object
    // { isExact: true
    //  params:
    // username: "john" .
    // __proto__: Object
    // path: "/management/users/:username"
    // url: "/management/users/john" }**
    return params.username;
  };

And here is my test:
  describe('componentDidMount', () => {
    it('should call fetchUsers function', () => {
      const match = { params: 'testName' };
      const params = match;
      const fetchUserFn = jest.fn(params);
      const wrapper = shallow(<UserDetailsScreen fetchUsers={fetchUserFn} />, {
        disableLifecycleMethods: true
      });
      wrapper.instance().componentDidMount();
      expect(fetchUserFn).toHaveBeenCalledTimes(1);
    });
  });

But I get the above error. Not sure what I need to do, and while I found answers similar to this problem, the answers don't solve my problem.
CODE for getUser:

export const getUser = username => {
  const options = {
    method: httpMethod.GET,
    url: endpoint.GET_USER(username)
    // The GET_USER is an endpoint for
    // that specific username
  };
  return instance(options);
};

The above returns a promise.
Comment: please add code for getUser function
Comment: parmas? That looks like a spelling mistake rather than a code error.
Comment: No the `parmas` is my spelling error. Syntax is correct.
Comment: Just updated the desc, and added the code for `getUser`. @akshay
Answer: Try below syntax
describe('componentDidMount', () => {
  it('should call fetchUsers function', () => {
    const match={params: {username: 'akshay'}, isExact: true, path: "", url: ""}
    const fetchUserFn = jest.fn(match);
    const wrapper = shallow(<UserDetailsScreen match={match} fetchUsers={fetchUserFn} />, {
      disableLifecycleMethods: true
    });
    expect(wrapper.containsMatchingElement(
Details for 1
)).toBeTruthy();
  });
});

also you can use containsMatchingElement
Answer: You are destructuring parmas for some reason, did you mean params?
Try to search throughout the APP for parmas and check if you have a spelling mistake.


C# SQL Sum of a column (salary) where the ID = 2

Question: I've managed to sum the whole column, but that's not what I wanted. I need the sum of column(salary) values by a button click where the Employee ID is the same as in a TextBox(txtBox1)
My code:
label4.Text = "0";
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
      label4.Text = Convert.ToString(double.Parse(label4.Text)
           + double.Parse(dataGridView1.Rows[i].Cells[2].Value.ToString()));
}

Now I need something like that "select sum(salray) from employee where Employee_ID='" + txtBox1 "')";
Comment: Don't concatenate SQL like that based purely on user input. Use parameterized queries!
Comment: I'm confused. Do you want the sum of a column in your database or in your DataGridView?
Comment: Aside: summing in a text label, like you do here, is terribly inefficient and also brittle. It's much better to do the sum in a local variable with the type of the cell value's native format (int, double, or whatever) and then assign the result to the label once done looping.
Comment: This code is not enough to answer your question.
Comment: Don't see any sql here
Answer: What you want to do is pretty simple and there is no sql needed.
I assume that you have multiple employees inside your Datagrid and a structure like this:

EmployeID
Year
Salery

1
2018
100000

2
2018
100000

3
2018
100000

1
2019
100000

1
2020
100000

The only thing you have to do is to check the Id value of each row.
If it matches the given Id, Sum up the saleries. If not continue
label4.Text = "0";
string employeId = filter.Text;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
      if(!string.IsNullOrEmpty(employeId))
      {
           if(dataGridView1.Rows[i].Cells[0].Value.ToString() == employeId)
           {
                label4.Text = Convert.ToString(double.Parse(label4.Text)
                + double.Parse(dataGridView1.Rows[i].Cells[2].Value.ToString()));
           }

      }
}


Combo Cidades com laravel 5.2

Question: Estou iniciando meus estudos sobre Laravel. Meu projeto é um simples cadastro de clientes onde gostaria de fazer um combo dos Estados com Cidades.
Seguem códigos:
MODEL ESTADOS
<?php

namespace SGW;

use Illuminate\Database\Eloquent\Model;

class Estado extends Model
{

    public $timestamps = false;
    protected $table = 'estados';
    protected $guarded = ['id'];

     protected $fillable = array(
        'nome',
        'sigla',
    );

    public function cidades()
    {
        return $this->hasMany('SGW\Cidade');
    }
}

MODEL CIDADES
<?php

namespace SGW;

use Illuminate\Database\Eloquent\Model;

class Cidade extends Model {

    public $timestamps = false;
    protected $table = 'cidades';
    protected $guarded = ['id'];

    protected $fillable = array(
        'cidade',
        'estado_id',
    );

    public function estado()
    {
        return $this->belongsTo('SGW\Estado');
    }
}

CIDADES CONTROLLER
<?php

namespace SGW\Http\Controllers;

use Illuminate\Support\Facades\DB;
use SGW\Cidade;
use Illuminate\Support\Facades\Request;
use Session;
use SGW\Estado;

class CidadesController extends Controller
{

    private $estadoModel;
    public function __construct(Estado $estado)
    {
        $this->estadoModel = $estado;
    }

    public function getCidades()
    {
        $estado = $this->estadoModel->findOrFail(13);
        $cidades = $estado->cidades()->getQuery()->get(['id', 'cidade']);
        return Response::json($cidades);
    }

    public function estado()
    {
       return $this->belongsTo('SGW\Estado', 'estado_id')
    }
}

ROUTES
Route::get('/', function () { return view('layout.index'); });
Route::resource('empresa', 'EmpresasController');
Route::get('/empresa/get-cidades', 'CidadesController@getCidades');

HTML CADASTRO

           *Estado
           <select class="form-control" id="estado"  name="estado" required>
               <option value=""></option>
                @foreach ($estados as $e)
                    <option value="{{$e->id}}">[ {{$e->sigla}} ]  - {{$e->nome}}</option>
                @endforeach
            </select>

          *Cidade
          <select class="form-control" id="cidade" name="cidade"></select>

@section('post-script')

@stop

Executando a aplicação ao selecionar o estado não são mostradas as cidades  mas o texto "Selecione uma cidade" é exibido. Poderiam me ajudar?
Ah para teste passei um id do estado direto na consulta.
Answer: Adicionei um alert no retorno da função $.get conforme.
Código abaixo:

< script type = "text/javascript" >

  $('select[name=estado]').change(function() {

    var idEstado = $(this).val();

    $.get("{{ action ('CidadesController@getCidades') }} ", function(cidades) {

      alert(cidades)

      $('select[name=cidade]').empty();
      $('select[name=cidade]').append("<option value='' disabled selected style='display:none;'>Selecione uma cidade</option>");

      $.each(cidades, function(key, value) {
        $('select[name=cidade]').append('<option value=' + key + '>' + value + '</option>');
      });

    });

  }); < /script>

A mensagem que recebo é: "Esta empresa não existe!".
Não sei porque mas o local onde defini este texto foi na classe EmpresasController.
EmpresasController
class EmpresasController extends Controller
{
    public function index()
    {
        $empresas = Empresa::all();
        return view('empresa.index')->with('empresas', $empresas);
    }

    public function create()
    {
        $estados = Estado::all();
        return view('empresa.create')->with('estados', $estados);
    }

    public function edit($id){

        $empresa = Empresa::find($id);
        if(empty($empresa)){
            return 'Esta empresa não existe!';
        }
        return view('empresa.edit')->with('e', $empresa);
    }

    public function show($id)
    {
        $empresaDetails = Empresa::find($id);
        if(empty($empresaDetails)){
            return 'Esta empresa não existe!';
        }
        return view('empresa.show')->with('e', $empresaDetails);
    }

}

Será que a rota está correta?
Comment: Essa é uma nova pergunta... deveria ser postada novamente e não aqui. Se a resposta está correta para o tópico em questão, marque como respondida e inicie um novo tópico. Sugiro, porém, que analise seu código parte a parte e tente dividir as funções. Pois a Empresa não tem nada a ver com a cidade e estado, ainda que tenha uma cidade e um estado, pois a consulta que está fazendo é independente da empresa. "Dividir e Conquistar!" Espero ter ajudado. Abs
Answer: O script deveria ficar assim:
@section('post-script')

@stop

key ao invés de value.id; e
value ao invés de value.cidade.
Pois está recebendo dentro da função o campo e não o objeto.
Espero ter ajudado.
Comment: Coloquei um **alert(cidades)** no retorno da função **$.get**. O parâmetro cidades está trazendo a frase **"Esta empresa não existe"**. Bom, onde defini este tipo de texto foi na classe EmpresasController
Comment: Certo, então deve haver algum filtro antes com relação à empresa que está bloqueando. Tente fazer por partes e veja que o código acima funciona. =) E só um comentário, seria um ** alert(cidade)**... mas como nem _cidades_ está trazendo a questão é antes disso. De qualquer maneira com o código acima, quanto estiver funcionando, vai preencher seu select corretamente. Abs!

Combo Cidades com laravel 5.2


How do I import a csv-file into a table via Drupal?

Question: I would like to import a csv into a table via Drupal. I use Drupal 7.
I create a content type 'Import', which contains a File field to upload a file to the server (destination: sites / default / files / import / *)
When I validate my form content 'Import', I will wish to make a db_query ()
<code>db_query ("
LOAD DATA INFILE '$ csv_filename' INTO TABLE $ temp_table
FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\\n'
IGNORE 1 LINES ");
</code>
$ csv_filename, I test the relative and absolute way, but drupal tells me it can not find the file. I even give the rights to the file to test 777 but it is not ca.
$ temp_table is my table, it already exists in the database.
You would know the procedure and a use case that works for this query?
Answer: I don't know if this quite what you're looking for, but the Feeds module can import CSV content into nodes. Perhaps it could help...

Import or aggregate data as nodes, users, taxonomy terms or simple database records.

One-off imports and periodic aggregation of content
Import or aggregate RSS/Atom feeds
Import or aggregate CSV files
Import or aggregate OPML files
PubSubHubbub support
Create nodes, users, taxonomy terms or simple database records from
import
Extensible to import any other kind of content
Granular mapping of input elements to Drupal content elements
Exportable configurations
Batched import for large files
Comment: Thank you for the info.
Made in, I had to matter *. Csv file that I sort to update the nodes.
I go through reading the file and adding line by line.


Model for spatiotemporal and discrete variables

Question: I have a situation where I am monitoring events at 50 or so geographical sites in a town and at each of these sites, I am making measurements regarding the count of certain particles (so the measurements are discrete). The measurements are done every 5 minutes and we have been monitoring these sites for many months now.
Now, what I am interested in is spatiotemporal interpolation and extrapolation i.e. be able to forecast these counts at the sites say 15 minutes in the future at these sites (and perhaps also in their vicinity).
As far as I understand it, this is equivalent to fitting some sort of a function where the output depends on the spatial and temporal coordinates. I am at a complete loss on how I can do something like this in the sense of how to model this discrete output and the spatiotemporal aspect.
I have played a bit with time series analysis but that has always been  predicting a continuous output which is only a function of time.
Does anyone know of any toolkits I can use for just trying some pre-made models on my data? I do not want something latest and greatest, even a "simple" model would do! I just want to see what it would generate on our data as a first step.
Comment: Have you tried machine learning ? Let is figure out the necessary spatiotemporal dependence on the nodes.
Comment: @onurcanbektas I have not thought about that yet. Can you recommend some ML frameworks/paradigms for learning such models?
Answer: The typical approach to this problem is land-use regression (LUR).
LUR hybridize methods for correlated data analysis and spatiotemporal dependence structures. Typically, at each site, there are one or more covariates which can be predicted at each geographic location, like proximity to highway, season, time of day, elevation, or other features. It's desirable to condition on these factors to increase predictive accuracy and consequently decrease spatiotemporal dependence. To handle the residual dependence structure, variograms are used to assess the extent of residual correlation over time and space, and these can estimate the variance-components of complex autoregressive covariance structures.
There are quite a number of good review articles on LUR, one for instance is here:
https://www.sciencedirect.com/science/article/pii/S1352231008005748 but pubmed will be your guide.
Comment: @Luca easy peasy.
Comment: This is a very interesting method. I, of course, need to look into more detail but I am guessing that it can be extended to work with counts or Poisson statistics.
Comment: hahaha....for you, perhaps :)


airflow tells me to delete ~/airflow/airflow.cfg. But when I do, it keep getting re-created

Question: <code>AIRFLOW_HOME=/path/to/my/airflow_home
</code>
I get this warning ...
<code>>airflow trigger_dag python_dag3
/Users/alexryan/miniconda3/envs/airflow/lib/python3.7/site-packages/airflow/configuration.py:627: DeprecationWarning: You have two airflow.cfg files: /Users/alexryan/airflow/airflow.cfg and /path/to/my/airflow_home/airflow.cfg. Airflow used to look at ~/airflow/airflow.cfg, even when AIRFLOW_HOME was set to a different value. Airflow will now only read /path/to/my/airflow_home/airflow.cfg, and you should remove the other file
</code>
I complied and deleted ~/airflow/airflow.cfg, but it keeps coming back.
Is there some way to tell airflow to stop re-creating this?
Running on macOS Mojave
<code>>pip freeze | grep air
apache-airflow==1.10.6
</code>
Answer: Have you created a systemd service for airflow server?
I think the ~/airflow folder is recreated again and again because you run webserver as daemon mode (maybe launchctl? I am not familiar with macOS)
You should figure out how to pass the enviroment variables to the daemon process. On Linux platform, when daemon configuration is created, "Environment=AIRFLOW_HOME=/path/to/my/airflow_home" is neccessary.
<code>[Unit]
Description=Airflow webserver daemon
After=network.target postgresql.service mysql.service redis.service rabbitmq-server.service
Wants=postgresql.service mysql.service redis.service rabbitmq-server.service

[Service]
EnvironmentFile=/etc/sysconfig/airflow
Environment="AIRFLOW_HOME=/path/to/my/airflow_home"
User=airflow
Group=airflow
Type=simple
ExecStart=/bin/airflow webserver
Restart=always
RestartSec=5s

[Install]
WantedBy=multi-user.target
</code>


x is correlated with y but log(x) is uncorrelated with log(y)

Question: I ran an experiment where I experimentally (randomly) manipulated $x$ to find out the effect on $y$. Both variables tend to have power law distributions, and this was indeed the case.
I ran some regressions and found out that $x$ is positively correlated with $y$ but $log(x)$ is uncorrelated with $log(y)$. Not only is it insignificant, the point estimate is actually negative. One can make a theoretical case for using either levels or logs.
What should I do for the purposes of an academic paper?
Comment: What would the purposes of the academic paper be?  Regardless, one thing you should do in any case is to determine whether either correlation coefficient is sensitive to a small number of data values (as the power law distribution suggests might be the case).
Comment: Have you plotted $x$ against $y$, $\log x$ against $\log y$ and so forth?
Answer: The correlation in the linear scale is probably being driven by few data points, and the influence of these data points is reduced in the log scale. Here's an example:
<code>rm(list = ls())
x <- 1:5
y <- 5:1
x[6] <- 6
y[6] <- 15

oldpar <- par(mfrow = c(1, 2))
plot(y~x, pch = 20, main = "Natural Scale")
abline(coef(lm(y~x)), col = "red")
plot(log(y)~log(x), pch = 20, main = "Log Scale")
abline(coef(lm(log(y)~log(x))), col = "red")
par(oldpar)
</code>

So one thing you should do is to investigate those "outliers" and make sure they are not measurement errors, and that they are what you think they are.
However, what you should do depends heavily on the substantive knowledge of your field and the question you want to answer.  The correlations are what they are, so if you are unsatisfied with them being different from of what you expected, this means you are probably trying to answer something deeper about the data generating process, so you need to define more precisely what you want to answer.


Why are Christmas songs usually in minor keys?

Question: Christmas is nominally about celebrating the birth of Christ, who (if you believe such things) is here to save the world. Sounds good, right? And yet, many Christmas songs don't sound happy or joyful; they sound more like a lament than a celebration.
For example:

God rest ye merry gentlemen — E minor.
We three kings — A minor.
Carol of bells — D minor (?)

The very last line of that first one reads "Oh tidings of comfort and joy!" Sounds joyous, right? Except that the very word "joy" is sung over a menacing pipe organ E minor block chord. It sounds less like cause for joy, and more like the end of the world or something.
Does anybody know why so many of these songs sound so mournful / menacing / disonnant?
Comment: Listen to the rest of the Christmas songs, and you'll understand why **so many** is so wrong. -1.
Comment: Your key assumptions: "most are in minor keys" and "minor keys sound mournful" are both incorrect. The 2nd one is dealt with in other questions on this site, and as Tim pointed out, your first is just numerically incorrect.
Comment: In addition to Tim's point, I would argue that minor doesn't necessarily mean mournful, menacing, or dissonant. None of these three examples sounds menacing to me, and the first and third especially sound perfectly "happy" to me.
Comment: *Fun fact:* - did you know that over the Dutch national Anthem, if you start with the last line of '& a partridge in a pear tree.' you can then sing the whole of 'Oh little town of Bethlehem' over the rest of it ;)) [Discovered whilst watching Max Verstappen win far too many F1 races this year]
Answer: Most of these are older tunes. They were written during the transition from the Renaissance to the Baroque (several centuries). Many have melodies written before the ideas behind minor and major keys were codified. They tend to sound a bit (or a lot) like they were written analogously to Chant and other earlier pieces. Some come from folk-song traditions that do not conform to modern major and minor keys either.
"God Rest Ye Merry, Gentlemen" can be analyzed as either Dorian or (depending on which theorist one is using) Aeolian. It conforms more to a modal (in a general sense) or pre-tonal style of harmony. Many of Bach's chorals are based on Cruger's and other composers' works; Bach harmonized them in either modal or harmonic styles. Later composers also wrote in a modalish style in order to sound archaic.
I think what people hear is attempts to sound "different" or "Christmas-like" by using modal melodies.
Also, minor vs major isn't as strong an indicator as sad vs happy as is popularly though. (Modal pieces seem to sound minor if not too deeply analyzed, also.) Quick example, "Faded Love" by Bob Wills sounds rather sad though it's a 3-chord major harmony.


Where to store JS and CSS that is not associated with a module?

Question: I've been given a ZIP file with the JS, CSS, HTML, and assets for a stand-alone jQuery application.  We would like to host this application through our Drupal 7 site hosted on Acquia Cloud.  I am looking for best practices on where to store this application. I've included additional info below but can supplement if there's other relevant info.  Can anyone suggest where I should store these files?
Due to some business-related decisions, we will always receive updates to this application in a ZIP file.  It may or may not receive updates. If it does, we'd like our content admin team to be able to manage it through Drupal or FTP.  It has not yet been decided if the application will be embedded in a page or accessed on it's own.
In our current site, we are not able to upload an entire directory and keep it in the same structure.  Each file must be uploaded manually.  We are fairly new to Drupal so I don't know if there is a module that would get us around this issue.
I am not allowed to make changes to the code or alter the directory structure (as that would require changes to the file references).
If there are no best practices for this, we can store it somewhere else and link out to it.  I would prefer to avoid this but if that's the recommended best practice, we can do it.
Answer: My gut feeling would be to place it in a folder in the root of your website and access it through a subdomain. I'm not sure, without knowing more about the application, if there is an effective way to integrate it with Drupal. It seems like it should stand on its own, in it's own directory structure, as it is a separate entity. I stand to be corrected here, but i don't see a problem with hosting it concurrently with your Drupal installation. It won't be manageable through the CMS, but without building the functionality in Drupal itself, it wouldn't be anyway.
Comment: This is the only sensible answer really, it comes down to "it's your server, put the files where you want them to be hosted, just make sure you don't nuke part of Drupal's code when you do it". Oh, and be mindful when upgrading Drupal; if you have an automated process, adjust it if necessary
Answer: If you have a library (js and css files) called MyOwnLibrary
You can create a folder called myownlibrary in sites/all/libraries and placed the js file myownlibrary.js in the folder, so the structure is like this:

YourSite/sites/all/libraries/myownlibrary/myownlibrary.js

And you can use the Libraries API module to use your library

The common denominator for all Drupal modules/profiles/themes that
  integrate with external libraries.
This module introduces a common repository for libraries in
  sites/all/libraries resp. sites//libraries for contributed
  modules.

You can check more info in the Libraries documentation page.
Comment: This is more of a stand-alone application.  We're not really referencing the JS/CSS.  The HTML bundled with it does.  Are you recommending that we create a module that wraps this application?
Comment: @Skoberlink Usually if you have some code to share between many modules you use a librarie, maybe is better if you take a look inside some modules that use libraries to see how this works. Take a look to this module: https://www.drupal.org/project/phantomjs_capture
Comment: This code isn't being shared between even one module @Adrian, it's a standalone app the op happens to want to serve from the same location as the Drupal site. Nothing inside Drupal could help with this (unless there's eg an ftp widget in he admin interface that facilitiates the upload). Libraries are only appropriate for assets that the Drupal site itself will consume. A standalone app will stand alone, and not get involved with Drupal.
Comment: @Clive sorry maybe I don't understand the question, should I delete my answer?
Comment: Up to you :) I think maybe you've misunderstood the situation the op is in but I could be wrong too


Trabalhando com Entity Framework, Multithreading e SQL Server em C#

Question: Estou usando o Entity Framework e Multithreading em um projeto C# e estou passando por problemas de conexão com o SQL Server.
Bom, queria melhorar a velocidade de umas buscas de dados para um grid pois são selects muito demorados. Primeiramente usei multithreading nas consultas e vi que na verdade não fazia diferença eu acionar as consultas em diferentes threads, porque no banco ele acaba enfileirando as consultas como se eu estivesse em um laço normal. Para conseguir resolver isso, começei a instanciar vários escopos, repositórios e connectionstring's novos a cada trhead que eu crio, para que ele faça os selects como se fossem pessoas diferentes acessando o banco e assim rode todas as consultas em paralelo. Funcionou, de certa maneira, porem quando crio muitas threads em algumas consultas ele da problemas como The underlying provider failed on open e Referência de objeto não definida para uma instância de um objeto, porem, nem sempre é na mesma consulta, é meio que aleatório. Alguem já passou pora tal problema ou possui uma solução para o mesmo? Também estou aberto a sugestões caso haja um jeito melhor de fazer o que estou fazendo. Abaixo está meu codigo:
public void BuscarDadosGridFamilia(string filialSelecionadaCodigo, string familiaSelecionada, string legendaSelecionada)
{
    _listaClasseGenericaFamiliaProduto.Clear();

    DateTime dataInicialPeriodoVendas = DateTime.Now.AddDays(-30);
    DateTime dataFinalPeriodoVendas = DateTime.Now;
    _totalVendas30Dias = 0;
    _totalEstoqueAtual = 0;
    _totalEstoquePrevisto = 0;
    _totalCapacidadeMin = 0;
    _totalCapacidadeMax = 0;
    _totalGiroObj = 0;
    decimal _totalGiroAtual = 0;
    decimal _totalGiroPrevisto = 0;
    decimal _totalGiroCapacidadeMax = 0;
    decimal _totalGiroObjetivo = 0;
    decimal _totalGiroIdeal = 0;
    int _quantidadeTasks = 0;
    int _totalLinhasGridFamilia = 0;
    string[] filialSplit = filialSelecionadaCodigo.Split('-');
    Filial filialSelecionada = _filialAplicacao.RepositorioFilial.ObterPorCodigo(_usuarioAtual.LocalEstoqueAtual.Filial.Empresa, filialSplit[0].Trim());

    var _familiaProduto = _familiaProdutoAplicacao.RepositorioFamiliaProduto.Todos()
                            .Where(d => d.FlagPercentualCapacidadeGondola == 1)
                            .Where(d => (d.Codigo.StartsWith(familiaSelecionada + ".") || d.Codigo == familiaSelecionada) && familiaSelecionada != "");

    if (legendaSelecionada != "Todos")
        _familiaProduto = _familiaProduto.Where(d => d.FamiliaMarcadaCapacidadeGondola.LegendaLinha.Legenda == legendaSelecionada.Split('-')[0].Trim());

    Task[] tasks = new Task[_familiaProduto.Count()];

    foreach (var familia in _familiaProduto)
    {
        ConexaoBanco.ConexaoMultiThread = "familia-" + familia.Codigo;
        string connectionString = ConexaoBanco.GetConexao();
        ConexaoBanco.ConexaoMultiThread = "familia-" + familia.Codigo;
        IRepositorioEscopo escopo = Havan.Infra.IoC.Container.Obter<IRepositorioEscopo>();

        ParametrosTask parametrosTask = new ParametrosTask();
        parametrosTask.familia = familia;
        parametrosTask.filialSelecionada = filialSelecionada;
        parametrosTask.legendaSelecionada = legendaSelecionada;
        parametrosTask.repositorioEscopo = escopo;

        Task _task = new Task(() => BuscarDadosGridFamiliaTask(parametrosTask), TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness);
        _task.Start();
        tasks[_quantidadeTasks] = _task;

        _totalLinhasGridFamilia++;
        _quantidadeTasks++;
    }
    Task.WaitAll(tasks);

    try { _totalGiroAtual = Arredondar((_totalEstoqueAtual / _totalVendas30Dias) * 30); }
    catch (Exception) { Arredondar(_totalGiroAtual = 0); };
    try { _totalGiroPrevisto = Arredondar((_totalEstoquePrevisto / _totalVendas30Dias) * 30); }
    catch (Exception) { Arredondar(_totalGiroPrevisto = 0); };
    try { _totalGiroCapacidadeMax = Arredondar((_totalCapacidadeMax / _totalVendas30Dias) * 30); }
    catch (Exception) { Arredondar(_totalGiroCapacidadeMax = 0); };
    try { _totalGiroIdeal = Arredondar((_totalVendas30Dias / 30) * _totalGiroObjetivo); }
    catch (Exception) { Arredondar(_totalGiroIdeal = 0); };
    try { _totalGiroObjetivo = Arredondar(_totalGiroObj / _familiaProduto.Count()); }
    catch (Exception) { Arredondar(_totalGiroObjetivo = 0); };

    ClasseGenericaFamiliaProduto _classeGenericaFamiliaProdutoTotal = new ClasseGenericaFamiliaProduto();

    _classeGenericaFamiliaProdutoTotal.Filial = "TOTAL:";
    _classeGenericaFamiliaProdutoTotal.Vendas30Dias = _totalVendas30Dias;
    _classeGenericaFamiliaProdutoTotal.EstoqueAtual = _totalEstoqueAtual;
    _classeGenericaFamiliaProdutoTotal.EstoquePrevisto = _totalEstoquePrevisto;
    _classeGenericaFamiliaProdutoTotal.CapacidadeMin = _totalCapacidadeMin;
    _classeGenericaFamiliaProdutoTotal.CapacidadeMax = _totalCapacidadeMax;
    _classeGenericaFamiliaProdutoTotal.GiroAtual = _totalGiroAtual;
    _classeGenericaFamiliaProdutoTotal.GiroPrevisto = _totalGiroPrevisto;
    _classeGenericaFamiliaProdutoTotal.GiroCapacidadeMax = _totalGiroCapacidadeMax;
    _classeGenericaFamiliaProdutoTotal.GiroObjetivo = _totalGiroObjetivo;
    _classeGenericaFamiliaProdutoTotal.GiroIdeal = _totalGiroIdeal;

    if (_listaClasseGenericaFamiliaProduto.Count > 0)
        _listaClasseGenericaFamiliaProduto.Add(_classeGenericaFamiliaProdutoTotal);

    gridFamilia.DataSource = _listaClasseGenericaFamiliaProduto;
}

E agora o método que é chamado pelas Tasks que contem consultas ao banco por LINQ
public void BuscarDadosGridFamiliaTask(ParametrosTask _parametrosTask)
{
    decimal _estoqueSeparadoFamiliaLoja = 0;
    decimal _estoqueTransitoFamiliaLoja = 0;
    decimal _estoqueEntrarFamiliaLoja = 0;
    decimal _estoqueLogicoFamiliaLoja = 0;
    decimal _estoquePrevistoFamiliaLoja = 0;
    DateTime dataInicialPeriodoVendas = DateTime.Now.AddDays(-30);
    DateTime dataFinalPeriodoVendas = DateTime.Now;

    _familiaProdutoAplicacao = new FamiliaProdutoAplicacao(_parametrosTask.repositorioEscopo);
    _filialAplicacao = new FilialAplicacao(_parametrosTask.repositorioEscopo);
    _dadosFamiliaFilialAplicacao = new DadosFamiliaFilialAplicacao(_parametrosTask.repositorioEscopo);
    _giroObjetivoFamiliaProdutoAplicacao = new GiroObjetivoFamiliaProdutoAplicacao(_parametrosTask.repositorioEscopo);
    _saldoEstoqueProdutoAplicacao = new SaldoEstoqueProdutoAplicacao(_parametrosTask.repositorioEscopo);
    _resumoVendasAplicacao = new ResumoVendasAplicacao(_parametrosTask.repositorioEscopo);
    _legendaLinhaAplicacao = new LegendaLinhaAplicacao(_parametrosTask.repositorioEscopo);
    _wrkGenerico01Aplicacao = new WrkGenerico01Aplicacao(_parametrosTask.repositorioEscopo);
    _parametroClasseABCFamiliaAplicacao = new ParametroClasseABCFamiliaAplicacao(_parametrosTask.repositorioEscopo);
    _usuarioAtualAplicacao = new UsuarioAplicacao(_parametrosTask.repositorioEscopo);

    Int64 _idPrimeiroNivelFamilia = _familiaProdutoAplicacao.RepositorioFamiliaProduto.ObterPorCodigo(_parametrosTask.familia.Codigo.Split('.')[0]).FirstOrDefault().Id;

    ParametroClasseABCFamilia _parametroClasseABCFamilia = _parametroClasseABCFamiliaAplicacao.ParametroClasseABCFamiliaPorFamiliaClasse(_parametrosTask.filialSelecionada.Id, _idPrimeiroNivelFamilia).FirstOrDefault();

    ClasseGenericaFamiliaProduto _classeGenericaFamiliaProduto = new ClasseGenericaFamiliaProduto();

    _saldoEstoqueProdutoAplicacao.ObterSaldoEstoqueProdutosFamilia(_usuarioAtual.TipoEstoque.Id, _parametrosTask.filialSelecionada, _parametrosTask.familia.Codigo, true, out _estoqueLogicoFamiliaLoja, false, out _estoqueSeparadoFamiliaLoja, false, out _estoqueTransitoFamiliaLoja, false, out _estoqueEntrarFamiliaLoja, true, out _estoquePrevistoFamiliaLoja);

    _classeGenericaFamiliaProduto.Filial = _parametrosTask.filialSelecionada.Codigo + " - " + _parametrosTask.filialSelecionada.Apelido;

    try { _classeGenericaFamiliaProduto.LinhaProduto = _parametrosTask.familia.FamiliaMarcadaCapacidadeGondola.LegendaLinha.Descricao; }
    catch (Exception) { _classeGenericaFamiliaProduto.LinhaProduto = ""; };

    _classeGenericaFamiliaProduto.Familia = _parametrosTask.familia.Codigo;

    _classeGenericaFamiliaProduto.DescricaoFamilia = _parametrosTask.familia.Nome;

    try { _classeGenericaFamiliaProduto.Vendas30Dias = Arredondar((decimal)_resumoVendasAplicacao.RepositorioResumoVendas.ObterQuantidadeVendaPorFamiliaFilial(_parametrosTask.filialSelecionada.Id, _parametrosTask.familia.Id, dataInicialPeriodoVendas, dataFinalPeriodoVendas)); }
    catch (Exception) { Arredondar(_classeGenericaFamiliaProduto.Vendas30Dias = 0); };

    _totalVendas30Dias += Arredondar(_classeGenericaFamiliaProduto.Vendas30Dias);

    _classeGenericaFamiliaProduto.EstoqueAtual = Arredondar(_estoqueLogicoFamiliaLoja);

    _totalEstoqueAtual += Arredondar(_classeGenericaFamiliaProduto.EstoqueAtual);

    _classeGenericaFamiliaProduto.EstoquePrevisto = Arredondar(_estoquePrevistoFamiliaLoja);

    _totalEstoquePrevisto += Arredondar(_classeGenericaFamiliaProduto.EstoquePrevisto);

    _classeGenericaFamiliaProduto.CapacidadeMin = Arredondar(_dadosFamiliaFilialAplicacao.RepositorioDadosFamiliaFilial.ObterLimiteMaximoFamiliaEstoque(_familiaProdutoAplicacao.RepositorioFamiliaProduto, _usuarioAtual.LocalEstoqueAtual.Filial.Empresa.Id, _usuarioAtual.TipoEstoque.Id, _parametrosTask.familia.FamiliaMarcadaCapacidadeGondola.Codigo, _parametrosTask.familia.Codigo, _parametrosTask.filialSelecionada.Id).Select(d => d.Quantidade).FirstOrDefault());

    _totalCapacidadeMin += Arredondar(_classeGenericaFamiliaProduto.CapacidadeMin);

    try { _classeGenericaFamiliaProduto.CapacidadeMax = Arredondar(_familiaProdutoAplicacao.CalculoEstoqueMaximoFamilia(_classeGenericaFamiliaProduto.CapacidadeMin, _classeGenericaFamiliaProduto.Vendas30Dias, _parametrosTask.filialSelecionada.TempoReposicaoEmDias, _parametroClasseABCFamilia.FatorClasseFamilia, _parametroClasseABCFamilia.PercentualCabideFamilia)); }
    catch (Exception) { Arredondar(_classeGenericaFamiliaProduto.CapacidadeMax = 0); };

    _totalCapacidadeMax += Arredondar(_classeGenericaFamiliaProduto.CapacidadeMax);

    try { _classeGenericaFamiliaProduto.GiroAtual = Arredondar((_classeGenericaFamiliaProduto.EstoqueAtual / _classeGenericaFamiliaProduto.Vendas30Dias) * 30); }
    catch (Exception) { Arredondar(_classeGenericaFamiliaProduto.GiroAtual = 0); };

    try { _classeGenericaFamiliaProduto.GiroPrevisto = Arredondar((_classeGenericaFamiliaProduto.EstoquePrevisto / _classeGenericaFamiliaProduto.Vendas30Dias) * 30); }
    catch (Exception) { Arredondar(_classeGenericaFamiliaProduto.GiroPrevisto = 0); };

    try { _classeGenericaFamiliaProduto.GiroCapacidadeMax = Arredondar((_classeGenericaFamiliaProduto.CapacidadeMax / _classeGenericaFamiliaProduto.Vendas30Dias) * 30); }
    catch (Exception) { Arredondar(_classeGenericaFamiliaProduto.GiroCapacidadeMax = 0); };

    _classeGenericaFamiliaProduto.GiroObjetivo = Arredondar(_giroObjetivoFamiliaProdutoAplicacao.BuscaGiroObjetivoFamiliaMaisProxima(_parametrosTask.familia.Codigo, _parametrosTask.filialSelecionada.Id));

    _totalGiroObj += Arredondar(_classeGenericaFamiliaProduto.GiroObjetivo);

    try { _classeGenericaFamiliaProduto.GiroIdeal = Arredondar((_classeGenericaFamiliaProduto.Vendas30Dias / 30) * _classeGenericaFamiliaProduto.GiroObjetivo); }
    catch (Exception) { Arredondar(_classeGenericaFamiliaProduto.GiroIdeal = 0); };

    _classeGenericaFamiliaProduto.NecessidadeGiro = (Arredondar(_classeGenericaFamiliaProduto.GiroIdeal - _classeGenericaFamiliaProduto.EstoquePrevisto) < 0 ? 0 : Arredondar(_classeGenericaFamiliaProduto.GiroIdeal - _classeGenericaFamiliaProduto.EstoquePrevisto));

    _classeGenericaFamiliaProduto.NecessidadeCapacidade = (Arredondar(_classeGenericaFamiliaProduto.CapacidadeMax - _classeGenericaFamiliaProduto.EstoquePrevisto) < 0 ? 0 : Arredondar(_classeGenericaFamiliaProduto.CapacidadeMax - _classeGenericaFamiliaProduto.EstoquePrevisto));

    try { _classeGenericaFamiliaProduto.SGiro = Formatar((_classeGenericaFamiliaProduto.GiroPrevisto / _classeGenericaFamiliaProduto.GiroObjetivo) * 100); }
    catch (Exception) { Formatar(_classeGenericaFamiliaProduto.SGiro = 0); };

    _listaClasseGenericaFamiliaProduto.Add(_classeGenericaFamiliaProduto);
}

Comment: Hmm sua dúvida é com as threads, certo? Acabei me concentrando no que me pareceu ser o verdadeiro problema e me esqueci das threads. Teu design abre bastante brecha para problemas ao trabalhar com threads. Já que você está aberto a sugestões, a minha sugestão é: não use threads. Elas não foram feitas para resolver problemas de performance, menos ainda problemas de performance em consultas a SGBDs (eles próprios abrem threads quando necessário). É melhor voltar ao código anterior sem as threads, identificar e resolver os problemas de performance.
Comment: Você já conseguiu identificar quais consultas estão demoradas? Minha aposta: uma mudança em apenas uma ou duas linhas pode melhorar várias vezes o tempo de resposta desta parte do teu sistema. Eu começaria por analisar esta aqui:  `_familiaProdutoAplicacao.RepositorioFamiliaProduto.Todos().Where(...` - veja que você primeiro retorna mais registros do que precisa e depois faz uma seleção em memória. Apesar de o seu design não parecer ideal, na maioria das vezes o problema de performance é localizado. Identifique qual das consultas está tomando 80% do tempo e volte aqui pra gente dar uma olhada.
Comment: Ok, Obrigado pela dica! faz sentido! Irei implementar. Porem a minha duvida é outra.
Comment: Bom, com as dicas de vocês e bastante leitura acabei abandonando essa ideia de threads fazendo vários acessos paralelos ao BD e optei por mudar a estrutura um pouco e melhorar minhas consultas. Obrigado.
Answer: Isto aqui:
_familiaProdutoAplicacao.RepositorioFamiliaProduto.Todos()

É péssimo em todos os sentidos para a performance, visto que você faz um TABLE SCAN para cada consulta. Aqui explico porque usar repositório com Entity Framework não vale a pena.
A segunda coisa que me chamou a atenção é quantas consultas você faz para sintetizar a informação. Não sei como está o seu código por baixo disso, mas é muito provável que a mesma informação seja trazida várias vezes. Quanto mais cheio o contexto (que no seu caso é compartilhado), mais lento ele fica. Aqui nesta resposta ensino como otimizar o contexto para grandes porções de dados, mas creio que o ganho será pequeno pela forma com que sua aplicação foi construída.
Sugiro repensar toda essa arquitetura. Posso ajudar se você der mais detalhes das suas consultas LINQ.
Comment: Valeu cigano! agradeço pela dica e a documentação. Irei implementar. Agora como eu disse ao @Caffé, A minha duvida é outra. Por mais que minhas consultas estejam demoradas e usar repositório não vale a pena.


What is the best approach to transform independent variables that have a bimodal relationship with the dependent variable?

Question: I am building a logistic regression model with a binary rating (High and Low) as the dependent variable and 40+ independent variables. One of the independent variable (Age) has a non-linear relationship (bimodal shape) with the dependent.
What is the best approach / transformation to deal with this? Are splines the best method? I feel splines make the model too complicated and hard to interpret especially if interactions are also included.
Comment: Because the response in a logistic regression is binary, could you explain what you mean by "non-linear relationship" or "bimodal shape"?
Comment: There is no one size that fits all. Could you try splitting the independent variable into bins and see the relationship with the dependent variable?
Comment: @karthikbharadwaj The independent variable Age is already bucketed into 5-year bins. I do not want to bucket further to avoid losing more "information".
Comment: @whuber The bimodal shape is seen when I smooth the Rating vs. Age plot (e.g. using loess)
Answer: My recommendation: use age in years as is, without any binning, and represent it with regression splines. Or Try generalized additive models (GAMs.)  See for instance Are both of these generalized additive models? (and search this site, many posts.)
One post with simple R code is Violation of linearity assumption in Logistic Regression.
Answer: I agree with Kjetil's answer, if you have age in years available.
If age was already binned into 5 categories, then splines probably won't work well as there are very few choices for the knots. You could try optimal scaling. This is available in the R package optiscale and in SAS PROC TRANSREG and probably in some other packages as well.
But binning throws away information (as you note in one of your comments). It can also distort the relationship. I wrote a blog post exploring this graphically: What happens when we categorize an independent variable? and a more general one: Why binning continuous data is almost always a mistake ,
Answer: IMO,Two approaches can be followed:
1)You can visualize how the target varies with the different age buckets
2) The most popular transformations used are log transformations or quadratic transformation. For each transformation, you can use cross-validation to check which one performs better


Cisco870, multiple VPN connection, same originating IP, possible?

Question: I have 2 users that need VPN into the office from the same originating IP. They are not able to connect simultaneously though. Is this a limitation of the Cisco box, or of the Linksys router on site there?
EDIT: Source machines are both using Cisco VPN Client, V5
Comment: Maybe some more details on your setup?... Are you using NAT?
Comment: Yes. What other details are needed?
Comment: Are they using Cisco VPN clients or Windows/OSX built-in ones?
Answer: If the source machines are connecting via a NAT router then standard IPsec VPN's wont work - the ESP protocol used by IPsec doesn't play friendly with NAT's as they use port remapping and ESP doesn't have a concept of ports. An L2TP\IPsec VPN can tunnel multiple concurrent clients through a NAT because it encapsulates the IPSec payload inside a UDP tunnel which does play nicely with NAT environments.
Comment: Check with the LinkSys documentation to see if it supports l2tp-nat-passthrough or something that sounds similar. Some consumer NAT routers do and some don't, and even those that do may not be able to support multiple connections to your VPN but it's worth checking. Also as David Collantes indicates the VPN client is important - the Cisco client has much better support for NAT clients than the Microsoft clients (at least up to Vista, not sure if things have improved with Windows7)
Comment: The source machines are connecting via consumer Linksys wireless router.


About $T(n^2) = T^2(n)/n$, with a point defined in $T(p) = q$.

Question: It is possible to find a generic solution for: $T(n)$ such that: $$T(n^2) = T^2(n)/n$$ with a start point defined in $T(p) = q$
and $ n, p, q \gt 1$ and $n, p, q \in Z_{+}$
I tried to solve it by developing the equation replacing variables, but I believe that this is not a correct or valid method. Does anyone have an idea?
Comment: domain and codomain?
Answer: Using the recursive development method, find one of the solutions, but I believe that this is not a generic and correct method. Does anyone have a suggestion? Let's do:
$$T(n^2) = \frac{T^2(n)}{n}$$
$$T(n^4) = \frac{T^2(n^2)}{n^2} = \left(\frac{T^2(n)}{n}\right)^2/n^2 = \frac{T^4(n)}{n^4}$$
$$T(n^8) = \frac{T^2(n^4)}{n^4} = \left(\frac{T^4(n)}{n^4}\right)^2/n^4 = \frac{T^8(n)}{n^{12}}$$
$$T(n^{16}) = \frac{T^2(n^8)}{n^8} = \left(\frac{T^8(n)}{n^{12}}\right)^2/n^8 = \frac{T^{16}(n)}{n^{32}}$$
$$......$$
$$T(n^z) = \frac{T^z(n)}{n^w}$$
$$w = g(z)$$ analyzing the evolution to find $w$:
for $z=2 \to w = 1 = 2^0$
for $z=4 \to w = 2*1 + 2 = 2^1 + 2^1 = 2*2^1$
for $z=8 \to w = 2(2^1 + 2^1) + 2^2 = 2^2 + 2*2^2 = 3*2^2$
for $z=16 \to w = 2(2^2 + 2*2^2) + 2^3 = 2^3 + 3*2^3 = 4*2^3$
for $z=32 \to w = 2(2^3 + 3*2^3) + 2^4 = 2^4 + 4*2^4 = 5*2^4$
$......$
for $z = 2^t \to w = t2^{t-1}$
But $t = \log_2 z \to w = (log_2 z)2^{log_2 z - 1} = (zlog_2 z)/2$
applying in $T(n^z) = \frac{T^z(n)}{n^w}$ we have do:
$$T(n^z) = \frac{T^z(n)}{n^{(zlog_2 z)/2}} $$
but the problem was that $T(p) = q$, so with $n = p$:
$$T(p^z) = \frac{q^z}{p^{(zlog_2 z)/2}}$$
doing $x = p^z \to z = log_p x$
so:
$$T(x) = q^{log_p x}/p^{(log_p x)*log_2 (log_p x)/2}$$
with $x = n$:
$$T(n) = q^{log_p n}/\left(n^{log_2 log_p n)}\right)^{1/2}$$
Now we must analyze the values of $n, p, q$ such that the function is possible! So we can find a domain for this solution.
Obviously one of the necessary conditions for the function to exist is that: $n \gt 1, p \gt 0 $ and $p \neq 1$.
As an example, see a sequence generated by the function starting at $T(2) = 4$ and how curious is its evolution:
$n = 2 \to T(2) = 4$
$n = 4 \to T(4) = 8$
$n = 16 \to T(16) = 16$
$n = 256 \to T(256) = 16$
$n = 256^2 \to T(256^2) = 1$
$n = 256^4 \to T(256^4) = 1/256^2$
$......$
$$\lim_{n\to \infty} T(n) = 0$$


Example showing set of periodic functions from $\mathbb{R}$ to $\mathbb{R}$ is not subspace of $\mathbb{R}^{\mathbb{R}}$.

Question:
Is set of periodic functions from $\mathbb{R}$ to $\mathbb{R}$ subspace of $\mathbb{R}^{\mathbb{R}}$?

My answer is No. I give the following counterexample:
We consider periodic functions $f(x),g(x)$ so that $f(x)=x$ for $x \in [0,\sqrt{2})$ and $f(x)=f(x+\sqrt{2})$, function $g(x)=x$ for $x \in [0,\sqrt{3})$ and $g(x)=g(x+\sqrt{3})$ then $f+g$ is not periodic.
Indeed, assume that the function $f(x)+g(x)$ is periodic with length $T$. Note that if $T/\sqrt{2}$ is not an integer then $f(x)<f(x+T)$, similar to $T/\sqrt{3}$. Thus, since $T/ \sqrt{2}$ or $T/ \sqrt{3}$ can't be both integers so $f(x)+g(x)<f(x+T)+g(x+T)$, a contradiction. Thus, $f+g$ is non-periodic function. This yields that set of periodic function from $\mathbb{R}$ to $\mathbb{R}$ is not a subspace of $\mathbb{R}^{\mathbb{R}}$.
My questions are

Is this counterexample correct?
Are there any other examples?
Comment: It looks fine. What about $\;f(x)=\sin x+\sin\pi x\;$ ?
Comment: @dxiv Oh, you are right. Thanks.
Comment: $f(x)=\sin x+ \sin \pi x$ is periodic I believe.
Comment: @ToanQuangPham What would you assume its period could be?
Answer: Your argument that $f+g$ is not periodic is not quite correct.  For instance, if $T=1$ then $T/\sqrt{2}$ is not an integer, but $f(1)=1>f(1+T)=2-\sqrt{2}$.  However, you can fix your argument by specifically looking at $x=0$: then $f(x)+g(x)=0+0=0$, but at least one of $f(x+T)$ and $g(x+T)$ must be positive since $T$ cannot be an integer multiple of both $\sqrt{2}$ and $\sqrt{3}$.  So for $x=0$, you must have $f(x)+g(x)<f(x+T)+g(x+T)$.
More generally, a similar argument shows that if $f$ and $g$ are periodic with periods $a$ and $b$ respectively where $a/b$ is irrational, and $f$ and $g$ both achieve their minimum values only at integer multiples of $a$ and $b$ respectively, then $f+g$ is not periodic.
Answer: Edit: The following is not true.
Yes to both: any two periodic functions with incommensurate periods will have a sum that is not periodic.
Comment: This is false, see http://math.stackexchange.com/questions/1079/sum-of-two-periodic-functions.
Comment: Correction: Any two periodic functions with incommensurate fundamental periods will have a sum that is not periodic.
Comment: That is still false.  Just modify the example in the answer I linked to above to take only $\mathbb{Z}$-linear combinations instead of $\mathbb{Q}$-linear combinations.
Comment: You're right. Now I wonder under what circumstances we can say f+g is not periodic.
Comment: @BenG. If the two functions are *continuous*, then their sum cannot be periodic unless both are constant. Indeed, the subgroup of $\mathbb{R}^+$ generated by $S$ and $T$ (the incommensurable periods) is dense in $\mathbb{R}$, so $0$ is an accumulation point of it. So if the sum is periodic, it has no minimum positive period, hence it is constant.
Comment: @egreg. You can also note that with $f,g$ as in the Q, that $ f+g$ is continuous on $[0,1].$  If $f+g$ is periodic then the set of its periods is dense, which means that the closed set $\{x\in [0,1]:f(x)+g(x)=f(0)+g(0)\}$ is dense in [$0,1]$, making $f+g$ constant on [$0,1],$ a contradiction.
Comment: @egreg: That doesn't work, since there's no reason that $S$ and $T$ need to be periods of the sum, so there is no obvious reason the periods of the sum should be dense. The result happens to be true, but you need a more complicated argument.  See http://math.stackexchange.com/questions/1356802/the-sum-of-two-continuous-periodic-functions-is-periodic-if-and-only-if-the-rati.


How to implement facebook feed which shows the latest facebook wall post

Question: I would like to display latest facebook wall post on my website. I found the Facebook Pull module; but it doesn't work for me. I have add the appropriate app id and App Secret and nothing is showing up. Any ideas?
Do you know how  I can accomplish it? I never have a similar problem with a twitter_pull module which does the same but for the twitter.
Answer: Why not use the facebook like box plugin? If you're just looking for a widget like capability on your site, this is the easiest and pushes the heavy lifting on to Facebook's servers without any more modules or extra PHP:
http://developers.facebook.com/docs/reference/plugins/like-box/
Play around with the options, you probably just want to show the stream. There are other options below to customize the output of this as well.
Answer: I installed the Facebook Pull and it worked very well at my local. But when i pushed the code in the live website. The feed facebook didn't show up. I looked the log entries and find out there was the "Failed to fetch data from the Facebook Graph" error in the logs. I followed the http://drupal.org/node/1587598 patch and it worked well.


External HDD wrong size

Question: I have an very interesting problem with a Seagate HDD (3TB):
Under Windows the HDD has a size of ~3TB.
When I connect it to Ubuntu 14.04 and try to format it with GParted, GParted tells me that the backup partition table (GPT) is corrupt and it uses the main. BUT:
After that gparted threw an error (in some .c file) and crashed.
I tried gdisk:
nch@Media:/mnt$ sudo gdisk /dev/sdi GPT fdisk (gdisk) version 0.8.8

Warning! Disk size is smaller than the main header indicates! Loading secondary header from the last sector of the disk! You should use 'v' to verify disk integrity, and perhaps options on the experts' menu to repair the disk. Caution: invalid backup GPT header, but valid main header; regenerating backup header from main header.

Warning! One or more CRCs don't match. You should repair the disk!

Partition table scan:   MBR: protective   BSD: not present   APM: not present   GPT: damaged

**************************************************************************** Caution: Found protective or hybrid MBR and corrupt GPT. Using GPT, but disk verification and recovery are STRONGLY recommended.
****************************************************************************

Command (? for help): p Disk /dev/sdi: 1565565872 sectors, 746.5 GiB Logical sector size: 512 bytes Disk identifier (GUID): 329DB2A5-1B26-4FCC-9599-288010699D37 Partition table holds up to 128 entries First usable sector is 34, last usable sector is 5860533134 Partitions will be aligned on 8-sector boundaries Total free space is 5860270957 sectors (2.7 TiB)

Number  Start (sector)    End (sector)  Size       Code  Name    1     34          262177   128.0 MiB   0C01  Microsoft reserved part

Command (? for help): v

Caution: The CRC for the backup partition table is invalid. This table may be corrupt. This program will automatically create a new backup partition table when you save your partitions.

Problem: The secondary header's self-pointer indicates that it doesn't reside at the end of the disk. If you've added a disk to a RAID array, use the 'e' option on the experts' menu to adjust the secondary header's and partition table's locations.

Problem: Disk is too small to hold all the data! (Disk size is 1565565872 sectors, needs to be 5860533168 sectors.) The 'e' option on the experts' menu may fix this problem.

Problem: GPT claims the disk is larger than it is! (Claimed last usable sector is 5860533134, but backup header is at 5860533167 and disk size is 1565565872 sectors. The 'e' option on the experts' menu will probably fix this problem

Caution: Partition 1 doesn't begin on a 8-sector boundary. This may result in degraded performance on some modern (2009 and later) hard disks.

Consult http://www.ibm.com/developerworks/linux/library/l-4kb-sector-disks/ for information on disk alignment.

Identified 4 problems!

Command (? for help): r

Recovery/transformation command (? for help): f Warning! This will destroy the currently defined partitions! Proceed? (Y/N): yes

Recovery/transformation command (? for help): f Warning! This will destroy the currently defined partitions! Proceed? (Y/N): y

Recovery/transformation command (? for help): w

Final checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING PARTITIONS!!

Do you want to proceed? (Y/N): y OK; writing new GUID partition table (GPT) to /dev/sdi. The operation has completed successfully.

So the interesting thing is that gdisk showed me a free space of 2.7TB but after the repair I used
fdisk -l

and it showed me the following:
    Disk /dev/sdi: 801.6 GB, 801569726464 bytes
256 Köpfe, 63 Sektoren/Spur, 97071 Zylinder, zusammen 1565565872 Sektoren
Einheiten = Sektoren von 1 × 512 = 512 Bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Festplattenidentifikation: 0x00000000

   Gerät  boot.     Anfang        Ende     Blöcke   Id  System
/dev/sdi1               1  1565565871   782782935+  ee  GPT

I tried several other repairs with gdisk but with no success.
Under windows I have only to convert the gpt disk to an mbr disk and then I can see unformated two partitions:

2048GB
~780GB

What is wrong here and how can I fix this?
Comment: Is this a Seagate USB drive, or did you install the drive in a USB enclosure?  What is the model of the drive?
Comment: Yes it is a Seagate SATA (st3000dm001) in a icybox USB enclosure.
Comment: It made a 2 TB partition because it can't be bugger using mbr partitioning. What's the question? What do you want to do?
Comment: No under linux there is no 2TB partition there is only a 800GB partition. I want to fix my GPT table to fix the problem with the wrong size
Answer: If the 2TB limit is exceeded, in many situations you will be able to detect what's above 2TB and up to the true HDD space, meaning the rest of ~730GB.
This can be a partitioning or controller problem. Some external drives use fake-SATA controllers (software-emulated) and will cause such issues with large drives, because the addressing the controller uses.
To identify if it's really a controller problem, try connecting the drive directly to a SATA port, or via another non-emulated adapter.
On the software side, note that fdisk (util-linux 2.20.1) does not understand GPT.
You should try parted -l.
You can use parted's mkpart primary to create partition larger than 2TB [ (parted) mkpart primary 0GB 2929GB ].
Answer: Very often "External" HDDs are reported with wrong size, if the size of the HDD exceeds the supported maximum size of the usb bridge.
if the external hhd is an bundled enclosure you can ignore my answer, if it is something like a docking station this could be your problem.
try a different enclosure that supports 3tb hdds and up...

External HDD wrong size


Python 2.7.3 IndentationError: expected an indented block - cant find mistake

Question: I am new to python and trying to submit my HW on Coursera Data Science course. The environment there is VM running Python 2.7.3, the file tweet_sentiment.py I am trying to run has the following script within it:
import sys
import json

def hw():
    print 'Hello, world!'

def lines(fp):
    print str(len(fp.readlines()))

def main():
    sent_file = open(sys.argv[1])
    tweet_file = open(sys.argv[2])
    # hw()
    # lines(sent_file)
    # lines(tweet_file)

    myfile = open(sys.argv[1], 'r')
    lines = myfile.readlines()
    mydict = {}
    for line in lines:
    key, value = line.split("\t")
        mydict[key] = int(value)

    twit_file = open(sys.argv[2], 'r')
    twit_lines = twit_file.readlines()

    mylist = []
    for line in twit_lines:
    mylist.append(json.loads(line))

    for listik in mylist:
    twit_value = 0
    twit_text = listik["text"]
    twit_words = twit_text.split()
    for word in twit_words:
        if word in mydict:
        twit_value =  twit_value + 1
    print float(twit_value)

if __name__ == '__main__':
    main()

When running $ python tweet_sentiment.py I am getting the following error:
    File "tweet_sentiment.py", line 25
    key, value = line.split("\t")
      ^
IndentationError: expected an indented block

Thanks for any hints!
Sergey
Comment: Think about it this way: A `for` statement only loops over the lines that are indented. Since you don't have any indented lines, it has nothing to do. Since that's almost certainly not what you want, Python is being nice and giving you an error, instead of treating it as a loop that wastes a bunch of time doing absolutely nothing.
Comment: Also, you have the same problem with at least one two places: `for line in twit_lines:` and `if word in mydict:`.
Comment: Finally, it's worth noting that all one of the loops you got wrong (that I noticed, at least) could be replaced with a one-line list comprehension, dict comprehension, or `collections.Counter`, which means you didn't even need to indent anything here anyway…
Comment: @abarnert, try editing the question and move the cursor left and right over those whitespaces, you'll see the tabs there.
Comment: @gnibbler: Actually, it looks like he's got tabs and spaces in the same line, to make things even more confusing. That's why I upvoted your answer.
Answer: Be careful! You're mixing tabs and spaces for indenting.
Often a tab is displayed as the equivalent of 8 spaces. So, when using the common practice of 4 spaces it looks like 2 levels of indentation, but is really only one.
When I examine your code in the editor, I can see that you've got  in at least two places. Replace those tabs with 4 spaces.
Comment: +1 Just to add to what @gnibbler says, [_PEP8_](http://www.python.org/dev/peps/pep-0008/#tabs-or-spaces) warns about just this, and recommends the use of spaces over tabs. (4 spaces per indentation level)
Answer: As it says, you have an indentation error. Line 25 should be corrected to this:
def main():

...

    for line in lines:
        key, value = line.split("\t")
        mydict[key] = int(value)

Answer: You have to indent the line after a for block. Your code should look like:
for line in lines:
    key, value = line.split("\t")
    mydict[key] = int(value)

Comment: Thanks!

Sorry for posting this mess,I looked like I am asking really basic question.
Indentation was actually well organized in my file, but when copying it to post, formatting got lost and I did not check that.

Eventually my file was successfully executed by the course script which checks assignment and results went out right. I am not sure why it did not work when running on VM.

Thanks for prompt response!
Answer: Your code must be like this:
for line in lines:
    key, value = line.split("\t")
    mydict[key] = int(value)

It's the same for all other for's.
Answer: Try:
import sys
import json

def hw():
    print 'Hello, world!'

def lines(fp):
    print str(len(fp.readlines()))

def main():
    sent_file = open(sys.argv[1])
    tweet_file = open(sys.argv[2])
    # hw()
    # lines(sent_file)
    # lines(tweet_file)

    myfile = open(sys.argv[1], 'r')
    lines = myfile.readlines()
    mydict = {}
    for line in lines:
        key, value = line.split("\t")
        mydict[key] = int(value)

    twit_file = open(sys.argv[2], 'r')
    twit_lines = twit_file.readlines()

    mylist = []
    for line in twit_lines:
        mylist.append(json.loads(line))

    for listik in mylist:
        twit_value = 0
        twit_text = listik["text"]
        twit_words = twit_text.split()
        for word in twit_words:
            if word in mydict:
            twit_value =  twit_value + 1
            print float(twit_value)

if __name__ == '__main__':
    main()

The indentation for the for statements is messed up. The for block has to be indented. Also, as stated before, Python will throw an error if you mix tabs and spaces. Use either all spaces(replace each tab with 4 spaces) or all tabs(replace every 4 spaces with a tab).
Comment: Thanks!

Sorry for posting this mess,I looked like I am asking really basic question.
Indentation was actually well organized in my file, but when copying it to post, formatting got lost and I did not check that.

Eventually my file was successfully executed by the course script which checks assignment and results went out right. I am not sure why it did not work when running on VM.

Thanks for prompt response!
Comment: @SergeySamusev: You're welcome! The error was an indentation error. Might have had something to do with...well...I don't really know. All I can say is...good luck! Maybe the indentation was like one space off or didn't correlate with the rest of the file. I make that seemingly novice mistake all the time.
Answer: Use vim to open it. And then type the commoand :retab
It then shows the line not correctly indented.


Trigonometric Limit 0*infinity

Question: I came across this trigonometric limit. I've tried to solve it by transformation but failed.
How can I evaluate it? Answer is $2/\pi$.

$$ \lim_{x\to 1} (1-x) \tan\left(\frac{x\pi}{2}\right) $$
Comment: I reformatted your problem.  Can you please make sure it's as you intended?
Comment: @MatthewLeingang yes, it is.
Answer: You want to use the fact that $\lim_{\theta\to 0} \frac{\sin\theta}{\theta} = 1$.
\begin{align*}
    \lim_{x\to 1}(1-x) \tan\left(\frac{x\pi}{2}\right)
    &= \lim_{x\to 1}(1-x)\frac{\sin\left(\frac{x\pi}{2}\right)}{\cos\left(\frac{x\pi}{2}\right)}
     = \lim_{x\to 1}\frac{1-x}{\cos\left(\frac{x\pi}{2}\right)}
\end{align*}
since the sine term tends to one.  Let $t = 1-x$.  Then $t\to 0$ as $x\to 1$ and
\begin{align*}
    \lim_{x\to 1}\frac{1-x}{\cos\left(\frac{x\pi}{2}\right)}
    &= \lim_{t\to 0} \frac{t}{\cos\left(\frac{\pi}{2} - \frac{t\pi}{2}\right)}
    \\&= \lim_{t\to 0} \frac{t}{\sin(t\pi/2)}
    \\&= \lim_{t\to 0} \frac{2}{\pi} \cdot \frac{t\pi/2}{\sin(t\pi/2)}
\end{align*}
Now let $\theta = \frac{t\pi}{2}$ and you are home free.
Alternatively, picking up on the good Doctor's suggestion, let $f(x) = \cot\left(\frac{\pi x}{2}\right)$.  Then
$$
    f'(x) = -\csc^2\left(\frac{\pi x}{2}\right)\cdot \frac{\pi}{2}
$$
So $f'(1) = - \frac{\pi}{2}$.  Your limit can be expressed as
$$
    \lim_{x\to 1} \left[(-1)\cdot \frac{x-1}{f(x)-f(1)}\right] = (-1) \cdot \frac{1}{f'(1)} = \frac{2}{\pi}
$$
Answer: write it in the form $$\frac{1-x}{\cot\left(\frac{x \pi}{x}\right)}$$ and use L'Hospital
the result should be $$\frac{2}{\pi}$$
Comment: Question was tagged [tag:limits-without-lhopital].  Although your expression of the function shows that the limit is the reciprocal of the derivative of $x \mapsto \cot\left(\frac{x\pi}{2}\right)$ at $x=1$.
Answer: Let $x=1-y.$ Then $$(1-x)\tan (\pi x/2)=y\tan (\pi /2-y\pi /2)=y\cot (y\pi /2)=$$ $$=\frac {2}{\pi}\cdot  \frac {y\pi /2}{\sin (y\pi /2)}\cdot \cos (y\pi /2).$$ Now $y\pi /2\to 0$ as $x\to 1 .$ So $\frac {y\pi /2}{\sin (y\pi /2)}\to 1$ and $\cos (y\pi /2)\to 1$ as $x\to 0.$
Answer: When $x\to 1$, $x\pi/2\to\pi/2$. Set $x\pi/2=\pi/2-t$, so
$$
x=1-\frac{2t}{\pi}
$$
and the limit becomes
$$
\lim_{t\to0}\frac{2t}{\pi}\tan\left(\frac{\pi}{2}-t\right)
=
\frac{2}{\pi}\lim_{t\to0}t\cot t=
\frac{2}{\pi}\lim_{t\to0}\frac{t}{\sin t}\cos t
$$

Trigonometric Limit 0*infinity


Chatbot integration in SharePoint Online Site. Chatbot created using MERN

Question: Hello SharePoint Online Community. Please help me, I have a SharePoint online communication site and I want to integrate a chat bot in it.. So the challenge I am facing is chat bot is created using MERN. Is there any possibility to add this chatbot to my SharePoint site? How we can use SPFx for it?
Please give any solution.
Thank you
I want to integrate ChatBot created in MERN in SharePoint online communication site using SPFx.
Answer: Implementing a MERN app in SharePoint is an interesting proof of concept, but I don't think it would be possible to implement express straight out of the box in SPFx as it seems it's mainly a frontend framework.
I recommend looking into the suit of tools Azure offers and try to replace express with those. For example make API calls to a azure function/logic app which would handle communicating with mongoDB.


Mixfdr penalization parameter

Question: I'm trying to use mixfdr in a simulation of p-values but sometimes the search for the penalization parameter spits out an error and shows some matrix entries to be infinite:
>m <- mixFdr(stdjk,plots=F,J=3,theonull=F,calibrate=T)
Fitting preliminary model
[1] 0.750 0.125 0.125
[1] -7412.522 -7412.522 -7412.522
[1] 3706.261 3706.261 3706.261
[,1]      [,2]     [,3]
[1,] 0.750 -7412.522 3706.261
[2,] 0.125 -7412.522 3706.261
[3,] 0.125 -7412.522 3706.261
[,1] [,2]
[1,] -Inf  Inf
[2,] -Inf  Inf
[3,] -Inf  Inf
 [,1] [,2]
[1,]  0.1  Inf
[2,]  0.1  Inf
[3,]  0.1  Inf
Error in if (distance < tol) converged = TRUE :
missing value where TRUE/FALSE needed

Is this normal or am i missing some parameter?
Comment: Looks like a bug. Try contacting the package author.
Answer: This is just saying that the algorithm has failed to converge.  I had the same problem and increasing the maxIter argument from the default 1000 to 2000 solved it for me.
You might also play with the tol argument.  If none of that works you should consider the possibility that your data are not well described by the model.

Mixfdr penalization parameter


The value of $a$ that maximizes $g(a)?$

Question: Let $X$ be a normal random variable with mean $2$ and variance $4$ and $g(a)=P(a \leq X \leq a+2)$. The value of $a$ that maximizes $g(a)?$
My thought: From the given information about random variable we get a standard normal. But after that how do I proceed?
Answer: Hint: We have that
$$\mathbb P(a \leq X \leq a+2)=\int_a^{a+2}\,\frac{1}{\sqrt{4\pi}}\,e^{-(x-2)^2/8}\,dx$$
Comment: I should note that another way to go about it would be to note that the usual 'bell curve' of the standard normal distribution is now symmetric about $x=2$, rather than $x=0$. It's no coincidence that you found $a=1$: if $I$ is some interval of fixed length, $\mathbb P (X\in I)$ is maximized when $I$'s midpoint is at $x=2$, the peak of the 'bell curve' for $X$.
Comment: @ramram ... and differentiate on $a$...
Comment: Yes, I got it , The value of $a$ is one...thanks
Comment: You're welcome! Glad to help.
Comment: This last comment of yours is a much better answer than your post... :-)
Comment: @Did Thank you; perhaps I should indeed have posted that as an answer. The downside is that it is very specific to normal distributions, while the current answer works in more general settings.

The value of $a$ that maximizes $g(a)?$