text:
Q: Problem fitting of Log Pearson Type III in R using method of moments estimators I am new in R and I am having difficulty in figuring out how to fit Log Pearson Type III using method = mme to the data.
YearThai <- c(2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018)
FlowThai <- c(2009.6,2071.8,3534.5,1813.6,1674.17,1892,4020,2572.4,2303.2,2299.8,3242,3720,1939.9,2221.6,1127,706.8,2109.7,2571.4,880.8)
DataThai <- as.data.frame(cbind(YearThai,FlowThai))

LFlowThai <- log(FlowThai)
m <- mean(LFlowThai)
v <- var(LFlowThai)
s <- sd(LFlowThai)
g <- e1071::skewness(LFlowThai, type=1)

n <- length(LFlowThai)
g <- g*(sqrt(n*(n-1))/(n-2))*(1+8.5/n)

my.shape <- 4/(g)^2
my.scale <- abs(g)/(g*(s/sqrt(my.shape)))
my.location <- m-(my.shape*my.scale)

my.param <- list(shape=my.shape, scale=my.scale, location=my.location)

dPIII<-function(x, shape, location, scale) PearsonDS::dpearsonIII(x, shape, location, scale, log=FALSE)
pPIII<-function(q, shape, location, scale) PearsonDS::ppearsonIII(q, shape, location, scale, lower.tail = TRUE, log.p = FALSE)
qPIII<-function(p, shape, location, scale) PearsonDS::qpearsonIII(p, shape, location, scale, lower.tail = TRUE, log.p = FALSE)

fitdistrplus::fitdist(LFlowThai, distr = "PIII", method = "mme", order = c(1,2,3), start = my.param)

The error I get is this:
Error in mmedist(data, distname, start = arg_startfix$start.arg, fix.arg = arg_startfix$fix.arg,  :
the empirical moment function must be defined

There is no problem when using method = mle, but our research requires the use of method of moments for the parameter estimation.
Thank you in advance to those who can help.

A: I'm having the exact same problem as you. What i've found googling about it is that you need to provide the empirical moments function and the theoretical moments function, for Pearson III distribution, when using fitdist from fitdistrplus.
If you use the fasstr package, you'll see that it fits Pearson type III to your data by matching moments. That's because these package provides, to fitdist, the "memp" and "mPearsonIII" functions needed to do so.
memp function:
function(x, order) mean(x^order)

mPearson III function:
function (order, shape, location, scale)
{
  if (order == 1)
    return(location + shape * scale)
  if (order == 2)
    return(scale * scale * shape)
  if (order == 3)
    return(2/sqrt(shape) * sign(scale))
}

Using compute_annual_frequencies() from fasstr gives you an object named Freq_Fitting with the estimated parameters for Pearson type III using MOM (object class is fitdistrplus). Sadly, is has some issues that i'm trying to fix (quantiles and scale issues when plotting).


text:
Q: Django admin site is changed to normal html Unfortunately my admin site got changed into a normal html site. I don't how it is happened. Did anyone came-across this problem and overcome of it.
Actual result:

Expected Result:

A: Most of the time, Django apps STATIC_ROOT and STATIC_URL are both set to "/static/". Unless you have a non-standard file setup, that should be the case for you

redpajama_set_name: RedPajamaStackExchange


text:
Q: CakePHP Facebook Plugin does not displays the logout button in FIrefox I'm working with webtechnick CakePHP Facebook Plugin, I finally managed to make it work (I can use the like/recommend buttons - I can login via facebook, etc) except for the logout button in Firefox v3.6 and IE that is not working. I think there is a problem because in Chrome the logout button get display and the PHP code works fine also. I have this code into a *.cpt view file:
if($facebook_user){
    echo $this->Facebook->logout();
    echo debug($facebook_user);
} else {
    echo $this->Facebook->login(array());
}

In Chrome after I click on the login button, the $facebook_user is true and the logout button get display as well as the debug(), therefor PHP is fine but in Firefox or IE the logout button gets hide almost instantly.
I'm following the video tutorial and the problem seems to be in the minute 19~
http://tv.cakephp.org/video/webtechnick/2011/01/12/nick_baker_--_facebook_integration_with_cakephp
Thanks!

A: I fixed this problem by enabling in Firefox's options on Privacy the "Accept third-party cookies"


text:
Q: Speed up iteration over DataFrame items I wrote a function in which each cell of a DataFrame is divided by a number saved in another dataframe.
def calculate_dfA(df_t,xout):

df_A = df_t.copy()
vector_x = xout.T

for index_col, column in tqdm(df_A.iteritems()):
    for index_row, row in df_A.iterrows():
        df_A.iloc[index_row,index_col] = df_A.iloc[index_row,index_col]/vector_x.iloc[0,index_col]

return(df_A)

The DataFrame on which I apply the calculation has a size of 14839 rows x 14839 columns. According to tqdm the processing speed is roughly 4.5s/it. Accordingly, the calculation will require approixmately 50 days which is not feasible for me. Is there a way to speed up my calculation?

A: You need to vectorize your division:
result = df_A.values/vector_x

This will broadcast along the row dimension and divide along the column dimension, as you seem to ask for.
Compared to your double for-loop, you are taking advantage of contiguity and homogeneity of the data in memory. This allows for a massive speedup.
Edit: Coming back to this answer today, I am spotting that converting to a numpy array first speeds up the computation. Locally I get a 10x speedup for an array of size similar to the one in the question here-above. Have edited my answer.

A: I'm on mobile now but you should try to avoid every for loop in python - theres always a better way
For one I know you can multiply a pandas column (Series) times a column to get your desired result.
I think to multiply every column with the matching column of another DataFrame you would still need to iterate (but only with one for loop => performance boost)
I would strongly recommend that you temporarily convert to a numpy ndarray and work with these


text:
Q: How to check WCF data element skipped in XML? In my WCF I defined an object "Product" as below:
<xs:complexType name="Product">
    <xs:sequence>
        <xs:element name="Name" type="xs:string"/>
        <xs:element name="Postcode" type="xs:string" nillable="true" minOccurs="0"/>
        <xs:element name="ProductID" type="xs:string" />
    </xs:sequence>
</xs:complexType>

Please note the element "Postcode" is nillable="true" minOccurs="0", this means when client application call the web service, they can either provide empty value for this element as below:
<Product>
    <Name>Product 1</Name>
    <Postcode></Postcode>
    <ProductID>10</ProductID>
</Product>

Or they can simple skip "Postcode" element so the incoming message becomes this (Postcode isn't there)
<Product>
    <Name>Product 1</Name>
    <ProductID>10</ProductID>
</Product>

My question is, in my host program how do I check if the element "Postcode" exists in the incoming XML message? I am asking because if it doesn't there and I call the method to get Postcode value, then the program will throw an error:
string postcode = product.Postcode - this call will throw an error?
Thank you all very much for any ideas/suggestions.
Charles

A: You are not correct in your assertion that using nillable in your definition permits the two cases you have listed.
In fact, the nillable xsd attribute permits the construction:
<Postcode xsi:nil='true'/>

which is semantically different from Postcode being either empty, or just not present at all.
In answer to your question,

how do I check if the element "Postcode" exists in the incoming XML
  message

I don't quite understand why you want to define Postcode with minOccurs=0. When wcf receives this type across the wire it will attempt to deserialise to a predefined C# type. In C#, types either have properties or they don't have.
eg.
public class Product
{
    public string Postcode { get; set; }
}

is not the same things as
public class Product
{
}

So by allowing callers to construct two different versions of your Product type you are actually forced to define two separate C# types to deserialise to, which means you'll need to expose your service operation twice, once for callers who want to use Product with postcode, and one for those who want to use Product without.
I would suggest that you redefine your Product type to include the Postcode element - after all because it's a string your callers can just leave it null if they do not wish to use it.


text:
Q: Int& to const int -static vs dynamic- class A
{
public:
  A(int i = 25) {x = i;y=new int[i];for(int j=0;j<i;j++) y[j]=j;}
  int& f() const {return x;}
  int& operator[](int i) const {return y[i];}

private:
  int x,*y;
};

int main()
{
   A a(15);
   cout << a[5];
   cout << a.f();

   return 0;
}

When I'm trying to compile the code it says
"Invalid initialization of reference of type int& from expression of type const int"

regarding f() function.
I understand it,since it returns a non-const reference to something declared as const by the function. But shouldn't it behave the same with the [] overloading?
It also returns a non-const reference to something that the function declared as const,but it shows no error there.
What's the difference?

A: The issue is here:
int& f() const {return x;}

Your function is marked const, so it can be only invoked by const instances. However, you return a non-const reference, therefore if valid you can use it an modify const instances. The compiler is not happy with this. Hence f() should return const int& instead.
On the other hand, int& operator[](int) const compiles, since you return a reference to the data the pointer member y points to, but you cannot modify the pointer itself. In other words, on a const instance, the pointer y is const, i.e. int * const y, but not the data. Therefore bitwise const-ness is preserved, but of course logical const-ness is not, however the compiler only cares about bit-wise const-ness.
To enforce logical const correctness, one option is to write 2 versions of your operator[]:
const int& operator[](int i) const {return y[i];}

and
int& operator[](int i) {return y[i];}

Note that the second version should be marked non-const, as otherwise you'd try to overload two functions that differ only by their return type. If you want to avoid code duplication in the non-const version, you can make use of the const version via a const_cast, like
int& operator[](int i)
{
    return const_cast<int&>(const_cast<const A&>(*this)[i]); // use the const version
}

EDIT
There is a proposal to introduce a const-propagating wrapper for pointer-like data members, propagate_const, which in effect will also make the data pointed to const, see
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4057.pdf

A: It is telling you that you can't return a non-const lvalue reference to a data member from a const member function. You need
const int& f() const {return x;}

You may decide to provide a non-const overload if needed:
int& f() {return x;}

As for operator[], it does not return a reference to a data member. You cannot modify x or y via operator[], so it is really a const member function. You may decide to disallow modification to the data pointed at by y, and this would make sense if your class models an array. But it isn't strictly necessary and the compiler has no reason to enforce it.
const int& operator[](int i) const {return y[i];}
int& operator[](int i) {return y[i];}

A: In C++ language constness of a class implies immediate constness of all its members (except for mutable ones). However, constness of the class does not propagate to data pointed by pointer members or referenced by reference members. That pointed/referenced data is not part of the class and its constness is not affected by constness of the class.
In your example, declaring a member function as const makes it treat members x and y as const. However, the data pointed by y does not become const, e.g. neither *y nor y[i] are const.
Propagation of constness from the enclosing class to the pointed/referenced data is actually a part of user intent. It is something you need or don't need depending on what you are trying to implement. The language leaves it completely up to you (or to a library-level solution).


text:
Q: Looking inside a lambda / expression tree Given either of the variables below, how can I 'inspect' them to obtain the parameter value passed in? i.e. 12345.
System.Func<DateTime> f1 = () => DateTime.Now.AddDays(12345);

System.Linq.Expressions.Expression<System.Func<DateTime>>
                      f2 = () => DateTime.Now.AddDays(12345);

Edit:
The two answers below by Mikael and Kirk both answer my orignal question.
However, I've now made this a little more complex to deal with 'real life'.
Ideally I'm looking for a 'general' solution, which will work with something alongs the lines of the below:
var days = 123;
var hours = 456;
System.Func<DateTime> f1 = () => DateTime.Now.AddDays(days).AddHours(hours);
Expression<System.Func<DateTime>> f2 = () => DateTime.Now.AddDays(days).AddHours(hours);

What I'm really after is a way to generate a unikey 'key' given a lamda expression.
My idea is to use the method name, and the parameter name/value pairs, but I'm welcome to other suggestions! Thanks.

A: As an addition to Kirk Woll's answer, if you want to have the 12345 as an object, you can use the following:
    public void Run()
    {
        System.Linq.Expressions.Expression<System.Func<DateTime>> f2 = () => DateTime.Now.AddDays(12345);

        MethodCallExpression call = (MethodCallExpression)f2.Body;
        ConstantExpression arg = (ConstantExpression)call.Arguments[0];

        var value = GetValue(arg);
        Debug.WriteLine(value);
    }

    private object GetValue(ConstantExpression expression)
    {
        Expression conversion = Expression.Convert(expression, typeof(object));
        var getterLambda = Expression.Lambda<Func<object>>(conversion);

        var getter = getterLambda.Compile();

        return getter();
    }

A: If you mean the value 12345, that data is only available in f2.  For f2:
MethodCallExpression call = (MethodCallExpression)f2.Body;
ConstantExpression arg = (ConstantExpression)call.Arguments[0];
Console.WriteLine(arg.Value);

A: The only way I can see to get it from f1 is by:
int days = (f1() - DateTime.Now).Days;

which I doubt is what you want.
Getting the value from f2, however, is possible, and not that difficult, if the body of the function is as clearly defined as your example.  It will start something like ((f2 as LambdaExpression).Body as MethodCallExpression)....
I could take a long time to figure out the exact process, but it would probably be easier, for you to just inspect f2 in the debugger.


text:
Q: How applications are managed in Linux? I am looking for design suggestions/documents etc. which contains specifics of system applications management in Linux (Ubuntu, Debian etc.)
Can you please point to a source of information or suggest a design?

A: I'm not sure to understand what you mean by system applications management (certainly it can mean several different things).
In practice, Linux distributions have some package management system to deal with that issue. init or systemd (etc....) is in charge of starting/stopping/managing daemons and servers. Its configuration is related to packaging.
Read also Ubuntu Packaging Guide and How To Package For Debian and Debian new Maintainer guide etc...
If you are coding some service application, read Advanced Linux Programming and about daemon(3) & syslog(3)
Also, study the source code of relevant system applications (similar to the one you are dreaming of), since Linux is generally (mostly) free software.


text:
Q: isAbstract template and visual studio The following template will decide if T is abstract with g++.
/**
   isAbstract<T>::result is 1 if T is abstract, 0 if otherwise.
 */
template<typename T>
class isAbstract
{
   class No { };
   class Yes { No no[3]; };

   template<class U> static No test( U (*)[1] ); // not defined
   template<class U> static Yes test( ... ); // not defined

public:
   enum { result = sizeof( isAbstract<T>::template test<T>( 0 ) ) == sizeof(Yes) };
};

For example:
    struct myClass2 { virtual void f() {} };
    struct myClass1 { virtual void f() = 0; };
bool twoAbstract = isAbstract<myClass2>::result;
bool oneAbstract = isAbstract<myClass1>::result;

However, it fails in visual studio 9.0 with the error:
error C2784: 'AiLive::isAbstract<T>::No AiLive::isAbstract<T>::test(U (*)[1])' : could not deduce template argument for 'U (*)[1]' from 'myClass2'

Does anyone have an idea of what the problem is and how to fix this?
MSDN Reports that they now have an is_abstract class since VS2008 as part of TR1 (inside the header type_traits). However, it seems to be missing from my installation.
PS. For reasons that are long and boring, I can't reimplement this via Boost.
Update
Also, tried replacing,
template<class U> static No test( U (*)[1] );

with each of,
template<class U> static No test( U (*x)[1] );
template<class U> static No test( U (*)() );
template<class U> static No test( U (*x)() );

and
template <typename U>
struct U2 : public U
{
   U2( U* ) {}
};

// Match if I can make a U2
template <typename U> static No test( U2<U> x  );

and
// Match if I can make a U2
template <typename U> static No test( U2<T> x  );

No luck - all say that template argument cannot be deduced for U.

A: This works for me in VC9:
template<typename T>
class isAbstract
{
    class No { };
    class Yes { No no[3]; };

    template<class U> static No test( U (*)[1] ); // not defined
    template<class U> static Yes test( ... ); // not defined

public:
    enum { result = sizeof( test<T>( 0 ) ) == sizeof(Yes) };
};

Notice I just had to remove isAbstract<T>:: from the call to test.

A: Not sure as I've note done C++ for a while but can you use
template< typename  T, typename  U>
class isAbstract
{
   class No { };
   class Yes { No no[3]; };

   template<class U> static No test( U (*)[1] ); // not defined
   template<class U> static Yes test( ... ); // not defined

public:
   enum { result = sizeof( isAbstract<T>::template test<T>( 0 ) ) == sizeof(Yes) };
};

bool twoAbstract = isAbstract<myClass2, SomeTypeU>::result;


text:
Q: Bigquery Custom first day of week (defaults Monday) I am trying to extract week from date using the function

format_timestamp('%V', DATE)

but Bigquery documentation says "Monday as the first day of the week".
Is there a way where I can specify Tuesday as first day of week.
I have achieved the same in Redshift using

date_part(week, date + interval '-1 day')

Is it possible in Bigquery?

A: Below is for BigQuery Standard SQL
You can use WEEK(WEEKDAY) as shown below
#standardSQL
SELECT FORMAT_TIMESTAMP('%V', CURRENT_TIMESTAMP()),
EXTRACT(WEEK(SATURDAY) FROM CURRENT_TIMESTAMP())

This was introduced quite recently - https://cloud.google.com/bigquery/docs/release-notes#november_30_2017


text:
Q: PCL 1.8.0 installation: Compile error for including QtGui I'm trying to build PCL 1.8.0 on my Ubuntu 14.04 machine from source, following these instructions. But every time I get the following error:
[ 73%] Building CXX object apps/CMakeFiles/pcl_manual_registration.dir/include/pcl/apps/moc_manual_registration.cpp.o
In file included from ~/pcl/release/apps/ui_manual_registration.h:26:0,
             from ~/pcl/release/apps/include/pcl/apps/../../../../../apps/include/pcl/apps/manual_registration.h:37,
             from ~/pcl/release/apps/include/pcl/apps/moc_manual_registration.cpp:9:
/usr/include/vtk-5.8/QVTKWidget.h:40:25: fatal error: QtGui/QWidget: No such file or directory
    #include <QtGui/QWidget>
                     ^
compilation terminated.
make[2]: *** [apps/CMakeFiles/pcl_manual_registration.dir/include/pcl/apps/moc_manual_registration.cpp.o] Error 1
make[1]: *** [apps/CMakeFiles/pcl_manual_registration.dir/all] Error 2
make: *** [all] Error 2

for locate QWidget I get amongst others the following output:
...
/usr/include/qt4/QtGui/QWidget
...
/usr/include/qt5/QtWidgets/QWidget
...

So how can I resolve the error and install pcl?

A: The problem happens because your configuration is trying to mix Qt4 and Qt5 during PCL build.
According to the link you've provided, PCL is suppossed so be built against Qt4 in this case.
Try to remove everything in release directory and re-initialize CMake config with correct version of Qt.
Like that (following provided example):
cd ~/Documents/pcl
rm -rf relese
mkdir release
cd release
cmake -DCMAKE_BUILD_TYPE=Release -DPCL_QT_VERSION=4 -DBUILD_GPU=ON -DBUILD_apps=ON -DBUILD_examples=ON ..
make


text:
Q: Getting "Vendor autoload is not found." error even the composer install succeeded When i open Magento in browser i got

Autoload error
Vendor autoload is not found. Please run 'composer install' under application root directory.

even i have run
composer update
composer install

on the root folder and it says

Nothing to install, update or remove

Is there somewhere I can dig to figure out why the autoload is still failing?

A: Try to run the following commands and then check.
php bin/magento cache:clean
php bin/magento cache:flush
php bin/magento indexer:reindex
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
sudo chmod -R 777 var/ generated/ pub/

A: I tried all the below  step  but still getting error   "Vendor autoload is not found." please Run Composer under root directory.
please help how can resolve
/var/www/html/magento2/ composer update
/var/www/html/magento2/  composer install
php bin/magento cache:clean
php bin/magento cache:flush
php bin/magento indexer:reindex
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
sudo chmod -R 777 var/ generated/ pub/


text:
Q: How to add item into List when checked checkBox on Android In my application i have 3 checkBoxs. And i want when checked each of this checkboxs add value into List<integer> and when unchecked it, remove this value from List<Integer>.
For example : I have 3 ceckboxs .
Android - Ios - Windows .
I want when Android is checked add number 2 into List.
when Ios is checked add number 4 into List.
when Windows is checked add number 8 into List.
And when uncheck each of this checkboxs, remove this number from List.
I write below codes, but not show me true result!
btnTesterSignUp.setOnClickListener(v -> {
        if (signUp_pcCheck.isChecked()) {
            userDevicesList.add(0, 2);
        } else {
            if (userDevicesList.size() > 0)
                try {
                    userDevicesList.remove(0);
                } catch (Exception e){

                }
        }

        if (signUp_mobileCheck.isChecked()) {
            userDevicesList.add(1, 4);
        } else {
            if (userDevicesList.size() > 0)
                try {
                    userDevicesList.remove(1);
                } catch (Exception e){

                }
        }

        if (signUp_tabletCheck.isChecked()) {
            userDevicesList.add(2, 8);
        } else {
            if (userDevicesList.size() > 0)
                try {
                    userDevicesList.remove(2);
                } catch (Exception e){

                }
        }

        Log.e("userDevicesLog", userDevicesList.toString());

    });

A: Check this:
        List<Integer> list = new ArrayList<>();
        CheckBox ios = ...
        CheckBox android = ...
        ios.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked)
                list.add(2);
            else if (list.contains(2))
                list.remove(Integer.valueOf(2));
        });
        android.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked)
                list.add(4);
            else if (list.contains(4))
                list.remove(Integer.valueOf(4));
        });


text:
Q: Launching a program (explorer extension) by keyboard hotkey? Wrote an explorer extension using sharpshell, that renames the highlighted files to a randomly generated name. But I just can't figure out how to make renaming work with the hotkeys shfit + f2.
The documentation contains Shortcut Keys, but as I understand it locally while the program is running, and I need to globally change the keyboard shortcuts in the windows environment.
namespace FileSystemScanner
{
    [ComVisible(true)]
    [COMServerAssociation(AssociationType.AllFiles)]
    [COMServerAssociation(AssociationType.Directory)]
    public class FileInfoExtension : SharpContextMenu
    {
        protected override bool CanShowMenu()
        {
            return true;
        }

        protected override ContextMenuStrip CreateMenu()
        {
            // create the menu strip.
            var menu = new ContextMenuStrip();
            var RenameFileItem = new ToolStripMenuItem
            {
                Text = "Случайное имя",
                Image = Properties.Resources.random,
                ShortcutKeys = Keys.Shift | Keys.F2
            };
            RenameFileItem.Click += (sender, args) => RenameFile();
            menu.Items.Add(RenameFileItem);
            return menu;
        }

        private void RenameFile()
        {
            foreach (var filePath in SelectedItemPaths)
            {
                string patchwitoutname = Path.GetDirectoryName(filePath);
                string exten = Path.GetExtension(filePath);
                string oldname = Path.GetFullPath(filePath);
                string newname = patchwitoutname + "\\" + GeneratedName() + exten;

                System.IO.Directory.Move(oldname, newname);
            }

        }

        private static readonly Random rnd = new Random();

        public string GeneratedName()
        {
            string parameters = "abcdefghijklnopqrstuvwxyz1234567890";
            int count = 13;
            string result = "";
            int lenght = parameters.Length;
            for (int i = 0; i < count; i++)
            {
                result += parameters[rnd.Next(lenght)];
            }
            return result;
        }
    }

}

A: If you using a Windows Forms; just needed to in designer comfirm a KeyDown action:
        private void yourForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode.ToString() == "2")
                //your code here;
        }

For shift action, you need to use just e.Shift


text:
Q: Force encode/databases to use asyncpg instead of psycopg2 Recently, I am trying to use encode/databases packages with my postgres db. I have done all correctly. But when I go to run it with uvicorn, I see that it shows me that psycopg2 is not installed. I do not wan to use psycopg2. So, I restated all and run databases[postgresql] instead of databases only. I also installed asyncpg. But I am still seeing the same err. I was also doing everything in a virtual environment. My code is attached below:
import databases, sqlalchemy, asyncpg
from fastapi import FastAPI

#POSTGRES DATABASE
DATABASE_URL = "postgresql://xxxxxxxxxxx" # hidden
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()

users = sqlalchemy.Table(
    "py_users",
    metadata,
    sqlalchemy.Column("id"        , sqlalchemy.String, primary_key=True),
    sqlalchemy.Column("username"  , sqlalchemy.String),
    sqlalchemy.Column("password"  , sqlalchemy.String),
    sqlalchemy.Column("first_name", sqlalchemy.String),
    sqlalchemy.Column("last_name" , sqlalchemy.String),
    sqlalchemy.Column("gender"    , sqlalchemy.CHAR  ),
    sqlalchemy.Column("created_at", sqlalchemy.String),
    sqlalchemy.Column("status"    , sqlalchemy.CHAR  ),
)

engine = sqlalchemy.create_engine(
    DATABASE_URL
)
metadata.create_all(engine)

app = FastAPI()

@app.get('/users')
def find_all_users():
    return "List All Users"

and the traceback is:
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [110] using statreload
Process SpawnProcess-1:
Traceback (most recent call last):
  File "/usr/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
    self.run()
  File "/usr/lib/python3.8/multiprocessing/process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "/home/runner/HelloCoderFastAPITuto/env/lib/python3.8/site-packages/uvicorn/subprocess.py", line 61, in subprocess_started
    target(sockets=sockets)
  File "/home/runner/HelloCoderFastAPITuto/env/lib/python3.8/site-packages/uvicorn/_impl/asyncio.py", line 47, in run
    loop.run_until_complete(self.serve(sockets=sockets))
  File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/home/runner/HelloCoderFastAPITuto/env/lib/python3.8/site-packages/uvicorn/_impl/asyncio.py", line 54, in serve
    config.load()
  File "/home/runner/HelloCoderFastAPITuto/env/lib/python3.8/site-packages/uvicorn/config.py", line 306, in load
    self.loaded_app = import_from_string(self.app)
  File "/home/runner/HelloCoderFastAPITuto/env/lib/python3.8/site-packages/uvicorn/importer.py", line 23, in import_from_string
    raise exc from None
  File "/home/runner/HelloCoderFastAPITuto/env/lib/python3.8/site-packages/uvicorn/importer.py", line 20, in import_from_string
    module = importlib.import_module(module_str)
  File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "./main.py", line 22, in <module>
    engine = sqlalchemy.create_engine(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/sqlalchemy/engine/__init__.py", line 500, in create_engine
    return strategy.create(*args, **kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/sqlalchemy/engine/strategies.py", line 87, in create
    dbapi = dialect_cls.dbapi(**dbapi_args)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/sqlalchemy/dialects/postgresql/psycopg2.py", line 778, in dbapi
    import psycopg2
ModuleNotFoundError: No module named 'psycopg2'

From the above errors I think that the package databases is trying to use psycopg2 instead of asyncpg. And in that case how do I force the databases package to use asyncpg instead of psycopg2. If that is not the case how do I use asyncpg instead of using psycopg2?
Thanks in advance.
My question may have some mistakes. Please ignore those silly mistakes and just edit the question if you find any mistakes in my question

A: You need a different connection string for SQLAlchemy.
DATABASE_URL = "postgresql://xxxxxxxxxxx" # database url for databases library
DATABASE_URL_SQLALCHEMY = "postgresql+asyncpg://xxxxxxxxxxx" # database url for SQLAlchemy

Also metadata.create_all(engine) won't work since that function don't include an awaitable hook.
Checkout https://docs.sqlalchemy.org/en/14/orm/extensions/asyncio.html for more information.

A: The documentation for databases clearly states, and I quote:

Note that if you are using any synchronous SQLAlchemy functions such as engine.create_all() or alembic migrations then you still have to install a synchronous DB driver: psycopg2 for PostgreSQL and pymysql for MySQL.

And you have this piece of code inside your program:
engine = sqlalchemy.create_engine(
    DATABASE_URL
)
metadata.create_all(engine)

A: No, in your case SQLAlchemy trying to use psycopg2.
See the error:

opt/virtualenvs/python3/lib/python3.8/site-packages/sqlalchemy/dialects/postgresql/psycopg2.py

When declaring tables, it is done by SQLAlchemy. But the connections between that, it is done by asyncpg.
In the documentation it clearly states

Driver support is providing using one of asyncpg.

So you do not need to worry about that. Encode will use asyncpg.


text:
Q: Getting Mass Pay Information via API Using the NVP Classic API: I am trying to get information on Mass Payment that was sent via our PayPal account. I can find the Mass Pay using TransactionSearch but when I try to get the TransactionsDetails of it, but I get a permission error. I tried adding all permissions possible but its the same error:
"You do not have permission to get the details of this transaction"
I really would like to get the details of this Mass Pay rather than having to rely on the 1 IPN URL in my account to receive it.
Also I notice I can find the individual transactions that were sent because of the Mass Pay but they have no information in them relating them to a Mass Payment or the Unique ID I assigned them. The best I can think of to verify if a Mass Payment was sent is to search for the email and amount using TransactionSearch and see if a matching one within the same date range exists. Not very fun.

A: It seems you dug into this quite a lot, so this might not be any news to you, but still for reference and hopefully some affirmation and clarification:
There does not seem to be a way to pull transaction details about the individual payments using the NVP-API at the moment. As you might already know, the official documentation points to either the Account History or IPN for Mass Payments reporting.
Account history
As you want to access the transaction details programmatically, logging into the site to access your account history is not feasible. However, the simplest solution seems to (automatically) download the transaction logs for your Mass Payments and extract the information (mainly the status of each payment) from it. You could do this periodically or even on demand to check the status of all your payments.

You can either download a Mass Payments transaction as a whole or download information about the individual transactions generated by the Mass Payments transaction.

This seems to be the best solution to get a machine readable list of all the transactions at once. Also, this can work as a fallback if for some reason your IPN listener misses status updates (also: you can resend them later on).
IPN listeners
Setting up an IPN listener seems to be the best solution to get "real-time" updates about the payments. I do not know specifics about your use case, so I don't know why you kind of ruled this solution out.
As the NOTIFYURL field is not available for Mass Payments, you are stuck with the one IPN endpoint set for your account/profile. This does not seem to be a big problem (again: I don't know any details), as you should be able to filter and sort the notifications using the IPN MassPay variables, which give you the mass payment reference that you were looking for. This might require some sort of persistence on your side to keep track about status changes. Or you could combine this with the CSV report.

There doesn't seem to be a (documented) way to access the individual payments in the context of the Mass Payment via the NVP-API, but I am confident that you can set up a monitoring system that suits your needs. I know that the PayPal documentation and APIs are sometimes cumbersome, but at least I learned today that they started to deprecate their PDF specs in favor of online documentation.


text:
Q: Observer effect with humans According to the observer effect, physical systems can behave differently when there is an 'observer'. This has been demonstrated in cases where the 'observer' is a machine.
It seems logical that if machines can effect processes, than human beings can do this too. After all, our bodies work in some ways like a complex machine.
Has it ever been experimentally demonstrated that observation by human beings can effect physical processes?
A way to check this would be: repeat the physical process twice. The first time, a human only observes the result at the end. The second time, he observes what happens throughout the entire process.
Remark
As I said above, it is very clear that the observer effect can happen when the observer is a machine. My question is, whether this can also happen when the observer is a human mind, and whether this has been experimentally verified.

A:
Has it ever been experimentally demonstrated that observation by human
beings can effect physical processes?

If the question is just, "is there evidence that humans have observed systems that are changed when they are observed?", the answer is that yes this is the whole point of quantum mechanics.
If your question is that if it is required for a human mind to be the thing that is collapsing the quantum state, then this is a less-accepted, less-popular interpetation of quantum mechanics.  I believe most physicists would insist that there is nothing special about the mind and that a simple detector can create this effect of collapsing a state.
If you want an experiment that tries to look at the difference between when you make a measurement of something, versus when someone else (human or detector) makes a measurement of something -- this creates a paradox in typical interpretations of quantum mechanics. The paradox is known as the Wigner's friend problem.
I suggest reading more about the Wigner's friend problem if you want to try to understand some of the pecularities of what happens when you think seriously about wavefunction collapse in qantum mecahnics.

A: Observation affects measurements in quantum systems. Humans (and other similar life forms) behave classically. So, there can not be an experiment conducted, in which observations affect measurement...


text:
Q: How to build a Kony iOS Project using commandline My aim is to build a Kony Project for the Jenkins CI. So basically I need to know how to build the project on the unix commandline. When using Kony Studio my project builds without issues.
I've already managed to build an android .apk using ant on the build.xml in the project directory. This also builds a .kar file for ios. How do I now trigger the ipa build via xcode using the commandline?
Environment: Mac OSX 10.10.2 with Kony Studio 6.0.

A: You need to copy the "com.kony.ios_5.5.x.jar" file  and rename it to "com.kony.ios_5.5.x.zip".
    Unzip the "com.kony.ios_5.5.x.zip",
    The unzipped folder contains 5 files, one of it is "**iOS-GA-5.5.x.zip**".
    Make sure that you DO NOT delete any of these 5 files.

    Unzip the "iOS-GA-5.5.x.zip" , it will give you the "VMAppWithKonylib" folder.

    Now, close all the xcodes you might have open.

    Then delete data at path Users/(UserName)/Library/Developer/Xcode/DerivedData

    Now go to Terminal

    Navigates upto Gen folder using cd (e.g. cd /Users/foo/Desktop/VMAppWithKonylib/gen)

    Type pearl extract.pl <KAR file path> and launch the Xcode and do a build. (e.g. perl extract.pl /Users/foo/Downloads/konyappiphone-193.kAR)

Now type open <xcodeproj path>. (e.g. open /Users/foo/Desktop/VMAppWithKonylib/VMAppWithKonylib.xcodeproj)

Now the app will run in xcode. Archive and proceed with IPA generation.

A: EDIT START
As of Kony 7 there is a better way to do headless builds:
http://docs.kony.com/konylibrary/visualizer/visualizer_user_guide/Content/CommandLine.htm
Basically use the HeadlessBuild.properties to configure your build and launch it with ant. It's a struggle in the beginning but we got a successful build of android and iOS via Jenkins.
Note: Building multiple projects at the same time does not seem to work (e.g. for multiple build types) and results in an error message. You'll have to build sequentially.
Comment if you're interested in the further build process and I'll consider writing a blog post about this :)
EDIT END
Finished a first version of a shell script to build a Kony Project for Android and iOS for Jenkins. Its far from elegant or perferct but it might be a good start for anyone who stumbles accross this post.
First I created a settings script which contains the configuration of my build (all values-to-be-entered are shown as <value> tags):
#!/bin/bash

# This script builds a Kony Project with following steps
# 1.  Inject settings into global.properties, build.properties, middleware properties
# 2.  Build Project by executing ant build.xml
# 2.1 When building android apps these are already packed as .apk
# 2.2 APK is signed
# 3.  If iOS app is build the iOS dumyWorkspace (VMAppWithKonylib) is unzipped and filled with KAR file from ant build
# 3.1 the iOS app is archived
# 3.2 this iOS app is signed and exported as ipa
# 4.  all APK and IPA files are copied to deploys folder.

# Note: The Directory the Kony Project is inside must be the name of the Kony Project. otherwise it will not build. This means, that if you clone your project from repository you'll have to put it into a folder or already have it checkedin as a folder.

_project_name=<Kony Application Project name. e.g. KonyTemplate>

# Targets
_target_android_phone=true
_target_android_tablet=false
_target_ios_phone=true
_target_ios_tablet=false

# Middleware Config
_middleware_ipaddress=127.0.0.1
_middleware_httpport=8080
_middleware_httpsport=443

# tools
_android_home=<android sdk home>
_android_zipalign=<zipalign in android build-tools>
_eclipse_equinox=<eclipse equinox jar in kony studio. e.g. /Users/userxyz/Kony_Studio/plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
_ant_bin_dir=<ant binary directory e.g. /usr/local/bin>

# you will need this parameter if you build an ios project. It is the You can retrieve it like this:
# - search for file "com.kony.ios_x.x.x.GA_vxxxxxxxxxxxx.jar" in Kony_Studio/plugins/ Folder
# - copy it to another folder and rename it as .zip
# - unzip
# - retrieve file "iOS-GA-x.x.x.zip" and copy it to destination referenced in _ios_dummy_project_zip variable
_ios_dummy_project_zip=<location of kony ios workspaced (zipeed). e.g. /Applications/Kony/Kony_Studio/iOS-GA-6.0.2.zip>

# OS Code Signing
_ios_code_sign_identity='<code sign identity>'
_ios_provisioning_profile_uuid='<xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx>'
_ios_provisioning_profile_name='<provisioning profile name'

# Android signing
_android_storepass=<keystore password>
_android_keyalias=<keystore alias>
_android_keypass=<key password>
_android_keystore=<keystore file within kony project directory. e.g. keystore.jks>

# Settings End
############################################################

# Execute
sh ./jenkins_build_internal.sh $_project_name $_target_android_phone $_target_android_tablet $_target_ios_phone $_target_ios_tablet $_middleware_ipaddress $_middleware_httpport $_middleware_httpsport $_removeprintstatements $_build $_android_home $_eclipse_equinox $_ant_bin_dir $_ios_dummy_project_zip "$_ios_code_sign_identity" "$_ios_provisioning_profile_uuid" "$_ios_provisioning_profile_name" $_android_zipalign $_android_storepass $_android_keyalias $_android_keypass $_android_keystore

I then have the actual script which does the build job as descripted at the top of the first script. Here we also do the Magic which Sam posted.
#!/bin/bash

####################
# Settings

_project_name=$1

# Targets
_target_android_phone=$2
_target_android_tablet=$3
_target_ios_phone=$4
_target_ios_tablet=$5

# Middleware Config
_middleware_ipaddress=$6
_middleware_httpport=$7
_middleware_httpsport=$8

# Build confif
_removeprintstatements=$9
_build=${10}

# Build tools Config
_android_home=${11}
_eclipse_equinox=${12}
_ant_bin_dir=${13}
_ios_dummy_project_zip=${14}

# OS Code Signing
_ios_code_sign_identity=${15}
_ios_provisioning_profile_uuid=${16}
_ios_provisioning_profile_name=${17}

# Android signing
_android_zipalign=${18}
_android_storepass=${19}
_android_keyalias=${20}
_android_keypass=${21}
_android_keystore=${22}

_sleep_while_xcode_startup=15

#######################
# Define functions

function escape_slashes {
    sed 's/\//\\\//g'
}

function change_line {
    local OLD_LINE_PATTERN=$1; shift
    local NEW_LINE=$1; shift
    local FILE=$1

    local NEW=$(echo "${NEW_LINE}" | escape_slashes)
    sed -i .bak '/'"${OLD_LINE_PATTERN}"'/s/.*/'"${NEW}"'/' "${FILE}"
    mv "${FILE}.bak" /tmp/
}

#######################
# Dump Settings
echo "##### Executing Jenkins Kony Build #####"
echo "#     Android Phone = " $_target_android_phone
echo "#     Android Tablet = " $_target_android_tablet
echo "#     iOS Phone = " $_target_ios_phone
echo "#     iOS Tablet = " $_target_ios_tablet
echo "##### Executing Jenkins Kony Build #####"
echo ''

#######################
# Clean

echo "# cleaning up"
rm -rf binaries
rm -rf jssrc

#######################
# Inject properties
echo "# injecting properties"

change_line "^android=" "android=$_target_android_phone" build.properties
change_line "^androidtablet=" "androidtablet=$_target_android_tablet" build.properties
change_line "^iphone=" "iphone=$_target_ios_phone" build.properties
change_line "^ipad=" "ipad=$_target_ios_tablet" build.properties

change_line "^android.home=" "android.home=$_android_home" global.properties
change_line "^eclipse.equinox.path=" "eclipse.equinox.path=$_eclipse_equinox" global.properties

change_line "^httpport=" "httpport=$_middleware_httpport" middleware.properties
change_line "^httpsport=" "httpsport=$_middleware_httpsport" middleware.properties
change_line "^ipaddress=" "ipaddress=$_middleware_ipaddress" middleware.properties

#######################
# Execute Main Build - Ant

echo "## Execute Kony Ant Build - Start ##"
export PATH=$PATH:${_ant_bin_dir}
ant -file build.xml
echo "## Execute Kony Ant Build - Done ##"
echo ''

#######################
# Android app signing

if [ ${_target_android_phone} == "true" -o  ${_target_android_tablet} == "true" ]
    then
    set +x
    echo "## Execute Android signing APK - Start ##"
    cd binaries/android

    jarsigner -storepass "${_android_storepass}" -keypass "${_android_keypass}" -keystore ../../${_android_keystore} luavmandroid.apk ${_android_keyalias} -signedjar luavmandroid-signed_unaligned.apk
    ${_android_zipalign} -v 4 luavmandroid-signed_unaligned.apk luavmandroid-signed.apk
    cd -
    echo "## Execute Android signing APK - Done ##"
    echo ''
fi

#######################
# Check and execute optional ios Workspace build for iphone
if [ ${_target_ios_phone} == "true" ]
    then
    echo "## Execute Kony iOS Workspace creation - Start ##"
    cd ..
    echo "# unzipping workspace #"
    rm -rf VMAppWithKonylibiphone
    unzip $_ios_dummy_project_zip -d .
    mv VMAppWithKonylib VMAppWithKonylibiphone
    cd VMAppWithKonylibiphone
    cd gen

    echo "# filling workspace #"
    perl extract.pl ../../webapps/KonyTemplater/kbf/konyappiphone.KAR
    # back to ios Workspace
    cd ..
    echo "## Execute Kony iOS iPhone Workspace creation - Done ##"

    # dirty piece of code to create the scheme files... open xcode and close it again :)
    echo "# opening project to generate scheme"
    open VMAppWithKonylib.xcodeproj
    sleep ${_sleep_while_xcode_startup}
    echo "# close project"
    osascript -e 'quit app "Xcode"'

    echo "## Execute Kony iOS Archive - Start ##"
    # create signed archive
    xcodebuild -scheme KRelease -archivePath build/Archive.xcarchive archive PROVISIONING_PROFILE="${_ios_provisioning_profile_uuid}" CODE_SIGN_IDENTITY="${_ios_code_sign_identity}"
    echo "## Execute Kony iOS Archive - Done ##"

    echo "## Execute Kony iOS IPA Generation - Start ##"
    # create ipa
    xcodebuild -exportArchive -exportFormat IPA -archivePath build/Archive.xcarchive -exportPath build/KonyiOSApp.ipa -exportProvisioningProfile "${_ios_provisioning_profile_name}"
    echo "## Execute Kony iOS IPA Generation - Done ##"
    echo ''
fi

#######################
# Check and execute optional ios Workspace build for ipad
if [ ${_target_ios_tablet} == "true" ]
    then
    echo "## Execute Kony iOS Workspace creation - Start ##"
    cd ..
    echo "# unzipping workspace #"
    rm -rf VMAppWithKonylibipad
    unzip $_ios_dummy_project_zip -d .
    mv VMAppWithKonylib VMAppWithKonylibipad
    cd VMAppWithKonylibipad
    cd gen

    echo "# filling workspace #"
    perl extract.pl ../../webapps/KonyTemplater/kbf/konyappipad.KAR
    # back to ios Workspace
    cd ..
    echo "## Execute Kony iOS iPhone Workspace creation - Done ##"

    echo "# opening project to generate scheme"
    open VMAppWithKonylib.xcodeproj
    sleep ${_sleep_while_xcode_startup}
    echo "# close project"
    osascript -e 'quit app "Xcode"'

    echo "## Execute Kony iOS Archive - Start ##"
    # create signed archive
    xcodebuild -scheme KRelease -archivePath build/Archive.xcarchive archive PROVISIONING_PROFILE="${_ios_provisioning_profile_uuid}" CODE_SIGN_IDENTITY="${_ios_code_sign_identity}"
    echo "## Execute Kony iOS Archive - Done ##"

    echo "## Execute Kony iOS IPA Generation - Start ##"
    # create ipa
    xcodebuild -exportArchive -exportFormat IPA -archivePath build/Archive.xcarchive -exportPath build/KonyiOSApp.ipa -exportProvisioningProfile "${_ios_provisioning_profile_name}"
    echo "## Execute Kony iOS IPA Generation - Done ##"
    echo ''
fi

echo "## Copy Binaries to ./deploys/ ##"
cd ..
mkdir deploys
cp VMAppWithKonylibipad/build/KonyiOSApp.ipa deploys/app-release-ipad.ipa
cp VMAppWithKonylibiphone/build/KonyiOSApp.ipa deploys/app-release-iphone.ipa
cp ${_project_name}/binaries/android/luavmandroid-signed.apk deploys/app-release-android.apk
echo ''

echo ''
echo "## JENKINS BUILD SUCCESS ##"
echo ''

In the jenkins configuration I now only call the first script by executing a shell script:
cd KonyTemplate
sh ./jenkins_build.sh

If anyone has any suggestions to improve this little script (and there most definitely are plenty), I'm sure we'll all be happy to hear them.


text:
Q: Pass a JSON object inside the function Is it possible to pass a JSON object as an argument in the first function, then pass the same JSON object into second function from the first function?  Do I need to extract it first, then stringify before pass it to the second function?
Thanks
For example, I have the following JSON object
var client=[{"clientID":"1234",
             "businessName":"ABC Corporation",
             "legalName":"DCF Inc.",
             "clientName":"John"}];

I pass this Client JSON object into the first function:
function saveClient(clients){

// inside this function, I want to pass this whole Client object into the
// second function

    function showClient(clients){
    // so inside this function, I can parse this Client object to get the
    // string and value
    var clientID=client.clientID;
    var businessName=client.businessName;
    .....
    .....
    }
}

A: Certainly, just pass the array element you want (assuming i is the index of the client of interest):
showClient(clients[i]);

There is definitely no need to "stringify" or anything like that, since you're working entirely within Javascript here.


text:
Q: Single chip power good IC? It seems like there should be a million chips for this, but for the life of me can't find any. I'm looking for a small (SOT23 or similar size if possible) IC that provides an active high when the supply voltage goes ABOVE a setpoint, and open circuit when below. Looking for ~3V trigger with up to 6V operation.
There are plenty of reset monitors that pull low when the voltage drops below the setpoint, but all the ones I've found only work down to a certain voltage, and go open circuit again when volts totally disappears. I'm using 2 different power supplies so that doesn't help me. I'm currently using the STM1061N31WX6F but discovered it doesn't work for me when there's no supply at all.
I could of course do it with several discrete components, opamps, even a microcontroller solution, but I was hoping there was a single chip solution. Google and Digikey are not being my friend today.

A: Look for the TPS37xx range of voltage supervisor ICs with open-drain outputs from Ti. Choose one that is stocked somewhere...

A: There are plenty of those. Following is MIC841LBC5TR from Micrel Inc., available at Digi-Key.


text:
Q: inequality involving the sides of a triangle I want to show that if $\alpha > \beta >\gamma> 0$ and $\beta - \gamma <\alpha < \beta+\gamma$   then
$α^6-4α^4 β^2+5α^2 β^4-2β^6-4α^4γ^2+3α^2 β^2γ^2-β^4γ^2+5α^2γ^4-β^2γ^4-2γ^6<0$
I tried it in Mathematica with the Reduce command and it showed that it holds.
Can anyone help?

A: Note that
$$\alpha > \beta > \gamma > 0; \ \beta - \gamma < \alpha < \beta + \gamma
\quad \Longleftrightarrow \quad \alpha = r + 2s + t, \ \beta = r + s + t, \ \gamma = r + s; \ s, t, r > 0.$$
Denote LHS as $f$. Using the substitutions $\alpha = r + 2s + t, \ \beta = r + s + t, \ \gamma = r + s; \ s, t, r > 0$, we have
\begin{align}
f &= -20 r^4 s^2-20 r^4 s t-8 r^4 t^2-92 r^3 s^3-138 r^3 s^2 t-62 r^3 s t^2-8 r^3 t^3-149 r^2 s^4-298 r^2 s^3 t\\
&\quad -183 r^2 s^2 t^2-34 r^2 s t^3-2 r^2 t^4-96 r s^5-240 r s^4 t-200 r s^3 t^2-60 r s^2 t^3-4 r s t^4-18 s^6\\
&\quad -54 s^5 t-60 s^4 t^2-30 s^3 t^3-6 s^2 t^4.
\end{align}
Clearly $f < 0$.


text:
Q: Print Arrays and maximum recurring element I have 1 string of alphabetical characters. Each character can
occur 1 or more times.I want to put every third character into an array like 3rd,6th,9th,12th
I want to Print the arrays and also the maximum recurring element.
Sample Input 1:
S = "abcbjjfgqaazckuccccpcp"

Sample Output:
[ c, j, g, a, k, c, c]

Maximum recurring character: c

A: You can get this done using the below code:
s = 'abcbjjfgqaazckuccccpcp'

#print ('[ c, j, g, a, k, c, c]') #your reference of 3rd, 6th, 9th is wrong

print (list(s[2::3]))

#store the char and count as a dictionary
d = {x:s[2::3].count(x) for x in set(s[2::3])}

#get key for max value from dictionary
mkey = max(d, key = d.get)
mval = d[mkey]

#print both key and value
print (mkey,mval)

The output will be
['c', 'j', 'q', 'z', 'u', 'c', 'c']
c 3


text:
Q: Mysql, How to custimize timestemp while selecting data Please I have a field date type timestamp (format 2013-03-29 14:32:34).
I want to select data from the table and group them by the field date but without time, I mean only by the format Y-m-d.
So I've tried :
SELECT date (Y-m-d) FROM table GROUP BY date (Y-m-d)

This return false. Please How could I do ? Thanks in advance.

A: To extract the date part of the datetime, use DATE()
SELECT DATE(date) FROM ...
GROUP BY DATE(date)


text:
Q: Kähler metrics on holomorphic vector bundles Let $(X,\omega)$ be a Kähler manifold not necessarily compact of complex dimension $n$. Let $\pi:E\to X$ be a holomorphic vector bundle of rank $r$, then $E$ can be seen as a complex manifold of complex dimension $n+r$. I also read that the total space of the canonical bundle $K_X:=\bigwedge^n(T^{1,0}X)^*$ over $X$ has a structure of a non-compact Calabi Yau manifold. Then it is natural to ask if a (complete) Ricci-flat Kähler metric exists on such manifold.
Could you please give me some references in which the authors treat this case with full details? I'm interested also in all the local calculation starting from the manifold structure on the bundle.

A: In Métriques Kähleriennes et fibrés holomorphes, Calabi showed that the total space of the canonical bundle or the cotangent bundle of a positive Einstein-Kähler manifold admits a complete, Ricci-flat Kähler metric.
Corollary B.2 in A momentum construction for circle-invariant Kähler metrics extends this to the total space of a tensor product of canonical bundles over a product of positive Einstein-Kähler manifolds. The calculations here are explicit, enough so that it's easy to plot the fibre metric as a surface of rotation in Euclidean three-space.


text:
Q: What do I have to do to add a new hard drive to an existing Linux system? I have a new mechanical hard drive I would like to add to my Ubuntu 10.10 system.
Currently, I have a 128 GB SSD hard drive which contains my whole / partition. I would now like to add a 1 TB HDD to the system, but without reinstalling Ubuntu.
Is this just a simple matter of plugging the new hard drive in or is there something more?

A: Yes basically it's sufficient to plug in the new drive and boot up the computer. It should be automatically recognized, though you still need to partition and format it in order to use it.

A: It is a simple matter of plugging the thing in, and possible searching for an appropriate driver.
It should probably be empty save for a few "included programs" in many cases but you can delete those.
If you want to move your /home folder to that drive to keep strain off your SSD, you'd be advised to check out this tutorial.


text:
Q: React router routes not working I have 2 basic routes like this:
<Route name="app" path="/" handler={Home}>
    <Route name="profile" path="profile" handler={Profile}/>
</Route>

Now, I want the default page ( mysite.com/page ) to just show the Home Component.
And when I browse to mysite.com/page#/profile , I want it to just show the Profile component.
However, both URLs just show the 'Home' component. And the Profile component is never seen.
Any clue as to what I have misconfigured? ( there are no errors in the console )

A: Have you tried surrounding Route with Router  :
var Router = require('react-router');

var DefaultRoute = Router.DefaultRoute,
    Link = Router.Link,
    Route = Router.Route,

then...
<Router history={history}>
    <Route component={App}>
      <Route name="app" path="/" handler={Home}>
      <Route name="profile" path="profile" handler={Profile}/>
      <DefaultRoute handler={Home}/>
    </Route>
  </Router>

check this link here


text:
Q: Spotfire line chart multiple axis 2 or more columns on left axis with just one scale I have a line chart with multiple axis (3 columns on the left and one on the right). I know how to make the right axis use a different scale but is there a way to make the three columns on the left display just one scale instead of one for each line on the left being drawn?
Thank you,
Chris Habrock

A: I don't think there is a built-in way to do this. with "Multiple Scales" turned on, Spotfire will create a scale for each column used on the axis.
you could try to combine the three columns into one column. I'm not sure if this will meet your requirements but it's the best workaround I can think of.
if your data is like:
ID    val1    val2    val3
1     100     111     121
2     200     222     232
3     300     333     343
...

use an unpivot transforation to get:
ID    Value    Category    val3*
1     100      val1        121
1     111      val2        121
2     200      val1        232
2     222      val2        232
...

*NOTE that I included [val3] here as a "pass through" column, but I don't recommend doing this. if you try to plot right the above, you'll get duplicate points for [val3].
instead, Insert...Rows and insert the [val3] column from your original table. finally, you want something like this:
ID    Value    Category    val3*
1     100      val1
1     111      val2
2     200      val1
2     222      val2
1                          121
2                          232
...

and then plot your line chart on this. set the vertical axis to [Value],[val3] and then color by [Category]

I recommend to do this transformation in a "virtual" table (Add Data Table...From Analysis to make a linked copy of an existing table, then do your manipulations on that table). this way you don't have an issue of altering your other visulizations and your transformed table is always up to date.


text:
Q: Is MANOVA the correct analysis for this case? During an experiment I presented participants with some sound stimuli and I asked them to modify two parameters of the sound (Centroid and Sound_Level_Peak) to reach a given experimental goal. The sounds represented hand interactions with different kinds of materials by means of different kinds of objects, and where created thanks to a parametric synthesizer.
The initial sounds (preset sounds) had a value for those two parameters. What I am interested in is whether participants' modifications of the two parameters of the sound stimuli resulted in values actually different from the initial values of the parameters of the preset sounds.
In more details, the experiment involved 19 subjects, who where subjected to 12 kinds of stimuli, each based on 3 presets of centroid and peak level (so in total there where 36 stimuli). Each stimulus was repeated twice for a total of 72 trials per subject. Accordingly, the number of presets was 72.
To give an idea, some rows of my data set are the following:
> head(scrd)
Stimulus_Type   Centroid        Sound_Level_Peak    Preset
Stimulus_A      1960.2          -20.963             no
Stimulus_A      5317.2          -42.741             no
.....
Stimulus_B      11256.0          -16.480            no
Stimulus_B      9560.3          -19.682             no
.....
.....
Stimulus_A      1900.2          -18.63             yes
Stimulus_A      5617.6          -44.41             yes
Stimulus_B      12056.0          -17.80            yes
Stimulus_B      8960.5          -21.82             yes

This is the analysis I performed:
> fit <- manova(cbind(Centroid,Sound_Level_Peak)~ Stimulus_Type*Preset, data=scrd)
> summary(fit, test="Pillai")
                       Df  Pillai approx F num Df den Df  Pr(>F)
Stimulus_Type          11 0.91888  106.629     22   2760 < 2e-16 ***
Preset                  1 0.00343    2.371      2   1379 0.09378 .
Stimulus_Type:Preset   11 0.01155    0.729     22   2760 0.81348
Residuals            1380
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
>

These results should then say that for each stimulus type there is no difference between the patterns of the two parameters in the preset and modified conditions.
Can anyone please tell me if this analysis is correct or suggest how to perform in R an alternative analysis?


text:
Q: Detect iPad Air/3 I ma in trouble with detecting iPad. I have a code for detecting if its iPhone 4/4s, iPhone 5/5s or iPad mini. But I have no idea how to detect iPad air(1536 x 2048). If I use this code it returns me for iPad retina in simulator the settings I set for iPhone 5.
 if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
            if ([[UIScreen mainScreen] scale] == 2.0) {
                if([UIScreen mainScreen].bounds.size.height == 568){
                   //iPhone5
                } else{
                    //Iphone4
                     }
        }else {
           //iPadmini

        }}

A: Finally fixed it!
#define iPhone4Or5oriPad ([[UIScreen mainScreen] bounds].size.height == 568 ? 5 : ([[UIScreen mainScreen] bounds].size.height == 480 ? 4 : 999))

    if (iPhone4Or5oriPad==4) {
                                 NSLog(@"This is 3.5 inch iPhone - iPhone 4s or below");
                             } else if (iPhone4Or5oriPad==5) {
                                 NSLog(@"This is 4 inch iPhone - iPhone 5 & above");
                             } else {
                                 NSLog(@"This is iPad");
                             }


text:
Q: code repeat in overloaded constructor I've a class with some overloaded constructor and no default constructor. The overloaded constructor essentially do the same things but differ on the type of params provided. Let's say I've a class as follows -
struct info {
  int one;    // must be filled
  int two;    // can be empty
  int three;  // can be empty
}

class A {
    int a;
    double b;
    float c;
    info I;

  public:

    A(a,b,c,one) :
      a(a),
      b(b),
      c(c)
    {
        // some processing
        I.one = one;
        // some other processing
        ....
    }

    A(a,b,c,i) :
      a(a),
      b(b),
      c(c),
      I(i)
    {
        // some processing
        // some other processing
        ....
    }

}

The processing and some processing part is repeating and is slightly dependent on certain paths which are frequently edited, forcing us to do same and same changes to both places.
Can this be reduced to same constructor in some way? I was hoping to do something with constructor delegation, but wasn't able to think of a clever way to do this :/

A:
Can this be reduced to same constructor in some way?

Yes. In C++11 there are delegating constructor.
For example:
class Foo {
public:
  Foo(char x, int y) {}
  Foo(int y) : Foo('a', y) {} // Foo(int) delegates to Foo(char,int)
};

EDIT:
As requested, take your example:
class A {
 private:
  A (int _a, double _b, float _c) : a(_a),
                                    b(_b),
                                    c(_c) {
    // This constructor does a lots of stuff...
  }

 public:
  A (int _a, double _b, float _c, int _one) : A(_a, _b, _c) {
    I.one = _one
    // This constructor does nothing
    // Because A(_a, _b, _c) already does everything
  }

  A (int _a, double _b, float _c, info _info) : A(_a, _b, _c) {
    I = _info;
    // This constructor does nothing
    // Because A(_a, _b, _c) already does everything
  }
};

A: Just create a proper ctor for info:
struct info {
  int one;    // must be filled
  int two;    // can be empty
  int three;  // can be empty

  info( int lone, int ltwo = 0, int lthree = 0 ) :
      one( lone ), two( ltwo ), three( lthree ) {}
};

then you only need one ctor for class A that accepts info, or you can express that explicitly:
 A(int la, double lb, double lc, int one) :
    A( la, lb, lc, info( one ) )
 {
 }


text:
Q: How can I create Yes/No dialog in C# .NET Framework So I tryed to make a simple text game.And I wanted to do Yes/No dialong I was trying to figure this out for 2 hours, but i didn't find any solution to my problem. I'm total beginner, so I don't know much about coding.
I was trying to achive it trough "bool" bot it wasnt the right option. Obviousli.
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace TEXTRPG

{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Greetings, stranger.");

            Console.ReadKey();

            Console.WriteLine("I've came here to give you a quest.");
            Console.ReadKey();
            Console.WriteLine("Do you accept?");
            //Yes/No
            Console.ReadKey();

A: Here is my sample
do {
        Console.Write("Do you accept? [y/n] ");
        response = Console.ReadKey(false).Key;
        if (response != ConsoleKey.Enter)
            Console.WriteLine();
    } while (response != ConsoleKey.Y && response != ConsoleKey.N);


text:
Q: Replace string in a element with vanilla JS Im using a jQuery script to replace text in an element. Now I need to do this with plain Javascript.
How do I do that?
This is the script I'm currently using:
$('document').ready(function(){
    $( ".tp-caption.black:contains('.000000')" ).text('.1111111');
});

A: Using a small polyfill like this:
function hasClass(element, cls) {
    return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}

You can do something like:
// Get all the elements.
var elements = document.getElementsByClassName("tp-caption");
// Iterate each.
for (var i = 0; i < elements.length; i++) {
    // Check if the text is found.
    if (elements[i].innerHTML.indexOf(".000000") != -1 && hasClass(elements[i], "black"))
        // Replace the contents.
        elements[i].innerHTML = '.1111111';
}

This replaces the whole string. If you wanna replace only that part, then use this:
// Get all the elements.
var elements = document.getElementsByClassName("tp-caption");
// Iterate each.
for (var i = 0; i < elements.length; i++) {
    // Check if the text is found.
    if (elements[i].innerHTML.indexOf(".000000") != -1 && hasClass(elements[i], "black"))
        // Replace the contents.
        elements[i].innerHTML = elements[i].innerHTML.replace('.000000', '.1111111');
}

Gosh, you can even do this way:
// Get all the elements.
var elements = document.getElementsByClassName("tp-caption black");
// Iterate each.
for (var i = 0; i < elements.length; i++) {
    // Check if the text is found.
    if (elements[i].innerHTML.indexOf(".000000") > -1)
        // Replace the contents.
        elements[i].innerHTML = '.1111111';
}

// Get all the elements.
var elements = document.getElementsByClassName("tp-caption black");
// Iterate each.
for (var i = 0; i < elements.length; i++) {
    // Check if the text is found.
    if (elements[i].innerHTML.indexOf(".000000") > -1)
        // Replace the contents.
        elements[i].innerHTML = elements[i].innerHTML.replace('.000000', '.1111111');
}

And for modern browsers, you can simply use:
// Get all the elements.
var elements = document.querySelectorAll(".tp-caption.black");
// Iterate each.
for (var i = 0; i < elements.length; i++) {
    // Check if the text is found.
    if (elements[i].innerHTML.indexOf(".000000") != -1)
        // Replace the contents.
        elements[i].innerHTML = elements[i].innerHTML.replace('.000000', '.1111111');
}

A: If you're wanting the whole thing in Vanilla JS its like this:
var arr = document.getElementsByClassName('tp-caption black');
for (var i = 0; i < arr.length; i++)
{
    var t = arr[i].innerHTML;
    t = t.replace('.000000', '.111111');

    arr[i].innerHTML = t;
}

If you're wanting just the replace bit in Vanilla JS its like this:
var t = $('.tp-caption.black').text();
$('.tp-caption.black').text(t.replace('.000000', '.111111'));

A: The comments give you an indication of what the vanilla (sort of) matches up to from the jQuery
window.addEventListener('load', function () { // $('document').ready(function () {
    Array.prototype.forEach.call(
        document.querySelectorAll('.tp-caption.black'), // $( ".tp-caption.black
        function (e) {
            if (e.textContent.indexOf('.000000') !== -1) // :contains('.000000')" )
                e.textContent = '.1111111'; // .text('.1111111');
        }
    );
}


text:
Q: How to tell Bash to not stop the simulations when ssh disconnects? I am running some simulations on another machine via ssh. Here is what I do
ssh username@ipp.ip.ip.ip
Go to the right directory
cd path/to/folder
And then I just call my executable
.\myexecutable.exe
The issue is that every time the ssh disconnect, the simulations stops. How can I make sure the simulations doesn't stop on the other machine? Will I somehow receive potential error messages (assuming the code will crash) once I reconnect (ssh)?

A: You should launch a screen or tmux to create a terminal from which you can detach, leave running in the background and later reattach.
Further reading:

*

*http://ss64.com/osx/screen.html

*https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/screen.1.html
You may also want to try out Byobu:

*

*http://byobu.co

A: run your command as follows : nohup ./myexecutable.exe >nohup.out 2>&1 &
The & is to run the command in the background
The >nohup.out 2>&1 sends your stdout and stderr to nohup.out)
Note the '/' as opposed to '\' - which won't work on osx


text:
Q: SwiftUI - Error - Initializer 'init(_:rowContent:)' requires that 'CustomDataModel' conform to 'Identifiable' In my watch app, I wish to display list of events. When the view is opened, I send a request to iPhone app to send the events list. This is working so far and I am getting the events list back to Watch. However when I try to display the data on the list, I am getting errors due to custom object type. What I want is to display the events list when the data is available or just show a text on the view when there are no events.
Note: Watch connectivity to transfer data between devices/OS's does not allow custom data types, so have to conform to Codable and convert the data from CustomDataModel to Data type before transferring and then convert from Data to CustomDataModel in my Watch project.
Below is the code and error that I see:
CustomDataModel
import Foundation

struct CustomDataModel: Codable {
    var startEndDate: String?

    var startEndTime: String?

    var locationDetails: String?

    var actions: Dictionary<String, String> = [:]

    var title: String?

    // Has more properties

    func encodeIt() -> Data {
        let data = try! PropertyListEncoder.init().encode(self)
        return data
    }

    static func decodeIt(_ data:Data) -> CustomDataModel {
        let customDataModel = try! PropertyListDecoder.init().decode(CustomDataModel.self, from: data)
        return customDataModel
    }
}

CustomViewModel
import Foundation
import Combine

class CustomViewModel: ObservableObject, SessionCommands {
    @Published var eventsList:[CustomDataModel] = []

    init() {
        NotificationCenter.default.addObserver(forName: Notification.Name("eventsListReady"), object: nil, queue: nil, using: self.processEventsList(_:))
    }

    @objc func processEventsList(_ notification: Notification) {
        if let response = (notification.object as! CommandStatus).response as? [Data] {
            response.forEach { event in
                eventsList.append(CustomDataModel.decodeIt(event))
            }
        }
     }

    func getEventsList() {
        self.eventsList = []
        sendMessage(["functionality": Functionality.events.rawValue, "notificationName": Notification.Name("requestEventsList")])
    }
}

CustomView
import SwiftUI

struct CustomView: View {
    @ObservedObject var viewModel: CustomViewModel

    var body: some View {
        VStack {
            if !viewModel.eventsList.isEmpty {
                List(viewModel.eventsList) { item in
                    let _ = print("##### !viewModel.eventsList.isEmpty")
                    NavigationLink(destination: EventsDetailsView(eventItem: item)) {
                        EventRowView(eventItem: item)
                    }.navigationViewStyle(StackNavigationViewStyle())
                }
            } else {
                let _ = print("##### viewModel.eventsList.isEmpty")
                VStack {
                    Text("No events to display")
                }.frame(maxWidth: .infinity, maxHeight: .infinity)
            }
        }.navigationBarTitle("Back").onAppear() {
            self.viewModel.getEventsList()
        }
    }
}

Error I get on "List(viewModel.eventsList)" in CustomView : Initializer 'init(_:rowContent:)' requires that 'CustomDataModel' conform to 'Identifiable'
I am getting data in eventList object in CustomViewModel, but am not able to display it.

A: Give your type an id and make it identifiable and if you don't need decidable don't add it.
struct MyType: Encodable, Identifiable {
  let id = UUID()

  // other properties
}

Using Codable is just shorthand for adding Encodable and Decodable. So if you don't need both, then just use the one you need.


text:
Q: Jest: Wait for called .then of async method in componentDidMount I am currently stuck on writing a test of my React-App.
I have an async call in my componentDidMount method and are updating the state after returning. However, I do not get this to work.
I have found several solutions and None seems to work as expected. Below is the nearest point I have come to.
App:
class App extends Component<{}, IState> {
    state: IState = {
        fetchedData: false
    };

    async componentDidMount() {
        await thing.initialize();
        this.test();
    }

    test = () => {
        this.setState({ fetchedData: true })
    };

    render() {
        return this.state.fetchedData ? (

Hello

        ) : (
            <Spinner />
        );
    }
}

The test
it('Base test for app', async () => {
    const spy = spyOn(thing, 'initialize').and.callThrough();  // just for debugging
    const wrapper = await mount(<App />);
    // await wrapper.instance().componentDidMount();  // With this it works, but componentDidMount is called twice.
    wrapper.update();
    expect(wrapper.find('Spinner').length).toBe(0);
});

Well, so...thing.initialize is called (it is an async method that fetches some stuff).
If I do explicitly call wrapper.instance().componentDidMount() then it will work, but componentDidMount will be called twice.
Here are my ideas that I have tried but None succeeded:

*

*Spying on thing.initialize() -> I did not find out how I proceed with the test after the method has been called and finished.

*Spying on App.test -> The same here

*Working with promises instead of async await

*At the beginning, I had an thing.initialize().then(this.test) in my componentDidMount

It can't be much, but can someone tell me which piece I am missing?

A: if this is integration test you better to follow awaiting approach that say Selenium use: that is, just wait until some element appears or timeout reached. How it should be coded depends on library you use(for Puppeter it should be waitForSelector).
Once it's about unit test then I suggest you different approach:

*

*mock every single external dependencies with Promise you control(by your code it's hard to say if automatic mock will work or you need to compose mock factory but one of them or both will help)

*initialize element(I mean just run shallow() or mount())

*await till your mocks are resolved(with extra await, using setTimeout(... ,0) or flush-promises will work, check how microtasks/macrotasks works)

*assert against element's render and check if your mocks has been called

And finally:

*

*setting state directly

*mocking/spying on internal methods

*verifying against state

are all lead to unstable test since it's implementation details you should not worry about during unit-testing. And it's hard to work with them anyway.
So your test would look like:
import thing from '../thing';
import Spinner from '../../Spinner';
import flushPromises from 'flush-promises';

it('loads data and renders it', async () => {
  jest.mock('../thing'); // thing.implementation is already mocked with jest.fn()
  thing.initialize.mockReturnValue(Promise.resolve(/*data you expect to return*/));
  const wrapper = shallow(<App />);
  expect(wrapper.find(Spinner)).toHaveLength(1);
  expect(wrapper.find(SomeElementYouRenderWithData)).toHaveLength(0);
  await flushPromises();
  expect(wrapper.find(Spinner)).toHaveLength(0);
  expect(wrapper.find(SomeElementYouRenderWithData)).toHaveLength(1);
})

or you may test how component behaves on rejection:
import thing from '../thing';
import Spinner from '../../Spinner';
import flushPromises from 'flush-promises';

it('renders error message on loading failuer', async () => {
  jest.mock('../thing'); // thing.implementation is already mocked with jest.fn()
  thing.initialize.mockReturnValue(Promise.reject(/*some error data*/));
  const wrapper = shallow(<App />);
  expect(wrapper.find(Spinner)).toHaveLength(1);
  await flushPromises();
  expect(wrapper.find(Spinner)).toHaveLength(0);
  expect(wrapper.find(SomeElementYouRenderWithData)).toHaveLength(0);
  expect(wrapper.find(SomeErrorMessage)).toHaveLength(1);
})


text:
Q: Python using scipy.optimise to find the solution to an equation I want to solve an equation using scipy.optimise
I want to find the solution, n, for the equation
a**n + b**n = c**n

where
a=2.3
b=2.4
c=2.94

I have a list of triplets (a,b,c) I want to experiment with and I know the range of the exponent n will always be 2.0 < n < 4.0. Could I use this fact to speed up the convergence of the solution.

A: If your function is scalar, and accepts a scalar (your case), and if you know that:

*

*your solution is in a given interval, and the function is continuous in the same interval (your case)

*you are interested in one solution, not necessarily in all (if more than 1) solutions in that interval

You can speed up the solution using the bisection algorithm, implemented here in scipy, which requires the conditions above to guarantee convergence.
The idea behind the algorithm is quite simple, with log convergence.
See this fundamental calculus theorem on which the algorithm is based.
EDIT: I couldn't resist, here you have a MWE
import scipy.optimize as opt
def sol(a,b,c):
    f  = lambda n : a**n + b**n - c**n
    return opt.bisect(f,2,4)
print(sol(2.3,2.4,2.94)

>3.1010655957

A: As requested in the comments, here's how to do it using mpmath.
We supply the a, b, c parameters as strings rather than as Python floats for maximum accuracy. Converting strings to mpf (mp floats) will be as accurate as the current precision allows. If instead we convert from Python floats then we'd be using numbers that suffer from the imprecision inherent in Python floats.
mp.dps allows us to set the precision in the form of the number of decimal digits.
The mpmath findroot function accepts an initial approximation argument. This can be a single value, or it may be an interval, given as a list or a tuple. It's ok to use Python floats in that interval.
from mpmath import mp

mp.dps = 30

a, b, c = [mp.mpf(u) for u in ('2.3', '2.4', '2.94')]

def f(x):
    return a**x + b**x - c**x

x = mp.findroot(f, [2, 4])

print(x, f(x))

output
3.10106559575904097402104750305 -3.15544362088404722164691426113e-30

By default, findroot uses a simple secant solver. The docs recommend using the 'anderson' or 'ridder' solvers when supplying an interval, but for this equation all 3 solvers give identical results.


text:
Q: How to validate multiple functions with one IF statement - Javascript, jQuery I want to validate multiple functions, and for each one returning false, do some animations.
Here's the code:
                function validarChido(){
                    var dedo = $('#dedo_pick');
                    if(dedo.children().size() < 2){
                        dedo.animate({'background-color' : 'red'},200);
                        dedo.animate({'background-color' : '#EEE'},200);
                        return false;
                    }
                    else{return true;}
                }

                function validarEx(){
                    var valEx = $('#rate1');
                    if(valEx.children().size() < 2){
                        valEx.animate({'background-color' : 'red'},200);
                        valEx.animate({'background-color' : '#EEE'},200);
                        return false;
                    }
                    else{return true;}
                }

$('#form').submit(function(){
                    if( validarChido() && validarEx() )
                            {return true }
                        else
                            {return false; }
                    });

When I send the form, I only see the first function doing the color animation, obviously because the form validation IF statement doesn't evaluate the next function because the first resulted in false here if( validarChido() && validarEx() )
Is there a way to evaluate all the functions and see the animation in each one and then send the form if everything is true?

A: Instead of returning false or true do something similar to the following:
function validarChido() {
                var dedo = $('#dedo_pick');
                if(dedo.children().size() < 2){
                    dedo.animate({'background-color' : 'red'},200);
                    dedo.animate({'background-color' : '#EEE'},200);
                    return "error";
                }
                else{return "";}
            }

            function validarEx(){
                var valEx = $('#rate1');
                if(valEx.children().size() < 2){
                    valEx.animate({'background-color' : 'red'},200);
                    valEx.animate({'background-color' : '#EEE'},200);
                    return "error";
                }
                else{return "";}
            }

$('#form').submit(function(){
     var check = validarChido();
     check += validarEx();

                if( check == "" )
                        {return true }
                    else
                        {return false; }
                });

A: It can be something like this:
$('#form').submit(function(){
    var validarChidoResult = validarChido(),
        validarExResult = validarEx();

    if( validarChidoResult && validarExResult )
        {return true }
    else
        {return false; }
});

A: var result = validarChido();
result = validarEx() && result;
return result;


text:
Q: linq join in ASP MVC I am new to mvc :)
I try to show a join but was not successfull .
I put below method in Model
LinqDataContext db = new LinqDataContext();
    public IQueryable getExam()
    {
        return from exam in db.Exam_Table
               join cat in db.Cat_Table
               on
               exam.Exam_Cat_ID_FK equals cat.Cat_ID

               select new { exam, cat };

    }

and call it from controller by below code :
   exam_rep exrep = new exam_rep();
    public ActionResult Index()
    {
        var exams=exrep.getExams();
        return View(exams);
    }

but can not display it in view by below code :
foreach(var ex in Model)
{
%>

  <%: ex.exam.Exam_Title %>

<%
}
%>

how should I display values in view?

A: Aren't the objects linked by the linq datacontext?
I think it would be something like this:
db.Exams.Select(e => new { Exam = e, Cat = e.Cat });

Or Linq syntax
from e in db.Exams select new { Exam = e, Cat = e.Cat };

Or Simply
// assuming Exam.Cat
return db.Exams

I would look at your datacontext and make sure you have it setup correctly. It seems like you might be over complicating things.


text:
Q: Fill Visible Area of Eclipse RCP Editor Without Scrolling This is a question about which general approach to take, so I haven't included any code.
Requirement:
I need to create a page within a multi-page editor that has two vertical sections in it.  The top section has a tree and the bottom section has a text field.  The tree and text field should fill their respective sections.  Each section should scroll independently and there should be a splitter in between.  When the editor is opened I want the visible area of the editor to be divided among the two sections based on some ratio I provide.  Then when the editor is resized, the two sections will adjust proportionally to maintain the ratio and fit the page.  This way there won't be scroll bars on the editor page itself, just the two sections.
Proposed Solution:
My idea was to add a SashForm to the editor page and set the size of the SashForm to be the same as the editor's visible area.  Then I'd add a resize listener to the editor page and adjust the size of the SashForm so that it stays in sync with the page.  However, I can't find a way to get the editor's visible area.  So when I add the SashForm it just makes each section big enough to fit its data and adds a scroll on the editor page itself.
Is it possible to meet my requirement?

A: Success!  The key was to listen for resize events on the ScrolledForm.  I've only tested on Fedora but I'll take a look on Windows soon.  The only thing that bothers me is that the use of the buffer constants seems a little hacky.

/**
 * Form page that contains a sash form and a button.  The sash form is dynamically sized to ensure
 * that it always fills the available space on the page.
 */
public class SashFormDemoPage extends FormPage
{
    /** Horizontal buffer needed to ensure that content fits inside the page */
    private static final int HORIZONTAL_BUFFER = 8;
    /** Vertical buffer needed to ensure that content fits inside the page */
    private static final int VERTICAL_BUFFER = 12;

    /** Percentages of the sash form occupied by the tree and text box respectively */
    private static final int[] SASH_FORM_WEIGHTS = new int[] {30, 70};

    /**
     * Constructor
     *
     * @param editor    parent editor
     */
    public SashFormDemoPage(ComponentEditor editor)
    {
        super(editor, "sashFormDemoPage", "Demo");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void createFormContent(IManagedForm managedForm)
    {
        // Set page title
        ScrolledForm scrolledForm = managedForm.getForm();
        scrolledForm.setText("SashForm Demo");

        // Set page layout and add a sash form
        final Composite parent = scrolledForm.getBody();
        parent.setLayout(new GridLayout());
        final SashForm sashForm = new SashForm(parent, SWT.VERTICAL);

        // Add a tree as the top row of the sash form and fill it with content
        FormToolkit toolkit = managedForm.getToolkit();
        int style = SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER;
        Tree tree = toolkit.createTree(sashForm, style);

        for (int i = 0; i < 40; i++) {
            TreeItem parentNode = new TreeItem(tree, SWT.NONE);
            parentNode.setText("parent-" + i);
            for (int j = 0; j < 3; j++) {
                TreeItem childNode = new TreeItem(parentNode, SWT.NONE);
                childNode.setText("child-" + i + "-" + j);
            }
        }

        // Add a text box as the bottom row of the sash form and fill it with content
        style = SWT.MULTI | SWT.V_SCROLL | SWT.WRAP | SWT.BORDER;
        Text text = toolkit.createText(sashForm, null, style);

        String message = "";
        for (int i = 0; i < 100; i++) {
            message += "This is a test of the layout demo system.  This is only a test.  ";
        }
        text.setText(message);

        // Add button below sash form
        final Button button = toolkit.createButton(parent, "Test", SWT.NONE);

        // Add resize listener to sash form's parent so that sash form always fills the page
        parent.addControlListener(new ControlListener() {
            @Override
            public void controlMoved(ControlEvent e)
            {
                // Stub needed to implement ControlListener
            }

            @Override
            public void controlResized(ControlEvent e)
            {
                GridData data = new GridData();
                Point size = parent.getSize();
                data.widthHint = size.x - HORIZONTAL_BUFFER;
                data.heightHint = size.y - button.getSize().y - VERTICAL_BUFFER;
                sashForm.setLayoutData(data);
            }
        });

        // Set sash form's weights and pack its parent so that the initial layout is correct
        sashForm.setWeights(SASH_FORM_WEIGHTS);
        parent.pack();
    }
}

A: Why set the size of the SashForm explicitly? Why not just add it to the parent Composite of the editor? The parent Compositehas a FillLayout and thus the SashForm with fill the editor area automatically.


text:
Q: Python Default Arguments Evaluation I was reading the python tutorial from Python Documentation Release 2.7.10 and I came across something like this.
Code
def fun1(a,L=[]):
    L.append(a)
    return L

print fun1(1)
print fun1(2)
print fun1(3)

def fun2(a,L = None):
    if L is None:
        L=[]
    L.append(a)
    return L

print fun2(1)
print fun2(2)
print fun2(3)

Output
[1]
[1, 2]
[1, 2, 3]
[1]
[2]
[3]

Process finished with exit code 0

If the L=[] in the first function fun1() is getting called only once , the output of fun1()is fine. But then why L=None is getting called every time in fun2().

A: L=[] in the function declaration makes Python essentially do this:

*

*this function has a parameter named L

*its default argument is [], let's set this particular [] aside and use it anytime there's no parameter passed for L

*every time the function is called, create a variable L, and assign it either the passed parameter or the value we set aside earlier

So, the [] part is getting executed once, which creates a list object, which is set aside and kept around, which is why it accumulates changes if you modify it. Exactly the same thing happens with None, however None is not being modified nor is it mutable to begin with, so you're not seeing any weird side effects. None is still only being "executed" once, and that particular None value is set aside just as the list was, it's just that you're not doing anything to the None value itself.

A: When you define a function the values of the default arguments get evaluated, but the body of the function only get compiled. You can examine the result of the function definition via attributes. Theres a __defaults__ attribute containing the defaults and __code__ attribute containing the body (so these are created when the function is defined).
What's happening in the second example is that None do get evaluated at definition (it evaluates to None duh!), but the code that conditionally assigns [] to L only gets compiled and is run each time (the condition passes).

A: default arguments are evaluated only once. In fun1 you have the same list which you keep adding to. In fun2 you assign a new [] to the parameter and then append to it. As any assignment, its scope will be limited to the block it occurred in.


text:
Q: Filter by keyword in clojure returning ClassCastException error I am defining my table as
(def persons '({:id 1 :name "olle"} {:id 2 :name "anna"} {:id 3 :name "isak"} {:id 4 :name "beatrice"}))

And then attempting to use the filter command with (< :id 2) being my function and persons being my argument that I'm filtering.
(filter (< :id 2) persons);

I am being returned this error and do not know how to fix my program
ClassCastException clojure.lang.Keyword cannot be cast to java.lang.Number  clojure.lang.Numbers.lt (Numbers.java:221)

A: The problem is that the first argument to filter should be a predicate function but in your example it's just the value of (< :id 2).
(filter #(< (:id %) 2) persons)

The function should take one argument (the current element) and return a value indicating whether it satisfies the predicate. This is also valid, longer syntax for the same thing:
(filter (fn [p] (< (:id p) 2)) persons)

You could also defn a standalone predicate function like this:
(defn id-less-than-2? [person]
  (< (:id person) 2))
(filter id-less-than-2? persons)


text:
Q: Why am I missing space on my hard drive in Windows?
Possible Duplicate:
Why is the effective hard drive size lower than the actual size?

I have an HP Pavilion DM4 with a 750 GB hard drive. A few days ago, I installed Windows 8 on it, so I am now dual booting Windows 7 and Windows 8 (and I also have a 100 MB system reserved partition).
I noticed that I am only able to see 700 GB of hard disk space (169 for Windows 8 and 529 for Windows 7).
I booted of an Ubuntu 11.04 LiveCD and in the disk utility it said that my Windows 8 partition is 182 GB and my Windows 7 partition is 568 GB, correctly adding up to 750 GB.
I would like to reclaim the missing space in its respective partitions. Any advice on how to go about doing this?

A: The problem is that you are confusing binary and decimal prefixes.
You said it was 750GB right? That means 750,000,000,000B. Now convert that to GB:
750000000000/1024/1024/1024 = 698.5GB

That's what you said you were seeing. You can repeat this for the individual partitions and you will get the same results.
Why does Linux give you different results? Because it is not dividing by 1,024 (the number of bytes in a kilobyte, number of kilobytes in a megabyte, etc.), but rather, dividing by 1,000.
This is a frequent point of confusion because hard-drive manufacturers always use SI prefixes (which go up in increments of 1,000, i.e., powers of 10) because it makes their drives sound larger, while software (especially Windows) uses binary prefixes (which go up in increments of 1,024, i.e., powers of 2).
So, you are not actually missing anything, nor is there anything to "get back". The "missing" space is simply due to a difference/disagreement in the interpretation of the term "gigabyte/GB".

As to why you saw it say 750GB before installing Windows 8, it depends on where you saw that. Did you see it say 750GB in My Computer? Linux? A system-information tool? Based on what you have said, I suspect it to be a Windows program as opposed to Windows explorer.
In this case, you may saw it say 750GB because the program you used is clever enough to be able to ignore the disk-space reported by Windows and instead look at the device id of the drive. Then it can look up the id in a table (or decode it, depending on the device), and use the official label and description for it.
As an example, let's say that you have a Western Digital 750GB drive. The model number is encoded in the drive's firmware, so Windows is able to see something like WD7500BPKT. Windows also sees that it has 750GB (decimal) of space available and stores that in binary as 698.5GB (or GiB if you like the baby-talk binary prefixes).
Simple programs like Explorer retrieve the free-space value and report that (698.5GB in this case).
A fancier program on the other hand does not ask Windows for the free-space value, but rather the device-id. It sees WD7500BPKT and either decodes it (in the case of WD drives, they encode the size in the model number), or else it looks it up in its database and says; hey, this is a Western Digital WD Scorpio Black 750 GB SATA 3 GB. Note the 750GB.
Alternately, a program may also just examine the total number of bytes and divide  (repeatedly) by 1,000 instead of 1,024 to report the size as stated by the manufacturer. This is common with Windows ports of Unix tools.

A: I would check the disk size from within Windows, Run "diskmgmt.msc" from the Run Prompt (Windows key + R) and see what it shows as the size of those partitions, if its showing what you are seeing in Windows then thats probably all you are going to get, have a look and post what you can see so we can see whats going on!

A: The reason you're seeing less hard drive space than you should be in Windows, is due thanks to the way that hard drives are marketed.
Let me explain: you see those drives going around, 1TB HDDs and stuff right? What you're actually seeing is the decimal notation of whatever storage unit. So when they say 1TB, they actually mean 10^12 bytes (or 1,000,000,000,000 bytes), not 2^40 bytes (1,099,511,627,776 bytes) as it should be. This discrepancy means that your drives are actually smaller than they should be.
The binary notation is usually prefixed with an i, so TB becomes TiB and GB becomes GiB and so on.
So how does windows calculate the drive size?  Well, they use the binary notation, which is why it's smaller. Linux uses the Dec-10 notation, which is why you're seeing the drive size being 750GB. There is in fact a handy ratio you can use to calculate your true HDD size in binary notation, which is as follows:
decimal value / binary value = space discrepancy

So for your Windows partition of 568 dec-10 gigabytes, you would do the following, which gives you a fraction which you can use for calculating binary hdd sizes-
(10^9/2^30) = 0.931322574615478515625

So...
568 * 0.9313 = 528.9784 Binary gigabytes

As you can see, it matches up to your Windows report of your hard drive. I hope that sheds some light on your plight.