Create Python code to supply json data for jQuery datatables

Question: I am new to Python, but I want to get fast in understanding it.
Currently I am working on Flask+SQLAlchemy+PostgreSQL+jQuery in Openshift platform.
And I finding it hard to try using this jQuery plugins datatables.net here :
http://datatables.net/release-datatables/examples/server_side/server_side.html
The server side example is in PHP, I can understand it well, but I am having problem in translating it to Python. My understanding on Python Dict (as I understand that is is comparable to JSON) data structure is not good at the moment.
I am working now to translating it, but if you can show me the correct python code to do that, I will be delighted
EDIT 1
After reading and playing around with Python docs on dict, I can build the exact JSON data by using regular python dict + json.dumps() :
@app.route ('/dataset/users')
    def dataset_users():

    data = {}
    data['aaData']=[]
    data['iTotalRecords']=3
    data['sEcho']=1
    data['iTotalDisplayRecords']=1

    data['aaData'].append(['Gecko', 'FFox', 'Win', '1.1','A'])
    data['aaData'].append(['Webkit', 'Safari', 'OSX', '3','B'])
    data['aaData'].append(['IE', 'IE', 'Win', '2','C'])
    return json.dumps(data)

Working now on using SQLAlchemy + Flask to jsonify the resultset
EDIT 2
These are my current flask+sqlalchemy code that conform to jquery datatables plugin :
@app.route ('/dataset/users')
def dataset_users():
    data = {}
    data['iTotalRecords'] = 2
    data['sEcho'] = 1
    data['iTotalDisplayRecords'] =  2

    aaData = []
    users=models.Users.query.with_entities(
        models.Users.id, models.Users.username,
        models.Users.email).order_by(models.Users.username).all()
    for user in users:
        aaData.append([user.id, user.username, user.email, 'Modify'])

    data['aaData']=aaData
    return json.dumps(data)

I believe that we can streamline the code so that it will not use for loop. Any idea?
Comment: I don't see anything in this question that involves twitter-bootstrap.
Comment: Pardon me as I am a complete new in Bootstrap + Python, but isn't that datatables.net is a bootstrap .. wait a minute. it's a jquery plugin. Thanks for noticing. I will rephrase my question
Answer: You can convert a Python dict to JSON using the json module:
import json
print json.dumps({"key": "value", "numbers": [1, 2, 3],})
# {"numbers": [1, 2, 3], "key": "value"}

Comment: Thanks! I already know that function, but .. how to construct that specified dict, is beyond my current understanding. This is the url that the given example use to send the correct JSON data : http://datatables.net/release-datatables/examples/server_side/scripts/server_processing.php I am trying to mimic that into python dict.. or, wait a minute, maybe I can save that into a file, and find python function that will directly convert it into dict... And after that I can construct python code on how to create that python dict using my data
Comment: OKay, got it. http://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file-in-python I already had that json as python dict. working now on how to construct that dict in my program. Thanks @Thomas for your concise answer. It lead me to clear path ;)


c# build a list of tasks before executing

Question: i'm trying to build a list of tasks before executing them.  here's some example code:
    public string Returnastring(string b)
    {
        return b;
    }

    public string Returnanotherstring(string a)
    {
        return a;
    }

    private void btnT_Click(object sender, EventArgs e)
    {
        bool cont = true;

        var Returnastringtask = Task.Factory.StartNew(() => Returnastring("hi"));
        var Returnanotherstringtask = Task.Factory.StartNew(() => Returnanotherstring("bye"));

        if (cont)
        {
            Task.WaitAll(new Task[] { Returnastringtask });
        }
        else
        {
            Task.WaitAll(new Task[] { Returnanotherstringtask });
        }

i know this code doesn't behave how i expect it as both tasks run.  i want to basically create the tasks initially and then execute one or the other based on the bool.  i don't want to create the tasks inside the true or false conditions as i want to avoid code copying.  by  this i mean if cont is true i might want to run tasks 1,2,3,4 but if cont is false i might want to run tasks 2,3,7,8.
Comment: Your code is, as it stands, a bit bizarre. You're creating and starting both tasks, but then only waiting on one or the other based on the if statement. There seems to be a lot of work here when just calling the methods directly based on the if statement would be much better. What are you really trying to acheive here?
Answer: Well, another approach, (which I find very direct)
        var list = new List<Task>();
        for (var i = 0; i < 10; ++i)
        {
            var i2 = i;
            var t = new Task(() =>
                {
                    Thread.Sleep(100);
                    Console.WriteLine(i2);
                });
            list.Add(t);
            t.Start();
        }

        Task.WaitAll(list.ToArray());

Comment: I did something a little different, since I needed to handle an event that could raise additional events of itself over the course of handling the event, but those child events need the current event to complete before running: I used a Queue, and a while loop that checked if the queue had any tasks remaining, and that's all wrapped in an if block that checks a static boolean at the class level to see if _handlingDqEvent is true: if it is, we just enqueue our next task + return void, otherwise, our loop continues to dequeue and process tasks as they're added, and turns off the latch when done.
Answer: Instead of using Task.Factory.StartNew to create the tasks (the clue is in the name), instead just create them by using new Task(...) with your lambdas, then simply use taskName.Start() inside the condition you want to begin them.
Answer: You can create an array of Action based on a flag, and then use Parallel.Invoke() to run in parallel all the actions in the array and wait for them to finish.
You can use lambdas for the actions which will allow you to assign their return values to a local variable, if you want.
Here's a complete compilable example. Try it with getFlag() returning true and again with it returning false:
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    sealed class Program
    {
        void run()
        {
            bool flag = getFlag();
            var results = new string[5];
            Action[] actions;

            if (flag)
            {
                actions = new Action[]
                {
                    () => results[0] = function("f1"),
                    () => results[1] = function("f2"),
                    () => results[2] = function("f3")
                };
            }
            else
            {
                actions = new Action[]
                {
                    () => results[3] = function("f4"),
                    () => results[4] = function("f5")
                };
            }

            Parallel.Invoke(actions); // No tasks are run until you call this.

            for (int i = 0; i < results.Length; ++i)
                Console.WriteLine("Result {0} = {1}", i, results[i]);
        }

        private bool getFlag()
        {
            return true; // Also try with this returning false.
        }

        string function(string param)
        {
            Thread.Sleep(100); // Simulate work.
            return param;
        }

        static void Main(string[] args)
        {
            new Program().run();
        }
    }
}

Answer: The Task.Factory.StartNew will actually begin your tasks. You want to setup the tasks and then run them based on some logic.
You can build your tasks wherever but you should start them after the logic. This example builds them after the logic.
Maybe you could run it like this:
If(A)
{
     doA();
}
Else
{
     doB();
}

Then start your tasks inside the function you call like:
public void doA()
{
     for (int i = 0; i < NumberOfTasks; i++)
     {
          tasks[i] = Task.Factory.StartNew(() =>
          {
               try
               {
                    //enter tasks here
                    // i.e. task 1, 2, 3, 4
               }
          }
     }, token);

     Task.WaitAll(tasks);
}

Answer: I based what I did on what Samuel did, except I have a recursive event handler that needs to finish what it's doing because its child events depend on it having completed (for nesting controls in a dynamic UI in an ASP.NET app). So if you want to do the same thing, except you're handling an event, and you are NOT multithreading because you need to process multiple tasks synchronously without goofing around with your call stack.
    private static Queue<Task> _dqEvents = new Queue<Task>();
    private static bool _handlingDqEvent = false;

    protected void HandleDynamicQuestion(int SourceQuestionId, int QuestionId)
    {
        //create a task so that we can handle our events in sequential order, since additional events may fire before this task is completed, and depend upon the completion of prior events
        Task task = new Task(() => DoDynamicQuestion(SourceQuestionId, QuestionId));
        lock(_dqEvents) _dqEvents.Enqueue(task);
        if (!_handlingDqEvent)
        {
            try
            {
                //lockout any other calls in the stack from hitting this chunk of code
                lock (_dqEvents) _handlingDqEvent = true;

                //now run all events in the queue, including any added deeper in the call stack that were added to this queue before we finished this iteration of the loop
                while (_dqEvents.Any())
                {
                    Task qt;
                    lock (_dqEvents) qt = _dqEvents.Dequeue();
                    qt.RunSynchronously();
                }
            }
            finally
            {
                lock (_dqEvents) _handlingDqEvent = false;
            }
        }
        else
            //We exit the method if we're already handling an event, as the addition of new tasks to the static queue will be handled synchronously.
            //Basically, this lets us escape the call stack without processing the event until we're ready, since the handling of the grandchild event
            //is dependent upon its parent completing.
            return;
    }

    private void DoDynamicQuestion(int SourceQuestionId, int QuestionId)
    {
        //does some stuff that has no dependency on synchronicity

        //does some stuff that may eventually raise the event above

        //does some other stuff that has to complete before events it triggers can process correctly
    }

Comment: I realize that I don't need the else/return block, and that the locks are unnecessary because I'm not multithreading, but got off on that spur before this, when I realized I didn't need multiple threads, I just needed to queue tasks rather than have them interrupt the current process immediately when the event is raised.


Septic Replacement: Can I Do it Myself?

Question: I am looking at a property with a serious fixer-upper on it.  I want to place a mobile home on the property while gutting out existing building to see if it can be renovated.  My question is about the septic.  I has a well and eptic, but has been abandoned for a few years now.  I believe the septic will need to be updated, parts of it replaced.
Is this something I can do myself, with the help of my brothers and dad?  If so, what kinds of costs am I looking at?
Comment: You'll have to at least have it pumped by a professional. There also might be environmental issues with this (leakage, seepage, disposal), so I would say this is probably **NOT** a diy project.
Comment: I'll have to agree with Tester on this one. My home has a septic system and the county had to do all of the proper inspections, of course, but also gave me a "Waste Water Treatment Permit" as part of the certification (your area may very).
Answer: Replacing a septic system is a really crappy job, you'll want to let the pros handle this one.  A job like this requires special licenses, permits, equipment, and knowledge. It may seem like your just digging a hole and dropping a tank in it, but there is a lot more planning and hassle involved.  It's worth paying to have this done, rather than doing it yourself and then finding out it's not right and has to be ripped out and redone.
Comment: @B Mitch @Shirlock:  Mike Rowe can get in and clean it out, Mike Holmes can remove and replace it. Team Work!
Comment: Sounds like a job for Mike Rowe. :)
Comment: Rather see Mike Holmes on this job!  lol.
Comment: sounds like that would be an entertaining show!
Answer: Tester is right on this one. Most towns require several items before issuing a permit. A septic plan designed for the proposed structure, (# of bedrooms/bathrooms ), a soils study done by a soils engineer, Perk tests in some areas. and a site inspection pre-excavate and again before system is covered up.
Before you consider the expense of building a new system, it would be wise to have the existing system inspected and tested.  The inspector/engineer should be able to tell you it's size, capability, leach field condition and draw out the system in a form that will be acceptable to the town as a septic plan for future use.
Although I have seen some hearty souls attack doing a septic system themselves, this is typically a job better left to an experienced contractor with the right heavy equipment and know how.
Answer: Also, depending on your location, you may need to be a licensed septic installer in order to have the design approved, obtain the necessary permits, etc.. (in the county I live in, this is the case).  I'd definitely call the pros in on this one.
Answer: As you can see, the answer is clearly, "no."
Let me offer another option: composting toilets and a graywater system! You probably can install a composting toilet system or separate individual units, as well as graywater plumbing for everything other than the toilets.  Then you can abandon the septic tank and all future septic-related expenses too (pumping can be north of $300 every couple of years). And you get free compost and irrigation water out of the bargain.

Septic Replacement: Can I Do it Myself?


Finding unique records in a table which did not repeat after a particular date in another table

Question: I am a beginner in SQL and trying to solve an issue.
I have two tables on my database, company and invoice as below
Company table
id          name          active
1           company A     True
2           company B     True
3           company C     True
4           company D     True
5           company E     True

Invoice table
id            date            companyid
1             18/01/2018      4
2             06/05/2014      1
3             04/03/2017      4
4             25/05/2016      3
5             17/04/2018      2
6             10/11/2017      3

I want to get a get a list of unique values of companies and change the "active" column value to False if a company doesn't have any invoice after 01/01/2017. By saying this, Company A and E active column should be changed to False. The desired outcome would be this:
id          name          active
1           company A     False
2           company B     True
3           company C     True
4           company D     True
5           company E     False

I have tried this but this is just half and I could't sort out the rest of the solution:
select distinct A.* from company A
    inner join invoice B
        on B.companyid = A.id
        where B.date < '20170101'

Comment: Welcome to StackOverflow! Would like to tell you that you've formatted your question perfectly, good job!
Comment: If you want to update the values in the table take a look at the [UPDATE Clause](https://learn.microsoft.com/en-us/sql/t-sql/queries/update-transact-sql?view=sql-server-2017). If you want to display it inside an SELECT take a look at the [CASE Clause](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-2017)
Answer: You could use this:
SELECT c.id, c.name,
    MAX(CASE WHEN i.date > '01/01/2017' THEN 'True' ELSE 'False' END) AS active
FROM company c
LEFT JOIN invoice i
ON i.companyid = c.id
GROUP BY c.id, c.name;

Answer: Use case when with subquery and aggregation
select id, name, case when mdate>'20170101' then 'Active' else 'False' end as Active
from
(
select A.id,A.name,max(date) mdate from company A
    left join invoice B
        on B.companyid = A.id
group by A.id,A.name)a

Answer: use join and case when
    select t1.id,t2.name,
   case when t2.date<'01/01/2017' and t1.active then
   'false' else t1.active end
    as active
     from Company t1 join invoice t2 on t1.id=t2.id

Answer: Like you said, you have indeed reached half your answer. You just need an update statement to go with your query.
UPDATE A SET active = 'false'
from company A
inner join invoice B
on B.companyid = A.id
where B.date < '20170101'


Update with CTE does not recognize column names in the set clause

Question: I need to update an existing table with data from another. My CTE is giving me correct result, but when I'm trying to update with the CTE SSMS complains on
Msg 102, Level 15, State 1, Line 13
Incorrect syntax near '.'.

or Invalid column names at the lines below:
set cm.Action.Identifier_fk = ID
set cm.ActionRequestedAction = Action
set cm.Action.apartment_fk = apartment_fk

This is the code:
Use DB;
GO

with CTE (ID,Action,Identifier_fk,apartment_fk) AS

(select a.ID, a.Action, b.Identifier_fk, m.apartment_fk
from Project.AllSent a (nolock)
    left outer join cm.Action b (nolock) on a.ID=b.Identifier_fk
    left Outer Join csv.Matching m (nolock) on m.Identifier_fk = a.ID
    left outer join csv.Apartment p (nolock) on m.apartment_fk=p.apartment_pk
    where b.Identifier_fk is NULL)

update cm.Action
set cm.Action.Identifier_fk = ID
set cm.Action.RequestedAction = Action
set cm.Action.apartment_fk = apartment_fk

    from CTE c
    JOIN Project.AllSent t (nolock) on t.ID=c.ID;

Comment: No, the syntax to update multiple columns is `set col1 = 1, col2 = 2, col3 = 3`
Comment: what is `cm.Action` in the `update` query?
Comment: cm - is a schema, Action - is a table.
Comment: It's been a while since I have used SQL Server, but can you have multiple `SET` calls in one updated? Don't you just separate them with commas?
Comment: I guess you are right, It handles just one per execution. I've already tried executing them one at a time, but I'm still prompting to the same issue.
Answer: The correct update statement has only one set.  Also, you have no cm in the from clause.  I'm going to propose getting rid of the CTE:
update b
    set Identifier_fk = a.ID,
        Action.RequestedAction = a.Action,
        apartment_fk = mm.apartment_fk
    from Project.AllSent a (nolock) left join
         cm.Action b (nolock)
         on a.ID = b.Identifier_fk left join
         csv.Matching m (nolock)
         on m.Identifier_fk = a.ID left join
         csv.Apartment p (nolock)
         on m.apartment_fk = p.apartment_pk
    where b.Identifier_fk is NULL;

I don't think the final join is necessary.
Comment: I think so too, I's not necessary.
Comment: I do see [cm] in the From clause in the join. What exactly are you referring to?
Comment: Not sue why, but this updates 0 rows... Any idea? (0 row(s) affected)
Comment: I see no `cm`.  All the aliases should refer to tables in the `from` clause.
Comment: @enigma6205 . . . You query is using `left join` to the table being updated.  That doesn't really make sense.  Either `b` should be the first table in the `from` clause or the first join should be an `inner join`.
Comment: I'm using left join on the query because table A and table B has 0 matching values. Example table A has id [1,2,3,4], table B has id [5,6,7,12]. I need all not matching IDs from table A to be loaded to table B.
Comment: @enigma6205 . . . But you are updating `B`.  If there is no matching record in `A`, then nothing is updated.


Can I prevent a neighbor from building a fence against my house?

Question: I live in a townhouse community, and the side of my house acts as a fence for my neighbor's yard. He wants to now put a fence next to my house so he doesn't have to look at the side of it. I have concerns regarding termites, rats and mold etc. living in the tiny area between. The side of my house is the property line. Do I even have a say so?
Comment: Your deed, lease, HOA contract, and other legal documents will define what rights you and your neighbor have.  In a townhouse community the area around the property line is often not strictly "owned" by you, or if it is, what you may do there is well defined.  I would be surprised if your neighbor could do something that prevents you from gaining access to perform maintenance on your house wall.  But it's possible.
Comment: I'm voting to close this question because it's a legal or local code issue.
Comment: Yes, this is a legal question, and the buzzword here is "HOA" or Home Owners Association.  They have neighborhood rules about what can be done, and they are more powerful than a city ordinance.  You can use their force to limit your neighbor's ability to do anything untoward.
Comment: So up to the roof line?
Comment: If your neighbor allowed you to take this picture you must have a reasonable working relationship.  Maybe you could find a compromise, such as allowing them to  paint your siding to their liking, or to attach inorganic fence panels or trellis directly to your wall without touching the ground, or to plant some bushes a suitable distance away from your wall.
Comment: As you can't see it, would you be upset if your neighbour decorated the wall up to the height of the existing fence? Perhaps with some brown paint that pretty much matches. It would be faster and cheaper for him, and give some weatherproofing to the surface for you.
Comment: Adding a fence will have minimal impact on the termite, rat or mold population. The real issue is what happens to the neighbor's fence when you need to do some repairs to your siding. You'll have to tear it down.
Comment: Is that wall to your house right on the property line?
Comment: Moving the fence onto your property? But the fence needs to be straight and now how much do you loose? I would not worry about mice, termites etc as the fence should not be in contact with the home. I am used to small lots like this requirement to have good neighbor fences, every other fence plank on the other side. What do you have to look at?
Comment: I think OP's concern is that if the fence is a few inches from the wall, leaves and crud will accumulate in the gap, will harbor moisture and rot and attract nesting.
Comment: Voting to close also because answers to the question as currently asked will inevitably just speculate on terms of ownership.  Christine you can edit and reopen the question making it more specifically about how to build something there, once you know what's allowed and what you and your neighbor can agree on.
Answer: It's reasonable to be concerned about accessibility of your building for inspection, maintenance, and upkeep and cleanliness reasons. It's almost certain that you personally do not have a "say so" in whether or not the neighbor can construct a fence here, but I think it's very likely that somewhere there is language that restricts him doing it. The onus is on you to find that language and then persuade the local government (or the HOA, if applicable) to step in and enforce it.
Municipal zoning rules ("ordinances" or "codes") often impose minimum "setback" requirements. A setback is the minimum distance separating a building from the edges of the property upon which it is built. You have what is called a "zero lot line home." This term alludes to there being a "zero setback" on one of the lot lines, meaning the house is built on or very near the property line. Some high density communities are designed with this feature to balance the need for adequate space between buildings with the need for that space to be allocated in a usable way (think of fire or maintenance access to the rear yard).
Because zero setback is an exception to the norm it would be expected that, in granting permission for the development, the zoning authority (a city, probably) would impose conditions -- for example, that a fence adjacent to a building would be prohibited.
You're going to have to do your own research. Here are several things to look for. Start with whichever is easiest for you to access. Read the material yourself: helpful people may summarize for you what they think these materials say, but chances are they've never read the materials with the same question in mind as you have now. They might be surprised by what you find!

City zoning code. Look for regulations applicable to zero lot line construction. Look for regulations on fencing too; there may be requirements for minimum space between parallel fences or fences parallel to buildings.
The complete plat map of the community. There may be several pages. The map may be included in your home mortgage paperwork, and should also be available through the county recorder's office. Pay attention to which areas of land are common area owned by the HOA and which areas are privately owned by homeowners. Read all the blocks of notes on every page - there can be interesting and important details hidden in the fine print.
Find out whether there was any conditional use permit or site plan issued for the community, and if so what are its conditions. A government records request through the city recorder's office may be the mechanism for obtaining this info.
Comment: Good point on checking with the County Recorder, the association documents are probably also recorded.
Answer: To answer your question, you probably do not have a say so, the association has the ultimate say so. That's one of the positive/negative things about having a condo/townhouse association. There should be bylaws or some sort of association documents that allow/restrict any sort of structure being placed or built. They also may not allow you to change colors, doors, garage doors exterior lights or place plantings. One positive is someone with poor decorating ideas can't make changes and lower the value of everyone else's unit. One of the negatives is if you want to do something that you think is an improvement it may not be allowed. Sometimes owners may try to get special permission from the board for something that is not allowed and if it affects you then you may have a say so.
Comment: I would say the OP has say so, the unit belongs to the OP the HOA has rules or covenants, but they can not intrude on a property.


use p:media or p:documentViewer with p:dialog dynamic

Question: first of all you should know that I am new to web application development with jsf, so if I ask for bad things please correct me.
I need to develop a table that shows the description of a pdf file and a button to display it in a dialog box, (important should not be able to download, copy or print this file). I have exhausted all my possibilities with the  and , but when displaying the dialog box, the document is not displayed, this is my code:
<h:body>  <ui:composition template="/template/plantilla.xhtml">  <ui:define name="content">
      <h:form id="frmpdf">

<h:outputText value="Docs .PDF" style="font-weight: bold;"/>

                  <h:outputText value="#{dpdf.sgTfd_descripcion}" />

                </h:form>
            </ui:define>
        </ui:composition>
    </h:body>

I have also used:

result
The above develop it taking into account this post
Answer: After doing more research, I managed to solve my problem with the tag
 that allows to establish a value from the bean when this event is triggered, I leave the code with the solution:
<f:view>

<h:head>
    <title>Page</title>

    <link rel="stylesheet" type="/text/css" href="/js/keyboard.css" />
</h:head>

<h:body>
    <ui:composition template="/template/plantilla.xhtml">
        <ui:define name="content">
            <h:form id="frmpdf">
                <f:event listener="#{documentPdfBean.onPrerender}" type="preRenderView" />

                    <h:outputText value="Docs. PDF" style="font-weight: bold;"  />

                        <h:outputText value="#{dpdf.sgTfd_descripcion}" />

                            <f:setPropertyActionListener target="#{documentPdfBean.ruta}" value="#{dpdf.sgTfd_valor}" />

                    <pe:documentViewer height="700" id="pdfvisualizer"  value="#{documentPdfBean.ruta}" />

            </h:form>
        </ui:define>
    </ui:composition>
</h:body> </f:view>

bean
 private String ruta;

public String getRuta() {
    return ruta;
}

public void setRuta(String ruta) {
    this.ruta = ruta;
}


simple fade not working

Question: I've made a simple box with CSS, I'm trying to fade it by dynamically changing it's opacity using the setInterval object.
http://jsfiddle.net/5gqRR/7/
CSS
#box {
margin:0px auto;
margin-top:10px;
height:50px;
width:50px;
background:black;
}

JAVASCRIPT
var fade;
function select(id) {
    return document.getElementById(id);
}
function disBox() {
    fade=setInterval(function(){
        select("box").style.opacity-=0.1;
    },300);
    if (select("box").style.opacity==0) {
        clearInterval("fade");
        select("box").style.display="none";
    }
    else {
        select("box").style.display="block";
    }
}

The problem is that the "-=" operator starts subtracting the opacity from 0 instead of 1.
Can someone please explain why this happens?
Comment: Don't forget jQuery http://jsfiddle.net/5gqRR/5/ :)
Comment: I know it'd be way easier to do this with jquery but why won't this work?
Answer: Your check about the opacity should be inside the loop.
function select(id) {
    return document.getElementById(id);
}

// Run at loading
window.onload = function () {
    // Preload variables
    var box = select('box'), opacity = 1, fade;

    // Looping
    fade = setInterval(function(){
        // Calculate and applying opacity
        opacity = Math.max( 0, opacity - 0.1 );
        box.style.opacity = opacity;

        // Stoping loop when box isn't visible
        if ( !opacity )
            clearInterval(fade);
    },30);
};

Demo: http://jsfiddle.net/5gqRR/8/
Answer: You can't set an onload event to div element. Instead of that you can do:
HTML

JavaScript
var fade;
function select(id) {
    return document.getElementById(id);
}
function disBox() {
    fade = setInterval(function(){
        select("box").style.opacity-=0.1;
    },300);
    if (select("box").style.opacity==0) {
        clearInterval("fade");
        select("box").style.display="none";
    }
    else {
        select("box").style.display="block";
    }
}

window.onload = (function() {
    disBox();
})();

Demo
According to edit
select("box").style.opacity = 1;  // add this line to set initial opacity
fade = setInterval(function(){
            select("box").style.opacity-=0.1;
        },300);

Comment: That's great advice but I used the onload event in the  tag in the actual page. The problem is that when I use the "-=" operator it starts subtracting the opacity from zero when it should start subtracting from 1.
Comment: @senilesage then you can try with set a `css` opacity or write `select("box").style.opacity = 1;` line before `-=` line
Comment: I don't think my question made the problem too clear so I made a few edits.

simple fade not working


Edge does not handle scaling and text-anchor:middle correctly in svg

Question: I'm writing a graph display program using D3 and I found an issue in which Microsoft Edge does not handle edge scaling correctly. My code is below:
HTML:
<svg id="container" width="200" height="200">
  <g id="inner-container">

  </g>
</svg>

JS:
var container = d3.select("#container");
var innerContainer = container.select("g");
container.call(d3.behavior.zoom().scaleExtent([.5,4]).on("zoom", function(){
  innerContainer.attr("transform", "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")");
}));

var nodes = innerContainer.append("g").selectAll(".graph-node");
var labels = innerContainer.append("g").selectAll(".graph-label");

var data = ["A", "B", "C", "D", "E"];

nodes.data(data).enter().call(function (selection){
  selection = selection.append("g");
  selection.attr("class", ".graph-node");
  selection.attr("transform", function(d, i){
    return ["translate(", (i * 20).toString(), " ", (i * 20).toString(), ")"].join("");
  });
  selection.append("rect")
    .attr("width", 20)
    .attr("height", 20)
    .attr("rx", 2).attr("ry", 2)
    .attr("fill", "red");
  selection.append("text")
    .text(function(d){ return d; })
    .attr("text-anchor", "middle")
    .attr("x", 10).attr("y", 15)
    .style("fill", "white");
});
labels.data(data).enter().call(function (selection){
  selection = selection.append("g");
  selection.attr("class", "graph-label");
  selection.append("text")
    .text(function (d) { return "Node" + d; });
  selection.attr("transform", function (d, i) {
    return ["translate(", (i * 20 + 25).toString(), " ", (i * 20 + 15).toString(), ")"].join("");
  });
});

View in JSFiddle
In Google Chrome, IE, and Firefox, zooming works exactly as expected. However, when I run this code in Microsoft Edge, the text labels on top of the nodes will shift to the right as I zoom in, entirely disappearing when they leave the rectangle. The problem disappears when I don't set text-anchor, but that will mean that I have to account for text positioning manually, especially considering when the site is used internationally. (The text characters themselves don't matter, since they're from a custom font in the final product).
How can I work around this, providing a centered text label and yet having it still display correctly on Edge?
Answer: Been in similar situations with browser incompatibilities in text layouting several times. If you fail to find the magic combination of CSS properties that works for all, here is one other option:
Add a
 element to your page. This element is invisible by definition. Select the element with D3's select. Add the text you want to layout as innerHTML. Use classed and style to style the element in the exact same way you will style the text. You can now get the text's exact length with the browser function getComputedTextLength or by reading the element's dimensions.
Hide all of this in a handy reuse function or TextLengthCalculator class.
Once you have the dimensions, you can calculate the desired offsets yourself and simply shift the text by adjusting its x and y attributes.
This is fast and takes localization and styling into account. It even is clean and reliable since it is still the browser itself that does the calculation. And although the browsers still sometimes produce different results here, at least each browser is consistent with its own calculation.


Electron's BrowserWindow zoomFactor can be changed after construction? and how to choose nearest neighbor instead of smoothing?

Question: In node electron's BrowserWindow constructor, you can specify webPreferences: { zoomFactor: x } to zoom the web contents of the window.
Is there a way to modify this when the BrowserWindow has already been created?
And is there a way to specify that the content is not smoothed when zoomed but rather magnified with nearest neighbor?
Comment: I am also trying to do this. Do I need to recreate the window and reload the contents?
Comment: hi! any solution on this? thanks
Comment: Nope, I haven't even touched electron again ever since.
Answer: You can use webContents.setZoomFactor(factor)
The zoom factor is zoom percent divided by 100, so 300% = 3.0.
Ref.
Comment: This worked for me when I called it in the "ready-to-show" event on the window.
Comment: Can verify that the key is to use a combination of `setZoomFactor` and the `ready-to-show` event.
Answer:   mainWindow.once('ready-to-show', () => {
    mainWindow.webContents.setZoomFactor(1.2);
  });

Where mainWindow is a BrowserWindow


Is it possible to give effects to falling blocks?

Question: I want to build a "rocket" out of concrete powder. I have a command block that gives a levitation effect to entities within 5 blocks of the command block. This is how I have the rocket set up:
Top layer: 2x2 square of concrete powder.
Layer 0: 2x2 piston door that is sideways.
On the press of a button, the piston door opens, causing the concrete powder to become an entity and fall. The command block activates, giving all entities within 5 blocks of it Levitation 255 for 1 second. However, I only get levitated, and the blocks just fall and plop onto the ground. The concrete powder is in range of the command block, but it won't fly up into the air. Is it possible to add status effects to falling block entities (i.e. sand, gravel, concrete powder, and/or primed TNT)?
Answer: I tested this by placing a command block with the /effect command with a pressure plate on top. I would look up, place a sand block next to a fixed block, and exit fly mode so that I would land on the pressure plate while it is falling.
Result in Bedrock Edition:
Falling Block cannot have effects
Block of TNT cannot have effects

Result in Java Edition
Unable to apply this effect (target is either immune to effects, or has something stronger)

Therefore, falling blocks and blocks of TNT cannot have effects.
I would also like to take this opportunity to remind you that if you want to give a target an effect they already have but at a weaker level, you will need to remove the effect first in Java Edition. You don't need to in Bedrock Edition.
Comment: Does "Block of TNT" mean that it is primed (it is flashing)?
Comment: So if I wanted to make a rocket using such commands, what would be an optimal solution?
Comment: Ok, so what method do you think would be the best in Java Edition?


HashMap values are changing without telling them to

Question: I have a problem that I am unable to understand..
I am building a HashMap called wholeSetHistory.
I am building a HashMap with the same keys and values that wholeSetHistory has, called wholeSetHistoryT.
In a similar way I create two HashMaps called wholeSetRates, wholeSetRatesT
All HashMaps have this format HashMap<String, HashMap<String, Double>> .
I have this function that creates a train set
public void createTrainSet(HashMap<String, HashMap<String, Double>> wholeSetRates, HashMap<String, HashMap<String, Double>> wholeSetHistory){
    for(String fbid : wholeSetHistory.keySet()){
        ArrayList<String> locsBe = new ArrayList<>();
        HashMap<String, Double> locss = wholeSetHistory.get(fbid);
        HashMap<String, Double> locss2 = wholeSetRates.get(fbid);
        for(String loc : locss.keySet()){
            if(locss.get(loc)==1.0){
                locsBe.add(loc);
            }
        }
        ArrayList<Integer> randomNums = new ArrayList<>();
        for(int i=0; i<2; i++){
            Random rn = new Random();
            int randomNum;
            do{
                int range = locsBe.size() - 1 + 1;
                randomNum =  rn.nextInt(range);
            }while(randomNums.contains(randomNum));
            randomNums.add(randomNum);
            locss.put(locsBe.get(randomNum), 0.0);
            locss2.put(locsBe.get(randomNum), 0.0);
            wholeSetHistory.put(fbid, locss);
            wholeSetRates.put(fbid, locss2);
        }
        randomNums.clear();
    }
}

So, later on I am using it like this
(... creation of wholeSetHistory, wholeSetHistoryT, wholeSetRates, wholeSetRatesT)
System.out.println(wholeSetHistory.get("1"));//1
createTrainSet(wholeSetRatings, wholeSetHistory, nearUserIDWithVisitedTrueValues);

That means that I am passing to the function as paramater only wholeSetHistory
Although, later I
System.out.println(wholeSetHistory.get("1"));//2
System.out.println(wholeSetHistoryT.get("1"));//3

This is what happens:

The values that changes in  wholeSetHistory changes in wholeSetHistoryT too!
  For example, prints 2 and 3 are the same(!) and different from 1.

Any help is mych appreciated.
Comment: Are you saying you're putting the same references in two different maps and when you change it in one map it changes it in the other too?
Comment: yes! the two pairs of hashmaps have the same keys and values
Comment: Changing a reference's value to an object in one map will change it accordingly in the other map as well. Try some sample code to test that it actually is that way
Comment: Are you sure locss and locss2 are different hash maps, and you are not passing the same reference? Same goes for wholeSetRates and wholeSetHistory?
Comment: Thanks you guys I found the solution!
Answer: A reference points to a location in memory. If you add the same reference to two different data structures, altering the reference in one will also alter the other. They point to the same object in memory.
Comment: The keys don't actually matter. If two different keys held the same reference as a value it would also change them both. What you need is independent objects to point the two different references to if you don't want the behavior you're experiencing. @IraklisBekiaris
Comment: Are you saying that if two different hashmaps have the same keys, you can't change the value in one of them? And if yes, what should I do? Overide a method or something ?
Comment: Yes! I got it. Thank you so much. I changed the way I create wholeSetHistoryT. I created a new hashmap to put as value and not the same i put on wholeSetHistory. Chears mate :)
Comment: @IraklisBekiaris, always glad to help!
Comment: Also, nice thing to know from now on ;d
Comment: @IraklisBekiaris, indeed, it is essential!


How do I stop my vacuum belt from making a noise and smelling when using it?

Question: Last week I had my Hover WindTunnel Max Multi-Cyclonic (Model # UH70601) vacuuming carpet on the bar floor setting. It started making a thwapping noise and smells like burned rubber when vacuuming with the brushroll on.
I opened up the bottom of the vacuum. When I remove the belt the vacuum doesn't make the noise. Looking at the belt and what is holding it in I don't understand why it is making the noise.
Comment: I can't explain the thwapping noise, but when I've had the burned rubber smell, it came from there being something keeping the roller from spinning freely (hair, string, or similar wrapped on the roller), so the belt was rubbing rather than turning.  So, look at the parts that the belt is transfering power to, not just the belt itself.
Answer: The belt is a wear item - it will need to be replaced occasionally.
Typically, what happens is that the beater will get stuck on something but the motor will continue to run, and the friction of the motor against the belt will cause it to heat up - that's what you're smelling.
Once that happens, it's time to replace the belt.  One trick that might get a bit more life out of it is to reverse the belt, but that probably won't last that long - most belts have grooves on one side to improve friction.
Comment: @TheEvilGreebo : 6 months?  Some of us don't even vaccuum that often.
Comment: Thanks Chris. I reversed the belt like you said and that has solved my issue for now :)
Comment: Plan on replacing it every six months or so.
Comment: I don't vacuum that often either.  My wife, however...


Resolve Route53 records whilst being joined to an Active Directory

Question: When I create a private hosted zone and add a record set to it, let's say an A record (test.apps.local -> 220.127.116.11), any EC2 instances deployed on that VPC will be able to resolve that record set (you can ping test.apps.local and get [22.214.171.124] back).
Part of the process of joining an instance (Windows) to an Active Directory domain is to change the DNS servers on the instance - the setting must be changed from automatic DNS servers to two specific IPs (the IPs of the domain controllers for the Active Directory).
After doing that, the instance resolves objects in the Active Directory domain (you can authenticate users defined in the AD for example). However, it stops resolving the record sets defined in Route53.
I guess the reason for that is that the instance doesn't look at the AWSProvidedDNS servers that know about the record set, so it doesn't find a match (i.e. when you ping test.apps.local you get nothing back now).
Is there a way to work around this and have an EC2 instance that is able to resolve Route53 whilst being joined to an Active Directory domain?
Answer: Since the second usable IP address in each subnet is reseved as DNS server by AWS add a new DNS forwarded record in AD to point to the second address .2 of your VPC subnet, for intance if your VPC is 10.0.0.0/16 the DNS address will be 10.0.0.2
Comment: That sounds promising! I'm off for a week for holidays now, I'll try when I'm back and let you know. Th als a lot for the answer!


Bluetooth not syncing with Logitech MX Anywhere 3 mouse after upgrade too 21.04 from 20.10 on HP255G5 laptop. Help?

Question: I am new to Ubuntu 21.04 after upgrading from 20.10. I am trying to pair my Logitech MX Anywhere 3 Bluetooth mouse and sometimes see a list of devices inluding it and sometimes not. Regardless, when I see the mouse listed to pair, requesting the pairing fails every time. I have updated Bluez and even created a new config file for the mouse yet nothing seems to work.
This began not immediately after the upgrade but after the last kernel update.
I see that several other people are having very similar problems with various Bluetooth devices on different hardware. Can anyone offer us all some help solving this problem?
Thanks.
Answer: I had the same problem. Somehow the pairing process seems to be broken in the user interface.
After trying many things, I found out that pairing with the bluetoothctl command line tool worked.
Start bluetoothctl
❯ sudo bluetoothctl
Agent registered

List devices
[MX Anywhere 3]# devices
Device 12:34:56:78:9A:BC MX Anywhere 3

Disconnect, just to make sure
[MX Anywhere 3]# disconnect
Attempting to disconnect from 12:34:56:78:9A:BC
Successful disconnected
[CHG] Device 12:34:56:78:9A:BC Connected: no

Pair the mouse via hardware address
[bluetooth]# pair 12:34:56:78:9A:BC
Attempting to pair with 12:34:56:78:9A:BC
[CHG] Device 12:34:56:78:9A:BC Connected: yes
Request authorization

Accept the pairing by typing "yes"
[agent] Accept pairing (yes/no): yes
[CHG] Device 12:34:56:78:9A:BC Paired: yes
Pairing successful
[CHG] Device 12:34:56:78:9A:BC Appearance: 0x03c2
[CHG] Device 12:34:56:78:9A:BC Icon: input-mouse
[CHG] Device 12:34:56:78:9A:BC Modalias: usb:v046DpB025d0015
[CHG] Device 12:34:56:78:9A:BC ServicesResolved: yes

From here on, the mouse worked like a charm.
Answer: This answer was originally posted here but it should be helpful also with this question.
Update: There seems to exist in newer Ubuntu versions a BlueZ v5.62 & v5.63 (Linux Bluetooth protocol stack) related issue with certain Logitech BT LE mouses. This should be fixed in BlueZ v5.64. And alternatively a downgrade to v5.61 may also help.
Note, the following information is BlueZ v5.53 related:
I had initially also problems in conjunction with a Logitech MX Anywhere 3 mouse (Mac version) under Kubuntu 20.04 LTS (kernel 5.13.0-41-generic).
Regardless what I tried, the mouse didn't connect when I want to pair it via the Bluetooth assistant in KDE plasma. Then I decided to connect the mouse via the USB cable. At first this didn't change anything, the mouse just started to load its battery.
However, I then tried again to pair the mouse via the "pairing button" (pushed it for more than 5 seconds) and simply select at the BT icon on the taskbar (right clicked on it) the "connect" option. And for whatever reason it worked that time. The Logitech MX Anywhere 3 mouse works perfectly well. There was nothing to adjust, the sensitivity and reaction time suits perfectly well and also the scroll wheel works as it should (it is not inverted, even on the Mac version of that mouse).
Final note, the proprietary Logitech transmitter (which comes as an USB dongle) is known to work under Linux almost always right out of the box. So this may be the alternative solution for using this mouse under Linux. Note, the Mac version of the Logitech MX Anywhere 3 doesn't include that Logitech transmitter. It has to be purchased additionally.
Warning, the Logitech MX Anywhere 3 is BT LE (aka BT 4.x) only. It doesn't work with legacy BT 2.x and BT 3.x controllers.


How to solve the error: WARNING:root:could not open file '/etc/apt/sources.list'

Question: wazir@wazir:~$ sudo software-properties-gtk
[sudo] password for wazir:

(process:15506): Gtk-WARNING **: Locale not supported by C library.
    Using the fallback 'C' locale.
Cannot set locale: unsupported locale setting
WARNING:root:could not open file '/etc/apt/sources.list'

WARNING:root:could not open file '/etc/apt/sources.list'

Traceback (most recent call last):
  File "/usr/bin/software-properties-gtk", line 104, in <module>
    app = SoftwarePropertiesGtk(datadir=options.data_dir, options=options, file=file)
  File "/usr/lib/python2.7/dist-packages/softwareproperties/gtk/SoftwarePropertiesGtk.py", line 89, in __init__
    SoftwareProperties.__init__(self, options=options, datadir=datadir)
  File "/usr/lib/python2.7/dist-packages/softwareproperties/SoftwareProperties.py", line 97, in __init__
    self.reload_sourceslist()
  File "/usr/lib/python2.7/dist-packages/softwareproperties/SoftwareProperties.py", line 585, in reload_sourceslist
    self.distro.get_sources(self.sourceslist)
  File "/usr/lib/python2.7/dist-packages/aptsources/distro.py", line 87, in get_sources
    raise NoDistroTemplateException("Error: could not find a "
aptsources.distro.NoDistroTemplateException: Error: could not find a distribution template

Answer: Changing the permissions might work:
sudo chmod -R 0644 /etc/apt/sources.list.d/

UPDATE: I previously set the mode to 0420, which worked in my case, but per comments and further testing it seems that 0644 is correct.
Comment: The proper permission would be 644 on those files.
Comment: Do you have a source for that? I tried 644 and it did not work. The files in that directory that were not throwing errors already had 0420 mode, so I applied that to the remaining files to get it to work.
Comment: Indeed i have a source, a clean install on a VM where I just looked at the directory and each file has `-rw-r--r--. 1 root root` which is in fact 644. Beside that giving the owner only read rights prevents later changes on this file greatly and I'm not really sure why you think the group needs write access but the owner not this is what your given permissions imply is `-r---w----. 1 root root` and thats plain wrong. See as well https://help.ubuntu.com/community/FilePermissions
Comment: Directories should be executable or else you can't get listings of them. You want `sudo find -type d /etc/apt/sources.list.d -print0 |sudo xargs -0 chmod 0755 && sudo find -type f /etc/apt/sources.list.d -print0 |sudo xargs -0 chmod 0644`
Comment: "Directories should be executable or else you can't get listings of them." I don't think this is quite right: https://unix.stackexchange.com/questions/21251/execute-vs-read-bit-how-do-directory-permissions-in-linux-work
Comment: Had `WARNING:root:could not open file '/etc/apt/sources.list.d/intel-sgx.list'` which was solved by changing this file's permissions to `0644`. All other files within the directory already had this permission level.
Answer:
You shouldn't use sudo to open graphical applications as root. You should install the gksu package from the Ubuntu Software Center and use the gksudo command instead of sudo to open a graphical application as root.

You shouldn't run software-properties-gtk as root either. If you need to be root, the application will prompt you in a popup window to authenticate with your user password. Since software-properties-gtk has a built-in authentication feature, you don't need to run it except as a regular user.

Try running software-properties-gtk properly, and see if you still get the same error.

Ubuntu 18.04 and later
gksu has been discontinued in Ubuntu 18.04 and later. To open software-properties-gtk as root run the following command:
sudo -H software-properties-gtk &>/dev/null

Comment: I learned something, but it did not solve my issue. Thank you anyway
Comment: bash: /dev/nulll: Permission denied
 for ubuntu 18.04
Comment: @Rocketq Thank you for bringing this to my attention. This `permission denied` error was caused by a typo error (misspelled the word `null`) which I found and corrected.
Comment: @karel `/etc/apt/sources.list` is neither an executable nor a directory. Why would you suggest adding execute permissions to it?
Answer: The sources.list files are in /etc/apt/sources.list.d in newer version of Ubuntu. So you need to make a symbolic link from official-package-repositories.list to the old place to solve this problem:
sudo ln -s /etc/apt/sources.list.d/official-package-repositories.list /etc/apt/sources.list

Answer: I think execution permission is needed, try to run the following command:
sudo chmod +x /etc/apt/sources.list.d

Comment: How is the directory `/etc/apt/sources.list.d` connected to the file `/etc/apt/sources.list` mentioned in the question?


How to capture output from tcpdump

Question: I'd like to capture the output from tcpdump and use it as input for a second command. By the way I don't want to use the pcap format!
I tried
sudo tcpdump -q ip > ./out.txt

When I watched the file I saw the whole STDOUT was written  to the file all the time but I expected the file to be overwritten with the new content only. Is all the STDOUT buffered or cleared when written to the terminal?

Is there a way I can read only the partial updates from STDOUT?
How can I redirect output continuously from tcpdump to an other cmd?

Does this work ?
sudo tcpdump -q ip | my_command

Comment: If I understand correctly you want only the last N line to be written to the file, is this correct?
Answer: To always overwrite the file with each new tcpdump line:
sudo tcpdump -l -q ip | awk '{system("echo " $0 " > out")}'

To use the output for an other comand, eg awk

$3 = only the 3rd column
sudo tcpdump -l -q ip | awk '{print $3}'

Filter by tcp
sudo tcpdump -l -q ip | awk '/tcp/ {print $0}'

Or a combination:
sudo tcpdump -l -q ip | awk '/tcp/ {"echo " $0 " > out"}'

from man tcpdump
   -l     Make  stdout  line  buffered.
          Useful if you want to see the data while capturing it.
          E.g.,
                 tcpdump -l | tee dat
          or
                 tcpdump -l > dat & tail -f dat

Comment: Gets the content replaced everytime tcpdump writes to STDOUT ? In terms of replaced i dont mean multiple calls to tcpdump rather the contionous output the command generates!
Comment: Now yes =) `sudo tcpdump -l -q ip | awk '{system("echo "$0" > out")}'`

How to capture output from tcpdump


Android ffmpeg: Path with spaces

Question: I have almost the same problem that this question: Android: ffmpeg with filenames containing spaces
The problem is I'm using this library: https://github.com/hiteshsondhi88/ffmpeg-android-java
In the stack overflow question that I've post the only way to achieve is passing the cmd command as String[] (which cannot be done with this library)
Comment: Did you ever solve this?
Comment: Did you ever solve this?
Answer: I had a similar problem. Because the video's file path contained a space that was encoded to %20, the ffmpeg execution failed. I solved this by replacing %20 with a white space. And then using the updated Uri string for the ffmpeg execution.
String videoUriString = videoUri.toString().replaceAll("%20", " ");

where videoUri is the Uri for my video file that contained spaces.
I hope this helps.

Android ffmpeg: Path with spaces


Typescript type for an array that can contain only elements from a specific list

Question: I want to declare a type for an array that can contain maximum one of the following strings: 'first', 'second', 'third'.
Some valid examples of how that array could be:

[]
[ 'first' ]
[ 'first', 'second' ]
[ 'first', 'second', 'third' ]
[ 'first', 'third' ]
[ 'second', 'third' ]

Some invalid arrays:

[ 'other-value' ] // no other values should be accepted
[ 'first', 'first' ] // no duplicates accepted

The types I've wrote:
export enum MyOptions {
  first = 'first',
  second = 'second',
  third = 'third'
}

export type MyType = {
  name: string;
  email: string;
  listings: {
   MyOptions;
  }[];
};

It has a warning saying Member 'MyOptions' implicitly has an 'any' type, but a better type may be inferred from usage.
So if it is changed to:
export type MyType = {
  name: string;
  email: string;
  listings: {
   options: MyOptions;
  }[];
};

Now, there is no warning but it has that extra options value that I don't think it must be added.
Any ways to fix this?
Answer: You can use the Set data structure.
export type Options = 'first' | 'second' | 'third'
export type Listing = Set<Options>

export type MyType = {
    name: string;
    email: string;
    listings: Listing;
};

const myType = {
  name: 'name',
  email: 'email',
  listing: new Set(['first', 'second'])
}

Then you will be sure that there are no repeated options in your listing.
Note: actually you can pass repeated options but Set will ignore them.
Answer: I think you have an extra set of braces that you don't need.
export type MyType = {
  name: string;
  email: string;
  listings: {
   MyOptions;
  }[];
};

should be changed to
export type MyType = {
  name: string;
  email: string;
  listings: MyOptions[];
};

You also have a more concise option: use string literal types:
export type MyType = {
  name: string;
  email: string;
  listings: ('first' | 'second' | 'third')[];
};

Comment: it seems that your answer accepts duplicates (`[ 'first', 'first' ]`) too which should not, I added it as invalid arrays in the question's body, maybe it wasn't clear before
Answer: It should be like this:
export type MyType = {
    name: string;
    email: string;
    listings: MyOptions[];
};

Let's assume you have variable named x of MyType, then to push new value to listings member you can do x.listings.push(MyOptions.first)
Answer: The second solution just means that you now have an object that could look like:
const exampleObject = {
  name: 'Ralf';
  email: 'email@example.com';
  listings: {
   options: 'first';
  }[];
};

Which is not what you intend, because you can´t have a ['first', 'second'] there, but only ONE value.
If you use the style
listings: MyOptions[];

Then it allows also the content ['first', 'first'].
As far as i know, there is no way to limit the possible values not only by its content, but also by its amount (having at maximum one of each values) via typescript types.
So you would have to create your own logic.
For example having a small business object
class Options {
  private _values: MyOptions[] = [];

  addOption(option:MyOption){
    if(this._values.some(option)){
      return; // or throw an error, depends on your usecase
    }
    this.values.concat(option);
  }

  get options():MyOptions{
    return this._values;
  }
}

Now you can have your wrapper type:
export type MyType = {
  name: string;
  email: string;
  listings: Options
};


Deriving max. likelihood estimate of β for a logistic model of two classes with a single binary regressor

Question: I have the log-likelihood function:
$$l(\overrightarrow\beta)=\sum_{i=1}^n   [y_i log(p(\overrightarrow x_i;\overrightarrow\beta))+(1-y_i)log(1-p(\overrightarrow x_i;\overrightarrow\beta)] $$
where $p(\overrightarrow x_i;\overrightarrow\beta)=\frac{e^{{\overrightarrow\beta^T}\overrightarrow x_i}}{{1+\overrightarrow\beta^T}\overrightarrow x_i} $ where $\overrightarrow\beta=(0,\beta_1)^T$ is the parameter vector and $\overrightarrow x$ is the matrix of inputs, whose first column is all 1's.
The two classes are $y_i=0$ or $1$, and since there is a single binary regressor,  $\overrightarrow x_i$ will be an $n\times2$ matrix where $x=0$ or $1$.
Additionally, $n_{1,0}$ denotes the number of observations with $x_i=1$ and $y_i=0$, and $n_{1,1}$ denotes the number of observations with $x_i=1$ and $y_i=1$.
The max. likelihood estimator of $\beta_1$ is claimed to be $log\frac{n_{1,1}}{n_{1,0}}$, but I can't see why that's the case. I know how to find the first derivative of the log-likelihood function: $\frac{\partial l(\overrightarrow \beta)}{\partial\overrightarrow \beta}=\sum_{i=1}^n   [\overrightarrow x_i (y_i-p(\overrightarrow x_i;\overrightarrow\beta))]$ *
I know for maximization we woud set this equal to zero, and can see that * breaks into two equations since $\overrightarrow x_i= (1,1)$ or $(1,0)$. For the first case we would arrive at $\sum_{i=1}^n y_i = \sum_{i=1}^n p(\overrightarrow x_i;\overrightarrow\beta)$, but I'm not sure what the next step might be to arrive at the given result.
Answer: Since there's only one regressor $x$ and there's no intercept in the model, you can treat each $x_i$ as a scalar instead of a vector, and regard $\beta=\beta_1$ as a scalar instead of a vector. So I'll drop the vector notation from now on. Set the expression
$
\sum_i[x_i(y_i-p(x_i;\beta))]
$
to zero. This yields
$$
\sum x_iy_i = \sum x_i p(x_i;\beta)\tag1
$$
The LHS of (1) simplifies to $n_{1,1}$ since the terms where $x_i=0$ or $y_i=0$ don't contribute.
Similarly the RHS of (1) simplifies to $$\sum_{x_i=1} p(x_i;\beta)= \#\{x_i=1\}\cdot p(1;\beta) = (n_{1,0} + n_{1,1}) e^{\beta_1}/(1+e^{\beta_1}) .$$
With these simplifications you can solve (1) for $e^{\beta_1}=n_{1,1}/n_{1,0}$.
Added: If your model had two parameters, say $\vec\beta=(\beta_1,\beta_2)$, for the intercept and the binary regressor $x_i$ (sorry, the meaning of $\beta_1$ has changed), then your equation ($*$) would split into two equations for the two unknowns $\beta_1$ and $\beta_2$. The $k$th equation would involve the column $k$ of the $x$ matrix: $$\sum x_{i,k}y_i=\sum x_{i,k} p(\vec x_i, \vec\beta).\tag2$$
The equation for column $2$ would be simplified as before using $n_{1,1}$ and $n_{1,0}$:
$$
n_{1,1} = (n_{1,0}+n_{1,1})p((1,1),\vec\beta)=(n_{1,0}+n_{1,1})\frac{e^{\beta_1+\beta_2}}{1+e^{\beta_1+\beta_2}}\tag3
$$
As for the intercept column, substitute $x_{i,1}=1$ for all $i$ to get:
$$
\sum y_i =\sum p(\vec x_i, \vec\beta).\tag4
$$
The LHS would involve only cases where $y_i=1$, and the RHS would break into one sum where $x_i=0$ and one sum where $x_i=1$:
$$
n_{0,1}+n_{1,1}=(n_{0,0}+n_{0,1})\frac{e^{\beta_1}}{1+e^{\beta_1}}
+(n_{1,0}+n_{1,1})\frac{e^{\beta_1+\beta_2}}{1+e^{\beta_1+\beta_2}}\tag5
$$
Comment: Thank you very much, that makes things clearer. If I were looking at a similar problem where the model had an intercept, what could I do instead of treating β and x as scalars at (1)? I'm assuming I'd have four cases to consider: n_(1,1), n_(1,0), n_(0,0), and n_(0,1).
Comment: @sk13 The MLE for the vector $\beta$ would involve the four possible $n$ values. See my edit.


Jenkins cannot access git

Question: After a crash of the Jenkins server, I cannot start my projects builds.
I get this weird message. Any clues?
<code>hudson.plugins.git.GitException: Command "git fetch --tags --progress origin +refs/heads/master:refs/remotes/origin/master --prune" returned status code 128:
stdout:
stderr: error: object file .git/objects/10/f103eb6e4590be766e67ca961e65f5c4e6836c is empty
error: object file .git/objects/10/f103eb6e4590be766e67ca961e65f5c4e6836c is empty
fatal: loose object 10f103eb6e4590be766e67ca961e65f5c4e6836c (stored in .git/objects/10/f103eb6e4590be766e67ca961e65f5c4e6836c) is corrupt
fatal: The remote end hung up unexpectedly
</code>
Answer: Had the same a few times.
Sometimes the answer of @"Mukesh M" may help - that is a decent approach. In other cases, the following approach helped me a few times.
First visit the /var/jenkins_home/caches folder. Delete the git-hashes. The next start of the job will retrieve everything from git again so the job will run smooth again. So omitting the git cache.
Answer: In my case I did following
Select Workspace and click on Wipe Out Current Workspace. This will delete your workspace.
Now just start new build and it will work.

Jenkins cannot access git


Show that if $w^3=1$, then $1+w+w^2=0$

Question:
Find the cube root of unity. Hence, show that if $w^3=1$, then
  $1+w+w^2=0$.

The cube root of unity is $1, -\frac{1}{2}+\frac{\sqrt{3}}{2}$ and $ -\frac{1}{2}-\frac{\sqrt{3}}{2}$. If $w^3=1$ then $w^3-1=0 \implies (w-1)(1+w+w^2)=0$
. The task is to prove that the second bracket is zero but we will only be sure that the second bracket is zero if the first is not zero, right? I think there is some assumption here that $w\ne1$ that I'm missing but I think that because $w^3=1$, $w$ can be any of the three roots of unity including $1$.
Comment: Yes, but it should have been stated explicitly.
Comment: @HaraldHanche-Olsen The world is never perfect.
Comment: "Find the primitive cubes root of unity". This is what was meant,
Comment: That's because the first bracket is zero for 1, so you can naturally assume w \ne 1$$ for the remainder of the proof
Answer: The conditional is clearly not true for $w=1$. The hypothesis holds ($1^3=1$), but the conclusion does not ($1+1+1^2 \neq 0$). Therefore, you have to assume that $w \neq 1$ in order to conclude the proof.

Show that if $w^3=1$, then $1+w+w^2=0$


hex to int 64 signed on php

Question: how convert hex A67BFE427CBDC58F to int 64 signed -6450282479763995249?
function bchexdec($hex) {
 if(strlen($hex) == 1) {
     return hexdec($hex);
 } else {
     $remain = substr($hex, 0, -1);
     $last = substr($hex, -1);
     $x = bcadd(bcmul(16, bchexdec($remain)), hexdec($last));
     return $x;
 }

bchexdec('A67BFE427CBDC58F') == 11996461593945556367.
This correct, but without sign((
how convert unsigned to signed?
PHP 5.3+; PHP_INT_SIZE == 4
Answer: if(bccomp($x, bcpow(2, 63)) >= 0) {
    $x = bcsub($x, bcpow(2, 64);
}

Comment: i use dirty hack:
if( bccomp($x, '9223372036854775808') == 1 )
$x = bcsub( $x, bcadd('9223372036854775808', '9223372036854775808') );

^__^
Comment: Hm, I think that using `bcpow` to get your constants is a bit more readable. Also, note that `9223372036854775808` should be converted to a negative value (`-9223372036854775808`), so that's why I used `>=` and not `>`.

hex to int 64 signed on php


MacOS PostScript Typ 1 fonts are 0 bytes after compressing with Python make_archiv

Question: I have a bunch of old Mac PostScript Typ 1 fonts that I want to compress in a zip file.
After compressing the folder with the fonts in it I uncompress the zip-File and all Fonts inside show 0 bytes and are no longer usable.
They look like this, before compression:

And like this, after compression:

My Code:
shutil.make_archive(ordner, 'zip', ordner)

Compressing the font-directory with the nativ MacOS archive program does not damage the fonts.
Update: I tried to compress my files with the original Unix-Tool over the command line (Terminal). With this code:
zip -r -X compressed_directory.zip directory_to_be_compressed/

I get the same broken result.
So I think I run into a problem that lies on a deeper level of Mac OS.
Update: As suggested by benwiggy I tried the following, without the -X flag. Same result:
 zip -r compressed_directory.zip directory_to_be_compressed/

Answer: Old Type 1 PostScript fonts use the MacOS Resource fork to store their data. This part of the filesystem isn't always handled well by Unix tools, unless they are explicitly written to cope with Mac resource forks.
The bundled zip utility in the MacOs CLI should include resource forks by default (since 10.3). It's possible the python util doesn't access the Mac-friendly utility.
Your zip command uses the -X flag, which deliberately excludes extended file attributes and other things, which probably includes resource forks.
Comment: Thank you, you're answer let me think and do some google work and came up with this excellent article: https://blog.jay2k1.com/2010/02/03/why-macs-may-have-trouble-with-fonts-from-smb-shares/ I think I have some issues with the resource fork that will not be included in the zip file with the unix or python tool. I have to do more search and will tell you if I found a solution.
Answer: After further research on old MacOS Resource Forks and a lot of testing, I found no way to include the resource fork of old MacOS Post Script Type 1 fonts in to a .zip File without using the native "Archiv Utility" or some other third party tools like Keka. The Python shutil.make_archiv() command does not include the resource fork for this type of file, neither does it the Unix Command Line tool zip.
I found some usefull information on this topic on Xhalees's blog (very nicely and comprehensively explained): http://xahlee.info/UnixResource_dir/macosx.html
The solution I came up with is to call the MacOS Terminal ditto command inside Python with the os module and let do it the work.
import os
os.system("ditto -ck --rsrc --keepParent directory_to_zip zipped_file.zip")


Pipes keep freezing

Question: Edited to add pics.
I live in an old home, built in 1919.
At some point before I bought the home, there was an addition that added a bathroom and three seasons porch.
The original foundation is stone, but the addition is block and has a dirt floor in part of it.
The addition part of the home is poorly insulated or not insulated at all.
There are pipes that run into the bathroom, from the addition - the sink, toilet and shower.
The lines to the sink and supply to the toilet occasionally freeze. The shower never freezes and the toilet can always flush, but sometimes will not refill.
We've put fiverglass insulation in the floor joists in that part of the addition and sprayed foam where the pipe enters the home in the block foundation.
There's a dirt-floor crawlspace in this section of the basement, and I've lined that with Astrofoil, in an attempt to hold heat in the space.
We're considering wrapping the pipes with insulating foam; Will this even help? Is there a better plan?
Comment: Have you thought through the heat path here? By insulating the floor joists you've _reduced_ the amount of heat that gets to the pipes (I assume--we don't have much info here). Maybe revise to explain the location of the insulation and the pipes in more detail. Ultimately it comes down to keeping the pipes _inside_ the building envelope, not outside it.
Comment: Or heating the pipes themselves. I've got heat tape wrapped around the pipes at greatest rush, plugged in much of the winter...
Comment: @JimStewart yeah, we haven't had any leaking or bursting.

The pipes are Pex tubing. Maybe some foam will be enough!
Comment: You want the pipes to be in the warm house air.  Pipes in outside walls are bad, pipes under an insulated floor is bad.  If pipes must be in the cold, heated pipe tapes can help.
Comment: Insulation keeps in heat. No heat? Then insulation won't make a difference. There's some heat conductance along metal pipes, so your home's internal heat can keep insulated outdoor pipe thawed to an extent, but I'm thinking of an insulated hose bib cover, not even a couple feet of pipe. This area sounds uncomfortable during cold months. Can you add a water shut off for this area during the cold?
Comment: Sorry for not being clear.

https://imgur.io/a/YwSRNzZ

This is the section of basement under the porch and the bathroom.

The three seasons porch is not insulated.

We tried to use a space heater in the past, to heat the space, but that's not a viable solution long term.
Comment: So these pipes freeze and stop water flow but do not split and start leaking? What type of pipes are these? What material? If they are not splitting from freezing with water inside, then they might be just barely freezing. In that case simply covering the pipes with insulating foam might be sufficient.  Putting foil along the (in)sides of the concrete block foundation would definitely hold heat in, but laying foil on the ground under the pipes might reduce heat flow from the ground into the space.
Comment: Be careful about covering heat tape with insulation. Some types of tape put out so much heat per unit length they should not be covered with insulation. Other types ("heat trace"?) could be so low in power that they are designed to be covered.
Comment: Insulating something in an unconditioned space only *delays* the "something" achieving ambient temperature.
Comment: I would simply add a small desktop or even USB fan to the opening of the crawlspace, so as to keep that space closer to the temp of the rest of the basement. Works great for edge cases and uses a lot less power than heat tape.
Comment: @dandavis lol
Answer: To fix the issue, install heat trace to the water lines (both hot and cold) and then add pipe insulation to keep the added heat in. There are many types, but the simplest option is to measure out the length that you need and buy the appropriate length 'automatic cable kit' from a box store. You can run more than one if needed and you can unplug them when it's the warm season.
Answer: You can install a hot water recirculating pump under the bathroom sink.
These are available as a kit containing everything you need: a near-silent pump, a thermostatic valve and a pair of hoses to connect to your shut-off valves under the sink.
The pump runs continuously, or you can plug it in / switch it on only when the temperature drops below freezing. I don't recommend that you use a timer because outdoor temperature doesn't run on a timer.
The way it works is that the thermostatic valve provides a path for hot water to return to your water heater via the cold water pipes, but only when the valve's temperature falls below 90F. When you first turn it on, the pump will force hot water into the cold water pipe continuously. The crossover valve will gradually warm up, and as soon as the valve reaches 90F, the valve will close and there will be no more flow.
Eventually, the valve will cool off because there is no hot water flow. When the valve detects the temperature drop, it will open slightly and pass a little more hot water into the cold water pipe until the valve is once again at 90F.
This system doesn't waste any water down the drain. It simply circulates water inside your pipes. The system does use some energy keeping your pipes warm, and keeping the pipes in your walls warm is not free.
When in use, your hot water pipe that sometimes freezes will stay lukewarm inside the wall and your cold water pipe in the wall will be tepid but not icy cold. That's all you really need to prevent freezing.
You can turn the device off in the spring to save energy, or you can leave it running if you become accustomed to instant warm water.
Comment: Thanks, I'll check that out.

Is there something similar I could install for the toilet?
Comment: @Kael Since both the sink supply and toilet supply were freezing, it's likely that they are getting their cold water from the same pipe. The device under the sink will keep that pipe from freezing for its entire length. So unless the pipe run from that now-tepid pipe is long or it passes through an extra frigid area, the one device should prevent freezing for both fixtures.
Comment: Thanks, I'll definitely check it out. Unfortunately, we'll have to wait to see if it works
Comment: @Kael Fair enough, but I can tell you that it works at my house. The previous owner built a second floor and sent water lines and hydronic heating lines through an unheated attic space for a short distance. They all froze up twice my first winter here. Fortunately the lines are PEX so no damage. The hydronic was a whole 'nother project, but bottom line is no more frozen pipes.

Pipes keep freezing


Find the limit $\lim_{n \to \infty} \frac {2n^2+10n+5}{n^2}$ and prove it.

Question: Find $\lim_{n \to \infty} \frac {2n^2+10n+5}{n^2}$.
I claim that $\lim_{n \to \infty} \frac {2n^2+10n+5}{n^2}=2$. To prove this, for given $\varepsilon >0$, I have to find $M\in N$ such that $|\frac {2n^2+10n+5}{n^2}-2|<\varepsilon$ for $n \ge M$.
By Archimedean property, we can find $M \in N$ such that $\frac {15}M<\varepsilon$, and note that $n\ge M \rightarrow \frac 1n \le \frac 1M \rightarrow \frac {15}n \le \frac {15}M$.
Then, for $n \ge M$, we have that $|\frac {2n^2+10n+5}{n^2}-2|=|\frac {10n+5}{n^2}| < |\frac {15n}{n^2}|$ (since $n \ge M \in N$) $<\frac {15}n\le \frac {15}M<\varepsilon$.
Therefore, by definition of convergence, $\lim_{n \to \infty} \frac {2n^2+10n+5}{n^2}=2$.
Should I say $M\in Z^+$ (because I am worried about the case where $M=0$)? Can you find any mistakes in this proof?
Thank you in advance.
Comment: Your proof is fine.
Answer: Your proof is fine, to simplify note that
$$\frac {2n^2+10n+5}{n^2}=2+\frac{10}{n}+\frac5{n^2}$$
then it suffices to prove that $\frac1n \to 0$.
Comment: @Student That's not the topic where I'm most confident but it seems a nice solution to me! Maybe you should write it in mathjax to encourage more answers! Or as an alternative you could give a small bounty to give more attention to that!
Answer: Your proof is correct, well done.
Some authors don't include $0$ in $\mathbb{N}$, but based on your question seems $\mathbb{N}=\{0,1,2,\dots\}$ for you.
I guess the definition of convergence of a sequence $(u_n)_{n\in\mathbb{N}}$ to $l\in\mathbb{R}$ that you have is this:
$$\forall\varepsilon>0,\exists M\in\mathbb{N},\forall n\ge M,|u_n-l|<\varepsilon.$$
Let $\varepsilon>0$ and $M\in\mathbb{N}$ (that exists) such that $$\forall n\ge M,|u_n-l|<\varepsilon.$$
Notice that, in particular, $$\forall n\ge M+1,|u_n-l|<\varepsilon$$ because $M+1>M$. So you can replace $M$ by $M+1$ or any larger integer. Therefore you can always choose $M$ to be positive. So you can safely have this as a definition:
$$\forall\varepsilon>0,\exists M\in\mathbb{Z}^+,\forall n\ge M,|u_n-l|<\varepsilon.$$
Answer: Another possibility: apply two times Cesàro-Stolz.
$$
\lim_{n\to\infty}\frac{2n^2 + 10n + 5}{n^2} =
\lim_{n\to\infty}\frac{((2(n+1)^2 + 10(n+1) + 5) - (2n^2 + 10n + 5)}{(n+1)^2 - n^2} =
\lim_{n\to\infty}\frac{4n + 12}{2n + 1} =
\lim_{n\to\infty}\frac{(4(n+1) + 12) -(4n + 12)}{(2(n+1) + 1) - (2n + 1)} =
\lim_{n\to\infty}\frac42 = 2.
$$


Retrieving all from all rows from jquery datatable

Question: I've a datatable, which is created dynamically. Number of rows differs from user to user. Some may create 2 rows, some may create 3 etc. For example, the table may look like this:
|     Category      |   User   |
|      Manager      |  Krishna |
| Assistant Manager |  Guru    |

They will be selected from a select dropdown. This is how I tried to retrieve all the data from the table when the submit button is clicked:
var noofrows = tabResources.data().count();
var data = tabResources.rows(0).data();
                alert(data);

In the alert, I get [object, object]. But, I don't know how to retrieve each value. How can I do that? This is the table:
tabResources = $("#tabResources").DataTable({
                "sDom":"t",
                ajax:{
                    "url":"../api/projectapi.php?action=getresourcebyprojectid",
                    "type":"GET",
                    "data":{"projectid": <?php echo $_GET ["projectid"]?>}
                },
                "destroy":true,
                "ordering":false,
                "columns":[

                           {"title":"Resource Category", "data":"resourcecategoryid","render":function(data, type, row){
                               return '<select class="form-control selectresourcecategoryid" name="resourcecategoryid[]" valueid=' + data + '></select>';
                            }},
                            {"title":"User", "data":"userid","render":function(data, type, row){
                                   return '<select class="form-control selectuserid" name="userid[]" valueid=' + data + '></select>';
                                }},
                                {"orderable":false, render: function ( data, type, row ) {
                                    return 'Remove';
                                    }
                                }
                ]
});

Answer: Checkout the snippet, does this solve your problem?

$(document).ready(function() {
    var data = [
       ['name1', 'position1', 'office1', 15],
       ['name2', 'position2', 'office2', 30]
    ];
    var table = $('#example').DataTable({
      data: data,
      columns: [
        {
          title: "Name"
        },{
          title: "Position"
        },{
          title: "Office"
        }
      ]
    });

    var data = table.data();
    for (var i = 0; i < data.length; i++) {
      console.log(data[i]);
    }

} );

<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet"/>


How to change the mouse pointer theme

Question:
Possible Duplicate:
How to change mouse cursor and theme?

How can I change mouse pointer theme in Ubuntu 11.10, as in previous versions of Ubuntu?
Comment: Do you mean changing the color? There are many mouse themes that you can download and install.
Comment: I mean how to change the theme of it not supported in Ubuntu 11.10
Answer: You can also select different mouse pointer color scheme with following command:
sudo update-alternatives --config x-cursor-theme

You should log out and log in again for the change to take effect.
Comment: Instead of login and logout, the following command worked for me too `compiz --replace &`
Answer: You can install additional mouse themes from the Ubuntu Software Center. Additionally, you can manually install new themes such as those from gnome-look.org by extracting the theme folders into /usr/share/icons/ or ~/.icons. (Source for manual installation)
Then, to actually use these themes, you'll need the GNOME Tweak Tool (click this link to install: GNOME Tweak Tool , or use sudo apt-get install gnome-tweak-tool in a terminal).
Next, you'll want to open the GNOME Tweak Tool (you can search for it in both Unity and GNOME Shell as "Advanced Settings"), then go to Theme > Cursor theme. Use the drop-down menu to select the cursor you want.
If you're running Unity, you may then have to run compiz --replace in a terminal or Alt+F2 prompt to make the changes take effect.
(Source)
Comment: good, But where to put the downloaded mouse theme(i mean the path or folder to put the theme in)
Comment: I don't have a section called "Theme". When I change my cursor under "Appearance -> Cursor", nothing happens!
Answer: It is possible to change the cursor to one that has been downloaded outside of the Software Centre - the method is similar to how it was done since Lucid. After downloading the mouse theme, extract the tar.gz file somewhere you can find it later. Next, you'll need superuser access to your filesystem - open a terminal (Ctrl + Alt + T) then enter

gksu nautilus

and press enter. Enter your password in the window that pops up. You now have root access to your filesystem so be careful. Navigate to /usr/share/icons/ Keep this location open, but open up another window or tab and go to the directory where you extracted your mouse theme. Copy the theme folder into /usr/share/icons/ after which you'll be able to see your new theme show up in the Gnome Tweak tool. But we aren't quite finished yet - open the terminal and enter

gksu gedit /usr/share/icons/default/index.theme

and change the name after "Inherits=" to the name of your new theme. This makes it the default cursor theme for the entire system and it will be the cursor seen in the login screen.
So, although not ideal and not as simple as it once was (think pre-Lucid), it still is possible to install cursor themes in Oneiric.
Edit: You'll likely need to reboot (or logout) to see the changes.
Comment: will give a try and tell you
Answer: You can use Gnome Tweak Tool (sudo apt-get install gnome-tweak-tool) to change the mouse theme in Ubuntu 11.10
Comment: But where to put the downloaded mouse theme(i mean the path or folder to put the theme in)

How to change the mouse pointer theme


What does git mean "wrong number of arguments"?

Question: I wanted to get all the git config entries, so I glanced over the options and found --get-all, but it gave:
C:\>git config --global --get-all
error: wrong number of arguments
usage: git config [<options>]

It doesn't seem to specify a number of arguments, it just says [<options>].
And I don't know what other options it would need.
Comment: @jonrsharpe I'm somewhere between beginner and intermediate at git and I find the message opaque. `--get-all             get all values: key [value-regex]` It's not all that clear what `key` means unless you already know how config organizes keys.  Fortunately  `-l, --list` is not too much farther down and does what `--get-all` sounds like it might do (but doesn't).
Comment: It means that's the... wrong number of arguments. As the help text shows, if you use `--get-all` it expects a `key` and, optionally, a `value-regex`. Did you look at [the docs](https://git-scm.com/docs/git-config#git-config---get-all)?
Comment: Since your own answer doesn't answer the question you asked, you must have a different question in mind. As it stands, this question is unlikely to help anyone else, but you could edit it to reflect what you really want (that is, so your answer addresses the question actually asked, rather than the one in your head no-one else can see)
Comment: @jonrsharpe Is there a policy on not including meta information (context) in a question? I'm fine with leaving it out if there is, but it doesn't feel nice to have part of what you wrote doubly deleted without explanation.
Comment: Both my question and answer were edited, removing context. And my answer did answer my question; it's just that my question was poorly formed.
Comment: I've updated the question and answer so that the problem is clear.
Answer: For viewing the entire config, the correct argument is --list, not --get-all
(or you may also want --edit).
The "number of arguments" is of arguments to the argument (or so to speak), subarguments;
it's just a really vague error message.
Comment: This isn't really an answer to the question. Perhaps you should include the fact that you were trying to list all global configuration options in it? If someone *is* trying to use `--get-all`, this doesn't help them at all.
Comment: `git config --local --list` was exactly what I needed.
Comment: @jonrsharpe I've updated it (and more importantly the question); the problem scenario should be clear now
Answer: You have set it
git config --global --get-all

but as you can see in the help section right below

Action
    --get                 get value: name [value-regex]
    --get-all             get all values: key [value-regex]

So that means you are missing the key argument and optionally the value-regex argument.
You can read more about it in the docs.
Answer: Only use double quotes.
Example:
git config --global --add safe.directory "D:/WORK/Angular Projects/website/panelapp"


How to return random string from a non binary tree in java

Question: I have a method to return a String from a non binary tree but its throwing "IllegalArguementException" What am I doing wrong.
 public String getRandomWord(Node node, String word){
      Random randomGenerator = new Random();
      randomInt = 0;
      current = node;
      if(node.getChildren() == null){
           //System.out.println(node.getData());
           return word;
      }
      while(node.getChildren() != null){
           randomInt = randomGenerator.nextInt(node.getChildren().size());
           randomInt = randomGenerator.nextInt(2);
           current = node.getChildren().get(randomInt);
           word += current.getData();
           //System.out.print(current.getData()+"\n");
           getRandomWord(current, word);
      }
      return word;
}

 Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
 at java.util.ArrayList.rangeCheck(ArrayList.java:604)
 at java.util.ArrayList.get(ArrayList.java:382)
 at treeapp.Tree.getRandomWord(Tree.java:71)
 at treeapp.Tree.getRandomWord(Tree.java:74)
 at treeapp.Tree.getRandomWord(Tree.java:74)
 at treeapp.Tree.getRandomWord(Tree.java:74)
 at treeapp.Tree.getRandomWord(Tree.java:74)
 at treeapp.Tree.getRandomWord(Tree.java:74)
 at treeapp.Tree.getRandomWord(Tree.java:74)
 at treeapp.Main.main(Main.java:34)
 Java Result: 1

Comment: The stracktrace is always helpful. Include it next time please.
Comment: I suspect `node.getChildren().size()` is returning something non-positive (perhaps 0?).
Comment: Yes but why? What's the way out ?
Comment: When `node.getChildren()` is empty, you receive that exception as a result of trying to access child `0` of the list when no children exist.  Maybe you mean to check `node.getChildren().isEmpty()`, rather than `node.getChildren() != null`?
Comment: I caught the exception and everything seems OK :) Thanks
Comment: In most cases, it's better to modify code to avoid an exception like this rather than to simply catch it.  I recommend you make such modifications, as they seem as if they'll be fairly simple in this case, since the exception is only caused when the children list is empty.
Answer: I think you meant to delete this line, which will overwrite the previous random number and assumes that there are always 2 children.
randomInt = randomGenerator.nextInt(2);

Also, I'm not sure exactly what the method is supposed to do, but you may want to change the while to an if if I understand it correctly.
Finally, change if(node.getChildren() == null) to if(node.getChildren().size()==0). When the node has no children, getChildren() returns an empty list, not null.


What is this emacs configuration doing?

Question: (setq backup-directory-alist `(("." . "~/.saves")))

I know that it's setting the directory where backup files are saved, but I don't understand specifically what the `(("." . "~/.saves")) part is doing. Specifically:

What is the ` mark doing? (also, does that thing have a special googleable name?)
Why does this require double parenthesis? It's like this in the default settings, not just in my configuration file.
It seems like the solitary . inside may be some kind of substitution operator and I notice that I have another similar line with a comma instead. What is the operation that these things are doing?

My google-fu has failed in the face of figuring out what punctuation marks do in lisp and I'm too lazy to work through the emacs lisp tutorial.
Answer: The documentation for backup-directory-alist does explain most of this. The value is an association list where each key is a regular expression. The simple regex "." matches every non-empty string, so it applies to every directory name.
An association list is read from beginning to end, and it's easy in Lisp to prepend a new association:
(setq backup-directory-alist
      (cons '("\\`/tmp/" . "/tmp/saves")
      backup-directory-alist))

... or more succinctly
(push '("\\`/tmp/" . "/tmp/saves") backup-directory-alist)

... to end up with a list with two settings: a specific one for paths matching the regex "\\`/tmp/" in front if the generic one for all other paths.
You wrote a backquote but the proper way to quote the expression is with a regular quote.
The dot between the alist key and the value is a cons, a primitive for creating lists. As a practical matter, a cons is simpler than a list, so you can get the value with a straight cdr, rather than the conceptually more complex cadr (the car of the cdr).
I don't think you can have a comma in that position (though comma has a use in backquotes).
Comment: Another term is quasiquote.  I once saw an explanation that made a lot of sense to me.  The default in lisp is for things to be unquoted, and the `'` quotes them.  The quasiquote `\`` flips this around, so that things are quoted by default and unquoted with `,`.
Comment: Thanks. This was helpful, especially with the edited expansion.

What is this emacs configuration doing?


how to get street level information using Google Map API

Question: I am new to Google Map API and i want to integrate Google Map API with my         application.I developed code for address from the postcode but its give me only one record but i have checked on other site who provide this kind of facility. They  will get 46 records,Please help me to get out of this.For demo purpose i am using 'IP27 0HP' this as a postcode which is in  UK. I have searched lots of things but even i am not finding in Google API documentation which return me county, town, street and address line 1, address line 2 etc..
Comment: Are you saying you want the 46 postal addresses for which `IP27 0HP` is the postcode?
Comment: 'IP27 0HP' is a postcode, Actually i am getting response from Google Map API : like Brandon, Suffolk IP27 0HP, UK but i need  address list from 1 to 46 Walton Way,Brandon, Suffolk IP27 0HP, UK, here is a link you enter this postcode and find the result :http://www.simply-postcode-lookup.com/for_web.htm
Answer: Google cannot provide multiple address information for a single postcode.
The Royal Mail own postcode data, and while they have been forced to release geographic information (so Google can provide a location given a postcode), address data is not released and not available from any other provider.
Your example site has access to PAF (the Royal Mail Postal Address File) which contains this data. It's not free, which is why that site charges. They have to cover their own licence cost.
Comment: Thanks you very much. Since last fives days i am trying to get this response but i was fail but you gave a clear guidance.


Why am i getting invalid syntax when adding a def?

Question: import pygame
import math

#initialise pygame
pygame.init()

#game window
WINDOW_WIDTH = 1200
WINDOW_HEIGHT = 750

#create game window
win = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('Castle Defender')

clock = pygame.time.Clock()
FPS = 60

#load images
background_img = pygame.image.load('Animations/BG.png').convert_alpha()
background = pygame.transform.scale(background_img,(1200,750))

castle_img = pygame.image.load('Animations/Castle.png').convert_alpha()

bullet_img = pygame.image.load('Animations/SmallBullet.png').convert_alpha()
b_w = bullet_img.get_width()
b_h = bullet_img.get_height()
bullet_img = pygame.transform.scale(bullet_img, (int(b_w * 0.075), int(b_h * 0.075)))

WHITE =(255,255,255)

#Castle class
class Castle():
    def __init__(self, image, x, y, scale):
        self.health = 1000
        self.max_health = self.health

        width = image.get_width()
        height = image.get_height()

        self.image = pygame.transform.scale(image, (int(width * scale), int(height * scale)))
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

    def shoot(self):
        pos = pygame.mouse.get_pos()
        x_dist = pos[0] - self.rect.midleft[0]
        y_dist = -(pos[1] - self.rect.midleft[1])
        self.angle = math.degrees(math.atan2(y_dist, x_dist))
        #mouseclick
        if pygame.mouse.get_pressed()[0] and self.fired == False:
            self.fired = True
            bullet = Bullet(bullet_img, self.rect.right[0], self.rect.right[1], self.angle)
            bullet_group.add(bullet)
        #reset mouseclick
        if pygame.mouse.get_pressed()[0] == False:
            self.fired = False

#Method
    def draw(self):
        self.image = self.image

        win.blit(self.image, self.rect)

class Bullet(pygame.sprite.Sprite):
    def __init__(self, image, x, y, angle):
        pygame.sprite.Sprite.__init__(self)
        self.image = image
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.angle = math.radians(angle)
        self.speed = 10
        self.dx = math.cos(self.angle) * self.speed
        self.dy = -(math.sin(self.angle) * self.speed)

    def update(self):
        #check if bullet has gone off the screen
        if self.rect.right < 0 or self.rect.left > SCREEN_WIDTH or self.rect.bottom < 0 or self.rect.top > SCREEN_HEIGHT:
            self.kill()

        #move bullet
        self.rect.x += self.dx
        self.rect.y += self.dy

castle = Castle(castle_img, WINDOW_WIDTH - 1350, WINDOW_HEIGHT - 400, 0.7)

bullet_group = pygame.sprite.Group()

run = True
while run:

    clock.tick(FPS)

    win.blit(background, (0, 0))

    castle.draw()
    castle.shoot()

    #bullet drawing
    bullet_group.update()
    bullet_group.draw(win)
    print(len(bullet_group))

    #event handler
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    #update display window
    pygame.display.update()

pygame.quit()

I am trying to see the line from my base and my mouse. However I get an error of the following
bullet = Bullet(bullet_img, self.rect.right[0], self.rect.right[1], self.angle)

(My end goal is for bullets to come out of the castle and i am relatively new to coding and this will be my first project) . Also i keep getting an error  when trying to submit this saying it is mostly code so the parenthisis was me rambling on
Comment: Are you sure you closed all the parentheses on the previous line?  That's usually what it is.
Comment: unfortunately not as I have amended the code and added new things but still didn't change an error code of popping up
Answer: The issue the code is trying to use self.rect.right as if it was a python list.  But self.rect.right is an integer.
self.rect.right[0]
self.rect.right[1]

Probably this should be self.rect.right and self.rect.top (since it deals with the y-dimension).
Then you also need to correct references to SCREEN_WIDTH and SCREEN_HEIGHT.  It looks like these should be WINDOW_ etc.
After these changes are made, your program does not exit with an error when the mouse is clicked.


Is it possible to build a Google Map showing nothing but overlays?

Question: I have an odd question: would it be possible to build a page containing a Google Map that doesn't actually display the map, i.e. the only things shown in the  are the overlays and markers you've created?
I'm looking for a way to build a map that appears empty except for the content that I overlay on top of it.
Answer: No. When you add markers and overlays, they won't show up until you add them to the map. The map can show different features, but you can't just have a blank div with markers and overlays. Why do you see this need?
Answer: You may use the "styled map" features and create a blank map like:
<code>var stylez05 = [ {
  featureType: "all",
  elementType: "all",
  stylers: [{ visibility: "off" }]
}];
</code>
http://code.google.com/intl/el/apis/maps/documentation/javascript/examples/maptype-styled-simple.html is an example of how to apply styles to a map.