How to automatically create a popup using a Google Chrome Extension on top of current page

Question: Right now, I am working on a Chrome Extension in which, after I download it to Chrome, it should automatically open a popup in the upper right of the screen and grey out the rest of the page. I have gotten it pretty much work when I just test the html file itself. Screenshot of an example website that is made with the html.
I am having trouble with two things:

I am lost on how to automatically open the popup when a new page follows a few conditions (specifically, the most important one is if the domain name of the page is contained in a database I will eventually use).

How to display the popup like it looked like in the screenshot (where it is not connected to the toolbar and it greys out the rest of the screen until your close).

For the first problem, I have tried researching "background pages," because that is what people from earlier posts have said you have to use in this type of situation. However, I just don't understand how to connect the background.js, for example, to my other html and javascript files. As well, to make matters worse, it seems Chrome has recently switched to something called "service workers" which I really do not know how to use. If I could do my project without these, that would be preferable.
Second, it seems that instead of applying to the current page, whenever I download my extension into Chrome and click on it in the toolbar, the popup in the upper right and the "greying out" only apply to the little page created by the extension. Screenshot of how only the little page created by clicking the extension shows up. Is there anyway I can make the popup shown in the first picture appear on the screen not connected to the toolbar with the greyed-out screen? Essentially as if it were overlaying the current page?
Thank you for your help. I have attached my javascript, html, and manifest files. I changed some unimportant text for privacy's sake (it's really just for strings that need to be displayed.) Note also that I am using an array of URL's to stand in for my database right now.

document.addEventListener('DOMContentLoaded', function () {

    chrome.tabs.getSelected(null, function (tab) {

        d = document;

        shorterUrlHttps = tab.url.substr(8);

        var hostName = shorterUrlHttps.substr(0, shorterUrlHttps.indexOf('/'));

        const hostNames = [
            "www.blah.com",
            "www.blahblah.co.uk",
            "www.blahblahblah.com"];

        var count = 0;

        for (let i = 0; i < hostNames.length; i++) {
            if (hostName == hostNames[i]) {
                count = 1;
            }
        }

        var popup = d.getElementById('extension-overlay');
        var companyName = d.getElementById('companyName');
        var company = hostName.substr(5,shorterUrlHttps.indexOf('.c',5))

        if (count == 1) {
            popup.style.display = 'block';
            companyName.innerHTML = company;

        }
        else {
            popup.style.display = 'none';
        }

        d.getElementById("extension-close-icon").onclick = function () {
            popup.style.display = 'none';
        }
    });
}, false);
<!doctype html>

    <title>LUX Rewards</title>

This is the example website

        <link href="https://fonts.googleapis.com/css?family=Montserrat:100,300,400,500,600,700" rel="stylesheet">

 <button
                    type="button" id="extension-close-icon"
                    style="background:url(closeicon.png);background-size:cover;position:absolute; top:13px; right: 13px; width:20px;height:20px;cursor:pointer;"></button>

blah

                    blah

blah blah blah

 blah blah blah

Answer: Your popup is declared via action or browser_action, which means it's a separate page with its own chrome-extension:// URL, shown in a separate window not related to the current web page.
The solution is to show your UI inside the web page as a DOM element using a content script.
To show it only on sites defined in a database, the best method is to register the content script dynamically only on the required urls, so the browser won't waste resources to run your content script on unrelated sites. In ManifestV3 you can use chrome.scripting.registerContentScripts (Firefox has a different API), which is available only in a non-content script e.g. the background script or the options/action page. If you want to avoid using a background script and allow the user to add the current site to the database, use the action popup to show the add/delete buttons.
manifest.json:
  "permissions": ["activeTab", "scripting", "storage"],
  "action": {"default_popup": "popup.html"},

popup.html (shown when the extension icon is clicked):
<button id=add disabled>Add</button>
<button id=del disabled>Delete</button>

popup.js:
const [btnAdd, btnDel] = ['add', 'del'].map(id => document.getElementById(id));
btnAdd.onclick = btnDel.onclick = toggleCurrentSite;
getData().then(({site, sites}) => {
  (sites.includes(site) ? btnDel : btnAdd).disabled = false;
});
async function getData() {
  const [[tab], {sites}] = await Promise.all([
    chrome.tabs.query({currentWindow: true, active: true}),
    chrome.storage.local.get({sites: []}),
  ]);
  const site = new URL(tab.url).hostname;
  return {site, sites, tab};
}
async function toggleCurrentSite(e) {
  const add = e.target === btnAdd || btnAdd.contains(e.target);
  const {site, sites} = await getData();
  const i = sites.indexOf(site);
  if (add && i < 0) sites.push(site);
  else if (!add && i >= 0) sites.splice(i, 1);
  else return;
  try {
    await chrome.scripting.unregisterContentScripts({ids: ['foo']}).catch(() => {});
    await chrome.scripting.registerContentScripts([{
      id: 'foo',
      matches: sites.map(s => `*://${s}/*`),
      js: ['content.js'],
    }]);
    await chrome.storage.local.set({sites});
    btnAdd.disabled = add;
    btnDel.disabled = !add;
  } catch (e) {
    document.getElementById('error').textContent = e.message;
  }
}

Finally, content.js adds the DOM element for your UI. To isolate your UI and styles use a chrome-extension:// iframe or a div with shadowDOM as explained in this topic.
Comment: Hello, thank you so much for your answer! Bear with me because I am basically brand new to html, javascript, and definitely to extensions. First, is that I all I need to change in my manifest.json or do I also need to add "content_scripts"? Second, for popup.html, is that all I need in  or should I add it to my existing html file? Third, how does popup.js both add URL's to a database and how does it connect to content.js (everytime I run the plugin and click "Add", it says "Nonexistent script ID 'foo'". Finally, what should I put it content.js specifically? And does it need an html file?
Comment: 1) No need to add `content_scripts` (these are static). 2) It's an example. 3) See the fixed code which now suppresses the foo error. 4) The examples are given in the topic I've linked.


Export all user policies using Pundit gem

Question: How do I can retrieve all user policies and scopes using Pundit Gem? I need to return a json object with all user policies to check permissions in Frontend javascript templates.
Using CanCanCan gem, I can do something like this:
class Ability
  include CanCan::Ability

  # ....

  def to_list
    rules.map do |rule|
      object = { actions: rule.actions, subject: rule.subjects.map{ |s| s.is_a?(Symbol) ? s : s.name } }
      object[:conditions] = rule.conditions unless rule.conditions.blank?
      object[:inverted] = true unless rule.base_behavior
      object
    end
  end
end

Is possible to do the same with Pundit?
Answer: I have the same requirement, I got the following code working per investigation:
def index
    classes = [Admin, BusNumber, Ticket, :ticket_statistics]

    permissions = { }

    classes.each do |clazz|
        policy =  Pundit.policy(current_admin, clazz)
        policy.public_methods(false).sort.each do |m|
            result = policy.send m
            permissions["#{clazz}.#{m}"] = result
        end
    end

    render json: permissions
end

the current_admin is the method to get the current login user, the code gives the following result
{
    "Admin.create?": true,
    "Admin.disable?": true,
    "Admin.enable?": true,
    "Admin.index?": true,
    "Admin.show?": true,
    "Admin.update?": true,
    "BusNumber.create?": true,
    "BusNumber.destroy?": true,
    "BusNumber.index?": true,
    "BusNumber.update?": true,
    "Ticket.index?": true,
    "Ticket.refund_by_admin?": true,
    "Ticket.show?": true,
    "ticket_statistics.overall?": true
}

Comment: will this work work namespaced models like `Foo::BarPolicy`?
Comment: @reiallenramos you can do this for namespaced policies:

`Pundit.policy(current_admin, [:foo, Bar]) # ==> Looks in Foo::BarPolicy`


grid view validation problem

Question: in a grid view how can i apply a validator to check if any of grid view rows with check box are checked or not.
i did it using the custom validator  like this but giving the error
"Control 'GridView1' referenced by the ControlToValidate property of 'gridCheck' cannot be validated. "
following is my code
what should i do please suggest me the alternate
<code>protected void gridCheck_ServerValidate(object source, ServerValidateEventArgs args)
    {
        foreach (GridView row in GridView1.Rows)
        {
            CheckBox cb = (CheckBox)row.FindControl("Chek");
            if (cb != null && cb.Checked)
            {
                args.IsValid = true;
                return;
            }
            else args.IsValid = false;
        }
    }
</code>
Comment: can you debug the application and tell whether check event is raising or not. Means if u checked a check box test it whether it is returning true or not
Answer: You'd have to add a template field column. Set the gridview to edit templates mode. (in your designer). You can drag and drop controls as usual and set their ids etc. Add your validator control, and set the id.
Comment: my project don't require to turn grid view in edit mode in that case how can i do this. Y direct as i did above doesn't work please let me know what else can i do ?
Comment: I meant "edit Templates" mode, in the designer...I am not talking about enabling "edit button" and all for each row. Click on the gridview's smart tag. Plz check this link if you are finding it difficult finding the smart tag... http://aspnetgoodies.files.wordpress.com/2007/12/grid-view-smart-tag.jpg

grid view validation problem


Why is cp_gullywash on the Attack/Defense mappool instead of Control Points mappool?

Question: On the Attack/Defense playlist, there's a map called Gullywash. However, it has a control points format rather than an attack/defense format. Why is it on the attack/defense mappool rather than the control points mappool?
Comment: Was this on an official server or found though the play multiplayer menu?
Comment: @Studoku It's a common map on official servers that are under the attack/defense gamemode
Comment: When did this happen? According to the changelog this was the case but was fixed in March 2013.
Answer: When Gullywash was added, it was accidentally put in the wrong map list because both Attack/Defense and Control Point maps use the format "cp_mapname".
This was, according to the changelog, fixed in updates in February and March 2013. If it's still happening, contact Valve.
Comment: I still see it when I click "show servers" for attack/defense, but it doesn't bother me. I was just curious. Thanks for the answer however :)


Measuring humidity through ceramic tile to deduce a course of action

Question: Just bought a house, and during the inspector noted in his report that the "shower step" (the door frame on which glass door rail sits) has a slope the wrong direction, causing water to accumulate against the rail, and probably infiltrating in the "step".
He said that if underneath it's concrete straight (it's in the basement) there is no cause to worry, and that I could probably just redo the silicon. When he inspected, he measured the humidity on the outside of the shower step, and it was at 100%. (using a General Tools & Instruments MMD5NP Pinless LCD Moisture Meter or somethign that looked like that.)
What I was planing on doing is:

Buy such an instrument.
Measure the humidity as a benchmark.
Redo the silicon
Wait a few weeks
Measure again and compare.

If the humidity stays the same, consult someone to help me with fixing the step, if the humidity drops, leave it like that and keep an eye on it.
My question is: Is that course of action viable, or I'm just wasting time and money?
Comment: If it is on a basement slab and there is no water outside the shower why fix something that is not broke. Concrete can pick up water from the ground level this may be the true source of the moisture.
Answer: Water penetration is usually destructive, such that damage is detectable without fancy instruments. The tile grout on the outside of the curb would show signs of being wet and/or you might see efflorescence from evaporating moisture. As well as loose tiles, wet floor, etc.
If the shower curb is indeed sloped towards the outside of the enclosure then it was not designed correctly, which is a concern. Put a level on it. In the end, if it's been like that for some time and there are no signs of damage, it may not be something to worry too much about. The detector is not the "be all end all", a few years back inspectors did not even use them.
Comment: I would add that if the curb is sloped wrongly, you might have a reason to be suspicious of the rest of the installation as well, so give the whole shower a close inspection for cracked grout and maybe even do a fill test. But if that passes, re-caulk the door frame and be done with it --- you don't need any fancy moisture meter.
Comment: It's very very slightly slanted. But you have to use a good level to see it. The rest of it seems nicely done. @PaulPrice For the fill test, would you put water above the curb, up to the side of the door rails to see if water can slip between the rails and the curb?
Comment: No, the fill test is something normally done on a shower pan to pass code. A temporary plug is inserted in the shower drain and the the pan is filled up to *just below the curb*, the inspector makes a chalk mark then comes back to see if the water level dropped.
Comment: Ok, ok, so it's to check the rest of the shower's pan for unknown problems, but not the calking between the rail and the curb. Thanks! I'll do all that!
Comment: The only reason I mention the fill test is that we had a lovely tiled shower that did not pass it: after filling the pan, it was raining downstairs. The test may not be necessary and certainly isn't urgent, but it's relatively easy to do and it may allow you to discover problems before they become PROBLEMS.


How to set global route in GNOME Network Manager

Question: My apologies for the German screenshot. I don't know how to force the settings window to be in English.
When configuring networks, GNOME offers to configure the routes manually. However, it does not seem to allow a route with a netmask of 0.0.0.0, as can be seen on the screenshot. If I change the mask to anything more specific, even 22.214.171.124, the grey apply button in the upper right corner turns green.
Is that a bug? Is it on purpose – but which purpose? (On the command line, that is no problem at all.)
Comment: "*the grey apply button in the upper right corner **turns green***", don't you mean "*doesn't turn green*"?
Comment: No, it will turn green when I change the net mask. It will stay grey as long as the net mask is `0.0.0.0`
Answer: Network-Manager default GW handling
The network-manager always uses the last configured interface as default gateway. In case of LAN vs. WIFI this is almost always the WIFI. To avoid this, the option "Use only for resources on this connection" can be set to the WIFI.
The problem with this setting is: It only works in the LAN+WIFI environment. If the LAN is not present, the WIFI will not be used as default gateway.
Network-Manager Dispatcher for special setups
The network-manager does not support profiles from the gnome GUI. But the network-manger dispatcher supports it. See the ArchWiki for a WLAN/Eth toggle sample.
# file: /etc/NetworkManager/dispatcher.d/wlan_auto_toggle.sh

#!/bin/sh

if [ "$1" = "LAN_interface" ]; then
    case "$2" in
        up)
            nmcli radio wifi off
            ;;
        down)
            nmcli radio wifi on
            ;;
    esac
fi

Comment: I don't share that view. `/etc/network/interfaces` makes no mention of my interfaces, as everything is so automatic. On the other side, my network is there right in front of my eyes, I can enter values, that is _very easy_ indeed. (Or, would be, if it allowed me to save my values.)
Comment: @MPi Yes, the `/etc/network/interfaces` is empty in a default desktop ubuntu installation. Which is okay, since the network-manger does the configuration.  Have you tried to use a static (non-dhcp) configuration with a default gateway?
Comment: This question in not about how to do it all in config files. I suppose I could do that. The question is _why_ does Network Manager not allow me to configure the default route? The original question, BTW, was: Why does Ubuntu choose my WIFI over my LAN, and I landed in NM to change the metric…
Comment: The network-manager always uses the last interface, which was configured via DHCP as default gateway. In case of LAN vs WIFI, the WIFI always wins. If you don't want that, that the "Use only for resources on this connection" (the german version "Diese Verbindung...") for the WIFI.
Comment: And what happens when I pull the plug?
Comment: -> no default gateway. Added update to post.
Comment: This is a cool answer, thank you. I'm not sure how to handle it, though: It does not answer my question, but it does in fact solve my problem.


Sql query using joins to find sum of quantity

Question:

Here,in billtran table the productid=1 is repeated twice
I want to find the sum(billtran.quantity) of each productid separately

select Query1:
 select name,billtran.quantity from product inner join billtran on product.id=billtran.productid where product.id in(select id from product)

Comment: Please don't use images. Paste the tables and code as text here instead. A request shall be understandable without any picture. You *can* use images, too, but they shall only enhance the information (e.g. an added ERM diagram). Some people cannot even see your images, because they are blocked for them.
Comment: Then, group by product name and sum the quantities
Comment: `product.id in (select id from product)`? What is this supposed to do? Make sure an ID read from the product table exists in the product table??? This makes no sense at all.
Answer: Per comment:
select name, SUM(billtran.quantity) from product inner join billtran on product.id=billtran.productid where product.id in(select id from product)
GROUP BY NAME

My additions in caps
Note: where product.id in(select id from product) is an entirely useless where clause and should be removed. Queries don't have to have a where clause and don't need one that says a table id should be in all the ids in that table (always true)
I would hence have written this one as:
SELECT
  p.name,
  SUM(b.quantity) as sumof_quantity
FROM
  product p
  INNER JOIN billtran b ON p.id=b.productid
GROUP BY
  p.name

Answer: First of all you have to get the sum of  the quantity according to the product_id
SELECT  product.name, SUM(billtran.quantity) AS value_sum
    FROM billtran inner join product on product.id= billtran.product_id where product.id in(select id from product )
    GROUP BY product_id;

This will be the result:
name    quantity
abc      6
xyz      1
pqt      3

You can get the same result by grouping the product.name as well:
SELECT  product.name, SUM(billtran.quantity) AS value_sum
FROM billtran inner join product on product.id=billtran.product_id where product.id in(select id from product)
GROUP BY  product.name;

Comment: Your top query only works because it automagically picks a random product name per id; other enterprise grade dbs (and mysql in ONLY_FULL_GROUP_BY mode) wouldnt accept it
Answer: Very simple query. Pls check below:
select product.name,sum(billtran.quantity) from product inner join billtran on product.id=billtran.productid group by billtran.productid


What are the consequences of marking a method async in C# 5.0?

Question: From what I understand in order to use await I have to be inside of a method which is marked as async. If that's the case, I can use await on any Task<Thing> to somewhat synchronously retrieve the value of the Task's result.
Task<bool> task = new Task<bool>(() => false);
task.Start();

int result = await task;

To do this I need to be inside of a method marked with async.
What I want to ask here is what exactly is the meaning of async and what are the consequences of marking a method with async.
Also, what's the difference between these two?
Task<bool> Foo() {
  var task = new Task<bool>(() => false);
  task.Start();
  return task;
}

async Task<bool> Foo2() {
  var task = new Task<bool>(() => false);
  task.Start();
  return await task;
}

I can both use them with await from inside an async method.
var res1 = await Foo();
var res2 = await Foo2();

Is the only difference that Foo2 can use await in it's body, while Foo can't?
Comment: With `async`-`await` you should always use `Task.Run` to create your tasks.
Comment: @PauloMorgado What's the difference from using the constructor?
Comment: it's not usal to instantiate a Task using it's constructor (although possible). Unless you want to create but not start it. As for the difference between `Run` and `StartNew`, please refer to Stephen Toub's blog post: http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx
Answer: It just alerts the compiler that the method may contain await expressions.  Which enables it to do a consistency check on the method return value.  And enables the rewriting logic built into the compiler that makes it transform the method into a hidden class.
If you don't actually use the await operator in the method body then this rewriting doesn't need to occur and the async keyword isn't needed either.  If you use async anyway then you'll get an otherwise benign warning (CS1998) to point out that your code is probably not what you intended to write.  A good diagnostic.
Comment: @JakubArnold Sure, [you can look at it that way](http://blogs.msdn.com/b/pfxteam/archive/2013/04/03/tasks-monads-and-linq.aspx).
Comment: I'd say it has also another effect: it wraps any returned value in a `Task`.
Comment: @svick So in another words, `Task` is a monad? :P
Answer: The main purpose of the async keyword is to avoid conflicts with code used in prior to C# 5.0 In other words we could say to maintain backword compatiblity.
Prior to C# 5.0 you could have used identifiers/types as await
void Somemethod()
{
    int await = 5;//identifier
    await myAwait = new await();//type
}

Above code is completely valid in prior to C# 5.0(in C# 5.0 also this is valid unless and until you use it in async method), What happens if await is added as a reserved keyword in c# 5.0? Your code won't compile. and that would be a breaking change.
So to maintain backward compatiblity language designers chosen to make await as a contextual keyword. So next question arises await is going to be a contextual keyword but what is the context here?
Well, there comes the async keyword, presence of async just enables the await keyword. and it makes the compiler to emit AsyncStateMachineAttribute to the method as well.
I didn't talk anything about how async method is transformed assuming you know that already or that is beyond the point of the question.
Comment: What has .Net 4.5 have to do with this? `await` works in .Net 4.0 too. I think you meant to say C# 5.0 whenever you said .net 4.5.
Comment: @svick How can you make async/await work in .Net 4.0?


Modifiying array pointers inside a function

Question:     void nothing(int* buffer)
    {
        int* temp = new int[5];
        for (int i = 0; i < 5; i++)
        {
            temp[i] = i;
        }
        buffer = temp;
    }

    void main(int argc, char* argv[])
    {
        int* a = new int;
        nothing(a);
        for (int i = 0; i < 5; i++)
        {
            cout << a[i] << endl;
        }
        system("pause");
    }

Why can't I get new address from buffer? I'm trying to pass an array(pointer) to function and modify it inside.
output:
 -842150451
-33686019
-1414812757
-1414812757
0

expected:
0
1
2
3
4

Comment: See [this](http://stackoverflow.com/questions/4426474/is-passing-pointer-argument-pass-by-value-in-c) question and corresponding answer.
Answer: You need to pass by pointer to pointer (or as others have pointed out reference to pointer), i.e. int ** and then assign using *buffer = temp and call function using nothing(&a).
If you don't do this, the changes you make to the buffer variable are lost when you leave the function. Think of the pointer variable itself like just any number, where as the thing it points to lives on after the function has ended.
However, I would recommend that you use a std::vector instead:
void nothing(std::vector<int> &buffer) {
    ...
}

int main(int argc, char* argv[])
{
    std::vector<int> a;
    nothing(a);
    for (int i = 0; i < 5; i++)
    {
        cout << a[i] << endl;
    }
    system("pause");
    return 0;
}

Depending on your scenario you might even want to change the nothing function into an initializer style function, i.e. returning an object directly:
std::vector<int> nothing() {
    std::vector<int> temp;
    // fill vector here
    return temp;
}

int main(int argc, char* argv[])
{
    auto a = nothing();
    for (int i = 0; i < 5; i++)
    {
        cout << a[i] << endl;
    }
    system("pause");
    return 0;
}

This is a lot more C++-ish and prevents you from having to handle deleting the array manually.
For actually generating the data into the vector, take a look at Initialization of std::vector<unsigned int> with a list of consecutive unsigned integers
.
Answer: Important prelude: If you can, using vector instead of arrays/pointers.  We would all encourage this as much as possible!  It's quite possible to program for months on end, writing some quite complex software, and never have to call new or delete and never have to worry about all those nasty C problems.

Just stop using temp!
void nothing(int* buffer)
{
    for (int i = 0; i < 5; i++)
    {
        buffer[i] = i;
    }
}

This will take, as input, a pointer to your array.  And it will then write directly to that array.
Your earlier code created a second array.  Every time you call new you get a new array. int* temp = new int[5];.  For this approach to work you would need to copy data in the temp array to the buffer array.  But, you can't copy arrays (easily) in C.
buffer = temp;  // This *doesn't* copy any array

This line did nothing.  The two arrays still exist, and no data was copied as a result of this.  The local variable called buffer was modified here ; but the change was minor -- buffer used to point at the old array and now it points at the new array.  And because buffer was a local variable, it lost all meaning as soon as the function returned (it pointed to non-local data, but the buffer pointer itself is still local.
In shorty, your original nothing function did nothing useful.  It created a new array, put some values into it, then it ignored it.  The buffer variable inside main was not affected by your function.
Answer: a is passed by value to nothing, so changing the copy of it in nothing has no effect on a.  You'd have to pass if by reference or, as @villintehaspam says, pass a pointer to the pointer.
Answer: "I'm trying to pass an array(pointer) to function and modify it inside"
But what your code does is that it allocates a memory for 1 int, passes a pointer to this memory to your function and your function allocates an array and attempts to assign an address or this newly allocated array to the passed pointer, i.e. it tries to modify the pointer itself.
Try to pass int** instead of int* and let the caller do:
int* a;
nothing(&a);

Also note that in C++ it should be rather rarity than a common practice that a function dynamically allocates some resources and throws a burden in a form of responsibility for freeing these resources (even using specific means, in this case calling delete[]) to the caller. Consider using STL containers such as std::vector or in case you have to stick with C-style arrays, then at least prefer those with automatic storage duration.
Answer: temp is a local variable, declared inside nothing(). This means that the memory for temp is lost when nothing() returns. You can't get the data back from inside a local variable - hence the garbage.
Comment: The problem isn't that temp is a local variable, because the value in temp is copied into buffer. The problem is that buffer is *also* a local variable.
Answer: The pointer buffer is being passed by value (which is the default in c++), and that means a copy is created. You then modify this copy. This being c++, you can pass a reference instead:
void nothing(int*& buffer)

This way, the original object is passed, not a copy.


How can I apply a max-height to an iframe but keep it at 100% width?

Question: I'm creating a relative (not fixed) video background in which YouTube provides the video source.
The main parent container has a max-height of 600px, but in doing this, the bottom part of the YouTube video gets cut off. Is there any way to apply the max-height of 600px to the iframe as well, but keep it at full width and responsive?
HTML

{video-area:content}

CSS
#video-container {
  width: 100%;
  overflow: hidden;
  position: relative;
  max-height: 600px;
}
.video-area {
  position:absolute;
  top: 0;
  width: 100%;
  height: 100%;
}
.video-table {
  display:table;
  width:100%;
  height:100%;
  max-width: 960px;
  margin: 0 auto;
}
.video-cell {
  display:table-cell;
  vertical-align:middle;
  padding:2em;
  box-sizing: border-box;
}
.embed-container {
  position: relative;
  padding-bottom: 56.25%;
  height: 0;
  overflow: hidden;
  max-width: 100%;
}
.embed-container iframe,
.embed-container object,
.embed-container embed {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

Comment: I think you are asking how to maintain the proper aspect ratio of the video but don't let it get taller than 600px. When you get to a wide screen, the video would be centered but maintain the aspect ratio and on smaller screens you would get a full width video because the height is less than 600px. Does that seem right? Is the video in the code the actual video you are trying to fit or is it the same aspect ratio as the intended video or do you know for sure that it will be 4:3, 16:9, or something else?
Comment: Exactly! Ideally it would create the same result as background-size:cover and background-position: 50% 50% for images. I'd like to account for all types of aspect ratios if possible, but if not, the video above works.
Comment: Cool. You can do it, I or someone else, will post an answer in a bit, but the style will need to to be adjusted per aspect ratio. Unfortunately it won't work as easily as an img tag or background size contain. The trick involves 0 height and percentage top or bottom padding on the child element.
Comment: You're the man, @JasonB! I really appreciate you taking the time to help me out with this one.
Comment: If you use `max-height: 600px` while also using `height: 100%` in the `iframe` the video will adjust nicely based on the `width` of the screen without cutting the video. Have you tried that @Weebs?
Comment: I did, but in applying the max-height: 600px to the iframe, the video is no longer at 100% width.
Comment: So what you want is the video to be `100%` without the black padding right and left, correct?
Comment: @AngelPolitis Exactly, but of course with the max-height: 600px.
Comment: Can this even be done?! Think about it, if you have a `4:3` video and a `16:9` screen the video's width will be quadrupled to be `100%` of the screen, but so will the height _(will reach `12`)_ in order to preserve aspect ratio. If you limit the height, let's say to `10`, either the part of the video exceeding the max-height will be cut or you'll lose aspect ratio.
Comment: Even if the video has the same aspect ratio as the screen, let's say `16:9`, if you limit the maximum height to `600px` the video's width will have to drop  to `~1066px` to preserve ratio. If you force the width to be `100%` and `100% <> 1066px` in the screen either the video is clipped or you lose ratio.
Comment: Okay, there doesn't have to be a max-height:600px, but if the iframe can be vertically aligned to the middle of the #video-container parent  - which has the max-height:600px -- that would work too.
Answer: I'm not sure if this is a hack, but this works for me when I went across the same case. You can use flex properties to stretch your child div inside parent div.
Made some structure changes to your original one:

#video-container {
  width: 100%;
  overflow: hidden;
  position: relative;
  display:flex;
  height:600px;
  -webkit-align-items: stretch;
 -ms-align-items: stretch;
 -moz-align-items: stretch;
 -o-align-items: stretch;
 align-items: stretch;
}
iframe
{
  width:100%;
}
.video-area {
  position:absolute;
  top: 0;
  width: 100%;
  height: 100%;
}
.video-table {
  display:table;
  width:100%;
  height:100%;
  max-width: 960px;
  margin: 0 auto;
}
.video-cell {
  display:table-cell;
  vertical-align:middle;
  padding:2em;
  color:white;
  box-sizing: border-box;
}

.embed-container object,
.embed-container embed {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

{video-area:content}

Answer: You can maintain the aspect ratio of an element by setting it's height to zero, and adding top or bottom padding as a percentage. It seems odd when you first encounter it, but the percentage padding calculates a percentage of the parent element's width.
The video seems to not be the standard 4:3 or 16:9 but more like 2:3 so I set a max-height:600px; max-width:900px; on the parent container. The child container has width:100%; height:0; padding-top:66.67%; The 66.67% figure is 2/3 (or 600/900), not some magic number, so you'll need to adjust it for different aspect ratios.
That's it. Now the video will fill the width of the screens that are less than 900px wide and maintain it's aspect ratio of 66.67%. Once the 900px width is exceeded, video is limited so the height won't go over 600px. I put margin:0 auto to center it, you'll want to handle the background so it looks good in your design.
https://codepen.io/Jason_B/pen/BYLqod
Answer: iframe
{
    height: -webkit-fill-available;
}

Add this height property to your Iframe


Displaying a date range with labels, what is the best practice?

Question: So I have a date range, for example:
21-05-2022 - 27-05-2022

Bear in mind that the date is in dd-mm-yyyy format. So my user wanted to add the "Start Date" and "Due date" before the date. So it becomes like this:
Start date: 21-05-2022 - Due date: 27-05-2022

I don't think that's right (at least according to my gut), if you want to use labels I think you need to put line breaks like so:
Start date: 21-05-2022
Due date: 27-05-2022

What do you think? I need some validation for this to present to them. Thank you
UPDATE:
For more context, this is supposed to be displayed in a web page I'm working on. So I'm currently working on a web page, mostly text, with a layout like so:
TITLE OF THE TASK
Start Date: 07-04-2022
Due Date: 17-04-2022

Header 1

Content...

It's not about displaying a date range picker component, it's just displaying the date text. In fact, the date cannot be changed (at least in this page)
Answer: From where did you get putting dates in the same line is not correct? Nearly all travel websites have the dates arranged in a line, which, in addition to following the reading order from left to right in continuity with the rest of the information, perceptively helps to better interpret which is the beginning ← and which is the end →.
What you can propose is placing the label on top:
Comment: I'm sorry I didn't put more context. I've updated my question above with the current situation I am currently on.
Answer: My assumption here is what users need is to scan, read and compare the dates. To achieve this, in the following example I used alignment, a monospace font for the dates and larger text size for them to make them stand out a bit better opposed to their label. Those are just examples of what you can do to make it more usable.

Or horizontal ...
Comment: I think this is the acceptable answer for me. Especially when you demonstrated the horizontal version. Thank you so much!
Answer: Listing labeled individual dates (your example) is correct. Showing a date range with a general label like "Time frame" is correct. Labeling both dates in a range (at least in American English) is incorrect.
If your company is large enough to have a copy editor, head of content, or tech writer on staff, this is something with which you should enlist their help. They are likely going to have a style guide that is considered the source of truth for your company.
Comment: Unfortunately I don't have any of those people to reach out for, hence I am asking it here :D
Answer: If one looks at travel booking sites, or doctor appointment sites, or pregnancy due date caluculators, the date format is dd-mm-yyyy presented in the same line. I guess this is the industry standards and the users are familiar with this way of functioning. Hence this becomes a control variable. In UX research, particularly, during the usability tests when we test new features of a product design control variables play a huge part as familiarity with the function or a feature makes the users tasks less cumbersome.
Comment: I'm sorry I didn't put more context. I've updated my question above with the current situation I am currently on.
Answer: Related data like a period, a start and end, an interval or however you want to call it, is based on the same basic rules on the language/region of the application/website. Most of the world like US/Europe are used to analyzing data from left -> right and top to bottom, but 1st and most important is LEFT to RIGHT. (If you would build something for Japan it would be different).
So, if dates are part of an interval/period and related, it would be best to place them next to each other on the same line, because a period can be compared with a "sentence", and it makes sense to be displayed and read in one go.
So it's natural to have Date 1 followed by a Date 2 which is an event further in time related to Date 1.
How to place the label that's up to your design/consideration.
Regards.


Why BIOS isn't recognizing USB drive during installation?

Question: I have a laptop that I would like to install ubuntu on. This laptop has windows xp on it, but windows wont load. I have ubuntu loaded onto a usb drive, but the computer I am trying to install it on will not recognize the usb drive in the BIOS menu.
Comment: Do you mind adding more information? Like, the kind of Laptop you have? What version of Ubuntu you're installing and how you went about obtaining the live-usb? What do you mean Windows wont load? Is there an issue with Windows or is it hardware related?
Comment: I appreciate the quick reply. The laptop is an old emachines with an AMD athlon processor. The version of ubuntu is 12.04.What do you mean "obtaining the live-usb"? And as far as Windows, When I start up the laptop, after the loading screen for window, a blue creen comes up and says Unmountable boot volume.
Comment: Reason I was asking about the laptop was to see if I could find information on the BIOS settings. Also, how did you load Ubuntu onto the usb drive? And any relevant information you want to add should be put into the body of the question using the edit button. Lastly, I was asking about your Windows distribution because I thought there may have been anissue with the harddrive. But if the windows logo is showing, I doubt that its an hardware issue.
Comment: I should point out that some BIOS don't support booting from usbs...
Comment: Ahhh. Ill add the info into the body. And I followed all of the instructions on the website to get it onto the usb drive. Ive gone into the BIOS menu, and It says "boot from removable device". Would that not be USB?
Comment: Sorry not sure. Do you know the exact model of your laptop? Emachine has numerous series each with quite a bit of different models.
Comment: M6810. And I appreciate you helping
Comment: It alo wont let me boot from disk drive so i guess it could be something to do with my mobo.
Comment: Sorry, tried checking emachine's website for documentation. That failed miserably. Google search turned up [this](http://forum.notebookreview.com/emachines/502926-booting-usb-m6810-possibly-dead-hdd.html) someone else with _identical_ problems. Only other idea I can think of is trying to boot using a live-cd instead of a live-usb.
Comment: Thanks. But I cant manage to boot from my disk drive.
Answer: you may enter the bios and chose the boot device and then save the bios setting and reboot.Though you do not really need to change the boot priority.In fact my samsung laptop always come across this phenomena,it's my solution.It seems that by entering the bios and pretending to change and save the bios setting can make the computer recognizing the usb device.
Answer: Ran into same problem, answer was that you have to go into the BIOs option about Hard Disks. In mine it saw the USB as a second HDD so I had to change the priority so it would read the USB "Hard Disk" first instead of the actual HDD which it did by default.
Comment: The OP stated that the BIOS menu does't recognize the USB. So changing the boot order won't help...


Citizens do not use the road I made for them in Cities Skylines

Question: I have a little bit traffic problem in some highway. So I tried to relieve the road from it but citizens do not use the road I made for them.
I want them to follow the light blue colored path but they follow the dark blue one and it causes traffic. How can I make them to follow the right road?
Comment: What happens if you make the extra road shorter (Or the existing route longer?) I'm not too knowledgeable about the traffic modelling, but if they prefer to pick the shortest path over the one with the least traffic that might be an issue.
Comment: I think that should work If I make the road long enough yes. But unfortunately I completely changed my design so I can't try it anymore. Thanks anyway.
Comment: The real question is: is that road really needed? Most of the traffic flows downwards, I don't think that's the solution. And as Paul suggested, maybe the new road is seen as longer than the old one and therefore not prefered.
Answer:
The road appears to be much longer than the alternative. The wide curve towards east does not seem to be necessary. It should be possible to build it much shorter.

The road does not seem to solve the actual traffic problem. Most of the cars passing through the heavily congested area seem to want to go south, and those which want to go north seem to want to change from the westmost road to the eastmost road. The road with the dark blue arrow doesn't seem to have any congestion, so the light blue one isn't really needed as an alternative.

What I would recommend in this case is to feed all the four roads coming from or heading to the north into a roundabout. There already appears to be one in the south. And then I would create a bridge to accomodate specifically those cars which come from the north via the western road and want to go north via the eastern road. But there doesn't seem to be a reason to do this here. It should be possible to do this much further north. Perhaps over the cloverleaf exchange in the north, or even further north.
Answer: It seems to me that your biggest problem is that the cars merging in from the two left-hand roads coming from the top of the screen don't have enough time to choose lanes after the two roads merge and before the intersection where they need to either turn right into the roundabout or go straight ahead back towards the top of the screen.  Just moving those two intersections further apart might help.
But I also agree with Philipp that the whole thing looks way overcomplicated.  This is how I'd redesign it, at least to start with:

Now the short two-way road segment coming off the roundabout is gone entirely, along with the problematic intersection at its end.  The two roads coming from the top of the screen now merge long before entering the roundabout, giving traffic plenty of time to merge and choose lanes, and lane math should guarantee no traffic jams at the merging point.
Note that any traffic that wants to come in from the top of the screen and go back up now has to go through the roundabout.  But you shouldn't be having much traffic taking such a weird route anyway — or, if you do, there's likely a problem somewhere else that you need to fix.
(I have noticed that the game sometimes generates weird external traffic that just wants to make a U-turn and exit the map the same way it came in.  If that's what's happening, you could probably handle it just by adding single highway ramp from the incoming side to the outgoing side of the highway near the map edge.  No need to let that useless traffic get anywhere near your actual city!)

Ps. If making the middle roads single-lane creates problems further up at the cloverleaf interchange, I'd also consider keeping them two-lane up to the point where the first ramps of the cloverleaf branch off, and maybe even all the way across the cloverleaf.  But if I was designing this from scratch, I'd definitely first try using one lane only for them.  Or even redesigning the whole interchange at the top of the screen so that the roads going across the left-to-right highway are kept entirely separate from the on- and off-ramps to that highway.
(Right now, you only have partial separation: while vehicles going across are presumably supposed to use the bypass bridges over the cloverleaf, they can instead take the middle roads through the cloverleaf and create needless congestion there.)
Frequently, in Cities: Skylines, having more lanes than you need just pushes problems to where those lanes end.  Instead, a good set of rules of thumb is to:

use no more lanes than you need,
keep the number of incoming and outgoing lanes the same at least in busy intersections, and
keep intersections on multi-lane roads as far apart as possible, so that vehicles have time to change lanes (and also so that, if a temporary traffic jam does form, it doesn't spread across multiple junctions).

FWIW, the cloverleaf interchange fails the last rule, which is one reason why it's not so great for high traffic volumes, both in-game and in real life.
Comment: A traffic jam cause by a cloverleaf can be fixed by changing the cloverleaf into a stack interchange.


how to use a pointer inside struct in C

Question: I have a two struct, one is linked list.
typedef struct Mark{
       int  people;
       Node *nodeyy;
}Mark

typedef struct Node{
       struct node next;
       int value;
}Node

if i allocated memory for a node, let say
 Node *node1=malloc( sizeof(struct Node));

And I also allocated memory for a bookmark, let say
 Mark *mark1=malloc( sizeof(struct Mark));

I want to make the pointer nodeyy in the mark1 points to the same thing as node1, how can i do that?
I think that
 mark1->nodeyy=node1;

is definitely wrong.
Comment: Now that you have edited the code, why do you think mark1->nodeyy = node1 is wrong?
Answer: its correct now:
You will have to initialize the pointer or point it to an existing variable that you know won't go out-of-scope. BUT since node1 is dynamically allocated, you're just assigning one pointer to another, this creates a sort of reference to the newly allocated memory pointed by node1.
mark1->nodeyy = node1;

After this statement, mark1->nodeyy and node1 point to the memory location returned by the malloc(sizeof(Node)).
Comment: sorry, typo , i mean  Node *nodeyy;
Answer: change the int* in struct Mark to Node*
typedef struct Mark{
       int  people;
       Node *nodeyy;
}Mark

then you can do
mark -> nodeyy =  (Node *) malloc(sizeof(Node))

Comment: i though mark-> nodeyy just a reference to  a node, why we need to allocate memory for a reference? What is the reason we can not just say mark->nodey=node1; ?
Comment: ya but mark->nodeyy is an int* in your code and it cannot hold the address of struct Node
Comment: sorry, typo , i mean Node *nodeyy;
Comment: we can say mark1->people=10, can we say mark1->nodeyy= node1; ? My question: is that the malloc steps necessary?
Comment: because node1 is just a type(just like primitive types int,float). you need to create variables of that type and make mark->nodeyy point to that variable.
Comment: if you have already created a variable for Node1, then you can do mark1->nodeyy=node1

how to use a pointer inside struct in C


I'm being haunted by an "Authentication dialog" and need help

Question: Like the title says I'm being haunted. No matter what I fill into the damned prompt it says the information is wrong and asks if I want to try again. It just won't stop.
Here is a picture of the satanic ritual that I must go through:
Evil authentication thing
It is followed by this: Dubious prompt
Now I suspect it has something to do with "Gmail feed" (seen in the 2nd picture) because I managed to raise the update timer to 90 minutes instead of 1 minute and it has helped. But I want it removed entirely. I have looked around and I've found nothing that helped me.
I should mention that I'm a monumental noob when it comes to PCs. I hope this whole deal doesn't look like I'm not serious. I'm just so annoyed by it that a lot of words just shoot out.
Answer: I found the answer! "Muon Package Manager" saved me. Just run Muon PM and search for "plasma-gmailfeed", right click and mark for removal. Restart and your hell is over!
I hope this can help someone else with this problem.
Thank you Muon Package Manager!


Is there a program that tracks the running times of computer games?

Question: I think I spend way too much time on computer games and would like to know exactly how much time I spend on them, in hopes that this will help me refrain myself from playing...
Is there a program that can give me a detailed report on how long these game processes run per day?
Comment: There is.. It's called a girlfriend.
Comment: Doesn't Steam do this?
Comment: Nor does Steam help for non-steam games (yes, it can launch them, but I'm pretty sure it doesn't track playtime etc).
Comment: i also find that steam gets it wrong quite often.
Comment: This sounds more like a [SU] question to me.
Comment: @Pubby8: It does, yes. Not sure if it works in offline mode.
Comment: @Bora I installed the upgrade to girlfriend, WIFE, and now my gaming time is down to near 0 :-(
Comment: @Bora, it may save me time, but it'll help me lose money.
Comment: @MatthewRead: It's a bit on the edge. Could as well stay here, it has to do with gaming, after all.
Comment: For consoles, certain TVs has a display mode which displays the amount of time played at every half hour interval,
Comment: If you're on Windows 8 or later, you can use the Task Manager (Ctrl + Shift + Esc). Simply go to "*App history*". Make sure you've checked "*Show history for all processes*" under "*Options*". The CPU time will give you a rough estimate of how long the game was running. However, CPU time depends on the CPU load. If your game doesn't put a lot of load on your CPU, the value might be much lower than you'd expect. If the game makes use of multiple cores, it could even exceed your expectations. For instance, a game that constantly puts 100% load on 2 cores will read 2 hours for every hour you play
Answer: There's ManicTime. It's great... and comes with a free usable version. It's stored in a local database...
Answer: Well there is Raptr.com and the downloadable client that tracks the amount of time you play a game not very detailed but it just counts the hours you play for each game.
Comment: I checked this site, unfortunately it gives incentives to play, so it's unacceptable, sorry.
Comment: incentives to play? as far as I know it just shows you what you've earned in the game and just records it.
Answer: You can also try Wakoopa. It monitors all running apps in your system, including games.
Answer: XFire's client will do this for you. They also provide game time profile images that you can add to forum signatures and other websites.
Comment: I checked this site, unfortunately it gives incentives to play, so it's unacceptable, sorry.
Comment: and they closed the service now.
Answer: TimeSnapper does this and it also takes screenshots periodically. (I remember this working quite well even for games, e.g. Left 4 Dead.)
Answer: I use RescueTime, it's cross platform, online, lets you set targets and even gives you a weekly summary email.
I've been using it for years and, even if the Sunday evening productivity emails can sometimes be depressing, I think it's helped me strike the right balance between games and work.


Should we change the site name to Mind?

Question: Following up on previous questions, should we change the site title to Mind?
Jeromy Anglim proposed some criteria for a good site title, which I think we ought to adopt for this question.

Short
Accurate in communicating scope
Unique

The first question to consider, then, is "Should we change the site title at all?" Based on these criteria, the answer seems to be yes. First, "Cognitive Sciences" is not short (neither is it particularly long, but that is not the criterion). Second, "Cognitive Sciences" does not accurately communicate the scope of the site, which also includes non-cognitive approaches to studying the mind, such as ecological psychology and possibly psychodynamics, and other non-representational approaches to the study of mind. The current title therefore only fully satisfies one of these criteria for a good site title.

NOTE: To prevent this from becoming a discussion with no possibility of a definite answer, you may simply downvote this post if you disagree with the proposed criteria or my conclusion that based on these criteria, we ought to change the site name.

I will give my own analysis of whether we ought to change the name to Mind based on these criteria in an answer.
Answer: There is already a Mind SE doing well in proposal, which is similar to this one in scope, but of a lower quality threshold.
This one is much more academic in scope, and requires a more academic sounding title to differentiate it. I think Cognitive Science and Psychology is just fine.
Comment: Update: this was renamed to _Mental Fitness_, and that beta has since been closed.
Comment: Ah, bollocks. I don't think Cognitive Science and Psychology is a good title by these criteria, and Mind and Behavior is probably not unique enough. Maybe best just leave it as it is, after all.
Answer: Thanks for getting this thread started. I agree with your analysis of "cognitive sciences". I think there have been a few discussions of titles like "Mind". The benefit of such names is their generality.
The challenge I see is that  names like "mind" don't directly align with existing discipline terms like "cognitive science", "psychology", "neurosciences", etc. Thus, it might be slightly more difficult to show connection to users.
With regards to "mind" specifically, I think the term "mind" has associations more with the phenomena of consciousness (i.e., thoughts, beliefs, attitudes, etc.) as opposed to the neurological basis, or behavioural aspects of interest to psychology and related fields.
Comment: Oh, that's a good point. Mind might discourage some neuro-oriented researchers the way our current name does some psychologists. Okay, that means we're definitely in "X and Y" (and possibly Z) territory. I still think it should satisfy the criteria, and that a title which satisfies all three criteria does not mention or imply any specific field. "Mind and Behavior" and "Mind and Brain" seem to be the viable candidates, then.
Answer: Previously proposed options have fallen along the lines of Brain and Behavior, Mind and Brain, Psychology and Neuroscience, etc. Although these options have some immediate appeal, specifically mentioning any field or unit of analysis is almost guaranteed to fall short of the Accurate Scope criterion by according special status to certain (sub)fields. For instance, researchers who do not adopt the view that mind is equal to behavior will likely be put off by Brain and Behavior, while Psychology and Neuroscience appeals to basic researchers, but excludes others (notably psychiatry).  Thus, I posit that a title which satisfies all three criteria does not mention or imply any specific field.
This leaves, in my mind, only three viable options: Mind and Brain, Mind and Behavior, or simply Mind. However, I would argue that an explicit inclusion of Brain in our site title is tantamount to an explicit inclusion of Neuroscience, and that it thus does not fully satisfy the Accurate Scope criterion. It also seems that not all of the brain actually falls within the scope of our site: for instance, I would not think that neuroimmunology falls within the scope beyond the extent it applies to mind and behavior. Mind and Behavior is accurately scoped and unique, but it is not very short, and further, the and Behavior strikes me as redundant.
By exclusion, this leaves Mind as the only viable site title: it is short, accurate and unique, and it is furthermore the only title which satisfies all three of these criteria, and does so impressively well. In my view, Mind fully captures the scope of our site and effectively excludes potential false positives, and should therefore be adopted post-haste.
Comment: I think that **Mind** is not a technical enough term. If we choose a name that is *too basic* I fear we'll frighten off experts. OTOH we also want to include everybody, and our current name doesn't do that terribly well.
Comment: @JoshGitlin I can't imagine any real cogsci researcher seeing a link to mind.stackexchange.com and thinking "That's probably not for me." I can imagine e.g. some psychologists seeing cogsci.stackexchange.com and thinking exactly that. That said, Muz noted there already is a proposed Mind community, so it's fairly moot.

Should we change the site name to Mind?


Subset pandas dataframe by overlap with another

Question: For the following two dataframes:
df1 = pd.DataFrame({'name': pd.Series(["A", "B", "C"]), 'value': pd.Series([1., 2., 3.])})

     name  value
0    A    1.0
1    B    2.0
2    C    3.0

df2 = pd.DataFrame({'name': pd.Series(["A", "C", "D"]), 'value': pd.Series([1., 3., 5.])})

     name  value
0    A    1.0
1    C    3.0
2    D    5.0

I would like to keep only the rows in df2 where the value in the name column overlaps with a value in the name column of df1, i.e. produce the following dataframe:
     name  value
0    A    1.0
1    C    3.0

I have tried a number of approaches but I am new to python and pandas and don't appreciate the syntax coming from R. Why does this line of code not work, and what would?
df2[df2["name"] in df1["name"]]

Answer: You can use isin:
print (df2[df2["name"].isin(df1["name"])])
  name  value
0    A    1.0
1    C    3.0

Another faster solution with numpy.intersect1d:
val = np.intersect1d(df2["name"], df1["name"])
print (val)
['A' 'C']

print (df2[df2.name.isin(val)])
  name  value
0    A    1.0
1    C    3.0

Comment: I believe this doesn't work if the index is different.
Comment: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.join.html
Answer: Slightly different method that might be useful on your actual data, you could use an "inner join" (the intersection) a la SQL. More useful if your columns aren't duplicated in both data frames (e.g. merging two different data sets with some common key)
df1 = pd.DataFrame({'name': pd.Series(["A", "B", "C"]), 'value': pd.Series([1., 2., 3.])})
df2 = pd.DataFrame({'name': pd.Series(["A", "C", "D"]), 'value': pd.Series([1., 3., 5.])})

# supposedly for the join you should be able to tell join on='<column_name>', 'name' here,
# but wasn't working for me.
df1.set_index('name', inplace=True)
df2.set_index('name', inplace=True)

df1.join(df2, how='inner', rsuffix='_other')

#       value  value_other
# name
# A       1.0          1.0
# C       3.0          3.0

Changing how to outer would give you the intersection of the two, left for just df1 rows, right for df2.


why cannot I assign a newly allocated byte array to a variable with []byte as type?

Question: I am trying to declare a variable of type array with unspecified size []byte and then filling it with an allocated array of size 256 as follows:
var buf []byte
buf = new([256]byte)

Unfortunately, it does not work. The compile error returned is the following:
cannot use *new([256]byte) (type [256]byte) as type []byte in assignment

Any idea?
Answer: You want to assign an array to a slice, which won't work (see "Go Slices: usage and internals")
To make a slice instead, use:
var buf []byte
buf = make([]byte, 256)

The difference:

An array variable denotes the entire array; it is not a pointer to the first array element (as would be the case in C).
  This means that when you assign or pass around an array value you will make a copy of its contents. (To avoid the copy you could pass a pointer to the array, but then that's a pointer to an array, not an array.)
  One way to think about arrays is as a sort of struct but with indexed rather than named fields: a fixed-size composite value.

Versus:

A slice is a descriptor of an array segment.
  It consists of a pointer to the array, the length of the segment, and its capacity (the maximum length of the segment).

If you want to create an array (an assign it to an array), that would have been:
var buf [256]byte
buf = [256]byte{}

Answer: You can also use the newly allocated array as a slice by slicing it like this:
var slice []byte = buf[:]

This creates slice as a slice that is backed by the array buf.


Restart a java application for linux and windows

Question: I have a java application when there is a update it should restart . how can i automatically  restart the java application again .
I tried using a Process builder to restart.
ProcessBuilder builder = new ProcessBuilder(command);
builder.directory(new File(workingDir));
builder.start();
System.exit(0);

However when i check the applications running the earlier process was still running.
Comment: Does the app. have a GUI?
Comment: For deploying Java desktop apps., the best option is usually to install the app. using [Java Web Start](http://stackoverflow.com/tags/java-web-start/info).  JWS works on Windows, OS X & *nix & provides both auto & programmatically controlled update.
Answer: Put your process restarting logic in a separate thread and register it as shutdown hook.
Perhaps you can give make this shutdown hook thread daemon and put some sleep in the main thread. If process does not restart in the given time them simply exit the application or else application will restart and let this (main) process close.
Also for starting new process you may want to consider
Runtime.getRuntime().exec(yourProcess);

For windows you can do
Runtime.getRuntime().exec("cmd /c start yourProcess");

and for linux process starts detached by default so just executing the command with  Runtime.getRuntime().exec(yourProcess); should do the trick.


How can I make my Ubuntu 12.04 look like a Mac?

Question: I want my Ubuntu to look like Mac OS X. Just icon and theme if possible! Is it possible? Is there any way to install slingshot launcher?
Answer: There is a OS X Lion theme for Precise and other versions available in the Noobslab themes PPA.
The full blog post on Noobslab about changing the cursors, installing Cairo Dock for a "OS X"-ish launcher and other ways to max out the OS X feeling like a Apple splash screen can be found here.

In short (for 12.04): you have to add the repository to you sources and install the packages then. To do that open a terminal and enter these commands:
sudo add-apt-repository ppa:noobslab/themes
sudo apt-get update
sudo apt-get install mac-os-lion-theme mac-os-lion-cursors mac-os-lion-icons

To change your theme, icons and cursors you must use a tool. You can install one like that (again: from a terminal):
## for Gnome Tweak Tool
sudo apt-get install gnome-tweak-tool

## for Ubuntu Tweak
sudo add-apt-repository ppa:tualatrix/ppa
sudo apt-get update
sudo apt-get install ubuntu-tweak

As for Slingshot launcher: there is no stable release yet! You could add the elementary-dev/daily PPA and install a unstable version but that bears a high risk for your system!
Maybe (and just maybe since I don't know if this will work) you could download the latest stable version of slingshot here and install it manually: How to install tar.gz
Comment: I think they changed the package names recently. I've corrected that now. If installing `mac-os-lion-theme`, `mac-os-lion-icons` and `mac-os-lion-cursors` fails, please let me know!
Answer: Here is another way...
sudo add-apt-repository ppa:webupd8team/themes
sudo apt-get update
sudo apt-get install adwaita-cupertino-gtk-theme

This will install the theme. Here is a description for the theme from the WebUpd8 website:

Mac-like GTK3 theme in two variants, each optimized for either GNOME
  Shell or unity Package name: "adwaita-cupertino-gtk-theme"
Ubuntu versions: 12.04, 11.10"


Jquery: Sort by inner element's attribute

Question: I have following code:

Price: 50

Price: 30

Price: 40

I need to sort these 3 divs based on min-price attribute. Is it possible in Jquery? I found sort() function, but I was not able to use it correctly. Thank you.
Comment: Yes it is possible
Answer: You can use .sort() function:
$('div[id]').sort(function (a, b) {
  var minprice1 = parseInt( $(a).find('span').attr('min-price'));
  var minprice2 = parseInt( $(b).find('span').attr('min-price'));
  return (minprice1 < minprice2 ) ? -1 : (minprice1 > minprice2 ) ? 1 : 0;
});

Comment: Since `minprice1` and `minprice2` are `int`s you can use `return minprice1 - minprice2;`.
Answer:

function sortElements(element, prop, sortDescending) {
  var arrElements = [], origElements = [];

  $.each(element, function(){
    arrElements.push($(this).attr(prop));
    origElements.push($(this).attr(prop));
  });

  arrElements.sort();

  if(sortDescending)
    arrElements.reverse();

  for(var i = 0, l = arrElements.length; i < l; i++)
    $("#sortDiv").append($("#"+arrElements[i]));

  $("#divOrig").html($("#sortDiv").html());
  $("#sortDiv").remove();
}

sortElements($("#divOrig span"), "min-price", true);

Price: 50

Price: 30

Price: 40

Answer: Try this :

$(document).ready(function() {

     $("div[id]").each(function(number,ele) {

         $("div[id]").not($(ele)).each(function(index,el){

             a = $(ele).find("span").attr("min-price");
             b = $(el).find("span").attr("min-price");

             if( parseFloat(a) > parseFloat(b) )
                 $(ele).insertAfter($(el));

         })

     })

 })

Price: 50

Price: 30

Price: 40


java.sql - ResultSet r.next() doesn't work

Question: I don't understand why ResultSet isn't working as if there are no results
<code>public static int checkProductID(Connection conn) {

    boolean productIDisvalid = false;
    int id = 0;
    while (!productIDisvalid) {
        System.out.println("Enter a product ID: ");
        try {
            id = Integer.parseInt(readLine());
            if (id < 10000000 && id > 0) {
                System.out.println(id);
                // PreparedStatement pstmt = conn.prepareStatement ("INSERT INTO INVENTORY VALUES (?,?,?,?) ");
                // pstmt.setInt(1,4000); pstmt.setString(2,"hello"); pstmt.setInt(3,4000); pstmt.setInt(4,400);
                PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM INVENTORY WHERE PRODUCTID = ?");
                pstmt.setInt(1, id);
                ResultSet r = pstmt.executeQuery();
                while (r.next()) {
                    System.out.println(r.getInt("PRODUCTID"));
                    if (r.getInt("PRODUCTID") == id) return id;
                }
            }

        } catch (NumberFormatException | SQLException | NullPointerException e) {
            e.printStackTrace();
            continue;
        }
    }

    return id;
}
</code>
I quoted out an insert values to prove it works and that it is correctly connected to the database.

The insert values works. But whenever I attempt to perform a search query on the database, it doesn't work, r.next() is never true and the print statement inside that while loop never executes, even if I change the query to "SELECT * FROM INVENTORY WHERE PRODUCTID = 1000"
Comment: I don't know if there's enough information here for us to help. What happens if you add a semicolon `;` to the end of the query? What happens if you wrap the `?` in apostrophes `'?';`?
Comment: @JacobG. I just changed it to "SELECT * FROM INVENTORY" and it prints 4000 once but not 1000, 2000, 3000 as it should when it cycles through (it should actually just be printing 1000 as the search id used was 1000, and then returning, very strange. Adding ; causes a syntax error btw, this is the correct format
Comment: "Adding ; causes a syntax error" - I find that hard to believe. Are you adding it in the correct location? And if you're seeing values that you don't expect, then your table probably contains other data.
Comment: @JacobG. It's true that adding ";" causes a syntax error, it's something I tried logically. I've just worked it out but it's beyond me, it works if i use the id 4000 and returns correctly. It's as if it thinks the table begins at id 4000, it's only recognising entries entered by the program itself and not the schema.sql batch file that entered some preliminary entries, even though they are indeed in the table.
Comment: Ok, ridiculous, it works now, just terminated the ssh connection and restarted it. Now recognises those entries.
Answer: Your problem was happening because you had not explicitly committed your insert from sqlplus. When you exit sqlplus there is an implicit commit that happens which is why the problem went away.


Sum of Telescopic Series

Question: Question :

$$\sum_{r=1}^n\frac{(r^2-r-1)}{(r+1)!}=?$$

I tried but I got $(-1)!$ in the end. This is what I tried:
$$
\require{cancel}
\frac{r^2-1}{(r+1)!}-\frac{r}{(r+1)!}\\
\frac{\cancel{(r+1)}\cancel{(r-1)}}{\cancel{(r+1)}r\cancel{(r-1)}(r-2)!}-\frac{\cancel{r}}{(r+1)\cancel{r}(r-1)!}\\
T_r=\frac{1}{r(r-2)!}-\frac{1}{(r+1)(r-1)!}\\
\sum_{r=1}^{n} T_r = \frac{1}{1(1-2)!}-\frac{1}{(n+1)(n-1)!}\\
= \frac{1}{(-1)!}-\frac{1}{(n+1)(n-1)!}\\
$$
Please point out my mistake.
Comment: Please show what you have done.
Comment: how did you get (-1)!
Comment: Find $a,b,c$ such that $r^2-r-1=ar(r+1)+b(r+1)+c$, identically.
Comment: "I am taught in school that after splitting the fractions. Put the minima in least denominator and maxima in greater denominator." That is not a good way to teach.
Comment: Since $\frac1{(-1)!}=\frac0{0!}=0$, your answer is correct, in a sense.
Answer: $$\begin{eqnarray*}\frac{r^2-r-1}{(r+1)!}&=&\frac{r^2-1}{(r+1)!}-\frac{r}{(r+1)!}\\&=&\frac{(r-1)(r+1)}{(r+1)!}-\frac{r}{(r+1)!}\\&=&\frac{r-1}{r!}-\frac{r}{(r+1)!}\end{eqnarray*}$$
Therefore:
$$\begin{eqnarray*}\sum_{r=1}^n\frac{(r^2-r-1)}{(r+1)!}&=&\sum_{r=1}^n\left[\frac{r-1}{r!}-\frac{r}{(r+1)!}\right]\\&=&\frac{0}{1!}-\frac{1}{2!}+\frac{1}{2!}-\frac{2}{3!}+\frac{2}{3!}-\frac{3}{4!}+...+\frac{n-1}{n!}-\frac{n}{(n+1)!}\\&=&\color{blue}{-\frac{n}{(n+1)!}}\end{eqnarray*}$$
Answer: For any $n\geq 2$ we have
$$\begin{eqnarray*}\sum_{r=1}^{n}\frac{r^2-r-1}{(r+1)!}&=&\sum_{r=1}^{n}\frac{(r+1)r}{(r+1)!}-2\sum_{r=1}^{n}\frac{(r+1)}{(r+1)!}+\sum_{r=1}^{n}\frac{1}{(r+1)!}\\&=&\sum_{r=1}^{n}\frac{1}{(r-1)!}-2\sum_{r=1}^{n}\frac{1}{r!}+\sum_{r=1}^{n}\frac{1}{(r+1)!}\\
&=&\sum_{r=0}^{n-1}\frac{1}{r!}-2\sum_{r=1}^{n}\frac{1}{r!}+\sum_{r=2}^{n+1}\frac{1}{r!}\\&=&\frac{1}{0!}-\frac{1}{1!}-\frac{1}{n!}+\frac{1}{(n+1)!}=\color{red}{-\frac{n}{(n+1)!}}.\end{eqnarray*}$$

Sum of Telescopic Series


Issue with choice of AP when connecting to university wifi on Lenovo X230/Ubuntu 16.04.2

Question: I have a Lenovo X230 running Ubuntu 16.04.2 and it has some minor issues when using the eduroam wifi at my University. The setup of the wifi is done according to the official guidelines, but I often have a weak Wifi signal strength, which leads to a slow connection.
I've used a small python script which uses iwlist to scan for the available APs nearby. The output is:
eduroam     00:81:C4:B7:41:C0    57 %     -70 dBm   2.412 GHz (Channel 1)
eduroam     FC:5B:39:AB:A3:30    50 %     -75 dBm   2.437 GHz (Channel 6)
eduroam     FC:5B:39:B5:81:50    56 %     -71 dBm   2.437 GHz (Channel 6)
eduroam     00:81:C4:E4:24:50    63 %     -66 dBm   2.462 GHz (Channel 11)
*eduroam*     00:81:C4:E4:24:DF    34 %     -86 dBm   5.18 GHz (Channel 36)
eduroam     00:81:C4:E4:24:5F    50 %     -75 dBm   5.18 GHz (Channel 36)
eduroam     00:81:C4:F9:7A:EF    37 %     -84 dBm   5.18 GHz (Channel 36)
eduroam     FC:5B:39:AB:A3:3F    37 %     -84 dBm   5.2 GHz (Channel 40)
eduroam     FC:5B:39:77:4F:FF    31 %     -88 dBm   5.2 GHz (Channel 40)
eduroam     00:81:C4:B7:41:CF    57 %     -70 dBm   5.2 GHz (Channel 40)
eduroam     FC:5B:39:B8:35:9F    37 %     -84 dBm   5.24 GHz (Channel 48)
eduroam     00:81:C4:F1:6A:9F    31 %     -88 dBm   5.24 GHz (Channel 48)

Where * eduroam * is the one I'm currently connected to. This of course changes, depending on where I am, but I quite often notice that I am connected to a weak AP which slows down my connection when APs which are stronger(closer?) are available.
So my questions are:

what factors governs the choice of AP, if not signal strength?
where can this be overridden in Ubuntu?
Is it possible to manually set up different connections for my usual spots with a "non-roaming" AP?

I've already seen this Choice of Wifi network , but this does not answer my questions or let me know how to set up different connections on the same ESSID.
You can see a dump of my wifi info here: https://paste.ubuntu.com/24046624/
Answer: You can lock your computer to a specific access point by placing the mac address of a specific access point into the BSSID field in your connection profile.


Custom reflection functionality in .Net

Question: Is it possible to override reflection functionality ?
Answer: In what way? What you can do is override the ComponentModel functionality, allowing your object to expose different properties at runtime than it does at compile - but this doesn't change reflection. This approach is used to support data-binding of (for example) DataView. You would look at ICustomTypeDescriptor.
In .NET 4.0 dynamic objects arrive; there is no special C# support for authoring a dynamic object, but if you don't mind doing the legwork you can write an object that behaves for non-static callers.
But to echo "silky" - what do you want to achieve?
Comment: Changing properties at runtime would be enough, I consider this an answer ... thank you.

Note: sometimes I ask the question in generic/fuzzy way cause I don.t need a specific answer... sharing thoughts.

Custom reflection functionality in .Net


Is there a way to suppress [Vue-warn] in prop validation?

Question: I need to display custom validator message on prop. Along with custom error I also see default Vue warning [Vue-warn]. Is there away to suppress [Vue-warn]:
My prop look like this:
props: {
  mode: String,
  default: h,
  validator: val => {
    if(['s','y','z'].includes(v)) {
      return true
    }
    else {
      console.error("Possible values for mode are: 's', 'y' or 'z'");
      return false
    }
  }
}

Answer: The warning only appears because the validator returns false.
To avoid the warning message in the console, return true instead:
props: {
  mode: String,
  default: h,
  validator: val => {

    if(!['s','y','z'].includes(v)) {
      console.error("Possible values for mode are: 's', 'y' or 'z'");
    }
    return true
  }
}


How long can I be AFK on Fortnite before getting banned?

Question: I want to know if like, maybe I have to use the toilet in the middle of Fortnite Battle Royale, and I go AFK for a couple minutes, how long can I stay AFK before getting perm banned?
Answer: Fortnite relies on players reporting you for AFKing for bans. In addition, the only real mentions I can find of people being permabanned for going AFK has 3 major similarities:

They're repeat and serial offenders who get multiple reports for going AFK every match;
They weren't just AFKing for several minutes, but rather actively using macros and bots to stay online beyond the normal 2-3 minutes it takes for the inactivity to kick them out of the game;
They were leeching rewards and resources in Campaign mode games and not actively participating in the game.

I do not have official confirmation, but I'm fairly sure that if you aren't actively trying to avoid the AFK kick timer, going to the toilet for a minute or so in the middle of a match every once in a while won't be enough to be flagged as a serial offender. Especially in a BR match where players are less likely to flag you for AFK and more likely to just kill you.
However, if I may give you some advice, just go to the toilet BEFORE you start the match. Fortnite Battle Royale matches at most last 20 minutes. Unless you have a medical condition that has frequent urination or defecation as a symptom, it's unlikely that you have to wait so long between queueing up and the end of the game that you end up needing to go to the toilet during the match.
And if there is anything else you need to do while playing the game: if it's urgent, just leave the match (if you're in a team, tell your teammates that something IRL has come up and you need to leave). If it's not urgent, wait for the end of the match and don't queue again until you are done with the thing you need to do.
Comment: @ACardboardBox If you think my answer helped you, be sure to upvote and accept it. Upvoting and accepting an answer adds extra visibility to the answer and also rewards me with reputation.
Comment: thanks. Lol I didn't want to get banned just going to the bathroom. Thank you.
Answer: In Stw, about twenty minutes.
Battle Royale, like 2 minutes. Enough to get your drink ;)


Listen button outside of listview and modify the first item

Question: I am learning android and this is my assignment of making music player interface. So far all is well but I stuck on the last part.
I want to Play (just changing the button icon) the first item in the ListView when hit the Play All button which is outside of theListView`.

You can find entire project on Bitbucket. Although adding some required code here.
activity_album.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:orientation="vertical"
    tools:context=".DreamVoyage">

    <android.support.constraint.ConstraintLayout
        android:id="@+id/album_cover_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintHeight_percent="0.3">

        <ImageView
            android:id="@+id/album_cover"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:scaleType="centerCrop"
            android:src="@drawable/album_four" />

        <View
            android:id="@+id/view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#80000000" />

        <TextView
            android:id="@+id/album_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="8dp"
            android:text="Album Title"
            android:textColor="#FFFFFF"
            android:textStyle="bold"
            android:textSize="24sp"
            app:layout_constraintBottom_toTopOf="@+id/album_band"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="@+id/album_cover" />

        <TextView
            android:id="@+id/album_band"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="24dp"
            android:text="Album Band"
            android:textColor="#FFFFFF"
            android:textSize="14sp"
            app:layout_constraintBottom_toTopOf="@+id/album_play_all_button"
            app:layout_constraintEnd_toEndOf="@+id/album_title"
            app:layout_constraintStart_toStartOf="@+id/album_title" />

        <Button
            android:id="@+id/album_play_all_button"
            style="@style/AppTheme.RoundedCornerMaterialButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="24dp"
            android:text="Play ALl"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="@+id/view"
            app:layout_constraintStart_toStartOf="parent" />

    </android.support.constraint.ConstraintLayout>

    <ScrollView
        android:id="@+id/playlist"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:fillViewport="true"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent="0.7"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/album_cover_layout">

        <ListView
            android:id="@+id/playlist_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

        </ListView>

    </ScrollView>

</android.support.constraint.ConstraintLayout>

SongAdapter.java
public class SongAdapter extends ArrayAdapter<Song> {

    int     playingIndex = -1;
    boolean currentTrack = false;

    public SongAdapter(@NonNull Context context, int resource, @NonNull List<Song> objects) {
        super(context, resource, objects);
    }

    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        View             playlistItemView = convertView;
        final ViewHolder holder;

        if (playlistItemView == null) {
            playlistItemView = LayoutInflater.from(getContext()).inflate(R.layout.playlist_item, parent, false);

            holder = new ViewHolder();

            holder.albumCoverThumbnail = playlistItemView.findViewById(R.id.playlist_album_thumbnail);
            holder.songTitle = playlistItemView.findViewById(R.id.playlist_song_title);
            holder.songAlbumTitle = playlistItemView.findViewById(R.id.playlist_song_album_title);
            holder.songArtist = playlistItemView.findViewById(R.id.playlist_song_artist);
            holder.songPlayButton = playlistItemView.findViewById(R.id.playlist_play_button);

            playlistItemView.setTag(holder);
        } else {
            holder = (ViewHolder) playlistItemView.getTag();
        }

        final Song currentSong = getItem(position);

        // set data to the list item
        assert currentSong != null;
        holder.albumCoverThumbnail.setImageResource(currentSong.getSongAlbumCoverId());
        holder.songTitle.setText(currentSong.getSongTitle());
        holder.songAlbumTitle.setText(currentSong.getSongAlbumTitle());
        holder.songArtist.setText(currentSong.getSongSingers());

        // check the play status of the song item
        if (playingIndex == position) {
            holder.songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
        } else {
            holder.songPlayButton.setImageResource(R.drawable.ic_play_arrow_black_24dp);
        }

        // set song button action
        holder.songPlayButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                holder.songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);

                // pause current song on other click
                if (position == playingIndex) {
                    playingIndex = -1;
                } else {
                    playingIndex = position;
                    notifyDataSetChanged();
                }

                // pause play current track
                if (currentTrack) {
                    holder.songPlayButton.setImageResource(R.drawable.ic_play_arrow_black_24dp);
                    currentTrack = !currentTrack;
                } else {
                    holder.songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
                }
                currentTrack = !currentTrack;
            }
        });

        return playlistItemView;
    }

    static class ViewHolder {
        ImageView   albumCoverThumbnail;
        TextView    songTitle;
        TextView    songAlbumTitle;
        TextView    songArtist;
        ImageButton songPlayButton;
    }
}

HiddenTruth.java
public class HiddenTruth extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_album);

        // get view ids
        ImageView albumCoverImage = findViewById(R.id.album_cover);

        // get intent extras
        Bundle bundle = getIntent().getExtras();
        // check if bundle in not null and containing value
        if (bundle != null) {

            String albumTitle = bundle.getString("album_two_title");
            String albumBand = bundle.getString("album_two_band");
            int albumCover = bundle.getInt("album_two_cover");

            albumCoverImage.setImageResource(albumCover);

            TextView albumTitleText = findViewById(R.id.album_title);
            TextView albumBandText = findViewById(R.id.album_band);

            albumTitleText.setText(albumTitle);
            albumBandText.setText(albumBand);

            ArrayList<Song> songs = new ArrayList<Song>();

            // get the thumbnail resource id
            int albumThumb = R.drawable.album_two_thumbnail;

            songs.add(new Song(albumTitle, "Hidden valley in the north", "Nicolo Viarina", albumThumb));
            songs.add(new Song(albumTitle, "The sea and the sky", "Mali nigara", albumThumb));
            songs.add(new Song(albumTitle, "Hidden valley in the north", "Nicolo Viarina", albumThumb));
            songs.add(new Song(albumTitle, "The sea and the sky", "Mali nigara", albumThumb));
            songs.add(new Song(albumTitle, "Hidden valley in the north", "Nicolo Viarina", albumThumb));
            songs.add(new Song(albumTitle, "The sea and the sky", "Mali nigara", albumThumb));
            songs.add(new Song(albumTitle, "Hidden valley in the north", "Nicolo Viarina", albumThumb));
            songs.add(new Song(albumTitle, "The sea and the sky", "Mali nigara", albumThumb));
            songs.add(new Song(albumTitle, "Hidden valley in the north", "Nicolo Viarina", albumThumb));
            songs.add(new Song(albumTitle, "The sea and the sky", "Mali nigara", albumThumb));
            songs.add(new Song(albumTitle, "Hidden valley in the north", "Nicolo Viarina", albumThumb));
            songs.add(new Song(albumTitle, "The sea and the sky", "Mali nigara", albumThumb));
            songs.add(new Song(albumTitle, "Hidden valley in the north", "Nicolo Viarina", albumThumb));
            songs.add(new Song(albumTitle, "The sea and the sky", "Mali nigara", albumThumb));
            songs.add(new Song(albumTitle, "Hidden valley in the north", "Nicolo Viarina", albumThumb));
            songs.add(new Song(albumTitle, "The sea and the sky", "Mali nigara", albumThumb));
            songs.add(new Song(albumTitle, "Hidden valley in the north", "Nicolo Viarina", albumThumb));
            songs.add(new Song(albumTitle, "The sea and the sky", "Mali nigara", albumThumb));

            SongAdapter songAdapter = new SongAdapter(this, 0, songs);

            ListView listView = findViewById(R.id.playlist_view);
            listView.setAdapter(songAdapter);

        } // @TODO move this brace after albumBand.setText(bundle.getString("album_two_band"));
    }
}

Comment: what exactly you want ? either to click play all button which is outside listview or click individual item which are inside listview ?
Comment: @Umair I want when `Play All` clicked the first item should start. If you see my code in `SongAdapter.java`, I have already finished coding for individual item. Just looking for `Play All` button. Thanks
Comment: just pass a boolean value... `isPlayAll` to the constructor of the adapter.. and on Click of each item check if `position == 0 && isPlayAll` then play ..
Comment: @CodeLover you can use interfaces for that or use the technique which above comment told you.
Comment: @SantanuSur where I should pass the Boolean value? I am having trouble to get the Play All` button in the `SongAdapter`. Can you please explain me in more detail. Where and how I should get the button.
Comment: set the `onClickListener` for `playAll` button on the activity .... and onClick of `playAll` set the adapter of the songs again ..using the boolean value.. like :-
`new SongAdapter(context,resource, objects, **isPlayAll**);`
Comment: @SantanuSur I see, let me try.
Comment: I appreciate your help but unable to make it. I am having trouble adding extra optional parameter in `SongAdapter` constructor
Comment: @SantanuSur done .. thanks..
Answer: Here is the answer.
I have added another constructor to SongAdapter
public SongAdapter(@NonNull Context context, int resource, @NonNull List<Song> objects, boolean isAllPlay) {
    super(context, resource, objects);
    isAllPlayClicked = isAllPlay;
}

Than added below
// play first track on Play All button clicked
if (isAllPlayClicked) {
    playingIndex = 0;
    holder.songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
    isAllPlayClicked = false;
    currentTrack = !currentTrack;
}

in activity file
// get the Play All button
Button playAll = findViewById(R.id.album_play_all_button);

// Play All button click event
playAll.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        SongAdapter newAdapter = new SongAdapter(HiddenTruth.this, 0, songs, true);
        listView.setAdapter(newAdapter);
    }
});

I hope this will help someone.


Pasting from a variable defined range

Question: New to vba and I am having difficulties with pasting. Here is my code:
Dim xtext As String
Dim ytext As String
x = ActiveSheet.Range("A8")
y = ActiveSheet.Range("A9")
Range("A6").Select
Selection.Copy
Range("xtext:ytext").Select
Selection.Paste
Endsub
Cell A8 (which is variable x) value is B2, and Cell A9 (which is variable y) is B10. I thought it would paste from B2:B10 but instead is pasting into columns x:y. So I kind of want it to work like an indirect formula? I am not sure if this is even close to what I want?
Thanks!
Answer: Rename your variables - "x" & "y" are bad as they are not indicative of what they hold. This is particularly true in Excel, where a single letter also refers to a column - which is what has happened here; you have posted to the range "X:Y", which is just the selection of all of column X, and all of column Y.
Your whole code together becomes [note that I changed your definition of x and y to be ranges, not text strings, and as such had to make them equal to your A8 & A9 by "set = to"] [assuming in your spreadsheet that cell A8 says "B2", and A9 says "B10"]:
<code>Sub test()

Dim x As Range
Dim y As Range

Set x = ActiveSheet.Range("A8")
Set y = ActiveSheet.Range("A9")

Range("A6").Select
Selection.Copy

Range(x.Text, y.Text).Select
ActiveSheet.Paste

End Sub
</code>
Edited to now refer indirectly to what is entered into cells A8 & A9
Comment: Sorry for the confusion, I think I may have mislead you. The Range("A10") and Range("A11") were for verification purposes only. If I change my variables to xtext and ytext, what I want is to paste in their range, so now I have more simply:                                                                                Dim xtext As String
Dim ytext As String

xtext = ActiveSheet.Range("A8")
ytext = ActiveSheet.Range("A9")                                                       Range("A6").Select Selection.Copy

Range("xtext:ytext").Select
ActiveSheet.Paste
Comment: Edit your question to provide your data and what you want your results to be.
Comment: Okay, I edited it. I just want to paste into the range that the variables are if that makes sense.
Comment: Check my edits. In the future, that sort of clarity is required. The more you say about what your data is and what you want to happen, the easier it is to resolve.
Comment: Thank you very much! It does exactly what I need it to do.
Comment: If the answer does what you need, please click 'accept' next to it. Thanks

Pasting from a variable defined range


CSS :after and :before to create spacing for  not working properly

Question: So I'm trying to customize some HTML tags by adding additional attributes to my CSS that will create spacing :before and :after the next  content.
I'm not able to succeed with
, I want a table to produce space before and after it. Please see my picture below for the outcome of based of my CSS below.

table:before {
  content: '\a';
  white-space: pre;
}

table,
th,
td:after {
  padding-top: 1em;
}

h1,
h2,
h3,
h4,
h5,
h6:after {
  content: '\a';
  white-space: pre;
}

p:after {
  content: '\a';
  white-space: pre;
}

p:before {
  content: '\a';
  white-space: pre;
}

How can I fix or tweak my CSS for tables to actually produce space (for the top and bottom of the table)

as you see in this image, my CSS is breaking the table header in half by adding a line break after, as well there is no space before.
How can I fix this with my CSS?
Comment: what about setting a margin:2rem 0; on the table tag?
Comment: margins? O.o ...
Comment: @AristeidisKaravas, that seemed to do the trick :).  devsandbox, is there any problem with using margins here?
Answer: Since the comment worked for you, here is the answer!
Before and after is not the recommended way to create space between elements. Only in few cases and very rarely you re going to need before and after for spacing.
In general the two most common ways to give some distance between elements.
Margin
For your case, margin-top would push the element down by 2rems. Margin-bottom would create space between the element and the next. In this space however, you can not do anything (eg. Style it) since it is a fix distance between elements
Padding
Padding pushes the content down BUT the distance between the elements is a part of the element itself. So if you add a background-color: blue; you will have the space with a blue background as well.
Some visual representation:

.row p {
  margin:0;
}
.div-2 {
  background:orange;
  margin:2rem 0;
}

.div-4 {
  background:blue;
  padding:2rem 0;
}

Irrelevant Item

With Margin

Irrelevant Item

With Padding

Irrelevant Item

Hope it helped
Best regards


Does an 8" round to 10x3.25" elbow exist?

Question: I have open space above cabinets and wife does not want a chimney on our range hood.
SO I am looking for an elbow that will take the 8" round vertical exhaust and go 90 degrees into a 10x3.25"  (we have ~4" of molding above cabinets)

I found this online, but it's not quite the right size.  Anyone know if there is a proper term for this I can search, or if I could get one to meet my specs?
Answer: I would take a piece of 10x3.25 duct, cap off one end and cut an 8" hole in one side and add a flange to connect the 8" duct to.  These should be common parts that are easier to source than some exactly sized elbow that still might need modification.
Comment: Note that 10x3.25 has a cross section of  about 32.  8" round is more like 50 - so you will have a lot more restriction.
Comment: thank you!  I guess without adding any additional height any elbow I find would essentially have the same airflow restriction/back-pressure from this sudden change .
Comment: You may be able to put some curved baffle inside this home-made option to help direct the airflow.  You can always put some more time into it - I just listed the basic idea.
Comment: Thanks @MartinBonner!  The hood itself uses a 10x3.25 if venting horizontally, the 8" vertical is I think larger to allow the optional 2nd blower that we're not purchasing. So hopefully the flow will be sufficient
Answer: Go to any HVAC shop or duct fabricator, explain what you want and they may be able to make it to your specs.
Comment: Ah great point.  Some family friends have a local HVAC business here, but I never thought to ask them.
Comment: I was just at Home Depot yesterday and saw a 6" straight X 3 1/4" adapter near the appliance parts, if that will help.


Portable home bar plans?

Question: I'm moving into about a 1500 sq. ft. house soon and I would like to build my own portable bar that I can store beverages in. It should be long enough to put a couple stools in front of where people can sit but not so heavy that it becomes a pain to move around. Can anyone recommend a place or website where I can find plans or blueprints for a smaller, DIY, portable home bar? Any suggestions for this setup would be appreciated.
Answer: A bar is very much like a kitchen island with a seating overhang. There are several sites that either have plans, discussions or links to islands that might suit your purpose.  See, for example:
http://www.diynetwork.com/topics/kitchen-islands/index.html
or
http://www.woodworkersworkshop.com/resources/index.php?cat=673
I made a fixed kitchen island from an unfinished base, a granite top I custom ordered, and brackets I created to match the style of the unfinished cabinet. A shallower version could serve as a classic bar. This is NOT portable (almost no stone top should be).
You could make it portable by substituting a wooden top covered in metal, a thin butcherblock top, or any other wood or even tile.  Portability could be enhanced by attaching wheels to the base, either caster type or larger wheels with axles, but if you are storing bottles and glasses, you may not want that much movement.

Portable home bar plans?