text:
Q: ShapeDrawable and LinearLayout not working as expected
My code:
<LinearLayout
       android:layout_width="match_parent"
       android:layout_height="30dp"
       android:background="@drawable/myCustomShapeDrawable"
       android:orientation="horizontal" >

            <View
                android:layout_height="match_parent"
                android:layout_width="0.4px"
                android:layout_gravity="center"
                android:background="#cccccc"/>
</LinearLayout>

As you can see, the first problem is that the line's height is not matching the LinearLayout's height, despite having "match_parent" at its height attribute.
The second problem is that it doesnt align itself in the center of the LinearLayout.

A: This below code will work according to the requirement:
 <LinearLayout
           android:layout_width="match_parent"
           android:layout_height="30dp"
           android:layout_gravity="center"
           android:gravity="center"
           android:background="@drawable/myCustomShapeDrawable"
           android:orientation="horizontal" >

                <View
                    android:layout_height="match_parent"
                    android:layout_width="0.4px"
                    android:layout_gravity="center"
                    android:background="#cccccc"/>
    </LinearLayout>


text:
Q: Two types of user accounts with django user accounts I'm creating a web application and I'd like to split the sign-up/registration process between
A. Individuals
and
B. Employers
where each sign-up form contains similar elements but are also different.
What's the best approach to doing this? Inheritance?

A: Concentrating only on forms + views section ( assuming you are done with the models).
Since all the fields are same for both the entities. You can differentiate when you create the object of the signup form in views method.
def employer_signup(request):
    form = CommonSignupForm(request.Post or None)
    # do something with it

def individual_signup(request):
    form = CommonSignupForm(request.Post or None)
    # do something else with it

Now, i assume, max you have to do in this is to set user_type of the user signing up. Following code should be in each method.
user = form.save(commit=false)
user.user_type = 'E'  # depends what tags you are using
user.save()

redpajama_set_name: RedPajamaStackExchange


text:
Q: SELECT list is not in GROUP BY clause and contains nonaggregated column 'conteggio.data' I have this query :
$sql_errori_doppie="select doc_doppio,count(*) as doppie,data
from(select data,doc_doppio,count(*) as num_lezioni_doppie
from(SELECT cou_id, DATE_FORMAT(FROM_UNIXTIME(cou_ts_1), '%d-%m-%Y %h:%i') as data ,cou_ins_1 as doc_doppio
FROM courses where cou_type='mot' and cou_ins_1<>0
and (substr(DATE_FORMAT(FROM_UNIXTIME(cou_ts_1), '%Y-%d-%m'),1,4))=".$q. "
UNION ALL
SELECT cou_id, DATE_FORMAT(FROM_UNIXTIME(cou_ts_2), '%d-%m-%Y %h:%i'),cou_ins_2 FROM courses where cou_type='mot'
and cou_ins_2<>0 and (substr(DATE_FORMAT(FROM_UNIXTIME(cou_ts_1), '%Y-%d-%m'),1,4))=".$q. "
UNION ALL
SELECT cou_id, DATE_FORMAT(FROM_UNIXTIME(cou_ts_3), '%d-%m-%Y %h:%i'),cou_ins_3 FROM courses where cou_type='mot'
and cou_ins_3<>0 and (substr(DATE_FORMAT(FROM_UNIXTIME(cou_ts_1), '%Y-%d-%m'),1,4))=".$q. "
)
as da group by data,doc_doppio
having num_lezioni_doppie>1
)
as conteggio group by doc_doppio;";

When I try to do it I Have this message:

SELECT list is not in GROUP BY clause and contains nonaggregated
  column 'conteggio.data' which is not functionally dependent on columns
  in GROUP BY clause; this is incompatible with
  sql_mode=only_full_group_by

How to change the query or the only_full_group_by parameter?


text:
Q: Query to see if row exists based on data without selecting fields So i know how to check a row exists from a set of data. But a lot of examples i find entails selecting a row and bunch of fields - something i don't need in this case.
In my case i just need to know it exists. I was wondering if there is a way to check a row exists without selecting/getting the row since thats some what redundant data ?
If not i will stick to using my SELECT id approach but wanted to see if i had missed a better approach just to ping the existence of a row.
Currently i am doing:
SELECT uid FROM users WHERE sessionID = ? AND uid = ?

Then i am checking if row count is == 1 afterwards. But i am still needlessly getting uid which i already technically have. It seems inefficient. So perhaps there is a better way built into mySQL?

A: You can do:
select (exists (select 1 from t) ) as exists_flag

This returns 1 if the row exists or 0 if no row exists.  You can add a where clause to the subquery if you want a particular row.


text:
Q: Having ModelBuilder auto-detect work-space environment? I have a model that I'm attempting to edit, that is used company wide. We have a structured folder template that all projects conform to. The model takes information from the personal geodatabase and returns a materials list in an excel file.
The tool is for non Arc users, and choosing file path for input and output locations is causing issues.
I need the model to automatically default to whatever database is open, and have it export the excel file to the corresponding folder location for that project.
I've been trying to figure this out on my own and had no luck.

A: I don't believe what you are asking is possible with a model. It would certainly be possible with a python script or script toolbox as you can validate a parameter, which you can't do with a model.
If the bulk of your workflow is a model then you could use the calculate value tool to pull out the workspace of say the first layer in the MXD but then you would not be able to expose the parameter as you currently have, so it would be a parameter-less model.
You can use this to return a workspace from the first valid layer and use the output of the Calculate Value tool in an inline substitution.

Python code is:
import arcpy
def getWorkspace():
  mxd = arcpy.mapping.MapDocument("CURRENT")
  df = arcpy.mapping.ListDataFrames(mxd)[0]
  lstLayers = arcpy.mapping.ListLayers(mxd, "", df)
  ws = None
  for aLyr in lstLayers:
    if aLyr.supports("WORKSPACEPATH"):
      ws = aLyr.workspacePath
      break
  return ws


text:
Q: POST jQuery array to Django I'm trying to POST a jQuery array of simple numbers to Django, and I really can't make it work. I need a little help on this. I'm getting an Http 500 with the following error:
Internal Server Error: /edit_lists/
Traceback (most recent call last):
  File "/home/jabez/.virtualenvs/hackernews/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in get_response
    response = middleware_method(request, response)
  File "/home/jabez/.virtualenvs/hackernews/local/lib/python2.7/site-packages/django/middleware/common.py", line 106, in process_response
    if response.status_code == 404:
AttributeError: 'list' object has no attribute 'status_code'

Here's my code:
JavaScript
    $('.btn-group').find('#mark_as_done').on('click', function() {
    var tasks = grab_selected();

    $.ajax({
        type: 'POST',
        url: '/edit_lists/',
        data: {'tasks': tasks},
    });
});

function grab_selected() {
    var tasks = [];
    $('input:checked').each(function() {
        tasks.push(this.id);
    });
    return tasks;
}

views.py
def edit_lists(request):
tasks = request.POST.getlist('tasks')
return tasks

urls.py
url(r'^edit_lists/$', 'todo.views.edit_lists', name='edit_lists')

A: You can try to use tasks[] instead of tasks as parameter when sending via ajax. Example:
$('.btn-group').find('#mark_as_done').on('click', function() {
    var tasks = grab_selected();

    $.ajax({
        type: 'POST',
        url: '/edit_lists/',
        data: {'tasks[]': tasks},
    });
});

Another thing is you are simply returning return tasks in edit_lists() view, you have return a HttpResponse instance or use shortcut like render:
from django.http import HttpResponse

def edit_lists(request):
    tasks = request.POST.getlist('tasks[]')
    return HttpResponse('Success')

Hope it helps,

A: You can try to use JSON.stringify() method instead of tasks as parameter when sending via Ajax.
Here's the array data on my consol

Then send Array data by ajax
$.ajax({
     type: "POST",
     url: "/user/Survey-Design/",
     headers: {
         'Authorization': "Token " + localStorage.access_token
     },
     data: {
         'arr': JSON.stringify(arr)
     },
     success: function(result) {
         alert('Data Has been saved')
     }
 });

In views.py:
 def create(self,request):
     array_data = request.POST['arr']
     data = json.loads(array_data)
     print(data)
     return HttpResponse('Success')

Finally, show print(data) on terminal


text:
Q: Mybatis delete returns negative value. Why is that? I have the following mybatis mapper and interface definitions:
<delete id="deleteTestSet">
        DELETE FROM projects_test_sets
         WHERE project_id = #{testSet.project.id}
           AND id = #{testSet.id}
    </delete>

and
interface ITestSetRepository {

    Integer deleteTestSet(@Param("testSet") TestSet testSet);

}

When calling from the code:
  Integer result = testSetRepository.deleteTestSet(testSet);

I get the result value -2147482646 being returned, no matter if the delete query deletes 0, 1 or multiple entries.
Any idea why is this ?
The DB is MySQL 5.7.19-17
Mybatis version: 3.4.6
Thanks

A: When mybatis BATCH executor is used operations are not executed immediately. Mybatis only records the fact that such operation should be executed and their execution is delayed. That's why the mapper method cannot return the actual number of records affected. It always returns hardcoded negative constant instead.
In order to get the actual number of affected rows you can force the batch execution using the method annotated with @Flush:
@Flush
List<BatchResult> flush();

It would return the result for every operation executed in a batch so far.


text:
Q: Plotting estimated HR from coxph object with time-dependent coefficient and splines I want to plot the estimated hazard ratio as a function of time in the case of a coxph model with a time-dependent coefficient that is based on a spline term. I created the time-dependent coefficient using function tt, analogous to this example that comes straight from ?coxph:
# Fit a time transform model using current age
cox = coxph(Surv(time, status) ~ ph.ecog + tt(age), data=lung,
     tt=function(x,t,...) pspline(x + t/365.25))

Calling survfit(cox) results in an error that survfit does not understand models with a tt term (as described in 2011 by Terry Therneau).
You can extract the linear predictor using cox$linear.predictors, but I would need to somehow extract ages and less trivially, times to go with each. Because tt splits the dataset on event times, I can't just match up the columns of the input dataframe with the coxph output. Additionally, I really would like to plot the estimated function itself, not just the predictions for the observed data points.
There is a related question involving splines here, but it does not involve tt.
Edit (7/7)
I'm still stuck on this. I've been looking in depth at this object:
spline.obj = pspline(lung$age)
str(spline.obj)

# something that looks very useful, but I am not sure what it is
# cbase appears to be the cardinal knots
attr(spline.obj, "printfun")

function (coef, var, var2, df, history, cbase = c(43.3, 47.6,
51.9, 56.2, 60.5, 64.8, 69.1, 73.4, 77.7, 82, 86.3, 90.6))
{
    test1 <- coxph.wtest(var, coef)$test
    xmat <- cbind(1, cbase)
    xsig <- coxph.wtest(var, xmat)$solve
    cmat <- coxph.wtest(t(xmat) %*% xsig, t(xsig))$solve[2, ]
    linear <- sum(cmat * coef)
    lvar1 <- c(cmat %*% var %*% cmat)
    lvar2 <- c(cmat %*% var2 %*% cmat)
    test2 <- linear^2/lvar1
    cmat <- rbind(c(linear, sqrt(lvar1), sqrt(lvar2), test2,
        1, 1 - pchisq(test2, 1)), c(NA, NA, NA, test1 - test2,
        df - 1, 1 - pchisq(test1 - test2, max(0.5, df - 1))))
    dimnames(cmat) <- list(c("linear", "nonlin"), NULL)
    nn <- nrow(history$thetas)
    if (length(nn))
        theta <- history$thetas[nn, 1]
    else theta <- history$theta
    list(coef = cmat, history = paste("Theta=", format(theta)))
}

So, I have the knots, but I am still not sure how to combine the coxph coefficients with the knots in order to actually plot the function. Any leads much appreciated.

A: I think what you need can be generated by generating an input matrix using pspline and matrix-multiplying this by the relevant coefficients from the coxph output. To get the HR, you then need to take the exponent.
i.e.
output <- data.frame(Age = seq(min(lung$age) + min(lung$time) / 365.25,
                               max(lung$age + lung$time / 365.25),
                               0.01))
output$HR <- exp(pspline(output$Age) %*% cox$coefficients[-1] -
                 sum(cox$means[-1] * cox$coefficients[-1]))
library("ggplot2")
ggplot(output, aes(x = Age, y = HR)) + geom_line()

Note the age here is the age at the time of interest (i.e. the sum of the baseline age and the elapsed time since study entry). It has to use the range specified to match with the parameters in the original model. It could also be calculated using the x output from using x = TRUE as shown:
cox <- coxph(Surv(time, status) ~ ph.ecog + tt(age), data=lung,
             tt=function(x,t,...) pspline(x + t/365.25), x = TRUE)
index <- as.numeric(unlist(lapply(strsplit(rownames(cox$x), "\\."), "[", 1)))
ages <- lung$age[index]
output2 <- data.frame(Age = ages + cox$y[, 1] / 365.25,
                      HR = exp(cox$x[, -1] %*% cox$coefficients[-1] -
                               sum(cox$means[-1] * cox$coefficients[-1])))


text:
Q: How to sort row data from Android sqlite database for a particular year in date field I am having below table on my android sqlite database.
My Date filed is TEXT;
ID   Name   Date
1    ABY    2014-12-01
2    RUBY   2015-01-10
3    AMY    2015-01-15
4    ROBEN  2014-10-25

I need to sort the result like in mysql
select * from Table where YEAR(DATE)='2015';

How can I get the above result in Andorid sqlite database?

A: I think you want to use the LIKE operand
SELECT * FROM table WHERE Date LIKE '2015%'
http://www.tutorialspoint.com/sqlite/sqlite_like_clause.htm
Edit for query:
String selectQuery = "SELECT id, name FROM table WHERE date like \'" + "2015" + "\'";
Cursor c = db.rawQuery(selectQuery, new String[] { fileNameOfDb });
if (c.moveToFirst()) {
    name = c.getString(c.getColumnIndex("name"));
}
c.close();


text:
Q: Python: Read list from file In my config.txt, I have something like this.
# Server
server = localhost:8080

# Credentials
username = admin
password = password

# Some list here
important_info = [
    {
         id: 1,
         meaning: something
    },
    {
         id: 2,
         meaning: something else
    }
]

# Another list here
not_that_important_info = [
    {
         id: 3,
         meaning: another
    }
]

# And another one
some_other_info = [
    a,
    b,
    c,
]

I want to read the file such that each line would be an element of a list except for lines that should be treated as a list. So far, I have this.
def get_params_from_file():
    list = []
    with open('config.txt') as file:
        for line in file:
            if not line.lstrip().startswith('#'):
                # Do something so that it would treat some multiple lines a single line if it contains a list
                list.append(line.rstrip());

    return filter(None, list)

Ofcourse, it doesn't work as expected yet. Is there a pythonic way to do this?
Expected output would be:
['server = localhost:8080', 'username = admin', 'password = password', 'important_info = [{id: 1, meaning: something},{id: 2, meaning: something else}]', ... ]


text:
Q: Why no code is executed after mainloop tkinter python I know what is the purpose of mainloop (or at least i think), also i know that code placed after mainloop can be executed using after(), but why is like that? Why is mainloop blocking it?

A: When you use .mainloop() method, you start a special loop used by Tkinter to check for events like keypresses and button presses. It functions like a forever while loop. Therefore, you can't run any code outside of the loop until either the window is closed by the user or is destroyed in the code.


text:
Q: running docker remotely on openvz I have a openvz vps which is centos 7 but with a 2.6 kernel. I know this is not compatible with docker. I have another KVM vps which has docker on it. Is there anyway to access docker in KVM remotely using my openvz vps? Basically I want my openvz box to be my dev machine and Ill deploy to KVM docker. What would be an ideal setup above?

A: You say the host has a 2.6.x kernel, but that covers a couple different releases.  I have made docker work in an openvz VPS on a host with 2.6.32 kernel (derived from RedHat el6) but it would probably not work for kernels 2.6.18 or 2.6.9 (you really should upgrade if you have 2.6.9 as that is based on RedHat el4 kernel, 2.6.18 should be fine until 3/2017).  You can find instructions to make it work with a compatible kernel at the openvz wiki.  WARNING: docker does not perform very well in this configuration (2.6.32 kernel, CentOS 7 VPS) as you do not get any of the fancy filesystem layering functionality since you are forced to use the "vfs" storage engine.  Each layer of the docker container will be a full copy of its underlying filesystem, grossly ballooning disk usage for images with lots of layers.
If you are not running a docker compatible kernel, you would not be able to run any of the docker tools at all, so your options are limited.  If you still want to develop docker containers on your VPS to move to your KVM, you could use chroot and yum/rpm to construct your container and make a ${docker_image}.tgz file on your VPS and then copy that to your KVM and import into docker.
Hope that helps.


text:
Q: About the HTTP Protocol I'm quite new to the HTTP Protocol, but I'm working on it in order to be able to automatically thought a C# Console Application create a new account on Twitter.
What I'm doing, is first doing a GET request in order to gather some data on the page (like the authenticity token for example) and then I'm posting my data to a specific URL designed to it. The URL I'm using for the GET operation is "https://www.twitter.com/signup/"
Then I do my POST operation, giving all the required headers (except the cookie, I don't know if the cookie is important or not for the process) and the formatted data of the account I want to create.
The problem is : when I start my program, first it doesn't create any account, and second the server answers me redirecting me back to www.twitter.com/account/new, it feels like I don't fill up the correct fields but I can't get any clue of what is actually really happening.
Here's my main code:
static void Main(string[] args)
        {
            // Set up data info
            string[] infos = SetUpAccountInfo();
            string parsedData= FormDataParsing(infos);

            StreamWriter myWriter = null;
            StreamReader myReader = null;
            CookieContainer cookies = new CookieContainer();

            HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(POSTSignUpURL);
            objRequest.Method = "POST";
            objRequest.Host = "twitter.com";
            objRequest.ProtocolVersion = HttpVersion.Version11;
            objRequest.ContentLength = machin.Length;
            objRequest.ContentType = "application/x-www-form-urlencoded";
            objRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            objRequest.Headers.Add("accept-encoding", "gzip,deflate,sdch");
            objRequest.Headers.Add("accept-language", "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4");
            objRequest.Headers.Add("cache-control", "max-age=0");
            objRequest.Headers.Add("origin", "https://twitter.com");
            objRequest.Referer = "https://twitter.com/signup";
            objRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36";
            System.Net.ServicePointManager.Expect100Continue = false;
            objRequest.CookieContainer = cookies;

            try
            {
                myWriter = new StreamWriter(objRequest.GetRequestStream());
                myWriter.Write(parsedData);

            }
            catch (Exception e)
            {
                // return e.Message;
            }
            finally
            {
                myWriter.Close();

            }

            HttpWebResponse response = objRequest.GetResponse() as HttpWebResponse;
            using (StreamReader sr =
                 new StreamReader(response.GetResponseStream()))
            {
                string result = sr.ReadToEnd();
                HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
                document.LoadHtml(result);

                // Close and clean up the StreamReader
                sr.Close();
            }

        }

A: Use Fiddler to observe what you are sending and what comes back. Compare that to what happens when you successfully register using a web browser.
You will find a difference. Twitter cannot tell what client program you are using. The problem can only be caused by what you are sending.


text:
Q: enable arm neon for bullet physics engine demo on android I'm building a demo with bullet physics engine library for android phone(NDK).
From 2.81 version, Bullet physics engine supports arm neon optimization, but only for apple devices.
My question is how to enable arm neon for android?
The flag for arm neon is defined in btScalar.h file, code is as below:
#if (defined (__APPLE__) && (!defined (BT_USE_DOUBLE_PRECISION)))
   #if defined (__i386__) || defined (__x86_64__)
             #define BT_USE_SSE
             #define BT_USE_SSE_IN_AP
   #elif defined( __armv7__ )
             #ifdef __clang__
             #define BT_USE_NEON 1
             #if defined BT_USE_NEON && defined (__clang__)
             #include <arm_neon.h>
             ……

As we can see in the code, flag BT_USE_NEON is defined in the condition of it is compiled for apple device, if I drop this code and define this flag by myself, some error occurs when compiling, something like bad alignment--vld1.f32 {d26},[r4:128].
What should I do for my demo to enable arm neon?

A: I had the same issues few days ago:)
The problem was assembly code defined in btVector3 (vld1q_f32_aligned_postincrement). As far as I know, syntax such as [r3, :128] is used in GAS - I guess it is used in iOS environment, but not sure. Modifying it to [%1, #128] may remove those errors.
By the way, from my experience, it is usually slow than plain implementation. I think the bullet neon intrinsics are not optimized for android, as you can see an assembly code(probably optimized) on the other side(defined as APPLE).


text:
Q: Is the click event no longer working on iOS devices? At the risk of sounding like Carly Rae Jepsen, this is crazy but I think this was working until yesterday after I updated my iOS to 10.3.3:

$(document).on('click','div',clicked)
function clicked() {
 alert('yay!')
}
<meta name="viewport" content="width=device-width, initial-scale=1">

click this div tag

A: James pointed out above that you have to have a cursor style for it to work:

div {
cursor:pointer
}


text:
Q: MYSQL how to speed up requests using EXISTS i have an SQL Requests:

SELECT DISTINCT id_tr
FROM planning_requests a
WHERE EXISTS(
        SELECT 1 FROM planning_requests b
        WHERE a.id_tr = b.id_tr
        AND trainer IS NOT NULL
        AND trainer != 'FREE'
      )
AND EXISTS(
        SELECT 1 FROM planning_requests c
        WHERE a.id_tr = c.id_tr
        AND trainer IS NULL
    )

but this requests take 168.9490 sec to execute for returning 23162 rows of 2545088 rows
should i use LEFT JOIN or NOT IN ? and how can i rewrite it thx

A: You can speed this up by adding indexes.  I would suggest:  planning_requests(id_tr, trainer).
You can do this as:
create index planning_requests_id_trainer on planning_requests(id_tr, trainer);

Also, I think you are missing an = in the first subquery.
EDIT:
If you have a lot of duplicate values of id_tr, then in addition to the above indexes, it might make sense to phrase the query as:
select id_tr
from (select distinct id_tr
      from planning_requests
     ) a
where . . .

The where conditions are being run on every row of the original table.  The distinct is processed after the where.

A: I think your query can be simplified to this:
SELECT DISTINCT a.id_tr
FROM planning_requests a
JOIN planning_requests b
ON b.id_tr = a.id_tr
AND b.trainer IS NULL
WHERE a.trainer < 'FREE'

If you index planning_requests(trainer), then MySQL can utilize an index range to get all the rows that aren't FREE or NULL. All numeric strings will meet the < 'FREE' criteria, and it also won't return NULL values.
Then, use JOIN to make sure each record from that much smaller result set has a matching NULL record.
For the JOIN, index planning_requests(id_tr, trainer).
It might be simpler if you don't mix types in a column like FREE and 1.


text:
Q: VBA loop in change event error I have this macro that creates a textbox in worksheet 2 when I write something in cell A1 of worksheet 1, and when I delete that value it deletes the textbox.
I want to do that for several cells, but it just is working. If Cell A1 has a value a textbox with that value should appear, if the A2 has a value a textbox with that value should appear, but if I delete A1 it should delete the texbox that refers to A1, not all of the textboxes
Sub RemoveShapes()

    Dim shp As Shape
    For Each shp In Worksheets(2).Shapes
        If shp.Type = msoTextBox Then shp.Delete
    Next shp

End Sub

Sub criarcaixastexto()

    Dim wsActive As Worksheet
    Dim box As Shape

    Set wsActive = Worksheets(2)
    Set box = wsActive.Shapes.AddTextbox(msoTextOrientationHorizontal, 20, 20, 100, 50)

    box.TextFrame.Characters.Text = Range("Folha1!A1").value

End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$A$1" Then
        Call criarcaixastexto
    End If
End Sub

I tried this but it doesn't work
'macro para apagar
Sub removercaixas()

    Dim shp As Shape
    For Each shp In Worksheets(2).Shapes
        If shp.Type = msoTextBox Then shp.Delete
    Next shp

End Sub

'macro para criar caixas de texto
Sub criarcaixastexto()

   Dim wsActive As Worksheet
   Dim box As Shape

   Set wsActive = Worksheets(2)
   Set box = wsActive.Shapes.AddTextbox(msoTextOrientationHorizontal, 20, 20, 100, 50)

   box.TextFrame.Characters.Text = Worksheets(1).Cells(i, 1).Value

End Sub

' macro corre ao escrever texto numa célula
Private Sub Worksheet_Change(ByVal Target As Range)

    For i = 1 To 3
        If Target.Count > 1 Then Exit Sub
        If Not Intersect(Target, Range("A&i")) Is Nothing Then
            removercaixas
        If Len(Target) > 1 Then criarcaixastexto
        End If
    Next

End Sub

A: You are removing all textboxes on the sheet any time you call removercaixas. You need to somehow link the textbox with the cell it was generated by.
Why not name the textbox with the cell address? Copy/Paste this:
Sub removercaixas(strName As String)

    Dim shp As Shape
    For Each shp In Worksheets(2).Shapes
        If shp.Type = msoTextBox AND shp.Name = strName Then shp.Delete
    Next shp

End Sub

And
Sub criarcaixastexto(strName As String)

    Dim wsActive As Worksheet
    Dim box As Shape

    Set wsActive = Worksheets(2)
    Set box = wsActive.Shapes.AddTextbox(msoTextOrientationHorizontal, 20, 20, 100, 50)

    box.TextFrame.Characters.Text = Worksheets(1).Range(strName).Value
    box.Name = strName

End Sub

And
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Count > 1 Then Exit Sub
    Select Case Target.Address
        Case "$A$1", "$A$2", "$A$3"
            removercaixas (Target.Address)
        Case Else
            Exit Sub
    End Select
    If Len(Target) > 1 Then criarcaixastexto (Target.Address)
End Sub

Textboxes are created in worksheet 2 all on top of each other. They are deleted appropriately. No textbox is created when the value entered in $A$1:$A$3 has a length of 1 or less. Not sure what the logic is there, but if you want single digit values to create a textbox just change the Len(Target) > 1 to Len(Target) > 0.


text:
Q: Starting a systemd service after resume not working I'm trying to have a service restart itself on system resume. This is my the .service file:
[Unit]
Description=Set the battery charge threshold
After=multi-user.target
After=sleep.target
StartLimitBurst=0

[Service]
Type=oneshot
Restart=on-failure
ExecStart=/bin/bash -c 'echo 60 > /sys/class/power_supply/BAT1/charge_control_end_threshold'

[Install]
WantedBy=multi-user.target
WantedBy=sleep.target

I've set WantedBy and After to sleep.target with the hopes that this service will be run after sleep.target is run. However, the service is started just before being putting to sleep instead of on resume. Is this a known bug? Or am I doing something wrong?
I'd also like it to run after resuming from suspend (i.e hibernation). But suspend.target pulls in sleep.target, so fixing this issue ought to allow this to on resume-from-suspend.
I know similar questions exist, however none of the solutions there work (specifically setting WantedBy and After).
PS: Please don't recommend using bash scripts placed in specific folders. Those seem too clunky for my use case and I'd like a simpler solution first instead.

A: Maybe you need something like this:
[Unit]
Description=Set the battery charge threshold
PartOf=sleep.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/true
ExecStop=/bin/bash -c 'echo 60 > /sys/class/power_supply/BAT1/charge_control_end_threshold'

[Install]
WantedBy=sleep.target

A:
I've set WantedBy and After to sleep.target with the hopes that this service will be run after sleep.target is run. However, the service is started just before being putting to sleep instead of on resume.

This is normal, as there is nothing that would actually be ordered before "sleep.target". All built-in services which actually trigger the kernel power actions (such as "systemd-suspend.service") only have After=sleep.target, so they run in parallel with your service.
The actual "sleep.target" does nothing by default, and is not involved in actually putting the system to sleep; that's done by the specific "hibernate.target" and "suspend.target" units.
You would need to hook your service directly after those two targets, or the corresponding "systemd-hibernate.service" and "systemd-suspend.service".


text:
Q: How to get height of Page? How can I get the height of a Page?, i.e; the height of all elements in the page.
For example, if I have this XAML which makes a Page, how can I get the height at runtime?
<Page x:Class="DialogViews.SomeError"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      mc:Ignorable="d"
      d:DesignHeight="300" d:DesignWidth="400"
    Title="SomeMessage">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="50" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        A Problem
        <TextBlock Grid.Row="1" Style="{StaticResource ResourceKey=DialogMsg}">
            Some message to user
        </TextBlock>

            <Hyperlink>
                Some link for info
            </Hyperlink>

    </Grid>
</Page>

Reason:
I've created a custom Window that will display as a Dialog message to the user, the Window contains a Frame which in-turn contains this Page. I'm trying to fix the height of the Window to that of the Page.
I have tried:
myPage.Height; //NaN
myPage.ActualHeight; //0

A: If you want to fit the size of the Window to your user control Page, then I would suggest trying the SizeToContent property of Window.
 <Window x:Class "MyNameSpace.MyWindow"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         SizeToContent="Height" />

Height - Specifies that a window will automatically set its height to fit the height of its content, but not the width.
Edit: This will stretch your Window to fit the Frame, which hopefully is set to change with the widths/heights of your Page.

A: Are you looking for
  SystemParameters.FixedFrameVerticalBorderWidth
  SystemParameters.FixedFrameHorizontalBorderHeight
  SystemParameters.WindowCaptionHeight

Please check this msdn link

A: Try with
this.Height;

this.Width;


text:
Q: How to check if any of the li's are selected or not?

a

a

a

a

a

How do I know if any of the
s have a select class? If found, how do I remove that class?

A: To find if any li is selected use
$('#ul > .select');

and use removeClass to remove select
.removeClass('select');

A: The following will remove the select class from all
 elements that have it:
$('li.select').each(function() { $(this).removeClass('select'); });

A: use

removeClass

  $('#ul li').removeClass("select");

to find this class is exist ?
use

hasClass

A: I'd do it like this:
$("#ul > li").filter(function(index) { return $(this).hasClass("select"); }).removeClass("select");

EDIT:
Interesting test case on jsperf showing that indeed, filter is the slowest method, while selector method is the fastest.


text:
Q: How to create cronjob for stopping the application in every month different date I need to create a cronjob for stopping an application every month at different date. For example: time: 2 am, date: jan 5th, feb 7th, mar 15th
00 02 * * * /export/home/jira-8.5.3-install/bin/stop-jira.sh


text:
Q: SSRS Report CreateCatalogItem using pySSRS Currently, I am migrating a Powershell script that deploys the SSRS report dll to the SSRS server. I am unable to the step where it creates the Catalog Item.
Powershell:
$r = $ra.CreateCatalogItem(
     "typeReport",
     $Name,
     $Path,
     $true,
     $filebytes,
     $warnings
)

pySSRS:
rs.ServiceClient.service.CreateCatalogItem("typeReport", name, file_path, file_bytes)

Looks like the library doesn't have the CreateCatalogItem method in it. I can't find any other way to create it.


text:
Q: Using apache Shiro with Spring MVC non xml project I have a project in which i am using Spring mvc 4 and i need to include there apache shiro security. I've tried to search over the web for a solution for my problem but didn't managed to fins something. Although there is a guide at Shiro's web site, but this example is only for xml configured Spring project, and my project doesn't contain any xml at all, and when i am trying to configure Shiro with annotation only it fails.
When i run this project i have an access to all of my end points, and non of them is being restricted by Shiro.
I guess that my configuration is wrong but i am unable to figure out which part of it is wrong.
I am not allowed to use Spring boot (i know that there is examples for that).
here is my configuration class:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.myproject.menu")
public class AppConfiguration extends WebMvcConfigurerAdapter{

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**").addResourceLocations("/");
}

@Bean(name="shiroFilter")
public ShiroFilterFactoryBean shiroFilter (){
    ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
    shiroFilter.setLoginUrl("/MenuTest/login");
    shiroFilter.setFilterChainDefinitions("/MenuTest/init=anon");
    shiroFilter.setFilterChainDefinitions("/MenuTest/**=authc");
    shiroFilter.setSecurityManager(realm());
    return shiroFilter;
}

private DefaultWebSecurityManager realm(){
    DefaultWebSecurityManager realm = new DefaultWebSecurityManager();
    return realm;
}
}

Thx in advance!

A: Take a look at the 1.4.0 (RC2) release. There is updated Spring and Spring-Boot support.
And examples in the source tree:
https://github.com/apache/shiro/tree/master/samples/spring-mvc


text:
Q: How can I show the details from the highest zoom of OSM webmaps in QGIS for printing? I would like to compose a large format map for printing in QGIS with the highest detail possible.  My process looks like this,

*

*Install "QuickMapServices" plugin

*Click the "QuickMapServices" button and choose OSM >> OSM Standard

*Pan to my selection area

*New print layout (ctrl + p) and make a name

*add item >> add map (its now at the zoom where I want more detail displayed and I don't know what to do).

A: You must increase either the page size, the export resolution, or both.
To change the page size right-click the layout --> go to Page Properties --> select or define a larger page dimension in the Item Properties panel (screen-right by default).
The export resolution may be changed at the time of (image) export, or within the Layout panel under Export Settings.
QGIS 3.2 (older versions as well) fetches images from a tile server at the time of screen render as well as at export/print. Screen-space tiles are fetched for the layout preview while page-space tiles are fetched at the time of export. Therefor, the layout preview will not reflect the higher-zoom map.
There are upper bounds to the exportable image size and QGIS will warn you if the operation will result in a memory overflow. Additionally, the process of fetching a large number of tiles can take a long time.
Below are the results of an OSM tile map preview and export of an Arch E @ 450dpi.


text:
Q: Laravel: User & Post Relationship Model Structure
user.php
public function inventories() {
   return $this->belongsToMany('App\Model\user\inventory')->orderBY('created_at','DESC')->paginate(10);
}

inventory.php
public function users() {
    return $this->belongsToMany('App\Model\user\user')->withTimestamps();
}

Table Structure:
inventories:
id
user_id
content

users:
id
name
email

How to call the inventories->user_id to connect in users->id in controller?
Example in laravel blade:
user_id = 1
content = 'This is content'

I want is:
user_id = 'Name of user 1'
content = 'This is content'

A: Since you have defined your relations, you can use :
$inventories = Inventory::all();

foreach ($inventories as $inventory) {

    foreach ($inventory->users as $user) {

         echo $user->name; // show the name of user
    }

    // or to get first user :
    $user_1_name = isset($inventory->users[0]) ? $inventory->users[0]->name : '-';
}

A: On your controller:
$inventories = Inventory::all();

On your blade file:
@foreach ($inventories as $inventory)
    {{ $inventory->users()->id }}<br/>
@endforeach


text:
Q: What happen to \mathcal (IEEE conf. sample) I am a beginner in Latex. I used to use \mathcal, for example:
old code
\documentclass[12pt]{article}
\usepackage{graphicx}
\usepackage{amsmath}
\begin{document}
$\mathcal{C}$
\end{document}

Output

I utilize the tex. sample from IEEE (open it with the original software):
http://control.disp.uniroma2.it/cdc2012/author_info.php
I use the same code; however, I got this:

How do I fix it? (I want the previous one.)

A: It seems to be hard-coded in ieeeconf.cls. It loads mathptmx by default and as a result, \mathcal calls \mathrsfs. You can circumvent the problem loading newtx, which loads TeX Gyre Termes, another Times-clone:
\documentclass[12pt]{ieeeconf}
\usepackage[utf8]{inputenc}
\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{newtxtext, newtxmath}

\begin{document}

Lalala…
$\mathcal{C}$

\end{document}

A: Do you have the package fourier, i.e., \usepackage{fourier} in your .tex file? For me, when I comment out this package, I get the correct fonts again.


text:
Q: CSS Position Absolute NOT ignoring element with no positioning I have a
 with a few
,
,and
 tags inside, then I have a
 below these h1,h2,and p tags inside of this parent
. I have position: relative; on the parent
 and position:absolute; top:0px; on the child
. There is no positioning set in the css for the h1,h2, and p tags. The result I'm getting is, the child
 is positioning to the bottom of the other child elements and not positioning to the very top of the parent div. Is this what is supposed to be happening?
** HTML **

Header

sub header

paragraph text

test

** CSS **
#parentDiv {
   position: relative;
   width: 500px;
   min-height: 300px;
}

#parentDiv h1, #parentDiv h2, #parentDiv p {
   margin-left: 30px;
   margin-top: 30px;
}

#displayAtTop {
   position: absolute;
   top: 0px;
   left: 350px;
}

I thought absolute positioning was supposed to ignore everything and place it at the very top of the closest parent element with positioning set.

A: The code works as expected.
I added a red border to make it easier to see.
I think you might be mistaking the  or  padding/margin for a problem.

Header

sub header

paragraph text

test

http://jsfiddle.net/StoneCypher/Lq95hcqe/


text:
Q: JObject error "Property with the same name already exists on object" Generally I have had no issue using JSON.NET to deserialize JSON to a dynamic object. However the JSON below is causing the error

Can not add property consent to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.

I have checked the JSON against JSONLint and it appears valid. What am I missing here?
Code
dynamic d = JObject.Parse(jsonString);

JSON
{
"DataFields": {
    "preamble": {
    },
    "applicant": {
        "description": {
            "count": "1"
        },
        "details": {
            "title": null,
            "first_name": null,
            "middle_name": null,
            "surname": null
        },
        "property": {
            "address": {
                "line1": null,
                "line2": null,
                "line3": null,
                "town": null,
                "county": null,
                "postcode": null
            },
            "solicitor": {
                "name": null,
                "address": {
                    "line1": null,
                    "line2": null,
                    "line3": null,
                    "town": null,
                    "county": null,
                    "postcode": null
                },
                "contact": {
                    "email": null,
                    "reference_number": null
                    }
                }
            }
        },
    "boundaries": {
        "description": {
        },
        "location": {
            "left": null,
            "right": null,
            "back": null,
            "front": null,
            "maintenance": null,
            "movement": null,
            "movement_details": null,
            "ownership": null,
            "additional_land": null,
            "additional_land_details": null,
            "flying_freehold": null,
            "flying_freehold_details": null
            }
        },
    "discom": {
        "descritpion": {
            "question": null,
            "details": null
        },
        "complaint": {
            "received": {
                "question": null,
                "details": null
            },
            "made": {
                "question": null,
                "details": null
                }
            }
        },
    "notices": {
        "sentrec": {
            "question": null,
            "upload": null,
            "details": null
        },
        "negotiations": {
            "question": null,
            "details": null
            }
        },
    "guarantees": {
        "individual": {
            "foundation_newbuild": null,
            "foundation_newbuild_upload": null,
            "damp_course": null,
            "damp_course_upload": null,
            "glazing_roofing": null,
            "glazing_roofing_upload": null,
            "electrical": null,
            "electrical_upload": null,
            "roofing": null,
            "roofing_upload": null,
            "infestation": null,
            "infestation_upload": null,
            "heating": null,
            "heating_upload": null,
            "underpinning": null,
            "underpinning_upload": null,
            "other": null,
            "other_type": null,
            "other_upload": null,
            "written_details": null
        },
        "misc": {
            "written_details_upload": null
        },
        "summary": {
            "originals": null,
            "claims": null,
            "claims_upload": null
            }
        },
    "central_heating": {
        "description": {
            "installed": null
        },
        "details": {
            "condition": {
                "working": null,
                "details": null,
                "type": null,
                "date": null,
                "unknown": null,
                "completion": null
            },
            "service": {
                "year": null,
                "unknown": null,
                "copy": null
                }
            }
        },
    "services": {
        "connected": {
            "gas": {
                "question": null,
                "supplier": {
                    "name": null,
                    "phone": null,
                    "meter": null
                    }
                },
            "electric": {
                "question": null,
                "supplier": {
                    "name": null,
                    "phone": null,
                    "meter": null
                    }
                },
            "mainwater": {
                "question": null,
                "supplier": {
                    "name": null,
                    "phone": null,
                    "stop_cock": null,
                    "meter": null
                    }
                },
            "maindrain": {
                "question": null,
                "supplier": {
                    "name": null,
                    "phone": null,
                    "meter": null
                    }
                },
            "telephone": {
                "question": null,
                "supplier": {
                    "name": null,
                    "phone": null
                    }
                },
            "broadband": {
                "question": null,
                "supplier": {
                    "name": null,
                    "phone": null
                    }
                },
            "cable": {
                "question": null,
                "supplier": {
                    "name": null,
                    "phone": null
                    }
                },
            "satellite_tv": {
                "question": null,
                "supplier": {
                    "name": null,
                    "phone": null
                    }
                }
            },
        "water": {
            "charge": {
                "water": {
                    "latest": null
                },
                "sewerage": {
                    "latest": null
                    }
                },
            "meter": {
                "question": null,
                "foul": null,
                "surface": null
                }
            },
        "your_property": {
            "question": null,
            "details": null
        },
        "neighbours_property": {
            "question": null,
            "details": null
        },
        "agreement": {
            "question": null,
            "copy": null,
            "details": null
        },
        "drain_problems": {
            "question": null,
            "details": null
        },
        "septic_cesspit": {
            "septic": null,
            "sewage": null,
            "cesspool": null,
            "drainage": {
                "septic_tank": null,
                "number": null,
                "year_last_emptied": null,
                "year_installed": null,
                "year_treated": null,
                "outside_property": null,
                "plan_upload": null
                }
            },
        "electricity": {
            "question": null,
            "tested": {
                "year": null,
                "copy": null
            },
            "rewire": {
                "question": null,
                "certificates": {
                    "bs7671": null,
                    "compliance": null,
                    "completion": null
                    }
                }
            }
        },
    "neighbours": {
        "contribution": {
            "question": null,
            "details": null
        },
        "repair": {
            "question": null,
            "details": {
                "information": null,
                "organiser": null,
                "charging": null
                }
            },
        "property": {
            "question": null,
            "details": {
                "information": null,
                "objections": null,
                "details": null
                }
            },
        "your_property": {
            "question": null,
            "objections": null,
            "details": null
        },
        "notice": {
            "question": null,
            "copy": null,
            "details": null
            }
        },
    "arrangements": {
        "description": {
        },
        "access": {
            "question": null,
            "details": null,
            "payment": {
                "question": null,
                "details": null
            },
            "neighbours": {
                "question": null,
                "details": {
                    "details": null
                    }
                },
            "other": {
                "question": null,
                "details": {
                    "details": null
                },
                "arrangements": {
                    "rights_of_light": null,
                    "rights_of_support": null,
                    "customary_rights": null,
                    "mines_and_minerals": null,
                    "chancel_repair": null,
                    "take_things": null,
                    "details": null
                    }
                }
            }
        },
    "occupiers": {
        "description": {
            "seller_at_property": null,
            "vacant": null,
            "occupants": null
        },
        "details": {
            "number": null,
            "other": {
                "name": null,
                "age": null
            },
            "rights": {
                "agreed_to_leave": null,
                "agreed_to_sign": null,
                "vacation_evidence": null,
                "tenants_or_lodgers": null,
                "tenants_or_lodgers_details": null
                }
            }
        },
    "changes": {
        "description": {
        },
        "building": {
            "question": null,
            "works": {
                "details": null,
                "year": null,
                "permission": {
                    "question": null,
                    "upload": null
                },
                "regulations_approved": {
                    "question": null,
                    "upload": null
                },
                "title": {
                    "question": null,
                    "restriction": {
                        "question": null,
                        "consent": {
                            "explanation": null,
                            "name": null
                            }
                        }
                    },
                "insurance_policy": {
                    "question": null,
                    "upload": null
                    }
                }
            },
        "change": {
            "use_question": {
                "question": null,
                "changes_change_use": {
                    "year": null,
                    "permission": {
                        "question": null,
                        "upload": null
                    },
                    "regulations_approved": {
                        "question": null,
                        "upload": null
                    },
                    "title_restriction_question": {
                        "question": null,
                        "changes_change_use_title_restriction": {
                            "question": null,
                            "consent": {
                                "explanation": null,
                                "contact": null
                                }
                            }
                        },
                    "insurance_policy": {
                        "question": null,
                        "upload": null
                        }
                    }
                }
            },
        "sub": {
            "question": null,
            "division": {
                "year": null,
                "permission": {
                    "question": null,
                    "upload": null
                },
                "regulations_approved": {
                    "question": null,
                    "upload": null
                },
                "title": {
                    "question": null,
                    "restriction": {
                        "question": null,
                        "consent": {
                            "explanation": null,
                            "contact": null
                            }
                        }
                    },
                "insurance_policy": {
                    "question": null,
                    "upload": null
                    }
                }
            },
        "conversionquestion": {
            "question": null
        },
        "conversion": {
            "year": null,
            "permission": {
                "question": null,
                "upload": null
            },
            "regulations_approved": {
                "question": null,
                "upload": null
            },
            "title_restrictionquestion": {
                "question": null
            },
            "title_restriction": {
                "question": null,
                "consent": {
                    "explanation": null,
                    "contact": null
                    }
                },
            "insurance_policy": {
                "question": null,
                "upload": null
                }
            },
        "business": {
            "question": null,
            "activity": {
                "year": null,
                "permission": {
                    "question": null,
                    "upload": null
                },
                "regulations_approved": {
                    "question": null,
                    "upload": null
                },
                "title": {
                    "restrictions": null,
                    "restriction": {
                        "question": null,
                        "consent": {
                            "explanation": null,
                            "contact": null
                            }
                        }
                    },
                "insurance_policy": {
                    "question": null,
                    "upload": null
                    }
                }
            },
        "underpinningquestion": {
            "question": null
        },
        "underpinning": {
            "year": null,
            "permission": {
                "question": null,
                "upload": null
            },
            "regulations_approved": {
                "question": null,
                "upload": null
            },
            "title": {
                "question": null,
                "restriction": {
                    "question": null,
                    "consent": {
                        "explanation": null,
                        "contact": null
                        }
                    }
                },
            "insurance_policy": {
                "question": null,
                "upload": null
                }
            },
        "solar": {
            "question": null,
            "panels": {
                "year": null,
                "permission": {
                    "question": null,
                    "upload": null
                },
                "regulations_approved": {
                    "question": null,
                    "upload": null
                },
                "title": {
                    "question": null,
                    "restriction": {
                        "question": null,
                        "consent": {
                            "explanation": null,
                            "contact": null
                            }
                        }
                    },
                "insurance_policy": {
                    "question": null,
                    "upload": null
                },
                "ownership": {
                    "question": null
                },
                "lease": {
                    "question": null,
                    "upload": null
                    }
                }
            },
        "replace": {
            "question": null,
            "window_roof": {
                "year": null,
                "permission": {
                    "question": null,
                    "upload": null
                },
                "regulations_approved": {
                    "question": null,
                    "upload": null
                },
                "title": {
                    "question": null,
                    "restriction": {
                        "consent": null,
                        "consent": {
                            "explanation": null,
                            "contact": null
                            }
                        }
                    },
                "insurance_policy": {
                    "question": null,
                    "upload": null
                },
                "certificate_regulations": {
                    "question": null
                    }
                }
            },
        "air_conditioning": {
            "installed": null,
            "year": null
        },
        "satellite_dish": {
            "installed": null,
            "year": null
        },
        "central_heating": {
            "installed": null,
            "details": {
                "year": null,
                "upload": null
                }
            },
        "unfinished": {
            "question": null,
            "details": null
        },
        "breaches": {
            "question": null,
            "details": null
        },
        "unresolved": {
            "question": null,
            "details": null
            }
        },
    "conservatory": {
        "description": {
            "question": null
        },
        "details": {
            "public": null,
            "ground_level": null,
            "domestic_purpose": null,
            "volume": null,
            "height": null,
            "boundary": null,
            "area": null,
            "roof_materials": null,
            "safety_glass": null,
            "sleeping_accommodation": null,
            "access": null,
            "heating": null,
            "drainage": null,
            "build_date": null,
            "building_regulations": null,
            "building_regulations_copy": null
            }
        },
    "planning": {
        "buildingcontrol": {
            "private": {
                "question": null,
                "details": null
            },
            "listed_building": {
                "listed": null,
                "conservation": null,
                "upload": null
            },
            "grants": {
                "question": null,
                "upload": null
            },
            "gas_installation": {
                "question": null,
                "upload": null
            },
            "proposed_development": {
                "question": null,
                "details": null
            },
            "treequestion": {
                "question": null
            },
            "tree": {
                "question": null,
                "local_authority": {
                    "question": null
                    }
                },
            "drain_alterations": {
                "question": null,
                "year": null
                }
            }
        },
    "expenses": {
        "property_costs": {
            "question": null,
            "details": null
            }
        },
    "sale_mechanics": {
        "chain": {
            "question": null,
            "details": null
        },
        "mortgage": {
            "question": null,
            "details": null
        },
        "deposit": {
            "question": null
        },
        "excess": {
            "question": null
            }
        },
    "moving": {
        "description": {
            "special": null,
            "date": null
            }
        },
    "environmental": {
        "description": {
        },
        "flooding": {
            "question": null,
            "details": {
                "date_and_location": null,
                "ground_water": null,
                "sewer_flooding": null,
                "surface_water": null,
                "coastal_flooding": null,
                "river_flooding": null,
                "other": null,
                "description": null
            },
            "risk": {
                "question": null,
                "details": null
                }
            },
        "contamination_land_fill": {
            "question": null,
            "details": null
        },
        "property": {
            "subsidence": {
                "question": null,
                "details": null
            },
            "defective_drains": {
                "question": null,
                "details": null
            },
            "damp": {
                "question": null,
                "details": null
            },
            "fungal_insect_infestation": {
                "question": null,
                "details": null
            },
            "structual_defects": {
                "question": null,
                "details": null
                }
            },
        "radon": {
            "gas": {
                "measured": null,
                "measurement": {
                    "copy": null,
                    "below_action_level": null,
                    "above_action_level_details": null,
                    "remedial_action": null,
                    "remedial_action_details": null
                    }
                }
            },
        "epc": {
            "copy": null
        },
        "sustainablecertificate": {
            "copy": null
        },
        "greendeal": {
            "green_deal": null,
            "details": {
                "details": null,
                "copy": null
                }
            },
        "japaneseknotweed": {
            "affected": null,
            "plan": {
                "in_place": null,
                "copy": null
                }
            }
        },
    "mining": {
        "description": {
            "question": null
        },
        "area": {
            "damage": {
                "question": null,
                "details": null
            },
            "claim": {
                "question": null,
                "details": null
            },
            "previous_owner_claim": {
                "question": null,
                "details": null
            },
            "coal_board": {
                "upload": null
                }
            }
        },
    "general": {
        "description": {
            "council_tax_band": null,
            "council_tax_amount": null,
            "keep_telephone_number": null,
            "burgled": null
        },
        "insurance": {
            "question": null,
            "anomalies": {
                "abnormal_premiums": null,
                "high_excesses": null,
                "unusual_conditions": null,
                "refused": null,
                "details": null
            },
            "claims": {
                "question": null,
                "details": null
                }
            },
        "gift_under_value": {
            "question": null,
            "details": null
        },
        "meter_readings": {
            "question": null,
            "details": null
        },
        "services_issues": {
            "question": null,
            "details": null
        },
        "parking": {
            "arrangements": null,
            "zonal": null
        },
        "covenants": {
            "question": null,
            "details": null
        },
        "confirm": {
            "rubbish_removal": null,
            "light_fittings": null,
            "removal_care": null,
            "keys_and_alarm": null
        },
        "propertytitle": {
        },
        "property": {
            "locks": {
                "question": null,
                "details": null
            },
            "windows": {
                "question": null,
                "details": null
            },
            "lavatory": {
                "question": null,
                "details": null
            },
            "kitchen": {
                "question": null,
                "details": null
            },
            "radiators": {
                "question": null,
                "details": null
            },
            "heating_hot_water": {
                "question": null,
                "details": null
            },
            "gas_appliances": {
                "question": null,
                "details": null
            },
            "gas_electrical_circuitry": {
                "question": null,
                "details": null
            },
            "gas_electrical_other": {
                "question": null,
                "details": null
                }
            }
        },
    "uploads": {
        "description": {
        },
        "notices": {
            "sentrec": {
            }
        },
        "guarantees": {
            "foundation_newbuild_evidence": {
            },
            "damp_course_evidence": {
            },
            "glazing_roofing_evidence": {
            },
            "electrical_evidence": {
            },
            "roofing_evidence": {
            },
            "rot_infestation_evidence": {
            },
            "central_heating_evidence": {
            },
            "underpinning_evidence": {
            },
            "other_evidence": {
            },
            "written_details_evidence": {
            }
        },
        "central_heating": {
            "certificate": {
            },
            "benchmark_scheme_logbook": {
            }
        },
        "services": {
            "water_charge": {
            },
            "sewerage_account": {
            },
            "septic_cesspit_drainage_regulations": {
            },
            "septic_cesspit_drainage_plan": {
            },
            "electricity_certificate": {
            },
            "electricity_rewire_certificates_bs7671": {
            },
            "electricity_rewire_certificates_compliance": {
            },
            "electricity_rewire_certificates_completion": {
            }
        },
        "neighbours": {
            "notice": {
            }
        },
        "occupiers": {
            "rights_vacation_evidence": {
            },
            "rights_tenancy_agreement": {
            }
        },
        "changes": {
            "building_works": {
                "permission": {
                },
                "regulations_approved": {
                },
                "insurance_policy": {
                },
                "listed_building": {
                }
            },
            "change_use": {
                "permission": {
                },
                "regulations_approved": {
                },
                "insurance_policy": {
                },
                "listed_building": {
                }
            },
            "sub_division": {
                "permission": {
                },
                "regulations_approved": {
                },
                "insurance_policy": {
                },
                "listed_building": {
                }
            },
            "conversion": {
                "permission": {
                },
                "regulations_approved": {
                },
                "insurance_policy": {
                },
                "listed_building": {
                }
            },
            "business_activity": {
                "permission": {
                },
                "regulations_approved": {
                },
                "insurance_policy": {
                },
                "listed_building": {
                }
            },
            "underpinning": {
                "permission": {
                },
                "regulations_approved": {
                },
                "insurance_policy": {
                },
                "listed_building": {
                }
            },
            "solar_panels": {
                "permission": {
                },
                "regulations_approved": {
                },
                "insurance_policy": {
                },
                "listed_building": {
                },
                "lease": {
                }
            },
            "replace_window_roof": {
                "permission": {
                },
                "regulations_approved": {
                },
                "insurance_policy": {
                },
                "certificate_regulations": {
                },
                "listed_building": {
                }
            },
            "central_heating": {
                "certificate_regulations": {
                }
            }
        },
        "conservatory": {
            "details_building_approval": {
            }
        },
        "planning": {
            "buildingcontrol_elec_works_certificate": {
            },
            "buildingcontrol_gas_installation_certificate": {
            },
            "tree": {
                "preservation": {
                }
            }
        },
        "environmental": {
            "flooding_risk": {
            },
            "radontestresults": {
            },
            "epc": {
            },
            "sustainabilitycertificate": {
            }
        },
        "mining": {
            "coal_board_info": {
            }
        }
    },
    "instructions": {
        "confirmation": {
            "authority": null
        },
        "completed": {
            "name": null,
            "date": null
        }
    }
}
}

A: I've just run your posted JSON through JSLint - there is a duplicate consent field in the structure. It's in the changes.replace.window_roof.title object.


text:
Q: Why are signed negative numbers converted to unsigned numbers? Particularly i have a large unsigned number and a large signed negative number.
Why can't I divide a large number by a negative number C++
When I try to divide the two, I get the result zero simply because something somewhere is converting my signed number to unsigned (meaning that it has to be positive). >.>;
Edit.
Just to be absolutely clear. I know that it is resolved to zero and I'm happy with that. I'm also happy with the previous reason that it is resolved to zero because a number is converted away from being a signed number to an unsigned number.
However that doesn't answer why the number is converted from a signed number to an unsigned number in the first place. There doesn't seem to be any logical reason for doing so.

A: The operands of the arithmetic operators need to have the same types. That makes the language easier to define and easier to implement, in part because there are fewer cases to handle, and in part because hardware doesn't generally support mixed-type operations, either. Formally, C++ is defined in terms of a virtual machine, but the capabilities expected of that machine are influenced by those of real-world hardware. Operations dictated by the standard but not supported by hardware (such as your hypothetical signed-unsigned division) would need to be implemented by compiler-writers in library code, and that would affect performance.
Either the signed operand needs to be converted to unsigned, or vice versa. The standard committee picked the former.


text:
Q: What is the good approach to check an existance of unique values in database table by SqlAlchemy in python2.7 I use session.merge in SqlAlchemy to insert data to the table with UniqueConstraint, which is common for several columns, for example, my ORM class has the following:
UniqueConstraint("attr_1", "attr_2", "attr_3", name="attributes_uix")

Should I use filter or filter_by with _and to check, if data, which I'm going to insert will violate this unique constraint, or is it the proper way to catch IntegrityError by try - except construction?

A: No an sql-alchemy expert but have struggled with this and similar questions for a while.  I am not sure if there is a single right way in this case.  What I can describe for you is what the tradeoff between grabbing db exceptions and handling it in your code are.
Personally I prefer to trap db exceptions. This has the advantage of not running extra queries (with extra latency, etc).  It also has the advantage of reusing existing framework pieces as much as possible.
However it has two real drawbacks.  The first, which can be solved on the db design level, is that multi-column unique constraints are not violated by matches containing NULL values.  In other words, if I have aa cnstraint on (id, value), then (1, null), (1, null) cannot be said to be non-unique and therefore no integrity exception is thrown.  So first it is worth checking to see if you can avoid this problem.  If not, you need to find a workaround, but PostgreSQL gives you pleny of tools there (for example, functional indexes).
The second is that catching IntegrityError is a kind of a blunt instrument and you can't really parse any error message available for the index name because this may vary between systems and the locale can mean the message may be translated.  So you are relying on SQLSTATE and this is not very precise.  I.e. you don't have good machine readable information. about which constraint was voilated if there are multiple candidates.
The question then is between these and duplicating code and queries.  Usually I think catching the error is the lesser evil, but due to the tradeoffs it is not a universal recommendation.


text:
Q: Convex cones in $\Bbb R^n$ Are the following sets convex cones:
1.$\{x\in\Bbb R^n:\langle a,x\rangle\leq 0, a\neq 0 \}$  2.$\{x\in\Bbb R^n:\langle a,x\rangle\lt 0, a\neq 0 \}$ ?
We say $C\subset \Bbb R^n$ is a cone if $\forall x \in C$ and $\lambda>0$, $\lambda x \in C$. A convex cone is a cone that is a convex set.  I drew the sets in $\Bbb R^2$ and from that we can see that both sets are convex cones. Is there a more formal proof?


text:
Q: SOCKET_PUSH not sending anything using ZMQContext? [Blocked by FireWall ...] I am trying to follow this tutorial for Ratchet/ZMQ Socket programming:
http://socketo.me/docs/push
with a bit of customisation to learn abit more about it.
The server itself is running fine and the connection between front-end html seems to be connecting right. But I cant figure the PHP file that sends a message to the server.
CODES BELOW:
SENDER.PHP
$context    = new ZMQContext();
$socket     = $context->getSocket(ZMQ::SOCKET_PUSH,'my pusher');
$socket->connect('tcp://127.0.0.1:5555');
$socket->send("SENDING A MESSAGE");

The code above is what Im having problems with. When I run the code in the command line
php sender.php
The server should at least display some feed back but it doesnt give me anything. And the sender.php just exits.
Im stuck trying to figure out what Im missing. At least the front-html bit works.
How can I get the sender.php to send the message? Any suggestion/advise/help would be greatly appreciated.
Below are the rest of my codes:
INDEX.html
This html file is connecting as Im getting the message from the constructor.
ab.debug(true,true);
var conn = new ab.Session('ws://localhost:8080',
        function() {
            conn.subscribe('kittensCategory', function(data) {
                // This is where you would add the new article to the DOM (beyond the scope of this tutorial)
                console.log("New data available: ",data);
            });
        },
        function() {
            console.warn('WebSocket connection closed');
        },
        {'skipSubprotocolCheck': true}
);

SERVER.PHP
use Models\SCSTRealtimeSubsObject;

// The event loop that will keep on triggering
$loop   = React\EventLoop\Factory::create();

// Our custom pusher that will do the logic, $loop is optional
$pusher =  new SCSTRealtimeSubsObject;

// Listen for the web server to make a ZeroMQ push after an ajax request
$context = new React\ZMQ\Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
//Binding to itself means the client can only connect to itself
$pull->bind("tcp://127.0.0.1:5555");
//On a 'message' event, pass the data to the myMessageHandler method of the MyPusherClass
$pull->on('message', array($pusher, 'customAction'));

// Set up our WebSocket server for clients wanting real-time updates
$webSock = new React\Socket\Server('0.0.0.0:8080', $loop); // Binding to 0.0.0.0 means remotes can connect
$webServer = new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        new Ratchet\WebSocket\WsServer(
            new Ratchet\Wamp\WampServer(
                $pusher
            )
        )
    ),
    $webSock
);

$loop->run();

PUSHER.PHP
class SCSTRealtimeSubsObject implements WampServerInterface {

    public function __construct() {
        echo "Constructor call. \n";
    }
    public function customAction($msg){ // Message from the onMessage
        echo "There was a message: $msg";
    }
    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    //                  WampServerInterface Implementations
    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

    public function onOpen(ConnectionInterface $conn) {
        echo "New connection! ({$conn->resourceId}) \n";
    }
    public function onClose(ConnectionInterface $conn) {
        // The connection is closed, remove it, as we can no longer send it messages
        echo "Connection {$conn->resourceId} has disconnected \n";
    }
    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "There is an error ". $e->getMessage();
    }
    public function onSubscribe(ConnectionInterface $conn, $topic) {
        echo "New subscriber : $topic \n";
    }
    public function onUnSubscribe(ConnectionInterface $conn, $topic) {
        echo "Unsubscribed : $topic \n";
    }
    public function onCall(ConnectionInterface $conn, $id, $topic, array $params) {
        // In this application if clients send data it's because the user hacked around in console
        $conn->callError($id, $topic, 'You are not allowed to make calls')->close();
    }
    public function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible) {
        // In this application if clients send data it's because the user hacked around in console
        echo "Published $topic. \n";
        $conn->close();
    }
}

A: Finally found the answer. I forgot to enclosed that my development server is on Windows.
In my case, php cli is firewalled by windows and is blocked from accessing any networks and ports.
To fix this go to control panel -> windows firewall. Look for inbound  CLI this is most likely the PhP exe. Allow access to network and that should do the trick.


text:
Q: Extending Unnamed Types in Go So the following works:
type Individual [][]int
type Population []*Individual

What I'm trying to do is add a field to Population so I do the following
var p Population
p.Name = "human"

So I tried this:
type Individual [][]int
type Population struct {
     []*Individual
     Name string
}

But it doesn't work for me. How do I do this?

A: You should declare a name for the field of your struct:
package main

import (
    "fmt"
)

type Individual [][]int

type Population struct {
    Individual []*Individual // <- A name for field
    Name       string
}

func main() {
    var p Population
    p.Name = "human"
    fmt.Printf("%+v", p)
}

playground
=> {Individual:[] Name:human}


text:
Q: Nested JsonArrayRequests using volley Android Hello Everyone,
I m working on a survey App which inputs different types of answers for questions like single choice answers (radio button), multi choice answers (checkbox) or free text answers (EditText), I want to display all of the questions and related answers to users and for retrieving the data from MySQL I have used nested json array requests so I could be able to loop through questions and for each question loop through its options if it has.
Here is my codes:
public class MainActivity extends Activity {

    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();

    // questions json url
    private static final String url = "http://yakja.net/survey/fetch_questions.php";
    // options json url
    private static final String url2 = "http://yakja.net/survey/fetch_options.php";

    private ProgressDialog pDialog;
    public JSONArray myArray;
    public JSONObject obj,obj2;
    public RequestQueue request;
    public ViewGroup rdbtn;
    LinearLayout main,questionLayout,radio,editLayout,check,checkLayout;
    TextView ques;

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

        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();

        // Creating volley request obj
        JsonArrayRequest questions = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

        // Parsing json
        for (int i = 0; i < response.length(); i++) {
                try {

                 obj = response.getJSONObject(i);
                    main = (LinearLayout) findViewById(R.id.questions_view);
                    questionLayout = (LinearLayout) View.inflate(getApplicationContext(), R.layout.row_radio, null);
                    radio = (LinearLayout) View.inflate(getApplicationContext(), R.layout.radio, null);
                    editLayout = (LinearLayout) View.inflate(getApplicationContext(), R.layout.row_edittext, null);
                    check = (LinearLayout) View.inflate(getApplicationContext(),R.layout.row_check,null);
                    checkLayout = (LinearLayout) check.findViewById(R.id.check_add_layout);
                    ques = ((TextView) questionLayout.findViewById(R.id.q_title));
                    ques.setId(obj.getInt("q_id"));
                    ques.setText(obj.getString("q_text"));
                    main.addView(questionLayout);
                    rdbtn = (ViewGroup) radio.findViewById(R.id.radiogroup);

                if(obj.getInt("q_type_id")==1 || obj.getInt("q_type_id")==2) {
                    JsonArrayRequest options = new JsonArrayRequest(url2,
                            new Response.Listener<JSONArray>() {
                                @Override
                                public void onResponse(JSONArray response2) {
                                    Log.d(TAG, response2.toString());
                                    hidePDialog();
                                    myArray = new JSONArray();
                                    myArray=response2;
                                 try {
                                     if(obj.getInt("q_type_id")==1){
                                         for (int j = 0; j < myArray.length(); j++) {
                                             obj2 = myArray.getJSONObject(j);
                                             if (obj.getInt("q_id") == obj2.getInt("q_id")) {
                                            RadioButton button = new RadioButton(getApplicationContext());
                                             button.setId(j);
                                             button.setText(obj2.getString("option_text"));
                                             button.setTextColor(Color.parseColor("#666666"));
                                             rdbtn.addView(button);

                                             }
                                         }
                                       main.addView(radio);
                                     }
                                     else if(obj.getInt("q_type_id")==2)
                                     {
                                         Log.d("question type is", String.valueOf(obj.getInt("q_type_id")));
                                         for (int j = 0; j < myArray.length(); j++) {
                                             obj2 = myArray.getJSONObject(j);
                                             if(obj.getInt("q_id")==obj2.getInt("q_id")) {
                                                 CheckBox checkBox = new CheckBox(getApplicationContext());
                                                 checkBox.setId(obj2.getInt("o_id"));
                                                 checkBox.setText(obj2.getString("option_text"));
                                                 checkBox.setTextColor(Color.parseColor("#666666"));
                                                 LinearLayout.LayoutParams checkParams = new LinearLayout.LayoutParams(
                                                         LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                                                 checkParams.setMargins(10, 10, 10, 10);
                                                 checkParams.gravity = Gravity.START;
                                                 checkLayout.addView(checkBox, checkParams);
                                             }
                                         }

                                         main.addView(check);
                                     }
                                 }
                                 catch (JSONException e) {
                                     e.printStackTrace();
                                 }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            VolleyLog.d(TAG, "Error: " + error.getMessage());
                            hidePDialog();
                        }
                    });

                    request =  Volley.newRequestQueue(getApplicationContext());
                    request.add(options);
                }

                else if(obj.getInt("q_type_id")==3)
                {
                    Log.d("question type is", String.valueOf(obj.getInt("q_type_id")));

                    main.addView(editLayout);
                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                   }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();
            }
        });

        request =  Volley.newRequestQueue(getApplicationContext());
        request.add(questions);
        }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

}

Now the problem is that the radio buttons and check boxes are not displaying because the object of the first json array request which is the questions array data (obj) is null or empty inside the second request block.
I have searched alot to find the solution of this problem but unfortunately couldn't.
I would be very thankful if anybody could help me fix this problem.
Thank you in advance!
Updates
This is the questions json response
[{"q_id":"1","date_posted":"2016-11-02 16:13:44","q_type_id":"1","survey_id":"1","q_desc":"Self efficiency test","q_text":"I am strong enough to overcome life's struggles"},{"q_id":"2","date_posted":"2016-11-02 16:13:44","q_type_id":"1","survey_id":"1","q_desc":"Self efficiency test","q_text":"I can handle the situations that life brings"},{"q_id":"3","date_posted":"2016-11-02 16:18:39","q_type_id":"2","survey_id":"1","q_desc":"","q_text":"Which foods do you like the most?"},{"q_id":"4","date_posted":"2016-11-02 16:18:39","q_type_id":"3","survey_id":"1","q_desc":"","q_text":"who is your inspiration in your life?"}]

This is the options json response
[{"o_id":"1","option_text":"Strongly Agree","q_id":"1","option_no":"1"},{"o_id":"2","option_text":"Agree","q_id":"1","option_no":"2"},{"o_id":"3","option_text":"Disagree","q_id":"1","option_no":"3"},{"o_id":"4","option_text":"Strongly Disagree","q_id":"1","option_no":"4"},{"o_id":"5","option_text":"Strongly Agree","q_id":"2","option_no":"1"},{"o_id":"6","option_text":"Agree","q_id":"2","option_no":"2"},{"o_id":"7","option_text":"Disagree","q_id":"2","option_no":"3"},{"o_id":"8","option_text":"Strongly Disagree","q_id":"2","option_no":"4"},{"o_id":"9","option_text":"Manto","q_id":"3","option_no":"1"},{"o_id":"10","option_text":"Aashak","q_id":"3","option_no":"2"},{"o_id":"11","option_text":"Qabli","q_id":"3","option_no":"3"},{"o_id":"12","option_text":"bolani","q_id":"3","option_no":"4"},{"o_id":"13","option_text":"pizza","q_id":"3","option_no":"5"}]

And this is the obj.toString() result inside the second json request block
{"q_id":"4","date_posted":"2016-11-02 16:18:39","q_type_id":"3","survey_id":"1","q_desc":"","q_text":"who is your inspiration in your life?"}

And the above result shows repeatedly in each loop , you can see that the q_type_id is 3 always which should be 1 or 2.

A: Instead of using getInt("key") , use optInt("key", fallback_value); So in such scenario if you don't get the key still you will get some value like null or fallback_value.
And if you only want to use getInt(), you should first check with has("key") to check if the key is present in the JSONObject.
     obj = response.optJSONObject(i);
    if (obj!= null) {
     //Continue
    }


text:
Q: How to retrieve current extents of the location? How google is getting its maps zoom to current extents where we have located eg: If i am get hyderabad kphp on google maps its directly redirects to hyderabad city extents while opening a map , if it is chennai the if i open google maps in chennai the city extents automatically changes do it goes ? Is it based on IP address location or what?

A: I am no expert in this matter but I researched the topic and it turns out that there are several ways a website or a browser tracks our physical location like IP address, HTTP referrer, cookies etc. See this link:
http://www.howtogeek.com/115483/htg-explains-learn-how-websites-are-tracking-you-online/
Google maps estimates your location from your browser's location information.
You can even turn off the location information in your browser:
https://support.google.com/maps/answer/2839911?hl=en&authuser=0&p=newmaps_mylocation&rd=2


text:
Q: Django - Unit test object's delection does not work as expacted For 2 of my models, Users and Groups, I have a view to delete objects. The code is almost the same for each of them, it works in the application but unit test have different results: it works for users, not for groups.
Thanks in advance for your advises.
Here are the unit tests:
class TestAdmUsers(TestCase):
    def setUp(self):
        self.company = create_dummy_company("Société de test")
        self.user_staff = create_dummy_user(self.company, "staff", admin=True)
        self.usr11 = create_dummy_user(self.company, "user11")
        self.usr12 = create_dummy_user(self.company, "user12", admin=True)
        self.usr13 = create_dummy_user(self.company, "user13")

        self.client.force_login(self.user_staff.user)

    def test_adm_delete_user(self):
        test_usercomp_id = self.usr13.id
        usrcomp = UserComp.objects.get(user__username="user13")
        self.assertEqual(usrcomp.id, test_usercomp_id)

        url = reverse("polls:adm_delete_user", args=[self.company.comp_slug, test_usercomp_id])
        response = self.client.get(url)
        self.assertEqual(response.status_code, 302)
        with self.assertRaises(User.DoesNotExist):
            User.objects.get(id=test_usercomp_id)
        with self.assertRaises(UserComp.DoesNotExist):
            UserComp.objects.get(id=test_usercomp_id)

class TestAdmGroups(TestCase):
    def setUp(self):
        self.company = create_dummy_company("Société de test")

        self.user_staff = create_dummy_user(self.company, "staff", admin=True)
        self.usr11 = create_dummy_user(self.company, "user11")
        self.usr12 = create_dummy_user(self.company, "user12", admin=True)
        self.usr13 = create_dummy_user(self.company, "user13")
        self.usr14 = create_dummy_user(self.company, "user14")

        user_list = [self.usr11.id, self.usr12.id, self.usr13.id, self.usr14.id]
        users = UserComp.objects.filter(id__in=user_list)
        self.group1 = UserGroup.create_group({
            "company": self.company,
            "group_name": "Groupe 1",
            "weight": 40,
            },
            user_list=users)

    def test_adm_delete_group(self):
        test_group_id = self.group1.id
        grp = UserGroup.objects.get(group_name="Groupe 1")
        self.assertEqual(grp.id, test_group_id)

        url = reverse("polls:adm_delete_group", args=[self.company.comp_slug, test_group_id])
        response = self.client.get(url)
        self.assertEqual(response.status_code, 302)
        with self.assertRaises(UserGroup.DoesNotExist):
            UserGroup.objects.get(id=test_group_id)

The test runs fine for users, but I have this fali for groups:

Traceback (most recent call last):   File "D:\Mes
documents\Informatique\Developpement\Votes
AG\projet_votes\polls\tests_admin.py", line 354, in
test_adm_delete_group
UserGroup.objects.get(id=test_group_id) AssertionError: DoesNotExist not raised

Here are related models:
class UserComp(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Utilisateur")
    company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name="Société")
    phone_regex = RegexValidator(regex=r'^0[0-9]([ .-]?[0-9]{2}){4}$', message=("Format de numéro de téléphone invalide"))
    phone_num = models.CharField("numéro de téléphone", validators=[phone_regex], max_length=14, null=True, blank=True)
    is_admin = models.BooleanField("administrateur", default=False)

class UserGroup(models.Model):
    company = models.ForeignKey(
        Company, on_delete=models.CASCADE, verbose_name="société"
    )
    users = models.ManyToManyField(UserComp, verbose_name="utilisateurs", blank=True)
    group_name = models.CharField("nom", max_length=100)
    weight = models.IntegerField("poids", default=0)
    hidden = models.BooleanField(default=False)

And the views:
@user_passes_test(lambda u: u.is_superuser or (u.id is not None and u.usercomp.is_admin))
def adm_delete_user(request, comp_slug, usr_id):
    del_usr = User.objects.get(pk=usr_id)
    msg = "Utilisateur {0} {1} supprimé.".\
            format(del_usr.last_name, del_usr.first_name)

    User.objects.get(pk=usr_id).delete()

    messages.success(request, msg)
    return redirect("polls:adm_users", comp_slug=comp_slug)

@user_passes_test(lambda u: u.is_superuser or (u.id is not None and u.usercomp.is_admin))
def adm_delete_group(request, comp_slug, grp_id):
    del_grp = UserGroup.objects.get(pk=grp_id)
    msg = "Groupe {0} supprimé.".format(del_grp.group_name)

    UserGroup.objects.get(pk=grp_id).delete()

    messages.success(request, msg)
    return redirect("polls:adm_groups", comp_slug=comp_slug)

A: There is no logged in staff on your TestAdmGroups test class so it most likely does not run the delete, but fails on user_passes_test (which returns a 302).
So to fix, just log in the staff user in TestAdmGroups:
class TestAdmGroups(TestCase):
    ...
    self.client.force_login(self.user_staff.user)