text:
Q: Why it is bad Idea to embed Widget into Qml based applicaiton I have to reuse the Widget application in the Qml based application with latest Qt version (Qt 5.2). But as per most of the people its is very bad idea to do so.
Can someone explain, why it is bad idea?
Some of the code snippet,
*.h
class MyAppItem: public QQuickPaintedItem{
    Q_OBJECT
public:

    explicit MyAppItem(QQuickItem *parent = 0);
    void paint(QPainter *painter);
private:

    CMyAppWidget *bp;
};

class RouteBWExtensionPlugin: public QQmlExtensionPlugin
{
  Q_OBJECT
  Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface")

public:

  /**
  * @brief                register the plugin
  * @param[in]  uri to be registered
  */
  void registerTypes(const char * uri);
};

*.cpp
MyAppItem::MyAppItem(QQuickItem *parent)
    : QQuickPaintedItem(parent)
{
    bp = new CMyAppWidget();
}

void MyAppItem::paint(QPainter *painter)
{
    bp->render(painter);
}

void RouteBWExtensionPlugin::registerTypes(const char * uri)
{
  qmlRegisterType<MyAppItem>(uri, 1, 0, "MyAppItem");
}

*.qml file
import MyAppWidget 1.0
Item {
    width: 300
    height: 10
    anchors.right: parent
    MyAppItem {
        width: 94
        height: 240
        anchors.right: parent
        MouseArea{
            anchors.fill: parent
            onClicked: {
                console.log("[veo] onClicked - capture triggered")
            }
        }
    }
}

A: Because you do not want to add a dependency on 3d rendering when you don't need to. 3d rendering can cause massive amount of trouble, which you might be able to avoid in a Qt Widgets application without Qt Quick.
If you are planning to develop a Qt Quick application it is likely that at some point you need stuff from Qt Widgets. This applies for example when you need proper file dialogs, tray icons or just want to get native system colors which you have in a Qt Widgets QApplication but not in Qt Quick's QGuiApplication. So I'd argue against Micht's point Unnecessary dependency to Qt Widgets based on my own experience.
So for new Qt Quick applications using existing QWidgets I think this is a nice intermediate step.

A: That's interesting, I didn't know that you could do that!
Here are some reasons that I can think of:

*

*Unnecessary memory overhead for storing and constructing each QWidget instance (this includes any signal/slot connections the widgets might make).

*Running through the QWidget::render() code path unnecessarily. I haven't looked into how complex this is, but it's something to consider.

*Unnecessary dependency to Qt Widgets.

*Loss of interaction (mouse, keyboard, touch, etc.), assuming that the widget had any in the first place.

These all assume that you don't need the widget dependency for other things. If you do need it elsewhere within the same application for some reason, it doesn't sound so crazy (feels weird writing this...). I'd actually be very interested in hearing reasons why this is a bad idea myself.
So, the question is, why can't you just move the painting commands out of the widget and directly into your QQuickPaintedItem::paint() implementation? Do you need widgets within your Qt Quick application for other things? If so, what?


text:
Q: Multi target framework issue -> Found conflicts between different versions of "System.Runtime" that could not be resolved I have a Visual Studio 2022 solution that is based on netcore 3.1 (some dll, some WPF apps) that is working properly . I decided to try to make it target also net48 to be able in some particular cases to use some third party API currently not compatible with netcore.
I changed my projects to files with the following line
 <TargetFrameworks>netcoreapp3.1;net48</TargetFrameworks>

I changed all the c#8 code parts.
And I put one application for test in net48 to see if everything goes ok.
When I launch my application, it crashes instantly complaining about System.Runtime version 4.2.2.0 not being found.
FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified

If I look in the output log of the build I have some warning about conflicts in resolution of System.Runtime (4.1.2.0 vs 4.2.2.0)
For exemple :
Severity    Code    Description Project File    Line    Suppression State
Warning MSB3277 Found conflicts between different versions of "System.Runtime" that could not be resolved.
There was a conflict between "System.Runtime, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" and "System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".
    "System.Runtime, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" was chosen because it was primary and "System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" was not.
    References which depend on "System.Runtime, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" [C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.8\Facades\System.Runtime.dll].
        C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.8\Facades\System.Runtime.dll
          Project file item includes which caused reference "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.8\Facades\System.Runtime.dll".
            System.Runtime
    References which depend on "System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" [].
        C:\Users\alex\.nuget\packages\system.io.pipelines\4.5.1\ref\netstandard1.3\System.IO.Pipelines.dll
          Project file item includes which caused reference "C:\Users\alex\.nuget\packages\system.io.pipelines\4.5.1\ref\netstandard1.3\System.IO.Pipelines.dll".
            C:\Users\alex\.nuget\packages\system.io.pipelines\4.5.1\ref\netstandard1.3\System.IO.Pipelines.dll
            C:\Users\alex\.nuget\packages\fubardev.ftpserver\3.1.2\lib\net47\FubarDev.FtpServer.dll
            C:\Dev\csharp\Demo1\InfrastructureCore\bin\Debug\net48\InfrastructureCore.dll
            C:\Dev\csharp\Demo1\InfrastructureAutomation\bin\Debug\net48\InfrastructureAutomation.dll
            C:\Dev\csharp\Demo1\InfrastructureVision\bin\Debug\net48\InfrastructureVision.dll
            C:\Dev\csharp\Demo1\ModuleBase\bin\Debug\net48\ModuleBase.dll
            C:\Dev\csharp\Demo1\ModuleDefinitionsManagement\bin\Debug\net48\ModuleDefinitionsManagement.dll
            C:\Dev\csharp\Demo1\ModuleLogger\bin\Debug\net48\ModuleLogger.dll
            C:\Dev\csharp\Demo1\ModuleLogin\bin\Debug\net48\ModuleLogin.dll
            C:\Dev\csharp\Demo1\ModuleNavigation\bin\Debug\net48\ModuleNavigation.dll
            C:\Dev\csharp\Demo1\BaseClassesFw\bin\Debug\net48\BaseClassesFw.dll
        C:\Dev\csharp\Demo1\InfrastructureCore\bin\Debug\net48\Syncfusion.Themes.MaterialDarkFW.WPF.dll
          Project file item includes which caused reference "C:\Dev\csharp\Demo1\InfrastructureCore\bin\Debug\net48\Syncfusion.Themes.MaterialDarkFW.WPF.dll".
            C:\Dev\csharp\Demo1\InfrastructureCore\bin\Debug\net48\InfrastructureCore.dll
            C:\Dev\csharp\Demo1\InfrastructureAutomation\bin\Debug\net48\InfrastructureAutomation.dll
            C:\Dev\csharp\Demo1\InfrastructureVision\bin\Debug\net48\InfrastructureVision.dll
            C:\Dev\csharp\Demo1\ModuleBase\bin\Debug\net48\ModuleBase.dll
            C:\Dev\csharp\Demo1\ModuleDefinitionsManagement\bin\Debug\net48\ModuleDefinitionsManagement.dll
            C:\Dev\csharp\Demo1\ModuleLogger\bin\Debug\net48\ModuleLogger.dll
            C:\Dev\csharp\Demo1\ModuleLogin\bin\Debug\net48\ModuleLogin.dll
            C:\Dev\csharp\Demo1\ModuleNavigation\bin\Debug\net48\ModuleNavigation.dll
            C:\Dev\csharp\Demo1\BaseClassesFw\bin\Debug\net48\BaseClassesFw.dll
        C:\Dev\csharp\Demo1\InfrastructureCore\bin\Debug\net48\Syncfusion.Themes.MaterialLightFW.WPF.dll
          Project file item includes which caused reference "C:\Dev\csharp\Demo1\InfrastructureCore\bin\Debug\net48\Syncfusion.Themes.MaterialLightFW.WPF.dll".
            C:\Dev\csharp\Demo1\InfrastructureCore\bin\Debug\net48\InfrastructureCore.dll
            C:\Dev\csharp\Demo1\InfrastructureAutomation\bin\Debug\net48\InfrastructureAutomation.dll
            C:\Dev\csharp\Demo1\InfrastructureVision\bin\Debug\net48\InfrastructureVision.dll
            C:\Dev\csharp\Demo1\ModuleBase\bin\Debug\net48\ModuleBase.dll
            C:\Dev\csharp\Demo1\ModuleDefinitionsManagement\bin\Debug\net48\ModuleDefinitionsManagement.dll
            C:\Dev\csharp\Demo1\ModuleLogger\bin\Debug\net48\ModuleLogger.dll
            C:\Dev\csharp\Demo1\ModuleLogin\bin\Debug\net48\ModuleLogin.dll
            C:\Dev\csharp\Demo1\ModuleNavigation\bin\Debug\net48\ModuleNavigation.dll
            C:\Dev\csharp\Demo1\BaseClassesFw\bin\Debug\net48\BaseClassesFw.dll BaseClasses C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\amd64\Microsoft.Common.CurrentVersion.targets   2302

After doing some research I have tried :

*

*To install a more recent version of System.Runtime nuget package in all my projects ( I cannot found System.Runtime 4.2.2.0 by the way)

*To modify the app.config of my test app with some binding redirection

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
              <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
              <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="4.1.2.0"/>
        </dependentAssembly>
</assemblyBinding>

*

*To play with the AutoGenerateBindingRedirects option

But the error is still the same. Note that if I roll back the test app to netcore everything is working fine.
Do I need to try to find another version of the packages that gives the warning (and hope that I can find one that fits) or is there another way to "force" my app to use a given version ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't add CSS on ERB file, Sinatra I'm trying to add Twitter Bootstrap CSS to an ERB file and run with Sinatra, but CSS don't show up.
My code:
<link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css">

my folder structure is the same in the code.
I've already tried href="lib/... and href="../lib/... and don't work
Any solution?

A: You should copy bootstrap.min.css in your Sinatra public directory. Then use:
<link rel="stylesheet" href="/bootstrap.min.css">

to include it in your page.


text:
Q: Creating personalised heat maps with added demarcation line I am wanting to create my own heat map, I am currently using the binary heat map, e.g.:
axScatter_top.hexbin(data_controlsample['log_NII_Ha'],
           data_controlsample['log_OIII_Hb'], bins='log', cmap=plt.cm.binary)

I was wondering if we were able to create our own cmaps ready for matplotlib, I would specifically like to create a heat map with the follow hex colour codes:
FF0088, FF0099, FF00AA and 660088, 660099, 6600AA
I would also like to have the distinct colour change either side of a demarcation line which is specified by:
NII   = np.linspace(-3.0, 0.35)

def log_OIII_Hb_NII(log_NII_Ha, eps=0):
     return 1.19 + eps + 0.61 / (log_NII_Ha - eps - 0.47)

axScatter_top.plot(NII, log_OIII_Hb_NII(NII), '-k')

So essentially to the upper right of this demarcation line I would like the hex colours 660088, 660099, 6600AA and to the lower left of it I would like FF0088, FF0099, FF00AA.


text:
Q: User-defined setting in Storyboard I have a LaunchScreen.storyboard that has an Image View and will display an image whenever the app is launched. However, I have a different launch image for each Scheme that I define in the project. I have defined a user-defined setting that holds a different image asset for every scheme. My question is, how do I make use of this setting in the storyboard?

A: I've also been looking for this feature for a long time but I don't think Asset Catalog supports it. Out of the box, Asset Catalog only supports changing the App Icon and Launch Images (not Launch Storyboard) based on build configuration. See attached:


text:
Q: Problem when attaching a Custom Validator to a control dynamicly Anyone have an idea why this code doesnt work?

Book:

            <telerik:RadComboBox ID="RadComboBoxBook" runat="server" OnClientFocus="AttachValidator">
            </telerik:RadComboBox>

Desk:

                <telerik:RadComboBox ID="RadComboBoxDesk" runat="server" OnClientFocus="AttachValidator">
                </telerik:RadComboBox>

<asp:CustomValidator ID="CustomValidatorDeskBook" runat="server"
            ErrorMessage="Error"
            ClientValidationFunction="BookDeskValidation" ForeColor="Red">*</asp:CustomValidator>

The OnClientFocus is fire but it then the custom validator doesnt seem to be attached because no validation is done when I exit the control on which the validator should be attached.
Thank you!

A: Ok I managed to get this work. Here`s what I did. If anyone knows a better way to do it or if what I did to solve the problem is not right please let me know!
So here's what I did:

Book:

      <telerik:RadComboBox ID="RadComboBoxBook" runat="server" OnClientFocus="AttachValidator" OnClientDropDownClosed="EnableValidator">
      </telerik:RadComboBox>

So basicly I got rid of the ValidatorHookupControl function and replaced it with ValidatorEnable on the event OnClientDropDownClosed


text:
Q: How To Add DATEDIFF & Update Tables? Currently I'm practising with DATEDIFF. Here are the details:
Table DB1: id, update_time, expire_time, total_diff
Table DB2: id, username
SELECT  db2.ID AS ID,
        updatetime.update_time AS Latest_Payment,
        expiretime.expire_time AS Payment_Till
FROM    db2
INNER JOIN db1 ON db2.ID = db1.user_id
LEFT JOIN db1 updatetime ON db2.ID = updatetime.user_id AND updatetime.update_time
LEFT JOIN db1 expiretime ON db2.ID = expiretime.user_id AND expiretime.expire_time
WHERE db2.id >= '0' AND expiretime.expire_time < NOW()
GROUP BY db2.ID;

I'm trying to add DATEDIFF(month, CURRENT_TIMESTAMP, updatetime.update_time) to the code above but got no luck.
What I'm trying to do is to display a table that contain :
1. Latest Payment
2. Payment Till
3. Total Diff (How many months payment due)*$80

At this moment I am only able to display 'Latest Payment' and 'Payment Till'. May I know how can I add the DATEDIFF and it will display it in 1 table?
Sample of data/ table that i try to achive:
Name     | Latest Payment (updatetime) | Subscribe Till (expiretime) | Month Due X $80

Arby     | 21/3/2020                   | 21/4/2020      | 80

Casi     | 21/2/2020                   | 21/5/2020      | 0

Will     | 21/2/2020                   | 21/4/2020      | 160

Really appreciate your help.


text:
Q: Changing video resolution in n95 with J2ME We've tried using the parameters in the capture url as documented:
capture://video?height=480&width=360
No combination of width and height works. We always get an error -6 when creating the player.
capture://video works fine but the videos are ridiculously small.
Is it possible to record at a higher resolution on the N95?

A: -6 is the following Symbian C++ error code : KErrArgument An argument is out of range.
At Least, it makes sense.
You can probably find your answer in the Nokia JavaME developer library:
http://www.forum.nokia.com/Resources_and_Information/Documentation/Java/
something like
"Note: S60 3rd Ed. FP2: All FP2 products support QCIF (176x144) resolution. Other resolutions – e.g. CIF (352x288), QVGA (320x240) and VGA (640x480) – may be supported in some devices. "
gives you a few specific values to try.
Note that you may need to specify an encoding like "video/3gp" in you capture url.


text:
Q: How to disable fake SSL check in development phase for Opera 17+ and Chrom 30+ During the test, we are configuring our web server(Tomcat) to be connected to with test SSL
When we try to connect to this site with IE, we face this error:
There is a problem with this website's security certificate

The security certificate presented by this website was not issued by a trusted certificate authority..
.............

..............
But At the end the we have an option which mentions:
Continue to this website (not recommended).

So we can continue to view our site.
Something same happens when we use Firefox.
But when I visit my site in Opera I got this error, and I can not go on:
Invalid Server Certificate

You attempted to reach localhost, but the server presented an invalid certificate.

Any comments!! How can I disable this. I see some related posts but non of them helped!


text:
Q: There is a better way to write this sql query (union)? I want to know if there is a better way to write this sql query, in terms of performance and stability.
Because, I think I'm repeating the code many times and maybe I can do it with the CASE clause or another one.
SELECT x.Fecha,x.IdTrabajador,Cast(x.Cantidad AS DECIMAL(18, 2)) AS Cantidad,x.Motivo,x.IdTrabajadorIncidencia
    FROM   (SELECT I.IdTrabajador,I.Fecha,
                Datediff(second, I.HoraIngreso, (SELECT HD.HoraInicio
                    FROM   [rrhh].TrabajadorHorarioDetalle HD
                            INNER JOIN [rrhh].TrabajadorHorario H
                                    ON HD.IdTrabajadorHorario = H.IdTrabajadorHorario
                    WHERE  H.Estado = 1
                            AND HD.Estado = 1
                            AND HD.Dia = Datename(dw, I.Fecha)
                            AND H.IdTrabajador = I.IdTrabajador)) / 3600.0 AS Cantidad,
                'Sobretiempo en hora de ingreso...' AS Motivo,I.IdTrabajadorIncidencia
            FROM   [rrhh].TrabajadorIncidencia I
            WHERE  I.Estado = 1
                   AND I.IdIncidencia = 1) AS x
    WHERE  x.Cantidad > 0.00
    UNION
    SELECT x.Fecha,x.IdTrabajador,Cast(x.Cantidad AS DECIMAL(18, 2)) AS Cantidad,x.Motivo,x.IdTrabajadorIncidencia
    FROM   (SELECT I.IdTrabajador,I.Fecha,
                Datediff(second, (SELECT HD.HoraInicioRefrigerio
                    FROM   [rrhh].TrabajadorHorarioDetalle HD
                            INNER JOIN [rrhh].TrabajadorHorario H
                                    ON HD.IdTrabajadorHorario = H.IdTrabajadorHorario
                    WHERE  H.Estado = 1
                            AND HD.Estado = 1
                            AND HD.Dia = Datename(dw, I.Fecha)
                            AND H.IdTrabajador = I.IdTrabajador), I.HoraInicioRefrigerio) / 3600.0 AS Cantidad,
                'Sobretiempo en hora de inicio de refrigerio...' AS Motivo,I.IdTrabajadorIncidencia
            FROM   [rrhh].TrabajadorIncidencia I
            WHERE  I.Estado = 1
                   AND I.IdIncidencia = 1) AS x
    WHERE  x.Cantidad > 0.00
    UNION
    SELECT x.Fecha,x.IdTrabajador,Cast(x.Cantidad AS DECIMAL(18, 2)) AS Cantidad,x.Motivo,x.IdTrabajadorIncidencia
    FROM   (SELECT I.IdTrabajador,I.Fecha,
                Datediff(second, I.HoraFinRefrigerio, (SELECT HD.HoraFinRefrigerio
                    FROM   [rrhh].TrabajadorHorarioDetalle HD
                        INNER JOIN [rrhh].TrabajadorHorario H
                                ON HD.IdTrabajadorHorario = H.IdTrabajadorHorario
                    WHERE  H.Estado = 1
                        AND HD.Estado = 1
                        AND HD.Dia = Datename(dw, I.Fecha)
                        AND H.IdTrabajador = I.IdTrabajador)) / 3600.0 AS Cantidad,
                'Sobretiempo en hora de término de refrigerio...' AS Motivo,I.IdTrabajadorIncidencia
            FROM   [rrhh].TrabajadorIncidencia I
            WHERE  I.Estado = 1
                   AND I.IdIncidencia = 1) AS x
    WHERE  x.Cantidad > 0.00
    UNION
    SELECT x.Fecha,x.IdTrabajador,Cast(x.Cantidad AS DECIMAL(18, 2)) AS Cantidad,x.Motivo,x.IdTrabajadorIncidencia
    FROM   (SELECT I.IdTrabajador,I.Fecha,
                Datediff(second, (SELECT HD.HoraFin
                    FROM   [rrhh].TrabajadorHorarioDetalle HD
                            INNER JOIN [rrhh].TrabajadorHorario H
                                    ON HD.IdTrabajadorHorario = H.IdTrabajadorHorario
                    WHERE  H.Estado = 1
                            AND HD.Estado = 1
                            AND HD.Dia = Datename(dw, I.Fecha)
                            AND H.IdTrabajador = I.IdTrabajador), I.HoraSalida) / 3600.0 AS Cantidad,
                'Sobretiempo en hora de salida...' AS Motivo,I.IdTrabajadorIncidencia
            FROM   [rrhh].TrabajadorIncidencia I
            WHERE  I.Estado = 1
                   AND I.IdIncidencia = 1) AS x
    WHERE  x.Cantidad > 0.00
    UNION
    --Search Horas Extras (HE25 y HE35) in table TrabajadorIncidencia
    SELECT x.Fecha,x.IdTrabajador,Cast(x.Cantidad AS DECIMAL(18, 2)) AS Cantidad,x.Motivo,x.IdTrabajadorIncidencia
    FROM   (SELECT I.IdTrabajador,I.Fecha,Datediff(second, I.HoraIngreso, I.HoraSalida) / 3600.0 AS Cantidad,'Sobretiempo en hora extra registrada...' AS Motivo,I.IdTrabajadorIncidencia
            FROM   [rrhh].TrabajadorIncidencia I
            WHERE  I.Estado = 1
                   AND ( I.IdIncidencia = 2
                          OR I.IdIncidencia = 4 )) AS x
    WHERE  x.Cantidad > 0.00
    ORDER  BY x.Fecha;

The previous sql query works fine, but maybe it could be better.
Thanks.

A: You can use Common Table Expressions (CTEs) to break the problem down.  In the example below I broke the problem down into its various parts.  I think the end result is much easier to follow.
Don't think that the CTEs will create any additional processing.  I am often amazed how the efficiently SQL Server's query planner uses them.
A few caveats:
There is a chance the results might be different because the SELECTs in the DATEDIFF function were removed and replaced with a JOIN.  I'm going to assume you had a one to one relationship with the given predicates or you would've been getting errors.  Also I probably made a mistake in the cutting and pasting, so don't be surprised if this doesn't run.
WITH TrabajadorIncidenciaDetalleCte AS (
    SELECT I.*, HD.HoraInicio, HD.HoraFinRefrigerio, HD.HoraFin
    FROM [rrhh].TrabajadorIncidencia I
    INNER JOIN [rrhh].TrabajadorHorarioDetalle HD ON HD.Dia = DATENAME(dw, I.Fecha)
    INNER JOIN [rrhh].TrabajadorHorario H ON HD.IdTrabajadorHorario = H.IdTrabajadorHorario AND H.IdTrabajador = I.IdTrabajador
    WHERE  H.Estado = 1 AND HD.Estado = 1 AND I.Estado = 1 AND I.IdIncidencia = 1
)
, IncidenciaCte AS (
    SELECT IdTrabajador,Fecha, DATEDIFF(second, HoraIngreso, HoraInicio) AS Cantidad,
        'Sobretiempo en hora de ingreso...' AS Motivo, IdTrabajadorIncidencia
    FROM TrabajadorIncidenciaDetalleCte
    UNION ALL
    SELECT IdTrabajador,Fecha, DATEDIFF(second, HoraInicioRefrigerio, HoraFinRefrigerio) AS Cantidad,
        'Sobretiempo en hora de término de refrigerio...' AS Motivo, IdTrabajadorIncidencia
    FROM TrabajadorIncidenciaDetalleCte
    UNION ALL
    SELECT IdTrabajador,Fecha, DATEDIFF(second, HoraFin, HoraSalida) AS Cantidad,
        'Sobretiempo en hora de salida...' AS Motivo, IdTrabajadorIncidencia
    FROM TrabajadorIncidenciaDetalleCte
    UNION ALL
    SELECT IdTrabajador, Fecha, DATEDIFF(second, HoraIngreso, HoraSalida) AS Cantidad,
        'Sobretiempo en hora extra registrada...' AS Motivo, IdTrabajadorIncidencia
    FROM [rrhh].TrabajadorIncidencia
    WHERE Estado = 1 AND ( IdIncidencia = 2 OR IdIncidencia = 4 )
)
SELECT x.Fecha, x.IdTrabajador,
    CAST((x.Cantidad / 3600.0) AS DECIMAL(18, 2)) AS Cantidad,
    x.Motivo, x.IdTrabajadorIncidencia
FROM IncidenciaCte x
WHERE x.Cantidad > 0.00
ORDER BY x.Fecha;

A: The WHERE  x.Cantidad > 0.00 means that you eliminate any results where the subquery didn't match any rows and returns NULL.
Your current query will fail with an error if the subquery returns more than one row. If you are happy to go without the error in that eventuality then you can use an INNER JOIN instead of 4 similar subqueries, and then CROSS APPLY ... VALUES to unpivot the four joined column values into rows. Then UNION that onto the final branch.
SELECT I.Fecha,
       I.IdTrabajador,
       CAST(x.Cantidad / 3600.0 AS DECIMAL(18, 2)) AS Cantidad,
       x.Motivo,
       I.IdTrabajadorIncidencia
FROM   [rrhh].TrabajadorIncidencia I
       INNER JOIN [rrhh].TrabajadorHorario H
               ON H.IdTrabajador = I.IdTrabajador
                  AND H.Estado = I.Estado
       INNER JOIN [rrhh].TrabajadorHorarioDetalle HD
               ON HD.IdTrabajadorHorario = H.IdTrabajadorHorario
                  AND HD.Estado = H.Estado
       CROSS APPLY ( VALUES (DATEDIFF(second, I.HoraIngreso, HD.HoraInicio), 'Sobretiempo en hora de ingreso...'),
                            (DATEDIFF(second, HD.HoraFinRefrigerio, I.HoraInicioRefrigerio), 'Sobretiempo en hora de inicio de refrigerio...'),
                            (DATEDIFF(second, I.HoraFinRefrigerio, HD.HoraFinRefrigerio), 'Sobretiempo en hora de término de refrigerio...'),
                            (DATEDIFF(second, HD.HoraFin, I.HoraSalida), 'Sobretiempo en hora de salida...') ) x(Cantidad, Motivo)
WHERE  x.Cantidad > 0
       AND I.Estado = 1
       AND I.IdIncidencia = 1
       AND HD.Dia = DATENAME(dw, I.Fecha)
UNION
--Search Horas Extras (HE25 y HE35) in table TrabajadorIncidencia
SELECT x.Fecha,
       x.IdTrabajador,
       CAST(x.Cantidad AS DECIMAL(18, 2)) AS Cantidad,
       x.Motivo,
       x.IdTrabajadorIncidencia
FROM   (SELECT I.IdTrabajador,
               I.Fecha,
               DATEDIFF(second, I.HoraIngreso, I.HoraSalida) / 3600.0 AS Cantidad,
               'Sobretiempo en hora extra registrada...'              AS Motivo,
               I.IdTrabajadorIncidencia
        FROM   [rrhh].TrabajadorIncidencia I
        WHERE  I.Estado = 1
               AND ( I.IdIncidencia = 2
                      OR I.IdIncidencia = 4 )) AS x
WHERE  x.Cantidad > 0.00
ORDER  BY Fecha;


text:
Q: Get auth parameters in Laravel login I want unique url for every user when he log in.
routes.php
Route::get('/', 'HomeController@index');
Route::get('USERNAME', 'HomeController@index'); // <--- this part
Route::get('about', 'PagesController@about');
Route::get('contact', 'PagesController@contact');

Route::pattern('id', '[0-9]+');
Route::get('news/{id}', 'ArticlesController@show');
Route::get('video/{id}', 'VideoController@show');
Route::get('photo/{id}', 'PhotoController@show');

Route::controllers([
    'auth' => 'Auth\AuthController',
    'password' => 'Auth\PasswordController',
]);

if (Request::is('admin/*'))
{
    require __DIR__.'/admin_routes.php';
}

AuthControler.php
protected $redirectTo = 'USERNAME'; // <--- this part

/**
 * Create a new authentication controller instance.
 *
 * @param  \Illuminate\Contracts\Auth\Guard  $auth
 * @param  \Illuminate\Contracts\Auth\Registrar  $registrar
 * @return void
 */
public function __construct(Guard $auth, Registrar $registrar)
{
    $this->auth = $auth;
    $this->registrar = $registrar;

    $this->middleware('guest', ['except' => 'getLogout']);
}

I want when user log in to have url like www.somesite.com/USERNAME

A: You can do it like this:
Route::get('/', 'HomeController@index');
Route::get('about', 'PagesController@about');
Route::get('contact', 'PagesController@contact');

Route::pattern('id', '[0-9]+');
Route::get('news/{id}', 'ArticlesController@show');
Route::get('video/{id}', 'VideoController@show');
Route::get('photo/{id}', 'PhotoController@show');

Route::controllers([
    'auth' => 'Auth\AuthController',
    'password' => 'Auth\PasswordController',
]);

Route::get('{username}', 'HomeController@index'); // <--- this part

if (Request::is('admin/*'))
{
    require __DIR__.'/admin_routes.php';
}

You want that if there are no matched routes use the HomeController@index. With this code you can do that. However this isn't the best option in my opinion. What if a person has a username 'about'. Then he is redirected to the about page. I suggest doing something like this:
Route::get('users/{username}', 'HomeController@user');

In you're homecontroller you can do this:
public function user($username)
{
    //$username contains the username
    //or something Auth::user()->username gives you the username
}


text:
Q: Mapping DataFrame column with other DataFrame I have a CSV file with players history ranks since the beginning of 2010 up to 2018. the ranking is refreshing each week so there are 54 x 8 rankings in one file. There are columns like date, rank position, player id and points. Player id is a specific number individual for each player. I do have a second csv with player id, player name, player surname. I want to map player id in the first data frame with name and surname of a player form the second csv.
I have just creat dict form second csv with  <to_dict> I was trying to map this with <.map(dict1)> and with <from_dict> but without success.
data_players = pd.read_csv(filepath, engine="python", sep=";",
keep_default_na=False)
data_rank = pd.read_csv(filepath2, engine="python", sep=",",
keep_default_na=False)

data_players = data_players.set_index('player_id')
dict1 = data_players.to_dict('index')
data_rank['player'] = pd.DataFrame.from_dict(dict1)

My data looks like this
ranking_date     int64
rank             int64
points          object
player          object
dtype: object

        ranking_date  rank points                      player
player
103819      20100104     1  10550    {'name_list': 'Federer'}
104745      20100104     2   9205      {'name_list': 'Nadal'}
104925      20100104     3   8310   {'name_list': 'Djokovic'}
104918      20100104     4   7030     {'name_list': 'Murray'}
105223      20100104     5   6785  {'name_list': 'Del Potro'}

I expect to find the solution for this, I think that this is simple but I am just learning python.

A: Dont use dict, use here
Df= data_players.merge(data_rank,left_on="player_id", right_on="player_id")


text:
Q: Flask with dash app, why WGSI can't import modules? I'm trying to add dash instance to a flask app, but struggle with WGSI import.
WGSI doesn't want to import the dash module while it's installed and works well when I run directly the file Flask_app.py.
The /var/www/pythonanywhere_com_wsgi.py
import sys

# add your project directory to the sys.path
project_home = '/home/mysite'
if project_home not in sys.path:
    sys.path = [project_home] + sys.path

# import flask app but need to call it "application" for WSGI to work
from flask_app import app as application  # noqa

The /home/mysite/flask_app.py
from flask import Flask, render_template
import dash

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello from Flask!

# Set-up endpoint 1
app_1 = dash.Dash(name='app1', server=app, url_base_pathname='/app1/')
app_1.layout = html.H1('App 1')

The error:
Error running WSGI application
2021-12-14 16:16:26,591: ModuleNotFoundError: No module named 'dash'
2021-12-14 16:16:26,591:   File "/var/www/pythonanywhere_com_wsgi.py", line 16, in <module>
2021-12-14 16:16:26,591:     from flask_app import app as application  # noqa
2021-12-14 16:16:26,591:
2021-12-14 16:16:26,592:   File "/home/mysite/flask_app.py", line 5, in <module>
2021-12-14 16:16:26,592:     import dash
2021-12-14 16:16:26,592: ***************************************************
2021-12-14 16:16:26,592: If you're seeing an import error and don't know why,
2021-12-14 16:16:26,592: we have a dedicated help page to help you debug:
2021-12-14 16:16:26,592: https://help.pythonanywhere.com/pages/DebuggingImportError/
2021-12-14 16:16:26,592: ***************************************************

EDIT: In fact it seems WGSI won't import any module, tried with pandas:
2021-12-14 16:47:51,730: Error running WSGI application
2021-12-14 16:47:51,734: ModuleNotFoundError: No module named 'pandas'
2021-12-14 16:47:51,734:   File "/var/www/pythonanywhere_com_wsgi.py", line 17, in <module>
2021-12-14 16:47:51,734:     from flask_app import app as application  # noqa
2021-12-14 16:47:51,734:
2021-12-14 16:47:51,735:   File "/home/mysite/flask_app.py", line 5, in <module>
2021-12-14 16:47:51,735:     import pandas
2021-12-14 16:47:51,735: ***************************************************
2021-12-14 16:47:51,735: If you're seeing an import error and don't know why,
2021-12-14 16:47:51,735: we have a dedicated help page to help you debug:
2021-12-14 16:47:51,735: https://help.pythonanywhere.com/pages/DebuggingImportError/
2021-12-14 16:47:51,735: ***************************************************

A: I think what's happening is that you don't have an environment active when running the app that has dash and pandas installed.
You might have dash and pandas installed in an environment inside /home/mysite, but that doesn't mean when your execute flask run inside /var/www it automatically import those dependencies from your other environment.
I was able to get your code running by installing dash and pandas in an environment inside the folder pythonanywhere_com_wsgi.py is in.

A: I was in the wrong environment, after installing all dependencies in the right on it works! Thanks


text:
Q: I know that an atomic value in relational database means that it's a value which can't be divided further Can you give examples of an atomic value and a non atomic value in the context of relational database?

A: The concept of atomicity is extremely hard to pin down precisely.
So much so that the concept itself has been pretty much totally abandoned in modern relational database theory.
Google for "What first normal form really means", and related material.
Also you might spend some time pondering the following two cases :
A set, is that a "further divisible" thing, typically because there are "obviously" members in the set that you "can take out of the set and put them back in" or some such ?  Well, no, it isn't !  If you take a member out of a set it is no longer the same set.
An integer number, is that a "further decomposable" thing ?  Well yes it is !  It can be "decomposed" in the distinct powers of two of which it is the sum !
The concept of atomicity has no real absolute meaning in database theory.


text:
Q: Program received signal SIGABRT when presses Info Button on the application when you receive this message Program received signal SIGABRT while pressing Info button on the application. Then how to figure out what is wrong and exactly where code is wrong.
Thanks for help.

A: Set an exception breakpoint,.
See this SO answer for a graphic illustration.
You might set a breakpoint in the UIApplication delegate methods:
- (void)applicationWillResignActive:(UIApplication *)application

or
- (void)applicationWillTerminate:(UIApplication *)application


text:
Q: .NET Core - AWS KMS - EncryptionMaterials issue I have been trying to use the KMS manager to encrypt and store some sensitive information in an S3 Bucket. I found plenty of examples on how to do this, the most  significant being the one in AWS Documentation (https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/kms-keys-s3-encryption.html)
using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;

using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Encryption;
using Amazon.KeyManagementService;
using Amazon.KeyManagementService.Model;

namespace S3Sample1
{
    class S3Sample
    {
        public static void Main(string[] args)
        {
            string kmsKeyID = null;
            using (var kmsClient = new AmazonKeyManagementServiceClient())
            {
                var response = kmsClient.CreateKey(new CreateKeyRequest());
                kmsKeyID = response.KeyMetadata.KeyId;

                var keyMetadata = response.KeyMetadata; // An object that contains information about the CMK created by this operation.
                var bucketName = "<s3bucket>";
                var objectKey = "key";

                var kmsEncryptionMaterials = new EncryptionMaterials(kmsKeyID);
                // CryptoStorageMode.ObjectMetadata is required for KMS EncryptionMaterials
                var config = new AmazonS3CryptoConfiguration()
                {
                    StorageMode = CryptoStorageMode.ObjectMetadata
                };

                using (var s3Client = new AmazonS3EncryptionClient(config, kmsEncryptionMaterials))
                {
                    // encrypt and put object
                    var putRequest = new PutObjectRequest
                    {
                        BucketName = bucketName,
                        Key = objectKey,
                        ContentBody = "object content"
                    };
                    s3Client.PutObject(putRequest);

                    // get object and decrypt
                    var getRequest = new GetObjectRequest
                    {
                        BucketName = bucketName,
                        Key = objectKey
                    };

                    using (var getResponse = s3Client.GetObject(getRequest))
                    using (var stream = getResponse.ResponseStream)
                    using (var reader = new StreamReader(stream))
                    {
                        Console.WriteLine(reader.ReadToEnd());
                    }
                }
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }

    }

}

This code as is does not work, even if I use the Full framework (to use the example above in .NET Core I had to make all aws calls async as per their documentation) version because
var kmsEncryptionMaterials = new EncryptionMaterials(kmsKeyID);

Does not accept a string but either a AsymmetricKey or SymmetricKey Object. I went around it by
var kmsEncryptionMaterials = new EncryptionMaterials(RSA.Create())

Obviously this would be a per session key, so I actually found this article https://aws.amazon.com/blogs/developer/client-side-data-encryption-with-aws-sdk-for-net-and-amazon-s3/, that basically details how to reuse a key this seems really outdated (created on 2013) and in my opinion defeats the point, of my usage as I initially wanted to use KMS as the actual authentication/authorization provider for all of our boxes in the aws ecosystem to then access the S3 bucket containing the secret key.
Am I missing something? Why does the AWS example has a string in it?
I am using the latest packages for AWS SDK .NET Core:

*

*AWSSDK.Core - v: 3.3.24.4

*AWSSDK.KeyManagementService - v: 3.3.6

*AWSSDK.S3 - v: 3.3.20

A: After almost a day or so with this problem I realised the issue was to do with multiple targets of the Amazon.S3.Encryption dll.
I found a github project that had the example correctly working against .net core (https://github.com/priyalwalpita/awssdk_dotnetcore) and from them it was very clear that the problem was with my cached dlls.
I've also triple checked by ItemGroups in the csproj and made sure they were correct
  <ItemGroup>
<PackageReference Include="AWSSDK.Core" Version="3.3.24.4" />
<PackageReference Include="AWSSDK.KeyManagementService" Version="3.3.6" />
<PackageReference Include="AWSSDK.S3" Version="3.3.20" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.1" />
  </ItemGroup>

Hopefully this might help somebody in the future


text:
Q: how to change npm install command in ElasticBeanstalk (Node)? I knew that the elastic beanstalk environments will execute the command npm --production install.
But, from https://github.com/npm/cli/issues/4027, npm v8 (Node 16) executes scripts even when doing npm --production install.
According to the npm documentation, it is supposed not to do prepare scripts when we give some arguments like --production. However, the npm v8 bug still exists so that prepare script will be executed when I deploy my Node.js application to ElasticBeanstalk.
So, I want to change ElasticBeanstalk's command npm --production install to npm install --production --ignore-scripts. Is there any way to accomplish this?

A: I believe you can create a .npmrc file then add:
ignore-scripts=true

https://docs.npmjs.com/cli/v7/configuring-npm/npmrc#files


text:
Q: Debug authorisation in R curl using NTLM I am trying to access a URL from a windows (sharepoint 2007) web server within a corporate network.  I'm using R and curl but can't seem to get the authorization part right. (There is no proxy or firewall between me and the web server, and I'm on a windows machine on the same domain)  This is what I've currently got;
library(SSOAP)
library(XML)
library(RCurl)

#This works fine for a page with no authroisation required
y = tryCatch(getURLContent("http://www.example.com/webpagewithnoauthroisation.html",
                verbose=TRUE,
                httpauth="ntlm", userpwd="DOMAIN/username:password"),
        HTTPError = function(e) {
            cat("HTTP error: ", e$message, "\n")
        })

#This fails for a page that needs authoisation
x = tryCatch(getURLContent("http://sharepoint.example.com/Pages/Default.aspx",
                verbose=TRUE,
                httpauth="ntlm", userpwd="DOMAIN/username:password"),
        HTTPError = function(e) {
            cat("HTTP error: ", e$message, "\n")
        })

> Error: Unauthorized

I'm a bit stumped how to debug this (on my Windows machine).  Any good suggestions on debugging (r) Curl authentication issues ?
Edit: I thought it would be NTLM, but have just read that it may something else (Kerberos ?).  The target web server is a Sharepoint 2007 server.


text:
Q: Orthogonal projection onto a vector with matrix transformation So I have this question here which says:
$a)$ Find the standard matrix of the linear operator $T:R^2\rightarrow R^2$ given by the orthogonal projection onto the vector $(1,-2)$.
$b)$ Given the linear transformation $T:R^2\rightarrow R^3$ such that
$$T(1,0)=(1,-2,3), T(1,1)=(0,1,4)$$
Find $T(2,3)$.
For part $a)$, I used my standard basis vectors to find the orthogonal projection. Thus, I went:
$T(e_1)=(1,0)-\frac{(1,0)\cdot(1,-2)}{\|(1,-2)\|}(1,-2)$
$=(\frac{4}{5},\frac{2}{5})$
Similarly, I get that $T(e_2)=(\frac{2}{5},\frac{1}{5})$
So thus, my standard matrix is:
$\left(
\begin{array}{cc}
\frac{4}{5} & \frac{2}{5}\\
\frac{2}{5} & \frac{1}{5} \\
    \end{array}
\right)
$
Apparently this isn't right. Why? Is there something I did wrong with my work?
For part $b)$, I know I need $T(1,0)$ and $T(0,1)$ however, I only know what $T(1,0)$ is. Can I find $T(0,1)$ by going $T(1,1)-T(1,0)$?
Some guidance would be appreciated. Thanks!

A: a) The projection of $v$ on the vector $w$ is $\displaystyle\frac{v.w}{\lVert w\rVert^2}w$. So, the projection of $(1,0)$ is $\displaystyle\left(\frac15,-\frac25\right)$ and the projection of $(0,1)$ is $\displaystyle\left(-\frac25,\frac45\right)$. So, the matrix is$$\begin{bmatrix}\frac15&-\frac25\\-\frac25&\frac45\end{bmatrix}.$$
b) Note that $(2,3)=3(1,1)-(1,0)$. Therefore, $T(2,3)=3T(1,1)-T(1,0)$.

A: The formula fir the orthogonal projection of $e_1$ along $(1,-2) $ as you have written is incorrect (a length should be squared, check).
In part two, since $T$ is linear,
$T (0,1)=T ((1,1)-(1,0))=T (1,1)-T (1,0)$.


text:
Q: Highcharts DateTime Localization Ukrainian Highcharts.setOptions({
    lang: {
        loading: 'Завантаження...',
        months: ['Січень', 'Лютий', 'Березень', 'Квітень', 'Травень', 'Червень', 'Липень', 'Серпень', 'Вереснь', 'Жовтень', 'Листопад', 'Грудень'],
        weekdays: ['Неділя', 'Понеділок', 'Вівторок', 'Середа', 'Четвер', 'П\'ятниця', 'Субота'],
        shortMonths: ['Січ', 'Лют', 'Бер', 'Кві', 'Тра', 'Чер', 'Лип', 'Сер', 'Вер', 'Жов', 'Лис', 'Гру'],
        exportButtonTitle: "Експорт",
        printButtonTitle: "Друкувати",
        rangeSelectorFrom: "З",
        rangeSelectorTo: "По",
        rangeSelectorZoom: "Період",
        downloadPNG: 'Скачати PNG',
        downloadJPEG: 'Скачати JPEG',
        downloadPDF: 'Скачати PDF',
        downloadSVG: 'Скачати SVG',
        printChart: 'Надрукувати графік'
    }
});

Ukrainian localization for Highcharts.
I searched, but could not find an answer. I hope this helps you.


text:
Q: Debug JavaScript in ASP.NET I needed to debug my javascript functions written in asp.net.
I am currently using chrome but its not going to the break point. If i put alert('Some message'). I can see message displayed.
If someone has any idea how to use debugger for JavaScript in ASP.NET please let me know.

A: To Debug in chrome you need to do two things

*

*Write debugger the place where you want to start debugging.

*Before the execution of script open developer tool (by pressing ctrl + shift + i)

Now when control of execution to statement where you wrote debugger the execution is paused for you to debug.
Here is an example for you to learn, Follow the instruction given in comments. How to debug in chrome

A: Try to debug your code with Internet Explorer, you can do it like this, place the debugger  keyword before the code you want debug.
   <script type="text/javascript">
    function s() {
   //enable the debugger feature.
        debugger;
        var alert = "this is a debugger test";
        alert(alert);
    }
   </script>

A: Visual Studio can only debug Javascript if it's attached to an instance of IE.
You should use Chrome's developer tools, which include a Javascript debugger.

A: From my experience Visual Studio can't debug Managed Code and JavaScript in the same time.
This mean that when you start an ASP.NET project in debug mode within Visual Studio, it will start web server, attach to it, then IE (or another browser) and attach to it. But JS breakpoint will not be hit.
But when you start a project without debug and attach to IE manually - those breakpoint will be hit.

A: Use FireBug!  It is great!  It gives you a little bit more power than traditional debugging.  http://getfirebug.com/errors

Status bar error indicator
On the right side of the Firefox browser's status bar you will see a
  little green icon. This is Firebug's way of telling you that
  everything is A-Ok. When that icon turns into a red "x", things aren't
  so peachy.
Click the "x" to open the Firebug error console which will show you
  all of the errors that have occurred on the page.
No error soup
Most browsers report errors by dumping them all into one big window
  that includes the problems with every web page you've ever visited.
  Firebug is kinder than that; it shows you only the errors for the page
  that you're looking at.
Jump to the debugger
Every error report has a link on its right side that points to the
  file and line number where the error occurred. Clicking this link will
  take you right to the Firebug JavaScript debugger or CSS inspector so
  that you can get started on solving the problem right away.
Some errors also include the actual snippet of source that contains
  the error, which is also a link to the original file.


text:
Q: SQL Server 2017 - How to capture JSON output from a stored procedure that contains a temp table I have a stored procedure in my SQL Server 2017 database which is used by a node.js API. This stored procedure does some calculations, then returns a json object using FOR JSON PATH.
I now want to write some tests in T-SQL to ensure correct functioning of this stored procedure. Altering the stored procedure is not an option.
To reproduce the problem, suppose I have a stored procedure like this:
USE tempdb
GO
CREATE PROCEDURE dbo.example_sp
AS
BEGIN
    SELECT val1, val2
    INTO #tmp
    FROM ( VALUES (1, 2), (3, 4)) vals (val1, val2)

    SELECT *
    FROM #tmp
    FOR JSON PATH
END

Now, noting that the FOR JSON PATH function will result in a single cell (1 row, 1 column) of type nvarchar, I would like to do something like this to extract the JSON object in order to test it:
CREATE TABLE #result (json_object varchar(max))

INSERT INTO #result
    EXEC dbo.example_sp

But this produces an error:

The FOR JSON clause is not allowed in a INSERT statement.

OK, that's frustrating, but I can use the openrowset work around for that, right?
INSERT INTO #result
    SELECT *
    FROM OPENROWSET('sqlncli', 'Server=(local);Trusted_Connection=yes;',
                    'EXEC tempdb.dbo.example_sp')

No, now I have a this new error:

The metadata could not be determined because statement 'Select * from #tmp FOR JSON PATH' in procedure 'example_sp' uses a temp table.

Yet more frustrating, but surely I can use the WITH RESULT SET trick to solve that?
INSERT INTO #result
    SELECT *
    FROM OPENROWSET('sqlncli', 'Server=(local);Trusted_Connection=yes;',
                    'EXEC tempdb.dbo.example_sp with result sets ((output varchar(max) NULL))')

Now I receive this error:

Cannot process the object "exec tempdb.dbo.example_sp with result sets (( output varchar(max) NULL))". The OLE DB provider "SQLNCLI11" for linked server "(null)" indicates that either the object has no columns or the current user does not have permissions on that object.

OK, to deal with that we have to use SET NOCOUNT ON which permits SQL Server to skip some validation. The final version is:
INSERT INTO #result
    SELECT *
    FROM OPENROWSET('sqlncli','Server=(local);Trusted_Connection=yes;',
                    'SET NOCOUNT ON; exec tempdb.dbo.example_sp with result sets (( output varchar(max) NULL))')

Which works at long last. I feel that this is way too much kludge for such a simple thing ... surely there is a better way to do this?


text:
Q: Is it possible to have an autocomplete using jtextfield and a Jlist?
I want to create an auto-complete program in java which should provide a list of suggestions instantly when the user types a character/String inside a JTextfield. The problem is that I am confused on how to do it.
Could somebody provide an idea or a sample on the said problem?

A: 1) you have to sort your array before use for better performance...
2) as I mentioned you have to take these two clasess
3) don't forget set initial value for better and nicest work with these Components
simple output

from code
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;

public class AutoCompleteTextField {

    private JFrame frame;
    private ArrayList<String> listSomeString = new ArrayList<String>();
    private Java2sAutoTextField someTextField = new Java2sAutoTextField(listSomeString);
    private ArrayList<String> listSomeAnotherString = new ArrayList<String>();
    private Java2sAutoComboBox someComboBox = new Java2sAutoComboBox(listSomeAnotherString);

    public AutoCompleteTextField() {
        listSomeString.add("-");
        listSomeString.add("Snowboarding");
        listSomeString.add("Rowing");
        listSomeString.add("Knitting");
        listSomeString.add("Speed reading");
        listSomeString.add("Pool");
        listSomeString.add("None of the above");
//
        listSomeAnotherString.add("-");
        listSomeAnotherString.add("XxxZxx Snowboarding");
        listSomeAnotherString.add("AaaBbb Rowing");
        listSomeAnotherString.add("CccDdd Knitting");
        listSomeAnotherString.add("Eee Fff Speed reading");
        listSomeAnotherString.add("Eee Fff Pool");
        listSomeAnotherString.add("Eee Fff None of the above");
//
        someTextField.setFont(new Font("Serif", Font.BOLD, 16));
        someTextField.setForeground(Color.black);
        someTextField.setBackground(Color.orange);
        someTextField.setName("someTextField");
        someTextField.setDataList(listSomeString);
//
        someComboBox.setPrototypeDisplayValue("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
        someComboBox.setFont(new Font("Serif", Font.BOLD, 16));
        someComboBox.setForeground(Color.black);
        someComboBox.setBackground(Color.YELLOW);
        someComboBox.getEditor().selectAll();
        someComboBox.getEditor().getEditorComponent().setBackground(Color.YELLOW);
        ((JTextField) someComboBox.getEditor().getEditorComponent()).setDisabledTextColor(Color.black);
        someComboBox.setName("someComboBox");
        someComboBox.setDataList(listSomeAnotherString);
//
        frame = new JFrame();
        frame.setLayout(new GridLayout(0, 1, 10, 10));
        frame.add(someTextField);
        frame.add(someComboBox);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(100, 100);
        frame.pack();
        frame.setVisible(true);
//
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                someTextField.setText("-");
                someComboBox.getEditor().setItem(0);
                someComboBox.getEditor().selectAll();
                someTextField.grabFocus();
                someTextField.requestFocus();
                someTextField.setText(someTextField.getText());
                someTextField.selectAll();
            }
        });

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                AutoCompleteTextField aCTF = new AutoCompleteTextField();
            }
        });
    }
}

A: SwingX has an autocomplete feature, it's a decorator which can be applied to several component types. It differs from what you are implementing in that it doesn't narrow the list of items. Code is free, you probably can adjust to your needs
The latest release is version 1.6.4. Its resources (binaries, source, javadoc) is available in the project download area or via maven. For a first look of the functionality you might want to run the webstartable, available on the homepage.


text:
Q: Using Ajax and Django conditions to display an html variable I'm new to using Ajax calls with Django. Im trying to implement a simple Display or not display depending on the type of get called by Ajax:
Views:
def dynamic(request):
    context = {}
    if request.method == 'GET':
        if 'backtest_type' in request.GET:
           context['display_details'] = False
           print ('Im not displaying')

        elif 'change_val' in request.GET:
            context['display_details'] = True
            print ('Im displaying')

        else:
            context['display_details'] = False

    return render(request, "demo/dynamic.html", context)

In my template:
{% extends 'demo/base.html' %}
{% block body %}

<link rel="stylesheet" href="{% static 'css/dynamic.css' %}">

  {% if display_details %}

I'm diplaying

  {% endif %}

        <button class="btn btn-secondary" type="button">Don't Display</button>

        <button class="btn btn-secondary" type="button">Display!</button>

{% endblock %}

From the console I'm sure that the get requests are being correctly sent using ajax (the get requests are being sent and the console prints the statements:

[09/Feb/2019 20:00:56] "GET /dynamic/?backtest_type=1 HTTP/1.1" 200
  6530
Im displaying

However, even if the ajax call works correctly, the template doesn't end up rendering
I'm diplaying
. Am I misunderstanding anything about Ajax?
Thanks in advance!


text:
Q: For next loop multiplying numbers I am attempting to create a calculator where a user inputs a number (1-20) and it gives the user the option to get the sum or product from 1 to the number they entered. ie the sum of 5 would be 15 while the product would be 120. I am using select case and a for next loop. I have managed to get the sum portion of the calculator working correctly and thought I could use the same principle for the product portion but I am having no such luck. Any help or a gentle nudge in the right direction would greatly appreciated.
Cheers.
Code:
    Dim intsum As Integer
    Dim intnum As Integer
    Dim intproduct As Integer

    If IsNumeric(txtinput.Text) Then
        intnum = CInt(txtinput.Text)
    Else
        MessageBox.Show("Please enter a numeric value", "Input error")
        txtinput.Clear()
        txtinput.Focus()

    End If

    If intnum >= 1 AndAlso intnum <= 20 Then

        Select Case True

            Case btnproduct.Checked
                For P = 1 To intnum Step 1
                    intproduct = intproduct * P

                Next

            Case btnsum.Checked
                For S = 1 To intnum Step 1
                    intsum = intsum + S
                Next

        End Select

A: Initialise intproduct to = 1 as at the moment you are multiplying your value by 0 so it will always show the final result as 0.

A: You don't need to check the value of intnum if the value is not numeric.
Dim intsum As Integer
Dim intnum As Integer
Dim intproduct As Integer

If IsNumeric(txtinput.Text) Then
    intnum = CInt(txtinput.Text)

    If intnum >= 1 AndAlso intnum <= 20 Then

        Select Case True

        Case btnproduct.Checked
            For P = 1 To intnum Step 1
                intproduct = intproduct * P

            Next

        Case btnsum.Checked
            For S = 1 To intnum Step 1
                intsum = intsum + S
            Next

        End Select
    End If
Else
    MessageBox.Show("Please enter a numeric value", "Input error")
    txtinput.Clear()
    txtinput.Focus()

End If


text:
Q: git pull broke something - how to go back to previous working commit and merge the remote changes in again? I commited a new feature locally, pulled from remote and got merge conflicts. After resolving them, my feature stopped working (seems like I made an error).
My idea was to go back to my commit and somehow repeat the merge. I checked out my commit, made a new branch, checked out master and tried to merge the new branch into master. This didn't work because "Everything is up to date".
How do I best handle this if I don't want to fix the error by looking through the code by hand?
/edit: I accepted the correct answer to the question but it turns out that my problem has a different origin than assumed above. I asked a follow-up question here.

A: If you do the checkout of your commit after the first merge to master, you will get an "Everything is up to date" when merging from master.
m--m--m
       \
 f--f1--F
      \
       newBranch: master is already merged

You need, as commented, to reset --hard to f1, and retry the merge.
As long as you don't push, you can reset/retry as many times as you need.


text:
Q: SQL Server : fix Error 18456, Severity: 14, State: 1. Login failed for user I'm trying to connect to my local system. But the server cannot be connected and getting the below error.

Cannot connect to HSL11594.
Login failed for user 'user\user'. (.Net SqlClient Data Provider)
Server Name: Servername
Error Number: 18456
Severity: 14
State: 1
Line Number: 65536

I have read many suggestions to change the authentication mode by right clicking the instance. But I don't find any instance in my SQL Server object explorer. I tried to reinstall SQL Server which failed with error 'No instance in this computer'.
Please guide me what is happening and what needs to be fixed. If I don't login how do I expect an instance in object explorer?


text:
Q: JavaScript: Assign an unique identifier to an array and iterate over objects in the array I have 4 arrays full of objects:
Array(16) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Array(27) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Array(21) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Array(16) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]

Each object contains a bit of information, that I want to display to the viewer:
0: Object { exchange: "NYSE", quote: "JPY", price: "3923.76016", … }

1: Object { exchange: "DEF", quote: "GBP", price: "3924.60972", … }

2: Object { exchange: "FEG", quote: "EUR", price: "3917.31980", … }

3: {…}

exchange: "NEX"

price: "3914.70000"

quote: "USD"

timestamp: "2018-12-31T07:47:11.253Z"

<prototype>: Object { … }
How can I
1) Assign a unique value to the array, ie. Array #1 is VTX, Array #2 is DEF, so that when I display it on the page, I don't need to change the ticker symbol (ie. VTX on exchange NEX is $100, and I only need to change the exchange name and currency/amount)
2) iterate over the arrays to where the iterator moves on to the next object in the array, let's say, every 2-3 seconds?
I'm doing this in React and have passed the data on to props, but now I'm stuck trying to figure this out.

A: 1) You can store all your arrays in on object like this :
const myArrays = [
    {
        uniqueName: 'VTX',
        infos: []
    },{
        uniqueName: 'DEF',
        infos: []
    }
]

2) You should store the index in the state, and make it change with setInterval in componentDidMount
componentDidMount() {
    this.timerID = setInterval(
        () => this.nextInfo(),
        1000
    );
}


text:
Q: How can I make this table span the entire width of the space between 2 elements? First of all, I'd like to apologise if this question is too simple to justify asking here, I'm extremely inexperienced when it comes to web design/development.
I'm trying to get these links to span the entire width of the nav bar, while still making room for the elements on each side, both of which have different widths.
Setting any width anywhere in my code to 100% doesn't do this, however taking the table out of the navbar works fine.
Here's my code.

header {
  position: fixed;
  width: 100%;
  height: 2.5em;
  background-color: #202020;
}
#top-spacer {
  height: 2.5em;
  width: 100%;
}
#logo {
  width: auto;
  height: 2.5em;
}
#nav-container {
  display: inline-block;
  max-width: 100%;
}
nav {
  display: block;
  width: 100%;
  background-color: blue;
  height: 0.5em;
  vertical-align: top;
  padding: 0;
  margin: 0 auto;
}
nav table {
  display: inline-block;
  width: 100%;
}
#menu-button {
  display: inline-block;
  width: auto;
  height: 2.5em;
  float: right;
  opacity: 0.3;
  transition: opacity 1s;
}
#menu-button:hover {
  opacity: 1;
}

  <meta charset="utf-8">
  <meta name="Description" content="describey mcscriberson">
  <meta name="keywords" content="a,b,c,d">
  <link rel="stylesheet" href="css/normalize.css" type="text/css">
  <link rel="stylesheet" href="css/style.css" type="text/css">

            link
            link
            link
            link
            link
            link

Thank you.

A: Is this what you're trying to achieve? (run the snippet to view)
Basically, if you want to have a header with 3 elements that have different widths yet fill the entire width then you can use CSS to set the parent as display:table then the children as display:table-cell. It works with dynamic widths for any of the elements without any need of floating...

html, body {margin:0;padding:0}

header {
  position: fixed;
  width: 100%;
  height: 2.5em;
  background-color: #202020;
  display:table;
  text-align: center;
}

#top-spacer {
  height: 2.5em;
  width: 100%;
}

#logo {
  width: auto;
  height: 2.5em;
  display:table-cell;
}

#nav-container {
  display:table-cell;
  max-width: 100%;
}

nav {
  width: 100%;
  height:100%;
  background-color: blue;
}

nav table tr {
  width: 100%;
  color:#FFF;
}

nav table td {
  height: 2.5em;
}

#menu-button {
  width: auto;
  display:table-cell;
  height: 2.5em;
  opacity: 0.3;
  transition: opacity 1s;
}
#menu-button:hover {
  opacity: 1;
  display:table-cell;
  background:red;
}

  <meta charset="utf-8">
  <meta name="Description" content="describey mcscriberson">
  <meta name="keywords" content="a,b,c,d">
  <link rel="stylesheet" href="css/normalize.css" type="text/css">
  <link rel="stylesheet" href="css/style.css" type="text/css">

            link
            link
            link
            link
            link
            link

A: Equal sized table cells to fill entire width of holding table
This topic is addressing similar issue, the idea is that you have to have in css the width in % for td. Meaning that if you have 6 columns width would be 100%/6
But I would rather use div elements for links instead of table.
Edit: The td takes the width of the text that is inside. For better understanding use the development tool (F12) and inspect the element of your table (right click on the table you want to see how it is generated) and select Inspect element. You will be able to see that actually the table is 100% in width. Just the columns are not expanded because in your css there is nothing related to this.

A: Generally, using a table for this layout is not recommended but a simple idea is to move the images into the table.

     link
     link
     link
     link
     link
     link

and also set #nav-container width to width: 100%;.
Also, you should supply an example without any unnecessary code such as meta tags and make sure the links are not broken (images links for example)

A: I made a fiddle replacing the table with list items which is the preferred method instead of tables for SEO, responsiveness, maintainability reasons.
Although because you need the list to stretch evenly using % will mean adjusting this number if your list changes length. The first and last item (images li items) will probably need to have their own % width set using nth-child as they may vary from the other list items. Hope it helps:
http://jsfiddle.net/43r7L2fj/1/

link

link

link

link

link


text:
Q: android + scala + intellij sbt returns warning and app crashes on emulator: bad class file magic (cafebabe) or version (0033.0000) I am trying to get a hello world android app work with scala and intellij
Whoever tried the same feat must be familiar with the following steps. The problem happens at the end when I am using the sbt
Please note the versions for each tool I use.
For starters I am using the java version 1.7.0_07
-Download and setup the android sdk. I have downloaded all versions from 1.5 (API 3) to 4.1 (API 16). I will not go into further details on this. There are many tutorials already.
We are going to need the android home path in an enviroment variable. So let's set a persistant enviroment variable for the current user
gedit ~/.pam_environment

and now append this: ANDROID_HOME=
e.g.
ANDROID_HOME=/home/pligor/android-sdks

Now let's grab the sbt tool.
We would rather have a manual installation of sbt.
Find the "Unix" section in the link:
https://github.com/harrah/xsbt/wiki/Getting-Started-Setup
and download sbt-launch.jar and place it in ~/bin
Currently this is version 0.12.0
Then create an sbt file:
gedit ~/bin/sbt

write this line inside:
java -Xms512M -Xmx1536M -Xss1M -XX:+CMSClassUnloadingEnabled -XX:MaxPermSize=384M -jar `dirname $0`/sbt-launch.jar "$@"

and make script executable:
chmod u+x ~/bin/sbt

Now you need to install an sbt plugin for the intellij. The sbt-idea version 1.1.0:
gedit ~/.sbt/plugins/build.sbt

add append inside the line (remember each .sbt files seperates each statement by an extra empty line):
addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.1.0")

For github templates you need the giter8 tool. So execute:
curl https://raw.github.com/n8han/conscript/master/setup.sh | sh
and then execute:
cs n8han/giter8

Now I use the g8 to get an android app template from jberkel:
g8 jberkel/android-app

There are some questions for you to setup. Currently I leave everything to default. Which means I use scala version 2.9.1 and Android 2.3.3 (API 10) and scalatest_version of 1.8.RC1.
I am not accustomed with proguard since I haven't use it before so I set useProguard to false.
Before you run sbt:
The android-plugin is currently compatible with the 0.11.3 version of sbt we need to make an adjustment. So inside the folder of the new android application execute:
gedit project/build.properties
and insert this line:
sbt.version=0.11.3
Inside the same folder execute:
sbt 'gen-idea no-classifiers' compile
and then go to the sbt interactive mode console:
sbt
Inside the console execute:
android:package-debug
And I believe these kind of warnings is where the problem starts:
trouble processing:
bad class file magic (cafebabe) or version (0033.0000)
...while parsing my/android/project/R$id.class
Now you can try to start an android emulator: android:emulator-start   # use  to get a list of avds
e.g.
android:emulator-start android2_3_3
after the emulator is fully started execute the android app like that:
android:start-emulator
AND AFTER ALL THIS THE APP WILL CRASH !!

A: The problem is with your Java version. Switch back to Java 6 or if you can't, https://stackoverflow.com/a/7705091/203487 might help.
"bad class file magic (cafebabe) or version (0033.0000)" means the generated class files has a version of 51 which is Java 7, so it's clear that neither the dexer nor ProGuard can work with these class files. Here I'm not talking about the latest ProGuard version but the one bundled with the Android SDK.

A: I can only speak about my setup, which is kind of successful so far.

*

*You will need Proguard to create apks of reasonable size.

*I use Scala 2.10-M6, since 2.8 is old and has its quirks, especially with Android, and 2.9 is very slow to Proguard.

*The keep class scala.collection.SeqLike { ... is important otherwise the class is left out to the contrary it has a method references (I posted this workaround).

*The Build.scala uses many fun stuff like scalaz or libgdx, feel free to prune these. Many android stuff is hacked together from various g8 templates, thx for all the people sharing them.

So here is a dump of my setup:
project/Build.scala
project/plugins.sbt
I use sbt 0.11.3 and Idea 11.1. I compile using the sbt console, mainly use the android:start-device command, and sometimes android:emulator-start RomName + android:start-emulator. Idea attaches nicely to the running Android process.
I'm developing a small game with non-intensive graphics, and so far I used idiomatic Scala (and even Scalaz) without slowdowns. So no need to revert to arrays, vars and while loops just for the sake of Android :)
Good luck!


text:
Q: Conversion between sub-classes using Curiously Recursive Template Pattern Given:

*

*a template class Base with the typename argument value_type,

*its Curiously Recursive Template
Pattern template "sub-classes" DerivedFoo and DerivedBar, and

*template "sub-class" DerivedBarCode and DerivedBarDoge which are derived from DerivedBar,

How may I, or is it possible for me to:

*

*achieve conversion (via explicit constructor, assignment operator, etc.) between every pair of the three leaf derived types as indicated in the diagram, and

*disable (via a compiler error message) conversions that aren't specified in the diagram?

The diagram:
Base -+---> DerivedFoo <-------+
      +-+-> DerivedBar         | // Three-way
        +---> DerivedBarCode <-+ // conversion
        +---> DerivedBarDoge <-+

The scenario is abstracted from:
MatrixBase -+---> DenseMatrix <------------+
            +-+-> SparseMatrixBase         |
              +---> MatrixCSR <------------+ // Multiple-way
              +---> MatrixCSC <------------+ // conversion
              +---> MatrixModifiedCSR <----+
              +---> MatrixModifiedCSC <----+

where every class has at least one common template argument, typename value_type.
Minimum demonstrative example:
Explanation:

*

*Lines 116...128 and lines 160...169 shows my attempt at defining the explicit template constructor of a template class outside the template class, to convert DerivedBarCode<value_type> and DerivedBarDoge<value_type> into DerivedFoo<value_type>.

*Line 49 contains the static assertion which stalls for all conversions not specified in the diagram.

*Remove lines 189...202 along with lines 116...128 and lines 160...169 to successfully compile and run.

Code:
#include <iostream>

// ----------------------------------------------------------------------------
// Base
// ----------------------------------------------------------------------------
template <typename value_type, typename derived_type>
class Base
{
public:
    // Pass along the value type.
    typedef value_type value_type;
    // Identify myself in the Curiously Recursive Template Pattern hierarchy.
    typedef Base object_type;
    // Delegate to derived types.
    derived_type & asLeaf() { return static_cast<derived_type &>(*this); }

protected:
    value_type m_Base;

public:
    Base(value_type base = value_type()) : m_Base(base) {}

public:
    // A delegated function
    void Dump() { asLeaf().Dump(); }
};

// ----------------------------------------------------------------------------
// Base -----> Derived Foo
// ----------------------------------------------------------------------------
template <typename value_type>
class DerivedFoo : public Base < value_type, DerivedFoo<value_type> >
{
public:
    // Identify myself in the CRTP hierarchy.
    typedef DerivedFoo object_type;

protected:
    value_type m_Foo;

public:
    DerivedFoo(value_type base = value_type(), value_type foo = value_type()) :
        Base < value_type, DerivedFoo<value_type> >(base), m_Foo(foo) {}

    template <typename object_type_2>
    DerivedFoo(object_type_2 const &other)
    {
        static_assert(false, "Non-specialized template constructor disabled.");
    }

public:
    // A possible implementation of the delegated function
    void Dump()
    {
        std::cout << "DerivedFoo = [" << m_Base << ", " << m_Foo << "]\n";
    }
};

// ----------------------------------------------------------------------------
// Base -+---> DerivedFoo -+ Two-way
//       +---> DerivedBar -+ conversion
// ----------------------------------------------------------------------------
template <typename value_type, typename bar_type>
class DerivedBar : public Base < value_type, DerivedBar<value_type, bar_type> >
{
public:
    // Pass along the derived bar type.
    typedef bar_type bar_type;
    // Identify myself in the CRTP hierarchy.
    typedef DerivedBar object_type;
    // Delegate to derived types.
    bar_type & asLeaf() { return static_cast<bar_type &>(*this); }

protected:
    value_type m_Bar;

public:
    DerivedBar(value_type base = value_type(), value_type bar = value_type()) :
        Base < value_type, DerivedBar<value_type, bar_type> >(base), m_Bar(bar)
    {}

public:
    void Dump() { asLeaf().Dump(); }
};

// ----------------------------------------------------------------------------
// Base -+---> DerivedFoo <-------+
//       +-+-> DerivedBar <-------+ Three-way conversion
//         +---> DerivedBarCode <-+
// ----------------------------------------------------------------------------
template <typename value_type>
class DerivedBarCode :
    public DerivedBar < value_type, DerivedBarCode<value_type> >
{
public:
    typedef DerivedBarCode object_type;

protected:
    value_type m_Code = 8;

public:
    DerivedBarCode(value_type base = value_type(),
        value_type bar = value_type(), value_type code = value_type()) :
        DerivedBar < value_type, DerivedBarCode<value_type> >(base, bar),
        m_Code(code) {}

public:
    void Dump()
    {
        std::cout << "DerivedBarCode = ["
            << m_Base << ", " << m_Bar << ", " << m_Code << "]\n";
    }
};

// DerivedBarCode => DerivedFoo
// Example of what I'm trying to do:
template <typename value_type>
template <>
DerivedFoo<value_type>::DerivedFoo(
    typename DerivedBarCode<value_type>::object_type const &other)
{
    m_Base = other.m_Base;
    m_Foo = other.m_Foo;
    // There may be other calculations, e.g. replacing the line above with:
    // m_Foo = other.m_Foo + other.m_Code;
    std::cout << "m_Code = " << other.m_Code << '\n';
}

// ----------------------------------------------------------------------------
// Base -+---> DerivedFoo <-------+
//       +-+-> DerivedBar <-------+ Four-way
//         +---> DerivedBarCode <-+ conversion
//         +---> DerivedBarDoge <-+
// ----------------------------------------------------------------------------
template <typename value_type>
class DerivedBarDoge :
    public DerivedBar < DerivedBarDoge<value_type>, value_type >
{
public:
    typedef DerivedBarDoge object_type;

protected:
    value_type m_Doge;

public:
    DerivedBarDoge(value_type base = value_type(),
        value_type bar = value_type(), value_type dance = value_type()) :
        DerivedBar < DerivedBarDoge<value_type>, value_type >(base, bar),
        m_Code(dance) {}

    void Dump()
    {
        std::cout << "DerivedBarDoge = ["
            << m_Base << ", " << m_Bar << ", " << m_Doge << "]\n";
    }

};

// DerivedBarDoge => DerivedFoo
// Another attempt.
template <typename value_type>
template <>
DerivedFoo<value_type>::DerivedFoo(DerivedBarDoge<value_type> const &other)
{
    m_Base = other.m_Base;
    m_Foo = other.m_Foo;
    std::cout << "m_Doge = " << other.m_Doge << '\n';
}

int main()
{
    DerivedFoo<double> foo(1.0, 2.0);
    foo.Dump();
    // Output:
    // DerivedFoo = [1, 2];

    DerivedBarCode<double> barcode(4.0, 8.0, 16.0);
    barcode.Dump();
    // Output:
    // DerivedBarCode = [4, 8, 16];

    DerivedBarDoge<double> bardoge(32.0, 64.0, 128.0);
    bardoge.Dump();
    // Output:
    // DerivedBarDoge = [32, 64, 128];

    DerivedFoo<double> converted(barcode);
    converted.Dump();
    // Expected output:
    // DerivedFoo = [4, 8];

    converted = bardoge;
    converted.Dump();
    // Expected output:
    // DerivedFoo = [32, 64];

    barcode = foo;
    barcode.Dump();
    // Expected output:
    // DerivedFoo = [1, 2, 16];

    // system("pause");
    return 0;
}

A: The CRTP bases will inject their class names into the derived class. So if each CRTP base knows the derived type to be derived_type, then getting to the other base other_base< derived_type > is a simple matter of
static_cast< typename derived_type::other_base & >(
            static_cast< derived_type & >( * this ) );

If the CRTP base mixin may be implemented by any of several templates, then it should add a typedef to its own type, to identify which mixin it is. Then use that for ::other_base.
To add conversions, just put such a cast into a conversion operator template. Be sure to sanitize the conversion with SFINAE before actually attempting it.
template< typename t,
    std::enable_if_t< std::is_base_of_v< t, derived_type > > * = nullptr >
operator t & ()
    { return etc; }

You could additionally/alternately tag all suitable mixins with a member typedef, and SFINAE check for that tag instead. To select only the transitions in the diagram, upgrade the tag to a Boolean metafunction.

A: First, stop thinking about your template hierarchy.  Second, stop thinking about casting.
Which seemingly doesn't leave much, but it leaves enough.
Suppose we have 3 unrelated types: Alice, Bob and Dense.
Anything can be converted to Dense easily:
template<typename T>
Dense to_dense( T&& );

Now, there is custom code that lets you convert Dense to Alice or Bob.  Lets use overloads, where we pass a tag parameter to tell us what we want to convert to:
template<class T> struct type_tag {};
Alice from_dense( Dense const&, type_tag<Alice> );
Bob from_dense( Dense const&, type_tag<Bob> );

these will be maintained by Alice and Bob respectfully.
Let us suppose that Alice and Bob belong to some type category -- call it ConvertUniverse:
template<class T>
constexpr bool InConvertUniverse();

where we can say InConvertUniverse<Alice>() and get true, and InConvertUniverse<int>() and get false at compile time.  For now, Dense is not in said universe.
Lets make a function that can automatically convert anything in said universe to anything else:
template<class T> using decay_t = typename std::decay<T>::type;

template<class Src, class Dest>
typename std::enable_if<
  InConvertUniverse< decay_t<Src> >() && InConvertUniverse< Dest >(),
  Dest
>::type
cross_convert( Src&& src, type_tag<Dest> ) {
  return from_dense( to_dense(src), type_tag<Dest>{} );
}

Now, cross_convert( alice, type_tag<Bob>{} ) will return a Bob.
We can use this to implement template casts to anything InConvertUniverse<?>() within Alice.  In fact, we can use it to implement such casts within a CRTP parent of Alice.
For casting to-from Dense you are all good.
The next step is to allow for faster cross_convert in special cases.  If you get this far, you'll want to make the global cross_convert above have some property that makes it not as preferred as ADL found overloads (such as ending the parameter list with a ... or Ts&&... that you never use).  Then a specific cross_convert overload will be preferred I believe.
Now, one annoying misfeature of the above is that ADL doesn't let us stick from_dense in the namespace of Bob and have it be automatically found, as type_tag<Dest>{} exists in an unrelated namespace (in theory).  So replace type_tag with:
template<class T> using type_tag = T*;

and ADL starts kicking in, and we can define from_dense in Alice's namespace and have it magically found by cross_convert.  It also causes covariant overloading, which is annoying if you have sub-classes of Alice hanging around, but that isn't a problem here.


text:
Q: Load jquery in popup chrome extension i want to create a chrome extension that opens a popup window and i want to use jquery in my html file.
i create my manifest.json
{
  "name": "My First",
  "description": "Test App",
  "version": "0.1",
  "app": {
    "background": {
      "scripts": ["background.js"]
    }
  },
  "icons": { "16": "radio_tower-32.png", "128": "radio_tower-128.png" }
}

then i create a background.js
chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create('window.html', {
    'bounds': {
      'width': 250,
      'height': 250
    }
  });
});

then create my html page
<!DOCTYPE html>

  Stop
    <audio controls="controls"  autoplay class="playeraudio"><source src="http://mystream.mp3" type="audio/mp3" /></audio>

the jquery-1.11.0.min.js is in the folder but the click doesn't function.
I tried to change the background.js using:
chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create('window.html', {
    'bounds': {
      'width': 250,
      'height': 250
    }
  });
});
chrome.tabs.executeScript(null, { file: "jquery.js" }, function() {
    chrome.tabs.executeScript(null, { file: "content.js" });
});

but it doesn't function (content.js is in the folder). Can anybody help me? what i need to change? Thanks

A: I just tried a test in a Chrome extension that I'm working on and got this error in the console:
Refused to execute inline event handler because it violates the following
Content Security Policy directive: "script-src 'self' chrome-extension-resource:".

Some more details on the violation: https://developer.chrome.com/extensions/contentSecurityPolicy.html#JSExecution
Basically you need to extract the onclick EventListener into its own JS file.


text:
Q: .Net Core project accesses too many class or API when it depends on some other projects I have two .Net Standard 2.0 library projects: Lib1 and Lib2, Lib2 depends on Lib1, Lib1 has class Class1, Lib2 has class Class2. Then I create a .Net Core 2.0 and a .Net Framework project:

*

*The .Net Core 2.0 console application project named DevInNetCore
which only depends on Lib2, but Lib1.Class1 can be accessed in this
project.

*The .Net Framework 4.6.1 console application project named
DevInNetFramework which also only depends on Lib2, but now
Lib1.Class1 can't be accessed in this project.

My question is: Why Lib1.Class1 can be accessed in the .Net Core project DevInNetCore since it only depends on project Lib2? Is there any way to let Lib1 can not be accessed in the project DevInNetCore?
Here is my demo solution: https://www.dropbox.com/s/u60xjl3i37arcs2/LibTest.zip?dl=0, Visual Studio 2017 may be needed to load the solution.

A:
Why Lib1.Class1 can be accessed in the .Net Core project DevInNetCore
  since it only depends on project Lib2?

This change came with new format of csproj files. Here is related issue on github. If you check the references in Visual Studio, you will see that for .Net Core project VS 'knows' that Lib2 depends on Lib1. However this is not the case for reference from .Net Framework project.

So answering your question "Why ..." - because it's the feature that was implemented for new project format and not for the legacy one.

Is there any way to let Lib1 can not be accessed in the project
  DevInNetCore?

Here is related discussion on github. I agree with Eilon's comment that such restriction should not take a place in general. However if you still want to do it, you could make types of Lib1 internal and then allow access them from Lib2 with InternalsVisibleTo attribute.


text:
Q: Information about the domain could not be retrieved (1355) Here is a sample of my code
var domainContext = new PrincipalContext(ContextType.Domain, "domain_server_ip",
            "domain_admin_username", "domain_admin_password");
var group = GroupPrincipal.FindByIdentity(domainContext, "mygroup");
var users = group.Members.Where(member => names.Contains(member.Name))
            .ToList();
users.ForEach(u => group.Members.Remove(u));
group.Save(domainContext); // <-- Here I get the error

Same error if I try to get user groups
var user = UserPrincipal.FindByIdentity(domainContext, "username");
var gps = user.GetGroups(domainContext).ToList(); // <-- Here I get the error

I tried using ContextOptions.SimpleBind in connection, but nothing changes.
I've also tried setting a container name in connection, but again nothing changes.
Please note that I'm able to retrieve the group and its members... so I don't understand why I can't save the group or read user groups.

A: Try adding the IP address of the domain controller you're querying (in the first line - domain_server_ip) as the first DNS server on your network card's IP settings.
(borrowed from here)

A: i had the same Problem.
the problem in our Case was that the Target was an external Domain Server. The .net Ad Library seems to take explicit the FQDN from the external AD Server (that one that the Server resolves for himself) for some requests and do not respect the FQDN or ip you gave as name to the PrincipalContext ctor in all cases.
so my Client was in x.Domain1, the External Ad Server (server1.x.Domain2) is for Domain x.Domain2.
The standard dns for Domain1 resolved the AdServer as server1.x.Domain1. This Dns don´t know about the Domain2. Thats the issue.
To Resolve this you have imho 3 choices

*

*Add ip from external Ad Server as your primary dns (do not forget do Enable/Disable Adapter after that) (Not an option for us)

*Edit hosts File And Add 2 Entrys: (good for test, but no option for production)
IpofDomain2Server server1.x.Domain2
IpofDomain2Server x.Domain2

*Speak with the Infrastructure to add above DNS Entrys for Domain2 in Domain1 (Dns Forwarding?)


text:
Q: Building Crypto++ 5.6.2 with Cygwin x86_64 I am attempting to build CryptoPP with Cygwin x86_64, but I'm having some trouble with osrng.cpp.
I'm using gcc's C++ compiler, and I'm getting the following error at line 50 of osrng.cpp
$ make
g++ -DNDEBUG -g -O2 -march=native -pipe -c osrng.cpp
osrng.cpp: In constructor 'CryptoPP::MicrosoftCryptoProvider::MicrosoftCryptoProvider()':
osrng.cpp:50:80: error: invalid conversion from 'CryptoPP::MicrosoftCryptoProvider::ProviderHandle* {aka long unsigned int*}' to 'HCRYPTPROV* {aka long long unsigned int*}' [-fpermissive]
  if(!CryptAcquireContext(&m_hProvider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
                                                                                ^
In file included from /usr/include/w32api/windows.h:95:0,
                 from osrng.cpp:19:
/usr/include/w32api/wincrypt.h:646:26: error:   initializing argument 1 of 'WINBOOL CryptAcquireContextA(HCRYPTPROV*, LPCSTR, LPCSTR, DWORD, DWORD)' [-fpermissive]
   WINIMPM WINBOOL WINAPI CryptAcquireContextA(HCRYPTPROV *phProv,LPCSTR szContainer,LPCSTR szProvider,DWORD dwProvType,DWORD dwFlags);
                          ^
GNUmakefile:208: recipe for target 'osrng.o' failed
make: *** [osrng.o] Error 1

I have successfully compiled the whole thing under the 32bit version of Cygwin before.
How can I fix this for the 64bit edition?
EDIT As suggested by @Yakov's answer, I replaced if defined(_WIN64)if defined(__x86_64__) by if in line 30 of osrng.h.
Sadly though, I immediately run into the next problem, indicated by the following error:
$ make
g++ -DNDEBUG -g -O2 -march=native -pipe -c fipstest.cpp
In file included from dll.h:30:0,
                 from fipstest.cpp:8:
osrng.h:34:19: error: expected ';' at end of member declaration
  typedef unsigned __int64 ProviderHandle; // type HCRYPTPROV, avoid #include <windows.h>
                   ^
osrng.h:34:27: error: 'ProviderHandle' does not name a type
  typedef unsigned __int64 ProviderHandle; // type HCRYPTPROV, avoid #include <windows.h>
                           ^
osrng.h:38:2: error: 'ProviderHandle' does not name a type
  ProviderHandle GetProviderHandle() const {return m_hProvider;}
  ^
osrng.h:40:2: error: 'ProviderHandle' does not name a type
  ProviderHandle m_hProvider;
  ^
GNUmakefile:208: recipe for target 'fipstest.o' failed
make: *** [fipstest.o] Error 1

A: Thankfully, GCC error messages have improved significantly in recent releases.  The {aka}s tell you that there is a mismatch between long and long long.  Keep in mind that Win64 is LLP64: long is still only 32-bits, and you need a long long to match the size of a pointer.  Most (all?) other 64-bit platforms are LP64, meaning that long matches the size of a pointer.
In this particular case, see the if defined(_WIN64) in osrng.h; you will need to change that condition to if defined(__x86_64__) instead.
You might run into problems with the __int64 type as well. Replace those with long long. (Occurs here, here and here.)

A: You might also find word64 useful. From Crypto++'s config.h:
#if defined(_MSC_VER) || defined(__BORLANDC__)
    typedef unsigned __int64 word64;
    #define W64LIT(x) x##ui64
#else
    typedef unsigned long long word64;
    #define W64LIT(x) x##ULL
#endif

There's a couple of Cygwin defines in there too. But they don't look interesting. For example:
#ifndef TYPE_OF_SOCKLEN_T
#   if defined(_WIN32) || defined(__CYGWIN__)
#       define TYPE_OF_SOCKLEN_T int
#   else
#       define TYPE_OF_SOCKLEN_T ::socklen_t
#   endif
#endif

#if defined(__CYGWIN__) && defined(PREFER_WINDOWS_STYLE_SOCKETS)
#   define __USE_W32_SOCKETS
#endif

(Sorry about the comment here. Its too bing to fit in the little comment block).


text:
Q: Symfony: extra field to a form not saved OK, I have one form with another embedded form. In actions.php I have:
...
// add extra field - select for dynamic population
$tempFrm = new SbCarteOpTempForm(array(), array('type' => 'transfer'));
$tempFrm->setWidget('inv_selectate',new sfWidgetFormSelectMany(array('choices' => array())));
$tempFrm->setValidator('inv_selectate', new sfValidatorPass());

$tempFrm->setWidget('status',new sfWidgetFormInputHidden(array(),array('value'=>'pending')));
$tempFrm->setValidator('status', new sfValidatorPass());

The extra fields "inv_selectate" and "status" should be included in displayed form, and they are indeed. But when I try to submit form, only status variable is sent, the select element is not (inv_selectate).
Why is this happening? I really don't see the problem (and neither the difference between these two new added fields.
Thanks.

A: I found it :)
It's related to the select element. Inside the template I use js to add elements to it (dynamically populated by user), but the select won't appear in form submission unless you have some elements selected within!
In my case the selected has only elements, none selected. D'oh! :)


text:
Q: Header "x-ms-throttle-limit-percentage" not coming in response My application makes a lot of calls to the graph API to get the properties I need. It is impossible to reduce the number of requests in my case. And for this, I need to understand when the number of requests approaches the limit and that I need to stop doing them so as not to get 429)
The documentation says that the parameter "x-ms-throttle-limit-percentage" should come in the header when the number of requests approaches the limit from 0.8. As I understand it, 0.8 is a coefficient from 1, where 1 is the upper limit of the limit:
https://learn.microsoft.com/en-us/graph/throttling?view=graph-rest-1.0#regular-responses-requests
But I didn't get this parameter in the header, although Retry-After with TooManyRequests.
How can I get this parameter in the response? Perhaps you need to specify additional parameters for this? Or set up Tenant for this?
Or is there another way to view throttle-limit?
Thanks in advance for your reply)

A: If you haven't got "x-ms-throttle-limit-percentage" parameter in header response, this means that you haven't consumed more than 0.8 of its limit, its mentioned in docs. please check the screenshot.

You can check service specific throttle limit ,please follow docs ,
We were curious to know, what service you were hitting ?