jquery mobile does not execute the Script on the response of ajax request

Question: I'm working on jQuery Mobile and currently stumbled upon a road block
On render to "task" index page after successfully creating the "Task"(I accordance with rails App) the index page compromise of ul#listview with count bubble  some thing of this is kind  . On the beneath the page there is the script to to get the count  as seen in the bubble example (mention above) but it seem that script never execute.
Here is the Code:
partials  => _index.html.erb

Tasks

        My Task

        All Task

I have also tried:
$(document).ready(function() { // above function // }) ,
    $("#task").live("pagecreate",function(){ // above function // })
    $("#task").live("pageshow",function(){ // above function // })
    $("#task").live("pagebeforecreate",function(){ // above function // })

But it seem not even the alert is also not executed.
Regards
Viren Negi
Comment: First you're missing the closing  tag, second go_fetch_the_count("mytasks","all_tasks"); does mytasks need to map to id="my_tasks"? Third do you have a demo site or http://jsfiddle.net you could add to your question
Comment: @Jasper The missing UL is not the problem - maybe the OP isn't using the current JS files or something
Comment: @K.Bob I didn't mean to infer that was the problem, I just posted a code example so Viren could see that the code worked fine.
Comment: @Jasper No worries, I think there must be something else he's not showing us.
Comment: @Phil the go_fetch_the_count() is javascript method to make and ajax request get the json response and the update the according span as visible in example
Comment: @Jasper thank for Example in jsfiddle but it seem that you got it wrong I said when I render the above page as ajax response without(it something like render :partial => "name_of_partial" in Rails Terminology)  template/layout the javascript doesn't execute even though binding all the event mention above
Comment: @Jasper ,@K.Bob , I have push the app at http://jquery-mobile.heroku.com/  to see the effect got to new page and submit the form and see the count is not getting updated
Comment: I see now what you mean. The first time the page is shown the get_count() function runs. When you add a new car and go back to the listing page the get_count() function does NOT run. Is that what the problem is ?
Comment: http://jquerymobile.com/demos/1.0/docs/api/globalconfig.html Have you tried turning off the default ajax post/link behaviour, so that when you return to the list you get a 'new' page.
Comment: @K.Bob ,Yes that is right , but as mention in a  separate comment address to you I mention that jQuery mobile is inject the same page in dom again (if you inspect the dom using firefug or dom inspector) that same div id="car_list" is inject again without flushing the old div from the dom so now my focus is to remove the old div id="car_list" before jQuery Mobile inject the response in into the om I hope I'm not confusing you
Comment: And Yes Turning off the default ajax can help on this but I don't want to follow that path because of various scenario like bandwidth.
Comment: The 'old' `car_list` is still in the DOM but is no longer active, you can find the active `car_list` as it will also have the `ui-page-active` class which the old one no longer does. I find the jQM caching to be troublesome and tend to switch it off - I don't find bandwidth to be enough of a problem these days.
Comment: Yes I think I got the way by removing the page from the dom after pagehide  event occur
Answer: You are missing a closing
 tag. But even without this works OK for me.
You don't have a template/layout with another data-role=page in it do you?
This code works for me (including the missing UL)
<!DOCTYPE html>

    <title>Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />

</script>

Tasks

        My Task

        All Task

Comment: Yes I'm aware that the layout is not render as I'm only returning the above div with data-role="page" for the ajax response for sake reducing the bandwidth , But for sake is there a way to achieve the same without rendering layout
Comment: It seem that the issue is that jquery inject the same page in dom event though the page exist in the dom (does not remove the old (use dom inspector to observe it)) in the example the event is fired but the not update on the current page put page that previously exists in dom hence the problem. "Now my focus is to remove that old page from the dom and inject the new page (Can this be achieved or am I sound over ambition's)"
Answer: There are 2 solution for above problem I manage to find out
SOLUTIONS

Remove the Page from the dom  through pagehide event so that there is only one dom in the page with same dom id .
something like this

$('#car_list').live('pagehide',function() {
      $(this).remove();

    });

(The approach has a serious caveat if you have jquery-mobile back functionality enable. It might land you on page whose back page would have been removed by the page hide event living the user in no man land situation . Plus to remove and download a page again just because the  bubble count got change in the page is a very hard trade off that where the second solution worked for me)

This solution defined the global variable on the page and every time the get_count method is called it check whether the global variable is define if yes update the current page with count just the way the old page is updated
function get_count() {
   $.ajax( {
         url:'/get_count.json',
         dataType : "json",
         success : function(result) {
           $.each(['fer','lam','fia','cor','mer'],function(index,value) {
              console.log(window.reloaded);
              // the below if statement will only execute for the second time
              if (window.reloaded && typeof(window.reloaded) != "undefined") {
                console.log("hello");
                $(".ui-page-active").find("#"+value).text(result[value])
              }
              $("#"+value).text(result[value]);
           })
           window.reloaded = true ;
         }
     });
   }

Update the code with the 2nd solution in heroku app too.
Accepting this as valid answer until some provide more better way to achieve the same


Injectivity and Range of a function

Question: Let, $A=\{(x,y)\in \Bbb R^2:x+y\neq -1\}$
Define, $f:A\to \Bbb R^2$ by $f(x,y)=\left(\displaystyle \frac{x}{1+x+y},\frac{y}{1+x+y}\right)$
$(1)$Is $f$ injective on $A$?
$(2)$What is the Range of $f$?
I started with $f(x,y)=f(u,v)$, then tried to show $(x,y)=(u,v)$. But I could not do it. Can someone help me out for this.
Secondly for computing the range,
$$\begin{align}
f(x,y)=(a,b)\\
 \implies \displaystyle \frac{x}{1+x+y}=a,\displaystyle \frac{y}{1+x+y}=b\\
\implies (1-a)x-ay=a\\
-bx+(1-b)y=b\\
\implies x=\displaystyle \frac{a}{1-(a+b)},y=\displaystyle \frac{b}{1-(a+b)}
\end{align}$$
So, $f(A)=\Bbb R^2-\{(a,b)\in \Bbb R^2:a+b=1\}$
Is the range correct? If yec can it be obtained in some other way?
Comment: @LiChunMin I did try each of these cases. What gets me crazy is the case where $x,y,u,v \neq 0$. Can you do something with that case?
Comment: @MundronSchmidt Yup!
Comment: The answer provided by schmidt is great. But to continue from your work, I think of first assuming $x,y,v \neq 0$ so that you might divide one equation by another and eventually you can get $(x,y) = (u,v)$. After that, suppose $x = 0$, then $u = 0$. Suppose $y = 0$, then $v = 0$....
Comment: see the answer that I give.
Answer: You are almost done. Define $B=\{(a,b)\in\mathbb{R}^2~:~a+b\neq 1\}$ and $g(a,b)=\left(\frac{a}{1-(a+b)},\frac{b}{1-(a+b)}\right)$. Then you have $f:A\to B$ and $g:B\to A$.
Consider $g(B)\subset A$ holds since $\frac{a}{1-(a+b)}+\frac{b}{1-(a+b)}=\frac{a+b}{1-(a+b)}\neq -1$.
You can directly compute, that $f\circ g=id_B$ and $g\circ f=id_A$. This yields $g=f^{-1}$ and $f:A\to B$ has to be bijective, especially injective.
Comment: This was totally out of the box!
Answer: To continue our discussion in the comments, pick any $(x,y), (u,v) \in A$.
Suppose $f(x,y) = f(u,v)$. Further suppose $x, y, v \neq 0$. (You have to prove the cases (i) $x = 0$, (ii) $y = 0$ and (iii) $v = 0$ later on)
Then $$\frac{x}{1+x+y} = \frac{u}{1+u+v}\quad \text{and} \quad \frac{y}{1+x+y} = \frac{v}{1+u+v}$$
For $\frac{y}{1+x+y} \neq 0$, we can divide $\frac{x}{1+x+y}$ by $\frac{y}{1+x+y}$, which is $\frac{v}{1+u+v}$. Then
$$\frac{x}{1+x+y} \frac{1+x+y}{y} = \frac{u}{1+u+v}\frac{1+x+y}{y}=\frac{u}{1+u+v}\frac{1+u+v}{v}$$
$$\frac{x}{y} = \frac{u}{v}$$
For $y, v \neq 0$, we can divide the numerator and divisor by $y$ and $v$.
$$\frac{\frac{x}{y}}{\frac{1}{y}+\frac{x}{y}+1} = \frac{\frac{u}{v}}{\frac{1}{v}+\frac{u}{v}+1}= \frac{\frac{x}{y}}{\frac{1}{v}+\frac{x}{y}+1} $$
And we can cancel $\frac{x}{y}$ on both sides, then
$$\frac{1}{\frac{1}{y}+\frac{x}{y}+1}= \frac{1}{\frac{1}{v}+\frac{x}{y}+1} $$
then
$$\frac{1}{y}+\frac{x}{y}+1 = \frac{1}{v}+\frac{x}{y}+1$$
then $v = y$. Then I think you can show that $x =u$ from now.
Comment: Looks Good. Thank You!

Injectivity and Range of a function


Cannot perform POST request in CodeIgniter

Question: I have a form in a page that uploads user data onto my online server using the CodeIgniter framework. I can access the form page normally using the HTTPS protocol, but when I try to submit the form using POST, I am given a 403 Forbidden: You don't have permission to access <url> on this server. error. What could be the issue?
The .htaccess file:
RewriteEngine On
RewriteCond $1 !^(index\.php|resources|images|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

My form attributes in the view. The $base_url variable is the base_url() configured in config.php:
<form name="new_article_form" id="new_article_form" method="POST" action="<?php echo $base_url; ?>entries/insert_article" enctype="application/x-www-form-urlencoded">
...
</form>

Am I missing something?
Edit:
The full form as requested. It does not use the form_helper from CI for now. Currently working on that:
<form name="new_article_form" id="new_article_form" method="POST" action="<?php echo $base_url; ?>entries/insert_article" enctype="application/x-www-form-urlencoded">

Blog Name:

    <select name="blog" id="blog" required>
    <?php
    echo $blogs; //pre-formatted <option> list from controller
    ?>
    </select>

Article Title:

    <input type="text" name="title" id="title" required />

Article Author:

    <input type="text" name="author" id="author" value="Own" required />

Authoring Date:

    <input type="datetime-local" name="auth_date" id="auth_date" value="<?php echo date("d-m-Y"); ?>" required />

Article URL:

    <input type="text" name="url" id="url" required />

Summary:

    <textarea name="summary" id="summary" style="resize:none" class="text" rows="10" cols="40" required ></textarea>

    <button name="reset" id="reset" type="reset">Clear</button>
    <button name="submit" id="submit" type="submit">ADD</button>
</form>

UPDATE:
I just rewrote the whole form using CI's form helper lib, and am still getting the same error. The form request is not even getting to the controller nor the main index.php file, it is being terminated before that as no POST data reaches the main index.php file at the root of the framework. So this may be a permissions issue or something else before that. NB: am on a shared website hosting platform just in case anyone's wondering, and am currently using a self-signed certificate for online SSL testing.
UPDATE 2:
routes.php:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

$route['default_controller'] = "main";
$route['404_override'] = '';

/* End of file routes.php */
/* Location: ./application/config/routes.php */

config.php:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

$config['base_url'] = 'https://<***full_url***>/';
$config['index_page'] = '';

$config['uri_protocol'] = 'AUTO';

$config['url_suffix'] = '';
$config['language'] = 'english';
$config['charset'] = 'UTF-8';
$config['enable_hooks'] = FALSE;
$config['subclass_prefix'] = 'BG_';
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';

$config['allow_get_array']      = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger']   = 'c';
$config['function_trigger']     = 'm';
$config['directory_trigger']    = 'd'; // experimental not currently in use

$config['log_threshold'] = 2;
$config['log_path'] = '';
$config['log_date_format'] = 'Y-m-d H:i:s';
$config['cache_path'] = '';
$config['encryption_key'] = '';
$config['sess_cookie_name']     = 'ci_session';
$config['sess_expiration']      = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie']  = FALSE;
$config['sess_use_database']    = FALSE;
$config['sess_table_name']      = 'ci_sessions';
$config['sess_match_ip']        = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update']  = 300;

$config['cookie_prefix']    = "";
$config['cookie_domain']    = "";
$config['cookie_path']      = "/";
$config['cookie_secure']    = FALSE;
$config['global_xss_filtering'] = FALSE;

$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = '************';
$config['csrf_cookie_name'] = '*************';
$config['csrf_expire'] = 3600;
$config['compress_output'] = FALSE;
$config['time_reference'] = 'local';

$config['rewrite_short_tags'] = FALSE;

$config['proxy_ips'] = '';

/* End of file config.php */
/* Location: ./application/config/config.php */

entries controller:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Entries extends CI_Controller
{
public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->helper('form');
        $this->load->model("entries_model", "entries");
    }

    public function index($data = array())
    {

        ...//other code

        $form_attrs = array("name"=>"new_article_form", "id"=>"new_article_form", "enctype"=>"application/x-www-form-urlencoded");

        $form = form_open(base_url()."entries/insert_article", $form_attrs);

        //... form entries

        $form .= form_close();

        $data["form"] = $form;

        $this->load->view('entries_view', $data); //the form is displayed on the view properly, no errors present, exactly as shown above
    }

    public function insert_article()
    {
        $blogID = $this->input->post("blog");
        $title = mb_convert_encoding($this->input->post("title"), "UTF-8");

        //... other insert code

        $this->index($data);
    }

    public function blogs($result = "")
    {
        //... blogs view function
        $this->load->view('blogs_view', $data);
    }
}

    //... other code
?>

NB: From what I can conclude, the error is on the server side, as POST requests from the mobile app using the site are able to get through, but browser POST requests specifically with form data are not getting through. GET requests are getting through fine though. The only error visible is also on the server error logs stating that the "404.html" page cannot be found. Anyone know what could be refusing the connections on the server side?
UPDATE:
HTTP Headers:
Host: <***site***>
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101     Firefox/40.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://<***site***>/entries/blogs
Cookie: PHPSESSID=ba4ce8f6cf3ebd19a443763fa8a187c0
Connection: keep-alive

Comment: Open your developer tools and check the network tab. I think your POST is working.
Comment: @GuyT i did that, but it showed a 403 forbidden error
Comment: @Peter Could you post the generated HTML form?
Comment: I want to ask, what is the accepted extension for MIME types "multipart/form-data" and "application/x-www-form-urlencoded" as I have just realized from the header output and some research, those types are not supported on my hosted server
Comment: navigate to host/index.php/entries/insert_article and insert an echo at the first line in the `insert_article` function. Are you using an .htaccess?
Comment: @GuyT thats what I did to test whether the controller function is being called. Turns out, my hosting does not support multipart/form-data enctype or application/x-www-form-urlencoded type either.
Comment: And now, even after enabling that support, the complete form still is not being POSTed.
Comment: Just saw your update. First of all remove to the certificate to terminate a step. Change your `insert_article` to `function insert_article(){print_r($_POST]);die;}` If you receive data from $_POST but not from $input->post() then the XSS or CSRF filter is removing the data.
Comment: Sorry! I see that you've answered the question yourself.
Answer: Turns out the data being submitted by the form was being detected as an XSS attack on the servers Mod Security Firewalls, that's why the requests were getting refused even before CI could be loaded. It has now been disabled on my domain specifically, and the submission now works. Hopefully, no more blocks from now on.
Comment: @GuyT am not sure either, since the form data was simple UTF-8 encoded text being submitted over a POST request, nothing special. From what I saw there were some special characters being checked for which were triggering a false positive e.g. semicolons and colons in the data I was posting
Comment: May I ask you why the server sees the request as an XSS attack? Do you not encode the data properly?
Answer: Use site_url helper in your form action then check in your controller if it's posting or not.
<form name="new_article_form" id="new_article_form" method="POST" action="<?php echo site_url('entries/insert_article') ?>" enctype="application/x-www-form-urlencoded">

Also don't forget to include url helper.
Comment: Using `site_url()` did not help, still getting the same error
Comment: my browser gives no error trace, just the error message, my server access logs show all access is being granted, and I can't find an error stack trace on CI logs either
Comment: @Peter did you check other post requests are working or not?
Comment: I just tried another POST request to the same controller but a different method/function and different view: same technique, using form helper, and it worked. Then I switched tabs to try the above page again, it failed. Now am not sure what is really going on here.
Comment: @Peter did you added any custom route
Comment: No, there are no custom routes, just the default controller route and 404 override route. BTW, I have an app which does POST requests to the app using the framework on every request, and they all go through. Only the above post to insert new stuff does not seem to work.
Comment: @Peter can you post your **`routes`** file & **`controllers`** file & **`config`** file


$\prod_{i=1}^{n} (3 +\frac{1}{a_i})$ cannot be a power of 2 if $a_i \equiv \pm 1 \pmod 6$

Question: I have encountered this problem and I can't solve it.
If $a_i \equiv 1 \pmod 6$ or $a_i \equiv -1 \pmod \ 6$ and $a_i \ne \pm 1$, for every $i \in \{1, 2, .., n\}$, then prove that
$$\prod_{i=1}^{n} \left(3 +\frac{1}{a_i}\right)$$ cannot be a power of $2$. Using induction, I proved that
$$2^{n + 1} \lt \prod_{i=1}^{n} \left(3 +\frac{1}{a_i}\right)$$ Then I tried working$\mod 6$,$\mod4$ and $\mod 3$, but I couldn't solve it. Have you got any ideas?
Comment: Well, first of all, the case for $n = 1$, $3 + \frac{1}{a_1}$ is clearly not a power of two. If $n = 2$, $(3 + \frac{1}{a_1})(3 + \frac{a_2}) > 3^2 > 2^3$. Now assume $\prod_{i = 1}^{n}(3 + \frac{1}{a_i}) > 2^{n + 1}$ and show that $\prod_{i = 1}^{n + 1}(3 + \frac{1}{a_i}) > 2^{n + 2}$. But $\prod_{i = 1}^{n + 1}(3 + \frac{1}{a_i}) > 2^{n + 1} (3 + \frac{1}{a_{n+1}}) > 2^{n + 2}$. The other assumptions I made were false.
Comment: What if $a_i=-1$ for all $i$? If the $a_i$ have to be positive, then the product is at least $3^n$, so if your proof by induction was correct, it follows that $3^n\le 2^{n+1}$ and $(3/2)^n\le 2$ which means that $n=1$.
Comment: Oh, well, I forgot about $-1$.
Comment: My mistake, I have revised the proof and it contained a mistake.
Comment: So is it true and given that this product is indeed bounded by $2^{n+1}$? OP, it is on the person writing the question
to be clear, and this is hard to follow with the corrections made in the comments.
Comment: Sorry for the mistakes, I think I have corrected them.
Comment: Can you outline the proof of the bound by $2^{n+1}$ though? I'm not sure I see that. But yes given that as per Mastrem's comments, the rest is relatively straightfoward.
Comment: Ah yes, it is bounded from below by $2^{n+1}$. And I mispoke, what is true and what I should have said, is that if it were **upper bounded** by $2^{n+1}$ then solving the rest would be straightfoward.
Comment: Yes, indeed. I am sorry for the original mistakes.
Comment: This does look like an interesting problem!
Answer: This does not hold. Examples:
$$(3+\frac1{-7})(3+\frac1{-5})=2^3$$
and
$$(3+\frac1{17})(3+\frac1{19})(3+\frac1{29})(3+\frac1{143})(3+\frac1{215}) = 2^8.$$


Python Input Driven Menu from Dictionary

Question: I am currently working on a script to list the Duck Hunting Limits by State, and I would like to add a dict.items() expression to search, but I don't know how to go about it. I basically want to be able to type in a number, for example "6", and have the function return all states that have a Duck Limit of 6. Any ideas on how to get started with a function to do so? I have included my current script.
# Please see following link for more information: https://www.ducks.org/conservation/where-ducks-unlimited-works/waterfowl-migration-flyways/du-projects-central-flyway

# Imports pyinputplus for input validation
import pyinputplus as pyip

# Dictionary of Central Flyway States and their respective limits
Montana = {
    "State:": "Montana",
    "Duck Limit:": "7",
    "Goose Limit:": "6",
    "Waterfowl Season:": "Oct. 2 - Jan. 14",
}
Wyoming = {
    "State:": "Wyoming",
    "Duck Limit:": "7",
    "Goose Limit:": "3",
    "Waterfowl Season:": "Sept. 26 - Jan. 8",
}
Colorado = {
    "State:": "Colorado",
    "Duck Limit:": "6",
    "Goose Limit:": "3",
    "Waterfowl Season:": "Oct. 11 - Dec. 1 and Dec. 13 - Jan. 25",
}
NM = {
    "State:": "New Mexico",
    "Duck Limit:": "6",
    "Goose Limit:": "5",
    "Waterfowl Season:": "Oct. 4 - Jan. 2",
}
Texas = {
    "State:": "Texas",
    "Duck Limit:": "6",
    "Goose Limit:": "5",
    "Waterfowl Season:": "Nov. 13 - Nov. 28 and Dec. 4 - Jan. 30",
}
Oklahoma = {
    "State:": "Oklahoma",
    "Duck Limit:": "6",
    "Goose Limit:": "8",
    "Waterfowl Season:": "Oct. 17 - Jan. 13",
}
Kansas = {
    "State:": "Kansas",
    "Duck Limit:": "6",
    "Goose Limit:": "6",
    "Waterfowl Season:": "Nov 1. - Jan. 4 and Jan. 17 - Jan. 25",
}
Nebraska = {
    "State:": "Nebraska",
    "Duck Limit:": "6",
    "Goose Limit:": "5",
    "Waterfowl Season:": "Oct. 3 - Dec. 15 and Jan. 6 - Jan. 27",
}
SD = {
    "State:": "South Dakota",
    "Duck Limit:": "6",
    "Goose Limit:": "3",
    "Waterfowl Season:": "Oct. 11 - Jan. 15",
}
ND = {
    "State:": "North Dakota",
    "Duck Limit:": "6",
    "Goose Limit:": "8",
    "Waterfowl Season:": "Sept. 27 - Dec. 7",
}

# Asking user to type name of state
print(
    """Please type Name of Central Flyway State for waterfowl information.
"""
)

# pyip module with a whitelist of available state names. Will return error if input is not whitelisted.
result = pyip.inputMenu(
    [
        "Montana",
        "Wyoming",
        "Colorado",
        "New Mexico",
        "Texas",
        "Oklahoma",
        "Kansas",
        "Nebraska",
        "South Dakota",
        "North Dakota",
    ],
)
# Function to return the result of inputMenu and call out the corresponding dictionary with it's key:value pairs
def statefunction(result):
    print(result)

# if and elif statements to iterate through dictionaries and print items
if result == "Montana":
    statefunction = Montana
    print(statefunction(Montana))

elif result == "Wyoming":
    statefunction == Wyoming
    print(statefunction(Wyoming))
elif result == "Colorado":
    statefunction == Colorado
    print(statefunction(Colorado))
elif result == "New Mexico":
    statefunction == NM
    print(statefunction(NM))
elif result == "Texas":
    statefunction == Texas
    print(statefunction(Texas))
elif result == "Oklahoma":
    statefunction = Oklahoma
    print(statefunction(Oklahoma))
elif result == "Kansas":
    statefunction == Kansas
    print(statefunction(Kansas))
elif result == "Nebraska":
    statefunction == Nebraska
    print(statefunction(Nebraska))
elif result == "South Dakota":
    statefunction == SD
    print(statefunction(SD))
elif result == "North Dakota":
    statefunction == ND
    print(statefunction(ND))

print("Please type Exit to close!")

# Final input menu to stop python from auto closing
close = pyip.inputMenu(
    [
        "Exit",
        "Please Come Again Soon!",
    ],
)

def closefunction(close):
    print(close)

Answer: First of all, don't have each state as it's own variable. Instead, have one variable as a list that stores all the dictionaries.
For example:
states = [
    {
    "State:": "Montana",
    "Duck Limit:": "7",
    "Goose Limit:": "6",
    "WaterfowlSeason:": "Oct. 2 - Jan. 14"
    },
    {
    "State:": "Nebraska",
    "Duck Limit:": "6",
    "Goose Limit:": "5",
    "Waterfowl Season:": "Oct. 3 - Dec. 15 and Jan. 6 - Jan. 27",
    }
    ...
]

Next, I see you want to whitelist some states. It's good to have a list (like whitelisted_states) of whitelisted states. To check if the user inputted a valid state, you can loop through the dictionary states and get the state's name by using "State" key from it, then check if that is in the whitelisted_states. If it isn't you can throw an error, or let them choose again.
This way reduces redundancy in your code and makes it much easier to work with.
To answer the actual question. Again, you will loop through the dictionary, and get the value of "Duck Limit" key. Check if it is "6", if it is, get the state's name by using the "State" key.


JavaScript Regex return null

Question: I have a string that look like this :
blablablablafunction tr(b){b=b.split("");b=b.reverse();b=b.slice(2);return b.join("")}blablablabla

And i want to get : b=b.split("");b=b.reverse();b=b.slice(2);return b.join("")
with Regex :
var match = "function tr(b){(.*)}";
var f = html.match(match);

And i get null in f.Any idea what is the problem?
Answer: You will have to escape special characters in the regex in this case I believe these are { , } and also ( and )(around the function argument list). Use the escape character(\) to do that. So try this regex:
var match = "function tr\\(b\\)\\{(.*)\\}";

Comment: do you have any example?

JavaScript Regex return null


Enumerating records by date

Question: Say we have 5 records for items sold on particular dates like this
Date of Purchase             Qty
2016-11-29 19:33:50.000       5
2017-01-03 20:09:49.000       4
2017-02-23 16:21:21.000       11
2016-11-29 14:33:51.000       2
2016-12-02 16:24:29.000       4

I´d like to enumerate each record by the date in order with an extra column like this:
Date of Purchase             Qty      Order
2016-11-29 19:33:50.000       5         1
2017-01-03 20:09:49.000       4         3
2017-02-23 16:21:21.000       11        4
2016-11-29 14:33:51.000       2         1
2016-12-02 16:24:29.000       4         2

Notice how both dates on 2016-11-29 have the same order number because I only want to order the records by the date and not by the datetime. How would I create this extra column in just plain SQL?
Answer: Using dense_rank() and ordering by the date of DateOfPurchase
select *
  , [Order] = dense_rank() over (order by convert(date,DateOfPurchase))
from t

rextester demo: http://rextester.com/FAAQL92440
returns:
+---------------------+-----+-------+
|   DateOfPurchase    | Qty | Order |
+---------------------+-----+-------+
| 2016-11-29 19:33:50 |   5 |     1 |
| 2016-11-29 14:33:51 |   2 |     1 |
| 2016-12-02 16:24:29 |   4 |     2 |
| 2017-01-03 20:09:49 |   4 |     3 |
| 2017-02-23 16:21:21 |  11 |     4 |
+---------------------+-----+-------+

Comment: such a smart solution. Thank you very much

Enumerating records by date


Sequences in $\ell_p$ spaces

Question: Does there exist a sequence $(x_n)$ belonging to $\ell_1\cap\ell_2$ which converges in one but not the other?  $(x_n)$ is of course a sequence in these spaces, so it's a sequence of sequences.
Answer: Try $x_n(k)=\frac1n$ if $k\leqslant n$ and $0$ otherwise. Then $\|x_n\|_2=\frac1{\sqrt{n}}$ hence $x_n\to0$ in $\ell_2$ but $\|x_n\|_1=1$ hence $(x_n)$ does not converge in $\ell_1$. This proves that convergence in $\ell_2$ does not imply convergence in $\ell_1$.
On the other hand, if $x$ and $y$ are sequences such that $\|x-y\|_1\leqslant1$ then $|x(k)-y(k)|\leqslant1$ for every $k$ hence $|x(k)-y(k)|^2\leqslant|x(k)-y(k)|$ for every $k$ and $\|x-y\|_2^2\le\|x-y\|_1$. This proves that convergence in $\ell_1$ implies convergence in $\ell_2$ (to the same limit).
Comment: You're just too fast :)
Comment: No problem :) Thanks, it's not as if I'm especially proud of that example. If you want to incorporate it into your answer, feel free to do that. I removed my answer because it gave much more away than your initial response and I didn't want to undermine the pedagogical idea of leaving the possibility open (if there was one). *off-topic* I'm more than jealous of your celebrated W, however, I'd have written `\mathsf{W}` which gives $\mathsf{W}$ (had I had the idea and had I dared). Anyway, congratulations!
Comment: The "identity" map is continuous from $\ell_1$ norm to $\ell_2$ norm, so there is no counterexample the other way.
Comment: @GEdgar, unless I am missing something, asserting this continuity to prove the result is a circular reasoning since it is what is asked, is it not? Rather, note that if $\|x-y\|_1\leqslant1$ then $\|x-y\|_2^2\le\|x-y\|_1$.
Comment: @t.b. Sorry about that... :-) But I note you proposed a different example so you might leave your answer, if you ask me.
Comment: @t.b. Thanks. Using mathsf is a good idea, I will apply it.
Comment: Another question:  Why does it follow from the fact that $||x_n||_1=1$ that $(x_n)$ diverges in $\ell_1$?
Comment: FPP, it does not follow right away, you are right that a (small) supplementary step is needed. Here it is. Assume that $(x_n)$ converges in $\ell_1$. Then $(x_n)$ converges in $\ell_2$ to the same limit hence $(x_n)$ converges to the sequence $0$ in $\ell_1$. But $\|x_n-0\|_1$ does not go to zero. This is absurd, hence the hypothesis was wrong, which proves that $(x_n)$ diverges in $\ell_1$.
Answer: I would refer you to the interpolation theorems, such as that of Marcinkiewicz.  Look in Cora Sadowsky's wonderful book on Harmonic Analysis.  Also there are works by Stein and Weiss.  There is a whole machinery on questions of this ilk.
Comment: Isn't that a little bit overkill?

Sequences in $\ell_p$ spaces


Problems when adding data into database (More data/parameters added)

Question: I have a database which i insert some data into. The problem i have is that it will add more data then it should.
When the logfordb.pos is increasing it will add all prevoius data one more time and next time it will add even more.
Here is the code... with some reduction of conn string and parametres.
<code>    public void WriteToDatabase(DatabaseLog logfordb)
    {
        conn.Open();

        var cmd = new SqlCommand();
        cmd.CommandText = "Insert INTO [X] (Y, Z, C " + "Values (@val1, @val2, @val3";

        for (int index = 0; index < logfordb.ListofDB[logfordb.pos].X.Count; index++)
        {
            cmd.Connection = conn;
            cmd.Parameters.Clear();
            if (logfordb.ListofDB[logfordb.pos].X[index].Details != null)
            {
                cmd.Parameters.AddWithValue("@val1", logfordb.ListofDB[logfordb.pos].X[index].Details.Age);
                cmd.Parameters.AddWithValue("@val2", logfordb.ListofDB[logfordb.pos].X[index].Details.Name);
                cmd.Parameters.AddWithValue("@val3", logfordb.ListofDB[logfordb.pos].X[index].Details.Etc);
                cmd.ExecuteNonQuery();
            }
        }
        conn.Close();

        logfordb.pos += 1;
    }
</code>
Comment: How much data should it add? Obviously "pos += 1" is causing the problem.
Comment: It should add all findings in a list (ListofDB) where the pos is the index value of the list
Comment: You're always starting from zero in the for loop so you're adding all data again
Comment: also the  "Insert INTO [X] (Y, Z, C " + "Values (@val1, @val2, @val3"; isa missing a ) before Values
Comment: try changing `cmd.Parameters.AddWithValue` to `cmd.Parameters.Add`. just curious to how that would affect it. as they accomplish the same thing
Comment: @EricRobinson the cmd.Parameters.Add dident add anything.
Comment: @AmiramKorach Yeah i should start from 0 at every new [index/logpos] if that what u mean?
Answer: It seems like you want to change the value of logfordb.pos I think you want to pass logfordb by ref. I suspect the value isn't changing and the second time you call this function you end up adding the same data again because the value outside of this scope isn't being changed just a local copy that the function sees (and then exists destroying references to the changes).
Answer: Your code iterates through the entire logfordb every single time this is called.
You have three options:

At the end of this method, clear the logfordb entirely. (probably makes the most sense)
Add a starting position parameter, and let the calling code decide the position to start pushing the logfordb records into the database.
Add a "Stored" property to each record inside logfordb so that you can set it when that individual record has been stored and not push that record again.

Out of those, option 1 is probably your safest bet.


How can I append date and time to node titles?

Question: I want to append the date and time to node titles. For example, If the title is Test, I want to change it to Test_DDMMYY_hhmmss.
How can I achieve this?
Answer: This will do for you
function modulename_node_presave($node) {
      if($node->type == 'node_type_machine_name') {
        $new_date = date("DMY_hms", time());
        $node->title = $node->title."_".$new_date;
      }
}

Comment: Where am i need to add this?
Comment: if you had custom module you can add it there
Answer: Check out the Automatic Nodetitles module to do it without code. In combination with the Token module you can build complex patterns.
Comment: Is there is any option to append the entered title with date?
Answer: I think you want to use hook_node_presave(). This should get you started.
function mymodule_node_presave($node){
  if ($node->type == "my_content_type") {
    $node->title = $node->title . "_" . date('dmy_his');
  }
}

Though I am only inferring that you want date and time of when the node was saved.
Comment: I am new for Drupal. May i know where am i need to add this Function?
Comment: You probably want to put it in a module. In the `modules` directory, you must create a folder for your module. In this example I would have a `my_test` folder, with files named `my_test.module` and `my_test.info`.

This function would go in the `my_test.module` file.
Comment: i just copied the function in my_test.module file but its not working
Comment: in your info declare these name = Test module
package = Custom Modules
description = Module for LO Admin related code
core = 7.x

files[] = my_test.module
Comment: @Sam1604, I believe there's a bare minimum you need in the .info file:

    name = My Test Module
    description = Test module
    core = 7.x

Then of course you must enable the module.
Comment: Enabled Test Module in my project, while saving the data it shows "function my_test_node....." in the top. The title is saved as usual (Test) not like (Test_ddmmyy_hhss). Am i need to edit something in Function?
Comment: What is the machine name of the content type of the node you are saving?
Comment: That's your local server. The node you're saving is of a particular content type, like page or article. If you copied that function, you'll have to change `my_content_type`.


Gradient descent doesn't find solution to ordinary least squares on this dataset?

Question: I have been studying linear regression and tried it on below set {(x,y)}, where x specified the area of house in square-feet, and y specified the price in dollars. This is the first example in Andrew Ng Notes.

2104,400
1600,330
2400,369
1416,232
3000,540

I developed a sample code but when I run it, the cost is increasing with each step whereas it should be decreasing with each step. Code and output given below. bias is W0X0, where X0=1. featureWeights is an array of [X1,X2,...,XN]
I also tried an online python solution available here, and explained here. But this example is also giving the same output.
Where is the gap in understanding the concept?
Code:
package com.practice.cnn;

import java.util.Arrays;

public class LinearRegressionExample {

    private float ALPHA = 0.0001f;
    private int featureCount = 0;
    private int rowCount = 0;

    private float bias = 1.0f;
    private float[] featureWeights = null;

    private float optimumCost = Float.MAX_VALUE;

    private boolean status = true;

    private float trainingInput[][] = null;
    private float trainingOutput[] = null;

    public void train(float[][] input, float[] output) {
        if (input == null || output == null) {
            return;
        }

        if (input.length != output.length) {
            return;
        }

        if (input.length == 0) {
            return;
        }

        rowCount = input.length;
        featureCount = input[0].length;

        for (int i = 1; i < rowCount; i++) {
            if (input[i] == null) {
                return;
            }

            if (featureCount != input[i].length) {
                return;
            }
        }

        featureWeights = new float[featureCount];
        Arrays.fill(featureWeights, 1.0f);

        bias = 0;   //temp-update-1
        featureWeights[0] = 0;  //temp-update-1

        this.trainingInput = input;
        this.trainingOutput = output;

        int count = 0;
        while (true) {
            float cost = getCost();

            System.out.print("Iteration[" + (count++) + "] ==> ");
            System.out.print("bias -> " + bias);
            for (int i = 0; i < featureCount; i++) {
                System.out.print(", featureWeights[" + i + "] -> " + featureWeights[i]);
            }
            System.out.print(", cost -> " + cost);
            System.out.println();

//          if (cost > optimumCost) {
//              status = false;
//              break;
//          } else {
//              optimumCost = cost;
//          }

            optimumCost = cost;

            float newBias = bias + (ALPHA * getGradientDescent(-1));

            float[] newFeaturesWeights = new float[featureCount];
            for (int i = 0; i < featureCount; i++) {
                newFeaturesWeights[i] = featureWeights[i] + (ALPHA * getGradientDescent(i));
            }

            bias = newBias;

            for (int i = 0; i < featureCount; i++) {
                featureWeights[i] = newFeaturesWeights[i];
            }
        }
    }

    private float getCost() {
        float sum = 0;
        for (int i = 0; i < rowCount; i++) {
            float temp = bias;
            for (int j = 0; j < featureCount; j++) {
                temp += featureWeights[j] * trainingInput[i][j];
            }

            float x = (temp - trainingOutput[i]) * (temp - trainingOutput[i]);
            sum += x;
        }
        return (sum / rowCount);
    }

    private float getGradientDescent(final int index) {
        float sum = 0;
        for (int i = 0; i < rowCount; i++) {
            float temp = bias;
            for (int j = 0; j < featureCount; j++) {
                temp += featureWeights[j] * trainingInput[i][j];
            }

            float x = trainingOutput[i] - (temp);
            sum += (index == -1) ? x : (x * trainingInput[i][index]);
        }
        return ((sum * 2) / rowCount);
    }

    public static void main(String[] args) {
        float[][] input = new float[][] { { 2104 }, { 1600 }, { 2400 }, { 1416 }, { 3000 } };

        float[] output = new float[] { 400, 330, 369, 232, 540 };

        LinearRegressionExample example = new LinearRegressionExample();
        example.train(input, output);
    }
}

Output:
Iteration[0] ==> bias -> 0.0, featureWeights[0] -> 0.0, cost -> 150097.0
Iteration[1] ==> bias -> 0.07484, featureWeights[0] -> 168.14847, cost -> 1.34029099E11
Iteration[2] ==> bias -> -70.60721, featureWeights[0] -> -159417.34, cost -> 1.20725801E17
Iteration[3] ==> bias -> 67012.305, featureWeights[0] -> 1.51299168E8, cost -> 1.0874295E23
Iteration[4] ==> bias -> -6.3599688E7, featureWeights[0] -> -1.43594258E11, cost -> 9.794949E28
Iteration[5] ==> bias -> 6.036088E10, featureWeights[0] -> 1.36281745E14, cost -> 8.822738E34
Iteration[6] ==> bias -> -5.7287012E13, featureWeights[0] -> -1.29341617E17, cost -> Infinity
Iteration[7] ==> bias -> 5.4369677E16, featureWeights[0] -> 1.2275491E20, cost -> Infinity
Iteration[8] ==> bias -> -5.1600908E19, featureWeights[0] -> -1.1650362E23, cost -> Infinity
Iteration[9] ==> bias -> 4.897313E22, featureWeights[0] -> 1.1057068E26, cost -> Infinity
Iteration[10] ==> bias -> -4.6479177E25, featureWeights[0] -> -1.0493987E29, cost -> Infinity
Iteration[11] ==> bias -> 4.411223E28, featureWeights[0] -> 9.959581E31, cost -> Infinity
Iteration[12] ==> bias -> -4.186581E31, featureWeights[0] -> -Infinity, cost -> Infinity
Iteration[13] ==> bias -> Infinity, featureWeights[0] -> NaN, cost -> NaN
Iteration[14] ==> bias -> NaN, featureWeights[0] -> NaN, cost -> NaN

Comment: The accepted answer by Matthew is *obviously* statistical. This means that the question required statistical (and not programming) expertise to answer; it makes it on-topic by definition. I vote to reopen.
Comment: If things blow up to infinity as they do here, you are probably forgetting to divide by the scale of the vector somewhere.
Comment: This is off topic here.
Answer: The short answer is that your step size is too big. Instead of descending the canyon wall, your step is so big that you're jumping across from one side to higher up on the other!
Cost function below:

The long answer is that it's difficult for a naive gradient descent to solve this problem because the level sets of your cost function are highly elongated ellipses rather than circles. To robustly solve this problem, note that there are more sophisticated ways to choose:

a step size (than hardcoding a constant).
a step direction (than gradient descent).

Underlying problem
The underlying problem is that level sets of your cost function are highly elongated ellipses, and this causes problems for gradient descent. The below figure shows level sets for the cost function.

With highly elliptical level sets, the direction of steepest descent may barely align with the direction of the solution. For example in this problem, the intercept term (what you call "bias") needs to travel a great distance (from $0$ to $\approx 26.789$ along the canyon floor) but it is for the other feature where the partial derivative has a much larger slope.
If step size is too big, you will literally jump over the lower blue region and ascend instead of descend.
BUT if you if you reduce your step size, your progress in getting $\theta_0$ to the proper value becomes painfully slow.

I suggest reading this answer on Quora.

Quick fix 1:
Change your code to private float ALPHA =  0.0000002f; and you'll stop overshooting.
Quick fix 2:
If you rescale your X data to 2.104, 1.600, etc... your level sets become spherical and gradient descent quickly converges with a higher learning rate. This lowers the condition number of your design matrix $X'X$.
More advanced fixes
If the goal were to efficiently solve ordinary least squares rather than simply learn gradient descent for a class, observe that:

There are more sophisticated ways to calculate step size, such as line search and the Armijo rule.
Near an answer where local conditions prevail, Newton's method obtains quadratic convergence and is a great way to choose a step direction and size.
Solving least squares is equivalent to solving a linear system. Modern algorithms don't use naive gradient descent. Instead:

For small systems ($k$ on the order of several thousand or less), they use something like QR decomposition with partial pivoting.
For large systems, they do formulate it is an optimization problem and use iterative methods such as the Krylov subspace methods.

Note that there are many packages which will solve the linear system $(X'X) b = X'y$ for $b$ and you can check the results of your gradient descent algorithm against that.
The actual solution is
  26.789880528523071
   0.165118878075797

You will find that those achieve the minimum value for the cost function.
Comment: +1 it is luxury to let other people to debugging the code!
Comment: @hxd1011 I thought it was a dumb coding error at first, but instead it turns (imho) to be a quite instructive example on what can go wrong with a naive gradient descent.
Comment: @MatthewGunn I got the solution b=0.99970686, m=0.17655967 (y = mx + b). And what did you mean by "a step size than hardcoding a constant"? Does that mean we should change it for every iteration? or we need to calculate it based upon the input values?
Comment: @Amber Beriwal Yeah, you would have $\alpha_i$ be specific to iteration $i$. A question is, how far to go in the direction of the negative gradient? A simple strategy (as what you do) is to have a hardcoded value for $\alpha$ (you had .0001).  Something more sophisticated is [line search](https://en.wikipedia.org/wiki/Line_search) and/or the [Armijo rule](https://en.wikipedia.org/wiki/Wolfe_conditions). The idea of line search is to choose $\alpha_i$ to minimize $f$. Pick a direction (eg. the gradient) and then do a line search to find the lowest point along the line.
Comment: @AmberBeriwal You will find that (26.789, .1651) will have a slightly lower cost. It's slightly downhill from (.9997, .1766) in a direction where the cost function has a tiny slope.
Answer: As Matthew (Gunn) has already indicated, the contours of the 3-dimensional cost or performance function are highly elliptical in this case.  Since your Java code uses a single step-size value for the gradient descent calculations, the updates to the weights (i.e. the y-axis intercept and slope of the linear function) are both governed by this single step-size.
As a result, the very small step-size that is required to control the update of the weight associated with the larger gradient (in this case, the slope of the linear function) drastically limits how fast the other weight with the smaller gradient (the y-axis intercept of the linear function) is updated.  Under the current conditions, the latter weight does not converge to its true value of approximately 26.7.
Given the time and effort that you have invested in writing your Java code, I would suggest modifying it to use two discrete step-size values, an appropriate step-size for each weight.  Andrew Ng suggests in his notes that it is better to use feature scaling to ensure that the contours of the cost function are more regular (i.e. circular) in form.  However, modifying your Java code to use a different step-size for each weight might be a good exercise in addition to looking at feature scaling.
Another idea to consider is how the initial weight values are picked.  In your Java code you initialized both values to zero.  It is also quite common to initialize the weights to small, fractional values.  In this particular case, however, both of these approaches would not work in light of the highly elliptical (i.e. non-circular) contours of the three-dimensional cost function.  Given the weights for this problem can be found using other methods, like the solution for the linear system suggested by Matthew at the end of his post, you could try to initialize the weights to values closer to the correct weights and see how your original code using a single step-size converges.
The Python code you found approaches the solution in the same way as your Java code - both use a single step-size parameter.  I modified this Python code to use a different step-size for each weight.  I have included it below.
from numpy import *

def compute_error_for_line_given_points(b, m, points):
    totalError = 0
    for i in range(0, len(points)):
        x = points[i, 0]
        y = points[i, 1]
        totalError += (y - (m * x + b)) ** 2
    return totalError / float(len(points))

def step_gradient(b_current, m_current, points, learningRate_1, learningRate_2):
    b_gradient = 0
    m_gradient = 0
    N = float(len(points))
    for i in range(0, len(points)):
        x = points[i, 0]
        y = points[i, 1]
        b_gradient += -(2/N) * (y - ((m_current * x) + b_current))
        m_gradient += -(2/N) * x * (y - ((m_current * x) + b_current))
    new_b = b_current - (learningRate_1 * b_gradient)
    new_m = m_current - (learningRate_2 * m_gradient)
    return [new_b, new_m]

def gradient_descent_runner(points, starting_b, starting_m, learning_rate_1, learning_rate_2, num_iterations):
    b = starting_b
    m = starting_m
    for i in range(num_iterations):
        b, m = step_gradient(b, m, array(points), learning_rate_1, learning_rate_2)
    return [b, m]

def run():
    #points = genfromtxt("data.csv", delimiter=",")
    #learning_rate = 0.0001
    #num_iterations = 200

    points = genfromtxt("test_set.csv", delimiter=",")
    learning_rate_1 = 0.5
    learning_rate_2 = 0.0000001
    num_iterations = 1000

    initial_b = 0 # initial y-intercept guess
    initial_m = 0 # initial slope guess

    print("Starting gradient descent at b = {0}, m = {1}, error = {2}".format(initial_b, initial_m, compute_error_for_line_given_points(initial_b, initial_m, points)))
    print("Running...")

    [b, m] = gradient_descent_runner(points, initial_b, initial_m, learning_rate_1, learning_rate_2, num_iterations)

    print("After {0} iterations b = {1}, m = {2}, error = {3}".format(num_iterations, b, m, compute_error_for_line_given_points(b, m, points)))

if __name__ == '__main__':
    run()

It runs under Python 3, which requires the parentheses around the argument for the "print" statements.  Otherwise it will run under Python 2 by removing the parentheses.  You'll need to create a CSV-file with the data from Andrew Ng's example.
Use can cross-reference the Python code to check your Java code.


JQuery param escaping & sign

Question: I have the following object:
var ob = {
  prop: 'ab&cs&ef'
}

When I use param method from jQuery ($.param()), it returns:
"prop=ab%26cs%26ef"

How can I make it return the following?
"prop=ab&cs&ef"

Update
I know, that if I use:
unescape($.param(ob))

I will receive what I need. However, unescape method is deprecated.
Comment: Th point of `param()` is to format the object so it can be passed in a URL. If you don't encode it, the `&` signs will make the single `prop` query string parameter into 3 separate ones. Therefore it is not possible to use `param()` for this.
Comment: @Rhumborl, if I use unescape on $.param(..), it will return the string I want. However, unescape is deprecated.
Comment: @Rhumborl, for example, what if I want to pass multiple values for one parameter?
Comment: Use an array: `prop: ['ab', 'cd, 'ef']`
Comment: Can you not use `encodeURIComponent()` & `decodeURIComponent()`?
Answer: You have to decode the URI coded result again p.e. like this:
var ob = {
  prop: 'ab&cs&ef'
}
alert(decodeURIComponent($.param(ob)));

Answer: Did you have try using decodeURI?
Sample:
var uri = "http://w3schools.com/my test.asp?name=ståle&car=saab";
var uri_enc = encodeURIComponent(uri);
var uri_dec = decodeURIComponent(uri_enc);
var res = uri_enc + "
" + uri_dec;

Result
http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab     // Encoded URI
http://w3schools.com/my test.asp?name=ståle&car=saab                            // Decoded URI

JQuery param escaping & sign


Is it ever good to use Razor views as AngularJS views?

Question: When, if ever, is it appropriate to render an angular partial view using Razor?
Comment: Well I don't know anything about Razor but my general feeling is that if you don't need it why introduce a whole extra layer of templating? Is there something Razor provides you with that Angular's templates can't handle or don't do well?  The nice thing about sticking with "The Angular Way" is that things are pretty darn well decoupled and can DI just about everything which means testing is easier.  Introducing other libraries/ways of doing things will undoubtedly complicate the decoupling.
Comment: Razor views work on server, angular on client so there is clear demarcation. Can you give a scenario and explain your question better?
Comment: I guess the scenario would be applying Security logic to the view itself.  If some part needs to be hidden or shown, you could avoid rendering it altogether.
Answer: I've generally tried to stay away from mixing server side rendering with client-side rendering when using Angular but I have found it convenient to sometimes:

Set variables/data that is known server-side

An example might be a client API key that you might want to use client-side without making an additional call to a backend for that information.
Here is an example of a template:

Where @soundcloudApiKey is presumably available in a model server-side and config is a directive that brings data from the markup into your Angular code in case you want to use it elsewhere:
myModule.directive('config', function() {
    return {
      link: function(scope, elm, attrs) {
        // you can save config to a service and use it elsewhere
        var config = scope.$eval(attrs.config);
        console.log(config.soundcloudApiKey);
      }
    };
  });

Note: there is likely a cleaner way to get to this type of configuration data like via a login process or an explicit call for config settings but I've used this type of thing in the past and it works just fine!


Derivation of survival copula

Question: $$ \begin{align}F(x,y) &= P(X\leq x, Y\leq y) \\
 &= C(F(x), F(y)) \end{align}$$
The copula of a bivariate distribution is equal to its CDF, $C(u,v) = F(x,y)$. The density of the data's CDF therefore can be expressed as
$$f(x,y) = c(u,v) \times f_X(x) f_Y(y)$$
where $c(u,v)$ is the copula density and $f_X(x)$ is a marginal.
If $\hat{C}(u,v)$ is the survival copula for determining
$$ \begin{align}\bar{F}(x,y) &= P(X> x, Y > y) \\
 &= \hat{C}(1-F(x), 1-F(y)) \end{align}$$
how is the first equation of the ordinary copula, $C(u,v)$, linked to the survival copula as
$$\hat{C}(u,v) = u + v - 1 + C(1-u,1-v)$$
are $u$ and $v$ merely vectors containing the (ranked) observations of the uniform marginals?
A derivation in integrals and probabilities (rather than $F$s) would be good.
Comment: the lhs of the first equation is $f(x,y)$
Answer: Here is a purely algebraic and entirely rigorous demonstration.
As a matter of notation, when $\mathcal A\subset\Omega,$ the indicator function of $\mathcal A$ is defined by
$$\mathscr{I}_{\mathcal{A}}(\omega)=\left\{\begin{aligned}1 & \quad\omega\in \mathcal{A}\\0&\quad\text{otherwise.}\end{aligned}\right.$$
Indicator functions connect probabilities and expectations because when $\Omega$ is a probability space (with probability measure $\mathbb P$) and $\mathcal A$ is measurable (which for our purposes merely means it has a probability),
$$\Pr(\mathcal A) = \int_{\Omega} \mathscr{I}_{\mathcal{A}}\,\mathrm{d}\mathbb{P}.\tag{*}$$
Indicator functions also enjoy intimate, simple relationships with set operations.  In particular,

$\mathscr{I}_{\Omega\setminus \mathcal{A}} = \mathscr{I}_{\mathcal{A}^\prime} =  1 - \mathscr{I}_{\mathcal A}.$ Set complements correspond to numerical complements (subtracting from $1$).

$\mathscr{I}_{\mathcal{A} \cap \mathcal{B}} =\mathscr{I}_{\mathcal A}\mathscr{I}_{\mathcal B}.$ Intersection corresponds to multiplication.

The question concerns $(X,Y),$ a random variable with continuous marginals $F_X$ and $F_Y.$  There are two corresponding random variables in the copula, $(U,V),$ defined by $U=F_X(X)$ and $V=F_Y(Y).$  To study the distribution of $(X,Y)$ we will, as always,  consider two arbitrary numbers $x$ and $y.$  Letting $F_X(x)=u$ and $F_Y(y)=v,$ we see $u$ and $v$ are also numbers between $0$ and $1;$ that is, $(u,v)\in [0,1]^2.$ The events conventionally associated with these numbers are $$\mathcal{A} = X\le x = U \le u$$ and $$\mathcal{B} = Y\le y = V \le v.$$
With these preliminaries in place, let's turn to the question.  You ask about the probability of the event $U\gt u,V\gt v.$  This is the intersection of the complements, $ \mathcal{A}^\prime \cap \mathcal{B}^\prime.$  Employing first $(1)$ to deal with the complements and then $(2)$ to deal with the intersection we obtain
$$\mathscr{I}_{\mathcal{A}^\prime \cap \mathcal{B}^\prime} = \left(1 - \mathscr{I}_{\mathcal{A}}\right)\left(1 - \mathscr{I}_{\mathcal{B}}\right).$$
The rest is so easy as to be trivial: the only work we need do is (1) algebraically expand this product and (2) apply linearity of expectation:
$$\begin{aligned}
\hat C(u,v) &= \Pr(U\gt u,V\gt v)\\& = \Pr\left(\mathcal{A}^\prime \cap \mathcal{B}^\prime\right)\\
&= \iint_{[0,1]^2} \mathscr{I}_{\mathcal{A}^\prime \cap \mathcal{B}^\prime}(u,v)\,\mathrm{d}u\mathrm{d}v\\
&= \iint_{[0,1]^2} \left( 1 - \mathscr{I}_{\mathcal{A}} - \mathscr{I}_{\mathcal{B}} + \mathscr{I}_{\mathcal{A}}\mathscr{I}_{\mathcal{B}} \right)(u,v)\,\mathrm{d}u\mathrm{d}v\\
&= \iint_{[0,1]^2} 1\,\mathrm{d}u\mathrm{d}v - \iint_{[0,1]^2}\mathscr{I}_{\mathcal{A}}(u,v)\,\mathrm{d}u\mathrm{d}v \\&\quad\quad\quad - \iint_{[0,1]^2}\mathscr{I}_{\mathcal{B}}(u,v)\,\mathrm{d}u\mathrm{d}v + \iint_{[0,1]^2}\mathscr{I}_{\mathcal{A}}\mathscr{I}_{\mathcal{B}}(u,v)\,\mathrm{d}u\mathrm{d}v\\
&= 1 - \Pr(U\le u) - \Pr(V\le v) + \Pr(U\le u, V\le v)\\
&= 1 - C(u,1) - C(1,v) + C(u,v)\\
&= 1 - u - v + C(u,v).
\end{aligned}$$
The first appearances of the survival copula $\hat C$ and copula $C$ are their definitions.  By construction, $$C(u,1)=\Pr(U\le u)=\Pr(F_X(X)\le F_X(x)) =\Pr(X\le x)=F_X(x)=u$$ and likewise $C(1,v)=v,$ thereby justifying the final equality.
An equivalent statement can be obtained by changing $u$ to $1-u$ and $v$ to $1-v$ (both of which remain between $0$ and $1,$ as required), yielding
$$\begin{aligned}
\hat C(1-u,1-v) &= 1 - (1-u) - (1-v) + C(1-u,1-v) \\&= u+v-1 + C(1-u,1-v).\end{aligned}$$
That seems to be what was intended by the question.
You might find it instructive to compare this to the section "Intuition from Algebraic Manipulation" at https://stats.stackexchange.com/a/43075/919 and then compare it to the visualization under "Intuition from Geometry" in the same post: it's the same underlying idea.
Comment: $C(u,1)=u$ and $C(1,v)=v$ are part of the definitions of a copula, but my string of equations following "by construction" shows why these equalities must hold.  Since $C$ is a function $C:[0,1]^2\to[0,1],$ your questions about "only scalar numbers" don't make much sense. Finally, you can't switch the marginals unless the copula is symmetric, which you don't assume.
Comment: are $C(u,1)=u$ and $C(1,v)=v$ what they call "subcopulas" that are grounded and 2-increasing? how does this match up with $u$ and $v$ being only scalar numbers between $0$ and $1$? also, what happens if you arbitrarily swapped  them: $C(v,1)=v$ and $C(1,u)=u$, i.e. does it matter which of the two marginals get gold or silver

Derivation of survival copula


limit of sequence/series in the form [infinity/ infinity]

Question: Suppose I have a series/sequence
$\{A_n\}$, ${n \to \infty}$ and the limit of the $A_n$ is:
$$\lim_{n \to \infty}A_n = \infty$$
Is it possible to find a sequence/series which will give
$$\lim_{n \to \infty}\frac{A_{n+1}}{An}= 0$$
(I am aware that the limit will be in the form $\frac{\infty}{\infty}$)
Answer: If $(A_n)$ is a positive sequence with $\lim_{n \to \infty}\frac{A_{n+1}}{A_n}= 0$, then there is $N \in \mathbb N$ such that $\frac{A_{n+1}}{A_n} <1$ for $n \ge N$. This gives
$A_{n+1}<A_N$ for all $n>N$.
Therefore $\lim_{n \to \infty}A_n = \infty$ can not occure.
Answer: If $(A_n)$ is a positive sequence with $\lim_{n \to \infty}\frac{A_{n+1}}{A_n}= 0$, then by the ratio test: $\sum_{n=1}^{\infty}A_n$ converges, hence $A_n \to 0$.
Comment: ok, and what about a case when a the limit of a  sequence An is infinity,Is it possible that the limit of An+1/An will be infinity too?
Comment: yes, $A_n=n! $.


Angular / Jasmine / Karma - can't start app due to $http call in main module

Question: I manually bootstrap my Angular app following the response to an API call (and corresponding setting of a constant), thus:
(function() {

    var myApp = angular.module('myApp');

    // Bootstrap the app once we've got a config
    var initInjector = angular.injector(['ng']);
    var $http = initInjector.get('$http');

    $http.get('/api/configs').then(
        function(response) {
            myApp.constant('myConfig', response.data);
            bootstrapApp();
        },
        function(error) {
            console.log('Unable to get config', error);
        }
    );

    function bootstrapApp() {
        angular.element(document).ready(function() {
            angular.bootstrap(document, ['myApp']);
        });
    }

})();

This is preventing my tests from running as the $http call isn't being mocked.
04 07 2017 14:05:53.965:WARN [karma]: No captured browser, open http://localhost:9876/
04 07 2017 14:05:53.987:INFO [karma]: Karma v1.3.0 server started at http://localhost:9876/
04 07 2017 14:05:55.169:INFO [Chrome 59.0.3071 (Linux 0.0.0)]: Connected on socket /#y-gZChEZ25VdBB7YAAAA with id manual-6637
04 07 2017 14:05:56.270:WARN [web-server]: 404: /api/configs

As you can see, the /api/configs call is unsurprisingly 404'ing.
I can't get my head around how to mock this. Creating a test for this module and mocking the $http call doesn't fix it as the call is being made when Karma starts the app.
It feels like I need a "global" $http mock that is available to the test runner when it starts. But I could barking up completely the wrong tree.
Does anyone have any thoughts? Thanks! :)
Answer: What you can do is to have a setup file that is added in the files:[ 'mysetup.js', ... ] in karma.conf.js. There you can mock the $http something like this:
//----mysetup.js----
var response = null;
var replaceHttpGet = function( get ){
    get.success( response ); // or whatever you need
};
//another variable for failure

and then you can do in your test:
//---in test---
var oldHttpGet = $http.get;
$http.get = replaceHttpGet;
response = { //mock response };
...test...
$http.get=oldHttpGet;


Unable save/update any content after migrating from local to production

Question: This is the first time I have made my Drupal site live on a production server (Ubuntu ls 10.04).
These are the steps I did:

Zip the entire webroot folder
Upload to the production server
Extract the contents into the webroot
Take db dump from local server
Dump into the production server
Update the production's Drupal admin password

I do not have a problem viewing the contents, but I am unable to save any content including the configuration settings such as Site information. It doesn't throw any error message or update the content.
What other steps might I have missed?
Comment: Did also .htaccess get copied? Do you have mod_rewrite working on the server?
Comment: Does your settings.php have correct database settings?
Comment: Yes, I have .htaccess file copied. Not sure what is mod-rewirte?
Comment: Please add mod_rewrite in answer. Thanks a million it solved
Comment: Answer below indicates this is a dup.
Answer: Check mod_rewrite (server module) and .htaccess (configuration files in Drupal installation, which easily can be left behind when copying) which take care of lot of the URL and path functionality.
Read more from https://drupal.org/getting-started/clean-urls
Credits to this question:
Can't save settings after copying site to new server
Answer: Find these lines in your .htaccess and uncomment RewriteBase /
# If your site is running in a VirtualDocumentRoot at http://example.com/,
 # uncomment the following line:
 RewriteBase /


Can't get 200 status code from post request to Rails route

Question: I have this in my Pizzas controller:
def post
  render :nothing => true, status: 200
end

def get
  render :nothing => true, status: 200
end

My routes:
 get '/' => 'pizzas#get'
 post '/' => 'pizzas#post'

And this is how I post to that route:
require 'httparty'
response = HTTParty.post('https://example.com', {})
p response.code #returns 422 (Unprocessable Entity)

What is the reason for this? With GET request to that route I reliably get 200. How to get code 200?
Comment: You're posting to where your app is rooted to, not the post action in your controller.

What is in your routes?
Comment: @japed, I did, thanks for the reminder, I'll add my routes to the question now.
Comment: where are you posting? does it require you send JSON?
Comment: @neo, no, it doesn't require me to send JSON. By the way, if it could be helpful - there is a `before_filter` in pizzas controller, which invokes a method that talks to websockets and creates a record in database.
Comment: can you show the function you call on the before_filter?
Comment: @Alfonso, thank you for trying to help! figures the problem was in authenticity tokens.
Answer: It figures I had to get rid of protect_from_forgery line in my application_controller.rb.
The GET request was passing through because it doesn't require authenticity token (the one that you see in form created by rails helpers).


Sending private messages between users

Question:  EDITED
The excellent Privatemsg module provides a wealth of functionality but some sites might not need/want this degree of complexity. Rather than starting with something complex and disabling/removing features, I would like to think about ways to build something relatively simple from basics.
Using the basic infrastructure of D7 what are the ways one could create a simple messaging system that allows user A to message user B, and both of these corresponding users to delete this message individually (i.e. user A deletes message 1, but user B does not; therefore user B can still see message 1)?
How might message threads (i.e. successive related messages) be managed and displayed?
How well would the solution scale (e.g. 1,000,000 messages, 100,000 threads, etc.).
Thank you.
Comment: @berdir can you help here please?
Comment: I'm voting to close this question as off-topic because it's a follow-up on specific comments in the Drupal issue queue. Please continue the conversation there.
Comment: @marcvangend Sorry, but I argue you've misunderstood the purpose of this question. I referenced Drupal.org in my 1st paragraph only to keep my question here as brief as possible, to provide helpful context. My 2nd paragraph contains the question, which I think is clearly not a "follow-up" to that Drupal.org thread: the latter is about D8 Privatemsg while I am asking for ways to accomplish simple messaging *using D7's basic infrastructure without Privatemsg*. Niall (below) has kindly suggested Entity References as 1 way to build the functionality I asked about.If you want I will edit my OP.
Comment: @marcvangend Have edited. I admit my initial post may not have been clear enough in its intention - sorry about that. Hopefully the edit is satisfactory. Private messaging in Drupal is apparently dominated by the (impressive) Privatemsg module. Therefore I think this question is helpful for the community. Not everyone wants to take a feature-rich OTB solution and start disabling/removing features/bending it to their use case. If only 25% of what Privatemsg can do is needed, what are the ways this could be built from scratch using D7's basic infrastructure.
Comment: "Questions asking to recommend or find a book, tool, module, theme, distribution, tutorial, or other off-site resource are off-topic for Drupal Answers as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it." I find this unnecessarily heavy-handed of the moderators. This is a helpful question  about how to leverage the intrinsic infrastructure of Drupal to accomplish a defined task, and "opinions" from experienced developers would be valuable to all interested - not "spam". Shame to see moderators like this.
Answer: By default, giving a role the permission to delete messages will not delete the message for the other user. I just tested this and it works as you require.
As for only allowing messages between certain users, you can prepopulate the "To" field with /messages/new/[nid]. So on the user page or in views or whatever, you can create this link using tokens or replacements.
Then disable the field with a custom module. Savvy users could change the [nid] in the url or even the html in the page so this depends on how secure it needs to be. They'd need to know another user's nid to be able to do this but they can only know that if they can already view the user.
<code>function CUSTOMMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'privatemsg_new') {
    $form['recipient']['#disabled'] = '1';
 }
}
</code>
Comment: Entity references. Have a content type with an entity reference field for each user. You can prepopulate this field with two or more users. Then have a view that displays these nodes and the users chat in the comments. If you are using rules, you can control access to the nodes or if not, a small custom module.
Comment: Thank you for this - I appreciate it. I should have said more clearly in the OP, I know how to do all this with Privatemsg. What I was wondering is if you wanted to achieve the basic functionality (described above) without using Privatemsg what are the ways you might go about this. I think it's a helpful line of enquiry because some might want basic message functionality without using Privatemsg, which as Berdir explains is a large and feature-packed module. Rather than starting with something complex and disabling/removing features, what are the ways to build just the basics? Thanks

Sending private messages between users


How to find delta, for a given epsilon?

Question:
Problem that I am facing:
So naturally I decided to shift to the polar co-ordinates, however when I try to simplify the expression remains very complicated and despite using the fact that sin and cos belong to [-1,1] I cannot get any conclusive bound.
Thanks
Comment: Same question: [If $f(x) =\left(\frac{2x^4y-5x^2y^2+y^5}{(x^2+y^2)^2}\right)$, how to choose $\delta$ so that $\sqrt{x^2+y^2}<\delta\implies |f(x,y)|<0.01\,$?](https://math.stackexchange.com/q/2240630/145141)
Comment: That question does not have an answer.
Comment: Is this because when r-> 0, the function can never be less than 0.01?
Comment: Sure it can be less than 0.01, but not on every path approaching $(0,0)$.
Comment: Yea sorry, I meant that there exists a path where it can never be less than 0.01.
Comment: For example, try the path $y=x$. On that path, as $x$ approaches zero, there is a limit, but the limit is not zero.
Comment: Bottom line: As stated, the problem is wrong. Perhaps a typo.
Answer: As commenters in this question and the linked question have stated, it is impossible to solve this problem.  Here is a proof of the negation.
You are asked to show that
$$\exists \delta > 0,\forall (x,y)\in \mathbb{R}^2,\ 0 < \sqrt{x^2+y^2} < \delta \implies |f(x,y)| < 0.01$$
I will show that
$$ \forall \delta > 0,\exists (x,y)\in\mathbb{R}^2,\ 0 < \sqrt{x^2+y^2} < \delta \wedge |f(x,y)| \geq 0.01
$$
Let $\delta > 0$ be given.
Setting $y=x$ in the function and taking the limit as $x\to 0$ gives
$$
    \lim_{x\to 0} f(x,x) = \lim_{x\to 0} \frac{2x^5 - 5 x^4 + x^5}{4x^4} = - \frac{5}{4}
$$
This means there exists $\delta_1 > 0$ such that for all $x\in\mathbb{R}$,
$0 < |x| < \delta_1 \implies f(x,x) < -1$.  Set $x = y = \min\left\{\frac{\delta}{2},\frac{\delta_1}{2}\right\}$.  Then $0 < \sqrt{x^2+y^2} < \delta$ and $|x|< \delta_1$ are both satisfied.  It follows from the second inequality that $|f(x,y)| \geq 1 > 0.01$.

How to find delta, for a given epsilon?


particle effect does not appear in libgdx?

Question: EDIT
OK I found this video that explains how to use it : http://www.youtube.com/watch?v=LCLa-rgR_MA
it works with this code:
//in create
effect = new ParticleEffect();
FileHandle fileDir = Gdx.files.internal("data");
effect.load(Gdx.files.internal("data/myParticleTxtFile"), fileDir);
effect.start();

//in render
effect.draw(batch, Gdx.graphics.getDeltaTime());
batch.end();

Previous message:
I created a particle effect with the particle editor, I added the text file to the data folder. The particle constructor needs an atlas, so I created a new atlas with TexturePacker but I could not make it work.
Comment: Can you post it as an answer and mark it as solved? It could help others with the same issue.
Answer: OK I found this video that explains how to use it : http://www.youtube.com/watch?v=LCLa-rgR_MA
it works with this code:
//in create
effect = new ParticleEffect();
FileHandle fileDir = Gdx.files.internal("data");
effect.load(Gdx.files.internal("data/myParticleTxtFile"), fileDir);
effect.start();

//in render
effect.draw(batch, Gdx.graphics.getDeltaTime());
batch.end();


Angular - Dependency injection through @Input property

Question: Is it a good practice to inject 'service' dependencies in @Input properties? The service in this context is not a singleton instance managed at the root level but multiple instances of different implementations of the interface.
Consider the following example: In an Angular library, the ShapeComponent has a dependency on ShapeService (interface).
Component
@Component({
  selector: 'ex-shape',
  templateUrl: '..',
})

export class ShapeComponent {
   constructor(shapeServiceCtor: ShapeService)

   @Input shapeServiceInput: ShapeService;
}

A simple way to resolve the dependency is to set the input property as shown in the following code.
<ex-shape [shapeServiceInput]="rectangleShapeService" />
<ex-shape [shapeServiceInput]="ellipseShapeService" />
<ex-shape [shapeServiceInput]="polygonShapeService" />

Does the above approach hold good in resolving dependencies in Components?
If the input property approach is used then the services/dependencies have to the propagated to the child components in the same fashion. The downside of this approach is that the parent component will have to accept all the dependencies as input properties.
Are there any recommended approaches to inject and scope dependencies at the library level?
Answer: You're not really using Angular's dependency injection at this point, which in your case I'm not sure is good or bad.
If the ShapeComponent has no way to know what instance of the service it's using, and any time you call it you need to pass an arbitrary instance, this should be ok.
If the parent of the ShapeComponent will always pass the same instance of the service, the parent could include it in its providers array and then children ShapeComponents will use that same instance.
Angular's docs have some more detailed info on the DI Hierarchy  https://angular.io/guide/hierarchical-dependency-injection
Your call to constructor(shapeServiceCtor: ShapeService) will also lead to some confusion, as the component will have both the DI injected one, and another (or possibly the same) instance from the @Input
Comment: The constructor parameter was included to discuss the alternative approach, either the constructor or the input dependency will be followed finally. If the input property approach is used then the services have to the propagated to the child components in the same fashion.
Answer: This could work in your case:
@Component({
  selector: 'ex-shape',
  templateUrl: '..',
})
export class ShapeComponent {
   // change the type to any since any service will be comping as input
   private shapeServiceCtor: any;

   constructor(
       private injector: Injector // injector to inject incoming services
   ) {}

   // type as any
   @Input shapeServiceInput: any;

   ngOnInit() {
       // this will inject the service
       this.shapeServiceCtor = this.injector(shapeServiceInput);
   }
}

Answer: "Injecting" a service like this will not work. You will have to pass an instance of said service. Instead, try to create multiple shape components and if they share functionality, then let them extend a base component OR use a service to be shared between them.
Answer: You should set providedIn to be true for the @Injectable decorator.
Your idea is to use a singleton and singleton injections could be implemented by setting providedIn as true.
Then you don't need to use @Input decorator in depth and you can simply import the service and use it inside the components where you are gonna use.
So the format should be like this.
@Injectable({
    providedIn: true
})
export class SomeService {
 ...
}

Comment: `providedIn: true` sounds like an unsupported hack. What does it actually do? https://angular.io/api/core/Injectable
Answer: @Input and @Output are for communication, communication between one component to another. @Input  will expose our variables to the outside of the component. Dependency Injection is a different concept, In dependency injection, we inject components and build-in classes in the constructor and this will make available for us. @Input is definitely not a correct approach.
Answer: Remove the parameter from the @Injectable () decorator. It ensures that the service is not provided at the root level:
@Injectable()
export class ShapeService{

You can declare a service at a component level, and you can inject the service as normal into any child components. The child components will get the same instance as the parent.
In the ShapeComponent, you can provide the service in the @Component Decorator:
@Component({
  selector: 'ex-shape',
  templateUrl: '..',
  providers:  [ ShapeService ]
})

export class ShapeComponent {
   constructor(private shapeServiceCtor: ShapeService)

This assumes that you want a new instance of the ShapeService for each ShapeComponent.


Simulating Observations from the Prior Distribution?

Question: Can you directly simulate data from Bayesian Priors and "add them as new rows" to your existing dataset - and then fit a statistical model to this new dataset?
In the context of statistical modelling, I could see this as having two advantages:
1) Simplify computations and avoid the need of MCMC sampling
2) Better exploit real world knowledge about your variables (Bayesian Regression requires you to specify prior distributions on the model parameters (i.e. regression beta coefficients) - when in real life, you are more likely to have knowledge about the prior distributions of the actual variables, and not the model parameters).
For example, suppose you have the following data about the height, weight and age of giraffes. Suppose you are interested in creating a regression model that predicts "age" as a function of "height and weight". Suppose I have the following measurements:
     weight   height age
1  2998.958 15.26611  53
2  3002.208 18.08711  52
3  3008.171 16.70896  49
4  3002.374 17.37032  55
5  3000.658 18.04860  50
6  3002.688 17.24797  45
7  3004.923 16.45360  47
8  2987.264 16.71712  47
9  3011.332 17.76626  50
10 2983.783 18.10337  42
11 3007.167 18.18355  50
12 3007.049 18.11375  53
13 3002.656 15.49990  42
14 2986.710 16.73089  47
15 2998.286 17.12075  52

Now, suppose a giraffe expert tells me the following information that I think can be used as priors:

The average age of a giraffe is 50 years, with a "bell curve shape"
The average height of a giraffe is 16 feet, with a "bell curve shape"
The average weight of a giraffe is 2500 lbs, with a "bell curve shape"

Could I simulate data from this (e.g. suppose I assume that each of these variables has a normal distribution and (for simplicity sake) is not correlated to the other variables), and add them to the original data? For example (using the R programming language):
age = rnorm(10, 50, 1)
height = rnorm(10, 16,1)
weight = rnorm(10, 2500, 100)

bayesian_data = data.frame(age, height, weight)
bayesian_data$source = "simulated"

old_data$source = "observed"

combined_data = rbind(old_data, bayesian_data)

The new data ("combined_data") would look as follows:
      weight   height      age    source
   2998.958 15.26611 53.00000  observed
   3002.208 18.08711 52.00000  observed
   3008.171 16.70896 49.00000  observed
   3002.374 17.37032 55.00000  observed
   3000.658 18.04860 50.00000  observed
   3002.688 17.24797 45.00000  observed
   3004.923 16.45360 47.00000  observed
   2987.264 16.71712 47.00000  observed
   3011.332 17.76626 50.00000  observed
  2983.783 18.10337 42.00000  observed
  3007.167 18.18355 50.00000  observed
  3007.049 18.11375 53.00000  observed
  3002.656 15.49990 42.00000  observed
  2986.710 16.73089 47.00000  observed
  2998.286 17.12075 52.00000  observed
  2563.850 15.93615 49.55841 simulated
  2646.080 15.85238 49.71639 simulated
  2336.807 16.24114 49.35653 simulated
  2467.514 15.67480 49.67832 simulated
  2501.552 16.55515 48.07730 simulated
  2582.426 16.33497 50.51050 simulated
  2549.077 16.20062 48.55126 simulated
  2595.276 16.80354 50.72527 simulated
  2429.517 16.90839 49.48397 simulated
 2497.516 14.25892 49.33416 simulated

Then, I could directly fit a regression model to this data that would "Bayesian in Spirit":
model <- lm(age ~ height + weight, data = combined_data)

Call:
lm(formula = age ~ height + weight, data = combined_data)

Residuals:
   Min     1Q Median     3Q    Max
-7.570 -1.602  0.416  1.091  5.879

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept) 45.512105  10.789639   4.218 0.000354 ***
height       0.560421   0.742336   0.755 0.458290
weight      -0.002040   0.003024  -0.675 0.506924
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3.132 on 22 degrees of freedom
Multiple R-squared:  0.02989,   Adjusted R-squared:  -0.0583
F-statistic: 0.3389 on 2 and 22 DF,  p-value: 0.7162

My Question: Does the approach I used make sense?

I do not think what I have done is mathematically correct - I am not sure if you can just simulate data from your priors and add it to your original data.

The approach I listed would require you to assume priors on all your variables, even if you only believed that you had reasonable prior information on only some of your variables. In a traditional Bayesian setting, you can just place "uninformative priors" on variables you did not have reliable information about, and place "informative priors" on the variables that you did have reliable information about (I suppose for any given row, you could just randomly sample your existing data and re-use existing values for some variables and simulate values for the other variables).

The approach I listed partly defeats the purpose of Bayesian Modelling - my approach does not provide the "much desired" posterior distributions and credible intervals of the parameters, as is traditionally associated with Bayesian Models. Although I suppose you re-run the simulation 1000 times, create 1000 new datasets where the results of each simulation is appended to the original data - then you can fit a linear regression model to each of the 1000 datasets, and plot a histogram for the estimates of each parameter (i.e. the regression beta coefficients) ... but this will probably become computationally expensive and defeat the original purpose of this approach (i.e. the original purpose of this approach was to reduce computation time by avoiding MCMC and directly simulating from the priors).

And finally, in the above example, I had 15 observations and simulated 10 observations from the priors. But why 10? Would 11 have been a better choice - why not 8? In the traditional Bayesian setting, you are not faced with this decision.

I am highly skeptical myself if what I have done is correct (as in the reasons I have just listed) - but can someone please provide some additional comments?
Thanks!
Answer: Two problems with this approach:

In a Bayesian regression model, the parameters to be estimated are the regression coefficients, so any priors you have would be on those, not on the distributions of age, height, and weight in the population.

If you simulate data in the way you described, then the new age, height, and weight values will be uncorrelated since you used independent univariate normal draws to generate them. This would bias any resulting regression coefficient estimates toward zero.

One thing your question brings to mind is the idea of prior predictive checking, which is a way of evaluating whether your prior distributions result in reasonable beliefs about your observed data. You could do this in a manner similar to what you coded above, but you would need to specify priors on the parameters, then simulate data based on the resulting linear models. If you haven't seen it already, I would recommend Ch 4.3 from Peter Hoff's book A First Course in Bayesian Statistical Methods.
Comment: I agree that the main issue is the difficulty in simulating the correlation between the covariates. An cheap expedient would be to use bootstrap on the available covariates, but with a small sample size this has little justification.
Comment: @ gibson25 : Thank you for your answer!  Regarding the 2nd point you raised - I also thought of this. If someone were to attempt this idea, they should probably try to find a multivariate distribution between the variables to better address correlations and dependencies in the data, thus attempting to target possible biases during the simulation process. However, for the sake of simplicity for this Stackoverflow question - I simplified this problem by assuming all  3 variables are uncorrelated in the real world, and thus simulated from univariate distributions.
Comment: @ Xi'an : Thank you for your reply! Regarding "difficulty in simulating the correlation between the covariates" - perhaps MCMC samples could be taken from a multivariate distribution of the covariates?


Projection matrix orthogonalization

Question: I have a projection matrix: $P = A(A^tA)^{-1}A^t$ where A's columns are base of a vector space V.
I understand that the projection must be done on a previously orthonomalized base, but I do not understand how $Px$ does that.
How does P orthonormalize the base?
Comment: An idea: Maybe it helps if you look at A as its singular value decomposition (https://en.wikipedia.org/wiki/Singular_value_decomposition), then it might become more apparent why P is a projection. Though I haven't gone through the whole thing myself.
Comment: @dasWesen the question is not why P is a projection though, it is how does it orthonormalize the base.
Comment: The SVD does two basis changes, with respect to orthonormal bases - M = UDV* where U and V are unitary, i.e. orthonormal bases. So it "moves" via V* into the basis where it scales the basis only, then moves back into a new basis via U. But maybe I misunderstood your question. Why and in what way does a projection have to be done on an orthonormalized base? You can choose a base (changing the representation of A and P), and typically you would use an orthonormal base. (E.g. euclidean - (1, 0, ..., 0) are orthonormal).
Answer: Actually $P$ is an operator so it doesn't orthonormalize any vector.
Yet, you can choose a orthonormal basis on $V$ to express the matrix of $P$ in that basis.
Actually we like to make orthogonal projection which are projection that project a vector onto orthogonal basis.
For example :
$$ P :  f \in \mathcal{C}^0[0,1]\to \int_0^1 f(t)(1+\dfrac{1}{2}t) dt$$ an orthogonal projection from $\mathcal{C} ^0$ on $ Vect(1,\dfrac{X}{2}) $
$$ Q :  f \in  \mathcal{C}^0[0,1]\to \int_0^1 f(t)(1+t) dt$$ is a projection from $\mathcal{C} ^0$ on $ Vect(1,X) $
But not orthogonal because $(1,X)$ is not orthonormal for the scalar product $<f,g>=\int_0^1f(t)g(t)dt$

In your example you want $P$ to be orthonormal, so you have to make a Gram-Schmidt orthonomalization method on $A$ (which means the orthonormalization of the column vector of $A$ that are, as you mention here, a base of $V$.)
So let $R$  the orthonormalized matrix. $Q$ transition matrix from previous basis to $R$.
$$A=QRQ^{-1} \ \ RR^t=1 $$
$$P= QRQ^{-1}(QRQ^{-1}QR^{-1}Q^{-1})QR^{-1}Q^{-1}=Id$$
So $P$ must be the identity, that are the trvial orthogonal projection
For more precision you can look here :
Look here : https://mathworld.wolfram.com/Gram-SchmidtOrthonormalization.html  and here: https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process
Comment: "Actually we like to make orthogonal projection which are projection that project a vector onto orthogonal basis." What do you mean?
Comment: "Actually P is an operator so it doesn't orthonormalize any vector." P projects, thus it should orthonormalize at some point shouldn't it?
Comment: I mean that we can consider simple projection that aren't orthogonal projection, and so often less interesting than orthogonal one.
Comment: "I mean that we can consider simple projection" How can you project into a vector space with no orthonomalized bases?
Comment: It clearer now for you?
Comment: But $P$ is given as $P = A(A^tA)^{-1}A^t$, it must do some kind of orthonormalization to be able to give the correct result for $Px$.
Comment: I think my lecturer uses 'othogonality' as defined by the inner product $a^{t}a$ where a is a vector.
Comment: Yes so you want $AA^t=1$ for the base of $V$ you choose to be orthogonal.

Projection matrix orthogonalization


SSIS package with multiple constraints

Question: Shown below is part of an SSIS package that runs daily. My objective is to execute the task 'Get Greaterthan500 Count on  Mondays' only on Mondays. However, I want the 'Send Mail Task' to be executed on all days.
This is not working. How can I achieve this?
Comment: Brad's answer works because both nodes need to reach Send Mail in order for Send mail to work in your layout. It can never happen because your decision is binary (one way or the other) and both paths cannot reach Send Mail.
Answer: Put the fist 2 in a sequence container.
Then have the send mail outside the sequence container and the send email will always be hit

SSIS package with multiple constraints


Does the short exact sequence $0\rightarrow \mathbb{Z}_3 \rightarrow G \rightarrow \mathbb{Z}_2\oplus \mathbb{Z} \rightarrow 0$ always split?

Question: Does the short exact sequence $0\rightarrow \mathbb{Z}_3 \rightarrow G \rightarrow \mathbb{Z}_2\oplus \mathbb{Z} \rightarrow 0$ always split?
Comment: No, the sequence $0\to \Bbb Z_3\to H\to \Bbb Z_2\to 0$ does not always split (for $H$ not necessarily abelian).
Comment: @QuangHoang Why does this mean that the above sequence does not always split?
Comment: $G=H\oplus \Bbb Z$.
Comment: @QuangHoang But if $G$ were Abelian, would it always split?
Answer: In the category of abelian groups this short exact sequence always splits. This is because all SESs of the forms $0\to\Bbb{Z}_3\to A\to\Bbb{Z}_2\to0$ and $0\to\Bbb{Z}_3\to A\to\Bbb{Z}\to0$ always split. The former because $\gcd(3,2)=1$. The latter because $\Bbb{Z}$ is free, hence projective. Also the bifunctor $E(A,B)$ classifying SESs of abelian groups of the form
$0\to A\to G\to B\to0$ is additive in both $A$ and $B$.
See for example Hilton-Stammbach or any other textbook on homological algebra for the details.

In this simple case we can also dispense with the general theory.
It is easy to see that
$G$ is necessarily finitely generated, so $G\cong \Bbb{Z}^r\oplus \Bbb{Z}_{n_1}\oplus
\cdots\oplus \Bbb{Z}_{n_k}$ with $n_{i+1}\mid n_i$ for all $i$ by the structure theorem of f.g. abelian groups. Here $G$ must have a subgroup isomorphic to $\Bbb{Z}_3$, so $3\mid n_1$. Moding out a finite subgroup won't affect the free part, so $r=1$. A homomorphic image of a torsion element is necessarily torsion, so the torsion part of $G$ will necessarily be mapped into the torsion part of
$\Bbb{Z}_2\oplus\Bbb{Z}$, i.e. $\Bbb{Z}_2$. This implies that $G_{torsion}$ is of order three or six. In either case it is cyclic, so $k=1$. Let $x\in G$ be an element mapping onto $(\overline1,0)$. Then $2x$ is in the kernel and, by exactness, has to come from $\Bbb{Z}_3$. This implies that $x$ is a torsion element itself and, furthermore, $2\mid |G_{torsion}|$. Thus $G\cong \Bbb{Z}\oplus\Bbb{Z}_6.$
Shortcuts probably available at selected steps.
Answer: Let $G=S_6\oplus\mathbb{Z}$
then $\mathbb{Z}_3 < S_6$ is a subgroup index $2$ and so normal with quotent $\mathbb{Z}_2$.
Thus
$$0\rightarrow \mathbb{Z}_3\rightarrow S_6\oplus\mathbb{Z} \rightarrow \mathbb{Z}_2\oplus\mathbb{Z} \rightarrow 0$$ is exact but not split since $S_6$ is not Abelian.


Issues of saving a matrix to a csv file

Question: I am trying to save an integer matrix to the csv file. My code is listed as follows.
try
    {
      FileWriter writer = new FileWriter("test.csv");
         for(int i = 0; i < row; i++)
         {
            for (int j=0; j<(column-1); j++)
             {
                 writer.append(Matrix[i][j]);
                 writer.append(',');
             }
               writer.append(Matrix[i][j]);
               writer.append('\n');
               writer.flush();
         }
         writer.close();
      }
    catch(Exception e)
    {
      e.printStackTrace();
    }

However, the  Eclipse gives the following error message:

method append(CharSequence) in the type Writer is not
   applicable for the arguments (int)

How to solve this issue? Thanks.
Comment: Style comment - do not name instance variables (Matrix) with initial leading capital.  That is how you should be naming classes instead.
Comment: Additionally, there are CSV utilities out there to help you avoid writing this kind of code.  See ostermillerutils for instance (http://ostermiller.org/utils/CSV.html)
Answer: Change your calls to append(Matrix[i][j]) to append(String.valueOf(Matrix[i][j]) or append("" + Matrix[i][j]).  The problem (as the error message points out) is that you are attempting to append an integer, but the append method only take a CharSequence (i.e. a String).  Both of the solutions I present coerce the integer/numeric type to a String.
Answer: As @I82Much mentioned, and an alternative is to use write (for ,, to avoid the creation of string). Also, you use j outside the for loop, so you need to declare it outside as well:
int j;
for (j=0; j<(column-1); j++)
{
    writer.append(Matrix[i][j]);
    writer.append(',');
}
writer.append(Matrix[i][j]);

Answer: The other answers are good, another way to do it is use
writer.append(Integer.toString(Matrix[i][j]));

Also as @MByD said you have to declare j outside the loop if you're using it outside the loop.

Issues of saving a matrix to a csv file


Dropdown control searching method

Question: In the below form a grid contains a dropDown control which contains products that should enter on the grid, dropDown fills on the form load event, A-Z products are present in the dropDown.
See the image below:
click here to see my form and dropdown http://imageshack.com/a/img838/5697/1knn.jpg
As you can see, when I press "G" it will show product names that start with G and others also. What I want is: If I press 'G' it should show product names that start with G only.
<code>Dim adapter As New NpgsqlDataAdapter(strSql, GenConnection)
adapter.Fill(SourceDataSetProducts)
bindSourceSale.DataSource = SourceDataSetProducts
SourceDataSetProducts.PrimaryKey = New DataColumn() {SourceDataSetProducts.Columns("ProductId")}
drpDwnProducts.DataSource = Nothing
drpDwnProducts.DataSource = bindSourceSale
drpDwnProducts.DisplayMember = "ProductName"
drpDwnProducts.ColumnHeaders = True
drpDwnProducts.Width = 800
</code>
In this way, I used to fill the dropDown in form load.
Comment: http://www.dotnetheaven.com/article/combobox-with-autocomplete-textbox-in-vb.net
Comment: @NagarajS S  using C1(Component One Controls) autocompletion properties are not available for them
Comment: dear for your dropdown just make autocompet property to true and dropdown style = dropdown
Comment: @Developerzzz there is no option to enable autocomplete ([ http://imageshack.com/a/img837/5805/pwv4.jpg ]) because am using component one (C1) control
Comment: Handle the keypress for the combobox. You can take your input and do a query to fill the combobox based on that input.
Comment: @Mr CoDeXeR there is no combobox associate with that dropdown , dropdown is set for the grid ([ http://imageshack.com/a/img838/5697/1knn.jpg ])
Comment: Or do a filter on your data source.
Comment: @Mr CoDeXeR How to ??
Comment: Does it have a keypress event?
Comment: @Mr CoDeXeR  YES for both grid and dropdown
Comment: Create a dataview from the table you need, then you data source for your binding set it to this new view, then set your dropdown.data source to your binding source. Then apply a filter to this binding source;  ex: source.Filter. = "productsname like' g'" example only.
Answer: <code>  ' Get a DataView of the table contained in the dataset.
    Dim tables As DataTableCollection = set1.Tables
    Dim view1 As New DataView(tables(0))

' Create a BindingSource and set its DataSource property to
' the DataView.
Dim source1 As New BindingSource()
source1.DataSource = view1

' Set the data source for the products...
Dropdown.DataSource = source1

' The Filter string can include Boolean expressions.
source1.Filter = "products = 'whatever'"
</code>
You can use like as well...
<code> Source.Filter = "products like' %whatever%'"
</code>
This is a good start for what you need.

Dropdown control searching method