text:
Q: How can I use Alpha Compositing (Porter and Duff) with C#? Are there a implementation (API) of Alpha Compositing for .NET. The Wikipedia means that Windows has a native implementation of it. Of course it can be do with pixel manipulation but this will be a bad performance. If there are a native implementation then we should use it.
If there is no native implementation that can be used from .NET then there is a library that implement it already?
In Java there is a class AlphaComposite and is very simple.

A: Windows GDI+ does provide some alpha blending.  In .NET, it's exposed by the Graphics class, which is quite well documented.  For alpha blending specifically, start with Alpha Blending Lines and Fills.


text:
Q: What's the field strength and energy density of a spinor field? The field strength and energy density of a vector field $A_\mu$ can be described using the field strength tensor $F_{\mu \nu}$.
What is the field strength and energy density associated with a (Dirac) spinor field $\Psi$?

A: Here's the symmetric energy-momentum tensor of the free Dirac field:
\begin{equation}\tag{1}
{T}_{\mu \nu}^{\textsf{D}} = i \, \frac{\hbar c}{4} \, \big( \, \bar{\Psi} \: \gamma_{\mu} \, (\, \partial_{\nu} \, \Psi \,) + \bar{\Psi} \: \gamma_{\nu} \, ( \, \partial_{\mu} \, \Psi \,) - (\, \partial_{\mu} \, \bar{\Psi} \,) \, \gamma_{\nu} \, \Psi - (\, \partial_{\nu} \, \bar{\Psi} \,) \, \gamma_{\mu} \, \Psi \, \big).
\end{equation}
This guy could be found using the canonical energy-momentum (or the Noether current associated to translation in spacetime), but it would need to be symmetrized using the complicated Belefante-Rosenfeld procedure.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP Set Cookies in MD5 I have an application script, where people can apply for our clan.
Is it possible, to generate a random string, convert this string to an md5, save it in a DB to the users application and also set this MD5 as a cookie for the applier.
If the Applier goes e.g. to "applicationstatus.php" that he only sees his own application with this cookie?
And if he doesn't have a cookie, which is in the DB he gets an error screen
Regards


text:
Q: SharePoint 2010 - enable custom ribbon button only if user has permission to edit selected item I have a custom action in a ribbon, and I need to enable the button only if current user has permission to edit the item (Contribute role). The action is defined in a document library, the way it should work is that user selects (highlights) an item and if he has edit permission the button should be enabled (much like 'Edit item' built in button). Also keep in mind that items can have different permissions.
I have a PageComponent to tell the UI if command can be handled, but I can figure out how to check user permissions for an item in javascript.
This is in my PageComponent:
        canHandleCommand: function (commandId) {
            switch (commandId) {
                case 'Command1':
                    var ids = getSelectedIds(); // gets an array of selected ids

                    var selectionChanged = false;
                    if (ids.length != this.previousIds.length) {
                        selectionChanged = true;
                    } else {
                        for (var index in ids) {
                            if (ids[index] != this.previousIds[index]) {
                                selectionChanged = true;
                            }
                        }
                    }

                    if (selectionChanged) {
                        this.enabledStatusChecked = false;
                    }

                    this.previousIds = ids;

                    if (!this.enabledStatusChecked) {
                        this.checkIsEnabled(ids);
                    }

                    return this.isEnabled;
            }

            return false;
        },
        checkIsEnabled: function (ids) {
            this.enabledStatusChecked = true;
            this.isEnabled = false;

            if (ids.length != 1) {
                return;
            }

            var id = ids[0];

            var context = SP.ClientContext.get_current();
            var web = context.get_web();

            var list = web.get_lists().getById(SP.ListOperation.Selection.getSelectedList());
            var item = list.getItemById(id);

            context.load(item);
            context.executeQueryAsync(Function.createDelegate(this, function () {
                var contentTypeId = item.get_item('ContentTypeId').toString();
                if (!contentTypeId.lastIndexOf(Constants.InternalNormContentTypeId, 0)) {
                    this.isEnabled = true;
                    // !! need to check permissions here !!
                }
                RefreshCommandUI();
            }), Function.createDelegate(this, function () {
                RefreshCommandUI();
            }));
        },

This code enables the button only if 1 item is selected and if it is of specified content type. Does anybody have any idea about how to check permission through javascript?

A: CustomAction has Rights attribute which accepts the permission levels. SharePoint should take care of disabling it if user does not have permission that you set.
http://msdn.microsoft.com/en-us/library/ms460194.aspx


text:
Q: Need to create a qt QTButton with multiple colors I am looking for how to create a QT button with multiple color in background color.
Button should look like this

A: if using a QPushButton then you can play with the stylesheet
for example setting following style to a button
background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 rgba(255, 255, 255, 255), stop:0.495 rgba(255, 255, 255, 255), stop:0.505 rgba(255, 0, 0, 255), stop:1 rgba(255, 0, 0, 255));

will produce this button


text:
Q: SAPUI5: Difference between invalidate and rerender After digging into the code a bit I see that invalidate() on a control will increase a counter which seems to mark the control as invalidated.
This seems to lead to a rerender.
So if you have a control that you want rerendered, is it better practice to use invalidate() or rerender()?
How does a rerender actually get triggered? (other than by explicitly invoking it of course)

A: Both are marked as "protected", meaning you should not call any of them unless you are really deep into developing custom controls.
A control gets invalidated when (for example) a property is changed. In that case you usually want to re-render the control, that's why setters call invalidate by default.
When you overwrite your invalidate method in your custom control, you can analyze the source of the invalidation and then decide whether you really want to rerender etc. See for example the unified.Shell which decides what to do on invalidate based on the source:
https://sapui5.netweaver.ondemand.com/sdk/resources/sap/ui/unified/Shell-dbg.js line 1539ff
Again: Protected means that it should not be called from the outside (and that it should not be necessary, except for debugging).

A:
Is it better practice to use invalidate() or rerender()?

As an application developer
Neither invalidate() nor rerender() should be used as they're not public APIs.
As a control developer
Usually, the framework already manages rerendering of the controls automatically if one of the control settings (properties, aggregations, or associations) changes. But if it's still required to trigger the rerendering explicitly, the API invalidate() should be favored over rerender() because:

*

*rerender()

*

*renders the control synchronously (blocking the main/UI thread)

*works only when the control has been rendered before (no initial rendering possible)

*does not combine multiple state changes into a single rerendering

*causes additional layout trashing

*has become deprecated since 1.70.

*invalidate(), on the other hand, just adds the control to a collection of to-be-rendered controls so that it can be rendered together with them in one process asynchronously (currently in the next browser task using setTimeout(fn, 0)).

A: I encountered such thing in my work recently. I am fixing an animation issue but the bad thing is I have to start the animation after rendering. If that is all I can handle it, but the worse thing is the control rendering twice. When the first rendering happen, the animation start to do, but the second rendering comes immediately and the DOM was restructed, then the animation is terminated and the effect is like no animation executed. After investigate the code, I found there is a place invoke render() method which will execute render immediately. After change it to invoke invalidated() method, it looks the animation works well. It looks multiple invalidate() method invocation only cause executing render once.


text:
Q: Crosstab with no totals In JasperReports (using Jaspersoft Studio), is there a way to show contents without including totals?

I have the crosstab code here. If I delete the lines were appear <crosstabTotalRowHeader> and <crosstabTotalColumnHeader>, the cross tab keeps showing a total column, the one that does not have a header. I need to delete that column.
<crosstab>
    <reportElement x="0" y="0" width="442" height="240" uuid="aae99187-4857-48ad-b2c6-6a66c5e6e89a"/>
    <crosstabDataset>
        <dataset>
            <datasetRun subDataset="grafica_perspectiva" uuid="a819174c-e145-4ad4-a3ef-cddde875ceab">
                <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
            </datasetRun>
        </dataset>
    </crosstabDataset>
    <rowGroup name="perspectiva1" width="60" totalPosition="End">
        <bucket class="java.lang.String">
            <bucketExpression><![CDATA[$F{perspectiva}]]></bucketExpression>
        </bucket>
        <crosstabRowHeader>
            <cellContents mode="Opaque" style="Crosstab_CH">
                <textField>
                    <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF"
                                   uuid="ff8ba239-2c96-4959-8d57-5751f1e67ce1"/>
                    <textFieldExpression><![CDATA[$V{perspectiva1}]]></textFieldExpression>
                </textField>
            </cellContents>
        </crosstabRowHeader>
        <crosstabTotalRowHeader>
            <cellContents/>
        </crosstabTotalRowHeader>
    </rowGroup>
    <columnGroup name="cot_nombre1" height="30" totalPosition="End">
        <bucket class="java.lang.String">
            <bucketExpression><![CDATA[$F{cot_nombre}]]></bucketExpression>
        </bucket>
        <crosstabColumnHeader>
            <cellContents mode="Opaque" style="Crosstab_CH">
                <textField>
                    <reportElement stretchType="RelativeToTallestObject" x="0" y="0" width="140" height="30"
                                   forecolor="#FFFFFF" uuid="76a9a21c-efed-4164-ab6c-4f91e2bf3903"/>
                    <textFieldExpression><![CDATA[$V{cot_nombre1}]]></textFieldExpression>
                </textField>
            </cellContents>
        </crosstabColumnHeader>
        <crosstabTotalColumnHeader>
            <cellContents/>
        </crosstabTotalColumnHeader>
    </columnGroup>
    <measure name="promedio_MEASURE1" class="java.lang.String">
        <measureExpression><![CDATA[new DecimalFormat("###0.00").format($F{promedio})]]></measureExpression>
    </measure>
    <crosstabCell width="140" height="20">
        <cellContents mode="Opaque" style="Crosstab_CD">
            <textField>
                <reportElement x="0" y="0" width="140" height="20" uuid="66c4a20e-d1d2-4263-8a1a-19b09f5d93fd"/>
                <textFieldExpression><![CDATA[$V{promedio_MEASURE1}]]></textFieldExpression>
            </textField>
        </cellContents>
    </crosstabCell>
    <crosstabCell width="140" height="20" rowTotalGroup="perspectiva1">
        <cellContents mode="Opaque" style="Crosstab_CD">
            <box>
                <topPen lineWidth="0.5" lineStyle="Solid" lineColor="#000000"/>
                <leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                <bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
                <rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
            </box>
        </cellContents>
    </crosstabCell>
</crosstab>

A: Never mind. To prevent showing a total column/row in a crosstab, ensure totalPosition attribute in columnGroup/rowGroup is equal to None.

A: I was looking for a way to do exactly the same thing in Jaspersoft Studio 5.6.
Click on the Crosstab tab beside the Main report tab

Then, in the Outline window for the report, open the crosstab tree and the row groups.

Select the row group you want to set the total position attribute for and set it's value to None in the property window, the cell tab.

Done.


text:
Q: bannerview.ad unit is obsolete: use adunitid property instead I'm trying to archive my iOS app and problem shows to me because of Google Mobile Ads .
bannerview.adunit is obsolete: use adunitid property instead
I'm trying to find solution to it
 private BannerView CreateBannerView()
    {
        if (_bannerView != null)
            return _bannerView;

        var origin = new CGPoint(0, UIScreen.MainScreen.Bounds.Size.Height - AdSizeCons.Banner.Size.Height);

        _bannerView = new BannerView(AdSizeCons.SmartBannerPortrait, origin)
        {
            AdUnitID = Element.AdUnitId,
            RootViewController = GetVisibleViewController()
        };

        _bannerView.LoadRequest(GetRequest());

        return _bannerView;
    }

    private Request GetRequest()
    {
        var request = Request.GetDefaultRequest();


text:
Q: How to access remote sql server using sqlcmd? I am trying to access remote sql server on another machine using :
sqlcmd -S <ip address>

But it gives me error -
command not found

Am I doing this wrong? Sorry but I am very new to this technology, so please let me know how i can connect to server. I have also made a user 'xyz'.
Should I have to download some client or something?
One more important thing, there is nothing install on my machine for sql server.

A: You need to install the client tools, via the SQL Server installer, on any machine from which you connect to SQL Server.
For instance, I have the SQL Server 2012 client on this machine, with the following "shared components" of SQL Server installed:

Client Tools Connectivity
Client Tools Backward Compatibility
Documentation Components
Management Tools - Basic
  Management Tools - Complete

Clearly a minimal client wouldn't need all of these.
Also note there is a lot of cross version compatibility (eg. I can use the SQL Server 2012 tools to connect to SQL Server 2014, but clearly newer features may not be accessible).

A: Did you install Sql Server Client Tools on "another machine" ?


text:
Q: OWA 2013 open url with To and Subject fields filled I've been using OWA 2010 for several years, a I had a way to prefill To and subject fields with this kind of link:
https://{server_name}/owa/?ae=Item&a=New&t=IPM.Note&to={to_address}&subject={custom_subject}

Recently my company updated OWA to OWA 2013, and this solution stopped working.
I've found a way to open compose mail screen with a link:
https://{server_name}/owa/#viewmodel=IMailComposeViewModelFactory

But I can't figure out how to fill To and subject fields.
Are there url parameters for filling To and subject in OWA 2013?

A: You may need to use the path instead of viewmodal. There was a post on webapps.stackechange that seemed to work for me. If this syntax works for you, then be sure to replace spaces with %20
The syntax I used:
https://{server_name}/owa/&path=/mail/action/compose&to=test@123.com&subject=Subject%20Here


text:
Q: App Store build crashes, doesn't on testing on Sim or my own device I have just released an update for my app to the app store. I tested it within the simulater and my own devices and never had an issue. I have since discovered that the updated version crashes, but only on the iPad and only from the app store
The update has made the app universal.
Any help would be great, i dont wanna effect my reting.
Crash Log below
Incident Identifier: 36D64A4B-25EF-4352-BEFC-DF4409B48048
CrashReporter Key:   ca77f364943901ada3da44974f547565326b5b64
Hardware Model:      iPad1,1
Process:         FuelCost [2659]
Path:            /var/mobile/Applications/4A738AC7-C717-46C2-9469-9B8888B6FE10/FuelCost.app/FuelCost
Identifier:      FuelCost
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2011-05-14 16:20:31.338 +0100
OS Version:      iPhone OS 4.3.2 (8H7)
Report Version:  104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x00000000, 0x00000000
Crashed Thread:  0

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x360ffa1c __pthread_kill + 8
1   libsystem_c.dylib               0x33e093b4 pthread_kill + 52
2   libsystem_c.dylib               0x33e01bf8 abort + 72
3   libstdc++.6.dylib               0x363fca64 __gnu_cxx::__verbose_terminate_handler() + 376
4   libobjc.A.dylib                 0x33b2806c _objc_terminate + 104
5   libstdc++.6.dylib               0x363fae36 __cxxabiv1::__terminate(void (*)()) + 46
6   libstdc++.6.dylib               0x363fae8a std::terminate() + 10
7   libstdc++.6.dylib               0x363faf5a __cxa_throw + 78
8   libobjc.A.dylib                 0x33b26c84 objc_exception_throw + 64
9   CoreFoundation                  0x303c548a +[NSException raise:format:arguments:] + 62
10  CoreFoundation                  0x303c54c4 +[NSException raise:format:] + 28
11  UIKit                           0x35aa2a4c -[UINib instantiateWithOwner:options:] + 1104
12  UIKit                           0x35aa3e02 -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:] + 86
13  UIKit                           0x358ce4c6 -[UIApplication _loadMainNibFile] + 90
14  UIKit                           0x358c8b02 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 174
15  UIKit                           0x3589d7d0 -[UIApplication handleEvent:withNewEvent:] + 1108
16  UIKit                           0x3589d20e -[UIApplication sendEvent:] + 38
17  UIKit                           0x3589cc4c _UIApplicationHandleEvent + 5084
18  GraphicsServices                0x35571e70 PurpleEventCallback + 660
19  CoreFoundation                  0x3039ca90 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 20
20  CoreFoundation                  0x3039e838 __CFRunLoopDoSource1 + 160
21  CoreFoundation                  0x3039f606 __CFRunLoopRun + 514
22  CoreFoundation                  0x3032febc CFRunLoopRunSpecific + 224
23  CoreFoundation                  0x3032fdc4 CFRunLoopRunInMode + 52
24  UIKit                           0x358c7d42 -[UIApplication _run] + 366
25  UIKit                           0x358c5800 UIApplicationMain + 664
26  FuelCost                        0x000022ee main (main.m:14)
27  FuelCost                        0x000022b8 0x1000 + 4792

Thread 1:
0   libsystem_kernel.dylib          0x361003ec __workq_kernreturn + 8
1   libsystem_c.dylib               0x33e0a6d8 _pthread_wqthread + 592
2   libsystem_c.dylib               0x33e0abbc start_wqthread + 0

Thread 2 name:  Dispatch queue: com.apple.libdispatch-manager
Thread 2:
0   libsystem_kernel.dylib          0x36100fbc kevent + 24
1   libdispatch.dylib               0x33d0b032 _dispatch_mgr_invoke + 706
2   libdispatch.dylib               0x33d0c03a _dispatch_queue_invoke + 86
3   libdispatch.dylib               0x33d0b5ea _dispatch_worker_thread2 + 186
4   libsystem_c.dylib               0x33e0a58a _pthread_wqthread + 258
5   libsystem_c.dylib               0x33e0abbc start_wqthread + 0

Thread 3 name:  WebThread
Thread 3:
0   libsystem_kernel.dylib          0x360fdc00 mach_msg_trap + 20
1   libsystem_kernel.dylib          0x360fd758 mach_msg + 44
2   CoreFoundation                  0x3039d2b8 __CFRunLoopServiceMachPort + 88
3       CoreFoundation                  0x3039f562 __CFRunLoopRun + 350
4   CoreFoundation                  0x3032febc CFRunLoopRunSpecific + 224
5   CoreFoundation                  0x3032fdc4 CFRunLoopRunInMode + 52
6   WebCore                         0x34c2627e RunWebThread(void*) + 382
7   libsystem_c.dylib               0x33e0930a _pthread_start + 242
8   libsystem_c.dylib               0x33e0abb4 thread_start + 0

Thread 0 crashed with ARM Thread State:
    r0: 0x00000000    r1: 0x00000000      r2: 0x00000001      r3: 0x00000000
    r4: 0x3e8a148c    r5: 0x00000006      r6: 0x0015bb5c      r7: 0x2fdfe068
    r8: 0x3f039964    r9: 0x00000065     r10: 0x0014ec40     r11: 0x00000001
    ip: 0x00000148    sp: 0x2fdfe05c      lr: 0x32d8f3bb      pc: 0x32ae2a1c
  cpsr: 0x00000010

Binary Images:

A: There are many things to check here

*

*Make sure that all of your files are included in the target, specifically the Nib files.

*Check to make sure you have nibs included for the iPad.

*You left out the Binary Images section of the report, but check to make sure these crashing devices aren't jail-broken.

Finally, if you are going to support iPad, I would highly recommend getting a physical one to test on. You could have avoided this otherwise.


text:
Q: Automate a remote rsync command using bash aliases? I deal with lots of servers that often have files and folders which are not under version control. This means I can just git remote add if I need to work with the files on my local machine.
With that in mind I often am browsing the server when I notice that I need a copy of a certain folder so I wrote this simple bash command to print the command so I can just copy it and run it on my local machine.
#!/bin/bash
echo "sudo rsync -av -e ssh $(whoami)@$HOSTNAME:$(pwd) ./"

Which outputs a command like this which I can run on my home computer:
sudo rsync -av -e ssh user@hostname:/opt/lib/folder ./

Now my question is, how do I make this into a bash alias so I can add it to my user account on each of the servers?

A: You can use a function instead of an alias.  Just put it into your ~/.bashrc file like this:
print_rsync ()
{
    echo "sudo rsync -av -e ssh $(whoami)@$HOSTNAME:$(pwd) ./"
}

Functions are much more flexible than aliases because you can execute an arbitrary number of commands and even pass parameters.

A: From my understanding of shell aliases, they are static and you cannot put dynamic things like variables or commands in them.
Just copy your script somewhere in your PATH like /usr/local/bin, or create a bin folder for your user:
mkdir ~/bin
echo 'export PATH="$PATH:$HOME/bin"' >> ~/.bashrc
. .bashrc # or reopen terminal
cp script.sh ~/bin


text:
Q: How to output just the user of a running process When I do ps aux | grep mongod, I get
mongod    53830  0.1  0.3 247276 27168 ?        Sl   Apr04 128:21 /var/lib/mongodb-mms-automation/mongodb-mms-monitoring-agent-5.4.4.366-1.rhel7_x86_64/mongodb-mms-monitoring-agent
mongod   104378  0.6  0.8 469384 71920 ?        Ssl  Mar22 571:03 /opt/mongodb-mms-automation/bin/mongodb-mms-automation-agent -f /etc/mongodb-mms/automation-agent.config -pidfilepath /var/run/mongodb-mms-automation/mongodb-mms-automation-agent.pid >> /var/log/mongodb-mms-automation/automation-agent-fatal.log 2>&1
mongod   104471  0.6  5.4 1993296 433624 ?      Sl   Mar22 578:03 /var/lib/mongodb-mms-automation/mongodb-linux-x86_64-3.4.13/bin/mongod -f /data/mdiag/data/automation-mongod.conf

However, I'm only interested in outputting user of the third entry, which runs the actual mongod process. I'd like the output to be just
mongod
How would I tweak around ps, grep, and awk to do this?

A: Pipe it to awk and search:
 ps aux | grep mongod | awk '/bin\/mongod /{print $8}'

With that you can probably drop the grep and just let awk do the searching:
 ps aux |  awk '/bin\/mongod /{print $8}'

This is searching for the string "bin/mongod " anywhere in the record and then returning whatever is in the 8th position for that record.

A: Trying to use shell commands to get that user is most likely going to break. Can you start mongod using the PID option?
/var/lib/mongodb-mms-automation/mongodb-linux-x86_64-3.4.13/bin/mongod -f /data/mdiag/data/automation-mongod.conf --pidfilepath /run/mongodb-pid.txt

Then you can simply run ps $(cat /run/mongodb-pid.txt) to get only the specific process you want.

A: It is probably best to specify the pattern to match the end of the first part of the COMMAND field we are interested in.  Also, using bracket expressions in place of \/ makes at least my eyes happier when looking at patterns for matching file paths.
ps aux | awk -v command=11 -v user=1 '$command ~ /[/]bin[/]mongod$/ { print $user }'

A: perhaps filter out agents?
$ ps aux | awk '/mongod/ && !/agent/{print $1}'

A: Following awk may help here.
ps aux | awk '/mongod/ && /automation-mongod.conf/{print $8}'

OR
ps aux | awk '/mongod/ && /\/data\/mdiag\/data\/automation-mongod.conf/{print $8}'


text:
Q: How to select class dependent features? Suppose, I have a data set which contains two classes and more than 50,000 features. Most of the works I have found try to select features which distinguishes two classes. We called those selected features most important features. But which features are most relevant to which class can't be defined by those approaches that I want to know. For example,
              f1    f2    f3 ....... f50000      class
sample 1:     .5    .4     23......... .45         1
sample 2:     .2    .56     .5......... .45        2
sample 3:     .4    56     .23......... .45        2
sample 4:     .3    .45     76......... .45        1

Here, f1= feature 1, f2=feature2 etc.
Suppose, Somehow I know, f1, f2, f3, f45, f344 is related with class 1, and f4, f5, f6, f90, f99 are related with class 2. Other features are not related with those classes. So the output be,
class1: f1, f2,f3,f45,f344
class2: f4,f5,f6,f90,f99

What will be the algorithms ?
It will be very helpful for me if anyone gives me any papers(deep learning or others) or references. Thanks in advance.

A: There are many ways to detect the significance of the features. A simple approach would be truncating features with low variance. Have a look at this scikit article if you'd like to use their implementation.
An other common why is to penalize the amount of features with L1/L2 regularization. This prevents the algorithm from using all weights. An implementation is in the same scikit article. I just found this github post which explains quite shortly and well the L2 regularization in combination with logistic regression.


text:
Q: Convert char to int in c Just trying to print the square of a number using macros.
Self explanatory C program :
#include <stdio.h>
#define  numb(a)  \
   printf(#a * #a)

int main(void) {
   int num;
   printf("Enter a num: ");
   scanf("%d",&num);
   numb(num);
   return 0;
}

Getting the error :
main.c: In function 'main':
main.c:4:14: error: invalid operands to binary * (have 'char *' and 'char *')
    printf(#a * #a)
              ^
main.c:10:14:
    square(num);
              ~
main.c:10:4: note: in expansion of macro 'square'
    square(num);
    ^~~~~~

How can I convert that char to int to sucessfully use the binary operator?

A: Your macro needs to be c code so just ditch the # and write the formatting string for an integer
#include <stdio.h>
#define  square(a)  \
   printf("%d", (a) * (a))

int main(void) {
   int num;
   printf("Enter a num: ");
   scanf("%d",&num);
   square(num);
   return 0;
}

A: check the output of preprocessor stage by using "cc -E main.c -o main.i" and check how the preprocessor converting macros to instruction .


text:
Q: Using a jQuery effect to change the contents of a div? I am having a form and I would like to change it's contents based on the selected value of a drop down list. All the following will be used in a PHP file.
It looks like this:


text:
Q: Routing & events - backboneJS How should I be handling routing in BackboneJS? When routing, after new-upping my view, should I be triggering an event, or rendering the view directly?
Here are the two scenarios:
Trigger Event:
routes: {
    'orders/view/:orderId' : 'viewOrder'
},
viewOrder: function (orderId) {
    var viewOrderView = new ViewOrderView();
    vent.trigger('order:show', orderId);
}

In my view, I have:
var ViewOrderView = Backbone.View.extend({
    el: "#page",
    initialize: function () {
        vent.on('order:show', this.show, this);
    },
    show: function (id) {
        this.id = id;
        this.render();
    },
    render: function () {
        var template = viewOrderTemplate({ id: this.id });
        this.$el.html(template);
        return this;
    }
});

OR, should I go this route:
routes: {
    'orders/view/:orderId' : 'viewOrder'
},
viewOrder: function (orderId) {
    var viewOrderView = new ViewOrderView({id : orderId });
    viewOrderView.render();
}

In my view, I have:
var ViewOrderView = Backbone.View.extend({
    el: "#page",
    initialize: function () {
        //init code here
    },
    render: function () {
        var template = viewOrderTemplate({ id : this.id});
        this.$el.html(template);
        return this;
    }
});

I think it's the first scenario - given that backbone is event driven, but the 2nd obviously has less code.
Also, I suppose a third scenario would be to keep the view code in the first scenario, but grab the router scenario of the second... rendering the view on navigation, but exposing an event in case I want to trigger that elsewhere.
Thoughts?

A: So all backbone questions usually end up with many plausible answers. In this case, I believe your second example is a more canonical/typical backbone pattern. Putting aside the tricky issue of handling loading spinners and updating after data loads, the simplified basic pattern  in your router would be:
routes: {
    'orders/view/:orderId' : 'viewOrder'
},

viewOrder: function (orderId) {
    //Use models to represent your data
    var orderModel = new Order({id: orderId});
    //models know how to fetch data for themselves given an ID
    orderModel.fetch();
    //Views should take model instances, not scalar model IDs
    var orderView = new OrderView({model: orderModel});
    orderView.render();
    //Exactly how you display the view in the DOM is up to you
    //document.body might be $('#main-container') or whatever
    $(document.body).html(orderView.el);
}

I think that's the textbook pattern. Again, the issue of who triggers the fetching of data and rerendering after it arrives is tricky. I think it's best if the view knows how to render a "loading" version of itself until the model has fetched data, and then when the model fires a change event after fetch completes, the view rerenders itself with the loaded model data. However, some people might put that logic elsewhere. This article on building the next soundcloud I think represents many very good "state of the art" backbone patterns, including how they handle unfetched models.
In general, you can code things with callbacks or events as you prefer. However, a good rule of thumb is to ask yourself some questions:

*

*Is more than one independent logical piece of work going to respond to this event?

*Do I need to decouple the source of this event from the things that happen in response to it?

If both of those are "yes", then events should be a good fit. If both are "no", than straightforward function logic is a better fit. In the case of "navigating to this URL triggers this view", generally the answer to both questions is "no", so you can just code that logic into the router's route handler method and be done with it.

A: I'd use second scenario. Don't see any benefits of using first approach. It would make more sence this way (but still arguable):
/* ... */
routes: {
    'orders/view/:orderId' : 'viewOrder'
},
viewOrder: function (orderId) {
    vent.trigger('order:show', orderId);
}
/* ... */
vent.on('order:show', function(orderId) {
    var viewOrderView = new ViewOrderView();
    viewOrderView.render();
});

var ViewOrderView = Backbone.View.extend({
    el: "#page",
    initialize: function (options) {
        this.orderId = options.orderId;
    },

    render: function () {
        var template = viewOrderTemplate({
            id: this.orderId
        });
        this.$el.html(template);
        return this;
    }
});

This way at least you'd be able to trigger route action without updating a url. But same effect might be achieved using Backbone.router.viewOrder(1) probably. Events are pretty powerful, but i wouldn't use them if i don't really need.


text:
Q: "behind the open door are hidden several differences". Is this grammatically correct? (Inversion+adverbial phrase of location+be verb)
Behind the open door are hidden several differences.

This seems to be an inversion of the sentence

Several differences are hidden behind the open door.

Both sound intuitively correct, but the former inverted sentence does not fit the general inversion pattern of 'adverbial phrase + verb + subject', since it also contains the complement, 'hidden'.
Is there an inversion sentence pattern that I'm missing? Or is the former sentence just plain wrong?

A: [1] Behind the open door are hidden several differences.
[2] Several differences are hidden behind the open door.
[1] is a straightforward example of subject-dependent inversion, while [2] is the basic version.
The inversion involves the subject "several differences" and the complement "behind the open door", which have swapped places in [1].
This type of inversion puts the subject in final position and the complement in front position, where it typically serves as a link to the preceding discourse.

A: First of all, Nate, the orders of words in English are not fully prescribed by a set of rules.  Some orders create confusion as to meaning or fail to convey a clear meaning at all.

Behind the several differences the open door are hidden

Here there is an obvious mistake:  the main verb is plural where it should be singular.  Even when this 'mistake' is corrected and are is replaced by is, or door is replaced by doors, the 'grammatically correct sentence makes no immediate logical or empirical sense.
But your alternatives all make perfectly good sense.  And you are right to think that, if we are looking at it in terms of how sample sentences are usually set out in text books for learners of the English language, your version would be the standard version.  Except, of course that this particular sentence is more literary than the type that would appear in English language text book, at least at the earlier stages.
Some variations are absolutely wrong, of course.  You cannot reverse subject and predicate.

A car was run over by a stray dog.

This is perfectly grammatical, of course.  Simply, we know it cannot be what the news reader meant to say.  In the case of your sentences, the order depends on what is being emphasised.  The 'open door', is obviously a metaphorical reference to something like a negotiation between two parties.  The 'open door' suggests that outward willingness on the part of one or possibly both parties.  The point of the sentence is that despite the apparent willingness 'several differences'  matters may not be a be as easy as they seem.
The order creates suspense by making us wait for the 'punch line'.  "Behind the open door" <"What's going on behind it?", we are thinking>.  "... are hidden" <"what?, come on, get on with it!" "...several differences."  This, in turn, makes us alert and ready for something very important.
So the rhetorical effect is to build tension towards a climax.

A:
Is there an inversion sentence pattern that I'm missing?

Behind the open door are hidden several differences is a sentence in the causative passive:
"Prior to the illusion taking place, the room is arranged to suit the illusionist and behind the open door are hidden several differences", which can be restated as = the illusionist arranges for several differences to be hidden behind the open door by his assistant.
The construction is fronted by a locative adverbial – "Behind the open door". The locative adverbial allows the subject verb inversion although in current Modern English this is not that common, c.f. "In the forest lived a hermit." / "Dearly do I love her."


text:
Q: How to fetch a column from a table(Persistence Database table) into a 'select' list of 'form' in a jsp page I want to fetch a column from a table(Persistence Database table) into a 'select' list of 'form' in a jsp page.
I am using struts2 and hibernate.
My column is 'name' and table is 'Category'
I have made the mapping configuration and bean classes.
code in a 'form' of a jsp page :
<s:select label="Select Category :" name="cname" list="categoryList" />

My action class :
package com.rambo.action;

import beans.Category;
import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;

public class FindCategory extends ActionSupport {

    private List<Category> cl = new ArrayList<Category>();
    private List<String> categoryList = new ArrayList<String>();

    @Override
    public String execute() throws Exception {
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            this.cl = (List<Category>) session.createQuery("from Category").list();
            if (this.cl.isEmpty()) {
                this.addActionError("Sorry.. No category Available. Try again Later.!");
                return ERROR;
            }
            for (int i = cl.size()-1; i >= 0; i--) {
                categoryList.add(cl.get(i).getName());
            }
            session.getTransaction().commit();
        } catch (Exception e) {
            this.addActionError("Oops. An Error Encountered...!");
            return ERROR;
        }
        return SUCCESS;
    }
}

Mapping in Category.hbm.xml :
<property name="name" type="string">
            <column name="NAME" length="20" not-null="true" />
        </property>

Getter and setter of the bean "Category.java":
public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

My glassfish server shows error as :
org.apache.jasper.JasperException: tag 'select', field 'list', name 'cname': The requested list key 'categoryList' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]

root cause tag 'select', field 'list', name 'cname': The requested list key 'categoryList' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]

Can some one please point out what may b the error..?
thanks in advance.

A: Create a public getter for categoryList, otherwise the tag can't access the list.
Also, you're doing too much work in the action, IMO.


text:
Q: Equivalence of $a \rightarrow b$ and $\lnot a \vee b$ Is there a proof for the logical equivalence of $a \rightarrow b$ and $\lnot a \vee b$?

A: Suppose we are for the moment using $p \to q$ for the informal indicative conditional, if $p$ then $q$.

*

*Suppose we are given that if $p$ then $q$ (i.e. $p \to q$). Then, since we have $\neg p \lor p$ it follows (arguing by cases) that $\neg p \lor q$.

*Suppose, conversely, we are given $\neg p \lor q$ is true. Then if $p$ is true that rules out the first disjunct, so we have $q$. In short, if $p$ then $q$, (i.e.  $p \to q$).

That pair of arguments makes it rather plausible that $p \to q$ (the indicative conditional) is inter-dervable with $\neg p \lor q$, and so is equivalent at least as far as truth-conditions go with $\neg p \lor q$.
OK: That gives us some reason to suppose that the truth-functional account of the conditional isn't just fanciful -- it gets something important right. Or so a familiar story goes.
But do note (important point!) it is a further question whether the truth-functional story about 'if' is the whole story.
Compare, arguably '$p$ but $q$' is truth-functionally equivalent to $p \land q$: however 'but' doesn't mean just bare conjunction. 'But' does more than '$\land$' -- very roughly it signals the speaker's sense that the joint truth of $p$ and $q$ is unexpected/surprising. Well likewise, perhaps "if p then q" does more than '$\neg p \lor q$'. E.g. it arguably signals the speaker's willingness to infer $q$ should it turn out that $p$. For more on this, see e.g. http://www.logicmatters.net/resources/pdfs/Conditionals.pdf

A: I'm gonna use p and q.
Natural deduction:
\begin{align}
&1\ p \rightarrow q &&P\\
&2\ |\ \lnot (\lnot p \lor q) &&H\\
&3\ |\ |\ p &&H\\
&4\ |\ |\ q &&1,3 I \rightarrow\\
&5\ |\ |\  \lnot p \lor q &&4 I \lor\\
&6\ |\ |\  \lnot ( \lnot p \lor q) \land (\lnot p \lor q) && 2,5 I \lor \bot\\
&7\ |\ \lnot p&&3-6 I \lnot\\
&8\ |\ \lnot p \lor q&&7I\lor\\
&9\ |\ (\lnot p \lor q) \land \lnot (\lnot p \lor q)&&2,8\land \bot\\
&10\ \lnot p \lor q&&2\lnot
\end{align}
Hope this helps you!

A: Try using a truth table comparing $p\rightarrow q$ with $\lnot p \lor q$.
That's as good a proof as you need.
$p$ | $q\,$ |$\;p\rightarrow q$ | $\lnot p \lor q$
T | T |$\quad$ T $\quad$|$\quad$ T
T | F |$\quad$ F $\quad$|$\quad$ F
F | T |$\quad$ T $\quad$|$\quad$ T
F | F |$\quad$ T $\quad$|$\quad$ T
Both expressions evaluate false if and only if $\,p\,$ is true and $\,q\,$ is false.

For developing a bit of intuition regarding the conditional (logical implication): see, e.g.,
$(1)$ this post, and
$(2)$ this post.

A: Think of it this way. Suppose I signed a contract to you, saying "If I win the lottery, then I will give you $\$1$ billion." The only situation in which my statement would be false (contract violated) is: I win the lottery and don't give you the money I promised. Otherwise, I'm just fine. In particular, if I never win the lottery, you have no claim on any of my money. On the other hand, I can give you the money just for kicks, and I still haven't violated the contract.
Similarly, what if I said "If it's raining, I carry an umbrella." You couldn't call me a liar if it isn't raining, nor if I have an umbrella (regardless of the weather).
A general conditional statement "if (hypothesis) then (conclusion)" is (by this reasoning) the same as saying "(hypothesis) is false or (conclusion) is true."


text:
Q: Homotopy invariant $K$-theory spectrum version vs space version Let $K^H$ be the homotopy $K$-theory spectrum. It is defined as a colimit of the form $|\mathbb{K}(X\times \Delta^{\bullet})|$. Here $\Delta^{\bullet}$ is the co-simplicial scheme defined by the algebraic simplices. $\mathbb{K}$ denote the algebraic $K$-theory spectrum. Now you can define something similar but instead of the spectrum you replace it with the space (like loop space of $Q$-construction) we denote it by $K$. What is the relation of non-negative homotopy groups of $|\mathbb{K}(X\times \Delta^{\bullet})|$ and $|K(X\times \Delta^{\bullet})|$? When do they coincide? I think if $X$ is $K_0$-regular i.e. $K_0(X\times \mathbb{A}^n)\cong K_0(X\times \mathbb{A}^{(n+1)})$ which automatically implies $K_i$-regular for $i<0$, the isomorphism of non-negative homotopy groups happen. If it is not right or there are other conditions I'd like to know about them. Thanks.
BTW if my guess is correct I'd also like a reference for it!


text:
Q: Get jaccard distance between rows without preformong one hot encoding on the column in python I have a table that looks like that:
id   feature_1  feature_2  feature_3
1       A          x          r
23      A          v          r
56      B          z          r

I want to create some sort of Jaccard distance between the rows (ids) in an efficent way and without converting the feature to one hot encoding cols (a lot of possibilities).
How can I get a result of sum of the similarity between rows? something like that:
id_1  id_2  similarity  num_of_features  distance
 1     23       2              3            2/3
 1     56       1              3            1/3
 23    56       1              3            1/3

My code:
def create_pairs(ids_list):
  pairs_list = []
  for (p1,p2) in itertools.combinations(ids_list,2):
      pair = [p1,p2]
      pairs_list.append(pair)

  return pairs_list

def get_distance(id_1, id_2, df):

    ????

    return distance

ids_list= list(df['id'].unique())
pairs_list = create_pairs(ids_list=ids_list)
pairs_df = pd.DataFrame(pairs_list,columns=['id_1','id_2'])
distance_list = []
for [id_1, id_2] in pairs_list:
  distance = get_distance(id_1=id_1, id_2=id_2,df=df)

pairs_df['distance'] = distance_list

A: I believe there is no row-wise built in functionality for jaccard distance in scikit, but you can try out following:
from sklearn.metrics import jaccard_score
import pandas as pd

data = [['a', 'x', 'r'], ['a', 'v', 'r'], ['b', 'z', 'r']]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['feature_1',  'feature_2',  'feature_3'])

print(df)
df_cmp = df.copy()
for index, row in df.iterrows():
  for index_, row_ in df_cmp.iterrows():
    if index == index_:
      continue
    print(index, index_, jaccard_score(row,row_, average='weighted'))
  df_cmp = df_cmp.drop(index) #remove after as done already

Create a copy you will work with - so you remove already passed rows. Then you can calculate jaccard distances for rows. Output:

  feature_1 feature_2 feature_3
0         a         x         r
1         a         v         r
2         b         z         r

And scores for lines:

0 1 0.6666666666666666
0 2 0.3333333333333333
1 2 0.3333333333333333

You can instead of printing write it to a dataframe and work with it later. This method however has complexity O(n*log(n)), maybe there will be something faster.
EDIT:
I somehow didn't notice you have pairs already created, thus just replace your question marks by:
distance = jaccard_score(df.iloc[id_1],df.iloc[id_2], average='weighted')

A: Try this, it should be faster:
def get_distance(id_1, id_2, df):

    similarity_count = df.loc[id_1]==df.loc[id_2]
    similarity_count = similarity_count.sum(0)
    distance = 1-(similarity_count /len(list(df.columns)))

    return distance


text:
Q: Database needs to be regularly updated using excel spreadsheets, but formatting is NOT uniform Thus far I've been manually importing/updating new records into our Access DB. Of course that's time consuming and a hassle. The reason for this is that we send our customers a template, but they don't always send us back the template with their information. Sometimes they change headers, include data in the wrong fields or maybe the wrong data...
There's nothing that I, personally, can do about that aspect of the process. Is there a way for me to develop something that will allow either myself or someone else to automatically update my DB with the click of a button (or a few)?


text:
Q: Page.FindControl? I am working on a page that inherits a Base Page.  The aspx page includes a control that uses xslt for to transform an xml document to html markup.  Within that document I am using the following:
<xsl:template match="Headline">
    <h1 runat="server" id="h1" class="article-heading">
      <xsl:value-of select="text()"/>
    </h1>
</xsl:template>

I am trying to get the get the value of the h1 to set it to page.title, can this be done with page.findControl ?

A: XSLT within a browser tends to be interpreted on the client-side, not the server side.  Using Page.FindControl to find the content of the H1 won't get you too far, as all that will return is the literal <xsl:value-of...> statement.
The best approach is to also open the XML document within the codebehind on the server and set the Page Title from there.

A: you can use javascript to find h1 on clientside then set it to the document.title

A: Unfortunately no, because your <h1> element never gets added to control tree on the server. Even though you have runat="server" ASP.NET doesn't parse HTML resulting from XSLT transformation.
You would have to resort to parsing your XML to get the heading. With XPath it should be easy.


text:
Q: Is a Bayesian posterior kind of like the marginal distribution of a frequentist estimator? I've been thinking a lot about the relationships between various concepts like hypothesis testing, posterior distributions, and estimators.
If I understand correctly, a frequentist estimator $\hat\theta$ aims to approximate an unknown but constant $\theta$ based on some observed data $X$, or in other words it attempts to optimize some pointwise metric by marginalizing out $X$ (for example unbiasedness, $E_X[\hat\theta(X)-\theta|\theta]=0$ for all $\theta$). Confidence intervals are also implicitly conditioned on the unobserved $\theta$ (i.e. $P(\theta\in[a(X),b(X)]|\theta)=0.95$).
On the other hand, Bayesian posteriors attempt to marginalize out the unknown $\theta$ (as opposed to $X$) according to a prior distribution $P(\theta)$, replacing the "pointwise" estimate $\hat\theta$ with a single posterior distribution $P(\theta|X)$. The answer is simpler because we are assuming more than in the frequentist approach.
Both methods assume the same known data generating distribution $X\sim D(\theta)$.
Am I correct in my interpretation that frequentist methods try to marginalize out $X$ while Bayesian methods try to marginalize out $\theta$?
I found another (the same?) example of this "symmetry": https://en.wikipedia.org/wiki/Admissible_decision_rule#Generalized_Bayes_rules

A: In Bayesian setting, you are considering the prior distribution of $\theta$, this does let you use Bayes theorem and calculate the conditional probabilities. In frequentist setting you end up with estimate that depends on the observed data. In frequentist setting you are not "marginalizing out" the data unless you observed the whole population, otherwise this is still an estimate given single sample. So I would argue that this intuition is not correct.


text:
Q: Roots of sum of two polynomials, with added assumption Suppose I have two polynomials
$$ P(x) = a_0 + a_1x+ ... + a_n x^n$$
$$ Q(x) = b_0 + b_1x+ ... + b_n x^n$$
where:

*

*all coefficients are real;

*$a_n, b_n$ are negative;

*$a_i, b_i$ are positive for any $0 \leq i < n$;

*$a_0 + ... + a_{n-1} > |a_n|$;

*$b_0 + ... + b_{n-1} > |b_n|$.

It is fairly straight forward to show that any such polynomial has a unique positive root (and if you want to be fancy, you can use Decartes' Rule of Signs to prove that).
--> Suppose I know this unique positive roots for both $P$ and $Q$. How can I compute the unique positive root of $P + Q$?

*

*If it is easier, how can I compute any of the other roots?

*If it is easier, I can assume $a_0 = a_1 = ... = a_{n-1}$ and $b_0 = b_1 = ... = b_{n-1}$.


text:
Q: MongoDB database db.collection.find returns results but meteor-angular pub/sub nor collection.find does not In meteor I have:
var data_set = elephant_site_service_calcs_ts.find(
                        {
                            calc_tag_id: parseInt(calc.alert_id),
                            calc_ts_update_hour: start_date
                        });
console.log(data_set.fetch());

In an autorun. For testing I also have:
var calc_tag_data =  $meteor.collection(elephant_site_service_calcs_ts)
                        .subscribe('site_calcs_realtime',{
                            calc_ts_update_hour: 1,
                            calc_tag_id: 1,
                            values: 1
                        },
                        {
                            calc_tag_id: parseInt(calc.alert_id),
                            calc_ts_update_hour:
                            {
                                $gt:  start_date.toString()
                            }

                        });
console.log("Calc time series data " + calc_tag_data);

When I run either of them directly against MongoDB I get:
elephant_data_replicaset:PRIMARY> db.elephant_calc_evalv_ts.find(
...     {
...             calc_tag_id: 138,
...             calc_ts_update_hour:
...             {
...                 $gt:  '2015-08-24 15:00:00'
...             }
...
...     },
...     {
...         calc_ts_update_hour: 1,
...         calc_tag_id: 1,
...         values: 1
...     });

{ "_id" : ObjectId("55dba62a71aad4b469c2dcd7"), "calc_tag_id" : 138,     "calc_ts_update_hour" : "2015-08-24 16:00:00", "values" : { "18" : { "2" : 0.00011940298507462686 }, "53" : { "22" : 0.00011940298507462686 } } }
{ "_id" : ObjectId("55dbb8a571aad4b469c2dce6"), "calc_tag_id" : 138, "calc_ts_update_hour" : "2015-08-24 17:00:00", "values" : { "36" : { "53" : 0.00011940298507462686 } } }

elephant_data_replicaset:PRIMARY> db.elephant_calc_evalv_ts.find(     {              calc_tag_id: 138,             calc_ts_update_hour:             {                 $gt:  '2015-08-24 15:00:00'             }      },     {         calc_ts_update_hour: 1,         calc_tag_id: 1,         values: 1     });
{ "_id" : ObjectId("55dba62a71aad4b469c2dcd7"), "calc_tag_id" : 138, "calc_ts_update_hour" : "2015-08-24 16:00:00", "values" : { "18" : { "2" : 0.00011940298507462686 }, "53" : { "22" : 0.00011940298507462686 } } }
 { "_id" : ObjectId("55dbb8a571aad4b469c2dce6"), "calc_tag_id" : 138, "calc_ts_update_hour" : "2015-08-24 17:00:00", "values" : { "36" : { "53" : 0.00011940298507462686 } } }
elephant_data_replicaset:PRIMARY> cls
elephant_data_replicaset:PRIMARY> db.elephant_calc_evalv_ts.find(     {                calc_tag_id: 138,             calc_ts_update_hour:             {                   $gt:  '2015-08-24 15:00:00'             }      },     {            calc_ts_update_hour: 1,         calc_tag_id: 1,         values: 1     });
{ "_id" : ObjectId("55dba62a71aad4b469c2dcd7"), "calc_tag_id" : 138, "calc_ts_update_hour" : "2015-08-24 16:00:00", "values" : { "18" : { "2" : 0.00011940298507462686 }, "53" : { "22" : 0.00011940298507462686 } } }
{ "_id" : ObjectId("55dbb8a571aad4b469c2dce6"), "calc_tag_id" : 138,   "calc_ts_update_hour" : "2015-08-24 17:00:00", "values" : { "36" : { "53" : 0.00011940298507462686 } } }
elephant_data_replicaset:PRIMARY> db.elephant_calc_evalv_ts.find(     {             calc_tag_id: 138,             calc_ts_update_hour:  '2015-08-24 15:00:00' },     {         calc_ts_update_hour: 1,         calc_tag_id: 1,         values: 1     });
{ "_id" : ObjectId("55db93fc71aad4b469c2dcc6"), "calc_tag_id" : 138, "calc_ts_update_hour" : "2015-08-24 15:00:00", "values" : { "0" : { "28" : 0.00011940298507462686 }, "10" : { "16" : 0.00011940298507462686 }, "19" : { "2" : 0.00011940298507462686 }, "30" : { "53" : 0.00011940298507462686 } } }
elephant_data_replicaset:PRIMARY>

But when run through meteor I get:
Getting calc current value from time series data: 133
elephantTopicListCtrl.js?f5170d3f444b49f17026653cb5c451bda922d0e3:120 Data hour: 2015-08-24 15:00:00 data minute: 52 for calc_id 133
elephantTopicListCtrl.js?f5170d3f444b49f17026653cb5c451bda922d0e3:129 []
elephantTopicListCtrl.js?f5170d3f444b49f17026653cb5c451bda922d0e3:146 Calc time series data
elephantTopicListCtrl.js?f5170d3f444b49f17026653cb5c451bda922d0e3:294 Processing calc dataset

Pretty much an empty dataset. On the server publish routine I have:
Meteor.publish("site_calcs_realtime", function(options, searchString) {
console.log("Calcs realtime");
console.log(searchString);
console.log(options);

if(searchString == null)
    searchString = {};

//Get real time data for the past hour for tags
//console.log(elephant_site_service_calcs_ts.find(searchString, options));
return elephant_site_service_calcs_ts.find(searchString, options);
});

The output from the meteor command line:
I20150824-20:04:30.236(-7)? Calcs realtime
I20150824-20:04:30.237(-7)? { calc_tag_id: 133,
I20150824-20:04:30.237(-7)?   calc_ts_update_hour: { '$gt': '2015-08-24   15:00:00' } }
I20150824-20:04:30.237(-7)? { calc_ts_update_hour: 1, calc_tag_id: 1, values: 1 }
I20150824-20:04:30.269(-7)? Calcs realtime
I20150824-20:04:30.269(-7)? { calc_tag_id: 134,
I20150824-20:04:30.269(-7)?   calc_ts_update_hour: { '$gt': '2015-08-24 15:00:00' } }
I20150824-20:04:30.269(-7)? { calc_ts_update_hour: 1, calc_tag_id: 1, values: 1 }
I20150824-20:04:30.307(-7)? Calcs realtime
I20150824-20:04:30.308(-7)? { calc_tag_id: 135,
I20150824-20:04:30.308(-7)?   calc_ts_update_hour: { '$gt': '2015-08-24 15:00:00' } }
I20150824-20:04:30.308(-7)? { calc_ts_update_hour: 1, calc_tag_id: 1, values: 1 }
I20150824-20:04:30.328(-7)? Calcs realtime
I20150824-20:04:30.328(-7)? { calc_tag_id: 136,
I20150824-20:04:30.329(-7)?   calc_ts_update_hour: { '$gt': '2015-08-24 15:00:00' } }
I20150824-20:04:30.329(-7)? { calc_ts_update_hour: 1, calc_tag_id: 1, values: 1 }
I20150824-20:04:30.348(-7)? Calcs realtime
I20150824-20:04:30.348(-7)? { calc_tag_id: 137,
I20150824-20:04:30.348(-7)?   calc_ts_update_hour: { '$gt': '2015-08-24 15:00:00' } }
I20150824-20:04:30.348(-7)? { calc_ts_update_hour: 1, calc_tag_id: 1, values: 1 }
I20150824-20:04:30.366(-7)? Calcs realtime
I20150824-20:04:30.366(-7)? { calc_tag_id: 138,
I20150824-20:04:30.367(-7)?   calc_ts_update_hour: { '$gt': '2015-08-24 15:00:00' } }
I20150824-20:04:30.367(-7)? { calc_ts_update_hour: 1, calc_tag_id: 1, values: 1 }

This is my entire autorun:
$meteor.autorun($scope, function() {
            $meteor.subscribe('site_topic_calc_data', {
                limit: parseInt($scope.getReactively('perPage')),
                skip: (parseInt($scope.getReactively('page')) - 1) *    parseInt($scope.getReactively('perPage')),
                sort: $scope.getReactively('sort')
            }, {'alert_site_id':      parseInt($stateParams.site_id)}).then(function() {
                $scope.site_calcs_count = $meteor.object(Counts     ,'number_of_calcs', false);
                $scope.site_services_count = $meteor.object(Counts ,'number_of_services', false);

                $scope.site_calcs.forEach( function(calc) {
                    console.log("Getting value information for calc tag " +   calc);
                    console.log("Getting calc current value from time series     data: " + calc.alert_id)
                    // console.log("Preparing current value query...");
                    var start_date = moment(new Date()).subtract(4, 'hours').format('YYYY-MM-DD HH:00:00');
                    // console.log(start_date)
                    //used to go back five minutes just in case query false  within
                    var durationInMinutes = 5;
                    var value_minute = (new Date().getMinutes() - durationInMinutes);
                    console.log("Data hour: " + start_date.toString() + " data  minute: " + value_minute.toString() +
                        " for calc_id " + calc.alert_id);

                    var data_set = elephant_site_service_calcs_ts.find(
                        {
                            calc_tag_id: parseInt(calc.alert_id),
                            calc_ts_update_hour: start_date
                        });

                    console.log(data_set.fetch());

                    var calc_tag_data =          $meteor.collection(elephant_site_service_calcs_ts)
                        .subscribe('site_calcs_realtime',{
                            calc_ts_update_hour: 1,
                            calc_tag_id: 1,
                            values: 1
                        },
                        {
                            calc_tag_id: parseInt(calc.alert_id),
                            calc_ts_update_hour:
                            {
                                $gt:  start_date.toString()
                            }

                        });

                   console.log("Calc time series data " + calc_tag_data);

                    $scope.formatTagValue(calc_tag_data);

                });

                $scope.elephant_services.forEach( function (service_element) {
                    //get all tags

                    //do a foreach on each tag
                    //when clicked show graph popout
                    service_element.onClicked = function () {
                        //get service tags
                        console.log("Getting servers for service: " +  service_element.service);
                        var service_meta = service_server_dict_map.find({name: service_element.service});
                        console.log("Getting service: " + service_meta + "    server information for site id: " +
                            site_id);
                        $scope.get_service_site_servers(service_meta);
                        //go to tag_trend
                        //create tag list view t
                        //allows user to build a trend of all tags in service
                        //$state.go('tag_trend_details', {calc_id: calc._id});
                    };
                });
            });
        });

Please advise why meteor is not returning the results to the autorun as expected. When I comment out the find on the server side and add a fetch the results are as expected. The problem is the dataset is not being return to the frontend at all.
One last thing. Router:
.state('site_status',
            {
                url:'/site_status/:site_id/:site_name',
                          templateUrl:'client/elephant_heard_view/view/elephantProcess.ng.html',
                controller:'elephant_site_server_service_stats_ctrl',
                resolve:
                {
                    'subscribe':
                        [
                            "$meteor", function($meteor)
                        {
                            return $meteor.subscribe('site_topic_calc_data');
                        },

                        ],
                    'subscribe':
                        [
                            '$meteor', function($meteor)
                        {
                            return $meteor.subscribe('site_calcs_realtime');
                        }
                        ],
                    'subscribe':
                        [
                            '$meteor', function($meteor)
                        {
                            return $meteor.subscribe('site_servers');
                        }
                        ],
                    'subscribe':
                        [
                            '$meteor', function($meteor)
                        {
                            return $meteor.subscribe('site_tags');
                        }
                        ],
                    'subscribe':
                        [
                            '$meteor', function($meteor)
                        {
                            return elephant_site_service_calcs_ts.find();
                        }
                        ]
                }
            })

collection is defined in the model
elephant_site_service_calcs_ts = new Mongo.Collection("elephant_calc_evalv_ts");


text:
Q: Passing Eval value to C# method for shopping cart I am creating a shopping cart web app for my class. When the user clicks on the add to cart button, I want to pass the value of the ID of each specific product to a separate method in the code behind. Not sure if my syntax is off or if this just wont work. Here is my mark up:
<asp:Button ID="AddToCart" CommandName="Add"
OnClientClick ='<%# ListView1_AddToCart(Eval("ID"))%>'
CssClass ="Button" runat="server" Text="Add to Cart" />

Here is my code behind:
public void ListView1_AddToCart(string CatID)

{cart.AddToCart(CatID);}

I keep getting various issues, but this gives me the following error:
The best overloaded method match for 'OurCats_GrumpyCats.ListView1_AddToCart(string)'
has some invalid arguments.

How can I resolve this? Is there any better way?
EDIT: Here is my mark up
    <%@ Page Title="All Cats" Language="C#" MasterPageFile="~/MasterPage/Layout.master"        AutoEventWireup="true" CodeFile="AllCats.aspx.cs" Inherits="OurCats_GrumpyCats" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cpMainContent" Runat="Server">

Meet all of our kittens!

    <asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" DataSourceID="SqlDataSource2">

        <EmptyDataTemplate>
            No data was returned.
        </EmptyDataTemplate>

        <InsertItemTemplate>
            ID:
            <asp:TextBox ID="IDTextBox" runat="server" Text='<%# Bind("ID") %>' />

            Name:
            <asp:TextBox ID="NameTextBox" runat="server" Text='<%# Bind("Name") %>' />

            Price:
            <asp:TextBox ID="PriceTextBox" runat="server" Text='<%# Bind("Price") %>' />

            Imgu:
            <asp:TextBox ID="ImguTextBox" runat="server" Text='<%# Bind("Img") %>' />

            Description:
            <asp:TextBox ID="DescriptionTextBox" runat="server" Text='<%# Bind("Description") %>' />

            <asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />
            <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Clear" />

        </InsertItemTemplate>

        <ItemTemplate>

                    <a href ="Details.aspx?ID=<%# Eval("ID")%>">
                        <img src="../Images/<%# Eval("Img") %>" width ="200"  />

                    <asp:Label ID="Label1" runat="server" Text="Name: "></asp:Label><asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />
                    <asp:Textbox ID="CatID" runat="server" Visible="false" Text='<%# Eval("ID")%>'></asp:Textbox>

                    <asp:Label ID="Label2" runat="server" Text="Price: $"></asp:Label><asp:Label ID="PriceLabel" runat="server" Text= '<%# Eval("Price") %>'/>

                    <asp:Label ID="Label3" runat="server" Text="Description: "></asp:Label><asp:Label ID="DescriptionLabel" runat="server" Text= '<%# Eval("Description") %>' />

                    <asp:Button ID="AddToCart" CommandName="Add" OnClientClick='<%# "AddToCart(" +Eval("ID") + " );" %>' CssClass ="Button" runat="server" Text="Add to Cart" />

        </ItemTemplate>
        <LayoutTemplate>

        </LayoutTemplate>

    </asp:ListView>
    <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:420_Project_GLConnectionString1 %>" SelectCommand="SELECT * FROM [OurCats]">
    </asp:SqlDataSource>

</asp:Content>

A: try below code
<asp:Button ID="AddToCart" CommandName="Add"
OnClientClick ='<%# ListView1_AddToCart((string)Eval("ID"))%>'
CssClass ="Button" runat="server" Text="Add to Cart" />

A: OnClientClick ='<%# "ListView1_AddToCart(" +Eval("ID") + " );" %>'


text:
Q: Can't save Arabic text from csv to txt file I have a csv file like this:
region_name, city_name, district_name, ppm_value
منطقة, مدينة , حي , 220.92
...

All columns are strings in Arabic, except ppm_value which is a float number. I'm trying to process the csv file and reproduce it in json format. I tried this:
$districts = array();
$fd = fopen('data2.csv', 'r');
while ($row = fgetcsv($fd)) {
    $region = $row[0];
    $city = $row[1];
    $district = new stdClass();
    $district->name = "".$row[2];
    $district->ppm = $row[3];
    //also add region and city to $district

    $districts[] = $district;
}

$json1=json_encode($districts);
file_put_contents("text.txt",$json1);

This produces the following:
[{"name":null,"ppm":"220.92","region":null,"city":null}, ... ]

The float is saved correctly, but the Arabic strings are all null. I even tried to save it like this but I got the same result:
$myfile = fopen('text.txt', "w") or die("Unable to open file!");
fwrite($myfile, json_encode($districts));
fclose($myfile);

A: I know next to nothing about php, but perhaps the problem is that your arabic text is being encoded as ASCII?
try changing it to unicode before you add it to you JSON object, you probably know how to do this better than I do...
string utf8_encode ( string $data )


text:
Q: ADODB INSERT INTO command adding ' at the start of each field after adding record I am trying to add a record into a closed excel book from an open excel book using ADODB and SQL INSERT INTO Statement. I am on O365 version.  Whenever record is added to file it adds ' at start of each field.
eg. 3/3/2022 is added as '3/3/2022, no 234 added as '234...
Pls help
Below is the sql text:
MYSTRING = "'" & Range("$A$2").Text & "'" & "," & "'" & Range("$B$2").Text & "'" & "," & "'" & Range("$C$2").Text & "'" & "," & CInt(Range("$D$2").Value) & "," & "'"

SQLCommand = "INSERT INTO \[Dump2$\] " & "VALUES (" & MYSTRING & ")"

I tried using ', # around field, changing data type in destination excel file. If I assign specific data type to columns in destination file I get the error

Data type mismatch in criteria expression

Pls suggest


text:
Q: How to remount a disk that goes into read-only mode without rebooting? I have a kernel bug that makes my SSD go into read-only mode. To fix this I have to reboot the system, do fsck /dev/nvme0n1p2, and then reboot again to make everything work.
Instead of doing the reboot, I tried to just do
sudo fsck /dev/nvme0n1p2

but how can I mount the nvme0n1p2 disk without rebooting? I want to work on my machine without needing to reboot.
I tried:
lz@blade:~$ sudo mount /dev/nvme0n1p2
mount: /: /dev/nvme0n1p2 already mounted on /.

So I tried:
lz@blade:~$ sudo umount /dev/nvme0n1p2
lz@blade:~$ sudo mount /dev/nvme0n1p2
mount: /: /dev/nvme0n1p2 already mounted on /.

Can somebody help me?

A: Can you please try this:
mount -o remount,rw /dev/nvme0n1p2

It works fine for me.
If you find anything please let me know.
-Karmdip Joshi

A: From Linux, how to change HDD state from ReadOnly after temporarly crash? the accepted answer (with 12 upvotes, at the time of this writing) states:

try with blockdev --setrw or hdparm -r 0


text:
Q: What is the best way to simplify/optimize a piece of code that looks at combinations of conditions? I have a piece of code that I want to optimize for readability and performance and coolness. Right now I have this ugly looking thing:
if      ( cond1 &&  cond2 &&  cond3 && !cond4)
{
     // do something
}
else if ( cond1 &&  cond2 && !cond3 &&  cond4)
{
    // do something
}
else if ( cond1 && !cond2 &&  cond3 &&  cond4)
{
   // do something
}
else if (!cond1 &&  cond2 &&  cond3 &&  cond4)
{
    // do something
}
else
{
    // do something
}

where cond1, cond2, cond3 and cond4 are booleans that have been initialized prior to the block of code above. I want to make this faster, less ugly and more cool.
I'm thinking about doing this:
int val = (cond1 ? 0 : 1) + 2 * (cond2 ? 0 : 1) + 4 * (cond3 ? 0 : 1) + 8 * (cond4 ? 0 : 1);
if (val == 8)
{
    // do something
}
else if (val == 4)
{
    // do something
}
else if (val == 2)
{
    // do something
}
else if (val == 1)
{
    // do something
}
else
{
    // do something
}

Does that work or are there flaws? Is there a better way? What is the typical way of achieving the desired result when looking through different combinations of multiple conditions?

A: From my experience - having a series of long if/else statements indicates a similar yet distinguishable behavior.
I usually try to introduce an interface and implementing classes that catch this behavior, and invoke a method that will produce the desired outcome.
This makes the code much more readable - no need to go over a complex flow (that might get nested later on). Each class is responsible for the implementation of the abstract method, and the object manipulated will have static type of the interface, and its dynamic type - the most matching implementing class.

A: put on the left the condition that has the most chance to be false, doing that it continues to the other if without checking the remaining conditions, so you gain in performance, in what is known as short-circuit

A: Requirement for both readable and well-performing code may be contradictory and does not have an easy one-size-fits-all solution. My recommendation is to clearly prioritize the goals you want to achieve by the refactoring. What is the primary "Why" why you're optimizing the code
optimize for readability
use declarative table driven aproach to declare branches their conditions and other artifacts (what they do). Use a code generator to create ugly code from that. Tables are usually easy to read (BTW the "ugly looking thing" you want to optimize is easy to read once you read it as a table with columns [cond1,cond2,cond3,cond4,action])
or don't bother. Most of today's code ($->_::.:==> etc.) can not be read without colorizers or go-to-definition tools and other code reading enhancers anyway. e.g. Code Rocket can display automatic easy to read flow diagrams right inside your IDE
optimize for performance
exact effective optimization technique depends on the compiler and the target. What's effective may be found out for sure only by analyzing generated low-level machine code. e.g. how friendly it is to the hardware pipeline. This may be different for CISC or RICS architectures. In your case of combination of conditions especially branch prediction is important. Many times direct jump tables may be more efficient. Both real and abstract processors usually have special optimized instructions for this case. On the other hand slightly different copy/pasted code may perform better but will be less maintainable
optimize for coolness
don't know. My lately learned definition for cool code is:

*

*correct (no bugs)

*portable (easily reusable in other projects preferably as black box. copy/paste friendly is plus)

*documented (what it does and why - explained at least in the embedded comments)

the typical way to simplify/optimize combinations of conditions

*

*current hardware guys solve this puzzle frequently on the level of VHDL code. They have some circuit output signal simulators to help

*old hardware guys solved circuit minimization as well, e.g. Karnaugh's maps were in the books long before I was born

*software testers solve this problem when looking for combination of tests with sufficient code coverage. One technique is the decision tables

A: If you can use c++11, you can possibly rewrite it based on my work for this earlier answer: How to simplify multiple if-else-if statements in c++:
switch(combine(cond1, cond2, cond3, cond4))
{
    case combine(1,1,1,0): do_something(1); break;
    case combine(1,1,0,1): do_something(2); break;
    case combine(1,0,1,1): do_something(3); break;
    case combine(0,1,1,1): do_something(4); break;
    default:
        do_something_else();
        break;
}

The beauty of it is that combine is fully compile-time evaluated - leveraging the powers of constexpr.
It is variadic too (so it supports up to the number of bits in int_max_t on your compiler configuration).
Full Example: Live On Coliru. The mechanics (which you can put into some header, e.g. logic_combine.hpp):
#include <iostream>
#include <iomanip>
#include <limits>
#include <cstdint>

namespace detail
{
        // a little overkill to have a functor here too, but it's a good habit™
    template <typename T = uintmax_t>
    struct to_bitmask_f
    {
        template <typename... Flags> struct result { typedef T type; };

        template <typename... Flags>
            typename result<Flags...>::type
            constexpr operator()(Flags... flags) const {
                static_assert(sizeof...(Flags) < std::numeric_limits<uintmax_t>::digits, "Too many flags for integral representation)");
                return impl(flags...);
            }

    private:
        constexpr static inline T impl() { return {}; }
        template <typename... Flags>
            constexpr static inline T impl(bool b, Flags... more) {
            return (b?1:0) + (impl(more...) << (T(1)));
        }
    };
}

template <typename T = uintmax_t, typename... Flags>
    constexpr T combine(Flags... flags)
{
    return detail::to_bitmask_f<T>()(flags...);
}

The demonstration:
void do_something(int i) { std::cout << "something " << i << "\n"; }
void do_something_else() { std::cout << "something else\n"; }

void f(bool cond1, bool cond2, bool cond3, bool cond4) {
    switch(combine(cond1, cond2, cond3, cond4))
    {
        case combine(1,1,1,0): do_something(1); break;
        case combine(1,1,0,1): do_something(2); break;
        case combine(1,0,1,1): do_something(3); break;
        case combine(0,1,1,1): do_something(4); break;
        default:
            do_something_else();
            break;
    }
}

int main()
{
    // some test-cases
    f(1,0,1,0);
    f(1,0,0,1);
    f(0,1,1,0);
    f(0,1,0,1);
    f(0,1,1,1);
    f(1,1,1,1);
    f(1,1,1,0);
    f(0,0,0,0);
}

Prints
something else
something else
something else
something else
something 4
something else
something 1
something else

A: One way or another you want to get your values into bit flags. That is you want a bit set or not in an integer type for every condition. Then every 4-bit value in your case represents one of your above ANDed conditions. After that, you can use a switch statement. It's arguably more readable, and the compiler can often optimize it into a jump table. That is, it will just offset your program counter by some value in a lookup table or something of the sort, and you no longer need to check every combination of values. In this way your checking for ANDed cases becomes constant time rather than linear, that is if you added 4 more flags and there were now 256 combinations rather than 16 than this method would be just as fast in a big-oh way. Alternatively, if you don't trust the compiler to make the switch statement a jump table you can do it yourself using the flags value as an index to an array of function pointers. It's also probably worth noting that the ORed enum case values are folded or pre-computed at compile-time.
  enum {
    C1 = 0x1,
    C2 = 0x2,
    C3 = 0x4,
    C4 = 0x8
  };

  unsigned flags = 0;
  flags |= cond1 ? C1 : 0x0;
  flags |= cond2 ? C2 : 0x0;
  flags |= cond3 ? C3 : 0x0;
  flags |= cond4 ? C4 : 0x0;

  switch (flags) {
    case 0: // !cond1 && !cond2 && !cond3 && !cond4
      // do something
      break;
    case C1: //  cond1 && !cond2 && !cond3 && !cond4
      // do something
      break;
    case C2: // !cond1 &&  cond2 && !cond3 && !cond4
      // do something
      break;
    case C1 | C2: //  cond1 &&  cond2 && !cond3 && !cond4
      // do something
      break;
    case C3: // !cond1 && !cond2 &&  cond3 && !cond4
      // do something
      break;
    case C1 | C3: //  cond1 && !cond2 &&  cond3 && !cond4
      // do something
      break;
    case C2 | C3: // !cond1 &&  cond2 &&  cond3 && !cond4
      // do something
      break;
    case C1 | C2 | C3: //  cond1 &&  cond2 &&  cond3 && !cond4
      // do something
      break;
    case C4: // !cond1 && !cond2 && !cond3 &&  cond4
      // do something
      break;
    case C1 | C4: //  cond1 && !cond2 && !cond3 &&  cond4
      // do something
      break;
    case C2 | C4: // !cond1 &&  cond2 && !cond3 &&  cond4
      // do something
      break;
    case C1 | C2 | C4: //  cond1 &&  cond2 && !cond3 &&  cond4
      // do something
      break;
    case C3 | C4: // !cond1 && !cond2 &&  cond3 &&  cond4
      // do something
      break;
    case C1 | C3 | C4: //  cond1 && !cond2 &&  cond3 &&  cond4
      // do something
      break;
    case C2 | C3 | C4: // !cond1 &&  cond2 &&  cond3 &&  cond4
      // do something
      break;
    case C1 | C2 | C3 | C4: //  cond1 &&  cond2 &&  cond3 &&  cond4
      ; // do something
  };

Also, this covers all the combinations. If you just need some subset feel free to remove some of the cases. The compiler is very good at optimizing switch statements. It's probably faster than any clever special-case arithmetic trick you could roll yourself.
  enum {
    C1 = 0x1,
    C2 = 0x2,
    C3 = 0x4,
    C4 = 0x8
  };

  unsigned flags = 0;
  flags |= cond1 ? C1 : 0x0;
  flags |= cond2 ? C2 : 0x0;
  flags |= cond3 ? C3 : 0x0;
  flags |= cond4 ? C4 : 0x0;

  switch (flags) {
    case C1 | C2 | C3: //  cond1 &&  cond2 &&  cond3 && !cond4
      // do something
      break;
    case C1 | C2 | C4: //  cond1 &&  cond2 && !cond3 &&  cond4
      // do something
      break;
    case C1 | C3 | C4: //  cond1 && !cond2 &&  cond3 &&  cond4
      // do something
      break;
    case C2 | C3 | C4: // !cond1 &&  cond2 &&  cond3 &&  cond4
      // do something
      break;
    default:
      // do something
      ;
  };

A: Your proposed modification works. You get a power of two precisely when all but one of the conditions are true, and the power of two you get is determined by which condition is false. In general you could handle any short list of true/false combinations this way, by simply using the binary representations of the combinations that you wish to use as cases that you test for. For readability you may want to write the combination numbers in your if statements in binary instead of decimal, so you can easily tell which combinations of true/false you are checking for.

A: This is just begging for some kind of lookup table and function pointers/delegates. The pattern If/elseif/elseif/elseif should be avoided, it's hard to read, it's hard to understand.
Replace int val=.... and the big fake switch statement with enumb action = getAction(); actions(action)();.  It's easy, it's simple, and if things go wrong it lets you immediately focus on what the problem is: either the action is coded incorrectly, or you picked the wrong action.  Both possibilities are easy to investigate, and will be straightforward to work on.
Of course, depending upon your language and your conditions, you might want to do this with an interface or subtyping (polymorphism), which will naturally look different, but basically it boilps down to the same thing:

A: Well, the most pleasant way to write that would probably be
if(cond1 + cond2 + cond3 + cond4 == 3)
{
    if(!cond1)
    {
        // do something
    }
    else if(!cond2)
    {
        // do something
    }
    else if(!cond3)
    {
        // do something
    }
    else // !cond4
    {
        // do something
    }
}
else
{
    // do something
}

I'm wary of those values not being in an array, though.

A: I am suspicious of the four 'independent' looking booleans, which cover 16 cases of which only 4 seem to be expected, plus a default case. Can any combination really be covered? Are several of these set in the same place or dependent on each other? If the default case is hit, what case(s) will usually be expected?
Just the fact that you are usually looking for one false value out of four rather than one true value suggests that four booleans might not be the right data structure.
Should you be using an enum which has five or so values, eg notCond1, notCond2, notCond3, notCond4 and notAny? If you do some special behavior when either cond1 or cond2 are false but not when both are, should you change the code that sets each one of them, to make sure that not both are false, and either raise an error or change the other one, according to what is acceptable?
Unless you really have constraints on the size of the code, I think it's worth adding some verbosity to make sure that data states which should never happen, can never happen. This improves both readability and error handling.
Does the code above run in a loop or nested loops, and if so, does every bool have the chance to change each time the loop is run, or can you move some of the checks outside of the inner loop?
Could it be that the separate code you call for each combination actually have something in common which can be factored out. You could be aiming for refactoring in several steps something like this (using only two bools for simplicity):
if (cond1 && !cond2) {
    SomethingGeneral();
    Cond1Specific();
}
if (cond2 && !cond1) {
    SomethingGeneral();
    Cond2Specific();
}

to
if (cond1 != cond2) {
    SomethingGeneral();
}
if (cond1) {
    Cond1Specific();
}
if (cond2) {
    Cond2Specific();
}

to
if (MoreThanOneModeSet()) {
    break; // or throw?
}
SomethingGeneral();
if (mode == Mode1) {
    Cond1Specific();
}
if (mode == Mode2) {
    Cond2Specific();
}

Most of the suggestions above should probably end up leading you towards @amit's very important and correct solution. If you really, really don't see any of them as valid, you should probably opt for @Apriori's neat and complete way of switching between all possible combinations.
If the length of your code and your right to share it allow, you should also try posting a more complete snippet on codereview.stackexchange.com, the suggestions you get there will have a slightly different focus and hopefully be complementary to the help on SO.

A: You don't say anything about the complexity of your conditions.  That would be a key deciding factor for me.
I'll ignore the 'faster' for now.  I'll get back to that later.
Consider Servant Pattern or  Strategy Pattern if:

*

*your if-elseif pattern holds up for all conditions

*'state' being used in the conditions is small, or can be refactored into a 'state object/struct', which makes it easier to pass into a function

*the list of conditions is much longer and/or complex than you include here

code:
class CondState {
  int x;
  int y;

  // I'd use bool? or Lazy<bool> in C# but if you don't have
  // those constructs use a simple tri-state enum.
  // Unknown = 0 is not yet evaluated
  // True    = 1
  // False   = 2
  TriState cond1Cache = 0;
  TriState cond2 = 0;
  TriState cond3 = 0;
}

function Rule1(ref CondState state) : bool // returns true when done
{
  if (... first complex condition) {
    ... do complex action
    return true;
  }
  return false;
}

function Rule2(ref CondState state) : bool
function Rule3(ref CondState state) : bool
...
function Rule40(ref CondState state) : bool // returns true when done

// --- in your original function
// build state object
var state = {}

// build the list of rules: a list of function pointers (C)
// or function objects (js/node/python)
var rules = [Rule1, Rule2, Rule3 ..., Rule40]

foreach (r in rules) {
  if (rule(state))
    break;
}

This is much cleaner code to 'execute' the rules.  It makes it simple and cleaner to:

*

*lazy-evaluate conditions

*cache conditions

*have different lists of rules (rare, but powerful)

Finally, let me get back to performance.  If performance is important this only makes sense if part of the conditional logic overwhelms the lower-level performance concerns.  Of course this adds OO overhead and you have to allocate the list (to hold the function refs).  But this is a step toward larger OO patterns: Strategy Pattern or Visitor Pattern, which I see as the 'cool' solution to this problem once you get beyond trivial samples (say more than 10 complex conditions).


text:
Q: A heap has been corrupted on realloc() I am trying to write a common function to resize and concatenate strings but on calling realloc() a runtime exception occurs stating a heap has been corrupted.
//two string pointer initialized with malloc()
wchar_t* stream;
wchar_t* toAdd;

stream = (WCHAR *)malloc(sizeof(wchar) );
toAdd= (WCHAR *)malloc(sizeof(wchar) );

//function declaration
int ReallocStringCat(wchar_t *, const wchar_t *);

//
int ReallocStringCat(wchar_t *dest,const  wchar_t *source)
{
    //below line throws a heap corrupt exception
    *dest =(wchar_t) realloc(dest, wcslen(dest) + wcslen(source) + 1);
    return  wcscat_s(stream,wcslen(dest) + wcslen(source) + 1, source);
}

I"m sure that I'm wrong somewhere in using with pointers and addresses but not able to figure out.
Also is there any inbuilt function like mutable classes available in Visual Studio 2012 C++ for native Win32 C++ applications without any CLR/MFC/ATL libraries?

A: You need to provide byte size instead of number of wchar_t into realloc:
dest =(wchar_t *) realloc(dest, (wcslen(dest) + wcslen(source) + 1)*sizeof(wchar_t ));

A: *dest =(wchar_t) realloc(dest, wcslen(dest) + wcslen(source) + 1);

should be
dest =(wchar_t*) realloc(dest, sizeof(wchar_t ) * ( wcslen(dest) + wcslen(source) + 1) );

You are also creating a memory leak since dest is being changed and not returned by function.


text:
Q: Can't connect to to siteground database with SQL I'm trying to connect to my siteground native database, but I'm getting this error:

ER_ACCESS_DENIED_ERROR: Access denied for user
'root'@'cpc1234569-man6-2-1-cust215.7-1.cable.virginm.net' (using
password: YES)

when I try to make a query. I'm connecting via mySQL's VSCode plugin.
I've entered my public IP address in to Siteground's remote access host section, but I'm still being denied permission. Any ideas?

A: I solved it by creating a new database access account within the siteground tools page. There must have been something wrong with the credentials of the previous account passed on to me by my colleague. It worked smoothly from a new account.


text:
Q: Error when sending e-mail from Keycloak with StartTLS option enabled Keycloak run in Kubernetes via helm chart. With disabled SSL and enables StartTLS (it's our mail server requests) there is error:
14:26:54,545 ERROR [stderr] (default task-8)    ... 84 more
14:26:54,545 ERROR [stderr] (default task-8) Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
14:26:54,545 ERROR [stderr] (default task-8)    at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:439)
14:26:54,545 ERROR [stderr] (default task-8)    at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:306)
14:26:54,545 ERROR [stderr] (default task-8)    at java.base/sun.security.validator.Validator.validate(Validator.java:264)
14:26:54,545 ERROR [stderr] (default task-8)    at java.base/sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:313)
14:26:54,545 ERROR [stderr] (default task-8)    at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:222)
14:26:54,545 ERROR [stderr] (default task-8)    at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:129)
14:26:54,545 ERROR [stderr] (default task-8)    at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:629)
14:26:54,545 ERROR [stderr] (default task-8)    ... 98 more
14:26:54,545 ERROR [stderr] (default task-8) Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
14:26:54,546 ERROR [stderr] (default task-8)    at java.base/sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
14:26:54,546 ERROR [stderr] (default task-8)    at java.base/sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
14:26:54,546 ERROR [stderr] (default task-8)    at java.base/java.security.cert.CertPathBuilder.build(CertPathBuilder.java:297)
14:26:54,546 ERROR [stderr] (default task-8)    at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:434)
14:26:54,546 ERROR [stderr] (default task-8)    ... 104 more
14:26:54,547 ERROR [org.keycloak.services.resources.admin.RealmAdminResource] (default task-8) Failed to send email
 javax.mail.MessagingException: Could not convert socket to TLS;
  nested exception is:
        javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

A: Most probably the reason is, that the Java Virtual Machine (JVM) is not trusting your Mailservers Certificate (maybe self-signed?)
A solution can be to manually create a truststore containing this certificate
see multiple answers about creating a filling a truststore
e.g. How to import a .cer certificate into a java keystore?
This keystore now need to mounted into keycloak container and passed to the JVM as JAVA_OPTS parameter.
-Djavax.net.ssl.trustStore=/loc/in/container/truststore.jks
-Djavax.net.ssl.trustStorePassword=changeit

Depending on the helm chart you are using the solution varies.
E.g. with Codecentric-Keycloak Chart you set the JVM settings here
https://github.com/codecentric/helm-charts/tree/master/charts/keycloak#jvm-settings
and mount the keystore with help of extraVolumeMounts/extraVolumes


text:
Q: Haskell - How to construct a program which will read some setting files? According to the introduction about ReaderT , I can only find:
ReaderT Env IO String

And it means
...is a computation which involves reading values from some environment
of type Env (the semantics of Reader, the base monad) and performing some
IO in order to give a value of type String.

So the order of execution will become
1. ( Already has ) some environment values          -- ReaderT Env
2. Do `IO` accroding to these pre-existing values   -- IO a
3. Use the `IO a` values to do more computations    -- IO b...z

This will requests our program has some pre-existing values as the environment, but I thought most of program need to load these environment values. Such like the database URL, debugging switcher or anything else.
Thus, we have an inverse order of execution, and which is illegal according to the Monad stack:
1. Do some `IO` to load environment settings        -- IO a first !!
2. Do more `IO` according to these settings         -- fill the env and do IO

The monad stack will become:
IOT Env ReaderT Env

This is illegal because the IO monad can't be the base monad in monad stack. So, is there a proper way to initialize my program with external setting files ?
PS1. I noticed that the xmonad compile it's settings as a part of program. I'm still not sure whether this is the only way to "load" settings...

A: First, the order of monads in the monad stack doesn't have anything to do with the order of actions that you're going to perform.
Second, you probably don't even need a stack here.
A typical program that deals with configuration is structured in the following way:
data Config = ...

readConfig :: IO Config
readConfig = do
    text <- readFile "~/.config"
    let config = ... -- do some parsing here
    return config

meat :: Reader Config Answer
meat = do
    -- invoke some operations, which get config automatically through the
    -- monad

main = do
    config <- readConfig
    let answer = runReader meat config
    print answer

You need a monad stack only if meat itself needs to perform some IO (apart from reading the config). In that case, you'd have
meat :: ReaderT Config IO Answer
meat = ...

main = do
    config <- readConfig
    answer <- runReaderT meat config
    print answer


text:
Q: Getting numbers from parse.com object in Android I have an object/list coming from parse.com(using parse sdk) and receive both strings and numbers. While I am able to fetch strings I don't know how to fetch numbers.
This works fine for string as driver:
ParseObject u = (ParseObject)scoreList.get(i);
    String truckName;
 truckName = u.getString("driver").toString();

How do I get the number assuming my "xcor" (assume another property such as "driver") is a number not string.

A: Maybe I don't understand your question perfectly, but isn't this:
double xcor = u.getDouble("xcor");

just what you need?
(alternatively if you store integer instead of a double you can use int otherVariable = u.getInt("otherVariable");)


text:
Q: Failed to build multi broker kafka with wurstmeister/kafka docker I tried several docker-compose.yml to build kafka cluster with wurstmeister docker image on my owner server but still failed so far.
Currently, my docker-compose.yml is:
version: "2"
services:
  zookeeper:
    image: wurstmeister/zookeeper
    ports:
      - "2181:2181"
  kafka1:
    image: wurstmeister/kafka
    ports:
      - "9095:9092"
    environment:
      KAFKA_ADVERTISED_LISTENERS: INSIDE://:9092,OUTSIDE://10.227.76.112:9095
      KAFKA_LISTENERS: INSIDE://:9092,OUTSIDE://:9095
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
  kafka2:
    image: wurstmeister/kafka
    ports:
      - "9096:9093"
    environment:
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: INSIDE://:9093,OUTSIDE://10.227.76.112:9096
      KAFKA_LISTENERS: INSIDE://:9093,OUTSIDE://:9096
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
  kafka3:
    image: wurstmeister/kafka
    ports:
      - "9097:9094"
    environment:
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: INSIDE://:9094,OUTSIDE://10.227.76.112:9097
      KAFKA_LISTENERS: INSIDE://:9094,OUTSIDE://:9097
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock

After starting the containers using docker-compose, all container are up:

While I tried to connect to my kafka(producing a mocked message) cluster outside the server by Java API, the errors are like
16:14:23.027 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient - [Producer clientId=producer-1] Initialize connection to node 10.227.76.112:9094 (id: -1 rack: null) for sending metadata request
16:14:23.027 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient - [Producer clientId=producer-1] Initiating connection to node 10.227.76.112:9094 (id: -1 rack: null) using address /10.227.76.112
16:14:23.044 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.common.network.Selector - [Producer clientId=producer-1] Connection with /10.227.76.112 disconnected
java.net.ConnectException: Connection refused
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:716)
    at org.apache.kafka.common.network.PlaintextTransportLayer.finishConnect(PlaintextTransportLayer.java:50)
    at org.apache.kafka.common.network.KafkaChannel.finishConnect(KafkaChannel.java:219)
    at org.apache.kafka.common.network.Selector.pollSelectionKeys(Selector.java:530)
    at org.apache.kafka.common.network.Selector.poll(Selector.java:485)
    at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:544)
    at org.apache.kafka.clients.producer.internals.Sender.runOnce(Sender.java:325)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:240)
    at java.lang.Thread.run(Thread.java:748)
16:14:23.045 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient - [Producer clientId=producer-1] Node -1 disconnected.
16:14:23.045 [kafka-producer-network-thread | producer-1] WARN org.apache.kafka.clients.NetworkClient - [Producer clientId=producer-1] Connection to node -1 (/10.227.76.112:9094) could not be established. Broker may not be available.
16:14:23.045 [kafka-producer-network-thread | producer-1] WARN org.apache.kafka.clients.NetworkClient - [Producer clientId=producer-1] Bootstrap broker 10.227.76.112:9094 (id: -1 rack: null) disconnected

BTW, the is no firewall opened on my server.