jQuery.ajax cannot find server when use an alias defined in "hosts" file, but can with ip address - how fix?

Question: I have defined an alias in my hosts file (on linux): 192.168.1.123    mysite-example.com. When I go to this in a web browser, it works. But when my JavaScript calls for a jquery ajax post, it doesn't work.
THIS DOES NOT WORK
$.ajax({
        url: "http://mysite-example.com/mypage.php",
        data: { "test": "test" },
        success:function(data) {
            console.dir(data);
        },
        error: function(errorThrown){
            console.dir(errorThrown);
        }
});

THIS DOES WORK
$.ajax({
        url: "http://192.168.1.123/mypage.php",
        data: { "test": "test" },
        success:function(data) {
            console.dir(data);
        },
        error: function(errorThrown){
            console.dir(errorThrown);
        }
});

What is causing this? How do I fix this?
Answer: Check main domain. In question is other that your JS ajax
question: mysite-example.com
js: mysite.example.com
Comment: I discovered the problem (cross-origin due to ip and domain name, see my answer for an explanation).
Answer: The error was due to how domains are interpreted. When I was loading the client-side page, I loaded it from 192.168.1.123, the actual ip address of the server. But it was requesting the server by domain name. Since multiple domains can be on the same server, this (I believe) causes the browser to interpret them as cross-origins and thus rejects it.
When I visited the client page (with the ajax call) at the domain name (http://mysite-example.com), the ajax call works.
(I can also make it work by adding the header header('Access-Control-Allow-Origin: *'); on the server, but that's not a good idea.)


Having trouble hiding and showing a div using PHP+Jquery

Question: User submits their email address, email is checked if it's valid and not in the database..
The problem I am having is that I cannot get the form to hide and the thank you div to show, once the form has been submitted successfully. It currently replaces the email textbox with "Thank you!" text which I don't want.
What must be changed or added so the form is hidden (after it passes error/validation checks) and the thank you div is shown?
Thank you!!
Index.php
<?php

require "includes/connect.php";

$msg = '';

if($_POST['email']){

    // Requested with AJAX:
    $ajax = ($_SERVER['HTTP_X_REQUESTED_WITH']  == 'XMLHttpRequest');

    try{
        if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){
            throw new Exception('Invalid Email!');
        }

        $mysqli->query("INSERT INTO coming_soon_emails
                        SET email='".$mysqli->real_escape_string($_POST['email'])."'");

        if($mysqli->affected_rows != 1){
            throw new Exception('You are already on the notification list.');
        }

        if($ajax){
            die('{"status":1}');
        }

        $msg = "Thank you!";

    }
    catch (Exception $e){

        if($ajax){
            die(json_encode(array('error'=>$e->getMessage())));
        }

        $msg = $e->getMessage();
    }
}
?>

<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Notify me test</title>

<link rel="stylesheet" type="text/css" href="css/styles.css" />

Notify

Notify me

    <form id="form" method="post" action="">
        <input type="text" id="email" name="email" value="<?php echo $msg?>" />
        <input type="submit" value="Submit" id="submitButton" />
    </form>

    Thank you!

script.js
$(document).ready(function(){

    // Binding event listeners for the form on document ready

    $('#email').defaultText('Enter your Email Address');

    // 'working' prevents multiple submissions
    var working = false;

    $('#page form').submit(function(){

        if(working){
            return false;
        }
        working = true;

        $.post("./index.php",{email:$('#email').val()},function(r){
            if(r.error){
                $('#email').val(r.error);
            }
            else $('#email').val('Thank you!');

            working = false;
        },'json');

        return false;
    });
});

// A custom jQuery method for placeholder text:

$.fn.defaultText = function(value){

    var element = this.eq(0);
    element.data('defaultText',value);

    element.focus(function(){
        if(element.val() == value){
            element.val('').removeClass('defaultText');
        }
    }).blur(function(){
        if(element.val() == '' || element.val() == value){
            element.addClass('defaultText').val(value);
        }
    });

    return element.blur();
}

Comment: I don't see any code in there at all that even attempts to do anything like hiding the form and showing that "thankyou" div. Also, I **do** see code that **explicitly** sets the input field value to "Thank you".
Comment: @Pointy: I attempted to replace the line of setting the textbox id "email" with the hide/show function but it errors, even as suggested below, it still errors.
Answer: why do you do this if you dont want to replace input with thank you text?
else $('#email').val('Thank you!');

instead do
else {
    $("#form").hide();
    $("#thankyou").show();
}
Comment: @Eugene msc: It was from a tutorial :) just wanted to customise. Thanks for the help, but it errors with: Fatal error: Call to undefined function hide() in /home/..../index.php on line 28
Comment: do you have anything on your page that jquery might conflict with? try jQuery("#form").hide();jQuery("#thankyou").show();
Comment: @Eugene msc: Still the same error - Fatal error: Call to undefined function hide(). The above code in my original post os all the code there is..
Comment: @Eugene msc: Very strange.. the error no longer appears, however the hide/show doesn't occur. Rather, the "thank you!" text is displayed in the textbox.
Comment: yeah that is strange. if you use firebug you can set brakpoint at that line and look what $("#form") object looks like and see what functions it has
Comment: @Eugene msc: what's stranger is that even when I remove else $('#email').val('Thank you!');  and replace with else { }, it still displays the thank you text in the textbox. Does this help? I think it's grabbing it from PHP at the top of the index file. I'll run firebug.. in the meantime if you work it out please let me know. Thanks
Comment: i don't think it's possible. the only piece of code that sets text into textbox is $('#email').val('Thank you!'); it's probably caching or something.
Comment: @Eugene msc: I've cleared cache, tested firebug, nothing wrong. I don't get it :/ If you run it on your end does it work correctly?
Comment: @Eugene msc: If I change $msg = "Thank you!"; at the top of index.php to $msg = "Thank you test!"; it displays the new message. Is there something I can edit in that area? (at the top of index.php)
Comment: @jeremycollins i think i found the problem it's $('#page form') there is no #page element, so submit just reload the page with email parameter posted, and javascript doesn't work at all. try changing it to $("#form")
Comment: @Eugene msc: GENIUS!! Thank you sooooo much!!
Comment: @Eugene msc: One more thing, sorry - do you know how I can fade in and then fade out, both slowly?
Comment: $("#form").fadeOut('slow') or $("#form").hide('slow') same for fadeIn and show


Installable storage heaters - why manufacturers bother putting the bricks in?

Question: Recently I have learned of "installable storage heaters". Those are fairly heavy devices which consist of a ceramic brick stack and electric heater. The brick stack is heated during the off-peak electricity hours and gives back heat the rest of the time.
This made me think: the density of bricks is at best twice the density of water. Heat capacity of bricks, on the other hand, is closer to being 4-6 time smaller than heat capacity of water.
A simple calculation thus shows, that device with exactly same dimensions as those available on the market but featuring a drainable water tank as a heat accumulator instead of bricks:

Will be able to store more energy
Will be light and portable when water is drained
Will have better efficiency transferring heat from primary heater to accumulator

So the question is: why offerings on the market mostly consist of immovably heavy, brick filled devices?
Comment: @Harper - water makes no sense in this application.  The upper temperature to avoid a pressure vessel and safety valves would be somewhat less than 100 deg C.  Materials like stone or bricks can be heated to several hundred deg C.  If using water, the system has to be drained if there's any potential of freezing, also unneccessary with stone or bricks.  Finally, bricks won't corrode the vessel.
Comment: @Harper - I agree with everything you say, but the fact is that these heaters are built as simple electric resistance heaters to take advantage of lower off-peak electric rates.  From what I can find, the bricks are heated to very high temperatures, and very well-insulated.  I found a thesis which studied thermal performance of one of these heaters, and it states that the internal temperature reaches the 600 deg C range (see pages 70 and 83, for example): http://www.esru.strath.ac.uk/Documents/MSc_2013/Becerril.pdf
Comment: Whoever is using bricks has never taken a physics course.  Grams don't store heat. Atoms store heat.  238g of U238 stores *roughly* the same amount of heat as 7g of Li7. The densest thermal storage medium isn't even a question, water is either the highest or rounding error away from the highest, due to packing 3 atoms into 18g/mol and high molar density. Nevermind the advantages of cost, pumpability and toxicity.
Comment: The problem with using hundreds of degrees is now you must insulate it to extremes   Heat loss is proportional to temperature differential.  High temp requires much higher insulation value. You must also protect a high temp source from precious fingers and from starting fires. It's also precludes heat pumping, forcing you to inefficient resistive/ fuel heat. The bolt-to-wall. Units that replace radiators are just unworkable, as they are too small to insulate.
Comment: if it can get 4-6X hotter (over ambient)  it can store more heat than water, which can't be heated much.
Comment: @dandavis but then you have to insulate it.  Everyone is armwaving the insulation issue.   Thermal leakage through insulation us proportional to delta-T: a mass with 600C difference leaks energy 20x faster than a mass with 30C delta-T *given same insulation*.  Remember the goal here is to make it through an 8-12 hour period so you can move cheap midnight energy to the 5pm peak.  Read Mark's linked report, the passive units leak 80% of their "storage" through their insulation, all uncommanded, undesired heat.  Topped up at 7am, how warm will it be at 6pm when you are in peak and want the heat?
Comment: @Harper: true. depending on the duty cycle, you probably want a mix of materials to customize the time/temp curves for your climate and indoor conditions.
Answer: Good observation on the relative merits of water.
However, your key assumption about relative heat capacity is almost certainly wrong: Many common metals have volumetric heat capacity exceeding half that of water.  And many ceramics have higher heat capacity than water!
You could still argue that it would be cheaper to produce and ship these storage heaters empty, and then fill them with water once they're installed.  But then you would have to consider the unique drawbacks of water:

It is corrosive to many metals
It expands when heated (and also if frozen)
It can't be heated beyond its relatively low boiling point in a non-pressurized system
If its container leaks it causes a lot of collateral damage.

Plumbers tend to view water heaters like time bombs: No matter how exotic the alloys and coatings used in their containers, the effects of expansion and contraction seem to always find a way to break them.  I.e., it's just a question of when, not if water heaters will leak.
Granted, it is possible to build water-based heat systems that last for generations without leaking or failing.  But in a smaller system it might not be – in fact, as you observe, evidently is not – cost effective.
Comment: Here's a figure from a study of materials for this application.  The goal was to find the most cost-effective material with high heat storage capacity and high maximum use temperature.  It points to bricks as the preferred solution.  http://www.grantadesign.com/education/InDepth/html/indepth/materialcasestudies/ces6fua.htm
Comment: @mark That chart certainly reflects a preconceived notion of using **very, very high** 1000K-ish temperatures to do the heat storage. *Sweet Lily Allen, what do they use for insulation, Space Shuttle tiles?* But you need to be that hot to store a meaningful amount of heat at a mass workable for a bolt-up appliance. Problem is those temperatures bet all the marbles on resistive electric heat (even fuel is a challenge at 1000K).  It makes insulation challenging (our go-to, styrofoam, is right out).
Comment: @Harper - You're close - While looking into this I saw a reference somewhere to Aerogel insulation, which is a very high performance insulation material that I think was developed at NASA!  I can't find the reference now though.  Believe me, I don't think these are a good idea, and would never buy one, for all the reasons you mentioned.  But apparently they were developed back in the 1950s as a way to shift electric use out of peak periods to take advantage of lower rates.  Heat pumps weren't an option then.
Answer: The better-made storage heaters will use materials optimised for the task
Feolite has

specific heat = 920.0 J·kg−1·°C−1,
density = 3,900 kg·m−3,
thermal conductivity = 2.1 W·m−1·°C−1.
maximum operating temperature 1000 °C.

Water has

specific heat = 4184 J·kg−1·°C−1
density 1,000 kg·m−3,
thermal conductivity = 0.591 W·m−1·°C−1.
maximum operating temperature <100 °C unpressurised.

Footnote
These things are heated up using half-price electricity overnight. You have to have a dual-rate meter and dual-rate tariff (e.g. "Economy 7" in UK). The heater's core is surrounded by insulation so that most of the stored heat is retained until needed. When heat is needed, air is blown through the core to extract the heat.

Image source
Comment: So the Feolite has a similar volumetric capacity (3.588 "units") vs water (4.184) at the same temperature - but can be used at 10x the temperature - giving a significantly higher storage capacity?
Comment: How do they pump/circulate the feolite?  Seems like any pump would suffer abrasion damage.  If not pumping, how do they efficiently interchange heat when they want it and insulate it when they don't? Motorized insulation plugs?
Comment: @Harper - there's no pumping - they are just piles of bricks with heating elements running through them.  Air blows across and through the bricks to distribute the heat when needed.
Comment: @Harper: Good question, I should have made that clearer, answer updated.
Comment: Nice, dense material this feolite is.
Answer: Fire and air: cheap and bolt-up
These things are sold for a few hundred dollars and are intended to "bolt up" to any wall in the normal place a wall heater goes.
The "cheap" requirement forecloses any possibility of using efficient tech like a heat pump.  They use simple (but rather expensive) resistive heating.  That's wasteful.
The "bolt-up" requirement requires light weight and small size - so a storage reservoir of meaningful size is impossible - it would collapse the floor.  Instead they use very high temperatures to store the heat in a sane-sized mass. The high temps won't play with heat pumps or passive solar, the only option at those temps is appallingly inefficient electric resistive heating.
That is your answer: they can't use water because they need to make the unit Very Hot to store a meaningful amount of heat in small space and mass.
Loss through insulation is proportional to temperature differential / insulation value.  So very high temps require very good insulation. Temperatures pushing 1000K preclude easy, cheap styrofoam or fiberglass, leaving the asbestos family of rock wools or other silicates. many of(and very balky insulation since most insulation does not like 1000K temps, leaving you in the asbestos family, yay).
You have to pay the piper, either in huge mass, or potent insulation to contain lots of heat.  If you don't pay the piper, the device doesn't work very well.
Looking at the units I see on the Web, indeed, they do leak like a sieve, the convection units losing 80% of their heat via uncontrolled loss through the weak insulation.   This makes them rather hard to control.
I remain skeptical that these small units can really time-shift heat the 8-12 hours needed to exploit evening electric rates.   Where they show real potential is demand side management: the utility commanding heaters to turn off momentarily rather than spinning up a peaker. This ability greatly improves the resiliency of the grid, as it can effortlessly shed load if overloaded.  If these are being pushed in your area, I suspect that is the agenda.
This for sure: because they store energy for such a short time, they are 100% energy efficient.  Since there is no escape for heat but the living space, the only way these units fall below 100% is if they time-shift heat to times it is undesired. E.g. By leaking.
But they also cannot exceed 100%. We can do much better.
Water.  Do everything, be everything.
Or safe propylene glycol antifreeze.  "oh no, you can't run water at pyrophilic temperatures" Darn right. This is a completely different approach, and it is much cooler.  The working temps would be 10-70C (in heat mode), so no need to cap the tank.  Which goes somewher where leaks won't matter.
The delta-T being so small, we need a MUCH larger thermal mass but insulation losses will be 1/10. We also benefit from square-cube law: cube the volume, only square the envelope size.
You install a large tank, either as a cistern (with proper drainage) or outdoors and make up for it with better insulation. Any common agricultural tank will do.  12"+ of styrofoam would be good.  The delta-T is 60C not 600C, so the insulation could be less, but it's easy with materials like styrofoam available, so go for a lot more.  You'd use a hefty sized tank right-sized for your load - 1000 gal. would not be excessive if your design engineering called for it.
You have many options to add heat to such a low-temp tank - fuel, solar collectors, resistive electric if you really want to, but the darling will be heat pumping because it will run 200-400% efficiency.  In fall/spring, the heat it pumps in at night could be the heat you rejected by day using its air conditioning mode.
Then you'd use heat pumps to transfer the heat into the house - if the tank is 60C and you want your heat pump outputting 40C air, that heat transfer will be VERY efficient because it is "downhill" for the heat pump.  You're simply using the heat pump to transport the heat from place X to place Y.
Heat pumps which do this aren't uncommon, they are used in large complexes which circulate "service water" at 70 degrees for both A/C and heat.  In summer they use cooling towers, in winter the boiler room heats the water with fuel (gas).
I mentioned "heat mode".  Heat pumps reverse into air conditioners, so this system comes with A/C. At night your heat pump chills the tank, dumping to ambient or house heat.  If the tank can abide freezing, water wins massively in A/C mode: the enthalpy of fusion lets you store an insane amount of cooling power. (too bad you can't find a substance that freezes at 25C). By day, you pump heat from the house out to the tank - "downhill" again.  If dump freon temperature exceeds ambient outside air, you can cool to ambient before dumping in the tank.
Earth: build the thermal storage into the house
In this case, you use an even lower delta-T and even more storage material: the masonry construction materials of the house itself. This is obviously not a bolt-on, but passive thermal design from the outset.
In this case a high-thermal-mass construction material is used, and generous insulation is placed on the outside. As a result the building envelope strongly resists change to interior temperature, and itself stores the heat that we are time-shifting.
Dealing with only a 5-10 degree delta-T, proportionately more mass is needed. Insulation has less work to do, but it is still important.
Implementation is easy: any commercial off-the-shelf HVAC equipment will suffice. Using the thermal storage is just a matter of timing thermostat settings.
If that does not suffice and the homeowner wants something more on-demand, it would combine nicely with a water system, and the "water" could even be an enormous chunk of concrete.
Comment: i heard the school obama went to in hawaii makes ice at night to cool during the day.


B is a subring of A and f is a homomorphism

Question:
Let $A$ and $B$ be rings, and $f: A \rightarrow B$ a homomorphism. Prove that $f(A)=\{f(x): x\in A\}$ is a subring of B.

To begin, I need to prove there are subtraction and multiplication for $B$ to be a subring. I've started with attempting to prove $a+(-b) \in f(A)$ for $a,b\in A$.
So $f(a)$ and $f(b)$ are in $f$ because $f$ is a homomorphism. So $f(a+b)$ is also in $f(A)$ thus $f(a+(-b))\in f(A)$ so $a+(-b)\in A$
Now proving $ab\in f(A)$ for $a,b \in A$. I started with $f(a)$ and $f(b) \in f$ because $f$ is a homomorphism, thus $f(ab)$ is also in $f(A)$. QED and B is a subring?
Comment: Could you clarify a bit? $A$ and $B$ are only related by homomorphism, so they're not guaranteed to have the same elements. In the second sentence of your proof, you let $a + (-b) \in f(A) \subset B$, but also $a, b, \in A$. This wouldn't make sense, for instance, if $A$ was a cyclic ring and $B$ was the set of all movements on a Rubik's Cube.
Comment: I guess they wouldn't share elements per say. I know elements of $A$ are mapped to $B$ and elements of $A$ are mapped to $f(A)$ so are $B$ and $f(A)$ should relate
Answer: We want to show that :

$1_{B}\in f(A)$
$a,b\in f(A)\Rightarrow a-b\in f(A)$
$a,b\in f(A)\Rightarrow ab\in f(A)$

Let $a=f(c)$, $b=f(d)$, for $c,d\in A$

The first should be obvious.
For the second observe that $f(c)-f(d)=f(c-d)\in f(A)$.
For the third observe that $f(c)f(d)=f(cd)\in f(A)$.


How to extend a JavaScript prototype in the Servoy Framework?

Question: I am developing in the Servoy Rapid Application Development Tool using the Servoy JavaScript Framework and having difficulty extending an object via adding methods to it's prototype.
In normal JavaScript you can extend the object's prototype to add methods. This technique is used to save memory when you want to have multiple instances of a class and do not want each object to redefine the same method in memory.
When I try to do this in the Servoy JavaScript framework, Servoy throws an error, here is my code:
<code>// Create the object
function Person(firstname, lastname) {
    this.firstname = firstname;
    this.lastname = lastname;
}
Person.prototype.greet = function () {
    application.output('Hello, my name is '+this.firstname);
    return;
}
Person.prototype.stateFullName = function () {
    application.output('My full name is: '+this.firstname+' '+this.lastname);
    return;
}
</code>
This code throws the following error in Servoy:
<code>The property greet is undefined for the javascript type Object
</code>
How can I extend an object using prototype in the Servoy environment without this error being thrown?
Comment: Note: I would like to tag this question as "Servoy" but I don't have enough reputation to create the tag, if somebody with enough reputation would create the tag for me it would be much appreciated.
Answer: To prevent Servoy from throwing the error you must wrap it in an immediately invoked function and store it in a variable. When Servoy reads the JavaScript file it will see the immediately invoked function, execute it and in turn store the prototype modifications into memory:
Here is the code:
<code>// Create the object
function Person(firstname, lastname) {
    this.firstname = firstname;
    this.lastname = lastname;
}

// Extend prototype to add methods:
var seeMyPersonPrototypeExtensionsServoy = function(){

    Person.prototype = {

        greet: function () {
            application.output('Hello, my name is '+this.firstname);
            return;
        },

        stateFullName: function() {
            application.output('My full name is: '+this.firstname+' '+this.lastname);
            return;
        }
    };

}();
</code>
Servoy will no longer throw the error when you wrap the prototype extensions in this manner.


In extjs4 Ext.MessageBox.alert() msg disalays blank window?

Question: I am working in extjs4 and i am going to print a message box on screen but it displays a blank message window.Nothig displays in it.
here is my code:-
<code>Ext.application({
    name: 'App',

    appFolder: 'app',

    //controllers: ['Books'],
    requires:[
                 'Ext.window.MessageBox',
              //   'Ext.tip.*'
             ],
    launch: function() {
        Ext.create('Ext.tab.Panel', {
            renderTo: Ext.getBody(),
            height: 100,
            width: 200,
            items: [
                {
                    // Explicitly define the xtype of this Component configuration.
                    // This tells the Container (the tab panel in this case)
                    // to instantiate a Ext.panel.Panel when it deems necessary
                    xtype: 'panel',
                    title: 'Tab One',
                    html: 'The first tab',
                    listeners: {
                        render: function() {
                           //Ext.MessageBox.alert('Rendered One', 'Tab One was rendered.');
                             Ext.Msg.alert('hi', 'Please enter your name:');
                            //Ext.MessageBox.confirm('Confirm', 'Are you sure you want to do that?');
                            //alert("hi");

                        }
                    }
                },
                {
                    // this component configuration does not have an xtype since 'panel' is the default
                    // xtype for all Component configurations in a Container
                    title: 'Tab Two',
                    html: 'The second tab',
                    listeners: {
                        render: function() {
                            //Ext.MessageBox.alert('Rendered One', 'Tab Two was rendered.');
                        }
                    }
                }
            ]
        });
    }
});
</code>
and here is the message screen window

there is no any messageBox method working whats wrong in this code?
please give me some suggestions...
Comment: These links might be Helpful: http://www.c4learn.com/alert-message-box-in-extjs.html and http://www.sencha.com/forum/archive/index.php/t-184113.html?s=550da2024ec35b4a06fc2e26241a9171
Comment: I'm not sure why you are displaying a message when a penel renders.. If you put it on the bottom of the `launch: function()`, is it working then? Is the `Ext.MessageBox.confirm` and normal `alert()` working as you expect?
Comment: I am referring code from following link http://docs.sencha.com/ext-js/4-1/#!/guide/components
Answer: Use 'boxready' event (jsfiddle).
If output to the console:
<code>...
render: function() {
    console.log(Ext.Msg.alert('hi', 'Alert message'))
}
....
</code>
in the 'render' listener, you will see that were incorrectly calculated the size and position of the alert:
<code>...
width: NaN
x: -41
...
</code>


What's the easy way to add ldap support for a simple golang web app?

Question: I have an internal tool written in golang, with a simple web interface which is just a single web page.
Now I need to add a "login with ldap" feature but don't know much about the web stuff, is there something like a "middleware" which I could simply plug into my application without introducing a whole "web framework"?
Answer: The first part of this is the UX - if you go with HTTP basic authentication, you can probably avoid writing any code, assuming there's a webserver in front of your app most will have authentication support. If you want to stick to go, http.Request makes handling basic pretty easy, and there are many ways of composing net/http based handlers together, so bikeshed away.
If you require an integrated login form, then of course you'll have to write that logic, but you can take a micro service style approach, and implement that logic by calling to an HTTP basic auth based service internally. I think this approach makes sense if you prefer to use a generic LDAP authentication (e.g. nginx/apache module or something like that), but not if you want to talk to the LDAP server yourself.
As for the actual credentials, if you do need to do that manually, there are multiple LDAP implementations in go. I've had success with go-ldap for both binding and legacy password validation by fetching fields as an admin user.


Python "if" statement changes variable value

Question: This code is from a beginning python book I'm studying, the chapter is discussing Dictionaries.
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }

friends = ['phil','sarah']

for name in favorite_languages.keys():
    print(name.title())

    if name in friends:
        print(" hi " +name.title() +
            ", i see your favorite language is " +
            favorite_languages[name].title() + "!")

The result is:

Jen
Ed
Phil
 hi Phil, i see your favorite language is Python!
 hi Sarah, i see your favorite language is C!

I'm having trouble understanding the logic of the code relative to the varible "name" and why the value changed. Meaning, the variable "name" is created by the "for" loop and all the Dictionary keys are stored in it, so that when the "if" statement begins the value of "name" is all keys.
My understanding of the "if" statement is that it just returns a boolean value of true or false, in this case true. But why does the value of "name" (as a result of this "if" statement) get changed to the value of "friends" at this point?
Is it just a rule that is built into Python? Because it does not logically follow, unless I'm missing something.
It would make more sense to me to write it:
if friends in name:
    print(" hi " friends.title() +

Comment: 'All the dictionary keys' are not stored in name, name takes on the value of each key one at a time. Maybe you should try for loops with a simpler example because it seems you do not yet understand how they work.
Comment: It doesn't and I can't understand why you think it does. And no, `name` is not "all the keys" - it is defined by the for loop, and takes the value of *each* item in the dictionary in turn - as demonstrated by the first `print()`. It is not modified by the if statement.
Comment: The output doesn't match the code.
Answer: "...the variable "name" is created by the "for" loop and all the Dictionary keys are stored in it,"
I think that's your misconception. The line for name in favorite_languages.keys(): does not store all the keys in the variable name. It means, for for each entry in the keys, execute the following code (the "suite"), one at a time, with the variable name set to a different entry each time.
So if favorite_languages.keys() is ['jen', 'sarah', 'edward', 'phil'], execute the suite four times: once with name set to 'jen'; once with it set to 'sarah', once with it set to 'edward' and once with it set to 'phil'.
Comment: Thanks, I get it now.
Answer: to the keys in the dictionary is assigned the identifier name in the for loop, the key is the string before the : in a dictionary
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}

friends = ['phil','sarah']

for name in favorite_languages.keys():
    print(name.title())

    if name in friends:
        print(" hi " +name.title() +
            ", i see your favorite language is " +
            favorite_languages[name].title() + "!")

so the for-loop iterates through any key in the dictionary and prints its value with the title() method
in addition the if-statement determines if the key ( = name ) is existent in the list friends, if this is true it executes the linked code, if it is false it doesn't
the exact output is
Sarah
 hi Sarah, i see your favorite language is C!
Edward
Jen
Phil
 hi Phil, i see your favorite language is Python!

for-loop greps key 'Sarah', if-statement checks if it is in list friends : is true so print
for-loop greps key 'Edward', if-statement checks if it is in list friends : is false so no print
for-loop greps key 'Jen', if-statement checks if it is in list friends : is false so no print
for-loop greps key 'Phil', if-statement checks if it is in list friends : is true so print

in the dictionary the value that is associated with a key is accessed with [key].title(), in this case [name].title() because name is used as identifier for the keys


Pushing to a different remote repository

Question: Let's say I have a local repository A and also I have access to remote repository B. These repositories are completely different! I want to push all files/commits etc... from A to B repository.
So I did following git commands:

git remote add origin <my remote git url>
git push origin master

And I got the following error:
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.

The reason of question is that I don't want to do git pull command because B repository taking up a lot of space (tons of gigabytes!) while A repository take couple of kilobytes.
Is there any way to push without a pull?
Comment: Push to a branch that does not exist in the remote.  (eg, create a new branch on the remote)
Comment: AFAIK you can't "push files from A to B". Commits are snapshots of all files, and commits are what get "pushed and pulled". - but then this question doesn't seem to be asking that
Answer: Create a new branch on the remote:
git push origin master:my-branch

Then, on the remote, you'll probably want to add your work to the master branch.  One way to do that is:
git checkout my-branch
git rebase master
git checkout master
git merge my-branch

Comment: Thank you! that's what i needed


Using lxml in Python, I need to replace "RNA" with RNA in input xml file. Code below

Question:
My input XML file is:

<?xml version='1.0' encoding='UTF-8'?>
<try>
something somethingRNA and RNA in RNA.
</try>

My Python Code:

import lxml.etree as ET
import openpyxl
import re

url = 'output_15012015_test.xml'

tree = ET.parse(url)

lncrna = "RNA"
abstract = tree.xpath('//try)

string = abstract[0].text

if(abstract):
        anotherString = re.sub(r'\b'+lncrna.lower()+'\\b', ''+lncrna+'', string.lower())

abstract[0].text = anotherString
print abstract[0].text
tree.write('FalseRoller.xml', encoding='UTF-8', pretty_print=True)

Output

I get the following replaced text instead of RNA
 <mark>RNA</mark>

I think it has to do with tree.write() method. Also I'm new to Python and the community. Please help me with this.
Comment: I've edited my answer; hope it helps
Answer: You are setting an XML mark in element .text, so when writing to XML it is interpreted as text, not markup, and characters are escaped with &...;.
What you want to do is:

divide .text into three parts: before new tag, in new tag,
after new tag
add new tag and set texts and tails

See code:
tree = ET.parse(url)

lncrna = "RNA"
abstract = tree.xpath('//try')

aList = re.split(r'(\b'+lncrna+r'\b)', abstract[0].text, flags=re.IGNORECASE)

abstract[0].text = aList[0]
for i in range(1,len(aList),2):
  anElement = ET.SubElement(abstract[0], 'mark')
  anElement.text = aList[i]
  anElement.tail = aList[i+1]
  abstract[0].insert( (i-1)/2, anElement )

print abstract[0].text
tree.write('FalseRoller.xml', encoding='UTF-8', pretty_print=True)

Comment: This works perfectly. But I can't understand how ONLY "RNA" is enclosed in  and not the other "re.split" returned strings.
Comment: `i` jumps by 2, i.e. 1, 3, 5,... If pattern in `re.split` is in enclosed in parentheses, then match is placed in result list at these places https://docs.python.org/2/library/re.html#re.split
Comment: Thank you for the missing piece! It did seem like the logical thing but this is the first time I have come across such a concept. I would vote up your answer once I have enough rep.
Comment: Would this be a prob if the first string returned was "RNA". Something like:

RNA something somethingRNA and RNA in RNA.


Why eslint throw error when I want check array length?

Question: why eslint throw error ( no-unused-expression ). I simply want to check if array is empty or not, and execute dispatch.
 useEffect(() => {
    let totalPrice = 0;
    // eslint-disable-next-line no-unused-expressions
    cart.length
      ? cart.forEach((item: AsideItemInterface) => {
        totalPrice += item.quantity * item.price;
        dispatch(setTotal(totalPrice));
      })
      : dispatch(setTotal(0));
  }, [cart]);

If, I remove eslint-disable-next-line, get error.
Comment: is the value of cart async? try  `cart?.length`
Comment: What is the error? Also where is cart defined? What is cart initial value?
Answer: The problem is you're writing an expression that has a value result, but you're not using that result. More specifically, you're using the ? : operators like an if statement. The solution is to write the if statement that you're actually using (i.e if (cart.length) { ... } else { ... }).


Autotyping with "enter" and a delay

Question: I'm basically lost. I am looking for a way to automatically type a message and ENTER After it, with a 3 hour delay. I can't seem to find it, AT ALL. I just want to type something and ENTER after it each 3 hours automatically. I have tried to find that for so long and i can't seem to find anything that works and types ENTER and has a delay.
EDIT :: Okay, I used AutoHotKey. It worked, delay worked, but it can't type the "+" symbol. My main purpose required the + symbol and it was the most important in all of it. Why can't AutoHotKey type +'s?
Answer: A general-purpose solution to keyboard automation is AutoHotkey. AHK allows you to write scripts which automatically perform some behavior. The following script will:

Wait 3 hours (10800000 milliseconds)
Type the message defined in Message
Press ENTER
Repeat until stopped (by pressing Ctrl + N)

The script:
; Change the value to the right of the = to what you want to type
Message = My unquoted awesome message

; Enable with Ctrl + M
^m::
SetTimer, SendMessage, 10800000 ; 3 hours = 1000 * 60 * 60 * 3
Return

; Disable with Ctrl + N
^n::
SetTimer, SendMessage, off
return

SendMessage:
Send, %Message%{Enter}
Return

Answer: As Michael suggested AHK is a great option for automating things. You install it then you can create scripts. Basically just open a notepad and save the file as a someFileName.ahk which you can then double click to run.
Firstly if you want to have it be different text you might want to user InputBox for getting that.
So for example you could do something like:
; Kick off the script with Ctrl + M
^m::
InputBox, messageVar, Your Title for the Window, Please enter some text:, , 300, 150

if ErrorLevel
    ; The cancel button was pressed so return
    return

; Negative number will only run once after the specified amount of time.
SetTimer, SendMessage, -10800000 ; 3 hours = 1000 * 60 * 60 * 3
return

SendMessage:
Send, %messageVar%{Enter}
Return

If you want it to repeat mix this with Michaels suggestion.

Autotyping with "enter" and a delay


Why is there a reserved spot in the Launcher?

Question: Why is there a spot reserved for a Launcher icon?  See the arrow in the image, please.  Is this a missing icon?  Hovering reveals nothing.  Hover-right-click provides an unlock-from-launcher option.

Edit: I was requested to click it.  Nothing happens upon a click. Well at least I don't have much evidence that anything happened when I clicked it. I hope it doesn't launch nuclear missiles.
Comment: and clicking it starts a program? >:)
Comment: If clicking this starts a program, please edit your question to provide more information, including what program starts (or any information you can see about what is going on). If clicking this spot does nothing, you've probably found a bug in unity; in that case, I recommend [reporting this as a bug](https://help.ubuntu.com/community/ReportingBugs/).
Comment: Clicking it does nothing.
Answer: log out or restart your computer. I've had this happen before, you've probably got an additional program drug into your launch menu but Unity hasn't caught up to displaying it. After restarting the icon of whatever program you've placed there should become visible (or the space will disappear.)
EDIT: Also, there are some programs which do not play nice with Unity and create extra icons in it's launch bar. They're usually programs you already have in it but they don't know how to tell that they're already in it so they make more icons for themselves.
Comment: Reboots do not cause the icon to appear and the blank space remains.  I unlocked the blank icon from the launcher since I probably don't need to invoke something that does nothing.
Comment: If it happens again I'd probably start looking at the program you ran right before it happened. This is usually the culprit.


Delta Dirac and duality property

Question: I know that the property of duality says:
$$x(t) \iff X(f)$$
$$X(t) \iff x(-f) "="x(t=-f)$$
and I know that:
$$\delta(t-t_0) \iff exp(-j2\pi ft_0)$$
If I apply the duality property, I get:
$$exp(-j2\pi f_0t) \iff \delta(-f-f_0)$$
$$exp(j2\pi f_0t) \iff \delta(f-f_0)$$
instead the correct result is:
$$exp(j2\pi f_0t) \iff \delta(f+f_0)$$
Why?
Thank you for your help.
Comment: I guess $exp(j2\pi f_0t) \iff \delta(f-f_0)$ is correct, while $exp(j2\pi f_0t) \iff \delta(f+f_0)$ is false.
Answer: I think you're getting confused between $t$ and $f$ , Duality says

$$x(t) \Leftrightarrow X(\omega) \implies X(t)\Leftrightarrow2\pi x(-\omega) $$
  Or in terms of $f$
  $$x(t) \Leftrightarrow X(f) \implies X(t)\Leftrightarrow x(-f) $$

So for $\delta(t-t_0)$
$$\delta(t-t_0)  \Leftrightarrow \mathrm{exp}(-jt_0 2\pi f) \implies \mathrm{exp}(-jt_02\pi t) \Leftrightarrow \delta(-f-t_{0})=\delta(f+t_0)$$
And for $\delta(t+t_0)$
$$\delta(t+t_0)  \Leftrightarrow \mathrm{exp}(jt_0 2\pi f) \implies \mathrm{exp}(jt_02\pi t) \Leftrightarrow \delta(-f+t_{0})=\delta(f-t_0)$$
Note that $\delta(t)$ is even function
Please let me know if i can improve my answer somehow , thanks !
Comment: http://fourier.eng.hmc.edu/e101/lectures/handout3/node2.html#Symmetry see the proof on this page
Comment: Hi @Lelouch.D.Light. Why did you write $2\pi x(-\omega )$? I know that $\omega = 2\pi f$, thus I expect $\frac{x(-\omega )}{2\pi}$.

Delta Dirac and duality property


image first or text content first?

Question: Lets consider the following senario:
I'm building a website for a mobile application and I have to create a text/image walkthrough for new users.
Should I set first the text content and then add the image that is reffering to the text's content or vice versa??
According to that question I should use image first, and text after(something like caption).
But 1)text and image on a tutorial-like page, both have the same importance and 2) I may use 6-10 images on the same page, so it seems logical that I could set text first and image as an explanation.
So should image be used first, or text??
Answer: Can the one survive without the other?
If you leave out the text, will people still understand the walkthrough?
And vice versa, will people still understand the walkthrough if you leave out the images?
This way you can determine which content is primary.
If your images tell the whole story I would show the images first and support those with text. This works best if the text are just short sentences, one per image like some image caption.
If your text tells it all I would place that first and later add the images to visually support the text.
Answer: The image goes first if it demonstrates the objective you're after and the text is just a caption for it.
The text should be first when it describes what you want the users to know, while the image is only demonstrative and plain.

image first or text content first?


Windows 8.1 app not listed in Windows 10 store?

Question: I have a Windows store app (made for Windows 8.1). After upgrading to Windows 10, I was able to install my app without problems.
I was always able to find my app through the category and the top charts. But now, I cannot find it at all. Only when I search for a keyword related to the app, it shows up as expected.
Is that normal? What could be the reason?
Answer: I have contacted Microsoft regarding this matter and received a reply.
It appears that Microsoft has changed the chart listing algorithm in Windows 10, kicking all apps out (from Windows 8/8.1) that are not cross-platform pc-mobile. You can still find the applications by the search, but they are not visible in any charts anymore.


Can't restore 2017 (1200) Tabular model in 2016 DB (also 1200)

Question: I developed a tabular model using a 2017 Developer DB for both data source and deployment server. Compatibility level set to 1200.
From the deployment server, I backed it up to as ABF file which I moved to a 2016 Developer server and tried to restore it.
The server gave me "The embedded PowerPivot data in the workbook cannot be loaded due to a version mismatch." error.
(Screenshot : https://i.stack.imgur.com/jE0qE.jpg )
I don't understand what PowerPivot has to do with anything.
Also shouldn't I be able to import if the compatibility levels are the same?
Help please!
Answer: As I know, we usually restore an older version database on a newer version(cannot restore a database from new to an earlier version of Analysis Services).
In addition, when you restore, you need to make sure location must be the same server type.
Zoe


Does rewarding of daily tasks drive away a group of users?

Question: I noticed that some websites invite me to do a particular kind of activity daily. For example, Duolingo would challenge me to learn a language for 10 days in a row and StackExchange would give me a gold badge if I kept visiting the website for 100 days. I am under the impression that it doesn't really motivate me because I prefer to work in bursts (for example, do a three-days work in a day then rest for two days) compared to keeping a daily routine. I feel that I could have gone away from Duolingo because I couldn't keep up with their suggested pace and I wonder if it actually works like this. If so, what would a better solution, one that motivates both me and the users that actually can do a chunk of a task daily?
Comment: changing an icon on Facebook drives away a group of users -- :)
Answer: This is an interesting question, but I think if you look at some other websites or apps, they will cater for both types of user behaviours. For example, they will provide a reward or badge for continuous login/visits, and they will also provide a reward or badge for a burst of activity (e.g. 10 posts in one day). So you can see in StackExchange that there are badges for these types of behaviours, and there are even badges for people who have been using the website for an extended period of time (probably to reward loyalty and long term involvement) as well as reward for people who have participated at a specific time (e.g. during moderator election).
Although you can also see this as a way for them to drive their users to what they believe is the optimal process for learning languages (in Duolingo's case anyway), where steady progress is the preferred approach to build on existing knowledge, rather than short bursts since you will tend to forget things when the memory is overloaded.
Comment: Thanks for the insightful answer :) One detail - you cut the end of sentence in the first paragraph, I wonder what you meant there.
Comment: @d33tah thanks for picking that up. I added it back into my answer.
Answer: (How) do rewards work?
The connection between rewards and motivation is quite complex, and is more on the side of "rewards reduce motivation", despite the superficial appearance of increasing it. They induce you to do a task, while lowering your intrinsic motivation of it, making it less likely that you will pick up the task again another time, and also reduce your desire to do the task properly. For a more thorough explanation, there are popular science books like Punished by rewards by Kohn, as well as a sizeable body of academic literature. What you describe is one of the common side effects of rewards.
Gamification and motivation
In my observation, gamified sites end up with three groups of users (note a user can change his type over time):

Users "hooked" by the gamification. For them, the ratio of reward desirability to effort is favorable. This happens usually when the user unconsciously ties the badges (or rep points) to a powerful internal motivator such as "proof that I'm good at something". It is also more likely to happen if the task for which they get points has a low drudgery factor or was deliberately engineered to induce flow, such as most actual games (1).
Users who are not influenced by the gamification. They disregard all the badges and points and concentrate on the task at hand. Their interaction with the site depends on their intrinsic motivation only.
Users slightly to severely demotivated by the rewards. Of course, the gamification rewards are not the only contributor to their motivation, so even when their influence is negative, many users have enough total motivation to continue using the site. It is just a bit harder to do so, so they use it less, or do the tasks more mechanically and with less pleasure, or under more stress. The "more stress" part is the one you pointed out, in this case feeling that you have to invest time when it's not convenient to you just to keep up with the badge.

The explanation above stems from my general knowledge of the working of rewards, as well as observation. I am not aware of any quantitative studies which do this specifically for web site users. It would be very interesting to know what is the proportion of users whose motivation is helped by rewards (first group) to the ones harmed (third group), but I am not aware of such studies. But anecdotally, I'd say that most people do not internalize the badges of a random website they use as an important personal goal.
What can you do?
As for the "what can I do" part: As the website builder, there is not much you can do about it. You can stop pestering your users with so many rewards, reducing both the pull on group 1 and the push against group 3. You can also try to tie your rewards to the users' emotional needs - a good example of this is the recent Stack Overflow user profile redo, in which they added an estimation called "X people helped" - it is an inaccurate heuristic based on page views, but it sure feels good to see a number saying that I help people :)
Making the task more pleasant for the user is rarely an option. Assuming that you have built your site well, there is no way to do such a change without changing your complete business model. No matter what the author of a tax-filing software does, he cannot make the task itself fun.
If you are the user of a gamified site, the best option is to try to enter the second group - cultivate a mild disinterest for all these badges and focus on learning in Duolingo for learning's sake. Being in the third group is really a bummer, because not only do you achieve less of your goal, it is also less pleasant doing so. Being in the first group might make you achieve more of your goal, but it comes at a cost. We have enough stress in our lives and have to allocate our attention to a few worthy goals. Among all the gamified sites you sign up for, very few or none deserve becoming one of your primary goals - but being in the first group means you get hooked, exhibiting all the symptoms of a mild addiction, especially neglecting to do other, important things.

(1) A thing people don't get about gamification: What binds people to games is the combination of several factors, including simple goals. Introducing these goals, together with the metrics needed to track if they were reached, is what is widely known as "gamification". But if the other factors for a game are not in place, the result feels not at all gamelike.


Set a default build configuration for project

Question: I have several possible configurations in a Visual Studio project file. How can I specify which one is selected by default (when no .suo is present)? Right now, when I open the project in Visual Studio, Debug configuration is selected by default.
Relevant part of the project file:
<PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>...</ProductVersion>
    <SchemaVersion>...</SchemaVersion>
    <ProjectGuid>{...}</ProjectGuid>
    <OutputType>...</OutputType>
    <RootNamespace>...</RootNamespace>
    <AssemblyName>AAAAA</AssemblyName>
    <MyType>Windows</MyType>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>Full</DebugType>
    <DefineDebug>false</DefineDebug>
    <DefineTrace>true</DefineTrace>
    <Optimize>false</Optimize>
    <OutputPath>Bin\Release</OutputPath>
    <DocumentationFile>AAAAA.xml</DocumentationFile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <DefineDebug>true</DefineDebug>
    <DefineTrace>true</DefineTrace>
    <OutputPath>bin\</OutputPath>
    <DocumentationFile>AAAAA.xml</DocumentationFile>
    <PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>

I want this configuration to be selected by default:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>Full</DebugType>
    <DefineDebug>false</DefineDebug>
    <DefineTrace>true</DefineTrace>
    <Optimize>false</Optimize>
    <OutputPath>Bin\Release</OutputPath>
    <DocumentationFile>AAAAA.xml</DocumentationFile>
</PropertyGroup>

Comment: Not sure but try changing this like `Debug` to `Release`
Answer: Visual Studio always invokes the build through a solution. Each solution configuration has a (case-insensitive) name and maps each project to its configuration. Solution configurations can be edited through Build > Configuration manager and the currently active one is selected there or in the drop-down in the toolbar.
Which solution build configuration is used?
Active build configuration is saved in solution user options file (.suo). This is a per-user configuration and should not be checked in the source control. No shared configuration exists for this.
If no .suo file is present, VS selects the configuration, whose name sorts alphabetically first with several exceptions:

All names starting with "Debug" sort before "A".
S1␣S2 sorts before S1 for any two strings S1 and S2. (␣ denotes a space.)

E.g. if you have this list of configurations, "Debug all" is selected by default. If you remove the first configuration in the list, close VS and delete the *.suo file, the next one on the list will be selected by default.

Debug all
Debug
Debugging
A release
ARelease
Release
WinterBash

Note that VS displays a different order:

A release
ARelease
Debug
Debug all
Debugging
Release
WinterBash

Which solution is used?
If you open a project file (e.g. MyProject.csproj) directly, Visual Studio tries to locate a solution file.

Solution with the same name in the same directory (MyProject.sln) is preferred. If it is found, it is used.
Any other solutions in the same directory (*.sln) are searched. If exactly one is found, it is used.
The parent directory is searched for any solutions (..\*.sln). If exactly one is found, it is used.
Otherwise, VS creates a new solution (named MyProject.sln) containing only the project and asks on exit where to save it. This new solution's build configurations correspond to the ones the project has.

Note that this is probably going to be different in the upcoming VS 2017 as it supports even bare files without projects.
You can see the path to the solution as Path in Properties window. (Select the solution in Solution Explorer first.)

By the way, the first PropertyGroup in a project file specifies the defaults to be used by MSBuild when Configuration and Platform properties are empty (unspecified). Visual Studio always specifies these properties, so the defaults are irrelevant.
Comment: Do you know if S1.S2 sorts also before S1 for any two strings S1 and S2? It seems to me that way. I have the configurations Debug.Custom and Debug. When I clone the solution and open VS Debug.Custom is selected.
Comment: @dyedwiper, I have no time to test that but it seems even period character may be treated just like space. Wonder how they sort relatively, i.e. what is the order of "Debug Custom" versus "Debug.Custom". I have no official source for the sorting part of the answer, I remember figuring it out by trial and error and it takes some time to create the project and solution required to test this.
Answer: I believe the build configurations are listed alphabetically. Meaning the "Debug" configuration will be the default item. And "Release" will not be. If you wish Release to be the default configuration you can create a new build configuration and ensure it is displayed before "Debug", by using the alphabetic sorting, e.g. name the build configuration "ARelease".
Not a perfect solution, but it works.
Comment: It doesn't use alphabetical order. It prefers Debug or names starting with Debug by default if there is no .suo file. For example, Debug configuration will be selected even if there is configuration with name "ARelease"


wget to https://graph.facebook.com/cocacola error connection time out

Question: I have the following errors when I try to wget in my box:
wget https://graph.facebook.com/cocacola
--2012-11-07 14:01:27--  https://graph.facebook.com/cocacola
Resolving graph.facebook.com... 188.8.131.52, 2a03:2880:10:8f01:face:b00c:0:26
Connecting to graph.facebook.com|188.8.131.52|:443... failed: Connection timed out

Whats wrong? Port https is open in my firewall.
ACCEPT     tcp  --  anywhere             anywhere
state NEW tcp dpt:https

Can someone have solution for this problem?
Answer: It should work since it's just JSON returned and there is no access token needed
wget --no-check-certificate https://graph.facebook.com/cocacola


Image Stabilization Issue in LGV30

Question: Video suddenly zooming into the frame when recording starts in preview mode is known behavior, but the issue I am facing currently is the extreme jump in preview when using LGV30.

In pixel 1 XL and pixel 2 XL the jump is negligible
In Samsung S8+ the jump is visible but can be considered for the final smoother videos
But in LGV30 the jump is terrible, the video moves to the extreme top right corner of the preview and the final output quality of the video is worse than VGA.

I know that Image Stabilization is dependent on the combination of Sensor Orientation, Gyroscope and Accelerometer and the jump in video is decided by the quality of these sensors, but is there any way I can control the Jump in LGV30 or is it the hardware that has flaw.
I am writing down my configuration code for reference
mPreviewBuilder.set(CaptureRequest.COLOR_CORRECTION_MODE, CaptureRequest.COLOR_CORRECTION_MODE_FAST);
mPreviewBuilder.set(CaptureRequest.CONTROL_CAPTURE_INTENT, CaptureRequest.CONTROL_CAPTURE_INTENT_VIDEO_RECORD);
mPreviewBuilder.set(CaptureRequest.HOT_PIXEL_MODE, CaptureRequest.HOT_PIXEL_MODE_FAST);
mPreviewBuilder.set(CaptureRequest.EDGE_MODE, CaptureRequest.EDGE_MODE_FAST);
mPreviewBuilder.set(CaptureRequest.NOISE_REDUCTION_MODE, CaptureRequest.NOISE_REDUCTION_MODE_FAST);
mPreviewBuilder.set(CaptureRequest.TONEMAP_MODE, CaptureRequest.TONEMAP_MODE_FAST);
mPreviewBuilder.set(CaptureRequest.SHADING_MODE, CaptureRequest.SHADING_MODE_FAST);
mPreviewBuilder.set(CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE, CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_ON);

I assume that this jump can not be controlled, but is there any way to reduce the jump?
Answer: The solution turned out to be the wrong camera.
Sounds trivial but in this code
CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
manager.getCameraIdList()

The manager returns all the accessible camera for a given device.
In LGV30 since there are 2 rear cameras, one regular and another wide angle, I was accessing the wide angle camera.
Wide angle camera was not able to handle the Image Stabilization and was causing this issue. So the solution was to pick the first camera from the list for given camera facing. This is still a workaround because I couldn't figure out the API to check whether given camera is regular or workaround.
Details for above question is in How to check whether given Camera is regular camera or wide angle camera?

Image Stabilization Issue in LGV30


Maven and eclipse: a reliable way to add non-Maven or external jars to a project?

Question: Maven is great. It mostly keeps me out of jar dependency hell by specifying versions of dependent packages in the pom configuration, and applies them automatically. It also has great integration with Eclipse via m2e, so that things work seamlessly in an IDE.
This is all great for dependencies that are globally known to Maven. However, sometimes, there are libraries that need to be included in a project that is not available in the Maven repos. In this case, I usually add them to a lib/ directory in my project. As long as they are in the classpath then things compile.
However, the problem is getting them to be included automatically when importing a project. I've been tolerating this problem with half-baked fixes and hacks for far too long. Every time someone installs this project, I have to tell them to manually add the jars in lib/ to their Eclipse build path so that all the errors go away. Something like the following:

I'm searching for a way to automate this process in a way that works with both the mvn command line program and Eclipse: more an emphasis on Eclipse, because it's nice to have projects that just compile when you import them.
I don't want to set up a repo server for this, nor do I have any in-house proprietary components that would warrant setting up anything locally. I just have some jar files where the developers don't use Maven; and I want to compile with them...I should just be able to include them in the distribution of my software, right?
I'm really looking for a reasonable way to implement this that will also work in Eclipse with no fuss. This is one solution I've found promising, but
there definitely doesn't seem to be an authoritative solution to this problem. The only other thing that comes close is the maven-addjars-plugin, which works okay but only on the commandline. This plugin is not bad, and has a pretty reasonable configuration:
<plugin>
    <groupId>com.googlecode.addjars-maven-plugin</groupId>
    <artifactId>addjars-maven-plugin</artifactId>
    <version>1.0.5</version>
    <executions>
        <execution>
            <goals>
                <goal>add-jars</goal>
            </goals>
            <configuration>
                <resources>
                    <resource>
                        <directory>${project.basedir}/lib/java-aws-mturk</directory>
                    </resource>
                    <resource>
                        <directory>${project.basedir}/lib/not-in-maven</directory>
                    </resource>
                </resources>
            </configuration>
        </execution>
    </executions>
</plugin>

However, trying to get it to run in Eclipse involves adding the following mess about lifecycle mapping to your pom.xml, which I have never gotten to work; I don't even think it is configured to actually add anything to the Eclipse build path.
<pluginManagement>
    <plugins>

        <plugin>
            <groupId>org.eclipse.m2e</groupId>
            <artifactId>lifecycle-mapping</artifactId>
            <version>1.0.0</version>
            <configuration>
                <lifecycleMappingMetadata>
                    <pluginExecutions>
                        <pluginExecution>
                            <pluginExecutionFilter>
                                <groupId>
                                    com.googlecode.addjars-maven-plugin
                                </groupId>
                                <artifactId>
                                    addjars-maven-plugin
                                </artifactId>
                                <versionRange>
                                    [1.0.5,)
                                </versionRange>
                                <goals>
                                    <goal>add-jars</goal>
                                </goals>
                            </pluginExecutionFilter>
                            <action>
                                <execute />
                            </action>
                        </pluginExecution>
                    </pluginExecutions>
                </lifecycleMappingMetadata>
            </configuration>
        </plugin>
    </plugins>
</pluginManagement>

Comment: I'd prefer relying on a local nexus installation.
Comment: I want to be able to give this software to others to use, so that seems unreasonable. It's just a few jars that I want to share, so it shouldn't be that complicated.
Comment: Nexus (or any other repo implementation) would help your build process, so it would not be needed for your users; while if you are FOSS, maven-izing other's libraries and sending patches upstream would contribute to the community. Anyway, your choice.
Comment: I don't need it for users; I need it for other people who check out the code on github. I have some plugins and code (some from closed source) that it is not feasible to maven-ize, and it's not reasonable to expect to be able to do that for every dependency.
Comment: Refer this https://stackoverflow.com/a/45120371/1709793
Answer: 1) you can use system scope dependency
    <dependency>
        <groupId>test</groupId>
        <artifactId>x</artifactId>
        <version>1.0</version>
        <scope>system</scope>
        <systemPath>${basedir}/lib/x.jar</systemPath>
    </dependency>

2) you can copy your x.jar to local maven repository as
repository/test/x/1.0/x-1.0.jar
and add a dependency as
    <dependency>
        <groupId>test</groupId>
        <artifactId>x</artifactId>
        <version>1.0</version>
    </dependency>

Comment: I've found the system scope to influence the handling of transient dependencies further downstream and we could not use it.  I believe the proper way is to install (manually or scripted) the artifacts you need in your local repository.
Comment: That's EXACTLY what I needed. It also makes the jars available for projects dependent on this one. Integrates perfectly with Eclipse and avoids all this managing-repo and XML that everyone else is suggesting. Also doesn't involve copying crap into Maven repositories. +100 upvotes if I could.
Comment: @Andrew Mao Fine if this solution works for you. Beware of the fact, that [system scope dependencies are similar to "provided" dependencies](http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Scope). Thus they are expected to exist on a target platform and will not be included in the packaged artifact (e.g. war file).
Comment: If I use the system scope, are the `groupId` and `artifactId` even relevant? (i.e. can I just put whatever in those fields?) As these jars aren't in Maven repos, I'm assuming they don't matter?
Comment: They can be anything but empy
Comment: Anyone reading this QA might want to look at [this answer](http://stackoverflow.com/questions/364114/can-i-add-jars-to-maven-2-build-classpath-without-installing-them) before trying any of the approaches mentioned here.
Comment: Very useful for me! Thanks a lot!
Answer: You can use maven to install files from a project\lib folder to the local repo with the maven-install-plugin as below. I have done this before with JDBC drivers. You might have to create a separate pom for it and execute it with mvn -f installdeps.pom  or something like that.
If you can get it to play nice and bind with a lifecycle like validate or something, then you can use the m2e plugin with Eclipse and it just might play nice and read dependencies straight from the pom.xml and install the jars as needed to the local repo.
    <plugin>

        <inherited>false</inherited>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-install-plugin</artifactId>
        <executions>
            <execution>
                <id>Microsoft JDBC Driver File 1</id>
                <phase>install</phase>
                <goals>
                    <goal>install-file</goal>
                </goals>
                <configuration>
                    <file>lib/sqljdbc4.jar</file>
                    <groupId>com.microsoft</groupId>
                    <artifactId>microsoft-jdbc-driver</artifactId>
                    <version>4.0</version>
                    <packaging>jar</packaging>
                </configuration>
            </execution>
            <execution>
                <id>ojdbc5</id>
                <phase>install</phase>
                <goals>
                    <goal>install-file</goal>
                </goals>
                <configuration>
                    <file>lib/ojdbc5.jar</file>
                    <groupId>com.oracle</groupId>
                    <artifactId>ojdbc5</artifactId>
                    <version>11.1.2</version>
                    <packaging>jar</packaging>
                </configuration>
            </execution>
        </executions>
    </plugin>

Comment: Why can children not install the non maven jars? Please explain.
Answer: It seems to me that you could use the Maven Resources Plugin to do this for you. Just bind copying of resources to an appropriate lifecycle phase (a phase prior to compilation). You'll most likely need to tweak the maven-compiler-plugin so that these libraries are on the classpath when compiling and at runtime.