text:
Q: python exe error when importing PyQt5 and opening Mixxx I have made a small program for dj automation.
The code:
#from PyQt5 import QtCore, QtGui, QtWidgets
from pywinauto.application import Application as PyWinAutoApplication
from subprocess import Popen
import time
import os

os.environ["QT_DEBUG_PLUGINS"] = "1"

#Open mixxx
Popen(r'C:\Program Files\Mixxx\mixxx.exe')
#time.sleep(5)
#mixxx_app = PyWinAutoApplication(backend="uia").connect(title="Mixxx")
while(True):
    time.sleep(10)

if you compile the above script with pyinstaller the run it everything works good (mixxx.exe  is opening correctly).
But if you uncomment the first import line  then when trying to run it this error happens:
QFactoryLoader::QFactoryLoader() checking directory path "C:/Users/cpapp/OneDrive/???????????/dist/py_error_1/PyQt5/Qt5/plugins/platforms" ...
QFactoryLoader::QFactoryLoader() looking at "C:/Users/cpapp/OneDrive/???????????/dist/py_error_1/PyQt5/Qt5/plugins/platforms/qminimal.dll"
Found metadata in lib C:/Users/cpapp/OneDrive/???????????/dist/py_error_1/PyQt5/Qt5/plugins/platforms/qminimal.dll, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "minimal"
        ]
    },
    "archreq": 0,
    "className": "QMinimalIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("minimal")
QFactoryLoader::QFactoryLoader() looking at "C:/Users/cpapp/OneDrive/???????????/dist/py_error_1/PyQt5/Qt5/plugins/platforms/qoffscreen.dll"
Found metadata in lib C:/Users/cpapp/OneDrive/???????????/dist/py_error_1/PyQt5/Qt5/plugins/platforms/qoffscreen.dll, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "offscreen"
        ]
    },
    "archreq": 0,
    "className": "QOffscreenIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("offscreen")
QFactoryLoader::QFactoryLoader() looking at "C:/Users/cpapp/OneDrive/???????????/dist/py_error_1/PyQt5/Qt5/plugins/platforms/qwebgl.dll"
Found metadata in lib C:/Users/cpapp/OneDrive/???????????/dist/py_error_1/PyQt5/Qt5/plugins/platforms/qwebgl.dll, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "webgl"
        ]
    },
    "archreq": 0,
    "className": "QWebGLIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("webgl")
QFactoryLoader::QFactoryLoader() looking at "C:/Users/cpapp/OneDrive/???????????/dist/py_error_1/PyQt5/Qt5/plugins/platforms/qwindows.dll"
Found metadata in lib C:/Users/cpapp/OneDrive/???????????/dist/py_error_1/PyQt5/Qt5/plugins/platforms/qwindows.dll, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "windows"
        ]
    },
    "archreq": 0,
    "className": "QWindowsIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("windows")
QFactoryLoader::QFactoryLoader() checking directory path "C:/Program Files/Mixxx/plugins/platforms" ...
QFactoryLoader::QFactoryLoader() looking at "C:/Program Files/Mixxx/plugins/platforms/qwindows.dll"
Found metadata in lib C:/Program Files/Mixxx/plugins/platforms/qwindows.dll, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "windows"
        ]
    },
    "archreq": 0,
    "className": "QWindowsIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("windows")
QFactoryLoader::QFactoryLoader() checking directory path "C:/Program Files/Mixxx/platforms" ...
Cannot load library C:\Users\cpapp\OneDrive\???????????\dist\py_error_1\PyQt5\Qt5\plugins\platforms\qwindows.dll: The specified procedure could not be found.
QLibraryPrivate::loadPlugin failed on "C:/Users/cpapp/OneDrive/???????????/dist/py_error_1/PyQt5/Qt5/plugins/platforms/qwindows.dll" : "Cannot load library C:\\Users\\cpapp\\OneDrive\\???????????\\dist\\py_error_1\\PyQt5\\Qt5\\plugins\\platforms\\qwindows.dll: The specified procedure could not be found."
qt.qpa.plugin: Could not load the Qt platform plugin "windows" in "" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: minimal, offscreen, webgl, windows.

The output if I don't use: from PyQt5 import QtCore,QtGui,QtWidgets
C:\Users\cpapp\OneDrive\Υπολογιστής\dist\py_error_1>py_error_1.exe
QFactoryLoader::QFactoryLoader() checking directory path "C:/Program Files/Mixxx/plugins/platforms" ...
QFactoryLoader::QFactoryLoader() looking at "C:/Program Files/Mixxx/plugins/platforms/qwindows.dll"
Found metadata in lib C:/Program Files/Mixxx/plugins/platforms/qwindows.dll, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "windows"
        ]
    },
    "archreq": 0,
    "className": "QWindowsIntegrationPlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("windows")
QFactoryLoader::QFactoryLoader() checking directory path "C:/Program Files/Mixxx/platforms" ...
loaded library "C:/Program Files/Mixxx/plugins/platforms/qwindows.dll"
QFactoryLoader::QFactoryLoader() checking directory path "C:/Program Files/Mixxx/plugins/platformthemes" ...
QFactoryLoader::QFactoryLoader() checking directory path "C:/Program Files/Mixxx/platformthemes" ...
QFactoryLoader::QFactoryLoader() checking directory path "C:/Program Files/Mixxx/plugins/styles" ...
QFactoryLoader::QFactoryLoader() looking at "C:/Program Files/Mixxx/plugins/styles/qwindowsvistastyle.dll"
Found metadata in lib C:/Program Files/Mixxx/plugins/styles/qwindowsvistastyle.dll, metadata=
{
    "IID": "org.qt-project.Qt.QStyleFactoryInterface",
    "MetaData": {
        "Keys": [
            "windowsvista"
        ]
    },
    "archreq": 0,
    "className": "QWindowsVistaStylePlugin",
    "debug": false,
    "version": 331520
}

Got keys from plugin meta data ("windowsvista")
QFactoryLoader::QFactoryLoader() checking directory path "C:/Program Files/Mixxx/styles" ...
loaded library "C:/Program Files/Mixxx/plugins/styles/qwindowsvistastyle.dll"
Warning [Main]: Failed to load "mixxx" translations for locale "el_GR" from "C:/Program Files/Mixxx/translations/"
Warning [Main]: Found metadata in lib C:/Program Files/Mixxx/plugins/iconengines/qsvgicon.dll, metadata=
{
    "IID": "org.qt-project.Qt.QIconEngineFactoryInterface",
    "MetaData": {
        "Keys": [
            "svg",
            "svgz",
            "svg.gz"
        ]
    },
    "archreq": 0,
    "className": "QSvgIconPlugin",
    "debug": false,
    "version": 331520
}

Warning [Main]: Found metadata in lib C:/Program Files/Mixxx/plugins/imageformats/qgif.dll, metadata=
{
    "IID": "org.qt-project.Qt.QImageIOHandlerFactoryInterface",
    "MetaData": {
        "Keys": [
            "gif"
        ],
        "MimeTypes": [
            "image/gif"
        ]
    },
    "archreq": 0,
    "className": "QGifPlugin",
    "debug": false,
    "version": 331520
}

Warning [Main]: Found metadata in lib C:/Program Files/Mixxx/plugins/imageformats/qicns.dll, metadata=
{
    "IID": "org.qt-project.Qt.QImageIOHandlerFactoryInterface",
    "MetaData": {
        "Keys": [
            "icns"
        ],
        "MimeTypes": [
            "image/x-icns"
        ]
    },
    "archreq": 0,
    "className": "QICNSPlugin",
    "debug": false,
    "version": 331520
}

Warning [Main]: Found metadata in lib C:/Program Files/Mixxx/plugins/imageformats/qico.dll, metadata=
{
    "IID": "org.qt-project.Qt.QImageIOHandlerFactoryInterface",
    "MetaData": {
        "Keys": [
            "ico",
            "cur"
        ],
        "MimeTypes": [
            "image/vnd.microsoft.icon",
            "image/vnd.microsoft.icon"
        ]
    },
    "archreq": 0,
    "className": "QICOPlugin",
    "debug": false,
    "version": 331520
}

Warning [Main]: Found metadata in lib C:/Program Files/Mixxx/plugins/imageformats/qjp2.dll, metadata=
{
    "IID": "org.qt-project.Qt.QImageIOHandlerFactoryInterface",
    "MetaData": {
        "Keys": [
            "jp2"
        ],
        "MimeTypes": [
            "image/jp2",
            "image/jpx",
            "image/jpm",
            "video/mj2"
        ]
    },
    "archreq": 0,
    "className": "QJp2Plugin",
    "debug": false,
    "version": 331520
}

Warning [Main]: Found metadata in lib C:/Program Files/Mixxx/plugins/imageformats/qjpeg.dll, metadata=
{
    "IID": "org.qt-project.Qt.QImageIOHandlerFactoryInterface",
    "MetaData": {
        "Keys": [
            "jpg",
            "jpeg"
        ],
        "MimeTypes": [
            "image/jpeg",
            "image/jpeg"
        ]
    },
    "archreq": 0,
    "className": "QJpegPlugin",
    "debug": false,
    "version": 331520
}

Warning [Main]: Found metadata in lib C:/Program Files/Mixxx/plugins/imageformats/qsvg.dll, metadata=
{
    "IID": "org.qt-project.Qt.QImageIOHandlerFactoryInterface",
    "MetaData": {
        "Keys": [
            "svg",
            "svgz"
        ],
        "MimeTypes": [
            "image/svg+xml",
            "image/svg+xml-compressed"
        ]
    },
    "archreq": 0,
    "className": "QSvgPlugin",
    "debug": false,
    "version": 331520
}

Warning [Main]: Found metadata in lib C:/Program Files/Mixxx/plugins/imageformats/qtga.dll, metadata=
{
    "IID": "org.qt-project.Qt.QImageIOHandlerFactoryInterface",
    "MetaData": {
        "Keys": [
            "tga"
        ],
        "MimeTypes": [
            "image/x-tga"
        ]
    },
    "archreq": 0,
    "className": "QTgaPlugin",
    "debug": false,
    "version": 331520
}

Warning [Main]: Found metadata in lib C:/Program Files/Mixxx/plugins/imageformats/qtiff.dll, metadata=
{
    "IID": "org.qt-project.Qt.QImageIOHandlerFactoryInterface",
    "MetaData": {
        "Keys": [
            "tiff",
            "tif"
        ],
        "MimeTypes": [
            "image/tiff",
            "image/tiff"
        ]
    },
    "archreq": 0,
    "className": "QTiffPlugin",
    "debug": false,
    "version": 331520
}

Warning [Main]: Found metadata in lib C:/Program Files/Mixxx/plugins/imageformats/qwbmp.dll, metadata=
{
    "IID": "org.qt-project.Qt.QImageIOHandlerFactoryInterface",
    "MetaData": {
        "Keys": [
            "wbmp"
        ],
        "MimeTypes": [
            "image/vnd.wap.wbmp"
        ]
    },
    "archreq": 0,
    "className": "QWbmpPlugin",
    "debug": false,
    "version": 331520
}

Warning [Main]: Found metadata in lib C:/Program Files/Mixxx/plugins/imageformats/qwebp.dll, metadata=
{
    "IID": "org.qt-project.Qt.QImageIOHandlerFactoryInterface",
    "MetaData": {
        "Keys": [
            "webp"
        ],
        "MimeTypes": [
            "image/webp"
        ]
    },
    "archreq": 0,
    "className": "QWebpPlugin",
    "debug": false,
    "version": 331520
}

Warning [Main]: Found metadata in lib C:/Program Files/Mixxx/plugins/sqldrivers/qsqlite.dll, metadata=
{
    "IID": "org.qt-project.Qt.QSqlDriverFactoryInterface",
    "MetaData": {
        "Keys": [
            "QSQLITE"
        ]
    },
    "archreq": 0,
    "className": "QSQLiteDriverPlugin",
    "debug": false,
    "version": 331520
}

Warning [Main]: Found metadata in lib C:/Program Files/Mixxx/plugins/sqldrivers/qsqlodbc.dll, metadata=
{
    "IID": "org.qt-project.Qt.QSqlDriverFactoryInterface",
    "MetaData": {
        "Keys": [
            "QODBC3",
            "QODBC"
        ]
    },
    "archreq": 0,
    "className": "QODBCDriverPlugin",
    "debug": false,
    "version": 331520
}

Warning [Main]: Found metadata in lib C:/Program Files/Mixxx/plugins/sqldrivers/qsqlpsql.dll, metadata=
{
    "IID": "org.qt-project.Qt.QSqlDriverFactoryInterface",
    "MetaData": {
        "Keys": [
            "QPSQL7",
            "QPSQL"
        ]
    },
    "archreq": 0,
    "className": "QPSQLDriverPlugin",
    "debug": false,
    "version": 331520
}

Warning [Controller]: USB permissions problem (or device error.) Your account needs write access to USB HID controllers.
Warning [Controller]: USB permissions problem (or device error.) Your account needs write access to USB HID controllers.
Warning [Controller]: USB permissions problem (or device error.) Your account needs write access to USB HID controllers.
Warning [Controller]: USB permissions problem (or device error.) Your account needs write access to USB HID controllers.
Warning [Controller]: USB permissions problem (or device error.) Your account needs write access to USB HID controllers.
Warning [Controller]: USB permissions problem (or device error.) Your account needs write access to USB HID controllers.
Warning [Controller]: USB permissions problem (or device error.) Your account needs write access to USB HID controllers.

It seems that PyQt5 imports are affect pywinauto start or Mixx program which is writter in C++ qt.
What's wrong and how can i fix it?
The problem exists only after pyinstaller compilation.
Note that if i create an .exe with this code:
from PyQt5 import QtCore, QtGui, QtWidgets

or with an pyuic5 py file created from Qt Designer there is no error.
The error exists only when i import PyQt5 and then try to open mixx (pyinstaller). If i import PyQt5 and then try to open another app like calc there is no problem...

A: The actual problem was that platforms plugin of Qt C++ (mixxx) was interfered with PyQt5 initialization by PyInstaller.
The problem was solved by extending:
Popen(r'C:\Program Files\Mixxx\mixxx.exe')

with this:
Popen(r'C:\Program Files\Mixxx\mixxx.exe', env=dict(os.environ, QT_PLUGIN_PATH=''))

This change stores QT_PLUGIN_PATH the right value ('').
Thanks to @relent95 because he was the solver of the problem.


text:
Q: Check if entity implements interface and add predicate in generic repo Some of my entities have IEnabledEntity interface.
I want to check in repository if entity implements interface then add some predicate. I have the following code:
public class Repository<T> : IRepository<T> where T : class, IEntity, new()
{
   public IQueryable<T> Get(Expression<Func<T, bool>> predicate, params string[] includes)
     IQueryable<T> query = Context.Set<T>();
     foreach (var include in includes)
     {
        query = query.Include(include);
     }

     query = query.Where(predicate);

     var isEnabledEntity = typeof(IEnabledEntity).IsAssignableFrom(typeof(T));

     if (isEnabledEntity)
     {
        query = query.Where(e => ((IEnabledEntity) e).IsEnabled);
     }

     return query;
}

 public interface IEnabledEntity
 {
    bool IsEnabled { get; set; }
 }

 public class Test : IBaseEntity, IEnabledEntity
 {
    // ...
    public bool IsEnabled { get; set; }
 }

But, I get exception about casting:
Unable to cast the type 'Domain.Test' to type 'Domain.Interfaces.IEnabledEntity'. LINQ to Entities only supports casting EDM primitive or enumeration types.

How to make it work?

A: Linq-to-Entities only knows models which are classes, that's why an expression can't contain an interface type. However clearly it's possible runtime to access the IsEnabled property if T implements it, so if you do the check yourself with IsAssignableFrom() (like you do), it's possible to use the ExpressionVisitor class to bypass the casting:
internal class IgnoreCast : ExpressionVisitor
{
    protected override Expression VisitUnary(UnaryExpression e)
    {
      if(e.NodeType == ExpressionType.Convert && e.Type.IsAssignableFrom(typeof(e.Operand))
         return e.Operand;
      else
         return e;
    }
}

Then you need to create your filter with an extensionmethod which implements the IgnoreCast class:
internal static class LocalExtensions
{
   internal static IgnoreCast ic = new IgnoreCast();

   internal static IQueryable<T> FilterEnabled<T>(this IQueryable<T> query) where T: class
   {
      Expression<Func<T,bool>> expr = e => ((IEnabledEntity)e).IsEnabled;
      expr = (Expression<Func<T,bool>>)ic.Visit(e);
      return query.Where(expr);
   }
}

Then you can just use that method in your program:
if(typeof(IEnabledEntity).IsAssignableFrom(T))
   query = query.FilterEnabled();

The base method Visit(Expression e) will pass each node of the expression to a more specialized Visit method for that kind of node. The Convert nodetype is a UnaryExpression so this method will be overriden in the derived class. If the unaryexpression is of the Convert nodetype and the operand implements the type it will just return the operand, thus removing the casting.

A: The type parameter in IQueryable<T> is covariant, so instead of worrying about casting the entity in your expression, just safe-cast the entire query itself and then use Cast<T>() to get it back to your entity type:
    public IQueryable<T> Get(Expression<Func<T, bool>> predicate, params string[] includes)
    {
        IQueryable<T> query = Context.Set<T>();
        foreach (var include in includes)
        {
            query = query.Include(include);
        }

        query = query.Where(predicate);

        var enabledQuery = query as IQueryable<IEnabledEntity>;

        if (enabledQuery != null)
            query = enabledQuery.Where(e => e.IsEnabled).Cast<T>();

        return query;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: ParseQueryAdapter : sort data on client side My problem is quite simple, but my code is not working.
I want to sort result of a ParseQuery into the ParseQueryAdapter before display it into a ListView.
products.addOnQueryLoadListener(new ParseQueryAdapter.OnQueryLoadListener<Product>() {

        @Override
        public void onLoaded(List<Product> data, Exception e) {
            Collections.sort(data, LastDealComparator);
            products.notifyDataSetInvalidated();
        }

        @Override
        public void onLoading() {
        }

    });

I checked in debugger data is sorted by the Comparator ... but not updated into the ParseQueryAdapter ... notifyDataSetInvalidated do nothing.
For information, initially my problem is to sort a query on a pointer field :
query.orderByDescending("deal.date");

But that's not working too ... so i write a manual sort.

A: You can create the onLoaded event and create the sort index (sort of HashMap)
@Override
public void onLoaded(List<ParseObject> objects, Exception e)

And in the getItem function you can map the data based on the index.
Example of a reverse order list:
@Override
public ParseObject getItem(int position) { //For descending order
    return super.getItem(getCount() - position - 1);
}


text:
Q: javascript object/variable issue I have below code in angular service
this.get = function(url,qParams)
{
    var webresponse = new Object();

    $http.get(url+qParams)
    .success(function(result){
        webresponse.data = result;
        webresponse.state = 1;
    })
    .error(function(result){
        webresponse.data = result;
        webresponse.state = 0;
    });

    console.log('webresponse :' + webresponse.data);
    return webresponse;
}

In console log shows webresponse.data as undefined. Please help me to understand why. Is it scope issue?
just to let you know result is JSON array and in console log it shows JSON array as expected with all elements in it.

A: Your $http.get() is an async call and your console.log is in synchronous fashion, so console.log initiated first then your $http.

A: Method calls in $http are asynchronous: The result will not be necessarily available after the function .get() returns. Please check again the docs for $http.
Data in webresponse will not be available (i.e. your variable is not set yet to anything other than the plain object) but only when the $http.get request fetches the data from the server. Such moments are the .success trigger, the .error trigger, and also a trigger you did not use (and perhaps don't need) called .finally (works regardless whether .success and .error have been triggered).
You cannot access the webresponse outside those callbacks since they are the only guaranteed moments where such values will be available. Even more! You cannot RETURN such value from the function. Since the behavior is asynchronous you will have to return something in the same asynchronous way. Please check the $q service to learn how to do it. It is a long topic and you lack the basics on this topic so I will give you some guidelines:

*

*$http is an asynchronous service. Their calls (e.g. .get() return something called a promise. Your function should return a promise (either the same or other).

*The actual result itself (i.e. the result you want) will not be available as you intend: The function's invoker must attend the promise you return, specify a callback for it, and attend it in the callback.

*More information: You need a deeper knowledge of $http and $q services. They are pretty well documented in the official docs.

A: you function is an synchronous call.
this.get = function(url,qParams)
{
    var webresponse = new Object();

    $http.get(url+qParams)
    .success(function(result){
        webresponse.data = result;
        webresponse.state = 1;

        console.log('webresponse :' + webresponse.data);
        //triger any function @here when its success
    })
    .error(function(result){
        webresponse.data = result;
        webresponse.state = 0;

        console.log('webresponse :' + webresponse.data);
        //triger any function @here when its fail

    });
}

A: Your this.get() function can't return result immediately.
As you know, the $http module use ajax, (AJAX: Asynchronous Javascript and Xml )
so you have to wait for the asynchronous response in your success or error callback function.
If you want to return the response, please consider promise pattern.


text:
Q: How do I add a new column to a Spark dataframe for every row that exists? I'm trying to create a comparison matrix using a Spark dataframe, and am starting by creating a single column dataframe with one row per value:
val df = List(1, 2, 3, 4, 5).toDF

From here, what I need to do is create a new column for each row, and insert (for now), a random number in each space, like this:
  Item   1   2   3   4   5
 ------ --- --- --- --- ---
     1   0   7   3   6   2
     2   1   0   4   3   1
     3   8   6   0   4   4
     4   8   8   1   0   9
     5   9   5   3   6   0

Any assistance would be appreciated!

A: Considering to transpose the input DataFrame called df using .pivot() function like the following:
val output = df.groupBy("item").pivot("item").agg((rand()*100).cast(DataTypes.IntegerType))

This will generate a new DataFrame with a random Integer value corrisponding to the row value (null otherwise).
+----+----+----+----+----+----+
|item|1   |2   |3   |4   |5   |
+----+----+----+----+----+----+
|1   |9   |null|null|null|null|
|3   |null|null|2   |null|null|
|5   |null|null|null|null|6   |
|4   |null|null|null|26  |null|
|2   |null|33  |null|null|null|
+----+----+----+----+----+----+

If you don't want the null values you can consider to apply an UDF later.


text:
Q: Obtaining a property due to being part of a larger whole I'm looking for a word which describes obtaining a certain property due to being part of a larger whole.
E.g.

*

*a dinner set has a property "color". An instance of a dinner set could be white. Automatically, a dish, part of the dinner set, obtains this property. It has a white color, too.

*a sweater has a property "material". An instance of a sweater could be woolen. Automatically, a sleeve, part of the sweater, obtains this property. It has (been made of) material which is woolen, too.

*a people has a property "nationality". An instance of a people could be the English. Automatically, a person, part of the people, obtains this property. He has the English nationality, too.

How would you describe the implicit obtainment of these properties?
The closest I could think of was "inheritance".

A: This is an interesting question. After some thought, derive comes into mind.
Derive

to receive or obtain from a source or origin / to trace from a source or origin

A: I dont't know if this is what you were looking for, but in some spheres (maths, phylosophy...), this is called the 'transitive property'. In general --and not too technical-- lines, given a, b and c, transitive property establishes that if a is related to b in a specific manner, and  b and c are also related, then a and c are related accordingly. Not too long ago, I heard something like this in the TV show called Silicon Valley, from an episode called Adult content. In a scene, EndFrame workers were claimed to be "pieces of sh-t". A certain "he" (I don't remember his name) worked for EndFrame "so, by the transitive property, he is, therefore, also a piece of sh-t." This sounded to me to resemble what you were trying to say. In your case, the transitive property would apply as follows:

*

*A given sweater (a) is made of woolen (b).

*A given sleeve (c) belongs to that sweater (a).

*Therefore, the sleeve (c) is made of woolen (b) too.

I thought maybe you could work something out from that (what about transitivity or something like that?).

A: The person or thing has the property as a member of the given set by definition.


text:
Q: Script php stop without error messages I want to input in a database some values from a txt files.
I have a loop who extract the data that i want, check if it don't already exist and else insert it.
$res = mysqli_query($conn, "SELECT COUNT(*) AS nb FROM SITE WHERE domain_site = '".$domain."'");
$res = mysqli_fetch_assoc($res);
if ($res["nb"] == 0) {
    $conn->query("INSERT INTO SITE (domain_site) VALUES ('".$domain."')");
}

I have see that in my DB, their is not all the values, so I add this line :
echo $domain."</br>";

and the output stop before the end of my file without reasons and error messages
PS : I have set these parameters in the top of my php
ini_set('max_execution_time', 1000);
ini_set('memory_limit', '100M');
set_time_limit(0);
ini_set('display_errors',1);
error_reporting(E_ALL);

Someone have an idea why my script stop or how to solve it ? Thank you.

A: Try adding:
printf("Errormessage: %s\n", mysqli_error($conn));
This will print the error(if any from DataBase).


text:
Q: Area of a critical triangle ABC if PA,PB known and PC unknown help me to solve this this problem please:
In a triangle $ABC$, $\angle BAC$ = $60\,^{\circ}$,$AB=2AC$.Point P is inside the triangle such that $PA=\sqrt{3}$,$PB=5$. What is the area of triangle $ABC ?$

A: You can apply the cosine rule:

*

*By applying it on $\bigtriangleup APB$, $c^2=25+3-2\cdot5\cdot\sqrt{3}\cdot\cos\angle APB$

*Now, $\bigtriangleup ABC=\frac{1}{2}\cdot cb\cdot \sin60=c^2\frac{\sqrt{3}}{8}$ [as $c=2b$]

*So we must need $\angle APB$. If it is given we are done.

A: The shape of $ABC$ is determined up to similarity, without the information on $P$, so the question is effectively asking for a removal of the scaling ambiguity, which would mean a complete determination of all distances between the points (or the reduction to a very small finite number of possibilities, such as having a "$P$ inside $ABC$" and a "$P$ outside" solution, each with one or two possibilities for the shape and size of the figure $ABCP$).  This is impossible:
If the information is given in the form of the data on $ABC$ and the ratio $PA/PB$, the whole diagram is determined only up to similarity, and the locus of $P$ (for fixed positions of $A,B,C$) with that ratio of distances is a circle.  Thus, one can continuously change the scale of $ABC$ (and the circle) in some range, while at the same time adjusting the position of $P$ on the circle to keep $PA$ constant (therefore equal to $3$, in some adapted but constant system of units) and this will also maintain the correct value for $PB$, satisfying all conditions of the problem (both $PA$ and $PB$, and not only their ratio, will have the correct value) while varying the shape of the figure $ABCP$.
Because there is a continuous deformation of the shape of the solutions, they are not unique.

A:
It's trivially found that $\triangle ABC$
is the right triangle with
$\angle BCA=90^\circ$ and
$\angle ABC=30^\circ$.
Let's fix the point $A$ at the origin
with two rays $AB$ and $AC:$
$\angle CAB=60^\circ$.
Since $|PA|=\sqrt3$ is fixed,
the point $P$ must be located
on the circular arc $P_{\min}P_{\max}$
centered at $A$.
In order to fit the other condition
$|PB|=5$,
the point $B$ must be located
anywhere
on the segment $B_{\min}B_{\max}$,
\begin{align}
|AB_{\max}|&=|PA|+|PB|=5+\sqrt3
,\\
|AB_{\min}|&=|AD|+|DB_{\min}|
=\tfrac{\sqrt3}2+\sqrt{5^2-\tfrac94}
=\tfrac12\,(\sqrt3+\sqrt{91})
.
\end{align}
Since $\angle BCA=90^\circ$,
the point $C$ is found at the intersection
between the ray $AC$ and the circle centered at the middle of $AB$
with radius $\tfrac12\,|AB|$.
The area $S$ of $\triangle ABC$
must be between $S_{\min}$ and $S_{\max}$,
\begin{align}
S_{\min}&=\tfrac{\sqrt3}8\,|AB_{\min}|^2
=\tfrac1{16}\,(47\,\sqrt3+3\,\sqrt{91})
\approx 6.876535251
,\\
S_{\max}&=\tfrac{\sqrt3}8\,|AB_{\max}|^2
=\tfrac{\sqrt3}8\,(5+\sqrt3)^2
=\tfrac14\,(15+14\,\sqrt3)
\approx 9.812177826
,
\end{align}
so at best we can say that
\begin{align}
S&=
\tfrac1{32}\,(60+103\,\sqrt3+3\,\sqrt{91})
\pm
\tfrac3{32}\,(20+3\,\sqrt3-\sqrt{91})
,\\
&\approx
8.344356539\pm 1.467821289
.
\end{align}

A: Let $a:=AC$ ; therefore $BC=a\sqrt{3}$, $AB=2a$.
Let $b=PC$ and $\alpha:=a^2$, $\beta:=b^2$.
Let us express that the Cayley-Menger determinant of the four points $A,B,C,P$ is zero (see here):
$$\begin{vmatrix}0 & 4\alpha & \alpha & 3 & 1\\
   4\alpha & 0 &3\alpha &25& 1\\
   \alpha & 3\alpha &0& \beta& 1\\
     3& 25 &\beta &0 &1\\
     1&1 &1 &1& 0\end{vmatrix}=0\tag{1}$$
Expanding, one obtains :
$$-8\alpha(3\alpha^2 - 42\alpha + \beta^2 - 17\beta + 163)=0\tag{2}$$
Dropping the case $-8\alpha=0$ (which is the impossible case of a triangle reduced to a point), (2) is equivalent to :
$$3(\alpha-7)^2+(\beta-\dfrac{17}{2})^2=\left(\dfrac{15}{2}\right)^2\tag{3}$$
which is the equation of an ellipse represented here :

Fig. 1 : The ellipse with equation (3) with respect to axes $\alpha=a^2$ and $\beta=b^2$.
As we are looking for a maximal value for the triangle's area :
$$S=\dfrac{1}{2} a \times \sqrt{3}a = \dfrac{\sqrt{3}}{2}a^2=\dfrac{\sqrt{3}}{2}\alpha\tag{4}$$
It suffices to consider the maximal value $\alpha_{max}$ of $\alpha$ which is reached for the rightmost point of the ellipse (indicated by a little star on Fig. 1) giving
$$\alpha_{max}=7+\sqrt{3}\dfrac{15}{2}\tag{5}$$
Using (4) and (5), we  can assert that the maximal area is

$$\alpha_{max}\dfrac{\sqrt{3}}{2}=\dfrac{\sqrt{3}}{2}+\dfrac{45}{4}\approx 9.8121778...$$

which coincides with the value obtained by G.Kov, and corresponds to the extreme case where point $P$ is on side $AB$.
Remarks :
1) In fact, we have worked using "necessary arguments". We have checked that the solution obtained is actually a "feasible solution". But, there are constraints that we haven't handled, which in particular forbid some parts of the ellipse, but without impact on this solution.
2) Equation (2), when we take $\beta=2^2$ gives back equation $a^4-14a^2+37=0$ in a solution of the fully constrained problem indicated by Calvin Lin.

A: There is not enough information to solve the problem.  By drawing the line from $C$ to the midpoint of $AB$, we know $ABC$ is $30-60-90$.  We don't have enough to get $AB$.  We know $5-\sqrt 3 \lt AB \lt 5+\sqrt 3$ and some of the low end may drive $P$ outside the triangle, but there are triangles of various areas that satisfy the requirement.


text:
Q: How to determine the number of divisors of an integer through combinatorics How would you formally derive the fact that integer $100$ has 9 divisors $(1,2,4,5,10,20,25,50,100)$, knowing in advance that, apart from 1, its prime divisors are 2 and 5, each recurring 2 times $(2 \cdot 2 \cdot\ 5 \cdot 5 = 100)$?
This should be achievable using counting rules in combinatorics.

A: Yes, it is possible. Suppose we have $n = p_1^{k_1}...p_m^{k_m}$ where $p_1,...,p_m$ are distinct primes and $k_1,...,k_m \ge 1$. Then, for each prime factor $p_i$, we have the options $\{0,1,...,k_i\}$ for its power $k_i$ since $p_i^a|p_i^{k_i}, \forall a \text{ such that } 0 \le a \le k_i$. So we have $k_i+1$ options for each. Considering the fact that the prime factors are independent from other prime factors (as they are prime numbers), can you get a general result from here?

A: The divisor counting function is usually noted with $\tau(n)$ (tau). In other words, $n$ has $\tau(n)$ divisors.

$$n=\prod_{i=1}^{m}p_m^{a_m}\Rightarrow\tau(n)=\prod_{i=1}^{m}(a_i+1)$$

The proof for this? Well observe that $p^k$ with prime $p$ has indeed $k+1$ divisors ($1,p,...,p^k$). Finally, observe that $$\tau\bigg(\prod_{i=1}^{m}p_m^{a_m}\bigg)=\prod_{i=1}^{m}\tau(p_i^{a_i})$$ and you are done.


text:
Q: Function to calculate max value of int not returning desired result I'm just starting out learning C. I'm trying to find the max value of an int by calculation (actually I'm trying to find the max value of a float through the same method, but I want to test it on int first).
The logic seems to be OK, but my function always returns 0 at the end.
int max_int_helper(int base)
{
  int prev_i, next_i, counter;
  counter = 1;
  prev_i = next_i = base + counter;

  // found max
  if (next_i < base) {
    printf("WE RETURN BASE %d\n", base);
    return base;
  } else {
      while(prev_i <= next_i)
      {
        prev_i = next_i;
        counter *= 2;
        next_i = base + counter;
      }
        max_int_helper(prev_i);
  }
}

I call it in my main function like this
printf("max int calculated: %d", max_int_helper(0));

But when I run the thing I get this:
WE RETURN BASE 2147483647
max int calculated: 0
I explicitly put the printf statement, so that I'm "sure" I only return once and the value is correct.
Please point me out where it's going wrong.

A: It is a recursion. You need to return the value of it.
So in the last line it should be:
return max_int_helper(prev_i);


text:
Q: Datepicker can't be saved to MySQL I'm working on a program with a datepicker, but when i try to submit it to the MySQL database it gives the following error:
CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0000-00-00' for key 'Dag'.

The code that i use for the datepicker is:
<div class="row">
<?php echo $form->labelEx($model,'Dag'); ?>
    <?php

    $form->widget('zii.widgets.jui.CJuiDatePicker', array(
        'model' => $model,
        'attribute' => 'Dag',
        'htmlOptions' => array(
        'size' => '10',         // textField size
        'maxlength' => '10',    // textField maxlength

        ),
    ));
    ?>
<?php echo $form->error($model,'Dag'); ?>
</div>

I know it says there already is a date named 0000-00-00 but i didn't add that one, but date 2014-09-02!

A: If the attribute Dag is considered unsafe by your Yii ActiveRecord model, then the new value sent from DatePicker (and assigned possibly by $model->attributes = $_POST['ModelName'];) won't get assigned unless you assign it manually like so: $model->Dag = $_POST['ModelName']['Dag']
If you want, you could also set the Dag attribute as safe in your model:
public function rules()
    {
        return array(
            ...,
            array('Dag', 'safe'),
        );
    }


text:
Q: JavaScript checkbox validation in table I have designed a table  below using HTML. I have validated for only one row, but for the 2nd row it was not validated. Below UI have given submit that validates entire table.
Condition is that at least one checkbox should be selected from each row.

A: Using pure js: https://jsfiddle.net/v8mghww9/1/
function validate(form)
{
    var rows = document.getElementsByTagName('tr');
    var isTableValid = true;
    for(var i=0;i<rows.length;i++) {
        var checkboxs=rows[i].getElementsByTagName("input");
        var okay=false;
        for(var j=0;j<checkboxs.length;j++)
        {
            console.log('here' + checkboxs[j].checked);
            if(checkboxs[j].checked)
            {
                okay=true;
                break;
            }
        }
        if(!okay && checkboxs.length > 0) {
            isTableValid = false;
            break;
        }

    }

    if(isTableValid)
            return true;
        else
        {
            alert("Please select atleast one item for male patients");
            return false;
        }

}

A: Your code was fine but you weren't writing the jsfiddle the right way, this is a live snippet showing that your code works fine:

function validate(form) {
  var checkboxs = document.getElementsByName("m1");
  var okay = false;
  for (var i = 0, l = checkboxs.length; i < l; i++) {
    if (checkboxs[i].checked) {
      okay = true;
      break;
    }
  }
  if (okay) return true;
  else {
    alert("Please select atleast one item for male patients");
    return false;
  }
}
table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
  padding: 0.5em;
  line-height: 1.5em;
}
#color {
  background-color: lightblue;
}
.adjust {
  text-align: left;
}
input[type="checkbox"] {
  margin-left: 47%;
}

    OAB Patient Types
    Therapy of First Choice

    Muscarinic Antagonists
    Beta-3 Adrenergic Agonist
    Other Therapies

    Detrol LA

(tolterodine)
    Enablex

(darifencian)
    Toviaz

(festoridine)
    VESIcare

(solifencian)
    Myrbetriq

(merabergan)
    Other

    General Patient Types

    Male Patients	//
    <form name=form1>

        <input type="checkbox" name=m1>

        <input type="checkbox" name=m1>

        <input type="checkbox" name=m1>

        <input type="checkbox" name=m1>

        <input type="checkbox" name=m1>

        <input type="checkbox" name=m1>
      	//</form>

    Female Patients
    <form name=form2>

        <input type="checkbox" name=f1>

        <input type="checkbox" name=f1>

        <input type="checkbox" name=f1>

        <input type="checkbox" name=f1>

        <input type="checkbox" name=f1>

        <input type="checkbox" name=f1>

    </form>

    Line of Therapy

    First-line (newly daignosed OAB patients on their first course of therapy)
    <form>

        <input type="checkbox">

        <input type="checkbox">

        <input type="checkbox">

        <input type="checkbox">

        <input type="checkbox">

        <input type="checkbox">

    </form>

    Second-line
    <form>

        <input type="checkbox">

        <input type="checkbox">

        <input type="checkbox">

        <input type="checkbox">

        <input type="checkbox">

        <input type="checkbox">

    </form>

    Third-line
    <form>

        <input type="checkbox">

        <input type="checkbox">

        <input type="checkbox">

        <input type="checkbox">

        <input type="checkbox">

        <input type="checkbox">

    </form>

  <input type="button" value="Submit" onclick='return validate()'>

Note:
The button Submit should be of type button and not submit.

*

*First thing because it's not inside any form to be submitted

*Second thing is that you have many forms in your page (which is strange here), so you may have a conflict in submitting which form of them wityh this submit button?

A: give the same name on all the checkboxes of each row and then give it a class to all which you want to validate.
function validate() {

    var flag = true;
    var array = [];
    $(".js-validate-required-radio").each(function () {
        array.push($(this).prop('name'));
    });
    var uniqueNames = $.unique(array);
    for (var i = 0; i < uniqueNames.length; i++) {
        if ($('input:checkbox[name=' + uniqueNames[i] + ']:checked').val() == undefined) {
             if (flag) {
                flag = false;
            }
        }
    }
    if(!flag){
    alert('select atleast one radio on each row');
    }
    else{
            alert('yeee');
    }
    return flag;
}

here is fiddle


text:
Q: Date time format with TZ specfied with datetime in R( ISO 8601 ) I need to get current time in R in this particular format:
2014-01-07T14:57:55+05:30

Sys.time() seems to return in a different format than this. How do I exactly get this ?
Link to the format : https://en.wikipedia.org/wiki/ISO_8601

A: The function for converting/formatting a time string is as.POSIXct or as.POSIXlt.  The documentation for these points to the docs for strptime for format symbols.  This reference indicates %F is the correct symbol for ISO-8601 however, implementing that results in a format different from what you suggest.
> as.POSIXct(Sys.time(),format="%F")
[1] "2016-10-02 18:57:58 EDT"

I suspect looking at strptime you will find the combination necessary to output the exact format you need.

A: Is this what your looking for?
format(Sys.time(), format="%Y-%m-%dT%H:%M:%S+01:00")
format(Sys.time(), format="%Y-%m-%dT%H:%M:%S%z")

The meaning of the letters you find a the documentation of strptime() function


text:
Q: Minecraft blocks disappearing Every time I mine a block in Minecraft the newest Version "vanilla Minecraft no mods just straight Minecraft" I was able to mine the block, but said block just vanished. It wasn't in my inventory or on the ground, it just went poof.
Can anyone tell me why or how I fix said problem?

A: It could be that you don't have the correct tool to mine the block but can still break it. For example, you can break stone found in the world however it will take a while to break it and you will receive nothing. I would suggest having a look at the following guide if this is the case: Beginner's Guide.
If that is not the issue, it could be that your gamemode is set to 'Creative' in which case you will need to go about creating a new world or enabling cheats and changing your gamemode using the following command: /gamemode survival. You can enable cheats by going to the menu, selecting 'Open to LAN' and enabling the cheats option.

A: I dealt with this problem. If you save and exit, then enter back in to it, it should work.

A: Try to see if 'dotiledrops' is set to true. You can do this by using the command /gamerule dotiledrops true. Then try to mine something. This should work, but if it doesn't, I don't know what to tell you.

A: It may be a bug I noticed in MC 1.14: if your inventory is full, sometimes you can no more add any collected item into it, but the block vanished.
Or, if you mine something without the right tool, it doesn't drops any item. Use a pickaxe, luke…
and browse https://minecraft.fandom.com/wiki/Log#Chest_loot to validate the drop of any item when breaking with any tool.

A: I had this issue when running the beta version of the game on a iPad mini. It was such a piece of trash and could hardly render about 50 blocks. When I was listening to music or multitasking on this ipad, whenever I mined a block, it broke but then if i put my crosshair on it there was still a outline. If I were you, I would check the minimum requirements for minecraft on ur device and if that doesn't fix it, check that you are not in creative.


text:
Q: Include sonata menu in custom link with controller view I have this code in config.yml to add a item to the menu:
    # PrestaSonataNavigationBundle
    presta_sonata_navigation:
        menu:
            with_description: false
            items:
                report:
                    roles:
                        - ROLE_SONATA_ADMIN
                    children:
                        reportes:
                            route: informe_show

This route, "informe_show", it's a route to an action on a controller with a custom view, it isn't display the menu with the  services items.
How can i do to include the sonata menu?

A: If you want to use the Sonata administration menu on your front layout, please have a look on this answer: show sonata admin menu in every page if the admin is logged in


text:
Q: How could I get the rows full of values in a txt file? I've been struggling on a problem for a few hours.
I've a data-set which looks like this :
References                                                         425 1451  259
/1/J.H.Gibbons,R.L.Macklin:Phys.Rev.B137,1508(1965)                425 1451  260
/2/P.R.Wrean,C.R.Brune,R.W.Kavanagh:Phys.Rev.C49,1205(1994)        425 1451  261
/3/L.Van der Zwan,K.W.Geiger:Nucl.Phys.A152,481(1970)              425 1451  262
/4/T.Murata:JAERI-Conf 98-003,p.215                                425 1451  263
 3.500000+6 3.844649-2 3.508375+6 3.783472-2 4.000000+6-2.064883-2 425 3  2    7
 4.014688+6-2.289045-2 4.403160+6-8.623264-2 4.500000+6-1.022847-1 425 3  2    8
 1.450000+7-2.039133-1 1.500000+7-1.930321-1                       425 3  2   17

and I wonder how I could read and have in an array or a txt object only the last rows where they're values in each columns. To be sure I would like to have an object like this :
 3.500000+6 3.844649-2 3.508375+6 3.783472-2 4.000000+6-2.064883-2 425 3  2    7
 4.014688+6-2.289045-2 4.403160+6-8.623264-2 4.500000+6-1.022847-1 425 3  2    8
 1.450000+7-2.039133-1 1.500000+7-1.930321-1                       425 3  2   17

Sincerely I've found no such thing on StackOverflow so I ask the question directly.
Any answers would be nice.
Thank you !
hh

A: You'll need two components:
1.) A file reader How to read files in python
2.) A filter. I'd recommend regex for this regex in python
Loop through each line using your file reader. Use your filter to look for and extract data on each line.
This example may work if 425 will be at the start of all your data:
import re

data = []
# Allows you to read from your file
with open('your.txt') as f:

    # Will loop through each line
    for line in f.readlines():

        # Looks for 425 and pulls till end of line:
        data_point = re.search('425.*', line).group()
        data.append( data_point )

A: The table columns appear to have fixed widths.
Without having more of the table, it is hard to reliably determine if a row is meaningful or not. I've dropped rows if the value in the first column doesn't appear to be a number like 3.500000+6 by looking for . at the exact position.
The numbers in the first 6 columns seem to be in scientific notation but without the e. Code fixing that is included at the bottom.
import pandas as pd

filename = r"C:\Users\Bobson Dugnutt\Desktop\table.txt"

column_widths = (11, 11, 11, 11, 11, 11, 4, 2, 3, 5)

df = pd.read_fwf(filename, widths=column_widths, header=None)

print(df, end="\n\n")

# Returns True if it looks like a number like "3.500000+6"
def is_meaningful_row(value):
    #print(value)
    if isinstance(value, str):
        if value[-9] == ".":
            return True

    return False

# Remove rows if the first column doesn't look like a number like "3.500000+6"
df = df[df[0].map(is_meaningful_row)]

# Reset the index so the first row is no longer index 5
df = df.reset_index(drop=True)

print(df, end="\n\n")

# Replace NA/NaN values with empty strings
df = df.fillna("")

print(df, end="\n\n")

# Transforms a string like "-2.039133-1" to "-2.039133e-1"
def fix_scientific_notation(value):
    if isinstance(value, str):
        return value[0:1] + value[1:].replace("+", "e+").replace("-", "e-")

    return value

# For the first 6 columns, fixes the strange scientific notation and converts
# values from string to float64 or int64
for column in df.columns[:6]:
    df[column] = df[column].map(fix_scientific_notation)
    df[column] = pd.to_numeric(df[column])

print(df)

Output:
             0            1            2            3            4            5    6  7    8    9
0   References          NaN          NaN          NaN          NaN          NaN  425  1  451  259
1  /1/J.H.Gibb  ons,R.L.Mac  klin:Phys.R  ev.B137,150      8(1965)          NaN  425  1  451  260
2  /2/P.R.Wrea  n,C.R.Brune  ,R.W.Kavana  gh:Phys.Rev  .C49,1205(1         994)  425  1  451  261
3  /3/L.Van de  r Zwan,K.W.  Geiger:Nucl  .Phys.A152,    481(1970)          NaN  425  1  451  262
4  /4/T.Murata  :JAERI-Conf   98-003,p.2           15          NaN          NaN  425  1  451  263
5   3.500000+6   3.844649-2   3.508375+6   3.783472-2   4.000000+6  -2.064883-2  425  3    2    7
6   4.014688+6  -2.289045-2   4.403160+6  -8.623264-2   4.500000+6  -1.022847-1  425  3    2    8
7   1.450000+7  -2.039133-1   1.500000+7  -1.930321-1          NaN          NaN  425  3    2   17

            0            1           2            3           4            5    6  7  8   9
0  3.500000+6   3.844649-2  3.508375+6   3.783472-2  4.000000+6  -2.064883-2  425  3  2   7
1  4.014688+6  -2.289045-2  4.403160+6  -8.623264-2  4.500000+6  -1.022847-1  425  3  2   8
2  1.450000+7  -2.039133-1  1.500000+7  -1.930321-1         NaN          NaN  425  3  2  17

            0            1           2            3           4            5    6  7  8   9
0  3.500000+6   3.844649-2  3.508375+6   3.783472-2  4.000000+6  -2.064883-2  425  3  2   7
1  4.014688+6  -2.289045-2  4.403160+6  -8.623264-2  4.500000+6  -1.022847-1  425  3  2   8
2  1.450000+7  -2.039133-1  1.500000+7  -1.930321-1                           425  3  2  17

            0         1           2         3          4         5    6  7  8   9
0   3500000.0  0.038446   3508375.0  0.037835  4000000.0 -0.020649  425  3  2   7
1   4014688.0 -0.022890   4403160.0 -0.086233  4500000.0 -0.102285  425  3  2   8
2  14500000.0 -0.203913  15000000.0 -0.193032        NaN       NaN  425  3  2  17


text:
Q: How to check string from database if it's a URL using PHP? im having a problem.
I have field in my database where a user can put a facebook url. What i need to do is to check if the data is a url, parse it and just return the username after the / in the url.
An example:
if the database says https://www.facebook.com/username  just username
if says www.facebook.com/username same
if says just the username just show the username
i have tried it like this:
$url = $facebook;

if (strpos($url,'https://') == true){
$facebook = str_replace('https://', '', $url );
$facebook = substr(strrchr($url, '/'), 1);

}
else
{
$facebook = $facebook;
}

A: You'll need to use a regular expression:
$username = preg_replace("/.*\//", "", $url);

A period matches any character and a star does a 'greedy match' for the character that precedes it, meaning it keeps matching as long as it continues to satisfy the pattern. The backslash escapes the forward slash and allows it to be used as a matching character. In plain english, the pattern matches everything up to the last forward slash on a line and stops, then replaces it with "".


text:
Q: AngularJS dropdown default value is blank I am displaying data from a database in a table.  One of the table columns stores true/false.  I am displaying this column as a drop down, but the value is not defaulting to the database value.  The default is blank.
JS
$scope.options = [{ label: 'false', val: false }, { label: 'true', val: true }];

$scope.usersList = users
HTML

                    <select ng-model="user.admin"
                            ng-options="opt as opt.label for opt in options">
                        <option value="{{user.admin}}">{{user.admin}}</option>
                    </select>

Page Source

                    <select ng-model="user.admin" ng-options="opt as opt.label for opt in options" class="ng-pristine ng-valid ng-touched"><option value="?" selected="selected"></option><option label="false" value="object:15">false</option><option label="true" value="object:16">true</option></select>

A: By default the select ng-option is blank. you can initialise it:
$scope.user.admin = options[0];

A: Essentially, ensure user.admin has a value that maps to a value in your ng-options to set a default value and handle the blank option.
Why does AngularJS include an empty option in select?

A: You just need to initialize $scope.user.admin like this:
$scope.user.admin = true;

or like this
$scope.user.admin = false;

Have a look at this fiddle - http://jsfiddle.net/r9sb53zv/


text:
Q: intel 945GME x86/MMX/SSE2 driver HD videos in Youtube doesn't run good on my Lenovo S10e Laptop.
If someone can bring me a full guide of installing which is clear, I'll appreciate it much.
I've tried one site but it was to complicated to me. Please help!
Thank You!

A: just upgrade your PC... those drivers are present on the kernel....
visit system info from dash and visit the graphics section see to it that the expierence is standard and not fail safe
i had the same issue it wont detect my video driver but a few days later it automatically detectd and said Ironfield

A: Take a look here. This graphics chipset is pretty weak, so don't expect too much of it. Also, please be aware that this steps can destroy a functioning System. Hope this helps...


text:
Q: jQuery form validation not working in several if statements I have a problem with jQuery validation.
HTML:
<form action="#" name="validate" onsubmit="return validateRegistration();">
   <input type="text" id="username" value="Username" />
   <input type="text" id="email" value="Email" />
   <input type="text" id="phone" value="Phone" />
</form>

function validateRegistration() {

    var username = $('#username').val();
    var email = $('#email').val();
        var phone = $('#phone').val();

    if(username=='' || username == 'Username'){
       $('#username').after('Enter a username');
    }

    if(email=='' || email == 'Email'){
       $('#email').after('Please enter a valid email address');
    }

    if(phone=='' || phone == 'Phone'){
       $('#phone').after('This field is required.');
       return false;
    }
}

Validation works when the form has no values in it. And if I fill only phone fields, the form submits with return true. I can't put return false in all fields, since all the validation errors should be visible at a time. The code I have given is short and original. I have more than 30 fields, so any major variation is a pain. Any help?

A: function validateRegistration() {
        var notError = true;
        var username = $('#username').val();
        var email = $('#email').val();
            var phone = $('#phone').val();

        if(username=='' || username == 'Username'){
           $('#username').after('Enter a username');
           notError = false;
        }

        if(email=='' || email == 'Email'){
           $('#email').after('Please enter a valid email address');
           notError = false;
        }

        if(phone=='' || phone == 'Phone'){
           $('#phone').after('This field is required.');
           notError = false;
        }

        return notError;
    }

Hope this will satisfy your need


text:
Q: Как сделать сортировку массива по алфавиту, введённого через textbox C#? private void button1_Click(object sender, EventArgs e)
{
    string[] strArr = new string[]
    {
        textBox1.Text
    };
    Array.Sort(strArr, StringComparer.InvariantCulture);
    foreach (string item in strArr)
    {
        textBox2.Text = strArr[0];
    }
}

После ввода слов в первый TextBox и нажатия на кнопку введённые слова выводятся, но не сортируются во втором TextBox.

A: Все намного проще
private void button1_Click(object sender, EventArgs e)
{
    string[] lines = textBox1.Lines;
    Array.Sort(lines, StringComparer.InvariantCulture);
    textBox2.Lines = lines;
}

Каждое слово в новой строке должно быть.
Если слова через пробел без новых строк, тогда можно так
private void button1_Click(object sender, EventArgs e)
{
    string[] words = textBox1.Text.Split();
    Array.Sort(words, StringComparer.InvariantCulture);
    textBox2.Text = string.Join(" ", words);
}


text:
Q: Accessing PyTorch modules - ResNet18 I am using a ResNet-18 coded as follows:
class ResidualBlock(nn.Module):
    '''
    Residual Block within a ResNet CNN model
    '''
    def __init__(self, input_channels, num_channels,
                 use_1x1_conv = False, strides = 1):
        # super(ResidualBlock, self).__init__()
        super().__init__()

        self.conv1 = nn.Conv2d(
            in_channels = input_channels, out_channels = num_channels,
            kernel_size = 3, padding = 1, stride = strides,
            bias = False
            )
        self.bn1 = nn.BatchNorm2d(num_features = num_channels)

        self.conv2 = nn.Conv2d(
            in_channels = num_channels, out_channels = num_channels,
            kernel_size = 3, padding = 1, stride = 1,
            bias = False
            )
        self.bn2 = nn.BatchNorm2d(num_features = num_channels)

        if use_1x1_conv:
            self.conv3 = nn.Conv2d(
                in_channels = input_channels, out_channels = num_channels,
                kernel_size = 1, stride = strides
                )
            self.bn3 = nn.BatchNorm2d(num_features = num_channels)
        else:
            self.conv3 = None

        self.relu = nn.ReLU(inplace = True)

        self.initialize_weights()

    def forward(self, X):
        Y = F.relu(self.bn1(self.conv1(X)))
        Y = self.bn2(self.conv2(Y))

        if self.conv3:
            X = self.bn3(self.conv3(X))
            # print(f"X.shape due to 1x1: {X.shape} & Y.shape = {Y.shape}")
        else:
            # print(f"X.shape without 1x1: {X.shape} & Y.shape = {Y.shape}")
            pass

        Y += X
        return F.relu(Y)

    def shape_computation(self, X):
        Y = self.conv1(X)
        print(f"self.conv1(X).shape: {Y.shape}")
        Y = self.conv2(Y)
        print(f"self.conv2(X).shape: {Y.shape}")

        if self.conv3:
            h = self.conv3(X)
            print(f"self.conv3(X).shape: {h.shape}")

    def initialize_weights(self):
        for m in self.modules():
            # print(m)
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_uniform_(m.weight)

                '''
                # Do not initialize bias (due to batchnorm)-
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
                '''

            elif isinstance(m, nn.BatchNorm2d):
                # Standard initialization for batch normalization-
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

            elif isinstance(m, nn.Linear):
                nn.init.kaiming_normal_(m.weight)
                nn.init.constant_(m.bias, 0)

b0 = nn.Sequential(
    nn.Conv2d(in_channels = 3, out_channels = 64, kernel_size = 3, stride = 1, padding = 1),
    nn.BatchNorm2d(num_features = 64),
    nn.ReLU())

def create_resnet_block(input_filters, output_filters, num_residuals, first_block = False):
    # Python list to hold the created ResNet blocks-
    resnet_blk = []

    for i in range(num_residuals):
        if i == 0 and first_block:
            resnet_blk.append(ResidualBlock(input_channels = input_filters, num_channels = output_filters, use_1x1_conv = True, strides = 2))
        else:
            resnet_blk.append(ResidualBlock(input_channels = output_filters, num_channels = output_filters, use_1x1_conv = False, strides = 1))

    return resnet_blk

b1 = nn.Sequential(*create_resnet_block(input_filters = 64, output_filters = 64, num_residuals = 2, first_block = True))

b2 = nn.Sequential(*create_resnet_block(input_filters = 64, output_filters = 128, num_residuals = 2, first_block = True))

b3 = nn.Sequential(*create_resnet_block(input_filters = 128, output_filters = 256, num_residuals = 2, first_block = True))

b4 = nn.Sequential(*create_resnet_block(input_filters = 256, output_filters = 512, num_residuals = 2, first_block = True))

# Initialize a ResNet-18 CNN model-
model = nn.Sequential(
    b0, b1, b2, b3, b4,
    nn.AdaptiveAvgPool2d(output_size = (1, 1)),
    nn.Flatten(),
    nn.Linear(in_features = 512, out_features = 10))

The layer names are now as follows:
for layer_name, param in trained_model.named_parameters():
    print(f"layer name: {layer_name} has {param.shape}")

Result:
> layer name: 0.0.weight has torch.Size([64, 3, 3, 3])

> layer name: 0.0.bias has torch.Size([64])

> layer name: 0.1.weight has torch.Size([64])

> layer name: 0.1.bias has torch.Size([64])

> layer name: 1.0.conv1.weight has torch.Size([64, 64, 3, 3])

> layer name: 1.0.bn1.weight has torch.Size([64])

> layer name: 1.0.bn1.bias has torch.Size([64])

> layer name: 1.0.conv2.weight has torch.Size([64, 64, 3, 3])

> layer name: 1.0.bn2.weight has torch.Size([64])

> layer name: 1.0.bn2.bias has torch.Size([64])

> layer name: 1.0.conv3.weight has torch.Size([64, 64, 1, 1])

> layer name: 1.0.conv3.bias has torch.Size([64])

> layer name: 1.0.bn3.weight has torch.Size([64])

> layer name: 1.0.bn3.bias has torch.Size([64])

> layer name: 1.1.conv1.weight has torch.Size([64, 64, 3, 3])

> layer name: 1.1.bn1.weight has torch.Size([64])

> layer name: 1.1.bn1.bias has torch.Size([64])

> layer name: 1.1.conv2.weight has torch.Size([64, 64, 3, 3])

> layer name: 1.1.bn2.weight has torch.Size([64])

> layer name: 1.1.bn2.bias has torch.Size([64])

> layer name: 2.0.conv1.weight has torch.Size([128, 64, 3, 3])

> layer name: 2.0.bn1.weight has torch.Size([128])

> layer name: 2.0.bn1.bias has torch.Size([128])

> layer name: 2.0.conv2.weight has torch.Size([128, 128, 3, 3])

> layer name: 2.0.bn2.weight has torch.Size([128])

> layer name: 2.0.bn2.bias has torch.Size([128])

> layer name: 2.0.conv3.weight has torch.Size([128, 64, 1, 1])

> layer name: 2.0.conv3.bias has torch.Size([128])

> layer name: 2.0.bn3.weight has torch.Size([128])

> layer name: 2.0.bn3.bias has torch.Size([128])

> layer name: 2.1.conv1.weight has torch.Size([128, 128, 3, 3])

> layer name: 2.1.bn1.weight has torch.Size([128])

> layer name: 2.1.bn1.bias has torch.Size([128])

> layer name: 2.1.conv2.weight has torch.Size([128, 128, 3, 3])

> layer name: 2.1.bn2.weight has torch.Size([128])

> layer name: 2.1.bn2.bias has torch.Size([128])

> layer name: 3.0.conv1.weight has torch.Size([256, 128, 3, 3])

> layer name: 3.0.bn1.weight has torch.Size([256])

> layer name: 3.0.bn1.bias has torch.Size([256])

> layer name: 3.0.conv2.weight has torch.Size([256, 256, 3, 3])

> layer name: 3.0.bn2.weight has torch.Size([256])

> layer name: 3.0.bn2.bias has torch.Size([256])

> layer name: 3.0.conv3.weight has torch.Size([256, 128, 1, 1])

> layer name: 3.0.conv3.bias has torch.Size([256])

> layer name: 3.0.bn3.weight has torch.Size([256])

> layer name: 3.0.bn3.bias has torch.Size([256])

> layer name: 3.1.conv1.weight has torch.Size([256, 256, 3, 3])

> layer name: 3.1.bn1.weight has torch.Size([256])

> layer name: 3.1.bn1.bias has torch.Size([256])

> layer name: 3.1.conv2.weight has torch.Size([256, 256, 3, 3])

> layer name: 3.1.bn2.weight has torch.Size([256])

> layer name: 3.1.bn2.bias has torch.Size([256])

> layer name: 4.0.conv1.weight has torch.Size([512, 256, 3, 3])

> layer name: 4.0.bn1.weight has torch.Size([512])

> layer name: 4.0.bn1.bias has torch.Size([512])

> layer name: 4.0.conv2.weight has torch.Size([512, 512, 3, 3])

> layer name: 4.0.bn2.weight has torch.Size([512])

> layer name: 4.0.bn2.bias has torch.Size([512])

> layer name: 4.0.conv3.weight has torch.Size([512, 256, 1, 1])

> layer name: 4.0.conv3.bias has torch.Size([512])

> layer name: 4.0.bn3.weight has torch.Size([512])

> layer name: 4.0.bn3.bias has torch.Size([512])

> layer name: 4.1.conv1.weight has torch.Size([512, 512, 3, 3])

> layer name: 4.1.bn1.weight has torch.Size([512])

> layer name: 4.1.bn1.bias has torch.Size([512])

> layer name: 4.1.conv2.weight has torch.Size([512, 512, 3, 3])

> layer name: 4.1.bn2.weight has torch.Size([512])

> layer name: 4.1.bn2.bias has torch.Size([512])

> layer name: 7.weight has torch.Size([10, 512])

> layer name: 7.bias has torch.Size([10])

In order to prune this model, I am referring to PyTorch pruning tutorial. It's mentioned here that to prune a module/layer, use the following code:
parameters_to_prune = (
    (model.conv1, 'weight'),
    (model.conv2, 'weight'),
    (model.fc1, 'weight'),
    (model.fc2, 'weight'),
    (model.fc3, 'weight'),
)

But for the code above, the modules/layers no longer have this naming convention. For example, to prune the first conv layer of this model:
> layer name: 0.0.weight has torch.Size([64, 3, 3, 3])

on trying the following code:
prune.random_unstructured(model.0.0, name = 'weight', amount = 0.3)

It gives me the error:
prune.random_unstructured(trained_model.0.0, name = 'weight', amount = 0.3)
                                           ^ SyntaxError: invalid syntax

How do I handle this?

A: this will work
import torch.nn.utils.prune as prune
prune.random_unstructured(list(model.children())[0][0] , name = 'weight', amount = 0.3) # first conv layer


text:
Q: Remove duplicate rows and add count I'm trying add a count column to my table. I want to remove duplicate rows and add an additional column with the count of rows removed.
My Table looks like this:
start             institution_code  year
Indianapolis, IN    IUBLA           2004
Indianapolis, IN    IUBLA           2004
Indianapolis, IN    IUINA           2004
Bloomington,  IN    IUINA           2002
Bloomington,  IN    IUINA           2002

And I'd like the final version to look like this:
start             institution_code  year    Count
Indianapolis, IN    IUBLA           2004    2
Indianapolis, IN    IUINA           2004    1
Bloomington,  IN    IUINA           2002    2

I thought come combination of Count and Group By or even Over but I haven't been able to come up with a working example.
                                              version
---------------------------------------------------------------------------------------------------------
 PostgreSQL 10.7 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-23), 64-bit

A: It should be a pretty straight forward group by and count:
select start, institution_code  , year, count(*) as Count
from yourtable
group by start, institution_code  , year;


text:
Q: Polite/professional auto-acknowledgment email for support inquries I am trying to create an auto acknowledgment email for support requests we receive. I want it to look polite and professional, but I find it a bit difficult to word properly since I am not a native speaker. How does my email look?

Subject: Your message is received
Thank you very much for your message! [optional(a): We know your time is valuable and we would like to acknowledge that we have received your request.]
We work hard on answering every support message as quickly as possible
  and usually respond within a few hours or less. Occasionally, [optional(b):
  due to the high number of inquiries we receive,] we might not be able get back
  to you right away. While you are waiting, another great source for
  answers is our FAQ section: http://www.example.com/support
Thank you for your patience.
[optional(c): Sincerely,]
Support Team

A: I am a native speaker of American English. Everything looks grammatically correct to me, and it reads clearly and professionally.
As a fellow programmer, I feel like users appreciate seeing a more personable response, even if it is just auto-generated, especially if it's in response to something that took them a bit of time to complete. It makes them feel important to your company. For that reason, I would add all of the optional sections you've suggested to the final email template.


text:
Q: Inconsistent behaviour accessing private nested class definition I have code that declares a subclass template as private and then a member as protected:
class X {
private:
    template <class T>
    class Y {
    public:
        void somethingToDo();
        // definition
    };
protected:
    Y<SomeType> _protectedMember;
    // More definition
};

class Z : public virtual X{
public:
    void f();
}
void Z::f() {
    ...
    _protectedMember.somethingToDo();
}

Originally I compiled this with gcc 4.3.4 and it accepted it.  I then sent it off to try and build against GCC, IBM and Microsoft compilers on various platforms and the non-gcc compilers rejected it.  Now that seems to be an indictment of (this version of) gcc's standards compliance.  But before I come to any conclusions, I'd like to verify what is technically correct.
Thanks.

A: I'm pretty sure I've seen this before.  It was a known bug in GCC at the time and has since been fixed.

A: Your program appears valid to me (well, except for Y::somethingToDo being nonsensically private). Z::f() isn't asking for access to any private names, only protected ones.
If Z::f() tried to reference Y<T>, then the compiler should err. But Z::f() is only accessing _protectedMember, which is surely allowed.

A: You Y template is private and can't used in codes that are not private, like _protectedMember witch intended to be accessible from derived class, you should also declare it as protected, so its member be visible to derived classes.
as a general rule if you want your variable to be completely accessible to some scope, then its type must be completely accessible in that scope. of course your code can be useful with current design in following situation:
class Base {
    class PrivateClass {};
protected:
    PrivateClass _val;
    void doSomething( PrivateClass& v );
}

now derived classes can use _val to call doSomething but they can't call its methods or use its properties.


text:
Q: How Mozilla Rhino can use nodejs "fs" module? Let's say I have my.js file that has dependency on nodejs fs module. Like:
var fs = require('fs');

The question: How can I load Core NodeJS module like "FS" in My Mozilla Rhino Java Code to be able to run my.js that depends on it ?

A: I don't think you can do this. fs module just a wrapper for native bindings built into node.js itself.
There are some thoughts flying in the sky of node.js community about being able to use different JS engines inside node.js but I don't think we will see this in the near future.

A: You can also write your own fs.js, only implementing the functions you need. Here is a start:
exports.readFile = function(file, enc, callback) {
  try {
    text = readFile(file, enc);
    callback(null, text);
  }
  catch (e) {
    callback(e, null);
  }
}

I've used this together with jvm-npm.


text:
Q: Extracting software commonalities in a Agile Process Recently i had the chance of working on a large software project which followed the Agile Process. When we began working on the project, a lot of the software requirements were not clear. However, the software lead made a mistake of developing a Framework which basically extracted commonalities and placed these in a super class. As the project progressed, a lot of requirements came clear and a lot of  existing requirements changed, which off course caused constant change in our "Framework" .
My question is, what should we do in such a case .

*

*Extract commonalities, only once all the requirements are clear.

*Do try any code optimization until the project is finished.

*Go with the flow, and adapt the code as the requirements change.

Is there any anti-pattern that describes this scenario ? Alot of developers have a fascination with moving common functions to a super class ? What is the general feedback for this ?
Kind Regards

A: Extreme Programming (a flavour of agile development, though less fashionable now than in the past) has the principle of YAGNI - "You Ain't Gonna Need It". This advises against creating such frameworks up-front, or anything that doesn't directly support the current story. See http://c2.com/cgi/wiki?YouArentGonnaNeedIt for more.
Of course, it's possible to take this too far. If a project is likely to need, say, logging/tracing, then it would be a lot of work to wait until you had a serviceability story in which the logs are used, and only then create a logging framework and go back and instrument all the classes with trace points, instead of doing it as a matter of course as you write the code.
So you need to be pragmatic and create just the right amount of "stuff that you foresee a need for". How much is the right amount I think is something you can only judge by experience.
In terms of your three options, I guess this is closest to number three. Refactoring code as you learn more about the problem and about the structure of your software is not a bad thing. Provided, that is, that your small-scale design (encapsulation, separation of concerns, etc) is good so that every change doesn't involve dozens of complex edits, and that you have good tests, which cover enough of the function but aren't tied too tightly to implementation. Then you can refactor with confidence as your design changes.

A: That's a hard one. I've been there a few times. It's hard because usually we (as developers or architects) should strive for gathering the requirements up front...my teammates and me usually phrase that without requirements we shouldn't write a single line of code, or make any design decisions. Which is absolutely true, but, in real life it gets a bit complicated, sometimes customers don't even know what they want...however, the Executive Board wants to keep the customer happy and make them believe we are the best fit for their project (and in fact we are) by getting the ball rolling.
At that point we start architecting a "very flexible", maintainable, scalable system and then a couple of months later requirements change and we have to re-design the system's foundations. You'd wish there were a magic design pattern/guideline to follow and prevent this...well, unfortunately, there isn't.
You can always minimize the impact of such requirement creeps but no matter how flexible you've built your system you will always have to build it with a set of basic requirements in mind, if the requirements change, then the system might need to be changed as well.


text:
Q: Missing bar in PGFplot I have the following chart yet the blue bar doesn't display correct:
\begin{tikzpicture}
 \begin{semilogyaxis}[ybar,   xticklabels={{2}, {10}, {28}, {112}, {224}, {392}}, xtick = {2, 4, 6, 8, 10, 12},
         width = 0.45*\textwidth,
         xtick style={draw=none},
         ymajorgrids=true,
         ylabel={Transmission Speed (kbps)},
         xlabel={Message Size}, xticklabel style={rotate=90},]
\addplot [draw=blue,pattern color = blue, pattern = north west lines]
                coordinates {(2, 473000)};
\addplot [draw=red,pattern color = red, pattern = north west lines]
                coordinates {(4, 88500)};
\addplot [draw=green,pattern color = green, pattern = north west lines]
                coordinates {(6, 2320)};
\addplot [draw=yellow,pattern color = yellow, pattern = north west lines]
                coordinates {(8, 1160)};
\addplot [draw=black,pattern color = black, pattern = north west lines]
                coordinates {(10, 251)};
\addplot [draw=black,pattern color = black, pattern = north east lines]
                coordinates {(12, 164)};
\end{semilogyaxis}
\end{tikzpicture}

I can't see why the 2, 473000 coordinates are missing.

A: You have multiple bar plots inside one axis environment. So there could be more than one bar for a x value. So the bars for each plot are shifted a bit to not overlap each other.
But it seems that you do not want/need this shift. So you could set bar shift=0pt as axis option:
\documentclass[margin=5pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}
\usetikzlibrary{patterns}
\begin{document}
\begin{tikzpicture}
 \begin{semilogyaxis}[ybar,   xticklabels={{2}, {10}, {28}, {112}, {224}, {392}}, xtick = {2, 4, 6, 8, 10, 12},
         width = 0.45*\textwidth,
         xtick style={draw=none},
         ymajorgrids=true,
         ylabel={Transmission Speed (kbps)},
         xlabel={Message Size}, xticklabel style={rotate=90},
          bar shift=0pt% <- added
         ]
\addplot [draw=blue,pattern color = blue, pattern = north west lines]
                coordinates {(2, 473000)};
\addplot [draw=red,pattern color = red, pattern = north west lines]
                coordinates {(4, 88500)};
\addplot [draw=green,pattern color = green, pattern = north west lines]
                coordinates {(6, 2320)};
\addplot [draw=yellow,pattern color = yellow, pattern = north west lines]
                coordinates {(8, 1160)};
\addplot [draw=black,pattern color = black, pattern = north west lines]
                coordinates {(10, 251)};
\addplot [draw=black,pattern color = black, pattern = north east lines]
                coordinates {(12, 164)};
\end{semilogyaxis}
\end{tikzpicture}
\end{document}


text:
Q: Entity Framework DeleteObject child What is the best way to delete an object (and its child objects) using EF?  I'd like to pass just the id for the object to delete, and have EF handle deleting its dependent data (foreign key'd data).  Do I have to retrieve the object first based on the id and then call "DeleteObject"?

A: If you have cascade configured in the database, then deleting the principle should be enough.
You can do this without a query to the database to GET the thing to be deleted using Stub entities like this:
var stub = new Principal{ID = idToDelete};
ctx.AttachTo("PrincipalsEntitySetName", stub);
ctx.DeleteObject(stub);

Of course this is not the whole story if there are references or fields used for concurrency checks you will need those too.
If on the other hand you only have a cascade delete in the model (i.e. there is no cascade in the database) you will need to get ALL the dependents in memory first, and then call delete:
var stub = new Principal{ID = idToDelete};
ctx.AttachTo("PrincipalsEntitySetName", stub);
stub.Dependendents.Load();
ctx.DeleteObject(stub);

This only works because the EF issues (what it expects to be ) redundant deletes to keep the ObjectContext in sync with what it expects to happen in the database.
Hope this helps
Alex
PS I have some tips on this topic on my MSDN blog. Check out tip 33 (cascade delete) and tip 26 (stub entities)


text:
Q: Editing the DOM using the response from a fetch() call I am simply trying to edit the DOM using the data I get back from a fetch() request. I am still new to asynchronous programming, and I am sure there is something I am doing wrong here.
Heres the code:
window.onload = () => {
  const apiURL = 'https://www.APIurl.......';
  fetch(apiURL).then( (response) => {
    return response.json();
  }).then( (object) => {
    let {values} = object;

    document.getElementById('date1').innerHTML = values[0][0];
    console.log('This will run');
    document.getElementById('date2').innerHTML = values[13][0];
    console.log('This will not run');
    document.getElementById('date3').innerHTML = values[31][0];

  });
}

My problem is that I make the call, get the data back just fine, but when I am trying to manipulate the DOM, only the first edit works. I am not sure if the document.getElementById is causing the callback to return early, but I need to edit multiple elements on the DOM with the data I get back.
If there is a better way to do this, or if anyone has a fix, that would be great!
Thanks!!

A: You're getting an error "TypeError: Cannot set property 'innerHTML' of null" which means that you're selecting element, this element doesn't exist in the DOM (null is returned) and you're trying to set innerHTML property of null.
In order to fix this you have to add elements with date2 and date3 to your markup so you can set their innerHTML.
Also in order to log errors from your Promises add catch() block as described in the docs


text:
Q: Advanced definition of derivative. In the paper On proof and progress in mathematics, W. P. Thurston gives the following interpretation of the derivative.

...one
  person's clear mental image is another person's intimidation:
The derivative of a real-valued function $f$ in a domain $D$ is the Lagrangian section of the cotangent bundle $T^∗(D)$ that gives the connection form for the unique flat connection on the trivial $\mathbf R$-bundle $D\times \mathbf R$ for which the graph of $f$ is parallel.

In order to make this interpretation clear, what should a person who only finished a "traditional" Calculus course (say in the James Stewart's style) read?
Indications of books or chapter of books would be great.


text:
Q: Is there a phase transition for degenerate matter? Does electron or neutron degenerate matter undergo a phase transition? Are there any thermodynamic quantities that are discontinuous?

A: Neutron degenerate matter can undergo a phase transition to a superfluid state. The process is thought to be analogous to Cooper-pairing, but the coupling interaction due to the long-range nuclear force is of order 1 MeV, so can occur at temperatures below about $10^{9}$ K in neutron star interiors. The neutrons (fermions) form bosonic pairs in an analogous way to a He-3 superfluid. The neutrons in the deep interior (which dominate the interior 100:1) can form a superfluid; the protons can form a superconducting superfluid. Neutrons in the inner crust can also form a superfluid that has been implicated in pulsar glitches.
Superfluidity immediately changes the viscosity and the heat capacity of the degenerate neutrons, since it is only neutrons at the top of the "Fermi sea" that pair up. These pairs then have to be broken again to extract whatever heat remains. Ironically, the phase change, which will occur over some period of years in a neutron star because of radial density and temperature variations, causes a period of rapid cooling due to the neutrinos produced by the formation and thermal breaking of neutron pairs. This has now been observed (or claimed, see papers by Heinke & Ho 2010; Shternin et al. 2011).
In the crust of a neutron star there is a phase change associated with it being energetically feasible for degenerate neutrons to drip out of neutron-rich nuclei to join the degenerate electron fluid. This phase change, at densities of about $4\times 10^{14}$ kg/m$^3$, significantly changes the adiabatic index of the gas through electron capture.
At even higher densities ($>10^{16}$ kg/m$^3$) there are thought to be a series of phase changes, collectively called the nuclear pasta phase. This is where the remaining nuclei and neutron fluid arrange themselves into a weird variety of planes (lasagne) or tubes (spaghetti) in order to minimise the total energy density of the material. I am not aware of any major thermodynamic discontinuities associated with this. Eventually the pasta loses its structure to form a fluid of degenerate nucleons (dominated by neutrons) plus degenerate electrons.
Neutrons near the core of a neutron may make a phase change from a fluid state into a structure that is more like a solid, with a very hard equation of state. The details are tied up in uncertainties in many-body strong nuclear interactions and whether the neutrons will start to decay into hyperons or heavy hadrons.
In white dwarf electron degenerate material there is a very important phase change associated with crystallisation of the non-degenerate ions. This increases the heat capacity, releases latent heat of crystallisation and prolongs white dwarf cooling. This crystallisation process is generally accepted fact and is required to match white dwarf luminosities in clusters of known age and the luminosity function of nearby white dwarfs. It has also been detected by asteroseismology because the phase change occurs at higher densities in the white dwarf core and spreads outwards as the white dwarf cools and causes a discontinuity in the interior sound speed (e.g. Winget et al. 1997; Metcalfe et al. 2005).  However, as far as I know, the electrons do not undergo any phase change. They are obviously much too hot to form the Cooper pairs responsible for super conductivity in laboratory materials.

A: At least in the context of ultracold atomic fermions, the answer is no. The creation of a degenerate fermi gas is, unlike a BEC, not a phase transition.
One major caveat: if there is an attractive force between the fermions, one can get a BCS-like phase transition to condensation of paired fermions. This is, of course, the case for electrons in metals, as well as fermionic liquid He-3.


text:
Q: Javascript closures and memory leak risks Recetly I was looking for memory leaks in my javascript code. Ater finding some major leaks I starter to look for minor and found something that could be a potential leak - the "hoverIntent.js" plugin. I would like to ask if this is really a leak or am I a bit too overzealous?
General schema fo the code (full code here http://cherne.net/brian/resources/jquery.hoverIntent.js):
(function($) {
    $.fn.hoverIntent = function(f,g) {

    //...

    var track = function(ev) {
        cX = ev.pageX;
        cY = ev.pageY;
    };

    var compare = function(ev,ob) {
        //... function body
    };

    var delay = function(ev,ob) {
       //... function body
    };

    var handleHover = function(e) {
      //... function body
    };

    return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover);
    };
})(jQuery);

I know that many js plugins are written that way, but... If I get that correctly every time I invoke hoverIntent on my object, 3 new functuions (closures) are created? Isn't it a possible memory leak (or at least a performace issue)?
Wouldn't it be better to write is this way:
(function($) {

  //create the methods only once on module init?

    var track = function(ev) {
        cX = ev.pageX;
        cY = ev.pageY;
    };

    var compare = function(ev,ob) {
        //... function body
    };

    var delay = function(ev,ob) {
       //... function body
    };

    var handleHover = function(e) {
      //... function body
    };

    $.fn.hoverIntent = function(f,g) {
            //no closures here
    return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover);

    };
})(jQuery);

A: You are correct, your second example would use less memory because of less closure functions. But as soon as you event isn't callable (element removed etc.) they would disappear again so it is not a "leak" as the memory isn't lost forever.
Also many plugins use the closure by setting the current state of an element in a variable instead of the element itself.


text:
Q: Update TempData after refreshing page I'm trying to setup a page that can combine two Excel file into one, and I want to show some message on the page after the file was downloaded, so I use TempData to send the message to my view and use ajax to reload the page after the download was done. However, the message didn't show up but if I click on the refresh button on the browser the will message show up. Here is my code on View.
$("#surveyform").on('submit', (function (e) {
    e.preventDefault();
    $.ajax({
        url: '@Url.Action("downloadreport", "surveyForm")',
        type: 'POST',
        data: new FormData(this),
        contentType: false,
        cache: false,
        processData: false,
        success: function () {
            location.reload(true);
        }
    });
}));

Can someone tell me why the message show up when I click on browser's refresh button but won't show up with my ajax? And how to fix it?
My controller:
public ActionResult downloadreport(HttpPostedFileBase file,HttpPostedFileBase file1)
{
    bool missCol = false;
    // .... code to create a excel file (missCol set to true if successful)
    if (missCol != true)
    {
        TempData["misscol"] = " File download success!";
        return File(newMS, "application/octet-stream", downloadFileName);
    }
    else
    {
        TempData["misscol"] = " Please check your headsource due to missing column!";
        return File(newMS, "application/octet-stream", downloadFileName);
    }
}

public ActionResult Index()
{
    var msgtemp = Convert.ToString(TempData["misscol"]);
    TempData["errorcode"] = msgtemp;
    return View();
 }


text:
Q: HTML5 Thymeleaf - placeholder for input type=number shows 0 I'm creating a simple HTML form along with Thymelaf that I use in my Spring Boot application.
  In the form I specified a following statement:
<input type="number" step="0.1" min="0" max="10" **th:field="*{rating}"**
                   class="form-control mb-4 col-4" placeholder="Rating">

However, instead of Rating, the value showed in the form is 0.

Once you delete the 0, placeholder finally appears.

Edit
Apparently, Thymeleaf seems to cause the problem here.
<input type="number" step="0.1" min="0" max="10" th:field="*{rating}"
                   class="form-control mb-4 col-4" placeholder="Rating">
<input type="number" placeholder="Test Rating"
                   class="form-control mb-4 col-4">

The form without th:field="{rating}"* works fine.

A: If you don't want the default of 0 you can't use primitive data types as int, long, float and double.
Instead use wrapper class with null for a variable related with th:field="*{rating}" for empty form.

A: Your code works as expected in plain HTML. Try using th:placeholder attribute instead of placeholder


text:
Q: Firebase + Google Games Services While setting up Firebase and Google Game Services it is not possible to link the app in the Play Developer Console (games services). Firebase projects auto generate the relevant api keys etc. altering these breaks Firebase.
I also tried creating a game from an existing project in the api console but it could not find any.
Has anyone had this and overcome it before?
I have confirmed that the Firebase implementation works as well as the Games Services implementation when they are independent of each other.

A: It sounds like the account you're using on Play Developer Console is not an owner of the Project you defined in Firebase. Can you verify if the logged in user account in Play is added as an owner for the given project on: https://console.cloud.google.com/iam-admin? You should then be able to import the project on the Play Developer Console.


text:
Q: graphql throwing 400 error even though the query is valid Following is the error that is being thrown when I am trying to load into the page, I have narrowed down the function that is throwing this error. That function is shown below the error. I am not sure what is causing this as it was working fine a few hours back, I have made changes to the file but not directly to this function.
Also when I visit the website which is the graphQLAPI, when I input the same query I do get an output, so the query is valid.
error - ClientError: GraphQL Error (Code: 400): {"response":{"error":"{\"errors\":[{\"message\":\"environment \\\"master;\\\" is invalid\"}],\"data\":null}","status":400,"headers":{}},"request":{"query":"\n    query MyQuery {\n      postsConnection {\n        edges {\n          cursor\n          node {\n            author {\n              bio\n              name\n              id\n              photo {\n                url\n              }\n            }\n            createdAt\n            slug\n            title\n            excerpt\n            featuredImage {\n              url\n            }\n            categories {\n              name\n              slug\n            }\n          }\n        }\n      }\n    }\n  "}}
    at C:\Users\shant\Desktop\React-Projects\project-1\node_modules\graphql-request\dist\index.js:359:31
    at step (C:\Users\shant\Desktop\React-Projects\project-1\node_modules\graphql-request\dist\index.js:63:23)
    at Object.next (C:\Users\shant\Desktop\React-Projects\project-1\node_modules\graphql-request\dist\index.js:44:53)
    at fulfilled (C:\Users\shant\Desktop\React-Projects\project-1\node_modules\graphql-request\dist\index.js:35:58)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  response: {
    error: '{"errors":[{"message":"environment \\"master;\\" is invalid"}],"data":null}',
    status: 400,
    headers: Headers { [Symbol(map)]: [Object: null prototype] }
  },
  request: {
    query: '\n' +
      '    query MyQuery {\n' +
      '      postsConnection {\n' +
      '        edges {\n' +
      '          cursor\n' +
      '          node {\n' +
      '            author {\n' +
      '              bio\n' +
      '              name\n' +
      '              id\n' +
      '              photo {\n' +
      '                url\n' +
      '              }\n' +
      '            }\n' +
      '            createdAt\n' +
      '            slug\n' +
      '            title\n' +
      '            excerpt\n' +
      '            featuredImage {\n' +
      '              url\n' +
      '            }\n' +
      '            categories {\n' +
      '              name\n' +
      '              slug\n' +
      '            }\n' +
      '          }\n' +
      '        }\n' +
      '      }\n' +
      '    }\n' +
      '  ',
    variables: undefined
  },
  page: '/'
}

The function that I believe is throwing this error is
export const getPosts = async () => {
  console.log(graphqlAPI)
  const query = gql`
    query MyQuery {
      postsConnection {
        edges {
          cursor
          node {
            author {
              bio
              name
              id
              photo {
                url
              }
            }
            createdAt
            slug
            title
            excerpt
            featuredImage {
              url
            }
            categories {
              name
              slug
            }
          }
        }
      }
    }
  `;

  const result = await request(graphqlAPI, query);

  return result.postsConnection.edges;
};


text:
Q: Javascript call is being ignored I am currently working on an advanced view page that display results for a set of data in Asp.NET MVC. I am having a problem with javascript. I have only used a small amount of javascript, so I am still learning. My code seems to go right over the call. I understand it is most likely horrible coding to include a script inside an if statement, but that seemed like the only solution to avoid a NullReferenceException.
This code is being used to not only redirect the user to another page, but also open the file.
     @if(item.PDFLink.GetValueOrDefault() != 0)
                    {

                    }
                    @if(item.PDFLink.GetValueOrDefault() != 0)
                    {
                           @Html.ActionLink("text", "Display", null, new { onclick = "return showfile();"})
                    }

A: There is really no reason to use the helper in this case. Since all you want it to do is to point a javascript function.
Change
@Html.ActionLink("text", "Display", null, new { onclick = "return showfile();" })

To
text

Unless I'm missing something this is all you need.

A: I fixed my own problem after puzzling over this...
I wanted to basically open another view and the file, so that the user did not lose the page they were currently on.
I scrapped all the javascript, and instead used this:

This opens the file in a new window, while keeping my current view. Pretty interesting how easy this solution actually was. Thanks for the help though.


text:
Q: ""ping 8.8.8.8 connect: Network is unreachable"" in centOS 7 on VMware workstation 14 I am trying to work with centOS 7 which I installed on VMware workstation.
But it doesn't have internet connection:
$ ping 8.8.8.8
connect: Network is unreachable

$ ping www.google.com
ping: www.google.com: Name or service not known

I checked NAT in my virtual machine settings and it is the output of ifconfig command:
ens33: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether 00:0c:29:7a:53:87  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 504  bytes 44064 (43.0 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 504  bytes 44064 (43.0 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

virbr0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 192.168.122.1  netmask 255.255.255.0  broadcast 192.168.122.255
        ether 52:54:00:14:b1:67  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

any idea how can I get internet access?

A: You do not have IP address assigned to your network interface "ens33".
Type "dhclient" in terminal, that should fix the issue,
if it does not work, please print output of command "ip addr" from terminal
Regards,
Nik

A: You should check your Virtual Machine network config in order to be sure the network adapter is properly mapped. The best way in my opinion is not to NAT, but bridge the adapter to the phisical host apadter. Then your router dhcp server will provide a correct IP to your Centos virtual machine. Anyway you would need to check the Centos network configuration to see if the ip was assigned properly as long as it is the default gateway and DNS server.


text:
Q: Prove that a function is solution of IVP Let $f\in \mathcal{C}^1$ and let $F$ defined by
$$F(x)=\dfrac{1}{a}\int_0^x f(t)\sin(a(x-t))dt$$
where $a\in \mathbb{R}\setminus\{0\}$. Prove that $F$ is solution of the IVP
$$y''+a^2 y'=f(x)$$
$$y(0)=y'(0)=0$$

I've used the fundamental Calculus theorem, but i can't get the request 'cause
$F'(x)=\dfrac{1}{a}f(x)\sin(a(x-x))(x')-\dfrac{1}{a}f(0)\sin(a(x-0))(0')=0$ ??
Anyone can help me? I've tried with integration by parts but i can't get the result too

A: Hint: $$F'(x) = \frac{1}{a} \int_0^x a f(t) \cos (a (x-t)) \, dt$$
$$F''(x) = \frac{1}{a} \int_0^x -a^2 f(t) \sin (a (x-t)) \, dt+a f(x) $$