text:
Q: How to get the parent template instance (of the current template) Is there a clean way to get the parent template of the current template? Nothing is officially documented in Meteor's API.
I'm talking about the Blaze.TemplateInstance, not the context (i.e. not Template.parentData).

A: What I've been doing so far is that if I need to access the parent instance in a child template's function, I try to instead refactor this function to declare it on the parent template, and then pass it as argument to the child, who can then execute it.
As an example, let's say I want to increment a template variable on the parent template from within the child template. I could write something like this:
Template.parentTemplate.onCreated(function () {
  var parentInstance = this;
  parentInstance.count = new ReactiveVar(1);
});

Template.parentTemplate.helpers({
  incrementHandler: function () {
    var parentInstance = Template.instance();
    var count = parentInstance.count.get();

    return function () {
      var newCount = count + 1;
      parentInstance.count.set(newCount);
    };
  }
});

Then include my child template:
{{> childTemplate handler=loadMoreHandler}}

And set up my event:
Template.childTemplate.events({
  'click .increment-button': function (event, childInstance) {
    event.preventDefault();
    childInstance.data.handler();
  }
});

A: In the end, I've extended the template instances similarly with Meteor's parentData, like this:
/**
 * Get the parent template instance
 * @param {Number} [levels] How many levels to go up. Default is 1
 * @returns {Blaze.TemplateInstance}
 */

Blaze.TemplateInstance.prototype.parentTemplate = function (levels) {
    var view = this.view;
    if (typeof levels === "undefined") {
        levels = 1;
    }
    while (view) {
        if (view.name.substring(0, 9) === "Template." && !(levels--)) {
            return view.templateInstance();
        }
        view = view.parentView;
    }
};

Example usage: someTemplate.parentTemplate() to get the immediate parent

A: If you don't want to extend Blaze.TemplateInstance you can access the parent instance like this:
Template.exampleTemplate.onRendered(function () {
  const instance = this;
  const parentInstance = instance.view.parentView.templateInstance();
});

Only tested in Meteor 1.4.x

A:
Is there a clean way to get the parent template of the current
  template?

Currently, none that I know of, but this is supposed to happen sometime in the future as part of a planned "better API for designing reusable components" (this is discussed in the Meteor post 1.0 roadmap).
For the moment, here is a workaround I'm using in my projects :
// extend Blaze.View prototype to mimick jQuery's closest for views
_.extend(Blaze.View.prototype,{
    closest:function(viewName){
        var view=this;
        while(view){
            if(view.name=="Template."+viewName){
                return view;
            }
            view=view.parentView;
        }
        return null;
    }
});

// extend Blaze.TemplateInstance to expose added Blaze.View functionalities
_.extend(Blaze.TemplateInstance.prototype,{
    closestInstance:function(viewName){
        var view=this.view.closest(viewName);
        return view?view.templateInstance():null;
    }
});

Note that this is only supporting named parent templates and supposed to work in the same fashion as jQuery closest to traverse parent views nodes from a child to the top-most template (body), searching for the appropriately named template.
Once this extensions to Blaze have been registered somewhere in your client code, you can do stuff like this :
HTML
<template name="parent">
  <div style="background-color:{{backgroundColor}};">
    {{> child}}
  </div>
</template>

<template name="child">
  <button type="button">Click me to change parent color !</button>
</template>

JS
Template.parent.created=function(){
  this.backgroundColor=new ReactiveVar("green");
};

Template.parent.helpers({
  backgroundColor:function(){
    return Template.instance().backgroundColor.get();
  }
});

Template.child.events({
  "click button":function(event,template){
    var parent=template.closestInstance("parent");
    var backgroundColor=parent.backgroundColor.get();
    switch(backgroundColor){
      case "green":
        parent.backgroundColor.set("red");
        break;
      case "red":
        parent.backgroundColor.set("green");
        break;
    }
  }
});

A: You can use a package like Aldeed's template-extension
The following method is available there:
templateInstance.parent(numLevels, includeBlockHelpers)


text:
Q: find the least number whose square is of form 1_2_3_4_5_6_7_8_9_0. Where "_" could be any 1 digit number In my recent interview, the interviewer asked me to
write a Java program to find the least number whose square is of form 1_2_3_4_5_6_7_8_9_0. Where "_" could be any 1 digit number.
And I'd stuck in that.
Can anybody help me with the logic to be implemented?

A: Well, the minimum number of that format is 1020304050607080900 which has square root 1010101010.10....  And the maximum number of that format is 1929394959697989990 which has square root approx. 1389026623.11.
Start at the lower bound, and iterate through to the upper bound.  You use regex or even rudimentary string character matching, just check that the first char is 1, the 3rd char is 2, etc.
Also, I think a long would be sufficient for this.
EDIT:
I just ran this on my machine, it took around 2 minutes.  I suck at regex so I did it primitive style.
public static void main(String[] args) {
    for (long l = 1010101010; l < 1389026623; l++) {
        long squared = l * l;
        String s = Long.toString(squared);
        if (s.charAt(0) != '1') continue;
        if (s.charAt(2) != '2') continue;
        if (s.charAt(4) != '3') continue;
        if (s.charAt(6) != '4') continue;
        if (s.charAt(8) != '5') continue;
        if (s.charAt(10) != '6') continue;
        if (s.charAt(12) != '7') continue;
        if (s.charAt(14) != '8') continue;
        if (s.charAt(16) != '9') continue;
        if (s.charAt(18) != '0') continue;
        System.out.println(s);
    }
}

The result was 1929374254627488900 (this is the squared number).  Therefore, the root number is 1389019170.  Also note this is the only number I found matching the pattern, not just the minimum.

A: A simple though probably not efficient solution will be to use a BigInteger, and to iterate numbers (from lower up) until you find n such that n.multiply(n).toString() matches the pattern.
Verifying if the pattern matches can be done easily with a regex, after doing toString() on the resulting squared number.
Regex:
Matcher m = Pattern.compile(
      "1[0-9]2[0-9]3[0-9]4[0-9]5[0-9]6[0-9]7[0-9]8[0-9]9[0-9]0").matcher("");

And invoke with:
m.reset(myString);
m.matches()

the matches() will return true if and only if myString matches the pattern

EDIT:
Use optimizations suggested by @The111 to improve performance, the idea still remains - iterate and check if the result matches the pattern.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ASP.NET authorization configuration - CMS backend user can't access resources I'm running an Umbraco instance. In order to prevent unauthorized users to download media files (like pdf docs) using a direct URL like http://mysite.xy/media/4343/sometext.pdf I used a web.config file in the media folder:
<configuration>
    <system.web>
        <authorization>
    <deny users="?" />
        </authorization>
    </system.web>
</configuration>

This works perfectly for frontend users. But for users logged into the backend the pictures don't show up and pdf files refuse download. If I remove the web.config file (access for everyone) the pictures appear in the backend and pdf download is possible.
I'm using Umbraco 7.4.3. In former versions (7.1.6) the behavior was correct. As far as I know Umbraco switched forms authentication from ASP.NET web forms to OWin / OAuth.
Does anybody have an idea, what I can do to allow backend users access to media files?
MM


text:
Q: How To fetch a specific value from all children in firebase database and then add it? I have Price stored in orders as shown in the image. And all i want to do is take the price from each child. Even though the method is called as many times as the number of children in orders, the for loop didnt work. The total is coming out wrong.
What Toast displayed was addition of 53 and 25 then 25 and 15 and then 15 and 80. It should be displaying total of 25,15,80,53 instead.
UI of the layout
Firebase Database Structure
    @Override
    public void onStart() {
        super.onStart();
    mFirebaseAdapter = new FirebaseRecyclerAdapter<ShowDataItems,
  CheckoutActivity.ShowDataViewHolder>(ShowDataItems.class,
  R.layout.show_data_items_checkout, ShowDataViewHolder.class, myRef) {

        public void populateViewHolder(final ShowDataViewHolder viewHolder,
    final ShowDataItems model, final int position) {
            viewHolder.ItemName(model.getItemName());
            viewHolder.Price(model.getPrice());
            viewHolder.Image_Count(model.getItemCount());

            viewHolder.delete.setOnClickListener(new View.OnClickListener()
             {
                @Override
                public void onClick(View view) {

   myRef.child(viewHolder.ItemName(model.getItemName())).child("ItemName")
   .setValue(null);

   myRef.child(viewHolder.ItemName(model.getItemName())).child("ItemCount")
   .setValue(null);
                    myRef.child(viewHolder.ItemName(model.getItemName())).child("Price").setValue(null);

                }
            });

            //OnClick Item
            viewHolder.itemView.setOnClickListener(new
    View.OnClickListener() {

                @Override
                public void onClick(final View v) {
                    int s = position;
                    mFirebaseAdapter.getRef((s));

                }
            });

            calling++;

            for(int i = 0; i<calling; i++)
            {

                total = temp +price;
                temp = price;
                Toast.makeText(getApplicationContext(),""+ total,
    Toast.LENGTH_LONG).show();

            }
        }
    };

A: Just some logic error, here's how you should do the count. I have added the "toast shown checker" to make sure that only one toast is shown each time.
... class' variable

private Toast toast;
private int total = 0;

... inside the populateViewHolder method

total = total + price;
if (toast != null) {
    toast.cancel();
}
toast = Toast.makeText(getApplicationContext(), ""+ total, Toast.LENGTH_LONG);
toast.show();

Hope this helps :)


text:
Q: Can't import module in virtualenv I'm trying to learn flask. I have created a virtualenv and am using the hello.py example file as in here.
For reference, the contents of hello.py is as follows:
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

I can run the file and it creates a functioning web application.
So now I've created a unit test file in the same directory as hello.py and it imports hello. The code for this file is as follows:
import os
import hello
import unittest

class FlaskrTestCase(unittest.TestCase):

    def setUp(self):
        self.app = hello.app.test_client()

if __name__ == '__main__':
    unittest.main()

When I run the unit test file it attempts to execute hello.py and fails with:
ImportError: No module named flask.

What am I missing?

A: It seems you have not activated your virtualenv yet, use the source virtualenv/bin/activate command to activate.
Relevant documentation: http://docs.python-guide.org/en/latest/dev/virtualenvs/


text:
Q: Get String From Array to call method I'm trying to get a string in my call from an array. But have no luck. It's being passed to another class.
MainClass.h
#import First
@class First;

@interface MainClass : UIViewController{
NSMutableArray *listArray;
}
///////////////////
MainClass.m

    First *first = [[First alloc] init];

    listArray = [[NSMutableArray alloc]init];
        [listArray addObject:@"first"];
        [listArray addObject:@"second"];

    int Aslot = 0;
    int sumA;
float level = 5, insample = 10;

    NSString *slotA =[listArray objectAtIndex:ASlot];

           sumA = [slotA out:insample andlevels:level];

/////////
First.h
-(float)out:(float)insample andlevels:(float)level;

First.m
-(float)out:(float)insample andlevels:(float)level{

float outsample = insample + 10 * level;

return outsample;
}

I want slotA (the Class) to equal a string from the array "first" or "second", so it can call the method.
I have a table which when I select first, it sends samples and other parameters to another class where it does processing then returns back to MainClass.
sumA = [first out:insample andlevels:level];
But I'm getting an error saying that NSString may not respond to my parameters out:andlevels. Please help..

A: Edit:
If I understand correctly, you want to dynamically create an instance of a class whose name you have stored as an NSString.  You can do that this way:
int Aslot = 0;
int sumA;
float level = 5, insample = 10;

NSString *className = [listArray objectAtIndex:Aslot];
Class sampler = objc_getClass([className UTF8String]);
id instance = [[sampler alloc] init];
sumA = [instance out:insample andlevels:level];

// Do whatever you want with sumA here.

[instance release];

If you're doing this a lot, you'll probably want to either keep the instance around or store the classes in the array instead of their names, depending on exactly what you are doing.


text:
Q: Eloquent hasManyThrough Alias I have two tables like so
users
id|username|...
1 |foo
2 |bar

relationship
id|user_one|user_two
1 |1       |2
2 |2       |1

Then in my User model I have the following function
public function friends($user_id)
{
    return $this->find($user_id)->hasManyThrough('User', 'Relationship', 'user_one', 'id');
}

The error I get is
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'users'

So the question is, is there a way to alias one of the tables in the query that is created by Eloquent?


text:
Q: How to redirect on app after successfull facebook login in iOS5 There is a facebook button in my app in login screen ,when user click on this button facebook login page open in browse and after successful login application redirect and display next page . Please hep mw with example .
IOS version : 5.0
ARC project
Thank You

A: in your you  AppDelegate modify the method
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{

    NSString *urlString = [url absoluteString];

    if ([urlString hasPrefix:@"fb://xxxxxxxxxxxx"]) {
        [FBSession.activeSession handleOpenURL:url];
        returnValue = YES;
    }

    return returnValue;
}

xxx will be your facebookappid
But keep in mind that this is not triggered in IOS 6.In ios 6 the following method will be triggered.
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {

   return [FBSession.activeSession handleOpenURL:url];
}

If the state of your session changes due to login or disconnect FBsession calls the following method and you should handle your cases.
- (void)sessionStateChanged:(FBSession *)session
                  state:(FBSessionState)state
                  error:(NSError *)error {
switch (state) {
    case FBSessionStateOpen: {
        //update permissionsArrat
        [self retrieveUSerPermissions];

        if (!needstoReopenOldSession) {
            //First User information
            [self getUserInformation:nil];
        }

        NSNotification *authorizationNotification = [NSNotification notificationWithName:facebookAuthorizationNotification object:nil];
        [[NSNotificationCenter defaultCenter] postNotification:authorizationNotification];

    }
    case FBSessionStateClosed: {
        break;
    }
    case FBSessionStateClosedLoginFailed: {
        [FBSession.activeSession closeAndClearTokenInformation];
        break;
    }
    default:
        break;
}

if (error) {
    NSNotification *authorizationNotification = [NSNotification notificationWithName:faceBookErrorOccuredNotification object:nil];
    [[NSNotificationCenter defaultCenter] postNotification:authorizationNotification];
}

}

A: by the way you guys can visit my reply here Native iOS Facebook SSO won't return to app
In my application i had to implement facebook and googleplus both and finally I made it successfully. I dont think facebook developer app portal needs any edit rather than getting appid. I made three apps with facebook login, one of them does not have iOS Native App setting in facebook developer app but that app's login part is also running well.

A: Use this official tutorial and you will be OK. See the 2-d point for your problem as well.


text:
Q: Caching the java script by browser I'm wandering how does browser caches the javascript files.
I have utility.js and I use it on multiple pages.
I know that when I go to www.some_host/page1.html the utility.js is cached for that request.
What happens if I go to different page  www.some_host/page2.html, utility.js is requested again from server or take it from browser cache?

A: Everything is cached based on its own URI. It doesn't matter what caused the browser to load it (unless you have something like Vary: referer in the headers, which I've never seen)

A: The browser normally follows the caching rules employed for the other resources (pages, images etc...)


text:
Q: Copy constructor and cascaded function calls I ran this example:
#include <cstdlib>
#include <iostream>
#include <istream>
#include <ostream>
using namespace std;
class Weight {
    int k;
    char a[100];
public:
    Weight(int kilos = 0)
        :k(kilos) {}
    Weight(const Weight& w)
        : k(w.k) {
        for(int i = 0; i < 100; ++i) this->a[i] = 'a';
        cout << "WCC\n";
    }
    friend Weight operator+(const Weight& a, const Weight& b);
    Weight& operator=(const Weight & w) {
        this->k = w.k;
        return *this;
    }
    friend ostream& operator<<(ostream&, const Weight&);
};
Weight operator+(const Weight& a, const Weight& b) {
    cout << "FP\n";
    int newkg = a.k + b.k;
    return Weight(newkg);
}
ostream& operator<<(ostream& out, const Weight& w) {
    out << w.k << " KGs";
    return out;
}
class Container{
    Weight w;
    static Weight totalW;
    static int count;
public:
    Container(){++count;}
    ~Container(){cout << "CD\n";}
    Container& add(Weight weight) {
        this->w = this->w + weight;
        totalW = totalW + weight;
        cout << "Just added a new item that weighs " << weight << endl;
        return *this;
    }
    static void print() {
        cout << "We have " << count << " Containers with a total weight "
                << totalW << endl;
    }
    friend ostream& operator<<(ostream&, const Container&);
};
Weight Container::totalW;
int Container::count = 0;
ostream& operator<<(ostream& out, const Container& c){
    out << "This container's " << c.w;
    return out;
}
int main(int argc, char** argv) {
    Container c1;

    Weight *w1 = new Weight(1);
    Weight *w2 = new Weight(2);
    Weight *w3 = new Weight(3);

    cout << "Adding items to container...\n";
    c1.add(*w1).add(*w2).add(*w3);

    cout << c1 << endl;

    Container::print();
    return 0;
}

And I got this output:
Adding items to container...
WCC
WCC
WCC
FP
FP
Just added a new item that weighs 1 KGs
FP
FP
Just added a new item that weighs 2 KGs
FP
FP
Just added a new item that weighs 3 KGs
This container's 6 KGs
We have 1 Containers with a total weight 6 KGs
CD

You can see that the copy constructor for the Weight class was called three times (Output lines 2-4) before any of the cascaded functions was called. I always thought that the left most function call will be performed before any copy constructor is called up to setup the second function call.
To be more specific, I thought this what should have happened:
WCC -> c1.add(*w1) -> WCC -> .add(*w2) -> WCC -> .add(*w3).
I thought this was necessary because the function argument will be stored in the function's stack frame. So, a stack frame needs to be setup before the copy constructor for the argument is called. Apparently, I am mistaken.
This makes me think that function arguments are store somewhere else other than the stack frame. So, where?
Do not mind the horrific coding style. This, obviously, is not meant to be in production code.

A: I think this is a basic compiler optimization. Since there's no requirement when a function's parameters should be initialized from supplied arguments, a compiler can do necessary optimization by rearranging them. That's why you see the copy constructors called all at once.


text:
Q: Google Calendar Push Notification Channel subscription Creation I have to create calendar push notification but didn't undersatnd how to create channel subscription ?
 private void perormWatch(Calendar service, String user) throws Exception {
            Channel content = new Channel();
            content.setId("abcd@gmail.com");
            content.setType("web_hook");
            content.setAddress("http://localhost:8888/calendarNotiication");
            com.google.api.services.calendar.Calendar.CalendarList.Watch cal = service.calendarList().watch(content);

        }

A: I assume that you want to set up a channel with CalendarList.watch(). To do so you must satisfy three minimum requirements:

*

*An id that uniquely identifies this new channel within your project.

*The type property set on web_hook

*An address over HTTPS where you want to receive the notifications.

By keeping that in mind, you only have to update your script to match the requirements. First of all the address is set to an invalid URL in the example. It must start with https, not http. Please be aware that only valid SSL certificates are acceptable (i.e. not selfsigned certificates, revoked or badly formed). Also please check that the id is truly unique within your project. Those small modifications should suffice in the example code, but feel free to update your question and leave a comment if you need further solutions.


text:
Q: how to save the values of two forms with one submit button in php hi i have a three forms and one submit button which is located outside of all three forms and i want to save the values of all the three forms using php into mysql database can anyone help  me in showing that how can it be done i am using jquery to submit the form values
here is my jquery
  <script>
    $(document).ready(function() {
        $("#submit").click(function(event) {
              alert('send 1st form');
            $.post($("#form1").attr("action"), $("#form1").serialize(),
              function() {
              alert('send 2nd form');
            $.post($("#form2").attr("action"), $("#form2").serialize(),
              function() {
              alert('send 3th form');
                $.post($("#form3").attr("action"), $("#form3").serialize(),
                  function() {
                    alert('Both forms submitted');
                  });
              });
          });
          event.preventDefault();
      });

    });
    </script>

as i posted a query before this helped me in submitting the forms and now i want to save the values into my database
her is my php code
if(isset($_POST["submit"])){

    $gen1 = mysql_query("SELECT MAX(accode) AS maxcode FROM quotmain LIMIT 0,1 ") or die(mysql_error());
    if (mysql_num_rows($gen1) > 0) {
        $vvouch = mysql_fetch_assoc($gen1);
        $qvouch = $vvouch["maxcode"] + 1;
    } else{
        $qvouch = '1';
    }

    $a = 1;
    $vouchdt  = mydt($_POST["vouchdt"]);
    $name     = $_POST["cmbparty"];
    $refno    = $_POST["refno"];
    $attn     = $_POST["attn"];
    $subj     = $_POST["subject"];
    $msg      = $_POST["messsage"];
    $rem      = $_POST["rem"];
    $count    = $_POST["items"];
    $h        = $_POST["h"];
    $status   = $_POST["cmbstatus"];

    mysql_query("DELETE FROM quotdtl WHERE vouchno='$qvouch'") or die(mysql_error());

    for ($i = 1; $i <= $count; $i++) {
        $ord     = $_POST['ord_' . $i];
        $srno    = $_POST['srno_' . $i];
        $descrip = $_POST['descrip_' . $i];
        $unit    = $_POST['unit_' . $i];
        $rate = $_POST['rate_' . $i];

        mysql_query("INSERT INTO `quotdtl`(vouchno, orderby, srno, `descrip`, unit, rate)
                            VALUES('$qvouch', '$ord', '$srno', '$descrip', '$unit', '$rate')") or die(mysql_error());
    }

     mysql_query("DELETE FROM quotnotes WHERE vouchno='$qvouch'") or die(mysql_error());

    for ($i = 1; $i <= $h; $i++) {
        $notes = $_POST['notes' . $i];

        mysql_query("INSERT INTO `quotnotes`(vouchno, `notes`)
                            VALUES('$qvouch', '$notes')") or die(mysql_error());
    }

    if ($addflag == 1) {
        mysql_query("INSERT INTO `quotmain`(vouchno, `vouchdt`, `name`, refno, `attn`, `subject`, `message`, `rem1`, `status`, `username`)
                            VALUES($qvouch, '$vouchdt', '$name', '$refno', '$attn', '$subj', '$msg', '$rem', '$status','$_SESSION[username]')") or die(mysql_error());

        insmess();
        header("refresh: 1; quotation.php?mode=true");
     } else {
            $mvouch = $_POST["vouch"];
             mysql_query("UPDATE `quotmain` SET `vouchdt`='$vouchdt', `name`='$name', refno='$refno', `attn`='$attn', `subject`='$subj',
                                 `message`='$msg', `rem1`='$rem', `username`='$_SESSION[username]' WHERE vouchno = '$mvouch' ") or die(mysql_error());
             updmess();
             header("refresh: 1; menu.php?action=quotation");
     }

}

A: Short answer: you cant. Your browser will always only send one form.
Long answer: You can create an equivalent for each input element of one form in the other form () and, onSubmit, set the value of the hidden fields to those of the non-hidden ones:
onsumbmit="$('#foobar_hidden').val( $('#foobar').val() ); return 1";

A: Try changing the HTML for your submit button to be
<button type="button" id="submit">Submit</button>

This will stop your browser from trying to send a single form when the submit button is hit, and will only do what you put in the JavaScript.


text:
Q: What disqualifies an expression from being linear? I'm taking some advanced math classes at my high-school, and I have some questions.
A helpful answer would include a definition. Examples of a concept or definition given (no matter how simple; please ELI5).
This question I have historically phrased: "What makes a linear equation linear?"
I get that an equation that graphs out to be a line is linear, but it seems there is more to the meaning of "linear."
Additionally, why is linear algebra called linear algebra? What's linear about it?

A: Perhaps the core idea of a function $f$ being linear* is the idea that if you change the input to $f$ in some specified way, it will affect the output the correspondingly. That is to say, in one dimension, a function $f(x)$ is linear if we can always say that $f(x+1)$ is $m$ bigger than $f(x)$ for some $m$ - that is, moving the input one value to the right corresponds to moving the output $m$ upwards. It is apparent that any function satisfying this is of the form
$$f(x)=mx+b$$
and that the description of "a move of $1$ to the left is a move $m$ up" corresponds to a geometric notion of a line. The convenience of this is that we can easily get from there to determining that, to increase $f$ by $1$, we must increase $x$ by $\frac{1}m$.
We can contrast this to functions like
$$f(x)=x^2$$
which do not behave so neatly - if we start with an input of $0$, then increasing it by $1$ yields a value $1$ greater - but increasing it by one again increases the value by $3$. This makes most operations with such a function harder than with linear functions - we can't so easily predict long term behavior based on a small sample, since the function might curve sharply or do other unexpected things.
In multiple dimensions, we end up finding functions of the form
$$f(x,y)=ax+by+c$$
where, for instance, increasing $x$ by 1 and $y$ by 1 increases $f$ by $a+b$ or increasing $y$ by $2$ increases $f$ by $2b$ - that is, if we pick any direction to move the input vector $(x,y)$, we still have the same "niceness" condition as before - that the change in $f$ will be constant, no matter what value we start at. We can, as before, easily predict how far we have to go in a given direction in order to elicit a given change in $f$ We could, more generally, formalize this notion as:

A linear function in one dimension is one of the form $mx+b$ - i.e. one whose graph is a line. In more dimensions, it is one which appears linear if viewed traveling on a single line; i.e. its restriction to a line in its domain is linear.

and it happens that these are exactly the functions of the form
$$f(x,y,\ldots,z)=ax+by+\ldots + cz + d$$
which tend to be very easy to work with.
Now, as for what this has to do with linear algebra. At an abstract level, linear algebra studies the concept of vector space - which, essentially, is a notion in which we can define two notations:

*

*We can add vectors together in a sensible way.

*We can scale vectors by a constant factor.
Which, essentially, is our way of defining a Euclidean (intuitively, "flat") space. A linear function, in this context, is one which preserves the above operations - so adding a given vector has the same effect regardless of basepoint and adding a multiple of a vector scales the effect of adding the vector. In particular, a linear function is defined as a function $f$ satisfying:
$$f(x+y)=f(x)+f(y)$$
$$f(\alpha x)=\alpha f(x).$$
It is worth noting that this notion of "linear" is a little stronger than the one used in the paragraphs before (which would be called "affine" functions) - the axioms imply that $f$ preserves the zero vector - i.e. $f(0)=0$, which is not true of the above. So a linear function actually starts to look like $f(x)=mx$ under this definition.
At some level, linear maps are the primary object of study in linear algebra - they define precisely what structure matters and what does not. In some sense, a linear map $f$ is one such that, if a set is flat, so is its image under $f$. This may all seem somewhat abstract, but it turns out that, in finitely many dimensions, matrices exactly correspond to linear maps - multiplying a matrix by a vector represents applying a linear function to that vector. Multiplying two matrices represents composing two linear functions. And, at the end of the day, for your intuition about the word "linear": Applying a matrix to a line (represented as a set of vectors) yields another line.

A: The idea of linearity is that the structure is conserved with the addition, and the multiplication by a scalar
About linear algebra :
If you have two vector spaces $E,F$ over a field $\mathbb K$, a function $f:E\to F$ is linear if $\forall x,y \in E, \forall a,b \in\mathbb K$
$$f(ax+by) = af(x)+bf(y)$$
Linear algebra is the study of such functions
About linear equation :
An equation is said to be linear if $\forall x,y \in E$ solutions and $a,b\in \mathbb K$, $ax+by$ is also a solution

A: There is a small cultural gap here: mathematicians don't usually talk much about "linear equations". However, if you pressed me to give you a definition, I would say that a linear equation is an equation of the form $f(x_1,x_2,\dots, x_n)=c$, where $f$ is a linear function.

There is also a large cultural gap here.
As Meelo mentions, there are two conflicting notions of a "linear function". Some look like
$$f(x_1,x_2,\dots, x_n) = a_1x_1+a_2x_2+\cdots+a_nx_n + b$$
and some look like this but without the $b$. This is simply an unfortunate choice that someone made at some point regarding the second definition: the first function has a graph which looks like a generic line (when $n=1$; vertical lines not included), and the second function is what most mathematicians mean when they say a function is "linear".
Both answers explain this latter notion of linear: it is a bit stronger (i.e. it is harder for a function to be this kind of linear than the other kind). Meelo also mentions in passing that mathematicians usually refer to the first kind of "linear" by the name affine. Unfortunately, this means that "an equation that graphs out to a line" is not given by a linear function (unless the line passes through the origin), but is a linear equation (as I defined it above). To make matters worse, a "linear equation", as I described above, looks a lot more affine than linear.
This may all seem hopelessly muddled and confusing to you; that's because it is. The two meanings of the word developed at different times and places, and the concepts became too useful in their context for the word to be replaced in either context. So we're stuck with it. This is really only a problem, though, at about your time in your math education. Give it a few more years, and you, too, will feel that faint annoyance anytime someone tries to tell you that $f(x)=x+3$ is "linear". For a mathematician, a function is not linear unless (in particular)
$$f(a+b)=f(a)+f(b),$$
and it is not true that $(a+b+3) = (a+3)+(b+3)$, since the right-hand side is $3$ bigger than the left-hand side.

However, you asked another question which I think is important: What's linear about linear algebra? The other two answers talk about this obliquely. The short answer is that linear algebra is the study of linear functions. But if you really want to know what's linear about linear algebra, it might help to see some examples of what's not linear about nonlinear algebra. This sort of algebra is just called algebra by mathematicians, although in university classes they usually append some adjective like "abstract" or "modern" to differentiate you from the remedial students :)
The answer to "what's nonlinear about algebra" is "approximately everything". Here is the simplest example of nonlinearity: you may have a nonlinear function; i.e. something like
$$f(x,y)=-x^2+y.$$
This isn't a linear function. But it's still defined on a "linear space", a "flat" space. So we can ramp up the nonlinearity by saying that maybe our numbers don't come in a nice number line any more, so not like $\Bbb R$ but like $\Bbb C$.
But $\Bbb C$ is a lot like $\Bbb R^2$, which is flat, so maybe we could get even less linear: going to $\Bbb Z$ would work: the numbers are back to being ordered, but they're now too "far apart" to be linear.
Okay, but this is still pretty linear, because we still can multiply a number by another one to "move it a long the line", so let's remove multiplication: there's only addition. It's harder to explain a natural setting for this, although they show up all over the place in higher math.
So now even the definition of a linear function that we gave before doesn't make sense, because we need multiplication: $a_1x_1+\cdots$.
But wait, we can make the space even less linear: who says that $a+b=b+a$? This is called commutativity, and there are very natural ways to define "addition" where this is no longer true. This "addition" isn't anything like the addition we're used to, of course. We still call it addition because it's a rule for taking two numbers and getting out a new number, but the rule is less linear than ordinary addition.
Now we could still define linearity to be something like $x_1+x_2+\cdots+x_n$ (note there are no multiplications happening here, so we're safe), but does that mean that $x_2+x_1$ isn't linear, just because the variables show up in the wrong order?

After removing all this structure, what we're left with is the notion of what's called a group, which is still more structured than a "set", because we at least have this notion of addition, however alien it may be. In an [abstract] algebra course, groups are usually the first object that you study. In our description above we spent a lot of time thinking about the numbers and the operations, but you could do a parallel "loss of structure" story for the linear functions, and what you'd be left with (if you start at the right place) is an object we call a homomorphism; these are the next objects that you study.
After learning about them for a long time you learn something about the intermediate stages of the construction above: rings and fields. And once you have a field, you are finally in the position to put the linearity "on top" of it.
So it seems like groups are very far removed from linearity. But in fact, linear spaces are just a very special type of group, and linear functions are just a very special type of homomorphism. From this vantage point, linear algebra is exactly what it sounds like: the section of [abstract] algebra that deals with linearity.


text:
Q: Scroll dialog body but not the page below it I have a dialog(with scrollable content body) on top of a page that's also scrollable. Now I want that when I try to scroll, from inside the dialog using mouse wheel, only the dialog body should scroll and not the page below it.
How do I do that ?

A: You could try wrapping all your content into a block with overflow: auto and set the overflow property of the window to hidden.
See example here.
I don't think you can prevent the window from scrolling otherwise. See similar question: prevent Scroll "bubbling" from element to window.
Another answer suggests you can prevent the mouse-wheel event's default effect: Prevent scrolling of parent element?.  But it's not ideal as scrolling also occurs upon pressing keys, selecting text and so on.


text:
Q: Inspect Column under the Inspect tab fixated on json document root I am working on transforming all json files under a folder. This is just a learning exercise for me regarding basic ADF.
I created a pipeline, added a data flow to it and in the data flow, I added a folder in Azure Data Lake as a dataset. In the source options, I am using the wildcard path to choose only the json files within the folder(Kept the file name argument in source empty for this to work). When I did a Data Preview, I saw the json properly with the elements.
Then I added a select transformation from the Data source. Nothing special but to just pick out the elements in the json as columns. But here I am facing issue.
This is my select settings page:

We can clearly see that I chose one string within the complex object(Location is the head object and country is the string within it). However, when I see the Inspect tab, it considers the Country as complex object by considering the input column as Location. This is the inspect page:

Why I am seeing this as a complex object in Inspect whereas the select option clearly says Country is a string in the settings page? What is it I am doing wrong or how to correct this out?

A: Since you files are nested JSON(Location is the head object and country is the string within it), The source Projection/Inspect also should be a complex column:

Off course the output of the Select is complex type column.

HTH.


text:
Q: Some quasi differential equations This question is inspired by the concept of "Differential Inclusion".
The ring of entire holomorphic functions  is denoted by $Hol(\mathbb{C})$.
Is there a complete classification of all $f\in Hol(\mathbb{C})$ such that the $Hol(\mathbb{C})$-module generated by $\{f,f',f'',\ldots,f^{(n)},\ldots\}$ would be equal to the whole ring $Hol(\mathbb{C})$?
Is there a complete classification of all $f\in Hol (\mathbb{C})$ such that the $\mathbb{C}$_ module (or $Hol (\mathbb{C})$_ module generated by $\{f^{(n)}, f^{(n+1)}, \ldots\}$ is independent of $n$?


text:
Q: concat 2 list in angular / js I have two "lists".
The first, array that contains only codes, and looks like this:
[10, 50, 75, 88]

The seconds, list that contains all codes + means that possible, and looks like this:
[
  {
    code: 10,
    name: 'example 10'
  },
  {
    code: 50,
    name: 'example 50'
  },
  {
    code: 60,
    name: 'example 60'
  },
  {
    code: 66,
    name: 'example 66'
  },
  {
    code: 75,
    name: 'example 75'
  },
  {
    code: 88,
    name: 'example 88'
  }
]

I would like to attach the interpretation from the second list, for each item of the first array.
For example, the result should be:
[
  {
    code: 10,
    name: 'example 10'
  },
  {
    code: 50,
    name: 'example 50'
  },
  {
    code: 75,
    name: 'example 75'
  },
  {
    code: 88,
    name: 'example 88'
  }
]

or:
['10- examle 10', '50 - example 50', '75 - example 75', '88 - example 88']

I prefer the first version but also the second version good enough...
how can i do it?

A: If you want, for every item in the input list, to find the name corresponding to the matching code, I would suggest converting the spec/mapping array into a code: name object.
For example using .map and .reduce array methods (check the links for polyfills if you need to support IE8-):

var list = [10, 50, 75, 88]
var spec = [{"code":10,"name":"example 10"},{"code":50,"name":"example 50"},{"code":60,"name":"example 60"},{"code":66,"name":"example 66"},{"code":75,"name":"example 75"},{"code":88,"name":"example 88"}]

// convert spec to {"10":"example 10", ...}
var spec_obj = spec.reduce(function(previous, current) {
  previous[current.code] = current.name
  return previous
}, {})

var annotated = list.map(function(item) {
  return item + ' - ' + spec_obj[item]
})

console.log(annotated)


text:
Q: If I change the default port number (3306) of MySQL during installation, then will it cause any problem? I need to use MySQL Community Edition 8.0CE and XAMPP both of them. But XAMPP can't start the MySQL service, it's showing error; because XAMPP use the same port (3306) for MySQL, which port is using by MySQL Workbench.
That is the error, which is showing in XAMPP:-

01:45:09 AM  [mysql]  Problem detected! 01:45:09 AM  [mysql]  Port
3306 in use by "Unable to open process"! 01:45:09 AM  [mysql]     MySQL
WILL NOT start without the configured ports free! 01:45:09 AM  [mysql]
You need to uninstall/disable/reconfigure the blocking application
01:45:09 AM  [mysql]  or reconfigure MySQL and the Control Panel to
listen on a different port 01:45:09 AM  [mysql]   Attempting to start
MySQL app... 01:45:09 AM  [mysql]     Status change detected: running
01:45:29 AM  [mysql]  Status change detected: stopped 01:45:29 AM
[mysql]   Error: MySQL shutdown unexpectedly. 01:45:29 AM  [mysql]
This may be due to a blocked port, missing dependencies,  01:45:29 AM
[mysql]   improper privileges, a crash, or a shutdown by another
method. 01:45:29 AM  [mysql]  Press the Logs button to view error logs
and check 01:45:29 AM  [mysql]    the Windows Event Viewer for more
clues 01:45:29 AM  [mysql]    If you need more help, copy and post this
01:45:29 AM  [mysql]  entire log window on the forums

So I want to reinstall MySQL Community Server with different port number. will it cause any problem? what other port number should I use?

A: You can definitely change the port without issue, but it's probably best to choose a port between 1024-49151 and avoid registered ports to prevent port conflicts.
Also note that many MySQL client libraries and programs will assume port 3306 but should always provide a way of specifying your own port.


text:
Q: How to chain commands that are not fully completed I have 5 worker servers on AWS that I have to deploy code to everyday usually by just doing this
eb deploy production-cron
eb deploy production-payments

etc..
the output for the full process is like so:
➜  backend git:(master) eb deploy production-payments
Creating application version archive "app-8726-190425_144820".
Uploading: [##################################################] 100% Done...
-- Events -- (safe to Ctrl+C) Use "eb abort" to cancel the command.
2019-04-25 06:48:34    INFO    Environment update is starting.
2019-04-25 06:49:16    INFO    Deploying new version to instance(s).
2019-04-25 06:49:53    INFO    Successfully loaded 16 scheduled tasks from cron.yaml.
2019-04-25 06:50:17    INFO    New application version was deployed to running EC2 instances.
2019-04-25 06:50:17    INFO    Environment update completed successfully.

Alert: An update to the EB CLI is available. Run "pip install --upgrade awsebcli" to get the latest version.

I know i can chain commands like eb deploy production-cron && eb deploy production-payments
but this will require me to wait for the first command to fully finish
Basically I want to be able to chain these commands then whenever
-- Events -- (safe to Ctrl+C) Use "eb abort" to cancel the command.
pops up I want to ctrl+c and start the next deployment.
If someone knows how to deploy to multiple environments with aws eb command that is even better

A: Perhaps using a terminal multiplexer like tmux?
tmux split-window 'exec eb deploy production-cron'
tmux split-window 'exec eb deploy production-payments'

That starts the command in a separate window, and once done, it cleans up. Or maybe exec is sufficient for you. Didn't quite understand your Ctrl+C interaction.


text:
Q: Have any Hogwarts students been killed by their house animal? Have any Hogwarts students been killed by their house animal?
For example, a Hufflepuff goes walking in the forest, and gets killed by a badger.

A: Yes, although probably not while they are still a student.
Severus Snape was killed by a snake, and he was a Slytherin student.  The murder is described in Deathly Hallows chapter 32.  J. K. Rowling claims that Snape was a Slytherin in the FAQ on her old website.

If a teacher is head of a house, can we assume that they were sorted into those houses when they were students at Hogwarts? Is that also true for the house ghosts? So was Snape a Slytherin?
Yes, if the teacher is Head of House you can indeed assume that they were pupils within that house. So Snape was very definitely a Slytherin and yes, the same is true of the house ghosts.


text:
Q: Android Studio 3.1.2 loads wrong project I have migrated my 2.3 settings to 3.1.2, and for testing I have opened a smaller project of mine, "proj2", in Android Studio 3.1.2. Structure of my projects:
AndroidDir/
  proj1/
    app
    lib
  proj2
    app

In proj2, I refer to proj1 lib, an Android library, with proj2/settings.gradle:
include ':lib', ':app'
project(':lib').projectDir = new File(settingsDir, '../proj1/lib')

In 2.3 this worked without any problems, and I could edit my lib code in both proj1 and proj2.
In 3.1.2, proj2 is treated as if I had loaded proj1, while I have opened the proj1 path. Android Studio shows the path of proj2 in the title bar, but the project overview shows all modules of proj1. And it tries to build proj1 instead of proj2. Restarting does not help.

A: Remove the proj2/.idea directory, then, in Android Studio, choose "File -> Invalide Caches / Restart..."

A: I am having this problem as well on Android Studio 3.4 and 3.5 canary 13.
More specifically, when I try to share gradle modules between different projects using the .projectDir directive in settings.gradle as described above, any attempt to load a second project that shares that gradle module will fail.
My current workaround is to use Git to load the shared gradle module into a different folder so that each project winds up with its own copy of that shared Gradle module like so:
Project A:
include ':lib', ':app'
project(':lib').projectDir = new File("./path/to/proj1/lib")

Project B:
include ':lib', ':app'
project(':lib').projectDir = new File( "../different/path/to/copy/of/proj1/lib")

Yes, this workaround brings with it its own set of problems like having to constantly sync the 2 folders, so please,
Please upvote this issue here to give it more priority.


text:
Q: iPhone Twitter app style Searchbar animation? I'd like to use the Twitter iPhone app style searchbar animation. When you click on the searchbar the navigation bar is hidden and the searchbar moves up to the top of the screen with keyboard popping up. I can do the Navigation bar hidden animation thing using this...
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    return  YES;
}

I want to move the searchBar upwards to the area vacated by the hidden navigationBar. I'm guessing its by some CAAnimation or something like that.

A: The UISearchBarController implements it by default. Should have figured it out though ;)


text:
Q: What are these wires on single-sided PCBs? I have a few questions about this PCB, namely the wires across the visible side:

*

*I am new to electronics. Would these wires be considered a "trace", "jump", a "via", or something else entirely?

*How would this be illustrated on a schematic to indicate that it is an actual wire and not part of the etching?

*If one were to purchase this kind of solid wire, what would its gauge be, its material, and how would I search for it so that I exclude results with shielding?

*Are there any issues with running wires like this without shielding? Such as electrical interference.
Other questions, not necessary for a complete answer:

*

*Unless I am mistaken, these do not appear to be hand-made due do their exactness and how straight they are. How does a machine place these? Or are they pre-bent, placed, and then sent through a wave solder machine?

*When would this method still used today? Or is it something that is an artifact of single-layer boards where one would otherwise use a through-hole via and traces on the other side?

A: Yes, they are just by-pass wires to cross over one or more tracks of the printed layer. Yes, the are still used in simple, not very dense, and cheap circuits.

A:
Would these wires be considered a "trace", "jump", a "via", or something else entirely?

Usually jumper wires or wire links.

How would this be illustrated on a schematic to indicate that it is an actual wire and not part of the etching?

They would not normally be shown on a schematic because they don't affect circuit operation and the use of the links is decided by the person who does the PCB layout. If, for some reason, they have to be shown on the schematic a 0 Ω resistor could be used.

If one were to purchase this kind of solid wire, what would its gauge be, its material, and how would I search for it so that I exclude results with shielding?

Gauge could be determined by PCB drill size for standardisation, bending equipment capability, current handling capacity, etc. Plated copper would be the normal choice for good conductivity and ability to solder.

Are there any issues with running wires like this without shielding? Such as electrical interference.

No. They're used here because the board is single sided. All the traces are unshielded.

Unless I am mistaken, these do not appear to be hand-made due do their exactness and how straight they are. How does a machine place these? Or are they pre-bent, placed, and then sent through a wave solder machine?

Given the few and odd components this board is most likely to be hand assembled.

Figure 1. An axial-lead component former would probably do the job. Source: OLAMEF USA.

When would this method still used today? Or is it something that is an artifact of single-layer boards where one would otherwise use a through-hole via and traces on the other side?

Yes, definitely, maybe, no. It depends. If it solves a particular routing problem, avoids an extra layer, etc., then why not.

Figure 2. Vishay make jumper wire taped in ammo fashion for ease of use in automatic insertion equipment. See Vishay WIRE0580000000A500 datasheet.


text:
Q: How can I run this batch file? This is the batch file:
OSQL -S 127.0.0.1 -U sa -P password
RESTORE DATABASE DATA FROM DISK = C:\backup\data.dat
GO
EXIT

But after I run the OSQL -S 127.0.0.1 -U sa -P password, the command prompt starts with the line:
1>

After that, the batch cmd can't run. How can I fix this problem?

A: after reading 'Running the osql Utility' i would use
% osql -S 127.0.0.1 -U sa -P password -i myscript.sql

and put
RESTORE DATABASE DATA FROM DISK = C:\backup\data.dat
GO
EXIT

into a file named myscript.sql


text:
Q: Send Confirmation email to the USer Who Filled a Form This is My HTML Form
 <form method="post" name="myemailform" action="form-to-email.php">

    Enter Name:

    <input type="text" name="name">

    Enter Email Address:

    <input type="text" name="email">

    Enter Message:

    <textarea name="message"></textarea>

<input type="submit" name='submit' value="submit">
 </form>

And this is PHP Mailing code which Grabs the data when user clicks submit
<?php
if(!isset($_POST['submit']))
{

echo "error; you need to submit the form!";
}
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];

//Validate first
if(empty($name)||empty($visitor_email))
{
echo "Name and email are mandatory!";
exit;
}
$email_from = 'tom@amazing-designs.com';//<== update the email address
$email_subject = "New Form submission";
$email_body = "You have received a new message from the user $name.\n".
 "Here is the message:\n $message".

$to = "khan.koder@gmail.com";//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";

mail($to,$email_subject,$email_body,$headers);

//done. redirect to thank-you page.

header('Location: thank-you.html');

?>

It shows no error but just land on the page thank-you.html I checked my email account but no mail recieved
Please help whats wrong

A: You can achieve it as follow:
1) create an activated field in database (default to false).
2) Upon registration, the email is sent
3) Populate a link in the email, to include...
a) user unique identifier
b) activation to active

so it would look something like this potentially
[code]
Welcome username_. Thanks for registering, please click on the link below to activate your account
domain.com/register.php?uid=100&activate=1
4) Your registration script attempt to grab the user by the id.
5) Update the activated field to true.
And there u have a new and active user.
May it will give you an idea.


text:
Q: Is "Either of the two" used correctly? "She would cry at the thought of it, sometimes scream about it, either of the two bore no fruit."
I know we can use, "neither of the two helped" but I wanted a different style.

A: It's not incorrect, but redundant. Either means one or the other so it would be more polished, but still somewhat stilted, saying:

either bore no fruit.

Or if you want it more succinctly, using neither:

neither bore fruit.

But in keeping with the flow of your sentence, much rather:

neither of which bore fruit.


text:
Q: State of the Grails datasources plugin I am trying to get the multiple datasources plugin running for an application I'm working on. It seems (to me) that one of the upgrades to grails has broken the plugin's functionality. I'm working with an up to date installation 1.3.7 and trying to use the example app that is posted . I've tried everything under the sun to get the functionality in the example app to work, but nothing does.
To do some further testing I downgraded my grails env to 1.0.3, the version that the demo application was written in.  When run with this version, everything works fine; I can connect to all three datasources without fail.
My question is: Is anyone out there able to use the plugin successfully under Grails 1.3.7, and, does anyone know if this is still an active project? Or, is the another way to approach connecting to multiple datasources?
Thanks in advance,
Donald

A: It appears the Datasources plugin is receiving some renewed attention.
From This Week in Grails (2011-22) - "Grails 1.4 development is going well. ... I've added support for multiple datasources to core (from the Datasources plugin) and am working on adding two-phase commit (XA/JTA) for JDBC and JMS."

I successfully integrated the Datasources plugin into a new Grails 1.3.7 project.  I chose to combine the configuration with the primary datasource to make it easier to maintain.  Here are the steps I followed:
Reference the plugin using plugin dependency resolution in conf/BuildConfig.groovy
grails.project.dependency.resolution = {
    plugins {
        runtime ':datasources:0.5'
    }
}

Create an additional datasource in conf/Datasources.groovy
import org.codehaus.groovy.grails.commons.ConfigurationHolder

datasources = {
    datasource(name: 'DS2') {
        domainClasses([domain.Object])
        if (ConfigurationHolder.config.DS2.dataSource.readOnly) readOnly(ConfigurationHolder.config.DS2.dataSource.readOnly)
        driverClassName(ConfigurationHolder.config.DS2.dataSource.driverClassName)
        url(ConfigurationHolder.config.DS2.dataSource.url)
        if (ConfigurationHolder.config.DS2.dataSource.username) username(ConfigurationHolder.config.DS2.dataSource.username)
        if (ConfigurationHolder.config.DS2.dataSource.password) password(ConfigurationHolder.config.DS2.dataSource.password)
        if (ConfigurationHolder.config.DS2.dataSource.dbCreate) dbCreate(ConfigurationHolder.config.DS2.dataSource.dbCreate)
        dialect(ConfigurationHolder.config.DS2.dataSource.dialect)
        if (ConfigurationHolder.config.DS2.dataSource.jndiName) jndiName(ConfigurationHolder.config.DS2.dataSource.jndiName)
        if (ConfigurationHolder.config.DS2.dataSource.pooled) pooled(ConfigurationHolder.config.DS2.dataSource.pooled)
        if (ConfigurationHolder.config.DS2.dataSource.loggingSql) loggingSql(ConfigurationHolder.config.DS2.dataSource.loggingSql)
        if (ConfigurationHolder.config.DS2.dataSource.logSql) logSql(ConfigurationHolder.config.DS2.dataSource.logSql)

        hibernate {
            cache {
                if (ConfigurationHolder.config.DS2.hibernate.cache.use_second_level_cache) use_second_level_cache(ConfigurationHolder.config.DS2.hibernate.cache.use_second_level_cache)
                if (ConfigurationHolder.config.DS2.hibernate.cache.use_query_cache) use_query_cache(ConfigurationHolder.config.DS2.hibernate.cache.use_query_cache)
                if (ConfigurationHolder.config.DS2.hibernate.cache.provider_class) provider_class(ConfigurationHolder.config.DS2.hibernate.cache.provider_class)
            }
        }
    }
}

Configure the default datasource and environment specific settings in conf/Datasource.groovy
DS2 {
    dataSource {
        pooled=true
        readOnly=false
        driverClassName="org.hsqldb.jdbcDriver"
        username=""
        password=""
        dialect="org.hibernate.dialect.HSQLDialect"
    }
    hibernate {
        cache.use_second_level_cache=true
        cache.use_query_cache=true
        cache.provider_class="net.sf.ehcache.hibernate.EhCacheProvider"
    }
}

environments {
    development {
        dataSource {
            dbCreate = "create-drop" // one of 'create', 'create-drop','update'
            url = "jdbc:hsqldb:mem:devDB"
        }
        DS2 {
            dataSource {
                dbCreate="create-drop"
                url="jdbc:hsqldb:mem:devDB2"
            }
        }
    }
    test {
        dataSource {
            dbCreate = "update"
            url = "jdbc:hsqldb:mem:testDb"
        }
        DS2 {
            dataSource {
                dbCreate="update"
                url="jdbc:hsqldb:mem:testDb2"
            }
        }
    }
    production {
        dataSource {
            dbCreate = "update"
            url = "jdbc:hsqldb:file:prodDb;shutdown=true"
        }
        DS2 {
            dataSource {
                dbCreate="update"
                url = "jdbc:hsqldb:file:prodDb2;shutdown=true"
            }
        }
    }
}

You can also use an externalized configuration to configure your primary and additional datasources.


text:
Q: PostgreSQL "ERROR: could not determine data type of parameter" Ruby exec_params I am trying to execute a query that selects recipes that match a search term from user input stored in the query variable. This is the portion of relevant code:
class DatabasePersistence
  def initialize(logger)
    @db = if Sinatra::Base.production?
        PG.connect(ENV['DATABASE_URL'])
      else
        PG.connect(dbname: "recipes")
      end
    @logger = logger
  end

  def search_recipes(query)
    p "Query parameter is:"
    p query
    p query.class
    sql = <<~SQL
    SELECT * FROM recipes
    WHERE labels ILIKE '%$1::text%'
    SQL
    results = query(sql, query)
    # ... more code
  end

  def query(statement, *params)
    @logger.info "#{statement}: #{params}"
    @db.exec_params(statement, params)
  end

end

The following error is raised on when this line results = query(sql, query) is executed.
PG::IndeterminateDatatype at /search
ERROR: could not determine data type of parameter $1

Another post suggested adding an explicit type cast which is why I added the type cast. I could be doing it incorrectly. I also tried it like the following:
WHERE labels ILIKE '%text($1)%'
WHERE labels ILIKE '%cast($1 as text)%'
WHERE labels ~ '$1::text'
WHERE labels ~ 'cast($1 as text'

In all of the above cases it returned the same error "could not determine the datatype of parameter. I added some #p method calls to make sure the query variable is referencing a real value for debuggin. I have confirmed that this error occurs when the query references a string object with value oats.
What is causing this error to still occur if I am casting the datatype and it is not nil? Am I passing the parameters incorrectly? Am I casting the parameters incorrectly? Is it possible there is a way to pass datatypes as arguments to the #exec_params method? Is there another way to safely pass parameters to be executed by the instance of the PG.connect class?

A: Simply:
WHERE labels ILIKE $1::text

I assume labels is a plain character type like text, too.


text:
Q: WTForms submitting form twice when multiple forms are in the same page On my view I have a few different forms.  In one you enter a first and last name to search for.  If there are results, the page refreshes and a second form to pick a user is displayed as a table where clicking on a row submits the data from that row.  For some reason, submitting the second form results in submitting two values for each field: one completely empty and one with the correct information.
I have some javascript that will be executed when a row in a table is clicked.  It's supposed to fill out and submit a hidden form with the data from the table.  The problem I'm running into is that when the form is submitted, two sets of values are submitted.  request.form after the form is submitted contains the following:
ImmutableMultiDict([('csrf_token', u'1420171907##6ad5346730985191250a52e6432e924ef05c23ee'), ('last_name', u''), ('last_name', u'Smith'), ('first_name', u''), ('first_name', u'John')])

Here's the script:
$('table#theTable tr').click(function () {
var cells = this.getElementsByTagName('td');
$('#selectuser_last_name').val(cells[0].innerHTML);
$('#selectuser_first_name').val(cells[1].innerHTML);
document.selectuser.submit();
});

and here is the HTML to go along with it:

            Last
            First

        {% for user in users %}

                {{ user.last_name }}
                {{ user.first_name }}

        {% endfor %}

<form id=selectUserForm action="/handle_users" method="post" name="selectuser">
    {{ forms.selectuser.hidden_tag() }}
    {{ forms.selectuser.last_name(id="selectuser_last_name") }}
    {{ forms.selectuser.first_name(id="selectuser_first_name") }}
    <input type="submit">Test</input>
</form>

I'm using Python and Flask to handle whatever is posted.

A: It seems you're actually submitting twice- once before there's anything in the form, and once after it's populated (the latter by the javascript, the former via the form submit mechanism).
If the user isn't really inputting anything into the form, but this is a simple call to the server any time a row is clicked. Skip the whole form, it's not helping here. Just pass a call to the server with the info you need- can be a simple ajax post:
 $('table#theTable tr').click(function () {
   var cells = this.getElementsByTagName('td');
   $.ajax({
        type : "POST",
        url : "/handle_users",
        async:true,
        contentType : 'application/json;charset=UTF-8',
        data: JSON.stringify({first_name:cells[0].innerHTML,last_name:cells[1].innerHTML}, null, '\t'),
        success : function(data) {
            // optional: do something when server-side processing is done
        }
    });
});

Then Grab your data on from flask using request.get_json() in the /handle_users route.


text:
Q: How to create a Python Model based on Z-score that maximize the ending PNL (profit and loss) I'm building a model that allocate money based on the combination of Z-score of differents indicators. Basically my model allocate 5M$ if the combination of the previous Z-score > 0.5. If i'm allocate 5M$ the Zscore need to be <0 to go back to an allocation of 0. If the previous Z-score is < -0.8 then I allocate -5M$ (means I short the market). If I'm short, the previous z-score need to be > -0.25 to go back to an allocation 0. In other case i'm just not allocated (youll see my code below!)
Lets say I Have 3 indicators in a dataframe name df:

Now here's my code to calculate the indicators Z-score and the combination of the three. Please note that after summing the Zscore i need to recalculate a z-score of the combination to normalize the result:
cols = list(df.columns)
    for col in cols:
        col_zscore = col + '_z'
        df[col_zscore] = (df[col] - df[col].mean())/df[col].std(ddof=0)

#I dont need the z score of the returns
df = df.drop(labels = 'Returns', axis = 1)

#creation of the combination
weight_vix = 1/3
weight_Unemp = 1/3
weight_Fed = 1/3
df['Combination'] = (df['VIX_z']*weight_vix + df['Unemployment_z']*weight_Unemp + df['Fed_funds_z']*weight_Fed)
df['Combination_z'] = (df['Combination'] - df['Combination'].mean())/df['Combination'].std(ddof=0)

Here's the dataframe with the individual Z-score :

Now base on this result I need to allocate my money (with the constraint mention in the beginning). Heres the code :
# Parameter of allocation
param = pd.DataFrame(
         {"Seuil": [1,2,3],
          "Augmentation": [-0.25,0.5,100],
          "Diminution": [-100,-0.8,0.0],
          "Alloc": [-2.5,0,2.5]})
param.set_index("Seuil", inplace=True)

def step_calculator(previous_zscore):
    if previous_zscore < param.loc[step_calculator.previous_step, "Diminution"]:
        current_step = step_calculator.previous_step - 1
    elif previous_zscore > param.loc[step_calculator.previous_step, "Augmentation"]:
        current_step = step_calculator.previous_step + 1
    else:
        current_step = step_calculator.previous_step
    step_calculator.previous_step = current_step
    return param.loc[current_step, "Alloc"]
previous_ind = None

step_calculator.previous_step = 2
df['Allocation'] = df[['Combination_z']].shift(1).fillna(0.4).apply(lambda x: step_calculator(*x), axis=1)

Here's now what my Dataframe look like (just to remind yall that allocation is base on the previous z-score) :

Now here's the code to calculate the my PNL :
df["PNL_M$] = df["Allocation"] * df["Returns"]*1000

Heres the final dataframe :

The sum of this PNL is -100m$ base on equally weight. Is there a way to maximize the final PNL base on the weight of the indicator z-score ? When i mean maximize PNL I mean the end total PNL (sum of the column).


text:
Q: QProcess and command line "/c" argument I have very strange problem with QProcess and it's strange behaviour.
What i wanna get at the end is something like this (this is cmd.exe in windows 7)
C:\path_to_somewhere>cmd /c "C:\Program Files\path_to_dir\executable"

(cmd is for compatibility with show of QProcess)
So to do something like that i create this:
QProcess proc;
QString command;
QStringList attributes;

command = "c:\\windows\\system32\\cmd.exe";
QStringList << QString("/c \"C:\\Program Files\\path_to-dir\\executable"");
proc.start(command, attributes);

What i get on error output is:
Name '\"c:\Program Files\Quantum GIS Wroclaw\bin\gdalwarp.exe\"' is not recognized as
internat or external command, executable or batch file.

(it's translated by me from polish so it may be a little diffrent in english).
Seems like the \ character is not escaped in the string, leaving the \" as to characters in command. What am I doing wrong?
I've tried the
proces.start(QString)

function with triple \"\"\" and it doesnt work either. I suppose the solution of this problem has to be sooo easy that I dont event think about it.

A: OK I don't know if it's Qt bug but in documentation about void QProcess::start(QString, QStringList, OpenMode) it is said something like that:

Windows: Arguments that contain spaces are wrapped in quotes.

Seems like it's not true as my program uses path with space and cmd shell breaks there.
But, I found out function that is designed for systems that accept one string only arguments (so like Windows does).
It's QProcess::setNativeArguments(QString)
that accepts one QString as argument, created especially for Windows and Symbian.
So after all, if one has a problem with passing arguments in Windows (or Symbian) to system, he should try setNativeArguments(QString).

A: As you already noted, Qt wraps arguments containing spaces with quotes, which means that the actual command issued by QProcess will look something like that (not sure about the inner quotes):
c:\windows\system32\cmd.exe "/c \"C:\Program Files\path_to_dir\executable\""

which is not what you want: the entire string is passed to cmd including /c. Since /c and the path are two arguments, you should pass them separately to QProcess, without worrying about spaces as they will be handled automatically:
QString command = "cmd.exe";
QStringList arguments =
    QStringList() << "/c" << "C:\\Program Files\\path_to_dir\\executable";
// note there are two arguments now, and the path is not enclosed in quotes
proc.start(command, arguments);


text:
Q: Configuration file for scons in an ubuntu system I am trying to install this tool (ISCE) on my computer running Ubuntu 14.04.
My scons configuration file is as follows:
# The directory in which ISCE will be built
PRJ_SCONS_BUILD= $HOME/isce
# The directory into which ISCE will be installed
PRJ_SCONS_INSTALL= $HOME/isce
PRJ_LIB_DIR = $HOME/isce/lib
# The location of libraries, such as libstdc++, libfftw3 (for most system
# it's /usr/lib and/or /usr/local/lib/ and/or /opt/local/lib)
LIBPATH='/usr/lib/x86_64-linux-gnu/' '/usr/lib/x86_64-linux-gnu/4.8'
# The location of Python.h. If you have multiple installations of python
# make sure that it points to the right one
CPPPATH='/home/shaunak/anaconda2/envs/ISCEp35/include/python3.xm'
# The location of the fftw3.h (most likely something like /usr/include or
# /usr/local/include /opt/local/include
FORTRANPATH='/usr/include'
# The location of your Fortran compiler. If not specified it will use the system one
FORTRAN='/usr/bin/gfortran'
# The location of your C compiler. If not specified it will use the system one
CC='/usr/bin'
# The location of your C++ compiler. If not specified it will use the system one
CXX='/usr/bin'

When I try to execute the command to install as instructed by the README: SCONS_CONFIG_DIR=~/isce scons -Q install it fails with the error message:
Error. Cannot locate the stdc++ library in the directories specified by LIBPATH in the SConfig file.
Exception: :
  File "/home/shaunak/isce/SConstruct", line 46:
    sconsConfigFile.setupScons(env,sconsSetupFile)
  File "/home/shaunak/isce/configuration/sconsConfigFile.py", line 384:
    retDict = setupCompilers(retDict)
  File "/home/shaunak/isce/configuration/sconsConfigFile.py", line 282:
    dict = setupLinux(dict)
  File "/home/shaunak/isce/configuration/sconsConfigFile.py", line 221:
    raise Exception

I have tried to search each library with the locate command and all the paths seem to be accurate. I cant seem to understand why the compilation is failing. For instance locate libstcc++ yields:
/usr/lib/gcc/x86_64-linux-gnu/4.8/libstdc++.a
/usr/lib/gcc/x86_64-linux-gnu/4.8/libstdc++.so
/usr/lib/gcc/x86_64-linux-gnu/4.8/32/libstdc++.a
/usr/lib/gcc/x86_64-linux-gnu/4.8/32/libstdc++.so
/usr/lib/gcc/x86_64-linux-gnu/4.8/32/libstdc++_pic.a
/usr/lib/gcc/x86_64-linux-gnu/4.8/x32/libstdc++.a
/usr/lib/gcc/x86_64-linux-gnu/4.8/x32/libstdc++.so
/usr/lib/gcc/x86_64-linux-gnu/4.8/x32/libstdc++_pic.a
/usr/lib/i386-linux-gnu/libstdc++.so.6
/usr/lib/i386-linux-gnu/libstdc++.so.6.0.19
/usr/lib/x86_64-linux-gnu/libstdc++.so.6
/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.19

A: Try this:
LIBPATH=['/usr/lib/x86_64-linux-gnu/', '/usr/lib/x86_64-linux-gnu/4.8']

Recall that SCons files are Python, and lists in Python are represented by [item1, item2, ...].


text:
Q: Will @TestPropertySource honor SPEL or values from other properties? I'm wondering if the @TestPropertySource will honor SpEL or will at least allow a property to substitute values from another property.
It's a similar question to  @TestPropertySource with dynamic properties
Assuming the properties I'm referring to exist in one of the files in the locations attribute...
For example if I'd like to do something like:
@TestPropertySource(
    locations = {"classpath:application.properties", "classpath:database.properties"},
    properties = {"newPortNum = #{1 + Integer.parseInt(${myapp.web.server.port.ssl})}})

Or this:
@TestPropertySource(
    locations = {"classpath:application.properties", "classpath:database.properties"},
    properties = {"outputFile = ${outputDir}/foo.txt"})

Do I need to implement a TestExecutionListener or @BootstrapWith to accomplish this?

A: Straight from the Javadoc for @TestPropertySource.locations():

Property placeholders in paths (i.e., ${...}) will be resolved against the Environment.

... that means: against anything already added to the Environment.
SpEL expressions, on the other hand, are not supported.
If you need programmatic support for adding a PropertySource to the Environment, you should implement an ApplicationContextInitializer which can be registered via @ContextConfiguration(initializers = ...).
Regards,
Sam (author of the Spring TestContext Framework)


text:
Q: How to make my function get invoked by $(..).name()? I have made a js function named draw(), now is it possible that I can call this method using . operator after I get the element using $(...). I mean I like this to work $(#myId).draw(). Right now it gives error like undefined function. How can I make it work?

A: It's hard to tell from your question, but it sounds like you want to create a jQuery plugin.  You can do that by extending $.fn:
$.fn.draw = function(){
    /* ... */
}

Then you can call that against a selector:
$('#myId').draw();

More documentation here: http://learn.jquery.com/plugins/basic-plugin-creation/

A: You have to create it as a jquery plugin. As described here.
Best Way to Extend a jQuery Plugin
Documentation from jQuery:
http://api.jquery.com/jquery.fn.extend/
JsFiddle sample: http://jsfiddle.net/Wdx75/
var obj1 = { "color" : "yellow" };
var obj2 = { "background" : "blue" };

var o = $.extend({}, obj1, obj2);

$.fn.draw = function(){
    $("div").css(o);
}

$('abc').draw();

A: You'll neet to look at adding a jquery plugin
$.fn.draw= function(){

}

A: The best way is to add methods using jquery.fn.extend ( As we can add several plugin functions at a time )
Sample code looks like
jQuery.fn.extend({
  draw: function() {
    return this.each(function() {
      // add code here to draw
    });
  }
});

Once you add this method, you can use below code to call your draw method on any jQuery element
$("#myId").draw()

Official Reference: jquery.fn.extend

A: You want to use jQuery.fn.extend, documented here http://api.jquery.com/jquery.fn.extend/.
$.fn.extend({
    draw: function() {

    // do something to the jQuery object
    return this;

    }
});

Now you can call .draw on a jQuery object created with $(...).


text:
Q: Detect if JQuery Mobile came from a select dialog I have a jquery mobile app that has a page. This page has three DIVs, I programmatically choose one of these DIVs based on a variety of variables. Regardless, the one DIV contains a select element. This element has 20 items in it. Because of the shear quantity, the select box opens in its own dialog. I'm fine with that, however, after a user makes a choice, the pagebeforeshow event of my hosting page is fired again. My problem is, I can't seem to figure out how to detect that this event was fired as a result of the user choosing an option or closing the select dialog.
Is there a way to detect in the pagebeforeshow event how we got here?

A: jQuery mobile passes meta-data to the callback functions of most events. From the docs on pagebeforehow:

Triggered on the "toPage" we are transitioning to, before the actual transition animation is kicked off. Callbacks for this event will recieve a data object as their 2nd arg. This data object has the following properties on it:

*

*prevPage (object) - A jQuery collection object that contains the page DOM element that we are transitioning away from. Note that this collection is empty when the first page is transitioned in during application startup.

You should be able to use this in your callback function to branch to your advantage, i.e. detect if prevPage is the current page. This might look like:
$('#yourPage').live('pagebeforeshow', function(event, data) {
    var from = data.prevPage;
    // do some inspection of `from` and branch accordingly
    // might require some experimental console.logging first
});

A: I also didn't verify the question raised in above comment, but data.prevPage has a copy of the entire previous page's HTML, accessed via data.prevPage[0].innerHTML. I'm sure you could do something like binding to the click event on the select dialog and tell it to add a class or whatever to the DOM where the user selected whatever entry, and scrape that back out of the HTML? Just throwing an idea out there.


text:
Q: Speech Recogniser Intent not getting back the data in OnActivityResult I have an Speech Recognizer Intent on click of a button.
voiceSearch.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {
        try{
            Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                    RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak Now...");
            startActivityForResult(intent, REQUEST_CODE);
        }
        catch (ActivityNotFoundException e) {
            Log.v("Speech", "Could not find any Speech Recognition Actions");
        }

    }
});

On Activity Result I have the code as
     @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
     System.out.println("Request code++++++++++++++++++++++++++++"+requestCode);
     System.out.println("Result Code+++++++++++++++++++++++++++++"+resultCode);
     System.out.println("Data++++++++++++++++++++++++++++++++++++"+data);
   System.out.println("Language"+data.getStringExtra(RecognizerIntent.EXTRA_LANGUAGE));
     System.out.println("data.getDataString()"+data.getDataString());
     if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
     if (data != null && data.getData() != null) {
            String searchKey = data.getData().toString();
            System.out.println("Search Key++++++++++++++++++++++++"+searchKey);
            searchEditText.setText(searchKey);
            webView.loadUrl(url+"searchKey");

        }
 }
 }

The output I get is when I am printing in onActivityResult is
Request Code I get as 1
Result Code I get as -1
Data I get as Intent { (has extras) }
Language data.getStringExtra(RecognizerIntent.EXTRA_LANGUAGE) as null.
Data.getDataString() as null.
Could anybody let me know what could be wrong I might be making in the code.
thanks.

A: I think you're trying to get at the results in the wrong way. They're not stored in the data string, but in a matches array.
You can get the array by doing:
ArrayList<String> matches = data.getStringArrayListExtra(
    RecognizerIntent.EXTRA_RESULTS);

Each entry in the array will be a multi-word string representing one guess the recogniser has for what the user said.


text:
Q: how does "multiply(arr, n-1)*arr[n-1]" work? I have this problem on freeCodeCamp as I'm learning JavaScript.
I'm trying to understand this block of code.
  function multiply(arr, n) {
    if (n <= 0) {
      return 1;
    } else {
      return multiply(arr, n-1)*arr[n-1];
    }
  }console.log(multiply([2,2,4],3));

As a whole, I understand what this code above does. But not this line below.
multiply(arr, n-1)*arr[n-1];

There's already a about post this specific problem here, but I have read all of the comments and I did not understand.
What I don't understand specifically is (arr, n-1). Exactly what does that do? The rest of the line I can understand after a long time thinking, it's just that little piece that I can't make sense of.

A:
What I don't understand specifically is "(arr, n-1)". Exactly what does that do?

This is the argument list for the function call of the multiply() function. You cannot understand this in isolation because it belongs to the function call.
In other words, the syntactic element is not (arr, n-1), it is multiply(arr, n-1).
A parameter is kind of like a "hole" that you leave in a function definition. Parameters allow you to make functions re-usable in different contexts.
For example, a function like this:
function doubleTheValueSix() {
  return 2 * 6;
}

is not very useful because it can be used for only one very specific thing. However, we can make it more useful by parameterizing it:
function doubleAnyArbitraryValue(n) {
  return 2 * n;
}

is much more useful. Here, n is called the parameter and (n) is called the parameter List. In this case, there is only one parameter in the parameter list, but there can be arbitrary many, including – as we have seen above – zero.
An argument is what you pass to a function call to "fill in" the "hole" left by the parameter in the function definition.
So, in this code here:
doubleAnyArbitraryValue(42)

The literal 42 is the argument which gets bound to the parameter n inside the function body of doubleAnyArbitraryValue. In other words, everywhere n appears in the function body, it gets replaced with 42.
So, in this case, 42 is the argument and (42) is the argument list.
What this means in your particular code snippet is the following:

*

*Look up the name multiply in the local scope. It could be a function defined in the local scope (or in an enclosing scope), a const, a let, or a var defined in the local scope (or in an enclosing scope).

*Call the object you found in step #1, passing the result of evaluating the expressions in the argument list as arguments:

*

*Evaluate the expression arr (which essentially means: look up the name arr in the local scope; it could be a const, a let, or a var defined in the local scope (or in an enclosing scope)).

*Evaluate the expression n-1:

*

*Look up the name n in the local scope; it could be a const, a let, or a var defined in the local scope (or in an enclosing scope).

*Apply the Binary Arithmetic Subtraction Operator - to the result of step 2.1.1 and the Numeric Literal 1.

You can find the details about how function calls work in subsection 13.3.6 Function Calls of the ECMAScript Language Specification. (Note, the version I linked to is the Living Document which always shows the current state of the next release, but that doesn't matter in this case – how function calls work fundamentally hasn't changed since ECMAScript was still called LiveScript in 1995 and even before that when it was still called Mocha.)


text:
Q: Electric potential energy after nuclear fission We have a uranium-236 nucleus that fissions into two equal fragments, and I'm supposed to find the electrical potential energy just as the two fragments split apart. No other information is provided.
I am very confused about this problem for two reasons. First, U-236 is electrically neutral, with exactly 92 protons and 92 electrons. After it splits into two equal fragments, why would there be a charge on the resulting pieces? Secondly, electric potential energy of two point charges is inversely proportional to the distance r between the particles. But since the question asks for the potential energy immediately after fission, r=0 and potential energy goes to infinity.
I'm appreciate any guidance!

A: Has your instructor (or your book) mentioned how much bigger a atom is than a atomic nucleus? On order of 10000 times.
Moreover, except for the $s$-shell electrons, most electron never come very close to the center (the $p$, $d$, etc shells all have nodes at $r=0$) so at the moment of fission the nuclei are sitting roughly at the middle of a roughly spherical shell of electrons.
You are probably meant to ignore the electrons and work it as if only the protons and neutrons mattered.

A: Like dmckee says, the potential energy of electrons in an atom doesn't really compare to the energy of the nucleus. Since the nucleus is so tightly packed, and (in the case of Uranium) contains so many protons, they have a lot of potential energy—it takes a lot of work to "push" them together. The strong force holds protons and neutrons together when they're close enough together. It's sometimes compared to a glue in that sense. However, this force disappears very quickly once the nucleons become separated past a certain distance (on the order of a femtometer), so for a large nucleus like that of Uranium, the protons on one end of the nucleus aren't "stuck" to the protons on the other side, but there's still plenty of electrostatic force pushing them apart. That's why large nuclei are unstable; especially those with a higher proton-to-neutron ratio, like U-235 (or U-236). If you can destabilize that nucleus enough (you could imagine it stretching out like a football), its own electric force will tear it apart, and release a tremendous amount of energy as the fragments accelerate apart.
It seems that you've already considered that to a degree, but yes, you don't have to worry about electrons. Just think about the protons, because the nucleus is definitely not neutral. It is a bit of a problem if you don't know how close together those nuclear fragments start out, but you could probably estimate it by considering the nuclear radius of uranium, which is about 7 or 8 fm (it's hard to find an exact figure), or by using double the radius of the fragments it creates, which, it would seem, would be paladium nuclei. Obviously the protons weren't in the same place when they start out, but they were very close together.


text:
Q: Flask & Js - Can't get json through a post request I am trying to make a site, it gets data from a flask webapp.
Can someone tell a way to fix this ....
Note -
https://flask-webapp.co & https://my-site.co are examples, not real URLs ...
importing flask as server
But when i post the data to flask, it gives me this error -
[2022-02-27 09:05:35,348] ERROR in app: Exception on /getData [POST]
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 2073, in wsgi_app
    response = self.full_dispatch_request()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 1518, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 1516, in full_dispatch_request
    rv = self.dispatch_request()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 1502, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "/home/runner/Discord-Smart-Bot/main.py", line 463, in getuser
    user = json.loads(server.request.get_json())
  File "/usr/lib/python3.8/json/__init__.py", line 341, in loads
    raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not NoneType
172.18.0.1 - - [27/Feb/2022 09:05:35] "POST /getData HTTP/1.1" 500 -
[2022-02-27 09:05:35,354] INFO in _internal: 172.18.0.1 - - [27/Feb/2022 09:05:35] "POST /getData HTTP/1.1" 500 -

My python code -
@app.route("/getData", methods=["POST"])
def getdata():
  print("GOT")
  data_rec = json.loads(server.request.get_json())
  print(user)
  id = data_res["id"]
  data = asyncio.run(getUser(int(id)))
  return data

Js code -
 xhr.open("POST", "https://flask-webapp.co/getData", true);
      xhr.getResponseHeader('Content-type', 'application/json')
      xhr.onload = function() {
        console.log(this.responseText)
        let data = JSON.parse(this.responseText)
        let val = data["val"]
        let i = data["i"]
      }
      params = {"id" : usr_id}
      xhr.send(params);

Error in browser -
Access to XMLHttpRequest at 'https://flask-webapp.co/getData' from origin 'https://my-site.co' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

POST https://flask-webapp.co/getData net::ERR_FAILED 500

XHR failed loading: POST "https://flask-webapp.co/getData".

A: I fixed No 'Access-Control-Allow-Origin' header is present on the requested resource.
NOTE -
importing flask as server

from flask_cors import CORS, cross_origin

app = server.Flask(" ")
CORS(app, support_credentials=True)

@app.route("/getData", methods=["POST"])
@cross_origin(support_credentials=True)
def getuser():
  print("GOT")
  print(str(server.request.data))
  data_rec = json.loads(server.request.data)
  id = data_rec["id"]
  data = getData(int(id))
  print(data)
  return str(data)

And in js code -
let data = JSON.parse(this.responseText)


text:
Q: What happens during initialization of a bare brand new hard disk? Do Operating systems handle it differently? Can you tell if a hard disk was first initialized by Windows or Linux on later abduction?
Like this https://www.youtube.com/watch?v=O7_aZwQ_p4w
After plugging it in, but before partitioning and formatting.

A: There's no permanent residue left by an operating system that first initialised a disk. That is, you can take a disk formatted by Windows, reformat it for use with Linux or Apple and there will be (if you do the full setup), nothing to leave a clue that it was Windows originally. Or not to a normal user anyway. There are forensic technique to recover data that might be able to work out that you started with a Windows loader rather than a Linux or Apple one but you need specialised equipment for that. ;)
Technically, you could put a bootloader on the raw disk. But most bootloaders are looking for their second stage to the FS in a partition to get going... so it would be an unusual state to find a bootloader without other evidence of the disk usage. And the bootloader would give you an implication of the intent. It wouldn't prevent you from creating arbitrary partitions, etc. You might not be able to boot them, but you could have them. :)
Temporary data - depends on whether the disk is the bootable disk of an OS. Generally, a non-bootable disk can be any file system that the OS uses. So you could have a bootable disk for Linux, and a second non-bootable disk partitioned as if for Windows with NTFS. In which case the secondary disk is only distinguishable from an NTFS secondary used on Windows because you have other inferences... what gets put on the disk would have to be the main clues.
What temporary data is there that gives a clue as to the last OS that initialised a bootable disk? Mostly the type of loader, and the file systems that have been put in the partitions. Windows tends to use NTFS. Apple uses HFS. Linux... mostly uses ext4, might have been using ext3, or reiserFS, or NTFS, or FAT32, or... a lot. Linux will be better identified by one of the boot loaders because only the strangest people run Windows and then use a different boot loader. GRUB, and LILO, etc, suggest that the most recent OS was Linux - because you mostly won't use those with Mac OS X only, and you'd only use other bootloaders with Windows if you were also running Linux, or had been intending to do so. No GRUB - then the disk is probably not used as a primary disk by Linux. With Grub and HFS - look for the other partition with a Linux FS... because it is probably a dual booted system. GRUB with NTFS and a Linux FS - dual booted to Windows and Linux. etc.
The easiest signals are that:

*

*the disk has no alternate bootloaders and does have NTFS - it's Windows.

*the disk has HFS only - it's Mac OS X

*the disk has GRUB or another bootloader, and ext4 - it's Linux

In ancient times, floppy disks for Macs were different media than floppy disks for PCs. It was pretty much impossible to handle a Mac floppy in a PC. It's sufficiently long ago that I can't recall exactly why.

A: Revised:
Yes, different OSes place different information on the hard drive when it is partitioned and formatted. For disks under 2 TB, a Master Boot Record (MBR) is used and for disks over 2 TB, a GUID Partition Table (GPT) is used. GPT can be used on smaller disks as well. Windows installs a bootloader (from Microsoft) and many Unix ditributions uses GRUB (or GRUB2) as a bootloader. Also, GRUB is capable of more formats than the Windows bootloader.
To determine which OS initialized the hard disk, you would need to determine which system placed the bootloader on the disk. But since the bootloader can easily be replaced, all you really know is the latest OS to place the bootloader.


text:
Q: Is there a Python analogue to Julia's LaTeXStrings? In Julia there is a package LaTeXStrings that allows for convenient input of LaTeX strings. E.g. you don't have to treat \ as an escape character or $ as a special symbol:
L"an equation: $1 + \alpha^2$"

instead of
"an equation: \$1 + \\alpha^2\$"

Is there an analogue in Python?

A: This is not specific to LaTeX, but you could use raw strings, which are marked by the letter r or R prefixing the string, as in r"your string".
For example:
>>> s = r"an equation: $1 + \alpha^2$"
>>> print(s)
an equation: $1 + \alpha^2$

A: I think Sympy might be what you're looking for. It's a symbolic mathematics library which supports Latex:
>>> from sympy import init_printing
>>> from sympy.parsing.latex import parse_latex
>>> init_printing()
>>> expr1 = parse_latex("\int_{a}^{b} x^2 dx")
>>> expr1
prints the integral in ascii in console or Latex in IPython QTConsole

This requires an additional dependency of the antlr-python-runtime library, which can be installed via conda/pip.


text:
Q: How to numba this expression From this stackoverflow post I got this for a way to produce unique mappings between two lists:
  for mapping in set(
        [
            tuple(sorted(zip(perm, neg_indices)))
            for perm in set(permutations(pos_indices, len(neg_indices)))
        ]
    ):

Now I would like to @njit the function to speed it up as much as possible.
However, it seems to have trouble converting the list of tuples from permutations and the list of tuples of tuples to a set.
I also already have problems converting the permutation function from here so that it returns a list of tuples that can be converted into a set of tuples in the first place.


text:
Q: Aptly : "gpg: no default secret key", but key isn't expired I have good not expired gpg secret key but when I run
aptly -architectures=all publish repo product
Warning: publishing from empty source, architectures list should be complete, it can't be changed after publishing (use -architectures flag)
Loading packages...
Generating metadata files and linking package files...
Finalizing metadata files...
Signing file 'Release' with gpg, please enter your passphrase when prompted:
gpg: no default secret key: secret key not available
gpg: signing failed: secret key not available
ERROR: unable to publish: unable to detached sign file: exit status 2

Why?

A: Aptly uses gpg1, you need to create a key with gpg1.
This solved it for me :
gpg1 --gen-key


text:
Q: VirtualizingPanel acts weird with many many Children Hiho,
im facing serious issues implementing a Horizontal VirtualizingPanel the right way. Virtualization works so far and items are positiones at the right positions but when i scroll though the items, some items start overlapping(for me at Item 671090) and the following Items start creating gaps between each other. This effect increases depending on the horizontal offset.
I already tried to locate the Problem watching the itemposition in Debug but its all as it intends to be. Different Implementations found in the internet have the same problem.
I tried the VirtualizingTilePanel Implementation provided by Dan Crevier and the StaggeredPanel described in "SAMS WPF Control Development unleashed".
Both seem to have the same Problem when i add a lot of items.
Steps to reproduce:
1. Download Example from http://blogs.msdn.com/b/dancre/archive/2006/02/16/implementing-a-virtualizingpanel-part-4-the-goods.aspx
or sample code from
http://www.informit.com/store/wpf-control-development-unleashed-building-advanced-9780672330339

*

*Add for example 1000000 items for Virtualization.

*Scroll through Data

*Problem starts for me at item 671090(maybe depending on architecture?)

edit: Itemswidth is set to 100.0,
Problem occurs at the same index for my colleagues
Any help would be really nice.
Thank you and greetings


text:
Q: How can i style the Countdown Element from react-coundown-now? I use the react-countdown-now component. https://www.npmjs.com/package/react-countdown-now/v/1.0.0
I use it like this:
import Countdown from 'react-countdown-now';

function Component() {
  return (
    <Countdown date='2020-02-01T01:02:03' style={{ color: '#00ff00' }}/>
  );
}

I wonder how i can style this component, beacause the style tag doesn't affect something.
Thanks for help.

A: You should style the rendered component or target styling span selector:
import React from 'react';
import ReactDOM from 'react-dom';
import Countdown from 'react-countdown-now';
import styled from 'styled-components';

const PurpleCount = styled.div`
  span {
    color: purple;
  }
`;

// Random component
const Finished = () => (
  You are good to go!
);

// Renderer callback
const renderer = ({ total, hours, minutes, seconds }) => {
  if (total) {
    // Render a countdown
    return (

        {hours}:{minutes}:{seconds}

    );
  } else {
    // Render a finished state
    return <Finished />;
  }
};

const App = () => (
  <React.Fragment>
    <Countdown date={Date.now() + 10000} renderer={renderer} />

    <PurpleCount>
      <Countdown date={Date.now() + 10000} />
    </PurpleCount>
  </React.Fragment>
);

ReactDOM.render(<App />, document.getElementById('root'));

A: Pass the style as a props of the Countdown component
return (
    <Countdown date='2020-02-01T01:02:03' styleColor={'#00ff00'}/>
  );

In Countdown component get the props and set the style of the parent div.
Goto Countdonw component and apply the below code