Q: Obtaining HTTP session from a webservice We have a web application built on a Tomcat 6/WebWork/Hibernate/SQL Server stack.
One part of the web application is a network map built using
the Flare toolkit (the predecessor to Flare was Prefuse). The network map data is retrieved via a webservice call, say getData(). This call is made by the Flare application to retrieve XML data it needs to display. The webservice itself has been developed using Apache CXF.
I am trying to figure out how I can obtain the HTTP session within the method designated as a webservice. I need this because I need to maintain server side data across client (Flare application) webservice requests.
Do I need to get the HTTP session using the basic servlet APIs (knowing that the CXF servlet is being used)? Or is there API support at the CXF level?
The webservice itself runs within Tomcat 6.

A: This is actually part of the JAX-WS spec.  You can do
@Resource
WebServiceContext ctx;

....

ctx.getMessageContext().get(MessageContext.SERVLET_REQUEST)

to get the ServletRequest object from which you can do anything with the session or whatever.
Note: by default, JAX-WS clients don't maintain the session cookie. You have to set them to maintain the session:
((BindingProvider)proxy).getRequestContext()
  .put(BindingProvider.SESSION_MAINTAIN_PROPERTY, "true");


Q: How to add id (primary key) when insert a multi-dimensional php array into a mysql table? I created this mysql table:
CREATE TABLE earthquakes (
 id INT(20) AUTO_INCREMENT,
 idserial VARCHAR(30),
 milliseconds BIGINT,
 latitude FLOAT,
 longitude FLOAT,
 magnitude FLOAT,
 ipocentro FLOAT,
 source VARCHAR(4),
 region SMALLINT,
 PRIMARY KEY(id),
 INDEX indice_idserial(idserial),
 INDEX indice_milliseconds(milliseconds),
 INDEX indice_lat_lng(latitude,longitude),
 INDEX indice_magnitude(magnitude),
 INDEX indice_ipocentro(ipocentro)
);

And i want to insert a multi-dimensional php array into a mysql table but i dont'know like to add also id.
This is code to add array:
//MULTIDIMENSIONAL ARRAY
$array_database= array(
 array("2017-06-30-104",1498858541000,39.3322,-122.9027,2.11,0,"U",36)
);
//

foreach($array_database as $row) {
    $idserial_db= mysql_real_escape_string($row[0]);
    $milliseconds_db = mysql_real_escape_string($row[1]);
    $latitude_db = mysql_real_escape_string($row[2]);
    $longitude_db = mysql_real_escape_string($row[3]);
    $magnitude_db = mysql_real_escape_string($row[4]);
    $ipocentro_db= mysql_real_escape_string($row[5]);
    $source_db= mysql_real_escape_string($row[6]);
    $region_db= mysql_real_escape_string($row[7]);

    $valori_db[] = "('$idserial_db',$milliseconds_db,$latitude_db,$longitude_db,$magnitude_db,$ipocentro_db,'$source_db',$region_db)";
}
$values = implode(',', $valori_db);

mysqli_query($connessione,"INSERT INTO earthquakes (idserial,milliseconds,latitude,longitude,magnitude,ipocentro,source,region) VALUES $values");

So how i add ID ?
Thanks a lot and sorry for my english
EDIT
Maybe i should to add ID in this way:
 mysqli_query($connessione,"INSERT INTO earthquakes (id,idserial,milliseconds,latitude,longitude,magnitude,ipocentro,source,region) VALUES $values");

A: In the declaration:
//MULTIDIMENSIONAL ARRAY
$array_database= array(
 array("", "2017-06-30-104",1498858541000,39.3322,-122.9027,2.11,0,"U",36)
);
//

In the loop:
 $valori_db[] = "    ('','$idserial_db',$milliseconds_db,$latitude_db,$longitude_db,$magnitude_db,$ipocentro_db,'$source_db',$region_db)";

In the query:
mysqli_query($connessione,"INSERT INTO earthquakes  (id,idserial,milliseconds,latitude,longitude,magnitude,ipocentro,source,region) VALUES $values");


Q: Binning in python with missing values I have to create bins based on age. There are some missing values (nan) that need to be changed as "N/A and assign to a new category as "Not_Availabe". I filled in the missing values and then transformed the strings to float.
Students.loc[:, AGE']=Students.loc[:,AGE'].fillna("N/A")
Students.loc[:,AGE'] = Students.loc[:,'AGE'].str.replace('\%', '', regex=True).astype(float)

When I do this I get an error message as "could not convert string to float: 'N/A'.
Then, I tried to use pd.cut and assign bins and labels, but nothing work.
If I just do it an error message is "not supported between instances of 'int' and 'str*
Code:
Students.loc[:,'AGE']=Students.loc[:,'AGE'].fillna("unknown")

Students.loc[:,'AGE'] = Students.loc[:,'AGE'].str.replace('\%', '', regex=True).astype(float)

Students.loc[:,'AGE'] = Students.loc[:,'AGE'].cat.add_categories("Not_Available")

Students.loc[:,'AGE']=pd.cut(x=Students.loc[:,'AGE'],bins=[0,18,30,50,65,75,100],labels=["Unknown,"18 and under", "19-30", "31-50", "51-65", "66-75","75+"])

The output should be similar as:
Not_Availabe: 10
18 and under: 16
19-30: 80
31-50: 15
51-65: 5
66-75: 2
75+: 1

A: Convert the AGE column to float first, to avoid trying to convert string to float:
df['AGE'] = df['AGE'].str.replace('%', '', regex=True).astype(float)

I would suppose to then replace missing AGE values with -1 instead of 'N/A' to simplify binning.
df['AGE'] = df['AGE'].fillna(-1)

So, strictly speaking, it would not have been necessary here to do the conversion to float first to avoid the error message. Nevertheless this is still the sensible order of steps.
Then, define custom ranges and do the binning:
ranges = [-1, 0, 18, 30, 50, 65, 75, np.inf]
labels = ['Not_Availabe', '18 and under', '19-30', '31-50', '51-65', '66-75', '75+']
df['AGE_labeled'] = pd.cut(df['AGE'], bins=ranges, labels=labels)
# print the result
print(df['AGE_labeled'].value_counts())

Note: I created the following dummy data for testing (hope it fits the question, as no sample data was given)
import numpy as np
import pandas as pd
# dummy data
length = 1000
data = {
    'STUDENT_ID': np.random.randint(1000, 9999, length),
    'AGE': np.random.randint(0, 99, length),
}
df = pd.DataFrame (data)
df['AGE'] = df['AGE'].astype(str)  # convert AGE value to str (as I assume from your question that this is the case)
df.loc[df.sample(frac=0.1).index,'AGE'] = np.nan  # randomly set some values to nan


Q: PayPal API GetVerifiedStatus not working So I've been trying to implement PayPal's GetVerifiedStatus API into my website but have been running into the following error:
Fatal error: Uncaught Error: Class 'PayPal\Types\AA\GetVerifiedStatusRequest' not found in C:\xampp\htdocs\paypaltest\getversys.php:14 Stack trace: #0 {main} thrown in C:\xampp\htdocs\paypaltest\getversys.php on line 14
What could the problem be? What I was able to figure out was that that particular directory is missing. But I have no idea as to how to get it because I've looked for it without any success.
I've been using exactly the same code as given by the PayPal SDK. Here it is:
<?php
use PayPal\Service\AdaptiveAccountsService;
use PayPal\Types\AA\AccountIdentifierType;
use PayPal\Types\AA\GetVerifiedStatusRequest;
require_once('bootstrap.php');
$getVerifiedStatus = new GetVerifiedStatusRequest();

$accountIdentifier=new AccountIdentifierType();

$accountIdentifier->emailAddress = $_REQUEST['emailAddress'];
$getVerifiedStatus->accountIdentifier=$accountIdentifier;

$getVerifiedStatus->firstName = $_REQUEST['firstName'];

$getVerifiedStatus->lastName = $_REQUEST['lastName'];
$getVerifiedStatus->matchCriteria = $_REQUEST['matchCriteria'];

$service  = new AdaptiveAccountsService(Configuration::getAcctAndConfig());
try {

    $response = $service->GetVerifiedStatus($getVerifiedStatus);
} catch(Exception $ex) {
    require_once 'Common/Error.php';
    exit;
}

$ack = strtoupper($response->responseEnvelope->ack);
if($ack != "SUCCESS"){
    echo "Error ";
    echo "
";
    print_r($response);
    echo "
";
} else {
echo "
";
print_r($response);
echo "
";
echo "
";
echo "
Ack :
$ack

";
echo "
";
}

require_once 'Common/Response.php';

A: So I'm answering my own question here because I contacted PayPal tech support and was told that the GetVerifiedStatus API is now deprecated and can't be used.
This is the reason for the error.


Q: PHP echoing an Array and splitting it up I'm currently getting dates from a web page by using the following
foreach($returned_content->find('div.box-inset') as $article) {
    $item['dates'] = $article->find('div.important-dates', 0)->plaintext;
    $articles[] = $item;
}

var_dump($articles);

Which will output the following
array(2) { [0]=> array(1) { ["dates"]=> string(235) " Important Dates Expires On October 28, 2013 Registered On October 29, 2012 Updated On October 29, 2012 " } [1]=> array(1) { ["dates"]=> NULL } }

I would ideally like to get the results to lay out as listed like so

*

*Important Dates

*Expires On October 28, 2013

*Registered On October 29, 2012

*Updated On October 29, 2012

But I am lost with getting the content to echo correctly as echo $articles just produces Array and I have never had such an Array before like this one

A: try:
echo $articles[0]["dates"];

A: foreach($returned_content->find('div.box-inset') as $article) {
    $item['dates'] = $article->find('div.important-dates', 0)->plaintext;
    $articles[] = $item['dates'];
}

you cannot use echo to output array
foreach($articles as $strarticle)
{
 echo $strarticle;
}


Q: Css Popup alert in button, instead input text How do i customize css so the popup alert just like this but instead alert popup focus in a button.

i have use this kind of validation on text box

Judul Laporan

         <input type="email" class="form-control" id="judul_laporan" >

<button type="button" id="save_laporan"></button>

JQuery
 $("#save_laporan").click(function(){
  var judul_laporan = $('input[name="judul_laporan"]');
  if(judul_laporan.val() == ''){
    judul_laporan.parent().parent().addClass('has-error');
    $('#warnlaporan').text("Judul Laporan Belum Ada");
    judul_laporan.focus();
    result
  }else{
    judul_laporan.parent().parent().removeClass('has-error');
     $('#warnlaporan').text("");
  }

But i dont know how to make a popup alert likes the image ( and it should be button )

A: You can see the x3schools' documentation. It gives you a sample popup at the top of a div.
This code opens a popup:

// When the user clicks on
, open the popup
function myFunction() {
    var popup = document.getElementById("myPopup");
    popup.classList.toggle("show");
}
/* Popup container */
.popup {
    position: relative;
    display: inline-block;
    cursor: pointer;
}

/* The actual popup (appears on top) */
.popup .popuptext {
    visibility: hidden;
    width: 160px;
    background-color: #555;
    color: #fff;
    text-align: center;
    border-radius: 6px;
    padding: 8px 0;
    position: absolute;
    z-index: 1;
    bottom: 125%;
    left: 50%;
    margin-left: -80px;
}

/* Popup arrow */
.popup .popuptext::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: #555 transparent transparent transparent;
}

/* Toggle this class when clicking on the popup container (hide and show the popup) */
.popup .show {
    visibility: visible;
    -webkit-animation: fadeIn 1s;
    animation: fadeIn 1s
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
    from {opacity: 0;}
    to {opacity: 1;}
}

@keyframes fadeIn {
    from {opacity: 0;}
    to {opacity:1 ;}
}

Click me!
  Popup text...

You also can use microtip, it is a pretty library witch give you the opportunity to create simply popup. This is the only declaration: <button aria-label="Hey tooltip!" data-microtip-position="top-left" role="tooltip">. However, you have to download a package (just 1kb) with rpm in your server.


Q: ASP.NET Razor - How to display data from multiple tables in database Sorry if the question isn't worded well but I am very confused and it is very late but I will do my best to explain. So I am trying to display all of the orders from my database into a table without using the Entity Framework. the problem is when I go to orders/getAllOrders I just get a big error that says "the view" then a bunch of

2	Javier	1	Groovestring	3.950000
etc..

with my data in it but I don't know how to display it properly. I know my query is working fine and my data is being retrieved fine but I am stumped on displaying it
This what I currently have for my controller.
namespace Website.Controllers
{
public class OrderController : Controller
{

    private static bool CanConnectToDb()
    {
        var cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
        try
        {
            cnn.Open();
            return true;
        }
        catch (Exception exception)
        {
            return false;
        }
        finally
        {
            if (cnn.State != ConnectionState.Closed)
                cnn.Close();
        }
    }

    public ActionResult getAllOrders()
    {
        // Connect to Database
        var cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
        cnn.Open();
        // Create Command
        SqlCommand cmd = new SqlCommand(
            @"SELECT CustomerOrderId, FirstName ,ProductId, [Name], Price
                FROM OrderProduct AS o
                INNER JOIN CustomerOrder co ON co.id = o.CustomerOrderId
                INNER JOIN Product p ON p.Id = o.ProductId
                INNER JOIN Customer c ON c.Id = co.CustomerId
                ORDER BY ProductId"
            );

        cmd.Connection = cnn;
        string store = "";
        // Read from Database
        SqlDataReader reader = cmd.ExecuteReader();

        var orders = new OrderIndexViewModel();
        while (reader.Read())
        {
            orders.CustomerOrderId = reader.GetInt32(0);
            orders.FirstName = reader.GetString(1);
            orders.ProductId = reader.GetInt32(2);
            orders.Name = reader.GetString(3);
            orders.Price = reader.GetDecimal(4);
            store += "
" + orders.CustomerOrderId + "	" + orders.FirstName + "	" + orders.ProductId + "	" + orders.Name + "	" + orders.Price + "
";
        }
        cnn.Close();
        return View(store);
    }
  }
}

EDIT: When I change the return to
rerturn View(orders);

I get this error
The model item passed into the dictionary is of type 'Website.Models.OrderIndexViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Website.Models.OrderIndexViewModel]'.

This is my Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Website.Models
{
    public class OrderIndexViewModel
    {
        public int CustomerOrderId { get; set; }
        public string FirstName { get; set; }
        public int ProductId { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}

And then finally this is my view
@model IEnumerable<Website.Models.OrderIndexViewModel>
@{
    ViewBag.Title = "getAllOrders";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

getAllOrders

    @Html.ActionLink("Create New", "Create")

            Customer Oder Id

            First Name

            ProductId

            Name

            Price

    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.CustomerOrderId)

                @Html.DisplayFor(modelItem => item.FirstName)

                @Html.DisplayFor(modelItem => item.ProductId)

                @Html.DisplayFor(modelItem => item.Name)

                @Html.DisplayFor(modelItem => item.Price)

                @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })

    }

Any help will be thoroughly appreciated

A: You sended string to model but you must send collection to model and then show in table

A: Your view is expecting IEnumerable<Website.Models.OrderIndexViewModel> as the model but you are passing it a single instance of Website.Models.OrderIndexViewModel.
This might be another bug in your code, as this will only ever render the last item from the select statement. So you'll want something like this, which will render a row for each result:
var orders = new List<OrderIndexViewModel>();
    while (reader.Read())
    {
        var order = new OrderIndexViewModel();
        order.CustomerOrderId = reader.GetInt32(0);
        order.FirstName = reader.GetString(1);
        order.ProductId = reader.GetInt32(2);
        order.Name = reader.GetString(3);
        order.Price = reader.GetDecimal(4);
        orders.Add(order);
    }
    cnn.Close();
    return View(orders);


Q: couchdb views os_process_error - big documents I have a database that we're filling up with documents, some of which are 10 KB, and some of which that are ~70 MB in size.
Any view that tries to load these large documents fails with error: {"error":"os_process_error","reason":"{exit_status,0}"}, even this elementary one:
function(doc) {
    emit(null, "test");
}

os_process_error is set to 35000, but calling the view dies in ~15 seconds:
time curl -X GET http://localhost:5984/portal_production/_design/all_data_keys/_view/view1
{"error":"os_process_error","reason":"{exit_status,0}"}

real    0m15.907s
user    0m0.016s
sys 0m0.000s

From a few other threads, seems like this is related stack size: couchdb issue thread. I've applied this patch to increase the stack size, although I couldn't find a reference to the method's value. So I'm shooting in the dark a bit.
Soooo.... the real question is: what is the correct approach for using views on large documents? I'm sure I'm not the first to have this problem.

A: You'd hit couchjs stack size limit. If you're using CouchDB 1.4.0+ his size is limited by 64 MiB by default. You may increase it by specifying -S <number-of-bytes> option for JavaScript query server in CouchDB config. For instance, to set stack size to 128 MiB your config value will looks like:
[query_servers]
javascript = /usr/bin/couchjs -S 134217728 /usr/share/couchdb/server/main.js

Note, that /usr/bin/couchjs may be different for you depending on your OS. After adding this changes you need to restart CouchDB.
If you'll try to update JavaScript query server config though HTTP API, make sure to kill all couchjs processes from shell to let them apply changes.
If your CouchDB version is <1.4 try to upgrade first.


Q: How to pickle an instance of a class which is written inside a function? Suppose I have this snippet inside a module
def func(params):
   class MyClass(object):
       pass

How can I pickle an instance of the class MyClass ?

A: You can't, because picklable object's class definitions must reside in an imported module's scope. Just put your class inside module scope and you are good to go.
That said, in Python there is very little that can't be achieved with a bit of hacking the insides of the machinery (sys.modules in this case), but I wouldn't recommend that.

A: The MyClass definition is local variable for the func function. You cannot directly create an instance of it, but you can map it's functions to a new class, and then to use the new class as it is the original one. Here's an example:
def func(params):
    class MyClass(object):
        some_param = 100
        def __init__(self, *args):
            print "args:", args
        def blabla(self):
            self.x = 123
            print self.some_param
        def getme(self):
            print self.x

func.func_code is the code of the func function, and func.func_code.co_consts[2] contains the bytecode of the MyClass definition:
In : func.func_code.co_consts
Out:
(None,
 'MyClass',
 <code object MyClass at 0x164dcb0, file "<ipython-input-35-f53bebe124be>", line 2>)

So we need the bytecode for the MyClass functions:
In : eval(func.func_code.co_consts[2])
Out:
{'blabla': <function blabla at 0x24689b0>,
 '__module__': '__main__',
 'getme': <function getme at 0x2468938>,
 'some_param': 100,
 '__init__': <function __init__ at 0x219e398>}

And finally we create a new class with metaclass, that assigns the MyClass functions to the new class:
def map_functions(name, bases, dict):
    dict.update(eval(func.func_code.co_consts[2]))
    return type(name, bases, dict)

class NewMyClass(object):
    __metaclass__ = map_functions

n = NewMyClass(1, 2, 3, 4, 5)
>> args: (1, 2, 3, 4, 5)

n.blabla()
>> 100

n.getme()
>> 123

A: You can work around the pickle requirement that class definitions be importable by including the class definition as a string in the data pickled for the instance and exec()uting it yourself  when unpickling by adding a __reduce__() method that passes the class definition to a callable. Here's a trivial example illustrating what I mean:
from textwrap import dedent

# Scaffolding
definition = dedent('''
    class MyClass(object):
        def __init__(self, attribute):
            self.attribute = attribute
        def __repr__(self):
            return '{}({!r})'.format(self.__class__.__name__, self.attribute)
        def __reduce__(self):
            return instantiator, (definition, self.attribute)
''')

def instantiator(class_def, init_arg):
    """ Create class and return an instance of it. """
    exec(class_def)
    TheClass = locals()['MyClass']
    return TheClass(init_arg)

# Sample usage
import pickle
from io import BytesIO

stream = BytesIO()  # use a memory-backed file for testing

obj = instantiator(definition, 'Foo')  # create instance of class from definition
print('obj: {}'.format(obj))
pickle.dump(obj, stream)

stream.seek(0) # rewind

obj2 = pickle.load(stream)
print('obj2: {}'.format(obj2))

Output:
obj: MyClass('Foo')
obj2: MyClass('Foo')

Obviously it's inefficient to include the class definition string with every class instance pickled, so that redundancy may make it impractical, depending on the the number of class instances involved.

A: This is somewhat tough to do because the way Pickle does with objects from user defined classes by default is to create a new instance of the class - using the object's __class__.__name__ attribute to retrieve its type in the object's original module. Which means: pickling and unpickling only works (by default)  for classes that have well defined names in the module they are defined.
When one defines a class inside a function, usulay there won't be a module level (i.e. global)  variable holding the name of each class that was created inside the function.
The behavior for pickle and npickle can be customized through the __getstate__ and __setstate__  methods on the class - check the docs - but even them, doing it right for dynamic class can be tricky , but I managed to create  a working implementation of it for another S.O. question - -check my answer here:
Pickle a dynamically parameterized sub-class


Q: Problem fitting data If I have the following data:
Tgexpandlit={{57.8505, 1.36339}, {58.1254, 1.0671}, {58.7645, 0.646116}, {59.221,
  0.349873}, {60.6788, -0.273668}, {62.7712, -0.803456}, {64.3186, \
-1.28659}, {64.3186, -1.28659}, {66.5927, -1.83193}, {68.7745, \
-2.20572}, {71.0471, -2.57948}, {72.7748, -2.92218}, {74.3203, \
-3.20255}, {76.138, -3.45164}, {78.5006, -3.74739}, {80.2275, \
-3.99651}, {81.4994, -4.12096}, {82.6805, -4.24544}, {83.4074, \
-4.32324}, {84.1346, -4.44783}, {85.1342, -4.57236}, {86.3147, \
-4.61885}, {87.1328, -4.75901}, {88.2229, -4.85232}, {88.859, \
-4.93014}, {90.04, -5.03902}, {91.4019, -5.06986}, {92.2198, \
-5.17884}, {93.4007, -5.28772}, {93.3998, -5.17853}, {94.4905, \
-5.34983}, {96.4889, -5.50529}, {97.3069, -5.62986}, {99.1234, \
-5.75417}, {99.2131, -5.62936}, {99.8498, -5.76958}, {101.848, \
-5.87825}, {101.847, -5.83145}, {102.575, -5.95605}, {103.936, \
-5.98689}, {105.389, -6.0489}, {53.05, 1.02729}, {54.3782,
  0.553702}, {54.2158,
  0.0303926}, {56.9221, -0.439578}, {59.0303, -0.956926}, {62.3764, \
-1.42534}, {66.8545, -1.9367}, {69.3497, -2.40747}, {70.7512, \
-2.70496}, {71.6037, -2.92466}, {51.2734, 1.02255}, {52.1209,
  0.547695}, {52.3608,
  0.0254565}, {55.4547, -0.443448}, {56.8651, -0.962607}, {59.8218, \
-1.43198}, {65.7229, -1.9396}, {69.0066, -2.40835}, {70.6466, \
-2.70522}, {71.5932, -2.92468}, {54.5032, 1.03115}, {54.9453,
  0.555205}, {56.6674,
  0.0368729}, {57.758, -0.437381}, {60.2665, -0.9537}, {62.7824, \
-1.42429}, {66.8842, -1.93663}, {69.7442, -2.40648}, {71.3554, \
-2.70343}, {72.963, -2.92124}, {53.05, 1.02729}, {54.4775,
  0.553965}, {54.7589,
  0.0318322}, {58.2357, -0.436128}, {60.1001, -0.954134}, {63.2519, \
-1.42308}, {66.8886, -1.93662}, {69.3662, -2.40743}, {70.8179, \
-2.70479}, {71.7396, -2.92431}, {51.2734, 1.02255}, {52.2206,
  0.547961}, {52.8968,
  0.0268856}, {56.701, -0.44016}, {57.9147, -0.959849}, {60.6854, \
-1.42973}, {65.7529, -1.93952}, {69.0215, -2.40831}, {70.7068, \
-2.70507}, {71.7159, -2.92437}, {54.5032, 1.03115}, {55.0455,
  0.55547}, {57.1738,
  0.0382057}, {59.0075, -0.434107}, {61.2621, -0.95111}, {63.6165, \
-1.42214}, {66.9159, -1.93655}, {69.7599, -2.40644}, {71.4196, \
-2.70327}, {73.0906, -2.92092}, {51.139, 2.32322}, {52.2163,
  1.80322}, {53.1749, 1.32866}, {53.6977, 1.02902}, {54.1641,
  0.808406}, {54.7846, 0.554779}, {55.0134, 0.333536}, {50.6163,
  2.32182}, {52.0102, 1.80267}, {52.6447, 1.32724}, {53.6972,
  1.02902}, {54.1492, 0.808367}, {54.1878, 0.553197}, {54.8392,
  0.333075}, {52.6762, 2.32733}, {53.7473, 1.8073}, {54.0918,
  1.33109}, {55.3849, 1.03349}, {55.5279, 0.812018}, {55.6434,
  0.557051}, {55.9373, 0.335978}}

and I am fitting it to a function such as:
   Eappitz = 99.925; q0 = 10/60; Tg0itz = 54.26 + 273.15; Aitz =
 Log10[(Tg0itz^2)/(q0*Eappitz*1000)];

(nlm = NonlinearModelFit[
    Tgexpandlit, {((-C11 (T + 273.15 - Tg0itz))/(C22 + (T + 273.15 -
            Tg0itz))) + Aitz}, {C11, C22}, T]) // Normal

nlm["BestFitParameters"]

C1itz = C11 /. nlm["BestFitParameters"](*7.76*);
C2itz = C22 /. nlm["BestFitParameters"](*19.22*);

fitz[T_] := ((-C1itz (T + 273.15 - Tg0itz))/(C2itz + (T + 273.15 -
        Tg0itz))) + Aitz

I get a very bad fit such as the following:
Show[Plot[fitz[T], {T, -5, 108}, Frame -> True, FrameStyle -> 16,
  Axes -> False, GridLines -> Automatic,
  GridLinesStyle -> Lighter[Gray, .8],
  FrameTicks -> {Automatic, Automatic}, ImageSize -> Large,
  LabelStyle -> {Black, Bold, 14}, PlotStyle -> Blue,
  PlotRange -> {All, {-6.4, 6}}]

 , ListPlot[Tgexpandlit]]

Which gives:

However, If I only use the first portion of the same data such as:
Tgexpandlit={{57.8505, 1.36339}, {58.1254, 1.0671}, {58.7645, 0.646116}, {59.221,
  0.349873}, {60.6788, -0.273668}, {62.7712, -0.803456}, {64.3186, \
-1.28659}, {64.3186, -1.28659}, {66.5927, -1.83193}, {68.7745, \
-2.20572}, {71.0471, -2.57948}, {72.7748, -2.92218}, {74.3203, \
-3.20255}, {76.138, -3.45164}, {78.5006, -3.74739}, {80.2275, \
-3.99651}, {81.4994, -4.12096}, {82.6805, -4.24544}, {83.4074, \
-4.32324}, {84.1346, -4.44783}, {85.1342, -4.57236}, {86.3147, \
-4.61885}, {87.1328, -4.75901}, {88.2229, -4.85232}, {88.859, \
-4.93014}, {90.04, -5.03902}, {91.4019, -5.06986}, {92.2198, \
-5.17884}, {93.4007, -5.28772}, {93.3998, -5.17853}, {94.4905, \
-5.34983}, {96.4889, -5.50529}, {97.3069, -5.62986}, {99.1234, \
-5.75417}, {99.2131, -5.62936}, {99.8498, -5.76958}, {101.848, \
-5.87825}, {101.847, -5.83145}, {102.575, -5.95605}, {103.936, \
-5.98689}, {105.389, -6.0489}}

I now get a great fit like:

Question:

*

*Why cannot use all the data or how can I arrange the data so that all the data can be used to get the fit? (as opposed to only part of the same data)

A: It appears that you have 9 different sets of data probably all under slightly different conditions.  You really need to account for that.  If you explained that here, you might get an appropriate solution.  Otherwise, you might try CrossValidated and ask about nonlinear mixed models (along with how the data was collected).
In the meantime I'll just expand on why @MarcoB 's advice is essential.
With not-so-good starting values the iterative algorithm won't converge or you'll land on a local minimum rather than the global minimum (assuming there is a global minimum) of the total sum of squares.
The default starting value is 1 if you don't specify a starting value.  Here are the results for using @MarcoB 's starting values and what happens when the default starting values are used:
nlm = NonlinearModelFit[Tgexpandlit,
  {((-C11 (T + 273.15 - Tg0itz))/(C22 + (T + 273.15 - Tg0itz))) + Aitz},
  {{C11, 17}, {C22, 70}}, T];
nlm["BestFitParameters"]
(* {C11 -> 13.5547, C22 -> 48.2289} *)

nlm1 = NonlinearModelFit[Tgexpandlit,
  {((-C11 (T + 273.15 - Tg0itz))/(C22 + (T + 273.15 - Tg0itz))) + Aitz},
  {{C11, 1}, {C22, 1}}, T];
nlm1["BestFitParameters"]
(* {C11 -> 1.81295, C22 -> 0.754181} *)

Because there are only 2 parameters to estimate we can construct a contour plot of the sum of squares for values of C11, and C22 showing the starting and ending values:
ss = Total[(Tgexpandlit[[All, 2]] - (((-C11 (Tgexpandlit[[All, 1]] + 273.15 -
  Tg0itz))/(C22 + (Tgexpandlit[[All, 1]] + 273.15 - Tg0itz))) + Aitz))^2];

Show[ContourPlot[ss, {C11, 0.5, 30}, {C22, 0.1, 100},
  ImageSize -> Large,
  Contours -> {25, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400,
    500, 600, 700, 800, 900, 1000, 2000},
  ScalingFunctions -> {"Log", "Log"}, ContourShading -> None,
  ContourStyle -> LightGray,
  FrameLabel -> (Style[#, 18, Bold] &) /@ {"C11", "C22"},
  PlotPoints -> 100],
 ListLogLogPlot[{
   {{17, 70}},
   {{C11, C22} /. nlm["BestFitParameters"]},
   {{C11, C22} /. nlm["BestFitParameters"], {17, 70}},
   {{1, 1}},
   {{C11, C22} /. nlm1["BestFitParameters"]},
   {{C11, C22} /. nlm1["BestFitParameters"], {1, 1}}
   }, PlotStyle -> {Green, Red, Black, Green, Red, Black},
  Joined -> {False, False, True, False, False, True},
  PlotLegends -> {"Starting value", "Ending value"}]]

One can see that there are several local minima that one will land on depending on the starting values.

A: With a simple rational model together with Method -> "NMinimize" (no need for starting values!) the approximation is quite well!
Try
nlm = NonlinearModelFit[Tgexpandlit, {a + b/(1 + c T)}, {a, b, c}, T,Method -> "NMinimize"]

Show[{ListPlot[Tgexpandlit], Plot[nlm[T], {T, 50, 110}]},PlotRange -> All]


Q: Join DataFrames, but keep only columns of one I have a DataFrame df1:
| ID | A |
---------
| 1  | 4 |
| 1  | 4 |
| 2  | 1 |
| 2  | 3 |
| 3  | 2 |

and a DataFrame df2:
| ID | B |
---------
| 1  | 2 |
| 2  | 2 |
| 3  | 9 |

I want to (left) join these, but only want to keep the columns of df2.
What is a short and easy solution for this?
The resulting DataFrame should look somehow like this:
|ID | B |
---------
| 1 | 2 |
| 1 | 2 |
| 2 | 2 |
| 2 | 2 |
| 3 | 9 |

A: You could slice the ID column from df1 as a DataFrame and merge on ID:
import pandas as pd

df1 = pd.DataFrame({'ID': [1, 1, 2, 2, 3],
                    'A': [4, 4, 1, 2, 3]
                    })

df2 = pd.DataFrame({'ID': [1, 2, 3],
                    'B': [2, 2, 9]
                    })

merged = df1[['ID']].merge(df2, how='left')

This returns a DataFrame of the form:
   ID  B
0   1  2
1   1  2
2   2  2
3   2  2
4   3  9

A: perform the join and pick up only columns in df2
df2.merge(df1, on='ID')[df2.columns]
# output:
   B  ID
0  2   1
1  2   1
2  2   2
3  2   2
4  9   3


Q: How to refactor models without breaking WPF views? I've just started learning WPF and like the power of databinding it presents; that is ignoring the complexity and confusion for a noob.
My concern is how do you safely refactor your models/viewmodels without breaking the views that use them?
Take the following snippet of a view for example:
<Grid>
    <ListView ItemsSource="{Binding Contacts}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding Path=FirstName}"/>
                <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding Path=FirstName}"/>
                <GridViewColumn Header="DOB" DisplayMemberBinding="{Binding Path=DateOfBirth}"/>
                <GridViewColumn Header="# Pets" DisplayMemberBinding="{Binding Path=NumberOfPets}"/>
                <GridViewColumn Header="Male" DisplayMemberBinding="{Binding Path=IsMale}"/>
            </GridView>

        </ListView.View>
    </ListView>
</Grid>

The list is bound to the Contacts property, IList(Of Contact), of the windows DataSource and each of the properties for a Contact is bound to a GridViewColumn.
Now if I change the name of the NumberOfPets property in the Contact model to PetCount the view will break. How do I prevent the view breaking?

A: Unfortunatly this is a known issue in WPF, the xaml is not taken into account when you refactor the entities behind the bindings. I have been making use of third party refactoring tools such as resharper or coderush to solve the problem, they tend to handle it better than the built in refactor function in visual studio.

A: If you really don't want to change the view (for whatever reasons) you could leave the NumberOfPets property in the original ViewModel and set its getter to the PetCount property of the refactored ViewModel, there fore this won't break the View.


Q: For loop brackets - C like syntax When i am using the below syntax to iterate why two brackets are needed ?
for (( expr1; expr2; expr3 ))
do
 command1
 command2
 ..
done

and the below code doesn't work ? and throws error "syntax error near unexpected token `('"
for ( expr1; expr2; expr3 )
do
 command1
 command2
 ..
done

A: The reason for this is ( has a different meaning. From the bash manpage:

        (list) list  is  executed  in  a subshell environment
               (see COMMAND EXECUTION ENVIRONMENT below).  Variable
               assignments and builtin commands that affect the shell's
               environment do not remain in effect  after  the  command
               completes. The return status is the exit status of list.

        ((expression))
               The expression is evaluated according to the rules
               described below under ARITHMETIC EVALUATION.  If
               the  value  of the  expression  is non-zero, the return
               status is 0; otherwise the return status is 1.  This is
               exactly equivalent to let "expression".


Q: Find out whether solutions exist rather than full-blown solution search I have some quadratics, and I am trying to find out whether there exist solutions in the integers. The following tells me that the first does, wheraeas the second doesn't:
Solve[2 + 4 x + 6 x^2 == 4 - 7 y + 3 y^2 && x < 0 && y < 0, x, Integers]
Solve[12 + 15 x + 9 x^2 == 4 - 7 y + 3 y^2 && x < 0 && y < 0, x, Integers]

This is fine. However, I am not particularly interested in what the solutions are, just whether a solution exists. I have a lot of these, and it is taking a long time to calculate, since it is trying to find a solution for each one.
Generally, if there isn't a solution, it spits out {} quite quickly (which is all I really want to know). Is it possible to find out whether such equations have integer solutions, without having to evaluate each one, and hence speed up calculation times?

A: I hope there is a better solution for you, but why not try something like this:
TimeConstrained[Solve[12 + 15 x + 9 x^2 == 4 - 7 y + 3 y^2 && x < 0 && y < 0, x, Integers], 0.01]

You might optimize the time to abort for your machine.


Q: Host HTML5 site on Google Cloud Storage I'm trying to host my HTML5 site on Google Cloud Storage.
When I load the site locally, all the animations work. When I upload it to Google Cloud Storage and access it, my CSS animations don't work.
The CSS files are in css/theme.css in my storage bucket and the HTML file points to it like this:
<link rel="stylesheet" href="css/theme.css">
<link rel="stylesheet" href="css/theme-elements.css">
<link rel="stylesheet" href="css/theme-animate.css">

A: Make sure the Content-Type metadata is set properly for your CSS files via the Developer Console.
If not, you should manually edit the metadata to set the proper type, which is text/css for CSS files. If the type is neither not specified nor auto-detected at upload time, Google Cloud Storage serves files as binary/octet-stream which may prevent the browser from properly rendering it.
Alternatively, you can also specify the MIME type in HTML, e.g.,
<link rel="stylesheet" href="css/theme.css" type="text/css">

to make sure that the browser handles it appropriately.


Q: Probability regarding random marbles chosen from a bag I am unsure if my thought process for these questions is correct.

Susie has a bag of marbles containing 3 Red, 7 Green, and 10 Blue marbles.

*

*What is the probability of picking 5 marbles and getting at least one red marble? Calculate the probability (a) with replacement, and (b) without replacement.

What I have tried so far is that with replacement, it would be $$1- \left(\frac{17}{20}\right)^5 = 0.556$$
For without replacement, I tried $$1- \left(\frac{17}{20} \times \frac{16}{19} \times \frac{15}{18} \times \frac{14}{17} \cdot \frac{13}{16}\right) = 0.601$$

*Calculate the probability of picking $8$ marbles and getting exactly $4$ green and $4$ blue (a) with replacement and (b) without replacement.

What I have tried for this so far is that with replacement, it would be $$\left(\frac{7}{20}\right)^4 \cdot \left(\frac{10}{20}\right)^4 \cdot 8^2 = 0.066$$
For without replacement, I am unsure so I just assumed it would follow the same as 1(b) based off of 1(a).

A: You solved both parts of the first problem correctly.
For the second part of the first problem, where you are selecting without replacement, you could also express the answer in the form
$$\Pr(\text{at least one red}) = 1 - \Pr(\text{no reds}) = 1 - \frac{\dbinom{17}{5}}{\dbinom{20}{5}}$$
where the denominator counts the number of ways of selecting five of the $20$ marbles in the bag and the numerator of the subtracted term counts the number of ways of selecting $5$ of the $20 - 3 = 17$ non-red marbles in the bag.

Susie has a bag of marbles containing $3$ red, $7$ green, and $10$ blue marbles.  Calculate the probability of picking $8$ marbles and getting exactly $4$ green and $4$ blue with replacement.

Since the selections are made with replacement, the probability of selecting a particular color is the same for each outcome.  We can use the multinomial distribution.  The probability of selecting exactly $r$ red, $g$ green, and $b$ blue marbles from $3$ red, $7$ green, and $10$ blue marbles when $n = r + g + b$ marbles are selected from the bag with replacement is
$$\Pr(r, g, b) = \binom{n}{r, g, b}\left(\frac{3}{20}\right)^r\left(\frac{7}{20}\right)^g\left(\frac{10}{20}\right)^b$$
Substituting $8$ for $n$, $0$ for $r$, $4$ for $g$, and $4$ for $b$ yields
$$\Pr(r, g, b) = \binom{8}{0, 4, 4}\left(\frac{3}{20}\right)^0\left(\frac{7}{20}\right)^4\left(\frac{10}{20}\right)^4$$

Susie has a bag of marbles containing $3$ red, $7$ green, and $10$ blue marbles.  Calculate the probability of picking $8$ marbles and getting exactly $4$ green and $4$ blue without replacement.

Since the marbles are selected without replacement, we can use the multivariate hypergeometric distribution.  The probability of selecting exactly $r$ red, $g$ green, and $b$ blue marbles when $n = r + g + b$ marbles are selected from the $3$ red, $7$ green, and $10$ blue marbles in the bag without replacement is
$$\Pr(r, g, b) = \frac{\dbinom{3}{r}\dbinom{7}{g}\dbinom{10}{b}}{\dbinom{20}{n}}$$
Can you finish?


Q: Compiling custom kernel I am interested in compiling a custom kernel in Ubuntu 20.04 so I can use the fingerprint scanner in my hp envy x360. Also I want to learn how to learn the process. Where do I start? How difficult is it? Any pointers and/or advice would be greatly appreciated.

A: From memory:

*

*Log in as root.

*Download the kernel sources from kernel.org and uncompress them to /usr/src/.

*Open a shell in the directory you just unpacked and run:
make oldconfig && \
make xconfig && \
make && \
make modules && \
make install && \
make modules_install

*Edit your grub configuration and reboot.
If you're not running X then change make xconfig to make menuconfig or make config.
If you want things to go a bit quicker, change make to make -j4 to run 4 tasks in parallel (change 4 to the number of cores your machine has).  The same applies to the make modules command.


Q: MVC Binding List of Objects in Object I'm trying to dynamically build a table that needs to be bound to a ViewModel on form submission.
First item is the Action the form is submitting to.  Then the Parent ViewModel and then the child ViewModel.  Below those are two text fields representing the data I need bound.
When I submit the form all the other fields from the page are bound to their respective property but the complex object of ProgramViewModels is not.
What am I missing?
public ActionResult Add(AddEntityViewModel viewModel){
 Code that does something
}

 public class AddEntityViewModel
    {
    public IList<int> Counties { get; set; }
    public IList<ProgramViewModel> Programs { get; set; }
    public IList<int> Regions { get; set; }
    public string EntityName { get; set; }

    public bool IsValid()
    {
        if (string.IsNullOrEmpty(EntityName))
            return false;

        if (Counties == null || Counties.Count == 0)
            return false;

        if (Programs == null || Programs.Count == 0)
            return false;

        if (Regions == null || Regions.Count == 0)
            return false;

        return true;
    }
}

public class ProgramViewModel
{
    public int Id;
    public string SystemId;
}

<input type="hidden" id="Programs[0]__Id" name="Programs[0].Id" data-programid="3" value="3">
<input type="text" id="Programs[0]__SystemId" name="Programs[0].SystemId" style="width:100%" maxlength="50">

Update:
Changed the fields to properties after adiga's answer. But that too did not fix the issue.
public class ProgramViewModel
{
    public int Id { get; set; }
    public string SystemId { get; set; }
}

A: Your ProgramViewModel contains fields. Change them to properties.
public class ProgramViewModel
{
    public int Id { get; set; }
    public string SystemId { get; set; }
}

The DefaultModelBinder uses reflection and binds only the properties and not fields.

A: If you have a List of a object, you should be performing a foreach instruction to get all of them:
<% foreach(var x in values) { %>

hello <%= x.name %>

<% } %>


Q: Evaluating worst case RAM effective bandwidth with discontinous memory access I'm trying to evaluate the effective memory "bandwidth" (throughput in bytes of data being treated) from main memory to CPU in a worst case scenario: the RAM cache is made totally inefficient due to long distances in the successive addresses being treated. As far as I understand what matters here is the RAM latency and not its bandwidth (which is the throughput when transferring big continuous blocks of data).
The scenario is this (say you work with 64 bits=8 bytes values):

*

*you read data at an address

*make some light weight CPU computation (so that CPU is not the bottleneck)

*then you read data at new address quite far-away from the first one

*and so on

I'd like to have an idea of the throughput (say in bytes). A simple calculation assuming the RAM has typical DDR3 13 ns latency yields a bandwidth of 8 B/ 13 ns = 600 MB/s. But this raises several points:

*

*is this reasoning (at least schematically) correct?

*is the time to get data exactly the RAM latency or do you have to add some time related to cache, CPU or any component in-between? Do you know how much?

*what happens when doing this in multiple threads? Would there be 600 MB bandwidth for all threads together of for each of them?

A:
... effective memory "bandwidth" ... from main memory to CPU in a worst case scenario:

There are two "worst" scenarios: memory accesses which don't use (miss) CPU caches and memory accesses which accesses too far addresses and can't reuse open DRAM rows.

the RAM cache

The cache is not part of RAM, it is part of CPU, and named CPU cache (top part of memory hierarchy).

is made totally inefficient due to long distances in the successive addresses being treated.

Modern CPU caches has many builtin hardware prefetchers, which may detect non-random steps between several memory accesses. Many prefretchers will detect any step inside aligned 4 kilobyte (KB) page: if you access address1, then address1 + 256 bytes, then L1 prefetcher will start access of address1 + 256*2, address1 + 256*3 etc. Some prefetchers may try to predict out of 4 KB range. So, using only long distances between accesses may be not enough. (prefetchers may be disabled https://software.intel.com/en-us/articles/disclosure-of-hw-prefetcher-control-on-some-intel-processors)

As far as I understand what matters here is the RAM latency and not its bandwidth

Yes, there are some modes when RAM accesses are latency limited.

The scenario is this (say you work with 64 bits=8 bytes values):

You may work with 8 byte values; but you should consider that memory and cache work with bigger units. Modern DRAM memory has bus of 64 bits (8bytes) wide (72 bits for 64+8 in case of ECC), and many transactions may use several bus clock cycles (burst prefetch in DDR4 SDRAM uses 8n - 8 * 64 bits.
Many transactions between CPU cache and memory controller are bigger too and sized as full cache line or as half of cache line. Typical cache line is 64 bytes.

you read data at an address
make some light weight CPU computation (so that CPU is not the bottleneck)
then you read data at new address quite far-away from the first one

This method is not well suitable for modern out-of-order CPUs. CPU may speculatively reorder machine commands and start execution of next memory access before current memory access is done.
Classic tests for cpu cache and memory latency (lat_mem_rd from lmbench http://www.bitmover.com/lmbench/lat_mem_rd.8.html and many others) use memory array filled with some special pseudo-random pattern of pointers; and the test for read latency is like  (https://github.com/foss-for-synopsys-dwc-arc-processors/lmbench/blob/master/src/lat_mem_rd.c#L95)
char **p = start_pointer;
for(i = 0; i < N; i++) {
      p = (char **)*p;
      p = (char **)*p;
  ... // repeated many times to hide loop overhead
      p = (char **)*p;
}

So, address of next pointer is stored in the memory; cpu can't predict next address and start next access speculatively, it will wait for read data from caches or from memory.

I'd like to have an idea of the throughput (say in bytes).

It can be measured in accesses per second; for byte accesses, or word accesses or 8 byte accesses there will be similar number of accesses/s and throughput (bytes/s) will be multiplied for unit used.
Sometimes similar value is measured - GUPS - guga-updates per second (data in memory is read, updated and written back) with test of Random Access. This test can use memory of computing cluster of hundreds (or tens of thousands) of PC - check GUP/s column in http://icl.cs.utk.edu/hpcc/hpcc_results.cgi?display=combo

A simple calculation assuming the RAM has typical DDR3 13 ns latency yields a bandwidth of 8 B/ 13 ns = 600 MB/s. But this raises several points:

RAM has several latencies (timings) - https://en.wikipedia.org/wiki/Memory_timings
And 13 ns CAS is only relevant when you access opened Row. For random accesses you will often access closed row and T_RCD latency is added to CAS.


Q: Spring Integration Dynamic Selector for JMS messages Spring Integration Dynamic Selector for JMS messages
I have a requirement to use dynamic selectors to retrieve messages from the queue. For example i need to get messages from the queue at regular intervals that are > then 1 hr old. It seems the message selector is initialized just once . Can it be changed everytime the poller is used? and how?

A: With the polled adapter, you can use a Smart Poller to change the selector expression before each poll; call setMessageSelector() on the JmsDestinationPollingSource.
You cannot dynamically change the selector on a message-driven adapter; you have to stop the adapter first.


Q: deriving beta 1 in ols linear regression model Hi I'm working on this OLS regression model problem I have started the question by calculating the b1 estimator but I have a different identity to the one used in the model answers, which I have also attached below.
How do I derive what they have in the model question?


Q: How to integrate $\int_0^{\infty} \frac{dx}{1+x^3}$ How would one go about integrating such the function $$\int_0^{\infty} \frac{dx}{1+x^3}$$
The reason I am struggling with this is because normally i would use a contour ingrgration around a semi circle and then extend the radius up to infinity and minus infinity and then solve using cauchys integral theorem.
However, this function is odd and so i am wondering how one would go about integrating such a function since it would disappear over such limits.


Q: EF Core declares two foreign key from different table in a single table I'm using EF core with Fluent api and I got three tables (DomainObject is for the Ids) :
public class Category : DomainObject
{
    public string Name { get; set; }
    public string Type { get; set; }
}

public class Deadline : DomainObject
{
    public Account Tiers { get; set; }
    public Category Category { get; set; }
    public DateTime Created_On { get; set; }
}

public class Transaction : DomainObject
{
    public Account Payee { get; set; }
    public Category Category { get; set; }
    public DateTime DateProcessed { get; set; }
}

as you can see Transaction and Deadline contains a Category foreign key.
modelBuilder
  .Entity<Deadline>()
  .HasOne(e => e.Account)
  .WithMany(e => e.Deadlines)
  .OnDelete(DeleteBehavior.Cascade);

modelBuilder
  .Entity<Transaction>()
  .HasOne(e => e.Account)
  .WithMany(e => e.Transactions)
  .OnDelete(DeleteBehavior.Cascade);

If create a Transaction with a "Food" Category and then I try to create a Deadline with a "Food" Category I got :

InnerException = {"SQLite Error 19: 'UNIQUE constraint failed: Category.Id'."}

This method create a deadline and update in database :
public async Task<ManagementResult> CreateDeadline(User user, Account account, string tiers, string type, double amount, Category category, string notes, DateTime next_Deadline, string frequency, int nbOccurences)
    {
        ManagementResult result = ManagementResult.Success;

        if (amount <= 0)
        {
            result = ManagementResult.IncorrectAmount;
        }
        if (category == null)
        {
            result = ManagementResult.CategoryMissing;
        }
        if (frequency == null)
        {
            result = ManagementResult.FrequencyMissing;
        }
        if (result == ManagementResult.Success)
        {
            user.Accounts.Remove(account);
            Deadline deadline = new Deadline()
            {
                Tiers = tiers,
                Account = account,
                Type = type,
                Amount = amount,
                Category = category,
                Notes = notes,
                Next_Deadline = next_Deadline,
                Frequency = frequency,
                NbOccurences = nbOccurences,
                Status = "En cours",
                Created_On = DateTime.Now
            };
            if (account.Deadlines == null)
            {
                account.Deadlines = new List<Deadline>();
            }
            // Updating ICollection inside the user object
            account.Deadlines.Add(deadline);
            user.Accounts.Add(account);

            // Here is where i get the Exception
            await _deadlineService.Create(deadline);
        }

        return result;
    }

Then this is DeadlineDataService method :
    // Here is the create method who's called
    public async Task<Deadline> Create(Deadline entity)
    {
        return await _nonQueryDataService.Create(entity);
    }

And here's the NonQueryDataService method :
public async Task<T> Create(T entity)
    {
        using (BookkeepingDbContext context = _contextFactory.CreateDbContext())
        {
            EntityEntry<T> createdResult = await context.Set<T>().AddAsync(entity);
            await context.SaveChangesAsync();

            return createdResult.Entity;
        }
    }

How can I solve this ?


Q: Show Errors instead of Internal Server Error When my code have error (even syntax errors) browser show 500 - Internal Server Error,
In .env I set the APP_DEBUG to true and APP_LOG_LEVEL is debug
How can I enable error messages?
UPDATE:
I use Laravel 5.3
UPDATE 2:
I use Apache and defined VirtualHost to access this app :
<VirtualHost *:80>
    ServerAdmin myemail@domain.com
    DocumentRoot "/Dev/Web/site/public"
    ServerName site.local
    ServerAlias www.site.local
    ErrorLog "/private/var/log/apache2/site.local-error_log"
    CustomLog "/private/var/log/apache2/site.local-access_log" common

    <Directory "/Dev/Web/site/public/">
        Require all granted
        AllowOverride All
    </Directory>
</VirtualHost>

UPDATE 3:
My /etc/hosts records:
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1       localhost gat.local www.gat.local site.local www.site.local shop.local www.shop.local

A: Short answer you can't. Why?
Simply because 500 - Internal Server Error is exactly what it says Internal Server Error, it has nothing to do with Laravel. Server software (Apache in your case) causes error 500. Most likely permissions problem. (server software can not read / write to certain files etc.)
From Laravel documentation:

After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run.

You have to check Apache logs
Default on OSX machine /private/var/log/apache2

You want to see more errors? Follow up this SO thread.

Neat trick, make sure to have one entry per project in your hosts file.
#127.0.0.1 project1.dev www.project1.dev
#127.0.0.1 project2.dev www.project2.dev
.
.
.

Why? You can just comment out / delete line, searchable, easier to read.

A: @MajAfy You can use barryvdh/laravel-debugbar. This will give you in depth knowledge of every error. What query you are running and lot more.
Here is the link https://github.com/barryvdh/laravel-debugbar .
Its easy to install due to its well documentation.

A: After many tries, I found problem,
Everything return to file permissions,
I changed the permission of laravel.log in storage/logs to 777 and everything work fine !


Q: Zero-inflated Poisson with known inflation probability I have a zero-inflated probit model but I know the inflation probability of each observation. So my model is:
$P(y_i = 0|X) = (1-\pi_i) + \pi_i*(1-\Phi(X_i'\beta))$
$P(y_i = 1|X) = \pi_i*\Phi(X_i'\beta)$
and I know what $\pi_i$ is for each observation. Is there a way to estimate the model in R with zeroinfl() or glm()?


Q: Print image field in advanced pdf/html I want to print an image field which is a signature on employee record.${entity.custbody_signature}
But when I print it is showing as '?' in the print.
This advanced pdf/html template is on purchase order record.

A: I created a free-form-text field on PO to store image file url in it. And then printed that image this way in the advanced pdf :

A: Use <@filecabinet nstype="image" src="${entity.custbody_signature}">.
You won't need to use "available without login"

A: The best way to get the image url from image field in NetSuite is to do something like this


Q: Use Microsoft.Office.Interop.Word In my project, I need to manipulate a .docx file. I was searching in Google and I found this dll: Microsoft.Office.Interop.Word. In my computer, I have Microsoft Office and it's ok but if I run my project in another computer without Microsoft Office installed (Microsoft.Office.Interop.Word.dll will go with project), will my program run?

A: No. Microsoft.Office.Interop.Word (and all other interop) will just work when Office is installed on that machine. It is a requirement to actually create the instance of Word.
Interop does start the Word executable and can't stand on its own.
It is also discouraged to use Interop on a server.

A: I concur with Patrick's answer.
If you need to manipulate a docx file on a machine without the Word application installed you can work directly with the file via the Office Open XML file format. This can be done with any tools that can work with Zip packages (a docx file is a zip package of the files that make up the document) and XML.
Microsoft provides the Open XML SDK for VB.NET and C# which makes things simpler. There's also an SDK for JavaScript.
You'll find more information at OpenXMLDeveloper.org.


Q: Why can't a class with a type parameter used exclusively as an argument type be covariant on it? The most common example I have found to explain why contravariantly-valid type parameters cannot be used covariantly has involved constructing some read-write wrapper of a derived type, casting it to a wrapper of the base type, injecting a different derived type, then later reading that wrapped value; something along the lines of the following:
class Base { public int base_property; }
class Derived : Base { public int derived_property; }
class OtherDerived : Base { public string other_derived_property; }
interface Wrapper<out T> {
  void put(T v);
  T pull();
}
Wrapper<Derived> derived_wrapper = new WrapperImpl<Derived>();
Wrapper<Base> cast_wrapper = (Wrapper<Base>)derived_wrapper;
cast_wrapper.put(new OtherDerived());
Derived wrapped = derived_wrapper.pull(); // Surprise! This is an OtherDerived.

I can understand why this is invalid. But what if Wrapper didn't have pull, and the property it wraps has a private getter? The problem with the (Wrapper<Base>)derived_wrapper cast seems to disappear, and I can't find a problem to replace it.
More specifically, I'm not aware of any way for functionality to be conditional on the eventual concrete type of a generic. Unsurprisingly, asserting the type like the following is no use:
class WrapperImpl<T> : Wrapper<T> where T : Base {
  public void put(T v) {
    if(typeof(T).Equals(Derived)) {
      Console.WriteLine(v.derived_property); // Type `T' does not contain a
                                             // definition for `derived_property'...
    }
  }
}

This leads me to believe that functionality in these methods can only make use of properties of the type T is constrained to. Even if the wrapped property is an OtherDerived where the original WrapperImpl expected a Derived (before being cast), no method could expect that wrapped property to have derived_property because Base is the most specific T is guaranteed to be.
Am I missing something here, or perhaps is this a limitation of the compiler to not be able to concretize T on the fly?
(I'm guessing that a class like Wrapper finds few uses, but the rules of variance appear quite broad and sweeping, and I'm curious if there are finer rules in play.)

A: The T in WrapperImpl<T> can be constrained on any subtype of Base, not just Base itself. Functionality in put should be able to safely access v.derived_property if T : Base is simply changed to a T : Derived.
This is the source of trouble when an OtherDerived is passed to put after the (Wrapper<Base>)derived_wrapper cast, in trying to access the nonexistent derived_property.


Q: Split a list into smaller equal-sized lists keeping a "middle value"? I am looking for a way to  split a python list in the following way.
So that if I have an array:
A = [0,1,2,3,4]
I would be able to get:
B = [0,1]

C = [1,2]

D = [2,3]

E = [3,4]

A: This is way easier than you think. You can use the same algorithm that itertools uses for their pairwise recipe except itertools.tee isn't needed as your input is a list therefore slicing will work.
B, C, D, E = zip(A, A[1:])

Results:
>>> print(B, C, D, E, sep='\n')
(0, 1)
(1, 2)
(2, 3)
(3, 4)

A: You could use a list comprehension to create a list of these lists:
pairs = [A[i : i + 2] for i in range(len(A) - 1)]

If you then want to unpack them into different variables, you can use tuple unpacking:
B, C, D, E = pairs

A: A more general solution for sublists of length n with overlap of k:
def chunk(lst, n=2, k=1):
    return [lst[i:i+n] for i in range(0, len(lst)-k, n-k)]

>>> A = [0, 1, 2, 3, 4, 5, 6, 7]
>>> chunk(A)
[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]]
>>> chunk(A, 3)
[[0, 1, 2], [2, 3, 4], [4, 5, 6], [6, 7]]
>>> chunk(A, 5, 2)
[[0, 1, 2, 3, 4], [3, 4, 5, 6, 7]]


Q: How do I repair a corrupted Firefox places.sqlite database? I had some problems with my RAM (bluescreen several times, Windows XP) and now are my Firefox databases damaged. Firefox is working, but my history is gone and it's reporting several inconsistencies and errors when executing pragma integrity_check on places.sqlite:

database disk image is malformed

Now the question, how do I repair SQLite-Databases?

A: This process described on MDN helped me resolve an issue where new pages I visited were not recorded in browser history. I did not have a places.sqlite.corrupt (or places.sqlite-corrupt) file, but checking the integrity of my places.sqlite file revealed the database disk image is malformed error.
Quit Firefox and make a backup of your Firefox profile before you go any further here.
$ cd /Users/<username>/Library/Application\ Support/Firefox/Profiles/<profile_dir>/
$ cp places.sqlite places.sqlite.bak  # for safety

$ sqlite3 places.sqlite
sqlite> PRAGMA integrity_check;
*** in database main ***
On tree page 2 cell 131: Rowid 20884 out of order
...
Error: database disk image is malformed
sqlite> .clone places-clone.sqlite
moz_places... done
moz_historyvisits... done
... more output like above plus a few errors (which I ignored) like
sqlite_sequence... Error: object name reserved for internal use: sqlite_sequence
SQL: [CREATE TABLE sqlite_sequence(name,seq)]
done
...
sqlite> PRAGMA user_version;
43  <----- TAKE NOTE OF THIS VALUE it may be different for you
sqlite> .exit

$ sqlite3 places-clone.sqlite
sqlite> PRAGMA integrity_check;
ok
sqlite> PRAGMA user_version = 43;  -- use the number you got from PRAGMA user_version; above
sqlite> PRAGMA journal_mode = truncate;
truncate
sqlite> PRAGMA page_size = 32768;
sqlite> VACUUM;
sqlite> PRAGMA journal_mode = wal;
wal
sqlite> .exit

$ mv places-clone.sqlite places.sqlite

Start Firefox. History should be working again.
I'm on a Mac with Firefox 60.0.1. You may need to adjust the commands for your platform.

A: Well, depending on how damaged it is, repair might not be possible. Your best bet is probably to try and dump the db using sqlite, then see what you can salvage.
If that fails, you'll probably have to restore from backup.
To dump and recreate a database, use the command .dump:
sqlite places.sqlite .dump | sqlite places-new.sqlite

A: As always with performing a repair like this, I recommend that you first make at least one backup copy of your places.sqlite file located in your profile directory. Having a backup allows you to try various different things to repair such problems while knowing that if the attempted repair makes things worse, you can always make another copy of the backup on which to try again.
Depending on what is corrupted and how badly it is corrupted, it may be possible to fix the problems with the extension Places Maintenance. I have ended up with a corrupted places.sqlite file on a few occasions. Places Maintenance has been able to fix the problem each time by running various of the checks/fixes which it provides as operations in its options dialog. The various different checks and/or reporting should take only a few moments to minutes.
If this does not work, then going the route of manually fixing it in a manner similar to what DragonLord describes above may be what is needed.

A: Note
Because Firefox must be closed to perform this procedure, be sure to open this page in another web browser or print it out before proceeding.

After hours of work trying to recover the Places database, even reading the Firefox source code, I've managed to succeed. Here's how I did it:

*

*Download the latest version of the SQLite shell and extract it into your profile folder. On Windows Vista and Windows 7, it is in the C:\Users\<username>\AppData\Roaming\Mozilla\Firefox\Profiles\<code>.default folder.

*Close Firefox if it is running.

*The Places database is in the places.sqlite file. If the file was replaced due to corruption, use the places.sqlite.corrupt file for recovery. Create a backup copy of the file, named places.sqlite.bak or places.sqlite.corrupt.bak.

*Use the SQLite shell to open the database file (sqlite3 places.sqlite or sqlite3 places.sqlite.corrupt), then enter:

.output dump.sql    -- sends output to file dump.sql
.dump               -- dumps database to file

*

*Because the database is corrupt, the resulting database dump is not complete, and not all of the recoverable data have been retrieved. To determine where the error occurred, search for the word ERROR (all caps) in an SQL comment inside the dump file dump.sql (I used Notepad++ to do this), and read the SQL INSERT command above it to determine the table in question. In my case, the damaged table is moz_places. (A description of the tables found in the Places database can be found here, which includes an outdated ER diagram.) I'll explain how to recover additional data from this table only; the following procedure is probably not applicable for the other tables, so skip these sub-steps if a table other than moz_places is involved.)

*

*Each row in the moz_places table has an ID. The rows are dumped from the table following the order of this ID.1 The ID is the first value following the opening parenthesis in the INSERT statement. The area where the database is damaged is likely to be a small block of rows in this table; the idea here is to skip this damaged area and recover as much data as possible. The start area of such a block is represented in the dump as the row before the ERROR comment appears. Using the ID for this row, we can determine where the database is damaged. We do so by using SELECT statements with the ID as a condition; this process takes some trial and error. For example, if the last ID before the error was 49999, and the error follows, the damaged block starts at ID 50000. Use statements like:

-- suppress unnecessary output
-- the following command is for Windows systems
-- for Linux and other Unix and Unix-like systems, use .output /dev/null
.output NUL

SELECT id FROM moz_places WHERE id >= 50100;

*

*Adjust the value following the id >= and repeat the above SELECT command until you find the smallest value that does not cause SQLite to output an error. This is the ID that refers to the row starting from which we can recover additional data. Let's assume this ID is 50200. To dump this data, enter:

.output dump2.sql
.mode insert
SELECT * FROM moz_places WHERE id >= 50200;

-- restore normal output behavior
.output stdout
.mode list

*

*Note that the INSERT statements in the dump2.sql file begins with INSERT INTO table VALUES, so use the find and replace feature in your text editor to replace all instances of this string with INSERT INTO moz_places VALUES.

*Copy the entire contents of the dump2.sql file and paste it into the dump.sql file where the ERROR comment appears.

*Replace the ROLLBACK; -- due to errors at the end of the file with COMMIT;.

*Add the following code to the top of the dump.sql file. Replace <version> with the correct value, which is required for Firefox to determine the database schema version based on the version of Firefox, as follows (this can be found in the Firefox source file toolkit/components/places/Database.cpp):

*

*Firefox 52: schema version 35

*Firefox 53: schema version 36

*Firefox 57: schema version 39

*Firefox 58: schema version 41

*Firefox 60: schema version 43

*Firefox 61: schema version 47

*Firefox 62: schema version 52

*Firefox 69: schema version 53

PRAGMA user_version=<version>;
PRAGMA journal_mode = truncate;
PRAGMA page_size = 32768;
VACUUM;
PRAGMA journal_mode = wal;

*

*Exit the SQLite shell, delete places.sqlite, then start the SQLite shell creating a empty places.sqlite database using sqlite3 places.sqlite. Type .read dump.sql to load the SQL dump into the database.

*Start Firefox and confirm that your history and location bar are functioning as intended. Once you have confirmed that everything is OK, remove the database dump files and SQLite shell executable from the profile folder.

More relevant information can be found on the following pages:

*

*http://kb.mozillazine.org/Locked_or_damaged_places.sqlite

*http://www.sqlite.org/pragma.html
A simplified procedure is described in this MDN article but I have not tested it. Nonetheless, I've incorporated updated PRAGMA commands from that article.

1 SQL does not normally guarantee that database output will be given in any order unless you use the ORDER BY clause. However, ORDER BY will likely fail to produce any output on a corrupted database (as SQLite will need to read the entire table before it can produce any output). As far as I know, Firefox always writes moz_places table entries with sequential IDs, so we can assume that all output is ordered by ID.

A: Another source of the "corrupt database" issue can happen when upgrading from a very old version of Firefox.  None of the database maintenance suggestions in other answers will help in this case.
I recently gave in and decided to upgrade my long-standing version 56 Firefox to version 90 (last version where Proton can be disabled). When my existing profile was opened with version 90, it always renamed my existing SQLite databases as .corrupt.  I found this question while looking for an explanation, and I found the answer in Database.cpp:
// Firefox 60 uses schema version 43.
if (currentSchemaVersion < 43) {
    // These are versions older than Firefox 60 ESR that are not supported
    // anymore.  In this case it's safer to just replace the database.
    return NS_ERROR_FILE_CORRUPTED;
}

This means that any profiles older than Firefox 60 will never be usable in newer versions of Firefox and will always be marked as corrupt.
The easiest way to deal with this and keep your existing profile when upgrading to the current version of Firefox is to use an earlier release as a stepping stone.  It will upgrade your databases to a newer version which is supported by the current Firefox.
To do it I used the following steps:

*

*Get the backup you should have of your Firefox profile from before you installed the current version.  If you don't have one, you can try making a copy of your existing one, renaming the .corrupt databases back to their normal names.

*Download and extract an older version of Firefox that will support your profile version. I used the previous ESR, version 68.0.9. That's the 64-bit version but other platforms and languages are available. The exe setup file can be extracted using 7zip.

*The extracted folder will have a core folder containing the Firefox application files.  Put the copy of your profile (the folder named like abcd1234.default) in this folder.

*To disable Firefox updates so they doesn't cause problems, create a folder named distribution inside core, then create a text file named policies.json inside that. Put the following into the JSON file and save it:
{ "policies": { "DisableAppUpdate": true } }

*Open a command prompt in core and run: firefox.exe -no-remote -profile YOUR_PROFILE_NAME.  This will run a standalone version of Firefox using your profile, which will upgrade the databases.

*Once the browser is open, verify your profile looks correct. Browser history and favicons shown in bookmarks are two good indicators. Close Firefox and check the profile folder that none of the databases were renamed .corrupt. (You can rerun the command as many times as you want to verify and test things.)

*Copy the profile folder you just updated back into your normal Firefox profiles folder (on Windows, %AppData%\Mozilla\Firefox\Profiles).  I'd suggest renaming the existing folder you have in that location to keep a backup.

*Install the current version of Firefox again. This time it should be able to upgrade your profile since the databases have been brought up to a supported version.
As an aside, this same method is a great way to test new Firefox versions. I used this method occasionally over the last few years to see if the addons I use had WebExtension versions available, and to see how hard it would be to update from version 56 to the newest.  Just be very careful to never run firefox.exe without using -no-remote or it will find your normal existing profile and update it (always make a backup beforehand!)


Q: A question on Lagrangian dynamics an the velocity phase space I've struggled in the past with understanding why we can treat position and velocity as independent variables in the Lagrangian, but I think I may have finally become a bit more enlightened on the subject. I have been reading these notes http://www.physics.usu.edu/torre/6010_Fall_2010/Lectures/01.pdf which to me seem to very well written. However, I would like to check if I'm understanding it all correctly?!
At the bottom of page 5 of the notes the lecturer starts talking about velocity phase space. My question really is, am I understanding this correctly?
Empirically, we know that the state of a physical system at a given instant in time is completely determined if one knows its position and velocity at that instant (where by state it is meant that we know all of the information required to predict the subsequent evolution of the system). The positions that the system can occupy correspond to points on a manifold $\mathcal{M}$. A given point $q\in\mathcal{M}$ can be represented in $\mathbb{R}^{n}$ by a list of $n$-coordinates $\lbrace q_{i}\rbrace$ via a coordinate chart, such that $q= \lbrace q_{i}\rbrace$. Of course, such points exist independently of any curve, which (abusing notation) we denote as $q(t)=\lbrace q_{i}(t)\rbrace$ (where the set of values $\lbrace q_{i}(t)\rbrace$ are the coordinates of the curve in $\mathbb{R}^{n}$ via a coordinate chart). At each point $q\in \mathcal{M}$ there exists a set of tangent vectors $\dot{q}$, with coordinates $\lbrace\dot{q}_{i}\rbrace$ (in some coordinate chart), which form a vector space, tangent to that point, denoted as $T_{q}\mathcal{M}$. Again, these tangent vectors exist independently of any given curve. Furthermore, at each given point on the manifold there exists an infinite number of vectors in the tangent space to the manifold at that point. As such we can introduce a manifold called the velocity phase space in which points on this manifold are determined by the pair $(q, \dot{q})$. Now, for each given point $q$ we can choose from an infinite number of tangent vectors $\dot{q}$ at that point, and as such, the pair are independent variables. Such pairs $(q,\dot{q})$ represent points in configuration space that a curve could pass through, and a possible tangent vector to the curve at that point. Clearly, infinitely many curves in configuration space can correspond to the same $(q,\dot{q})$. Is this ok so far (I'm basically augmenting what is written in the notes with what I think I'm understanding from it)?!
On the middle of page 6 the lecturer pauses to discuss a "common point of confusion" about the notation $\dot{q}$, stating that it is not the derivative of anything, but just a vector that exists at the point $q$. Is this just the case because for each given point we can associate a set of vectors (which form a tangent space at that point); they are not derivatives of anything, but they do, in essence, contain information on what direction (and at what speed) curves can move through that point?!
He then moves on to say that a given curve in velocity phase space looks like $$q=q(t),\qquad\dot{q}=\dot{q}(t)$$ I assume by this that the curve is parameterised by some parameter $t$ and that a given value of $t$ corresponds to a given point $(q,\dot{q})$ in the velocity phase space? Also, he says that such a curve may not actually correspond to any motion of the system and we need $\dot{q}(t)$ to actually represent the tangent to $q(t)$, that is, we need to choose $\dot{q}(t) = \frac{dq(t)}{dt}$. By this does he mean that although a given value of $t$ will correspond to a point $q=q(t)$ and a tangent vector $\dot{q}=\dot{q}(t)$, the tangent vector associated with that value of $t$ may not be that of the curve passing through $q$, hence we require that, in actual fact, the given value of $t$ corresponds to a vector tangent to the point $q$ such that its value $\dot{q}(t)$ corresponds to the derivative of the curve evaluated at that point, i.e. $\dot{q}(t)=\frac{dq(t)}{dt}$?
Having done all this, do we then say that the Lagrangian is a one-parameter family of functions (parameterised by $t$) on the velocity phase space, i.e. $$\mathcal{L}=\mathcal{L}(q,\dot{q}, t)=\mathcal{L}(\lbrace q_{i}\rbrace, \lbrace\dot{q}_{i}\rbrace , t)$$ One may then choose a curve in configuration space $q(t)=\lbrace q_{i}(t) \rbrace$ such that when the Lagrangian is evaluated on that curve, for a given value of $t$ it returns a number $\mathcal{L}(q(t),\dot{q}(t),t)$ corresponding to the value of the Lagrangian evaluated at the point $q=q(t)$ on the curve, whose tangent vector is $\dot{q}(t)=\frac{dq(t)}{dt}$?
Sorry, this probably isn't worded particulary well, but I'm just trying to get my head around the whole idea/ check if I'm understanding it at all correctly?!


Q: writing a function of class which will build a string that holds all the information about the class object i want to write a method of class and call it dumpData which will build a string that holds all the information about the object. i tried several codes but all i get is AttributeError: 'list' object has no attribute 'dumpData'
this is the code i have written so far:
class Car():

    def __init__(self, brand, productionYear)
        self.brand = brand
        self.productionYear = productionYear

    def dumpData(self,CarList1):
             return CarList1

 if __name__ =="__main__":
    carObject = []
    for i in range(10):
         carObjectList = []

         brand_list = ['kia', 'Hunday', 'BMW', 'Audi', 'Jeep']
         brand = random.choice(brand_list)

         productionYear = random.randint(1995, 2020)
         carObject.append(Car(brand, productionYear))

         carObjectList.append(carObject)

  print(carObject.dumpData(carObjectList))

i edited this question because it didn't seem to be clear enough.
thank you in advance

A: Your error is saying you have a list object, not an instance of your class that you've tried to call your function on.

I suggest making your class actually hold the list, and the add function take the info you want
You don't need a parameter for the list, at that point.
class Car():
  def __init__(self, brand, year):
    self.brand = brand
    self.year = year

  def __repr__(self):
     return self.brand + "," + str(self.year)

class CarList():
  def __init__(self):
    self.cars = []

  def dump(self):
    return str(self.cars)

  def add(self, brand, year):
    self.cars.append(Car(brand, year))

carList1 = CarList()
carList1.add('honda', 2009)

print(carList1.dump())


Q: Jest spy on React useRef hook not being used after updating Jest to 24.9 When I used jest 22.4 I had a test like the following
it ('should blah', () => {
  const spy = jest.spyOn(React, 'useRef').mockReturnValueOnce(blahMock);
  const comp = shallowWithIntl(<Blah />);
  const compShallow = comp.first().shallow();

  expect(spy).toBeCalled()
});

This works with jest 22.4, not in jest 24.9. I'm not certain that version is the problem as our team uplifted a few things. I will paste our current and old package json devdependencies area below.
Old package.json devdependencies
"devDependencies": {
    "@testing-library/react": "^8.0.1",
    "axios-mock-adapter": "^1.14.0",
    "babel-cli": "^6.24.1",
    "babel-core": "^6.24.1",
    "babel-jest": "^23.0.0",
    "babel-plugin-transform-object-assign": "^6.22.0",
    "babel-plugin-transform-object-rest-spread": "^6.23.0",
    "babel-plugin-transform-regenerator": "^6.24.1",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "enzyme": "^3.3.0",
    "enzyme-adapter-react-16": "^1.1.1",
    "enzyme-react-intl": "^1.4.8",
    "enzyme-redux": "^0.2.1",
    "enzyme-to-json": "^3.3.3",
    "eslint": "^5.0.0",
    "eslint-config-terra": "^2.5.0",
    "generic-site-app": "^1.0.0",
    "html-webpack-plugin": "^3.2.0",
    "husky": "^0.14.3",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^22.4.3",
    "jest-canvas-mock": "^1.1.0",
    "jsdoc": "^3.5.4",
    "jsdom": "11.11.0",
    "nightwatch": "^0.9.12",
    "orion-toolkit-js": "^3.12.0",
    "prettier": "^1.14.2",
    "prettier-eslint": "^8.8.2",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-intl": "^2.3.0",
    "react-on-rails": "7.0.4",
    "react-redux": "^5.0.7",
    "react-router": "^3.0.5",
    "react-test-renderer": "^16.2.0",
    "redux": "^3.7.2",
    "redux-saga": "^0.15.3",
    "redux-test-utils": "^0.2.2",
    "regenerator-runtime": "^0.11.1",
    "rimraf": "^2.6.1",
    "shelljs": "^0.8.1",
    "style-loader": "^0.20.3",
    "stylelint": "^9.2.0",
    "stylelint-config-sass-guidelines": "^5.0.0",
    "terra-markdown": "^2.24.0",
    "terra-slide-panel": "^3.3.0",
    "terra-toolkit": "^4.26.0",
    "url-loader": "^1.1.2",
    "webpack-bundle-analyzer": "^3.0.3",
    "webpack-merge": "^4.2.1"
  }

New package.json devdependencies
"devDependencies": {
    "@babel/cli": "^7.7.0",
    "@babel/core": "^7.7.2",
    "@babel/plugin-proposal-object-rest-spread": "^7.6.2",
    "@babel/plugin-transform-object-assign": "^7.2.0",
    "@babel/preset-env": "^7.7.1",
    "@babel/preset-react": "^7.7.0",
    "@testing-library/react": "^8.0.1",
    "axios-mock-adapter": "^1.14.0",
    "babel-jest": "^24.9.0",
    "browserslist-config-terra": "^1.3.0",
    "core-js": "^3.4.1",
    "enzyme": "^3.3.0",
    "enzyme-adapter-react-16": "^1.1.1",
    "enzyme-react-intl": "^1.4.8",
    "enzyme-redux": "^0.2.1",
    "enzyme-to-json": "^3.3.3",
    "eslint": "^5.0.0",
    "eslint-config-terra": "^2.5.0",
    "generic-site-app": "^1.0.0",
    "html-webpack-plugin": "^3.2.0",
    "husky": "^0.14.3",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^24.9.0",
    "jest-canvas-mock": "^1.1.0",
    "jsdoc": "^3.5.4",
    "jsdom": "11.11.0",
    "prettier": "^1.14.2",
    "prettier-eslint": "^8.8.2",
    "raf": "^3.4.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-intl": "^2.3.0",
    "react-on-rails": "7.0.4",
    "react-redux": "^5.0.7",
    "react-router": "^3.0.5",
    "react-test-renderer": "^16.2.0",
    "redux": "^3.7.2",
    "redux-saga": "^0.15.3",
    "redux-test-utils": "^0.2.2",
    "regenerator-runtime": "^0.13.3",
    "rimraf": "^2.6.1",
    "shelljs": "^0.8.1",
    "style-loader": "^0.20.3",
    "stylelint": "^9.2.0",
    "stylelint-config-sass-guidelines": "^5.0.0",
    "terra-aggregate-translations": "^1.4.0",
    "terra-markdown": "^2.24.0",
    "terra-slide-panel": "^3.3.0",
    "terra-toolkit": "^5.13.0",
    "url-loader": "^1.1.2",
    "webpack": "^4.41.2",
    "webpack-bundle-analyzer": "^3.0.3",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.9.0",
    "webpack-merge": "^4.2.1"
  }


Q: C++ extern storage class life-span I am a C++ newbie and come from a Java background.
I would like to confirm the following:
I am reading C++ by dissection by Ira Pohl and the book states that the
life-span for a file/extern variable/function is the duration of the program (which makes sense because the variable is not declared in a class).
What I want to know; is that also the case for a variable declared in a class? If not, if a variable is declared in a class does that make the variable use the auto storage class?
Thanks.

A: A member variable in a class has a life-span corresponding to the life-span of the class's instances, unless declared static.
struct Foo {
    int x;
    static int y;
};

This Foo, and therefore its x, has program life-span:
static Foo foo;

This one is auto:
int main() { Foo foo; }

This one is dynamically allocated and lives until the Foo is delete'd:
int main() { Foo *foo = new Foo; }

In each case, the y has program life-span.


Q: Toggle hide and show I have tried everything to get it to toggle show and hide but every time I add hide in the function, it stops working or I can get hide to work flawlessly while show doesn't work at all. Any help would be appreciated.

    Search:
    <input id="tags">
    <button class='clear' id="ClearButton"> Clear</button>

$(document).ready(function(){
     $('.ShowHideList').hide();
     $('.ShowHideClicker').click(function(){
          $(this).next().show('drop', {direction: 'left'}, 1000);
     });
});

A: Here is the simple solution with toggleClass:
$('.ShowHideClicker').on('click', function(){
    $(this).next().toggleClass('hidden');
});

http://jsfiddle.net/LcYLY/

A: You should be using the .toggle() this way: JSFIDDLE and make sure you have included jQuery and jQuery UI in your header ("drop" is a jQuery UI feature)
jQuery:
$(document).ready(function(){
  $('.ShowHideClicker').click(function(){
    $('.ShowHideList').toggle('drop', 1000);
  });
});

CSS:
.ShowHideList { display: none; }


Q: Indenting legend items in ArcMap My map legend looks like this:

I'd like to indent the circled items farther to the right but can't find any settings to adjust this. Using the item properties I know how to offset the label portion, but not the patch.
This is pretty much the same question I asked as Indenting subitems in QGIS Composer legend?, but now trying to do this with ArcMap instead of QGIS.

A: So, the way that I best know how to do this requires some manual work, but will return the results you are looking for.
Create the legend like normal. When it is created, right click on the legend and convert it to graphics. With the legend being converted to graphics, you can then ungroup everything and move the items you are focusing on. An easy way to align the indentation for these items is to click on the ruler on the top of the layout page and set it as a guide. Once done, you can then group everything in the legend back together to form one complete legend.
Again, this method is manually intensive but sometimes working like this on legends produces better looking results.


Q: how can I get pyodbc to perform a "SELECT ... INTO" statement without locking? I'm trying to copy a table in SQL Server, but a simple statement seems to be locking my database when using pyodbc. Here's the code I'm trying:
dbCxn = db.connect(cxnString)
dbCursor = dbCxn.cursor()
query = """\
SELECT TOP(10) *
INTO production_data_adjusted
FROM production_data
"""
dbCursor.execute(query)

The last statement returns immediately, but both LINQPad and SQL Server Management Studio are locked out of the database afterwards (I try to refresh their table lists). Running sp_who2 shows that LINQPad/SSMS are stuck waiting for my pyodbc process. Other databases on the server seem fine, but all access to this database gets held up. The only way I can get these other applications to resolve their stalls is by closing the pyodbc database connection:
dbCxn.close()

This exact same SELECT ... INTO statement statement works fine and takes only a second from LINQPad and SSMS. The above code works fine and doesn't lock the database if I remove the INTO line. It even returns results if I add fetchone() or fetchall().
Can anyone tell me what I'm doing wrong here?

A: Call the commit function of either the cursor or connection after SELECT ... INTO is executed, for example:
...
dbCursor.execute(query)
dbCursor.commit()

Alternatively, automatic commit of transactions can be specified when the connection is created using autocommit. Note that autocommit is an argument to the connect function, not a connection string attribute, for example:
...
dbCxn = db.connect(cxnString, autocommit=True)
...


Q: check single value from one table with table with multiple values separated by comma I have two tables in which one contains the correct answers to the questions and the other contains the answers submitted by user.
I want to calculate the correct answers the user has entered with the tables which have the correct answers and make a new column, status, which has the status such as 'correct' or 'incorrect'.
The problem is the correct answer tables has values separated by comma such as a,b,c and if a user enters the value its being send as single entry . such as a and then a new entry b . and i want to compare the values a and b present in the user answers submitted by user table to the correct answer table with entry a,b,c and also if a user enters a option d instead of b and d is not in a,b,c even if the user entry a is in a,b,c then also the answer should be marked as incorrect . So even if one option selected by user is wrong then the exact correct options in the correct option table then the status should be incorrect .
I have made a SQL fiddle of the tables against which I tried this query
SELECT  qa.question_id,qa.type,qa.answers
FROM    questions_answer qa, user_test_answers uta

            where FIND_IN_SET(uta.answers, qa.answers) > 0 and qa.question_id='4' and uta.user_id='2' and qa.question_id=uta.question_id

This returned empty results.
The result i expect is
question_id  test_id  user_answer     type             correct_answer     status
  13            4        a         multiple_choice          c            incorrect
  13            4        c         multiple_choice          c             correct
  14            4        a         multiple_choice          a,c           correct
  15            4        b          true_false              a             incorrect

A: You can try using GROUP_CONCAT in MySQL:
SELECT uta.question_id, uta.test_id, GROUP_CONCAT(uta.answers ORDER BY uta.answers) AS user_answer, qa.type, qa.answers correct_answer,
CASE WHEN GROUP_CONCAT(uta.answers) = qa.answers THEN 'correct' ELSE 'incorrect' END
AS status
FROM user_test_answers uta
LEFT JOIN questions_answer qa
ON qa.question_id = uta.question_id
GROUP BY uta.user_id, uta.question_id

Check I used ORDER BY in GROUP_CONCAT which means that inquestions_answer table, answers must be in alphabetical order.
Also, there seems to be an invalid entry in user_test_answers, with question_id 20.
HTH
EDIT:
SELECT uta.question_id, uta.test_id, uta.user_answer, qa.type,
qa.answers correct_answer,
CASE WHEN uta.user_answer = qa.answers THEN 'correct' ELSE 'incorrect' END
AS status
FROM questions_answer qa
LEFT JOIN
(
  SELECT user_id, type, test_id, question_id,
  GROUP_CONCAT(answers ORDER BY answers) AS user_answer,
  timestamp from user_test_answers
  GROUP BY user_id, question_id
) uta
ON qa.question_id = uta.question_id

EDIT 2:
SELECT uta.question_id, uta.test_id, uta.user_answer, qa.type,
qa.answers correct_answer,
CASE WHEN uta.user_answer = qa.answers THEN 'correct' ELSE 'incorrect' END
AS status
FROM questions_answer qa
LEFT JOIN
(
  SELECT user_id, type, test_id, question_id,
  GROUP_CONCAT(answers ORDER BY answers) AS user_answer,
  timestamp from user_test_answers
  WHERE user_id = 2 AND test_id = 4 -- for user 2 and test 4
  GROUP BY user_id, question_id
) uta
ON qa.question_id = uta.question_id
WHERE test_id = 4 -- try omitting this one in case you get incorrect results

IMHO, you need to look at and improve your DB design and schemas.


Q: Defining recrussive JSON Object notation Whats wrong in below JSON Object definition
I am trying to create a new JSON Object like below.
So that my idea is to access COMPANYSETUP.HourSetup.initiate();
Not sure the error ?
COMPANYSETUP = {
                    initiated : false,
                     companyId : "",

            initiate : function() {
                if(!initiated){
                    // TO DO
                    initiated = true;
                }           },

            HourSetup = {
                initiated : false,
                    hourId : "",

                    initiate : function() {
                       if(!initiated){
                          // TO DO
                         initiated = true;
                        }
                   }

            }

        };

A: Assuming you want a javascript object and not JSON, which disallows functions,
HourSetup =
Should be changed to:
HourSetup :
Also, as JonoW points out, your single line comments are including some of your code as the code is formatted in the post.

A: There's a "=" that shouldn't be there. Change it to ":"

A: JSON is a form of JavaScript deliberately restricted for safety. It cannot include dangerous code elements like function expressions.
It should work OK in plain eval()ed JavaScript, but it's not JSON.


Q: Saving Data as JSON feed from fullcalendar I'm wanting to save the objects that are created to the json-feed file, using $.ajax but nothing is being saved. The object is placed on the calendar but when I check the JSON feed in my .php file, nothing is changed?
var calendar = $('#calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: ''
        },
        selectable: true,
        selectHelper: true,
        select: function(start, end) {
            var title = prompt('Event:');

             $.ajax({
    url: "json-events.php",
    type: 'POST',
    data: {"foo": "bar"},
    processData: false,
    contentType: 'application/json'
});

            if (title) {
                calendar.fullCalendar('renderEvent',
                    {
                        title: title,
                        start: start,
                        end: end,
                        allday: false
                    },
                    true // make the event "stick"
                );
            }
            calendar.fullCalendar('unselect');
        },
        editable: true,

        events: "json-events.php",

        eventDrop: function(event, delta) {
            alert(event.title + ' was moved ' + delta + ' days\n' +
                'would update json-feed here');
        },

A: var calendar = $('#calendar').fullCalendar({
    editable: true,
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },

    events: "events.php",

    selectable: true,
    selectHelper: true,
    select: function(start, end, allDay) {
        var title = prompt('Event Title:');
        var url = prompt('Type Event url, if exits:');
        if (title) {
            start = $.fullCalendar.formatDate(start, "yyyy-MM-dd HH:mm:ss");
            end = $.fullCalendar.formatDate(end, "yyyy-MM-dd HH:mm:ss");
            $.ajax({
                url: 'add_events.php',
                data: 'title='+ title+'&start='+ start +'&end='+ end +'&url='+ url ,
                type: "POST",
                success: function(json) {
                    alert('Added Successfully');
                }
            });
            calendar.fullCalendar('renderEvent',
            {
                title: title,
                start: start,
                end: end,
                allDay: allDay
            },
            true // make the event "stick"
            );
        }
        calendar.fullCalendar('unselect');
    },
    editable: true,
    eventDrop: function(event, delta) {
        start = $.fullCalendar.formatDate(event.start, "yyyy-MM-dd HH:mm:ss");
        end = $.fullCalendar.formatDate(event.end, "yyyy-MM-dd HH:mm:ss");
        $.ajax({
            url: 'update_events.php',
            data: 'title='+ event.title+'&start='+ start +'&end='+ end +'&id='+ event.id ,
            type: "POST",
            success: function(json) {
                alert("Updated Successfully");
            }
        });
    },
    eventResize: function(event) {
        start = $.fullCalendar.formatDate(event.start, "yyyy-MM-dd HH:mm:ss");
        end = $.fullCalendar.formatDate(event.end, "yyyy-MM-dd HH:mm:ss");
        $.ajax({
            url: 'update_events.php',
            data: 'title='+ event.title+'&start='+ start +'&end='+ end +'&id='+ event.id ,
            type: "POST",
            success: function(json) {
                alert("Updated Successfully");
            }
        });
    }

});


Q: Confidence interval for binomial success parameter approximated by normal distribution Given is a group of 82 people, 7 of those are at risk for some disorder. The overall goal is to model the proportion p of people with the disorder - and it is clear that this can be modeled by a Binomial distribution.
The task, however, goes on to say the following:
"With the central limit theorem (CLT) it follows that $\hat{p}$ follows approximately N(p, p$\frac{1}{n}$(1-p)). Plot the normal approximation for different n and p, compare the binomial distribution to the normal approximation for different n and p. Calculate the 95%-confidence interval (CI) for the approximate proportion".
I am very confused because it is not clear to me what $\hat{p}$ is - I assume it is the estimated distribution (and not just the success parameter). But would this not be N(np, np(1-p))? And if this is
the estimated distribution, how can I construct a CI for it?