text:
Q: Compare values of one Array and output i have an array that can contain the same value more than once. What I'm trying to find is a way to compare the values inside that array and output every value only once.
$_just_a_tier = array();

foreach ($_associatedProducts as $_item){
// count all products

    $_tierprice = $this->getTierPrices($_item);
     foreach ($_tierprice as $_ay){
                $_tier = $_ay['price_qty'];
               // echo $_tier.' | ';

                $_just_a_tier[] = $_tier;
      }
}

print_r($_just_a_tier);

this will output e.g. that:
Array
(
    [0] => 36
    [1] => 50
    [2] => 72
    [3] => 108
    [4] => 110
    [5] => 120
    [6] => 144
    [7] => 180
    [8] => 360
    [9] => 540
    [10] => 960
    [11] => 20
    [12] => 30
    [13] => 36
    [14] => 72
    [15] => 108
    [16] => 144
    [17] => 180
    [18] => 360
    [19] => 540
)

Thanks.

A: There is a built-in function in PHP called array_unique that solves this problem for you.

A: Have you looked at PHP's array_unique() function?


text:
Q: How to get terminal to default open into my virtual environment? I've created a virtual environment for Python and VSCode, but everytime I open up the terminal, rather than opening up to the work environment folder, it opens up to the folder where I keep my .py file.
Let me explain my steps.
I've created a Work folder, then a work environment folder inside of it. C:\Work and C:\Work\work_env
Next I've created a folder in C:\Work\myprojects to place my .py files in.
Now when I open up the terminal in VSCode, it runs the Activate.ps1 file and my work environment is ready to use but ONLY when I navigate into my work environment folder using cd in the terminal.
Is there a way to default it so that the terminal is open to the work environment right away? I followed all the steps in this short tutorial and this guy got his terminal to work that way but it's different for me. https://www.youtube.com/watch?v=Wuuiga0wKdQ
Thanks!

A: Add the following line to your settings.json:
"terminal.integrated.cwd": "DESIRED/PATH"

You can find more details here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unnecessary space after 10th number in numbered list I created a numbered list. But there is unnecessary space after 10th.

What should I do?

A: You want to change the tab stop and associated hanging indent in the style associated with that level in your numbering.
I recommend doing  this in the Define New MultiLevel List dialog rather than through the tab settings. This is true even for a single-level list!

You can set both the left indent and the tab for your list in this dialog.
See:

*

*Number Alignment by Word MVP Suzanne Barnhill

*How to set up outline numbering by Word MVP Shauna Kelly

*Setting Tabs by Word MVP Suzanne Barnhill

A: Your tabs are set wrongly. Single digits are tabbing the the first stop, 2 digit are jumping to the second.
See how the first tab stop crosses the periods on the 2-digit numbers?

How to set Tab Stops - MS KB - Set tab stops and paragraph indents in Microsoft Word

A: Please also try to insert the cursor after number 10., right click > Adjust List Indents, check the Text Indents and Follow number with.


text:
Q: Recursive search to get  element This is the heirarchy of an HTML

I am passing parent
 and "A" as parameters in below function and expecting  element to be returned but its returnng me 2nd  from top.
b = function  tryRecursiveSearch (node,tag) {
     var child, tag;
    for (var i = 0; i < node.children.length; i++) {

   var len =  node.children.length;
      child = node.children[i];

    if (child.tagName === "A"){
     console.log('a');
             }
    else {
          tryRecursiveSearch (child,"A");
          }
    }
   return child;
}

What is missing in above code so that it returns ?

A: You can try something like this:
function tryRecursiveSearch(node, tag) {
    if (node.tagName === tag) {
        return true;
    } else {
        for (var i = 0; i < node.children.length; i++) {
            if (tryRecursiveSearch(node.children[i], tag)) {
                return true;
            }
        }
        return false;
    }
}

A: Tail calls are not optimized in ES5, tree walker is not necessarily faster. You can use a microtaskq for this kind of operation, pass a callback to execute with the node.
Input:
"

"

function:
function findTag(node,tag,callback,found){
    found = found || [];
    if(found.length){
        return
    };
    var children = Array.prototype.slice.call(node.children);
    children.some(function(d,i){
        if(d.tagName === tag.toUpperCase()){
            found.push(d);
            return true;
        }
    });
    if(found.length){
        callback(found);
    }   else {
        children.forEach(function(d,i){
            window.requestAnimationFrame(function(){
                findTag(d,tag,callback,found);
            })
        })
    }
}

usage:
findTag(x,"a",function(node){console.log(node)})
//[a]

I left the found variable as an array, you can modify the function to take first n elements or so.

A: One issue, is that the return child; code happens past the for () {} loop, meaning it won't fire until the loop has ended. At which point, child will now contain the last element processed by the loop.
Another, is there is nothing to send a descendant past a child up to the initial calling function.

b = function tryRecursiveSearch(node, tag) {
  var child; // tag is available as an argument, setting this would reinitialize it as an empty variable
  for (var i = 0; i < node.children.length; i++) {

    var len = node.children.length;
    child = node.children[i];

    if (child.tagName === tag) {
      console.log('Found ' + tag);
      return child; // Return once the tag is found
    } else {
      child = tryRecursiveSearch(child, tag);
      if (child.tagName === tag) {
        return child; // Return if the tag is found as a descendant of this element
        // This is what allows a descendant to send the given tag up the recursion
       }
    }
  }
  // the variable child gets overwritten everytime the loop runs; using "return child;" here will result in returning the last child in the set of nodes; regardless of whether it is tag or not
}

console.log(b(document.getElementById('trParent'), 'A'))

            Link

A: as pointed out by @SLaks  above, this simple change provided me a
if (child.tagName === "A"){
     return child;
             }
    else {
          return tryRecursiveSearch (child,"A");  //added return
          }
    }

}


text:
Q: Why won't my program read input from entry? from Tkinter import *
import requests
import base64
var = "lol"
var2 = "lol"
var3 = "111111"
var4 = "31039888252154&31039888252154&0&X168&1411869345&IQSAXYOS&"+var2+"&"+var3+"&&1&3&1&ubugg@zetmail.com&goohoo&1411603529&&2&"
encoded = base64.b64encode(var4)
var5 = encoded

payload = {'X1': '218',
           'X127': 'X325',
           'X171':var,
           'X677':'1420103258',
           'X678':'208180484',
           'X691':var5,
           'X763':'1'}
def bluh(e):
   var = e1.get()
   var2 = e2.get()
   var3 = e3.get()
def Send(e):
    requests.post("http://us23.chatzy.com/", data=payload)
def p1(e):
    print var
    print var2
    print var3

#Sh!t in the GUI
root = Tk()

root.title("Spam Project")
root.geometry("200x200")
app = Frame(root)
app.grid()
button1 = Button(app, text = "Send")
button1.grid()
button1.bind('<Button-1>', Send)

e1 = Entry(root)
e1.grid()
e1.insert(0,"Message")
e2 = Entry(root)
e2.grid()
e2.insert(0,"Name")
e3 = Entry(root)
e3.grid()
e3.insert(0,"Color in Hex")

button2 = Button(app, text = "Submit")
button2.grid()
button2.bind('<Button-1>', bluh)
button3 = Button(app, text = "Print")
button3.grid()
button3.bind('<Button-1>', p1)
var = e1.get()
var2 = e2.get()
var3 = e3.get()

#Event loop
root.mainloop()

Basically, what this is supposed to do is take a name, message and hex color and send them as an HTTP request to a chat, this all works in terminal but then I tried to stitch a GUI on top, at the very top, var, var2, var3 are all default values and I have the submit button to change those values, but it simply does not work, so I made the "print" button to print the three values and they do not change, can anyone tell me what's wrong with my code and how can I make the three entries change the variables according to what's inside them?
Here's what the variables do.

*

*var is the message to be sent.

*var2 is the name

*var3 is the color of the message in HEX

*var4 is the string which is part of the request, which is then
encoded into Base64

*var5 is var4 encoded into Base64

A: The usual way in GUI code to avoid using globals is to use a class. I hope this isn't too advanced for you. But if it is, well you gotta learn this stuff sometime if you want to do serious programming. :) So read about classes in the Python docs, and then if you still can't figure out what something in my code's doing, ask & I'll try to explain.
I've commented out the actual requests stuff for testing purposes.
#! /usr/bin/env python

from Tkinter import *
#import requests
import base64

def build_payload(var1, var2, var3):
    var4 = "31039888252154&31039888252154&0&X168&1411869345&IQSAXYOS&" \
        + var2 + "&" + var3 \
        + "&&1&3&1&ubugg@zetmail.com&goohoo&1411603529&&2&"

    print 'var4 = [%s]\n' % var4

    var5 = base64.b64encode(var4)

    payload = {
        'X1': '218',
        'X127': 'X325',
        'X171': var1,
        'X677': '1420103258',
        'X678': '208180484',
        'X691': var5,
        'X763': '1'
    }
    return payload

class my_GUI(object):
    def __init__(self):
        #Build GUI
        root = Tk()

        root.title("Spam Project")
        root.geometry("200x200")

        app = Frame(root)
        app.grid()

        button = Button(app, text = "Send")
        button.grid()
        button.bind('<Button-1>', self.send_data)

        self.e1 = Entry(root)
        self.e1.grid()
        self.e1.insert(0, "Message")

        self.e2 = Entry(root)
        self.e2.grid()
        self.e2.insert(0, "Name")

        self.e3 = Entry(root)
        self.e3.grid()
        self.e3.insert(0, "Color in Hex")

        button = Button(app, text = "Print")
        button.grid()
        button.bind('<Button-1>', self.print_data)

        #Start tkinter event loop
        root.mainloop()

    def print_data(self, e):
        var1 = self.e1.get()
        var2 = self.e2.get()
        var3 = self.e3.get()
        print var1, var2, var3

    def send_data(self,e):
        var1 = self.e1.get()
        var2 = self.e2.get()
        var3 = self.e3.get()
        print var1, var2, var3

        payload = build_payload(var1, var2, var3)
        print 'Sending payload', payload
        #requests.post("http://us23.chatzy.com/", data=payload)

def main():
    my_GUI()

if __name__ == '__main__':
    main()

PS. I've changed the names of some of the functions from what they were in your code, but I've left the variables names (mostly) as they were. In future, try to use more meaningful names - it makes life easier both for yourself & for other people who are trying to read your code.

A: To use global variables in Python you need the global statement. So, you need to modify your bluh function like this:
def bluh(e):
   global var, var2, var3
   var = e1.get()
   var2 = e2.get()
   var3 = e3.get()

(I've also fixed the code to use e1, e2, e3 resp. instead of e1 only)
In your version you were creating new, local variables var, var2 and var3 inside the bluh function, having nothing to do with the global ones defined at the top of your file. Please also note that in general using global variables is discouraged.
The same goes to the p1 function, as you also want to access globals.


text:
Q: How can I translate this URL into a Graph API search or FQL query? I can find all users who like StackOverflow and live in California using this URL on Facebook: https://www.facebook.com/search/1462865420609264/likers/union/108131585873862/residents/present/intersect
I've been trying to get the same results using the Graph API and FQL for hours but haven't been able to get the response I'm looking for. The data is there, and I can clearly access it on Facebook itself. How can I query this data outside of Facebook using either the Graph API or FQL?
I just need the user's uid.

A:
The data is there, and I can clearly access it on Facebook itself.

That does not mean it must be freely available via API as well.

How can I query this data outside of Facebook using either the Graph API or FQL?

You can't. Graph API offers very limited search functionality.
Graph Search (what you get via the search box on facebook.com) is not exposed via API, because it would be just too powerful a tool to acquire huge amounts of personal data, do all sorts of profiling on that, etc.
Graph Search is deliberately exposed to human users only, and not via API.

I just need the user's uid.

You won't get it. User privacy is more important than what you need.

The "but I can see it on facebook.com" argument is not valid here – because in that context it is about what you can see, whereas when this information was queried via API, a 3rd party (the app developer) would get their hands on this as well.


text:
Q: Capybara: How to test the title of a page? In a Rails 3 application using Steak, Capybara and RSpec how do I test the page's title?

A: I added this to my spec helper:
class Capybara::Session
  def must_have_title(title="")
    find('title').native.text.must_have_content(title)
  end
end

Then I can just use:
it 'should have the right title' do
  page.must_have_title('Expected Title')
end

A: In order to test for the title of a page with Rspec and Capybara 2.1 you could use

*

*expect(page).to have_title 'Title text'
another option is

*expect(page).to have_css 'title', text: 'Title text', visible: false
Since Capybara 2.1 the default is Capybara.ignore_hidden_elements = true, and because the title element is invisible you need the option visible: false for the search to include non visible page elements.

A: Testing the Title of each page can be done in a much easier way with RSpec.
require 'spec_helper'

describe PagesController do
  render_views

  describe "GET 'home'" do
    before(:each) do
      get 'home'
      @base_title = "Ruby on Rails"
    end

    it "should have the correct title " do
      response.should have_selector("title",
                                :content => @base_title + " | Home")
    end
  end
end

A: You should be able to search for the title element to make sure it contains the text you want:
page.should have_xpath("//title", :text => "My Title")

A: This works under Rails 3.1.10, Capybara 2.0.2 and Rspec 2.12, and allows matching partial contents:
find('title').native.text.should have_content("Status of your account::")

A: Since the version 2.1.0 of capybara there are methods on the session to deal with the title.
You have
page.title
page.has_title? "my title"
page.has_no_title? "my not found title"

So you can test the title like:
expect(page).to have_title "my_title"

According to github.com/jnicklas/capybara/issues/863 the following is also working with capybara 2.0:
expect(first('title').native.text).to eq "my title"

A: You just need to set the subject to page and then write an expectation for the page's title method:
subject{ page }
its(:title){ should eq 'welcome to my website!' }

In context:
require 'spec_helper'

describe 'static welcome pages' do
  subject { page }

  describe 'visit /welcome' do
    before { visit '/welcome' }

    its(:title){ should eq 'welcome to my website!'}
  end
end

A:
it { should have_selector "title", text: full_title("Your title here") }


text:
Q: WinForms in Excel (2002) and add-ons Good morning,
I am about to start writing an Excel add-in for Excel 2002.  The add-in needs to call a form.  Obviously, I can write the form within VBA.
My question is -- is there an easy/good way of calling a .NET (I am using 3.5) from Excel, and have the form be able to write stuff back to Excel the same way a native Excel 2002 form would?

A: Office XP... yes, functionally you can manipulate excel from add-in or the other way around, but obviously it requires more coding compared to VBA.
Most powerful solution is to use OLE automation, but it is not the easiest one to code and support.
If you really need it and have this option - get something like http://www.add-in-express.com/ - it gives a nice wrapper over Excel automation and addresses most common problems. Anyway, add-in-express looks like the most mature product supporting Office XP and worth checking out to get better idea about how .Net code and Excel can interact.
There are multiple ways you can implement data exchange between Excel and .Net code in add-in: OLE automation, calls to COM functions from VBA, RTD, not sure if anyone still uses DDE. There are some setup effort, programming challenges, and maintenance/stability problems for each of those.


text:
Q: How to add the product again to the cart or add to cart button not working? <?php foreach ($memberData as $c) {?>

      <?php echo $c->name;?>
       1 year

 <?php echo $c->Fees;?>

<?php if($c->member_approve==1){?>
          <button type="button" name="renew" class="btn btn-success add_cart" data-productname="membership" data-price="" data-productid="1" />Add to cart</button><?php }else{?>

Not Approved
<?php };?>

<?php }?>

The output of the above code is
Alex | 1 Year | 500 | Add to cart
blex | 1 Year | 300 | Add to cart
clex | 1 Year | 200 | Add to cart

Now when the user clicks on Add to cart button then product will add in the cart and button will change from add to cart to remove using jQuery. below is the code of add to cart and change the button from add to cart to remove.
Add to cart
$(document).ready(function(){

 $('.add_cart').click(function(){
  var product_name = $(this).data("productname");
  var product_id = $(this).data("productid");
  var product_price = $(this).closest('tr').find('.calActivitylPrice').text();
  var quantity =1 ;

  var changeToRemoveBTNSec = $(this).closest('tr').find('.display_table');

   $.ajax({
    url:"<?php echo base_url(); ?>Member_controller/addToCart",
    method:"POST",
    data:{product_id:product_id, product_name:product_name, product_price:product_price,quantity:quantity},
    success:function(data)
    {
        var obj = JSON.parse(data);

    $(changeToRemoveBTNSec).html('<button type="button" name="remove" class="btn btn-danger remove_inventory" id="'+obj.removebtn+'">Remove</button>');

     $('#totalDetails').html(obj.cart_total);
     $('#totalQty').html(obj.totalQty);
    }
   });

 });

});

After adding the product in a cart the I am getting the remove button so my list is
Alex | 1 Year | 500 | Add to cart
blex | 1 Year | 300 | remove
clex | 1 Year | 200 | remove

Now If I click on the remove button then the product is also removed from the cart and button change from remove to add to cart and the script is below
Remove from cart
 $(document).on('click', '.remove_inventory', function(){
  var row_id = $(this).attr("id");
  var changeToAddtocartBTN = $(this).closest('tr').find('.display_table');

  if(confirm("Are you sure you want to remove this?"))
  {
   $.ajax({
    url:"<?php echo base_url(); ?>Member_controller/Removecart",
    method:"POST",
    data:{row_id:row_id},
    success:function(data)
    {
        var obj = JSON.parse(data);
        alert("Product removed from Cart");

      $(changeToAddtocartBTN).html('<button type="button" name="renew" class="btn btn-success add_cart" data-productname=cmembership" data-price="" data-productid="-3">Add to cart</button>');

    }
   });
  }
  else
  {
   return false;
  }
 });

Above scenario is working for me. now I am getting the issue on I am not able to add the product again because add to cart button is not working. because this time it's not getting the product name and all information.
Would you help me out in this issue?

A: Change your add to cart function from .click to .on
$(document).on('click', '.add_cart', function() {
    var product_name = $(this).data("productname");
    var product_id = $(this).data("productid");
    var product_price = $(this).closest('tr').find('.calActivitylPrice').text();
    var quantity = 1;

    var changeToRemoveBTNSec = $(this).closest('tr').find('.display_table');

    $.ajax({
        url: "<?php echo base_url(); ?>Member_controller/addToCart",
        method: "POST",
        data: {
            product_id: product_id,
            product_name: product_name,
            product_price: product_price,
            quantity: quantity
        },
        success: function(data) {
            var obj = JSON.parse(data);

            $(changeToRemoveBTNSec).html('<button type="button" name="remove" class="btn btn-danger remove_inventory" id="' + obj.removebtn + '">Remove</button>');

            $('#totalDetails').html(obj.cart_total);
            $('#totalQty').html(obj.totalQty);
        }
    });

});


text:
Q: Is modification of dependency, of a dependency mentioned in makefile, not recognized by make? In my code, I have used three classes. All the classes are in separate files. And I am using Makefile to compile and link them.
See the implementation below:
class Medicine
{
   int a;
}

class Pain:public Medicine
{
   int b;
}

class Comb:public Pain
{
    string salt,com;
}

All classes have just parameterized constructors, virtual destructors and a function with same name call(), in all the three classes.
And call() is like
call()
{
     cout<<"You are in class the_name_of_the_class"<<endl;
}

The code of main.cpp goes like:
int main()
{
    Medicine *p[2];
    p[0]= new Comb("Salt","Com",2,110);
    p[1]= new Comb("SALT","COM",1,100);

    p[0]->call();

    delete p[0];
    delete p[1];
    return 0;
}

When I run this program, I got the expected output. But when I changed the Medicine::call() to be a virtual function, and again used make command, it says all files are up to date. As I have modified medicine.h, so make should created new version of medicine.o. Why is it considering older medicine.oas updated when I have modified medicine.h?
The Makefile goes like this:
using .PHONY:clean
OBJ:=medicine.o pain.o comb.o main.o
SOU:=medicine.cpp pain.cpp comb.cpp main.cpp

main:$(OBJ)
        g++ -o $@ $^

%.o:%.cpp
        g++ -c -o $@ $<

clean:
        rm *.o main

If you want to see implementation of medicine.h,
class Medicine
{
    int cost;

 public:

    int getCost();
    void setCost(int);

    Medicine();
    Medicine(int);
    Medicine(Medicine &a);
    virtual string getCompany(){};
    virtual string getSalt(){};
    virtual  ~Medicine ();
    virtual void call();
};

This medicine.h I have included in medicine.cpp, where all these functions are defined.

A: The problem is that medicine.o only depends on medicine.cpp, not on medicine.h. So you have to modify your rules to provide that missing dependency. It has absolutely nothing to do with "virtualness".
You might also want to add the Makefile itself as a dependency, so if you change it and run make, things get re-built.
To clarify, this generic rule:
%.o:%.cpp
    g++ -c -o $@ $<

means that any something.o depends on something.cpp only, and should be built with the following command:
g++ -c -o something.o something.cpp

i.e. $@ is the target name and $< is the first dependency.
the format is
target : <dependencies>
    command

A: make is not language-aware, so yes, make does not know whether a function is virtual or not; actually it does not even know what C++ is and that there are functions there.
make operates in terms of targets and dependencies, and those have to be specified explicitly. Here, the rule to make an object does not include any .h file in the dependencies and thus it deduces that .8 files are unused for the target.
It is actually quite difficult to get the proper set of transitive includes needed to build one .cpp file. There are scripts to assist such as make_depend.pl.

A: The problem is that your makefile doesn't have the dependencies for your header files to the source files, so it doesn't know that you need to recompile "x.cpp" when "y.h" has changed (because "y.h" is included by "x.cpp").
You can fix that by having rules like:
medicine.o : medicine.cpp medicine.h

However, as the number of source files get larger, and the relationship of headers to source gets more complex, you are going to forget/leave out some header files that you actually need - this will ALWAYS happen.
What I usually do is something like this:
SOU = medicine.cpp pain.cpp comb.cpp main.cpp
...

main:$(OBJ) .depends

...

.depends: $(SOU)
     g++ -MM $(SOU) > $@

include .depends

What this does is to let the compiler generate the rules into a file .depends - that way, you don't "forget" to fix it up when you update a file somewhere.
Edit:
For large projects, using a single dependency file is a poor idea, because every time a .cpp file is changed, the compiler will have to sort out all the dependencies for every file in the project. But for a small hobby project it's fine. For large projects, one would take the extra penalty of having lots of .depends files (one per source file, probably in a depends directory).

A: The working of make is like this:
It checks the latest modification time of the dependency (medicine.cpp for eg) and then check the latest modification time of medicine.cpp when medicine.o was created. If both are same, then its not recompiled, otherwise recompiled. In my case, medicine.h was modified, but the latest modification time of medicine.cpp remain unchanged. And that's why make was unable to detect this and not recompiled medicine.cpp.


text:
Q: using filter function to produce a list outputting non-common elements of two lists So i am in need of a function which takes two lists, x and y and output a list of elements that are in List x BUT NOT IN List y.
ie. the output should look something like is
*Main> filterVars ["a","c","h","d"] ["c","b","a"]
      ["h","d"]

I want to use the filter function in Haskell to practice. My code is below;
    filterVars :: [a] -> [a] -> [a]
    filterVars = filter IsInList (y:ys)
     where
IsiIList (x:xs) (y:ys) :: [a] -> [a] -> Bool
IsInList [] _ = []
IsiInList(x:xs) (y:ys)
                        | elem (x (y:ys)) = IsiInList (xs (y:ys))
                        | otherwise = x : IsiInList (xs (y:ys))

however I get the following error;
   Invalid type signature: IsInList (x : xs) (y : ys) :: ...
Should be of form <variable> :: <type>
     | IsInList (x:xs) (y:ys) :: [a] -> [a] -> Bool

My logic is as follows:

When the function filterVars is called with arguments (x:xs) (y:ys), it checks to see the filter criteria IsInList.

The function providing the filtering criteria, IsInList, takes both the arguments (x:xs) and (y:ys). if the first element of the list (x:xs) is an elements of (y:ys), then discard and move to the next element in the x list.

For the case that an element of (x:xs) IS NOT IN list (y:ys), store this value and move onto the next element of the list x until list x is completely parsed through.

return the list containing elements of list x that are not in list y

My confusion arises from my lack of experience with Haskell. Firstly the function filterVars must require two lists and output a list. However when i am defining the function, I use the filter function and the list y as arguments. I know filter outputs a list so i just wanted to know if my initial setup is correct (also would like to gain an insight to the flow of execution in Haskell)
Secondly I am not sure as to what the error means and how to resolve it. Does my logic make sense? Can this be done using lists or am i way of mark?

A: Your code has a few syntactic and semantic errors. I'll explain the syntax issues and then get into the semantics of your solution.

*

*In Haskell, the names of functions, variables, and type variables must begin with a lowercase letter; capitalised names refer to types, data constructors, or modules. Therefore you need to rename IsInList to isInList, and fix the name typos.

*A where clause on a definition is followed by a block of variable bindings (pattern = expression). A block may be delimited by curly braces with items separated by semicolons ({ … ; … ; … }) but it's more common to use indentation-based layout. Therefore you need to indent the contents of the where block. A simple rule is to put a newline + indent (with spaces) after any layout keyword—where, do, of, or let—whenever you have a multi-line block.

*The type signature of a function is written as name :: type, but you've written what looks like a pattern on the left-hand side in isInList (x:xs) (y:ys) :: [a] -> [a] -> Bool. If you want to include a type signature here, you should write isInList :: [a] -> [a] -> Bool. However, I'm going to just remove the signature, for reasons I'll explain below.
With those fixes, your code looks like this:
filterVars :: [a] -> [a] -> [a]
filterVars = filter isInList (y:ys)
  where
    isInList [] _ = []
    isInList (x:xs) (y:ys)
      | elem (x (y:ys)) = isInList (xs (y:ys))
      | otherwise = x : isInList (xs (y:ys))

Here's my reading of this code:

*

*filterVars is equal to calling filter with two arguments, isInList and y : ys. y and ys are not in scope here, since you haven't added them as parameters or pattern variables in the definition of filterVars.

*isInList takes two arguments; if the first is an empty list, it returns an empty list. This is not quite right, since filter has the type (a -> Bool) -> [a] -> [a], that is, its first argument should be a function which tests an element of the filtered list and returns a Bool to indicate whether it should be included in the result.

*If isInList is given two non-empty lists, then this is followed by a guard to decide which case to proceed to. You're trying to use the elem function to test whether x is in the list y : ys as the condition here, but the way you call it, you're passing y : ys as an argument to x, as if it were a function, and then calling elem on the result of that. If you want to pass two arguments to a function, you just separate them with spaces, and include parentheses if necessary for grouping, e.g.: elem x (y : ys). You have the same issue with both calls to isInList (xs (y:ys)), when you probably intended isInList xs (y:ys).
At this point it's clear to me that you're mixing up two things: filtering a list using filter, and filtering it by writing a recursive function.
If you want to write this using filter, you should begin with the problem statement: "a function which takes two lists, x and y and output[s] a list of elements that are in List x BUT NOT IN List y". You want to write a function that takes two parameters, x and y, and filters x by a function that, given an element of x, returns true if the element is not in y.
This can be transcribed fairly literally:
filterVars :: [a] -> [a] -> [a]

-- Select the elements of 'x' not in 'y'…
filterVars x y = filter notInY x
  where

    -- …where an element 'e' is not in 'y' if
    -- it's 'not' the case that 'e' is an 'elem' of 'y'.
    notInY e = not (elem e y)

But this has one issue: this function says it can take a list of values of any type a, and test for their presence in a list using elem, but this isn't true: we could supply a type like Double -> String that's not comparable at all! In reality, elem is restricted to types that are in the set of types with equality, the Eq typeclass, so we have to add an Eq constraint to the signature to enable the use of elem:
filterVars :: (Eq a) => [a] -> [a] -> [a]

Now, about the local type signature in the where block, the rule in Haskell is that if you write a polymorphic type signature with type variables (typically single letters like a, b, f, m…) then those variables are local to that type signature. So if you write this:
filterVars :: (Eq a) => [a] -> [a] -> [a]
filterVars x y = filter notInY x
  where
    notInY :: a -> Bool
    notInY e = not (elem e y)

That's equivalent to this:
filterVars :: (Eq a1) => [a1] -> [a1] -> [a1]
filterVars x y = filter notInY x
  where
    notInY :: a2 -> Bool
    notInY e = not (elem e y)

The a of the notInY signature is different from the a in the filterVars signature, so this would cause a type error. The solution is to remove the local type signature or use the ScopedTypeVariables extension to explicitly define the scope of a:
{-# LANGUAGE ScopedTypeVariables #-}

filterVars :: forall a. (Eq a) => [a] -> [a] -> [a]
filterVars x y = filter notInY x
  where
    notInY :: a -> Bool
    notInY e = not (elem e y)

The forall introduces an explicit scope for a, so any a in a type signature in this definition refers to the same a. (An explicit forall is just like the <T> syntax in many imperative programming languages to define generic parameters.)
As a matter of style, you can also write this same structure in a few different ways, and you should make sure you understand these:
filterVars x y = filter (notIn y) x
  where
    notIn list e = not (elem e list)

filterVars x y = filter (\ e -> not (elem e y)) x

filterVars x y = filter (`notElem` y) x

This is very typical Haskell code, and a good concise solution. But since you're learning Haskell, you should try to solve this problem with explicit recursion, effectively inlining the definition of filter into your code. For that, you do want to proceed by pattern-matching as you were trying to do in your isInList function. You can start with either of the following structures, using a case expression or multiple function equations, whichever you prefer:
filterVars :: (Eq a) => [a] -> [a] -> [a]
filterVars x y = case x of

  [] -> {- 1 -}

  e : rest
    | {- 2 -} -> {- 3 -}
    | otherwise -> {- 4 -}

filterVars :: (Eq a) => [a] -> [a] -> [a]
filterVars [] y = {- 1 -}
filterVars (e : rest) y
  | {- 2 -} = {- 3 -}
  | otherwise = {- 4 -}

And fill in the following details, marked with {- … -} comments in the code above:

*

*[a]; What do you return when x is empty, i.e., what happens when you call filterVars [] ["c", "b", "a"] directly or as the base case of your recursion?

*Bool; When x is non-empty, containing some element e and some (possibly empty) remainder rest, what condition do you use to test whether e is an element of y? (E.g. in filterVars ["a", "d", "b"] ["c", "b", "a"], e is "a" and rest is ["d", "b"].)

*[a]; What do you return when e is an element of y? Should you keep or discard the element? What do you do with the rest of the input?

*[a]; What do you return when e is not in y? What do you do with the rest of the input then?
Recall that you can always step through Haskell code using equational reasoning, by substituting things on either side of an = sign, since = actually means equal! For example, if your function had a case f [] = [], then whenever you see f [], you can replace it with []; if it had a case f (x : xs) = x + f xs, when you see a call to f [1, 2, 3], this is the same as f (1 : [2, 3]), and likewise f (1 : (2 : (3 : []))), so you can match x = 1 and xs = 2 : (3 : []) and substitute their values in the right-hand side x + f xs → 1 + f [2, 3].


text:
Q: Bash: 'if' statement always seems to evaluate first condition as true even when false I just started using bash recently and I'm having troubles with a simple command. Here's the script:
#!/bin/bash
if TouchpadOff=0; then
    synclient TouchpadOff=1
    echo "Touchpad has been turned off"
else
    synclient TouchpadOff=0
    echo "Touchpad has been turned on"
fi

Basically, what I'm trying to do is toggle the pad to turn off or on depending on whether it is currently on or off. When the pad is on, running the script turns it off, which is what I want it to do.
But for some reason, when I run it again to turn the pad on, it is still turned off and still echos "Touchpad has been turned off", even when I want it to turn on. I hope someone can help me with my question. Thanks!

A: The problem is your if-condition is wrong. It does not do what you think it does.
if TouchpadOff=0; then

This runs TouchpadOff=0 as a shell command, which creates a variable $TouchpadOff and assigns it the value 0. As this should normally run successfully, the result is that the condition is always true.
You'll have to call the synclient command and parse its output to check the state of the TouchpadOff property, like e.g. this way:
if [[ "$(synclient | grep 'TouchpadOff' | awk '{print $3}')" -eq 0 ]] ; then

This will run synclient | grep 'TouchpadOff' | awk '{print $3}', which parses the output of synclient for a line containing "TouchpadOff" and returns the third column of that line.
It's inside a command substitution $( ... ), so that whole part will be substituted with the output of the inner command.
Then [[ ... -eq 0 ]] checks whether the substituted output is equal to 0 and makes that the condition for the if-statement.

A: TouchpadOff=0 as a condition is interpreted as an assignment, so it's always true (unless the variable is readonly).
Use numeric comparison:
if (( TouchpadOff == 0 )) ; then


text:
Q: C# Class Inheritance Issue with Simple Calculator I am beginner to C# and am trying to get my second class, MyCalc2, to inherit from MyCalc. But I encounter the following error message in regards to MyCalc2:
There is no argument given that corresponds to the required formal parameter 'x' of 'MyCalc.MyCalc(int, int, string, string)'
The goal here is to just add another class that inherits from the base class.
I know that I need to add something like 'MyCalc: base(x)' to my base class but am lost to where to place the parameter (if that is even the correct thing to do). Any guidance would be appreciated. Here is what I have so far:
    using System;
class MyCalc
{
    // class variable
    public int x;
    public int z;
    public string y;
    public string n;

    // constructor
    public MyCalc(int x, int z, string y, string n)
    {
        this.x = x;  // assign the parameter passed to the class variable
        this.z = z;
        this.y = y;
        this.n = n;

    }
    // calculate the operations
    public int GetAdd()
    {
        return (this.x + this.z);

    }

    public int GetSubtract()
    {
        return (this.x - this.z);
    }

    public int GetMultiply()
    {
        return (this.x * this.z);
    }

    public int GetDivide()
    {
        return (this.x / this.z);
    }

    public string GetYes()
    {
        return (this.y);
    }

    public string GetNo()
    {
        return (this.n);
    }

}

class MyCalc2:MyCalc //where the error is occurring
{
    static void Main(string[] args)

    {
        bool repeat = false;
        do
        {

            repeat = false;

            int x = 0; int z = 0; string y; string n;
            Console.WriteLine("Enter the First Number");
            x = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Enter the Second Number");
            z = Convert.ToInt32(Console.ReadLine());

            //Using a switch statement to perform calculation:
            Console.WriteLine("Enter operator\r");
            switch (Console.ReadLine())

            {

                case "+":
                    Console.WriteLine($"The Answer is: {x} + {z} = " + (x + z));
                    break;

                case "-":
                    Console.WriteLine($"The Answer is: {x} - {z} = " + (x - z));
                    break;
                case "*":
                    Console.WriteLine($"The Answer is: {x} + {z} = " + (x + z));
                    break;

                case "/":
                    Console.WriteLine($"The Answer is: {x} - {z} = " + (x - z));
                    break;

            }

                //Repeat or Exit program using the do-while loop:

            string input = Console.ReadLine();
            Console.WriteLine("Do you want another operation(Y / N) ?");
            input = Console.ReadLine();
            repeat = (input.ToUpper() == "Y");

        }
            while (repeat);
            Console.WriteLine("Thanks for using our system.");
            Console.ReadKey();
        }

    }

A: MyCalc2 does not have a way of initializing MyCalc (Base Class) Because in your BaseClass you do not have a parameter less constructor.
Solution:

*

*Add a param less constructor in Base Class

*Add a constructor in Derived class which has a way of calling base class constructor

for your code below should work:
class MyCalc2 : MyCalc
{
    public MyCalc2 () : base(0, 0, "", "")
    {
    }
}

A: MyCalc2 has no explicit constructor.  Which means it has only one implicit constructor which takes no arguments and sets no values.  If made explicitly it would look like this:
public MyCalc2()
{

}

However, MyCalc does have an explicit constructor.  Which means it has no implicit constructor.  And its constructor does take arguments:
public MyCalc(int x, int z, string y, string n)
{
    this.x = x;  // assign the parameter passed to the class variable
    this.z = z;
    this.y = y;
    this.n = n;
}

So when you create an instance of MyCalc2 it has no way of providing any values to MyCalc.  You essentially have three options:

*

*Add a constructor to MyCalc (you can have as many constructors as you want, as long as the parameters differ) which takes no parameters.  However, in that case the class-level values for MyCalc would all be default values.  You'd have to set them explicitly after constructing the object.1

*Add a constructor to MyCalc2 which accepts those values and passes them to the parent constructor, or at least passes default values to the parent constructor.

*Don't use inheritance here.

Honestly, in this case I'd go with the third option.  What is inheritance meant to accomplish here?  MyCalc2 isn't meaningfully an instance of MyCalc.  All it does it hold the initial entry point of the application (the Main method), and that's really all it should do.
The logic in your Main method should create and use an instance of MyCalc, but the class which has that Main method shouldn't try to be an instance of MyCalc.  That will only cause more confusion than solve any meaningful problems.

1 Side Note: Public class fields are historically a bad habit to get into in object-oriented programming.  There's a variety of talk on the subject, and you'll see this often as you continue in your experience.  In general you want your objects to expose behaviors, not values.  The methods on the object look somewhat Java-like in convention.  For C# conventions consider using properties (which compile down to methods themselves, the syntax is just semantically different).  You can have { get; set; } auto-properties for the values themselves, and explicit read-only { get { /*...*/ } } properties for the calculated values.

A: Here is a possible solution. There are two classes MyClass, for the calculator (you may want to rename it) and Propram. Program holds just the method Main, which get your program started. It works like this, but there are some bugs left. I leave it to you to fix them. Except that you miss a clear understanding of the concepts class and inheritance, your code is not too bad for a beginner. It is almost working.
using System;

namespace TestCalculator
  {
 class MyCalc
{
// class variable
public int x;
public int z;
public string y;
public string n;

// constructor
public MyCalc(int x, int z, string y, string n)
  {
  this.x = x;  // assign the parameter passed to the class variable
  this.z = z;
  this.y = y;
  this.n = n;

  }
// calculate the operations
public int GetAdd()
  {
  return (this.x + this.z);

  }

public int GetSubtract()
  {
  return (this.x - this.z);
  }

public int GetMultiply()
  {
  return (this.x * this.z);
  }

public int GetDivide()
  {
  return (this.x / this.z);
  }

public string GetYes()
  {
  return (this.y);
  }

public string GetNo()
  {
  return (this.n);
  }

}
 class Program
{
static void Main(string[] args)
  {
  bool repeat = false;
  do
    {

    repeat = false;

    int x = 0; int z = 0; string y; string n;
    Console.WriteLine("Enter the First Number");
    x = Convert.ToInt32(Console.ReadLine());

    Console.WriteLine("Enter the Second Number");
    z = Convert.ToInt32(Console.ReadLine());

    //Using a switch statement to perform calculation:
    Console.WriteLine("Enter operator\r");
    switch (Console.ReadLine())

      {

      case "+":
        Console.WriteLine($"The Answer is: {x} + {z} = " + (x + z));
        break;

      case "-":
        Console.WriteLine($"The Answer is: {x} - {z} = " + (x - z));
        break;
      case "*":
        Console.WriteLine($"The Answer is: {x} + {z} = " + (x + z));
        break;

      case "/":
        Console.WriteLine($"The Answer is: {x} - {z} = " + (x - z));
        break;

      }

    //Repeat or Exit program using the do-while loop:

    string input = Console.ReadLine();
    Console.WriteLine("Do you want another operation(Y / N) ?");
    input = Console.ReadLine();
    repeat = (input.ToUpper() == "Y");

    }
  while (repeat);
  Console.WriteLine("Thanks for using our system.");
  Console.ReadKey();
  }
}

}


text:
Q: How do I stop running the program? I wrote my code, but I have an error. It says:

('break' statement not in loop or switch statement)

The thing is that I use loop in a program, but before that I check if the condition in incorrect I have to print out "False" and stop the program, without reading next symbols. How do I have to do that?
Here is my code:
if(l % 2 == 0) {
    cout << "False";
    break;
}
for(int i = 0; i < 5; i++) {
    cout << '*';
}

A: You can only call break inside a for or while loop, or a switch statement.
If this is your main function, the program will exit once the main function is done.
This can be made by using the return statement (with a value to return, 0 is the default return value if the program ran successfully)
if (l%2 == 0) {
    cout << "False";
    return 0;
}

for (int i = 0; i < 5; i++)
{
    cout << '*';
}

A: First option: further code won't be executed.
if(l%2==0){
    cout<<"False";
    return 1; //this ends program here
    }
    for(int i=0;i<5;i++){
    cout<<'*';}

or second
if(l%2==0){
cout<<"False";
}
else{
for(int i=0;i<5;i++){
    cout<<'*';}
}

By using else further code after else will be executed but not this for loop (if this l%2==1 for will be executed instead)


text:
Q: QTimer and QThread odd behavior from PySide.QtGui import *
from PySide.QtCore import *
import sys
from time import sleep

class MyWorkerThread(QThread):
    def __init__(self, parent=None):
        super(MyWorkerThread, self).__init__(parent)

    def run(self):
        timer1 = QTimer()
        timer1.singleShot(1000, self.alarm_goes1)
        print "Timer 1 Start"
        timer1.start()

    def alarm_goes1(self):
        print "goes off 1"

class MainFrame(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.thread = MyWorkerThread(self)
        print "Thread Start"
        self.thread.start()

        timer2 = QTimer()
        timer2.singleShot(1000, self.alarm_goes2)
        print "Timer 2 Start"
        timer2.start()

    def alarm_goes2(self):
        print 'goes off 2'

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = MainFrame()
    main.show()
    sys.exit(app.exec_())

Output:
Thread Start
Timer 2 Start
Timer 1 Start
goes off 2

Please, explain why alarm_goes1 doesn't execute. And how can I make it do it?

EDIT:
def run(self):
    timer1 = QTimer()
    timer1.singleShot(2000, self.alarm_goes1)
    print "Timer 1 Start"
    timer1.start()
    self.exec_()
    self._alive = True
    while self._alive:
        print 'this part will not execute'
        self.sleep(1)

With the self.exec_() both timers will work fine, but the part inside while loop won't. Without the self.exec_(), just one of the timers work, but the while loop will work.
I want both the timers and the while loop working together.
I tried moving the self.exec_() inside the while loop, but it will only run once.

A: The timer posts a QTimerEvent, but there is no event-loop running in the thread to process it.
So you need to do something like this:
    def run(self):
        timer1 = QTimer()
        timer1.singleShot(1000, self.alarm_goes1)
        print "Timer 1 Start"
        timer1.start()
        # start the clock
        clock = QTimer()
        clock.start(1000)
        clock.timeout.connect(self.tick)
        # start the thread's event loop
        self.exec_()

    def tick(self):
        print 'tick'

and it would probably be wise to add this to the MainFrame class:
    def closeEvent(self, event):
        # exit the thread's event loop
        self.thread.quit()


text:
Q: Using ggplot2, connect x- and y-coordinates by a third variable I would like to plot latitude vs longitude and connect the points via date and time, which I have stored in an object of class POSIXlt.  I have many, many GPS points, but here is a small set of them that I would like to plot using ggplot2.
My data are like so:
Description             lat         lon
6/16/2012 17:22         12.117017   -89.69692
6/17/2012 9:15          12.1178     -89.69675
6/17/2012 9:33          12.117783   -89.69673
6/17/2012 10:19         12.11785    -89.69665
6/17/2012 10:45         12.11775    -89.69677
6/17/2012 11:22         12.1178     -89.69673
6/17/2012 11:39         12.117817   -89.69662
6/17/2012 11:59         12.117717   -89.69677
6/17/2012 12:10         12.117717   -89.69655
6/16/2012 16:38         12.11795    -89.6965
6/16/2012 18:29         12.1178     -89.69688
6/16/2012 17:11         12.117417   -89.69703
6/16/2012 17:36         12.116967   -89.69668
6/16/2012 17:50         12.117217   -89.69695
6/16/2012 18:02         12.117583   -89.69715
6/16/2012 18:15         12.11785    -89.69665
6/16/2012 18:27         12.117683   -89.69632

I have a map that I am plotting these points onto.
I can plot the points just fine
plot1 <- map + geom_point(data=dat, aes(x = lon, y  = lat))

map is an object I made with ggmap, but it's not that important to include here.
The following code produces a line connecting points as lon increases
plot1+geom_line(data=dat, aes(x=lon,y=lat,colour="red"))

I can't figure out how to connect the points by the vector POSIXlt object Description
I know that in this small example I could easily reorder the points using something like dat2 <- dat[with(dat, order(Description)), ], and remake plot1 using dat2 and make the desired plot using the following code:
plot1+geom_path(data=dat2, aes(x = lond, y  = latd, colour="red"))

But for my much larger (hundreds of thousands of observations) dataset, this doesn't make sense as a solution without a bit more work to properly id each observation, which I will certainly end up doing anyway as part of additional data exploration.
Is there an argument I haven't discovered in geom_line for telling R how to connect the points?
I am admittedly still a novice at using ggplot2, and so, I apologize if I have missed something very simple.  I have been working on a lot of other code and learning, or at least using, several other packages, to work with this GPS data other spatial data available.  It's all a bit overwhelming... So many ideas, so little know-how! The larger point of this is to visualize (and eventually analyze) movement patterns and use of space by my study organisms, but for now, it would be great to visualize the data in a variety of ways to really get familiar with it.
If you have any recommended packages for working with spatial data and GPS data, I'd love to hear about them, as well.

A: You need the rows ordered by the date/time object to use geom_path. Since I think this is the best way to display the data we should focus on finding an efficient way to sort a large dataset. Obviously it would be good to get an idea of the scale of dataset you are working with. Millions of rows? Billions perhaps?!
Fortunately the data.table package does this very well indeed. Here is an example on a 1 million row table, with an ID column X, which the table is originally sorted on, an unsorted time column of 1 second observations, and two random columns for x and y, which takes < 1s on my laptop t sort according to date/time:
set.seed(123)
require(data.table)

#  Rows ordered on X, random order of unique date/time values of 1 second observations
df <- data.frame( ID = seq.int(1e6) , Desc = as.POSIXct(sample(1e6),origin=Sys.Date()) , x = runif(1e6) , y = runif(1e6) )
head(df)
#  ID                Desc         x         y
#1  1 2013-05-25 02:39:39 0.2363783 0.1387404
#2  2 2013-05-25 23:58:17 0.1192702 0.1284918
#3  3 2013-05-21 17:41:57 0.8599183 0.6301114
#4  4 2013-05-23 16:12:42 0.8089243 0.7919304
#5  5 2013-05-21 08:17:28 0.8197109 0.4568693
#6  6 2013-05-22 17:57:23 0.4611204 0.5358536
#  Convert to data.table
DT <- data.table(df)

#  Sort on 'Desc'
setkey(DT , Desc)
head(DT)
#          ID                Desc         x          y
#1: 544945 2013-05-18 01:00:01 0.7052422 0.52030877
#2: 886165 2013-05-18 01:00:02 0.2256636 0.04391553
#3: 893690 2013-05-18 01:00:03 0.1860687 0.30978506
#4: 932276 2013-05-18 01:00:04 0.6305562 0.65188810
#5: 407622 2013-05-18 01:00:05 0.5355992 0.98146120
#6: 138936 2013-05-18 01:00:06 0.5999025 0.81722902

#  Make data.frame to from this to use with ggplot2 (not sure if you can't just use the data.table directly)
df2 <- DT

So in your case you can try something like:
datDT <- data.table(dat)
setkey(datDT , Description)
dat2 <- datDT


text:
Q: Using Google Translate Code to Auto Translate Webpage onLoad How do you customize this code so that upon loading it will auto translate the page without clicking the select button. example i want to load the page automatically in spanish??

    The text is translated using Google translate.


text:
Q: What is a real-world use case for a marked transaction? I have read BOL about marked transactions and I can see contrived examples, but what is a real world use case for MARK'ed TRANSACTIONS?
After reading this I was thinking I would implement marked transactions henceforth in our large batch jobs that run over night. We already use TRANSACTIONS and log backups, but I was hoping to get a use case where this saved time for someone as opposed to just adding it because I just learned about it.

A: Marked transactions make it easy to do point-in-time restores without worrying about actual time. Instead, one restores to logical event.
As a practical example, consider an update that needs to be undone. Now, the update was such that a database restore is needed as wrong value was set to all the columns and original data is lost. Maybe a business analyst set VAT to 24% for all the products instead of a subset. We don't know what the previous VAT values were, so the update cannot be undone.
Restoring the database is simple, but how much of the transaction logs would be applied? At which point-in-time would one stop the log restores? Does the business analyst keep a detailed journal that records the beginning of the update? Maybe all that is remembered is that "it was done Monday afternoon". If there are lots of changes in the database, recovery to right spot is trial and error.
Should the update be done within marked transaction, the DBA will simply query msdb.dbo.LogMarkHistory table and pick symbolic name for the transaction. Log restore is then done with STOPBEFOREMARK = 'VAT update' parameter to stop at the precise point before marked transaction was started.


text:
Q: Java: having trouble calling a method from one class into another Still trying to grasp how classes and methods work in Java. To experiment, I tried to create a graphics class, with a void draw box method inside. Then, I try to call that method in the main method to try to draw those boxes. I'm getting "cannot be resolved to variable" errors which I believe means the main class can't see my other class for some reason?
Boxymain.java:
import java.awt.*;
import javax.swing.JFrame;

public class Boxymain extends Canvas {
    public static void main(String[] args){
        BoxyMethod c = new BoxyMethod();
        c.drawBox(window, Color.RED, 200, 300);

        JFrame win = new JFrame("Boxy Main");
        win.setSize(800,600);
        win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Boxymain canvas = new Boxymain();
        win.add(canvas);
        win.setVisible(true);
    }
}

BoxyMethod.java:
import java.awt.*;
import javax.swing.JFrame;

public class BoxyMethod {
    public void drawBox(Graphics window, Color c, int x, int y){
        window.setColor(c);
        window.fillRect(x, y, 100, 100);
        window.setColor(Color.WHITE);
        window.fillRect(x+10,y+10,80,80);
        }
}

Error text: "window cannot be resolves to a variable."

A: The error message is telling you exactly what is wrong. You're passing in a window variable into the drawBox method, but you don't declare or initialize such a variable in the main method before doing so, and so this cannot be done in Java.
BoxyMethod c = new BoxyMethod();
// *** window variable below is used but never declared prior to use
c.drawBox(window, Color.RED, 200, 300);

More importantly though, you're not doing Swing drawing correctly.
Instead, you should create a class that extends JPanel, give it a paintComponent(Graphics g) method override, and draw in that method. Then place that JPanel in a JFrame and display the JFrame. Please check out the Performing Custom Painting Swing graphics tutorial for more detail on how to do Swing graphics.
As an aside, do not follow that tutorial that you've linked to as it is 30 years out of date.

For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;

public class BoxyTest {

   private static void createAndShowGui() {
      JFrame frame = new JFrame("Boxy Test");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new BoxyPanel(200, 300));
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

@SuppressWarnings("serial")
class BoxyPanel extends JPanel {
   private static final int PREF_W = 800;
   private static final int PREF_H = 650;
   private int myX;
   private int myY;

   public BoxyPanel(int myX, int myY) {
      this.myX = myX;
      this.myY = myY;
   }

   @Override // so my JPanel will be big enough to see
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   @Override
   protected void paintComponent(Graphics g) {
      // call super method so that the JPanel can do housekeeping painting
      super.paintComponent(g);
      g.fillRect(myX, myY, 100, 100);
      g.setColor(Color.WHITE);
      g.fillRect(myX + 10, myY + 10, 80, 80);
   }
}


text:
Q: How get a ScrollBar to work on Only Left Frame Using Canvas? I am trying to get the ScrollBar to apply only to the LeftFrame.
When I use the Canvas setup the ScrollBar applies to the whole window.
Is there better way to setup a selectable long-list table?
Should I be using a listbox instead?
import tkinter as tk

root = tk.Tk()
root.geometry("1000x600")
# root.resizable(width=False, height=False)

def printname(event, i):
    print ("my name is", i)
    namelabel.configure(text="test" + str(i))

def onFrameConfigure(canvas):
    '''Reset the scroll region to encompass the inner frame'''
    canvas.configure(scrollregion=canvas.bbox("all"))

canvas = tk.Canvas(root, borderwidth=0, background="#ffffff")
leftFrame = tk.Frame(canvas, background="#ffffff", width=700, height=500)

vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=vsb.set)
vsb.pack(side="left", fill="y")
canvas.pack(side="left", fill="both", expand=True)
canvas.create_window((1,1), window=leftFrame, anchor="ne")

rightFrame = tk.Frame(root, background="#ffffff", width=300)
# vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
# canvas.configure(yscrollcommand=vsb.set)
# vsb.pack(side="right", fill="y")
canvas.pack(side="left", fill="both", expand=True)
canvas.create_window((1,2), window=rightFrame, anchor="nw")

# rightFrame = tk.Frame(root, width=400)
# rightFrame.pack()

leftFrame.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))

textlabel = tk.Label(leftFrame, text="Player List")
textlabel.grid(row=0)
for i in range(50):
    if (i % 2):
        w = tk.Text(leftFrame, height=1, fg="white", bg="black")
    else:
        w = tk.Text(leftFrame, height=1, fg="black", bg="white")
    w.insert(1.0, "test" + str(i))
    w.configure(relief="flat")
    w.configure(state="disabled")
    w.bind("<Button-1>", lambda event, a=i: printname(event, a))
    w.grid(row=7+i)

namelabel = tk.Label(rightFrame, text="Test", fg="white", bg="black")
namelabel.grid(row=1)

root.mainloop()

A: The short answer is that if you don't want something to scroll, don't put it in the canvas. Scrolling a canvas means every item added to the canvas will scroll. There's no way to avoid that. You can't scroll half of a widget.

Is there better way to setup a selectable long-list table?

Probably, though it depends on the data you're wanting to show. If it's a list of short strings, a Listbox is probably a better choice. If it's blocks of text, a single text widget with some tags and custom bindings might be better than multiple widgets.


text:
Q: Need help with a first name last name program I need help to create a program that allows the user to input their firstname and lastname separated by a space. I then need to display this information in reverse for example.
Input:
John Doe
Display:
Doe, John
Can someone please help me with this, I have been trying to do this for over a week and have made no head way. I am programming it in Visual Studio 2008 C#. Thanks in advance for any and all help.

A: Try using the String.Split Method for string, with the required seperator.
Once you have the string array, you can use these to format a return value. (see String.Format Method (String, Object[])
Please also remember that your string array might not contain the correct number of entries you expect so you might want to check out Array.Length Property (myStringArray.Length).

A: Here's the approach I would take.

*

*Find the index of the space in the name.

*Extract the first name, by extracting all characters from the beginning of the string to just before the space you found.

*Extract the last name, by extracting all characters from just after the space to the end of the string.

This should be enough to get you started.  The methods you need will be in the String class.  If you get stuck on any of these steps, post what you've tried and where it fails.

A: name.Split(' ').Reverse().Aggregate((acc, c) => acc + ", " + c);

A:         string fullName = "John Doe";
        string[] nameParts = fullName.Split(' ');
        string firstName = nameParts[0];
        string lastName = string.Empty;

        if (nameParts.Length == 2)
        {
            lastName = nameParts[1];
        }
        else
        {
            for (int i = 1; i < nameParts.Length; i++)
            {
                lastName += nameParts[i];
            }
        }

        string reversedName = lastName + ", " + firstName; // Cory Charlton rocks ;-)

A: #include<iostream>

using namespace std;

int main()
{
    //variables for the names
    char first[31], last[31];

    //prompt user for input
    cout<< "Give me your name (first then last) and I will reverse it: ";

    cin>> first;
    cin>> last;

    cout<< "Your name reversed is " << last << ", " << first << endl;

    return 0;
}


text:
Q: Packet loss with Ubuntu 11.10 I have a machine with Windows 7 and Ubuntu 11.10
In Ubuntu I have about 30% packet loss when I make pings either to my router gateway or to an external site such as google.com, so my internet connection goes very slow.
Since the network works perfectly fine in Windows 7 (without any packet loss), I assume it's not a problem of the line.
Is there anything I could change in network settings or something similar in order to make this work correctly in Ubuntu?
I edit to say that I found my solution here (the problem was defective realtek drivers):
How do I stop my ethernet network connection from dropping?

A: I have experienced Packet Loss in Ubuntu, too under two circumstances:

*

*Routing Issues when having multiple Interfaces in the same Network
I had two LAN Ports in the same network and the I suppose the routing of both interfaces overlapped and they took turns in sending/receiving from and to the network. The problem stopped as soon as i disabled one interface
$ sudo ifconfig eth1 down

*Connections are timing out because they tried to use IPv6 at times
Especially when doing DNS Requests while apt-get updating some repositories, even official ubuntu ones, cannot be resolved to an ip.
See https://help.ubuntu.com/community/WebBrowsingSlowIPv6IPv4 in this case.
Also you should give more information, like complete output of both
$ ifconfig

and
$ route

Under no circumstances should you need to remove network-manager or any other preinstalled network management software. They work just fine, when configured correctly.
I'm sorry that both points are rather blurry, but I guarantee, that both happened as I told them.

A: There is a similar problem like you and there a solution to it says:
I finally managed to download wicd with much pain and patience and I'm happy to report it is much better now. It works good enough to browse the web and post this although it is too early to say it's it is back 100%. The problem must have been with the network manager package.

and here is the link to the problem.

A: I have had earlier versions of Ubuntu fail to get along with older router firmware. Check to see if your router is older and there is newer firmware available.
You can find instructions on the internet to update this. You need to type your routers IP address into the URL bar with a web browser (there is a manufacturers default IP address for your model number). If you do not have the username and password than you will need to find the manufacturers default credentials from on the web as well. If you still cannot get in, than reset your router (small push button somewhere) and than try the default login credentials again. There should be a update button/menu in the UI somewhere to automatically update (you may need to download the file for it to update with).
NOTE: If your router has been configured, any changes to the router will be permanent. You can only go back to the manufactuaers defaults with the reset button. Any of your current deviations from the default settings will be lost!


text:
Q: How to set data using Nest REST API? I have tried to set the target temperature the following script and it returns {"error":"Invalid content sent"}.  How can I set the target temperature using the REST API?
#!/bin/bash

DATA='{"devices":{"thermostats":{"DEVICE_ID":{"target_temperature_f":75}}}'

curl --cacert curl-ca-bundle.crt -L -X PUT --data $DATA "https://developer-api.nest.com/?auth=ACCESS_CODE"

Note that I redacted the actual device id and access code.

A: The following works:
#!/bin/bash

DATA='{"target_temperature_f":76}'

curl --cacert curl-ca-bundle.crt -v -L -X PUT "https://developer-api.nest.com/devices/thermostats/DEVICE_ID?auth=ACCESS_CODE" -H "Content-Type: application/json" -d DATA


text:
Q: How to use php monolog I've heard a lot about monolog(https://github.com/Seldaek/monolog) & trying to use that in one of our app. But, can't able to fig. out how to use that. Don't know it's I'm only can't able to get any documentation of it or really it has no documentation at all.
We want to log all our errors in DB & as well as send an email notification about error when it'll get generate. For sending email we are using Swiftmailer(swiftmailer.org).
I can be able to run this sample code from Github link,
<?php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

// add records to the log
$log->addWarning('Foo');
$log->addError('Bar');

but can't able to understand how to use this with DB & any other email library.

A: You posted an example yourself. Instead of StreamHandler use one or more of the other handlers that monolog is offering.
You have to look into the code of the handlers to see which dependencies they need. Look inside the Monolog directory and you'll find the Handler classes. Code is the most reliable documentation.
<?php

use Monolog\Logger;
use Monolog\Handler\SwiftMailerHandler;

use Swift_Mailer;
// ... more dependencies you need

// create your Swift_Mailer and Swift_Message instances

$handlers = [
    new SwiftMailerHandler($swiftMailer, $swiftMessage),
    // add more handler you need
];

$log = new Logger('name', $handlers);

$log->warning('Foo');
$log->error('Bar');

You have to create a Swift_Mailer and Swift_Message instance for the SwiftMailerHandler. Instead of pushHandler, you can add an array of handlers into the Logger constructor.
The Swift_Message instance is used for every log message where the message replaces every time the mail body.
I can only suggest to you to read the monolog code for information where a further documentation is missing.


text:
Q: Validate date column in CSV with Data Factory I'm attempting to use Data Factory to import a CSV file from Azure File storage into SQL Azure. So far I'm using the copy data task to read the CSV and save into SQL Azure.
My CSV file contains 2 date columns with the date in the format dd/MM/yyyy. How can I set Data Factory to validate and read dates in this format?

A: You can follow my step, I tried this and Data Factory can validate and read dates in "dd/MM/yyyy" format.
This is my csv file, also has two columns with the date in the format "dd/MM/yyyy".

The difference between us is I import my file  from Azure blob storage into my Azure SQL database by using Copy Data.
If you want Data Factory can validate and read dates in "dd/MM/yyyy" format, during File format settings, you must set the the schema,  specify the column type and the format. Please see this picture:

After copy active completed,  the date with "dd/MM/yyyy" format will be parsed to the default format "yyyy-MM-dd".

Hope this helps.


text:
Q: How to run the java script functions using .net library class? I have the JavaScript string for calculating some formulas, but I need to execute the scripts from C#.
Like JS formula string:
function(params) {
  var itemAmount = 0,
      itemsList = JSON.stringify(params.items),
      billAmount = 0,
      itemDiscountAmount = 0,
      itemDiscountPercentage = 0,
      maxDiscountAmount = 0,
      maxDiscountPercentage = params.maxDiscountPercentage;
  return {
    billAmount: billAmount,
    maxDiscountPercentage: maxDiscountPercentage,
    maxDiscountAmount: maxDiscountAmount
  };
});

I need to pass the param and get the result using C#.

A: Maybe you are looking for a JavaScript Engine like this:
        var es = JsEngineSwitcher.Instance;
        es.EngineFactories.AddChakraCore();
        es.DefaultEngineName = ChakraCoreJsEngine.EngineName;
        var je = es.CreateDefaultEngine();

        je.EmbedHostType("console", typeof(Console));
        je.Execute("console.WriteLine('HELLO CHAKRA')");

And this should work for your :
        je.Execute("function foo(a,b,c){return a+b*c;};");
        je.CallFunction<int>("foo", 1, 2, 3);

https://github.com/Taritsyn/JavaScriptEngineSwitcher
BTW, if you need JSON in your code, this can be of help:
https://github.com/douglascrockford/JSON-js

A: The JavaScript sample is not using most of the variables, and is same as :
function(params) {
  return {
    billAmount: 0,
    maxDiscountPercentage: params.maxDiscountPercentage,
    maxDiscountAmount: 0
  };
});

Which in C# is something similar to anonymous function :
new Func<dynamic, dynamic>(params => new {
    billAmount = 0,
    maxDiscountPercentage = params.maxDiscountPercentage,
    maxDiscountAmount = 0
});


text:
Q: How to add attribute name to JFactory::getEditor() I have a question about this method (JFactory::getEditor()):
I want to implement a Editor in my component (front) and I've done this:
$editor =& JFactory::getEditor();
$params = array( 'smilies'=> '0', 'style'  => '1', 'layer'  => '0', 'table'  => '0', 'clear_entities'=>'0');
echo $editor->display( 'desc', '', '400', '400', '20', '20', false, $params );

I copied this from the Joomla documentation: https://docs.joomla.org/JFactory/getEditor
But my question, how I can add the name attribute to pick it up on your controller when you click the submit form?
Thanks in advance.
UPDATE:
In the OnDisplay () method's first parameter is the name of atribute name, I leave as eventually would, if anyone can serve data collection.
$editor =& JFactory::getEditor();
$params = array( 'smilies'=> '0', 'style'  => '1', 'layer'  => '0', 'table'  => '0', 'clear_entities'=>'0');
echo $editor->display( '**ATTRIBUTE_NAME**', '', '400', '400', '20', '20', false, $params );

In controllers:
$data = JFactory::getApplication()->input->get('**ATTRIBUTE_NAME**', '');

If you want more information about the parameters, you can see Joomla file:  /plugins/editors/tinymce.php.

A: I found a solution researching the library editor. The kind where the "OnDisplay" method is found is in the following path, in case you want to see all their parameters or other methods.

/plugins/editors/tinymce.php

To use it do the following:
$editor =& JFactory::getEditor();
$params = array( 'smilies'=> '0', 'style'  => '1', 'layer'  => '0', 'table'  => '0', 'clear_entities'=>'0');
echo $editor->display( 'ATTRIBUTE_NAME', '', '400', '400', '20', '20', false, $params );

And to pick through a submit a form to do the following in their respective controllador:
$data = JFactory::getApplication()->input->get('ATTRIBUTE_NAME', '');

I hope that helps.


text:
Q: TYPO3 rte_ckeditor plugin I try to insert a FontAwesome plugin in CKEditor.
https://github.com/brstuff/ckawesome
  externalPlugins:
    ckawesome:
      resource: "EXT:siteconfig/Resources/Public/JavaScripts/RTE/Plugins/ckawesome/plugin.js"

I copied the Font Awesome fonts and CSS in that folder and the RTE gives a button which popups the dialog.
However the console gives me a "Uncaught TypeError: $(...).select2 is not a function"
In plugin.js is:
CKEDITOR.scriptLoader.load(CKEDITOR.plugins.getPath('ckawesome') + 'resources/select2/select2.full.min.js');

This path is correct, however should a script in this way be loaded on a different method with TYPO3 CKEditor?

A: First of all, perhaps this extension solves the issue
https://github.com/DirkPersky/rte-ckeditor-fontawesome
it add font awesome, so no need for you to reinvent that wheel :-)
Second, if you really want to found out why your own solution doesn't work, try and find out, what path
CKEDITOR.scriptLoader.load(CKEDITOR.plugins.getPath('ckawesome') + 'resources/select2/select2.full.min.js');

resolves to, perhaps something is wrong there.


text:
Q: How is "X" pronounced in English? The letter x can sound (most often) like [gz] and [ks]:

*

*[gz] in words like exam, exactly.

*[ks] in word like extra, hexagon, etc.

I have found that x is pronounced [gz] whenever it's in or before the stressed syllable, and [ks] otherwise.
And in a few cases it sounds like [z] when at the beginning of a word.
Do you know other ways of pronouncing this letter? Or other facts that have something to do with its pronunciation?

A: As a rule of thumb, the prefix ex- is pronounced with /ks/ when the prefix is stressed.:

*

*'excellent

*'exit

*'exile

*'execute

When this prefix is not stressed, then if the first sound in the root (the part after the prefix) begins with a voiced sound, the prefix will be pronounced with /gz/:

*

*ex'am

*ex'asperate

*ex'actly

*ex'ist

This is still true, of course if the prefix is followed by a silent /h/ in the writing. In this case of course, the first sound in the root is a vowel sound:

*

*ex'hibit

*ex'haust

*ex'hort

*ex'hilaration

If the prefix is followed by an unvoiced sound, then it will be pronounced with /ks/

*

*ex'pect /ɪkˈspekt/

*ex'tol /ɪkˈstəʊl/

*ex'hale /eks'heɪl/

*ex'ceed /ɪkˈsiːd/

*ex'foliate /eksˈfəʊlieɪt/

In the words above we see roots beginning with the following voiceless sounds respectively /p, t, h, s, f/ and so the prefix used /ks/ instead of /gz/.
There is a different prefix in English exo- meaning 'outer' or 'outside'. The meaning is similar to ex- which tends to mean 'out of' or 'from'. The prefix exo- is always pronounced with /ks/. It is a Greek prefix. Another Greek prefix, hex(a), meaning 'six',  is also pronounced with /ks/:

*

*hexagon

*hexadecimal

X at the end of a word nearly always represents the sounds /ks/.

*

*latex

*six

*Bronx

Very few words  in English begin with X. Those that do are mostly from Greek and tend to be pronounced with /z/:

*

*xylophone

*xanthar gum

*xenon

A: I think your summary is good for UK English. Any controversy would be in how to pronounce the leading X

Xavier

You have stated the normal UK pronunciation, which I think follows from the French. If you see the X-men films you will see it pronounced

exavier

I have seen statistics that suggest that this is a more usual US pronunciation

A: In answer to the question, "Do you know other ways of pronouncing this letter?"
It is pronounced like the letter Y or unpronounced in the case of Bexar County (the county in which San Antonio, Texas, is located). So, it is said by locals like bear, or Bayer—the company known (among other things) for making aspirin/ASA. But honestly, that is an edge case, probably not worth committing to memory.
Cf. Bexar County, Texas Talk Notes on Wikipedia and Bexar County pronunciation on forvo.com.


text:
Q: Fluid, static, fluid - 3 row layout Okay, I've seen static, fluid, static layouts, but now I've come to a design that requires fluid, static, fluid layout.
As in:
+-------------------------------+
|             FLUID             |
+-------------------------------+
|      I SHALL                  |
|          TAKE 400             |
|              PIXELS           |
+-------------------------------+
|             FLUID             |
+-------------------------------+

How would I achieve this one with pure CSS?
Worth noting is that the fluid rows might be 0 pixels if the screen is too small.
As for what I have tried, nothing yet - have no clues what to begin with.

A: You can use display: table-row; on the elements.
see fiddle

A: Actually, I managed to hack my way around with absolute positioning.
HTML:

CSS:
#header, #footer
{
    background-color: blue;
    position: absolute;

    width: 100%;
    height: 50%;

    top: 0;
    left: 0;

    z-index: -1;
}

#footer
{
    top: auto;
    bottom: 0;
}

#content
{
    height: 400px;

    background-color: black;

    position: absolute;

    width: 100%;
    left: 0;

    top: 50%;
    margin-top: -200px;
}

While this one works, it seems usable only 3-row scenario... or, it will always fail to answer the No-SQL world famous question does it scale?. With that I mean, I doubt this will work for 4 rows, where three are being fluid, with one having a min-height.
Fiddle.

A: Try this simple layout structure
CSS
.wrapper{
   width:100%;
}
.fluid{
    width:auto;
    background:red;
    padding:20px;
}
.fixed{
    width:360px;
    margin:0 auto;
    background:green;
    padding:20px;
}


text:
Q: Building an error component logit using mlogit I want to build an error component logit using R's mlogit library.
I have considered my dataset as a panel dataset (i.e. each row indicates an alternative) and then build an error component logit model.
While I understand that in order to build a mixed-logit model, I need to add the list of covariates in rpar command. However, I do not want to estimate random parameters for the covariates but for the intercept term.

A: In a multinomial logit model you can estimate J-1 alternative specific constants (intercepts). The easiest way to make them random is to create alternative specific indicators.
For example, let's say that you have three alternatives: 1, 2 and 3, and that these are stored in the variable alt. Now you can create two new variables called alt_1 and alt_2, which are equal to 1 for alternative 1 and 2, respectively, and 0 otherwise.
data$alt_1 <- ifelse(data$alt == 1, 1, 0)
data$alt_2 <- ifelse(data$alt == 2, 1, 0)

Now use the mlogit.data() function.
In your model you would then specify alt_1 and alt_2 to be random parameters following some distribution. Now you have random alternative specific constants and you estimate the mean and standard deviation. If you want them to be simple error components with zero mean and unit standard deviation, you can fix the mean and sd parameters for the intercepts to 0 and 1 respectively.


text:
Q: Can't understand Iteratee.fold in Play 2.0 I'm reading the source code of Iteratee.scala: https://github.com/playframework/Play20/blob/master/framework/src/iteratees/src/main/scala/play/api/libs/iteratee/Iteratee.scala
Specifically the convenience method for constructing the "fold" iteratee.
def fold[E, A](state: A)(f: (A, E) => A): Iteratee[E, A] = {
  def step(s: A)(i: Input[E]): Iteratee[E, A] = i match {

    case Input.EOF => Done(s, Input.EOF)
    case Input.Empty => Cont[E, A](i => step(s)(i))
    case Input.El(e) => { val s1 = f(s, e); Cont[E, A](i => step(s1)(i)) }
  }
  (Cont[E, A](i => step(state)(i)))
}

On each of the case statements, we are calling Done or Cont constructors. But where are these constructors defined? I infer that these must be implementors of the Iteratee trait but I couldn't find them by doing ctrl+F for "extends Iteratee."

A: See docementation or source:
object Done {
/**
* Create an [[play.api.libs.iteratee.Iteratee]] in the "done" state.
* @param a Result
* @param e Remaining unused input
*/
  def apply[E, A](a: A, e: Input[E] = Input.Empty): Iteratee[E, A] = new Iteratee[E, A] {
    def fold[B](folder: Step[E, A] => Future[B]): Future[B] = folder(Step.Done(a, e))
  }
}

It's not a constructor. Done(s, Input.EOF) means Done.apply(s, Input.EOF). Same with Cont.

A: Done doesn't need to directly extend Iteratee. It could extend another class or trait which then extends Iteratee. You could search for class Cont and then follow the inheritance relationship from there.


text:
Q: Cocoa / Interface Builder how to set up the preview in Adobe Photoshop SDK for Retina display? We have a problem with our PS plug-ins for Mac OS X when used on Apple's Retina Display MacBook Pro models. The issue is that the preview image appears multifold.The problem as such also exists with the unchanged Dissolve example from the current PS CC SDK.
So I'll use that to illustrate the issue.
The Dissolve example plug-in displays a 4-up preview window on a Retina display as shown below:

Interestingly, with the dialog still up, if one connects an external display (we used Apple 27" Cinema LED display) and moves the dialog back and forth between Retina display and external display, the preview actually switches between the 4 up and the regular preview as shown below as the dialog crosses over from one display to the other.

Spontaneously we know of nothing we could do within the plug-in that would correct this but I guess the answer might be in interface builder. What we'd need to do is designate the preview to use physical pixels somehow. It reports its size back and will get used accordingly in our product.
Has anyone else solved this problem? Is it required to migrate to Xcode Version 4.6, Base SDK 10.7, Apple LLVM compiler 4.2, OS X Deployment Target 10.6 as Adobe did with the CC SDK or can the problem also be solved using Xcode Version 3.2.5, GCC 4.2, SDK 10.6 as used in the PS CS6 SDK?
Edit November, 28, 2013: Added a bounty of +50 rep. I am looking for a working step by step instruction on how to make the aforementioned Adobe PS CC SDK "Dissolve" filter example work on both Retina and regular displays.
Edit December, 6, 2013: Bounty expired...


text:
Q: Why won't this explode() print? I'm trying to make a video downloader and am putting the final touches on it but I can't get this simple explode() function to print to test.  Here's the code, it's very simple
$url = explode('"', $line);
print_r($url[1]);

I'm trying to take this input file: "http://cdn1.videolb2.videsite.com/18092013/2014182.mp4?nvb=20130917201517&nva=20130919201517&hash=0bd94fc24498f1f1bd7e1", and extract the url by exploding at the " but it won't print. What am I doing wrong?


text:
Q: Sub-Report with 2 detail Section I have a main report with subreports.one of the subreport has a detail section based on dataset table, it works fine. When I tried to add another detail section binding another table from the same dataset the entire subreport shows nothing. I need the 2nd detail section to look like continuation of 1st detail section.To display both sections within a box. Any suggestions?

A: Thats not possible bro..... if you want second detail section to follow first detail section then you need to add 2 sub reports in 2 detail section one for one dataset and another for second dataset.


text:
Q: Redirecting standard error to file and leaving standard output to screen when launching makefile I am aware that for redirecting standard error and output to file I have to do:
make > & ! output.txt

Note I use ! to overwrite the file. But How can I redirect standard error to file and leave standard output to screen? Or even better having both error and output on file but also output on screen, so I can see how my compiling is progressing?
I tried:
make 2>! output.txt

but it gives me an error.

A: Note that > it enough to overwrite the file. You can use the tail -f command to see the output on screen if it is redirected to a file:
$(make 1>output.txt 2>error.txt &) && tail -f output.txt error.txt

A: You can do this simply with pipe into tee command.  The following will put both stdout and stderr into a file and also to the terminal:
make |& tee output.txt

Edit
Explanation from GNU Bash manual, section 3.2.2 Pipelines:

If '|&' is used, command1's standard error, in addition to its
  standard output, is connected to command2's standard input through the
  pipe; it is shorthand for 2>&1 |. This implicit redirection of the
  standard error to the standard output is performed after any
  redirections specified by the command.

A: You are reading bash/sh documentation and using tcsh. tcsh doesn't have any way to redirect just stderr. You might want to switch to one of the non-csh shells.


text:
Q: Pasting text to VirtualBox FreeDOS I'm looking for an easy way to paste text from a Windows host machine to a VirtualBox VM running FreeDOS.
I've been mounting the VHD in Windows to move files, but this is not convenient to paste text snippets. Does anyone know of a way to get around the limitation of not having GA to paste plain text?

A: It's also possible to paste an entire file using "keyboardputfile".  An excerpt from https://forums.virtualbox.org/viewtopic.php?f=9&t=80315&start=15#p414817:
VBoxManage controlvm <uuid|vmname>
keyboardputscancode  [ ...]
keyboardputstring  [ ...]
keyboardputfile

A: All information I can find about VirtualBox shows that it does not have this ability. Which is strange, being it is nothing special to simulate keystrokes from the clipboard. Both Hyper-V and VMWare can do this without guest additions.

A: If you just need to send simple strings, you can use the "VBoxManage controlvm keyboardputstring" tool.
For example:
$ vboxmanage controlvm freedosvm keyboardputstring 'hello'

which'd essentially type "hello" into the VM for you, by issuing key-press key-release commands.
If you need to do anything more complicated like pressing key combinations, you can use the lower level keyboardputscancode interface:
$ vboxmanage controlvm freedosvm keyboardputscancode 1D 23 A3 9D

This'd type "ctrl-h". You have to manually manage modifier keys and both pressing and unpressing keys (1D is the hex scancode for press-left-ctrl, 23 is 'h', and a3 9d are the release scancodes for the same)
There's documentation on IBM PC scancodes here.


text:
Q: Bootstrap dropdown menu does not show up I'm using bootstrap3.1 recently, and I want to use "dropdown menu", here is official doc: http://getbootstrap.com/components/#dropdowns
The code is very sample and it likes below:

  <button class="btn dropdown-toggle sr-only" type="button" id="dropdownMenu1" data-toggle="dropdown">
    Dropdown

  </button>

Action

Another action

Something else here

Separated link

But somehow it does not work, you could check here : http://jsfiddle.net/52DDe/1/
Is there something I forgot to load ?
thanks,
++++++++++++++++++++++++++++++++++++++++++
The problem is resolved now by add css:
Note :
To resolve this problem, CSS needs to set:
.test>.dropdown>.dropdown-menu
{
    display: block;
    margin-bottom: 5px;
    position: static;
}

And use div:

.....

A: Remove the "sr-only" class, and the code will work.
http://v3.bootcss.com/javascript/#dropdowns may be helpful, though it's in Chinese.
Look what-is-sr-only-in-bootstrap-3 for more about "sr-only".

A: In my case I removed link to bootstrap.min.js what was included before dropdown.js and it worked for me.
The Dropdown looks like following (with little thymeleaf code what can be ignored):

    <button id="dropdownProperties" class="btn btn-primary
        dropdown-toggle" type="button" data-toggle="dropdown"
        aria-haspopup="true" aria-expanded="false"
    >
        Immobilien
    </button>

                ADRESSE


text:
Q: Argument Exception thrown by PtrToStructure Can someone please explain the following Argument Exception : The structure must not be a value class to me please.
It's being cause by the following line of code in my program:
Marshal.PtrToStructure(m.LParam, dbh);

given that dbh is of type:
[StructLayout(LayoutKind.Sequential)]
public struct Device_Broadcast_Header
{
    public int dbch_size;
    public int dbch_devicetype;
    public int dbch_reserved;
}

Thanks

A: You cannot call this particular Marshal.PtrToStructure overload with a value type (i.e. a struct).
If you call this overload you can receive an instance of your type back.

A: Sorry for not giving a code example, but here is a link that might help you.
Here is the key text from the above link:

The problem does nothing with the
  RegisterTraceGuids API.
According to the doc of
  Marshal.PtrToStructure(IntPtr, Object)
  http://msdn.microsoft.com/en-us/library/30ex8z62.aspx
  , it throws the ArgumentException that
  you saw when structure layout is not
  sequential or explicit or structure is
  a boxed value type.
In this case, the structure is
  declared as sequential, however, the
  elements in the array
  (traceGuidReg[i]) are boxed on the
  managed heap  because of the array
  object, thus you got the error "the
  structure must not  be a value class."
You would need to use the overload
  Marshal.PtrToStructure Method (IntPtr,
  Type)
  http://msdn.microsoft.com/en-us/library/4ca6d5z7.aspx
  and assign the result of
  PtrToStructure to the array elements.

A: [StructLayout(LayoutKind.Sequential)]
public class Device_Broadcast_Header_Wrapper{
    public Device_Broadcast_Header Header
}

Device_Broadcast_Header_Wrapper wapper = new Device_Broadcast_Header_Wrapper();
Marshal.PtrToStructure(m.LParam, wapper);


text:
Q: Same callback to multiple buttons in kivy I'm trying to use the same callback to multiple buttons, I wanted something that returned a boolean value to use the callback like it's done here, but I couldn't find something like this. Is there a way to do it without binding a different function to each button?
import kivy
from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button

kivy.require('1.9.2')

class VelhaGame(GridLayout, Screen):
    def __init__(self, **kwargs):
        super(VelhaGame, self).__init__(**kwargs)
        self.cols = 3
        self.rows = 3
        self.font_size = 100

        self.button1 = Button(text='', font_size=self.font_size)
        self.add_widget(self.button1)
        self.button1.bind(on_press=self.player_turn)

        self.button2 = Button(text='', font_size=self.font_size)
        self.add_widget(self.button2)
        self.button2.bind(on_release=self.player_turn)

        self.button3 = Button(text='', font_size=self.font_size)
        self.add_widget(self.button3)
        self.button3.bind(on_release=self.player_turn)

        self.button4 = Button(text='', font_size=self.font_size)
        self.add_widget(self.button4)
        self.button4.bind(on_release=self.player_turn)

        self.button5 = Button(text='', font_size=self.font_size)
        self.add_widget(self.button5)
        self.button5.bind(on_release=self.player_turn)

        self.button6 = Button(text='', font_size=self.font_size)
        self.add_widget(self.button6)
        self.button6.bind(on_release=self.player_turn)

        self.button7 = Button(text='', font_size=self.font_size)
        self.add_widget(self.button7)
        self.button7.bind(on_release=self.player_turn)

        self.button8 = Button(text='', font_size=self.font_size)
        self.add_widget(self.button8)
        self.button8.bind(on_release=self.player_turn)

        self.button9 = Button(text='', font_size=self.font_size)
        self.add_widget(self.button9)
        self.button9.bind(on_release=self.player_turn)

        self.player1 = True

    def player_turn(self, *args):
        if self.player1:
            self.player1 = False
            if self.button1:
                self.button1.text = 'X'
            elif self.button2:
                self.button2.text = 'X'
            elif self.button3:
                self.button3.text = 'X'
            elif self.button4:
                self.button4.text = 'X'
            elif self.button5:
                self.button5.text = 'X'
            elif self.button6:
                self.button6.text = 'X'
            elif self.button7:
                self.button7.text = 'X'
            elif self.button8:
                self.button8.text = 'X'
            elif self.button9:
                self.button9.text = 'X'
        elif not self.player1:
            self.player1 = True
            if self.button1:
                self.button1.text = 'O'
            elif self.button2:
                self.button2.text = 'O'
            elif self.button3:
                self.button3.text = 'O'
            elif self.button4:
                self.button4.text = 'O'
            elif self.button5:
                self.button5.text = 'O'
            elif self.button6:
                self.button6.text = 'O'
            elif self.button7:
                self.button7.text = 'O'
            elif self.button8:
                self.button8.text = 'O'
            elif self.button9:
                self.button9.text = 'O'

class VelhaGameApp(App):
    def build(self):
        game = Screen()
        table_screen = VelhaGame()
        game.add_widget(table_screen)
        return game

if __name__ == '__main__':
    VelhaGameApp().run()

A: If you see that you're repeating your code it's often mean that you need a loop. Also the method you're binding receive as a first argument instance of button that called it.
import kivy
from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button

class VelhaGame(GridLayout, Screen):
    def __init__(self, **kwargs):
        super(VelhaGame, self).__init__(**kwargs)
        self.cols = 3
        self.rows = 3
        self.font_size = 100

        self.buttons = []

        for i in range(1, 10):
            button = Button(text='', font_size=self.font_size)
            button.bind(on_press=self.player_turn)
            self.add_widget(button)
            self.buttons.append(button)

        self.player1 = True

    def player_turn(self, instance, *args):
        if self.player1:
            self.player1 = False
            instance.text = 'X'
        elif not self.player1:
            self.player1 = True
            instance.text = '0'

class VelhaGameApp(App):
    def build(self):
        game = Screen()
        table_screen = VelhaGame()
        game.add_widget(table_screen)
        return game

if __name__ == '__main__':
    VelhaGameApp().run()

You can also create a subclass of Button class but that would be an overkill here.


text:
Q: Intel Real Sense C# Recording stream to a file I am trying to use the Intel Real Sense SDK to acquire some guided frames and then I am trying to stitch them using the Intel Stitching algorithm.
However, the SetFileName function is not writing the file to the directory.
Can you please help?
PXCMSenseManager pp = PXCMSenseManager.CreateInstance();

RaiseMessage("Starting...");

pp.EnableFace()
pp.Enable3DScan()

if (!string.IsNullOrEmpty(StreamOutputFilename))
{
    if (File.Exists(StreamOutputFilename)) throw new Exception("File already exists");

    {
        System.Diagnostics.Debug.WriteLine(StreamOutputFilename);
        pp.QueryCaptureManager().SetFileName(StreamOutputFilename,true);

A: Please refer to the solution here
int wmain(int argc, WCHAR* argv[]) {
// Create a SenseManager instance
    PXCPointF32 *uvmap = 0;
    pxcCHAR *file = L"C:\\new.rssdk";
    PXCSenseManager *sm = PXCSenseManager::CreateInstance();
    // Set file recording or playback
    sm->QueryCaptureManager()->SetFileName(file, 1);
    // Select the color stream
    sm->EnableStream(PXCCapture::STREAM_TYPE_DEPTH, 640, 480, 0);
    // Initialize and Record 300 frames
    sm->Init();
    for (int i = 0; i<300; i++) {
         // This function blocks until a color sample is ready
        if (sm->AcquireFrame(true)<PXC_STATUS_NO_ERROR) break;
        // Retrieve the sample
        PXCCapture::Sample *sample = sm->QuerySample();
        sm->ReleaseFrame();
    }
    // close down
    sm->Release();
    return 0;
}