text:
Q: unable to create table using subreports in jasper reports I am using report book in Jasper reports and in that, I have to create a Content-report (same as sub-report) containing a table.I am using JRBeanCollectionDataSource.
when I compile and run the sub-report individually, It works perfectly.
but when I run whole Report book, then it won't even print that Subreport, other sub reports will be printed as expected.
I am sure that, I am missing some minor settings. Because in report book, I am using chart, crosstab  they are working fine. but the only problem is with that table.
this is my subreport jrxml:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.3.0.final using JasperReports Library version 6.3.0  -->
<!-- 2016-08-02T13:49:19 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="sub_filter_table" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="5ec68712-81e7-4231-85ad-a535169f9480">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
    <property name="net.sf.jasperreports.print.create.bookmarks" value="true"/>
    <style name="Table_TH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
            <topPen lineWidth="0.5" lineColor="#000000"/>
            <leftPen lineWidth="0.5" lineColor="#000000"/>
            <bottomPen lineWidth="0.5" lineColor="#000000"/>
            <rightPen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="Table_CH" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
            <topPen lineWidth="0.5" lineColor="#000000"/>
            <leftPen lineWidth="0.5" lineColor="#000000"/>
            <bottomPen lineWidth="0.5" lineColor="#000000"/>
            <rightPen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="Table_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
            <topPen lineWidth="0.5" lineColor="#000000"/>
            <leftPen lineWidth="0.5" lineColor="#000000"/>
            <bottomPen lineWidth="0.5" lineColor="#000000"/>
            <rightPen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <subDataset name="filterTableDataset" uuid="5e16eed0-53ee-4e32-9078-a3f75f05ca4e">
        <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
        <parameter name="filterTableDataSource" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
        <queryString>
            <![CDATA[]]>
        </queryString>
        <field name="database" class="java.lang.String"/>
        <field name="systemNumber" class="java.lang.String"/>
        <field name="channels" class="java.lang.String"/>
        <field name="from" class="java.lang.String"/>
        <field name="to" class="java.lang.String"/>
        <field name="keep" class="java.lang.String"/>
        <field name="description" class="java.lang.String"/>
    </subDataset>
    <parameter name="filterTableDataSource" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
    <parameter name="filter_table_title" class="java.lang.String">
        <defaultValueExpression><![CDATA["Filter logs"]]></defaultValueExpression>
    </parameter>
    <parameter name="SITE" class="java.lang.String"/>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <background>
        <band splitType="Stretch"/>
    </background>
    <summary>
        <band height="342">
            <componentElement>
                <reportElement x="0" y="110" width="555" height="100" uuid="f7bcc7fb-0f93-41a1-96fd-a17d82997667">
                    <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.VerticalRowLayout"/>
                    <property name="com.jaspersoft.studio.table.style.table_header" value="Table_TH"/>
                    <property name="com.jaspersoft.studio.table.style.column_header" value="Table_CH"/>
                    <property name="com.jaspersoft.studio.table.style.detail" value="Table_TD"/>
                    <property name="com.jaspersoft.studio.components.autoresize.proportional" value="true"/>
                    <property name="com.jaspersoft.studio.components.autoresize.next" value="true"/>
                </reportElement>
                <jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
                    <datasetRun subDataset="filterTableDataset" uuid="c89753d2-101b-4cbc-a23b-0c83bd725c45">
                        <parametersMapExpression><![CDATA[$P{filterTableDataSource}]]></parametersMapExpression>
                        <datasetParameter name="filterTableDataSource">
                            <datasetParameterExpression><![CDATA[$P{filterTableDataSource}]]></datasetParameterExpression>
                        </datasetParameter>
                        <dataSourceExpression><![CDATA[$P{filterTableDataSource}]]></dataSourceExpression>
                    </datasetRun>
                    <jr:column width="73" uuid="1f2db4a6-020e-47f7-baf2-3544dcb71121">
                        <jr:columnHeader style="Table_CH" height="30">
                            <staticText>
                                <reportElement x="0" y="0" width="73" height="30" uuid="14c78a1d-169f-4a55-9a9c-754fa02fd371"/>
                                <text><![CDATA[database]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="Table_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="73" height="30" uuid="4e86a802-0103-43ea-85fb-ae227412b60f"/>
                                <textFieldExpression><![CDATA[$F{database}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="73" uuid="b21d7484-4645-4759-b3a1-e0dc7dc2cdf9">
                        <jr:columnHeader style="Table_CH" height="30">
                            <staticText>
                                <reportElement x="0" y="0" width="73" height="30" uuid="a74174db-9266-4a63-8571-3e6b7a5e671a"/>
                                <text><![CDATA[systemNumber]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="Table_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="73" height="30" uuid="06a5dd33-40a5-48dd-93b2-ed21a86894b1"/>
                                <textFieldExpression><![CDATA[$F{systemNumber}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="73" uuid="672670d2-071a-4987-b9b5-b9ccec62ffcd">
                        <jr:columnHeader style="Table_CH" height="30">
                            <staticText>
                                <reportElement x="0" y="0" width="73" height="30" uuid="02b4645f-4e30-40f7-8229-bbb01dd3fc94"/>
                                <text><![CDATA[channels]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="Table_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="73" height="30" uuid="94eb42f5-b3f2-4592-b5f7-5a4cc48f1eec"/>
                                <textFieldExpression><![CDATA[$F{channels}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="68" uuid="83e9f896-849b-4d96-bde7-c35f73824100">
                        <jr:columnHeader style="Table_CH" height="30">
                            <staticText>
                                <reportElement x="0" y="0" width="68" height="30" uuid="30b2d1c9-4cd0-4358-9df9-aa7fa99c22a2"/>
                                <text><![CDATA[from]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="Table_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="68" height="30" uuid="64748c55-8224-4ba2-8275-13c13a2b66a5"/>
                                <textFieldExpression><![CDATA[$F{from}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="54" uuid="896e3191-2c4a-428d-a65f-658375611c01">
                        <jr:columnHeader style="Table_CH" height="30">
                            <staticText>
                                <reportElement x="0" y="0" width="54" height="30" uuid="34bfb207-d3e0-4343-8a7b-69aa6b15e881"/>
                                <text><![CDATA[to]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="Table_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="54" height="30" uuid="65268f63-f9c2-487f-9de6-b6045c3f8f33"/>
                                <textFieldExpression><![CDATA[$F{to}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="59" uuid="ca8721df-5260-41c3-b549-19f7478831d2">
                        <jr:columnHeader style="Table_CH" height="30">
                            <staticText>
                                <reportElement x="0" y="0" width="59" height="30" uuid="558d37f8-a6e0-49a0-948f-3a8352c014ca"/>
                                <text><![CDATA[keep]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="Table_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="59" height="30" uuid="5d15ec66-40c1-4b91-b330-639783230764"/>
                                <textFieldExpression><![CDATA[$F{keep}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="155" uuid="94e61aed-be5f-4d95-9342-0a4a129e7fb8">
                        <jr:columnHeader style="Table_CH" height="30">
                            <staticText>
                                <reportElement x="0" y="0" width="155" height="30" uuid="737886b1-2568-4840-8d59-b6bef0bb46ed"/>
                                <text><![CDATA[description]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="Table_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="155" height="30" uuid="f451bec1-8ae6-4ee5-b4ca-fb337b5c94fb"/>
                                <textFieldExpression><![CDATA[$F{description}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                </jr:table>
            </componentElement>
            <textField bookmarkLevel="2">
                <reportElement x="140" y="20" width="170" height="30" uuid="af7d5b5d-e209-4417-9830-0994cd6d5b39"/>
                <textFieldExpression><![CDATA[$P{filter_table_title}]]></textFieldExpression>
                <anchorNameExpression><![CDATA[$P{filter_table_title}]]></anchorNameExpression>
            </textField>
            <textField>
                <reportElement x="436" y="46" width="100" height="30" uuid="924b35b3-34f5-47ad-b404-9483044489b2"/>
                <textFieldExpression><![CDATA[$P{SITE}]]></textFieldExpression>
            </textField>
        </band>
    </summary>
</jasperReport>

main Report-book jrxml
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.3.0.final using JasperReports Library version 6.3.0  -->
<!-- 2016-08-02T13:50:30 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Abstract_Book" pageWidth="595" pageHeight="842" sectionType="Part" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="30" bottomMargin="30" whenResourceMissingType="Error" uuid="d2716064-8ae4-40cf-a575-33afba400e3a">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
    <property name="net.sf.jasperreports.print.create.bookmarks" value="true"/>
    <property name="com.jaspersoft.studio.book.group.cover.header" value="Cover and Table of Contents"/>
    <property name="com.jaspersoft.studio.book.group.cover.footer" value="Backcover"/>
    <parameter name="SUBREPORT_DIR" class="java.lang.String"/>
    <parameter name="Name" class="java.lang.String">
        <parameterDescription><![CDATA[]]></parameterDescription>
    </parameter>
    <parameter name="XYChartDataSource" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
    <parameter name="tableDataSource" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
    <parameter name="IMAGE_DIR" class="java.lang.String"/>
    <parameter name="filterTableDataSource" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
    <parameter name="externalDataSource" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
    <parameter name="REPORT_TYPE" class="java.lang.String"/>
    <parameter name="SITE" class="java.lang.String"/>
    <parameter name="CMS" class="java.lang.String"/>
    <parameter name="OPPORTUNITY_ID" class="java.lang.String"/>
    <parameter name="windTableDataSource" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <group name="cover">
        <groupHeader>
            <part uuid="7aed05b9-1301-4a53-b47e-34289560bc0c">
                <p:subreportPart xmlns:p="http://jasperreports.sourceforge.net/jasperreports/parts" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/parts http://jasperreports.sourceforge.net/xsd/parts.xsd">
                    <subreportParameter name="Name">
                        <subreportParameterExpression><![CDATA[$P{Name}]]></subreportParameterExpression>
                    </subreportParameter>
                    <subreportParameter name="externalDataSource">
                        <subreportParameterExpression><![CDATA[$P{externalDataSource}]]></subreportParameterExpression>
                    </subreportParameter>
                    <subreportParameter name="REPORT_TYPE">
                        <subreportParameterExpression><![CDATA[$P{REPORT_TYPE}]]></subreportParameterExpression>
                    </subreportParameter>
                    <subreportParameter name="CMS">
                        <subreportParameterExpression><![CDATA[$P{CMS}]]></subreportParameterExpression>
                    </subreportParameter>
                    <subreportParameter name="SITE">
                        <subreportParameterExpression><![CDATA[$P{SITE}]]></subreportParameterExpression>
                    </subreportParameter>
                    <subreportParameter name="OPPORTUNITY_ID">
                        <subreportParameterExpression><![CDATA[$P{OPPORTUNITY_ID}]]></subreportParameterExpression>
                    </subreportParameter>
                    <subreportParameter name="IMAGE_DIR">
                        <subreportParameterExpression><![CDATA[$P{IMAGE_DIR}]]></subreportParameterExpression>
                    </subreportParameter>
                    <subreportExpression><![CDATA[$P{SUBREPORT_DIR}+"/Abstract_Book_cover.jasper"]]></subreportExpression>
                </p:subreportPart>
            </part>
            <part evaluationTime="Report" uuid="56ab525c-754f-4f48-a52c-7cc23934be3d">
                <property name="net.sf.jasperreports.bookmarks.data.source.parameter" value="REPORT_DATA_SOURCE"/>
                <p:subreportPart xmlns:p="http://jasperreports.sourceforge.net/jasperreports/parts" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/parts http://jasperreports.sourceforge.net/xsd/parts.xsd">
                    <subreportExpression><![CDATA[$P{SUBREPORT_DIR}+"/Abstract_Book_toc.jasper"]]></subreportExpression>
                </p:subreportPart>
            </part>
        </groupHeader>
        <groupFooter>
            <part uuid="88decbbe-63ad-45cc-9e03-5dadc50004d5">
                <p:subreportPart xmlns:p="http://jasperreports.sourceforge.net/jasperreports/parts" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/parts http://jasperreports.sourceforge.net/xsd/parts.xsd">
                    <subreportExpression><![CDATA[$P{SUBREPORT_DIR}+"/Abstract_Book_backcover.jasper"]]></subreportExpression>
                </p:subreportPart>
            </part>
        </groupFooter>
    </group>
    <detail>
        <part uuid="3d143dd6-5587-4c12-90f0-ff77f9d026af">
            <p:subreportPart xmlns:p="http://jasperreports.sourceforge.net/jasperreports/parts" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/parts http://jasperreports.sourceforge.net/xsd/parts.xsd">
                <subreportParameter name="SITE">
                    <subreportParameterExpression><![CDATA[$P{SITE}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="REPORT_DATA_SOURCE">
                    <subreportParameterExpression><![CDATA[$P{filterTableDataSource}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportExpression><![CDATA[$P{SUBREPORT_DIR}+"/sub_filter_table.jasper"]]></subreportExpression>
            </p:subreportPart>
        </part>
        <part uuid="5e668430-9acd-4835-be21-f4e2902ce33d">
            <p:subreportPart xmlns:p="http://jasperreports.sourceforge.net/jasperreports/parts" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/parts http://jasperreports.sourceforge.net/xsd/parts.xsd">
                <subreportParameter name="REPORT_DATA_SOURCE">
                    <subreportParameterExpression><![CDATA[$P{XYChartDataSource}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportExpression><![CDATA[$P{SUBREPORT_DIR}+"/sub_chart.jasper"]]></subreportExpression>
            </p:subreportPart>
        </part>
        <part uuid="0e5ec483-6a4d-4323-8cb8-850ca3cefe34">
            <p:subreportPart xmlns:p="http://jasperreports.sourceforge.net/jasperreports/parts" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/parts http://jasperreports.sourceforge.net/xsd/parts.xsd">
                <subreportParameter name="REPORT_DATA_SOURCE">
                    <subreportParameterExpression><![CDATA[$P{tableDataSource}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportExpression><![CDATA[$P{SUBREPORT_DIR}+"/sub_crosstab.jasper"]]></subreportExpression>
            </p:subreportPart>
        </part>
        <part uuid="f4249881-1728-4f1f-8c54-75fc7725f6f6">
            <p:subreportPart xmlns:p="http://jasperreports.sourceforge.net/jasperreports/parts" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/parts http://jasperreports.sourceforge.net/xsd/parts.xsd">
                <subreportParameter name="REPORT_DATA_SOURCE">
                    <subreportParameterExpression><![CDATA[$P{windTableDataSource}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportExpression><![CDATA[$P{SUBREPORT_DIR}+"/sub_wind_crosstab.jasper"]]></subreportExpression>
            </p:subreportPart>
        </part>
    </detail>
</jasperReport>

A: I did minor changes on Java side.
Instead of passing a JRBeanCollectionDataSource:
parameters.put(FILTER_TABLE_DATA_SOURCE, new JRBeanCollectionDataSource(filterList));

I have directly passed List as Parameter
parameters.put(FILTER_TABLE_DATA_SOURCE, filterList);

Master report
Create a Parameters like following
<parameter name="FILTER_TABLE_DATA_SOURCE" class="java.util.List"/>

Select the sub-report on MasterReport  and Go to Properties of subreport and set Datasource Expression as following:
and it will set $P{REPORT_DATA_SOURCE}
new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{FILTER_TABLE_DATA_SOURCE})

Sub Report
Firstly, I made a mistake by placing a table in Summary band.

Table should always be in Detail band

because fields inside table need to be iterated, that what detail band does.
create table as usual with fields which are in that List , but remember to use *$P{REPORT_DATA_SOURCE}*  as JRDatasource expression


text:
Q: CSS not being applied to XUL window HTML contents I'm working on a very simple Firefox extension that will log info and dynamically append them to a basic HTML table in a XUL window.
Everything works except for the CSS styling for the HTML table.  None of them are being applied. I read somewhere to add -moz-appearance: none; to the CSS, but it still doesn't work.  Does anyone see what is wrong with this set of XUL and CSS files?
XUL file
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://rmtagfinder/content/log_window/log_window.css" type="text/css"?>
<!DOCTYPE window SYSTEM "chrome://rmtagfinder/locale/translations.dtd">

<window id="rm-tag-finder-log-window"
    title="&rmtagfinder.app.name;"
    xmlns:html="http://www.w3.org/1999/xhtml"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

<vbox flex="1" style="overflow:auto" >

<html:table cellspacing="1" cellpadding="4" bgcolor="#CCCCCC" border="0" id="rm-tag-finder-log-window-html-table">
    <html:thead>
    <html:tr class="tbl_header">
        <html:td width="100">Time</html:td>
        <html:td width="100">Domain</html:td>
        <html:td width="200">Request Made</html:td>
        <html:td width="200">Referer</html:td>
        <html:td width="200">Decoded Info</html:td>
     </html:tr>
    </html:thead>
    <html:tbody></html:tbody>
</html:table>

</vbox>
</window>

CSS file
@import url("chrome://global/skin/");
@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");

.tbl_header {
    -moz-appearance: none;
   font-weight: bolder;
   font-family: Arial, Verdana, Helvetica;
   font-size: 8pt;
   color: #fcfcfc;
   background-color: #4F80AB;
}

tr {
    vertical-align: top;
}

td {
    vertical-align: top;
}

A: I got it working soon after, here's the solution.  I have to add in the following line to the CSS file so that it would recognize the CSS styles in the html namespace:
@namespace html url("http://www.w3.org/1999/xhtml");

A: You only need to override css styles using !important because when you import
@import url("chrome://global/skin/"); it already has some css styles applied on window.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Event Store using nosql performance considerations This may be more of a general NOSQL infrastructure question.
With an event sourcing system I'm saving Event documents to ravendb.
In my domain model there are multiple types of events, an basic example below:
public abstract class Event
{
    public Guid AggregateId { get; set; }

    public Event(Guid aggregateId)
    {
        AggregateId = aggregateId;
    }
}

public class NewPersonEvent : Event
{
    public string Name { get; set; }

    public NewPersonEvent(Guid id, string name) : Base(id)
    {
        Name = name;
    }
}

public class NewOrderEvent : Event
{
    public DateTime OrderDate { get; set; }
    public double OrderCost { get; set;}

    public NewOrderEvent(Guid id, DateTime date, double cost) : Base(id)
    {
        OrderDate = date;
        OrderCost = cost;
    }
}

An event is persisted as an Event document no matter what type of aggregate the event is from.
Is this the best approach to use one Document type in ravendb for all events. Or is there any benefits of grouping the document types per aggregate
Instead of having just 'Event' documents, to instead have 'PersonEvent' documents and 'OrderEvent' documents.
What are the pros and cons of each of the two approaches, specifically is there any performance issues?

A: Are you overriding the default tag name for events as...
docStore.Conventions.FindTypeTagName = type => typeof(Event).IsAssignableFrom(type) ? DocumentConvention.DefaultTypeTagName(typeof(Event)) : DocumentConvention.DefaultTypeTagName(type);

Then whenever you do a query on Event it just works and retrieves all events.
session.Query<Event>()
If so, you can shoot yourself in the foot because if you just want a subset of the events and you do this session.Query<NewPersonEvent>() it's going to retrieve all the events since you overrode the tag convention in the beginning.
You can still do it another way but it wouldn't be as straight forward (e.g. having an enum for the event type and filter by the enum).
I would vote to NOT override default RavenDB behavior, leave the different event types as their own doc collections, and simply use a multi-map index.
The Raven docs state that static indexes are preferred over dynamic indexes so it shouldn't be a performance concern. docs:
If you don't mess with the tag convention, but you could create more indexes for a sub-set of the events, create map/reduce indexes to aggregate counts per event type, and much more.
The index would be a multi-map index and you have 2 flavors you can choose from.
Option 1
    public class Events_All : AbstractMultiMapIndexCreationTask
    {
        public Events_All()
        {
            AddMap<NewPersonEvent>(newPersonEvents =>
                from newPersonEvent in newPersonEvents
                select new
                {
                    Id   = newPersonEvent.AggregateId
                });

            AddMap<NewOrderEvent>(newOrderEvents =>
                from newOrderEvent in newOrderEvents
                select new
                {
                    Id   = newOrderEvent.AggregateId
                });
        }

    }

Option 2 (Reflection)
public class Events_All2 : AbstractMultiMapIndexCreationTask
{
    public Events_All2()
    {
        AddMapForAll<Event>(events =>
            from @event in events
            select new
            {
                Id   = @event.AggregateId
            });
    }
}

Here's an example test using the RavenDB.Tests.Helpers and Shouldly NuGet packages. It's using the first example index but you can modify it to use the second as well.
    public class MultimapIndexTest : RavenTestBase
    {
        private readonly Random _random = new Random();

        [Fact]
        public void GetAll_HasBoth_Success()
        {
            //Arrange
            const string personName = "Jimmy";
            double randomCost = _random.Next();

            var event1 = new NewPersonEvent(Guid.NewGuid(), personName);
            var event2 = new NewOrderEvent(Guid.NewGuid(), DateTime.Now, randomCost);

            using (var docStore = NewDocumentStore())
            {
                docStore.ExecuteIndex(new Events_All());

                using (var sesion = docStore.OpenSession())
                {
                    sesion.Store(event1);
                    sesion.Store(event2);
                    sesion.SaveChanges();
                }

                docStore.WaitForStaleIndexesToComplete();

                //Act
                var events = GetAll(docStore).ToList();

                //Assert
                events.ShouldNotBeEmpty();
                events.Count().ShouldBe(2);

                var newPersonEvent = events.FirstOrDefault(x => x is NewPersonEvent) as NewPersonEvent;
                newPersonEvent.ShouldNotBe(null);
                newPersonEvent.Name.ShouldBe(personName);

                var newOrderEvent = events.FirstOrDefault(x => x is NewOrderEvent) as NewOrderEvent;
                newOrderEvent.ShouldNotBe(null);
                newOrderEvent.OrderCost.ShouldBe(randomCost);
            }
        }

        private IEnumerable<Event> GetAll(DocumentStore docStore)
        {
            using (var session = docStore.OpenSession())
            {
                return session.Query<Event, Events_All>();
            }
        }
    }


text:
Q: How do Instance Methods work in Mongoose? I'm working on a course in building a REST API with Mongoose. We have a question and an answer document and they're showing how to update the answers to the questions collection using an Instance Method on the Answers Schema. I'm not able to follow along at this point because, i can't tell what the callbacks being passed in as arguments are for and what they're exactly doing to the schema.
AnswerSchema.method("update", function(updates, callback) {

      object.assign(this, updates, {updatedAt: newDate()});
      this.parent().save(callback);

A: Mongoose allows you to work with either callbacks or Promises, so you must choose one for your query to get invoked.
If you specify a callback - the query will be executed immediately and the callback will be invoked with the result right after it's done.
If you use Promises, then you need to explicitly call .then() at the end of your query to invoke it.
Otherwise, if you don't care about the result you can call .exec() which also returns a promise, but does not require handling.


text:
Q: How to enable python interactive mode in cygwin? I like python in interactive mode when on linux. However on cygwin, the interactive mode doesn't start. I don't see the ">>>" prompt and whatever I enter doesn't result in anything.
Solved: I figured out the problem from the answers below. I was using a windows installation of python and it needs -i option to start in interactive mode.

A: Try passing the -i flag to Python.
I've experienced this very same thing, as have others. There seems to be an issue with cygwin's ability to operate interactively with native-Windows applications (including Python.exe). If you can, install the cygwin version of Python via cygwin's package management, as it doesn't have this interactivity problem.

A: I use it all the time.
$ python
Python ****** (********)
**********************
Type "help", "copyright", "credits" or "license" for more information.
>>> "It works"
'It works'
>>>

If you supply a file name, or anything like that, it won't go into interactive mode by default.

A: A Windows install of ActiveState python won't enter interactive mode, AND it will be run instead of cygwin Python even if you have cygwin Python installed, because ActiveState python inserts its bin path at the front of your Windows System PATH environment variables.
I solved it by going (in Windows) to Control Panel->System -> Advanced system settings-> Environment variables, choosing PATH, selecting Edit, and cut-pasting all the ActiveState entries from the front to the back of the PATH list.


text:
Q: Bootstrap Login form in navbar in laravel I'm using Bootstrap 4 and Laravel 6.
Instead of having a different Login page,I want to let user login through form in navbar.
This is my form.
  Login form in navbar
My issue is when the user hit login, he redirects to a /login View offered by Laravel and error appears 419 | Page Expired.
I tried to override Laravel's code but the issue is I' m confused either I need to change the form action ,write something in LoginController or something in Route.
What i wish is the registered user will simply put in credentials and successfully login. After login he will redirect to the same page(homepage) but with logout button.
header.php

              @guest
              <form method="post" action="{{ route('login') }}">

                    <input id="email" type="email" class="form-control form-control-sm @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus placeholder="email address">

                    @error('email')

                            {{ $message }}

                    @enderror

                    <input id="password" type="password" class="form-control form-control-sm @error('password') is-invalid @enderror" name="password" required autocomplete="current-password" placeholder="password">

                    @error('password')

                            {{ $message }}

                    @enderror

                    <button type="submit" class="btn btn-primary login">{{ __('Login') }}</button>

              </form>

            @else

                      {{ Auth::user()->name }}

                          {{ __('Logout') }}

                      <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                          @csrf
                      </form>

            @endguest

Route.php
    Route::group([ 'middleware' => ['web']], function(){

      Route::get('/',[

        'uses' => 'niceActionController@getActionController'
      ]);

      Route::get('/{url}',  [
        'uses' => 'niceActionController@getPages',
        'as' => 'getURL'
      ]);

      Auth::routes(['verify' => true]);

    /***********Group Routes******************/
      Route::group(['prefix' => 'products'] , function(){

        Route::get('/{product}',  [
          'uses' => 'niceActionController@getProductPages',
          'as' => 'productPage'
        ]);

      });

});

LoginController.php
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    use AuthenticatesUsers;

      protected $redirectTo = '/home';

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}


text:
Q: How does Phil Tippett—the stop-motion artist for the original "Star Wars" trilogy—feel about the 1997 CGI reworking to the films? Phil Tippett is a fairly well known—and well regarded—stop motion artist and visual effects supervisor—whose big break happened when he was hired by George Lucas in 1975 to create the special effects for the stop-motion holographic chess game ("Dejarik") seen in the Millennium Falcon in Star Wars (1977).
His work with Lucasfilm and ILM (Industrial Light and Magic) continued with his use of stop motion animation to bring the Tauntauns and AT-AT walkers to life in The Empire Strikes Back (1980) as well as creating the Rancor beast and animating parts of the speeder bike chase on Endor for Return of the Jedi (1983).
Knowing this, how did he feel about the primarily CGI-based visual changes, additions, modifications and tweaks George Lucas made to the original trilogy of Star Wars films in 1997?

A: According to a 2011 Q&A session Phil Tippett participated in at the Alamo Drafthouse in Austin, TX prior to a screening of Jurassic Park (1993), his feelings on the new Star Wars "Special Edition" additions are as follows:

They're sh-t.

He went on to elaborate on his feelings towards the Mos Eisley spaceport scenes to express that he didn't think what was added was at all necessary and how he loved Lucas' original, "Sergio Leone"-like approach to shooting Mos Eisley as a minimal, barren place and how now it's just:

Filled with a bunch of… CGI sh-t.

Elaborating further beyond the realm of CGI additions to Star Wars, he weighed in on Hollywood's latest obsession with 3D as well by stating:

3D is sh-t.

And derided motion capture on top of it stating:

Robert Zemeckis is the Devil incarnate […] the motion capture stage is
  where good directors go to die.


text:
Q: Performance of Reading and Writing to Database: Can it be faster? Basically this code that I've created uses super csv to read in a csv file, of which about half of them need to call the data base to then update a value. The high level description of code is that I read a csv file in row by row and if certain checks are successful then it query's to update the database with the new value.
I was told to do some basic load testing, never used any kind of tools before, but after using google chrome developer to get the upload times and the records amount I collected the following data.

How accurate is google chrome developer tool when using it to measure time? because 2.68 seconds seems like a long time to read 18 records and update, 8? However, this seems to be roughly O(n log n ) right? Do you think it would be faster to do a only read and then a batch to database after? Would that be faster?
Anytime I query the database for existence of certain values, I use count and distinct, is there a more efficient way?
Any help would be greatly appreciated! here to learn all I can.

A: Chrome Developer Tools is quite accurate but it adds extra time you might not be really interested in like connect time and the time to render the page.
When it comes to load testing I think you should be rather simulating multiple users than adding more rows, however you can combine these approaches to see the outcome. The list of free and open source load testing tools can be found i.e. in Open Source Load Testing Tools: Which One Should You Use? article
With regards to "more efficient way" - we cannot state anything without seeing your code, I can only suggest considering using profiler tools for the programming language you're using and inspecting SQL query plan
If you cannot figure out what's wrong:

*

*For code review: https://codereview.stackexchange.com/

*For SQL : https://dba.stackexchange.com/


text:
Q: Highlight every other row of a table in a foreach loop and highlight columns depending on value of row I had a really long description written for my problem, but I've progressed and have managed to get it partially working... I basically want every other row in a table to be a different color - and to highlight certain rows if they meet a condition that I set.
foreach ($data as $row) {
    $style = null;
        while (($values = fgetcsv($handle, 0, '|')) !== false) {
                $comment_lines = $values[6];
                $priority      = $values[7];
                $time_worked   = $values[11];
                $var_X  = strpos($priority, '1');
                $var_C1 = strpos($comment_lines, 'CCB');
                $var_C2 = strpos($comment_lines, 'CEB');
                $var_U  = empty($time_worked);
        }

        if (empty($values[0]) && count($values) === 1) {
                continue;
        }
    if (strlen($var_X)) {
        echo '
';
        foreach ($values AS $index => $value) {
                echo '' . $value . '	' ;
        }
    } else if ($var_C1 !== false) {
        echo '
';
        foreach ($values AS $index => $value) {
                echo '' . $value . '	' ;
        }
    } else if ($var_C2 !== false) {
        echo '
';
        foreach ($values AS $index => $value) {
                echo '' . $value . '	' ;
        }
    } else if ($var_U !== false) {
        echo '
';
        foreach ($values AS $index => $value) {
                echo '' . $value . '	' ;
        }
    } else if ($odd) {
        $odd = !$odd;
        echo '
';
        foreach ($values AS $index => $value) {
                echo '' . $value . '	' ;
        }
    } else {
        $odd = !$odd;
        echo '
';
        foreach ($values AS $index => $value) {
                echo '' . $value . '	' ;
        }
    }
                echo '
';
}

Right now, only the 'every other' is working. I can't get the gradeX, gradeC and gradeU to show anything...
EDIT:
This is the working code, cheers.
while (($values = fgetcsv($handle, 0, '|')) !== false) {
        $style = null;
        $comment_lines = $values[6];
        $priority      = $values[7];
        $time_worked   = $values[11];
        $var_X  = strpos($priority, '1');
        $var_C1 = strpos($comment_lines, 'CCB');
        $var_C2 = strpos($comment_lines, 'CEB');
        $var_U  = empty($time_worked);

        if (empty($values[0]) && count($values) === 1) {
                continue;
        }

        if ($var_X !==false) {
                echo '
';
        } elseif ($var_C1 !== false) {
                echo '
';
        } elseif ($var_C2 !== false) {
                echo '
';
        } elseif ($var_U !== false) {
                echo '
';
        } else {
                //nothing
        }

        foreach ($values as $index => $value) {
                echo '' . $value . '	';
        }

        echo '
';
}

A: In your loop you need to add a counter to identify whether you're currently on an 'even' or an 'odd' iteration, and then add either class 'odd' or 'even' into the  as you output it.
There's a related question already on here that covers that here: php: how to add odd/even loop in array
The other parts should be fairly easy by using if statements to check if the relevant data exists or not.
For example, strlen will tell you whether a variable has length or not (to put out 'gradeX'), and strpos will allow you to check if a varibale contains a string (for 'gradeC').

A: If you can target IE later than IE8 and forget about IE8, you can use CSS3:
 tr:nth-child(odd) {
     background-color: #EEEEEE;
 }

 tr:nth-child(even) {
     background-color: #FFFFFF;
 }


text:
Q: Launcher shows up on the wrong monitor I have nvidia drivers and dual monitors.

It worked fine in 11.10 but since todays updates, my unity "launcher" is only on right monitor.

On vanila ubuntu display settings it recognizes only one monitor. And it looks like this:

So, the questions might be:

*

*Why Ubuntu's "Displays" shows only one monitor where nvidia drivers shows two? I assume nvidia overwrites?

*After Lot of playing between these two settings, I can't manage to move menu launcher to left screen. Any suggestions?

A: Maybe it's a bug. Have you tried the Ubuntu2d setting on the Ubuntu button at login?

A: As a workaround, you could try physically plugging the monitors into the opposite ports on your video card.

A: I had the same issue and what solved it for me was first selecting the left screen in the 'X Server Display Configuration' and setting the position to 'Right of'.
This resulted in the launcher at the correct position on the virtual desktop but with my displays physically swapped, so I simply physically plugged the monitors in the opposite ports of my video card.
I guess the bug is that the launcher is always displayed on the monitor that is physically plugged in in the first port of the video card, ignoring the position you configured in the Nvidia tool.
I hope this works for you.

A: I'm facing the same bug (I think it is).
OS: Ubuntu 12.04
Graphic Card: GeForce 310M
On dual monitor configuration the unity launcher is on right (wrong) screen.
I tentatively solve this by setting the primary monitor's position to Right of and then setting it back to Absolute.
I do this on every reboot (!).
Furthermore I set this via gconf-editor:
/apps/compiz-1/plugins/unityshell/screen0/options/num_launchers=1

This forces the launcher to appear in only one monitor (otherwise for me it appears on both)
Naver had problems with Ubuntu 11.04
Hope this helps.
Edit:
Actually I use to set both monitor to Absolute with the right one positioned from the pixel width of the left one.
So, in my case:
1366x768  Absolute +0+0 Primary
1280x1024 Absolute +1366+0

A: I think it's because of your configuration. If you select "twinView" in nvidia-settings, for gnome displays tool it's like there's just one gigantic display.
Try the "separate x screens" option in nvidia-settings.

A: It appears this was a bug in Unity.
I've update last week and tried again, problem is fixed.
Thanks for all answers!

Edit:
After reading few comments, It seems I just got lucky, people still have same problem that I had.
Interesting thing is that I've changed computer and graphic card since I asked the question and it's still fixed for me :(


text:
Q: How to connect Backstage to Kubernetes cluster to discover pods I am trying to connect Backstage to a Kubernetes cluster deployed on EKS in order to discover pods and display them on the pages for their respective components. To connect to a cluster, Backstage needs a "cluster URL". Where can I find the cluster URL and port? Should I be able to connect to this cluster when running locally?
I am running Backstage locally on my machine and trying to connect to a deployed EKS cluster. Here is the configuration in my app-config.yaml:
kubernetes:
  serviceLocatorMethod:
    type: 'multiTenant'
  clusterLocatorMethods:
    - type: 'config'
      clusters:
        - url: http://111.11.1.1:1111
          name: my-cluster-eks
          authProvider: 'aws'
          skipTLSVerify: true
          skipMetricsLookup: true

auth:
  environment: 'development'
  providers:
    aws:
      development:
        accessKeyId: ${AWS_ACCESS_KEY_ID}
        secretAccessKey: ${AWS_SECRET_ACCESS_KEY}


text:
Q: How to mock a method within an action method in ASP.NET MVC? I want to mock (with MOQ) the method CheckCredentials which is part of the LoginManager class.
public ActionResult Login(string username, string password)
            {
                if (lm.CheckCredentials(username, password) != 0)
                    return RedirectToAction("Index", "Login");

                return RedirectToAction("Index", "Home");
            }

Testmethod
public void TestMethod1()
    {
        Mock<LoginManager> mock = new Mock<LoginManager>();

        mock.Setup(x => x.CheckCredentials("", "")).Returns(0);

        HomeController homeController = new HomeController();

        RedirectToRouteResult ar = homeController.Login("", "") as RedirectToRouteResult;
        ...
    }

Now my problem is that I don't really now how to correctly mock that method. I have seen YT videos where the mock objects are passed as parameters but isn't that quite bad if I have to change the parameters of a method just to be able to create a unit test? Is that the only way to do it or are there other possibilities?

A: You need to extract an interface for your LoginManager class.
public interface ILoginManager
{
    int CheckCredentials(string userName, string password);
}

public class LoginManager : ILoginManager
{
    public int CheckCredentials(string userName, string password)
    {
        // your existing implementation.
    }
}

And inject an implementation of ILoginManager to your controller via constructor injection.
public class HomeController : Controller
{
    private ILoginManager loginManager;
    public HomeController(ILoginManager loginManager)
    {
        this.loginManager = loginManager;
    }
    public ActionResult Login(string userName,string password)
    {
        if (loginManager.CheckCredentials(username, password) != 0)
                return RedirectToAction("Index", "Login");

        return RedirectToAction("Index", "Home");
    }
}

and in your test, create a mocked version of the ILoginManager and mock the behavior using SetUp method.
public void TestMethod1()
{
    var mock = new Mock<ILoginManager>();

    mock.Setup(x => x.CheckCredentials("", "")).Returns(0);

    var homeController = new HomeController(mock.Object);

    var ar = homeController.ReportScore("") as RedirectToRouteResult;

    //TO DO : Assert something

}


text:
Q: Having Trouble Getting to Laverre City My young son is having trouble getting to Laverre City in Pokemon X.  Can somebody please give me a hint?

A: if he is having trouble, i take it he has met up with his neighbors at the scary house. If he hasn't done this: go forward until you meet the first trainer, then go left. Go forwards, then right, then up to the massive pool of water. Go to the top left corner of the pool,(the scary house is to the left) then go up. You will reach Laverre City! Also you can beat the gym without having to fight any trainers apart from the gym leader.

A: Answer for: "How do I get to Laverre City" as suggested in the comments
You also need cut and surf if you want to obtain every item, but I'll just explain how to get to Laverre City. Check the link below to see a guide for every item.

*

*Enter the route from the Lumiose city <-> route 14 gate.

*Meet up with your friends in the playground.

*Travel north into the swamp and go left at the first T junction. (There will be a female ranger there)

*Go up once again (past the male ranger)

*Follow the path right.

*Go past the hex maniac girl and go up again.

*Slightly north-west of the ranger running around in circles is a small intersection of paths. Go left.

*Enter the house, follow the storyline, then exit and go back to the intersection.

*This time, go up.

*Welcome to Laverre City.

Source:

*

*Just navigated the route

*http://bulbapedia.bulbagarden.net/wiki/Kalos_Route_14


text:
Q: Google App Engine SSL Version 2.7.11 Library Un/Supported According the the documentation...
https://cloud.google.com/appengine/docs/python/sockets/ssl_support
https://cloud.google.com/appengine/docs/python/tools/built-in-libraries-27
SSL Version 2.7.11 supports TLS v1.0, v1.1, and v1.2 (where I need TLSv1.2 for APNs communication).
And
Google App Engine / Python supports SSL Version 2.7.11 (as of July 2016)
When I add this to my app.yaml ...
libraries:
  - name: ssl
    version: 2.7.11

...and attempt to deploy the application (via appcfig.py on the commandline or "deploy" on the launcher) I receive an error...
Error parsing ./app.yaml: ssl version "2.7.11" is not supported, use one of: "2.7"

If I specify version 2.7 or "latest", I get SSL version 2.7 without TLS v1.1 or v1.2 support. If I omit SSL from the "libraries" clause in yaml, the ssl module is not supported in the application on import.
How should I proceed to "import ssl" with TLSv1.2 support?
Or have I overlooked an app.yaml configuration option?
the pertinent portion of my app.yaml follows...
api_version: '1'
runtime: python27
threadsafe: false

instance_class: F2
automatic_scaling:
  max_idle_instances: 4
  max_pending_latency: 250ms

builtins:
- remote_api: 'on'
- deferred: 'on'

libraries:
- name: django
  version: '1.2'
- name: ssl
  version: '2.7.11'

inbound_services:
- warmup

A: Make sure you update to the latest version of the SDK:
cloud.google.com/appengine/docs/python/download
That should get rid of the 2.7.11 error.  Older (pre 2.7.11) versions had that error.


text:
Q: How to install plugins into Qt Designer? I have scoured the internet for information regarding the installation process for plugins into Qt Designer and I have found no helpful/relevant information.
The plugin I want to install is the echo plugin.
I have also looked through the Qt Designer program files and found the echoplugin folder but have no idea how to install it. Here is the file location:
C:\Qt\Examples\Qt-5.5\widgets\tools\echoplugin
This holds the following file types; Qt Project Files, C++ Header, C++ Source and JSON
System Information
Windows 10
PyQt4
Qt Designer 5.5.0

A: Official documentation describes it very well.
To install plugin for Qt Designer or Qt Creator you need to place the plugin to plugins\designer directory.
For Qt Creator it is located in it's bin directory.
Qt Designer is a part of Qt installation so directory will be QTDIR\plugins\designer where QTDIR is Qt installation path (for me it is "E:\DEV\Qt\5.5\msvc2015_desktop_shared" and full plugins path is "E:\DEV\Qt\5.5\msvc2015_desktop_shared\plugins\designer").
One important thing - Qt Designer / Qt Creator and the plugin must be compiled using the same compiler version. You can not install plugin compiled with MSVC 2015 to Qt Designer compiled with MSVC 2013!
Edit:
I am using C++ version of Qt.
It looks like echo plugin is not a plugin for Qt Designer / Qt Creator.


text:
Q: Nodejs - arrays on the left side The following code works on browsers but not in Node.js. Why?
[a, b] = 'hey,there'.split(',');
console.log(a);

A: ES6 allows something called destructuring assignments. (Nicely explained here. And here is a link to the draft spec. ) That's what you've got in your code.
It looks like it is an ES6 feature that Firefox has adopted early. (Maybe too early). Unfortunately, this is par for the course with JavaScript runtimes. Many of them give access to features from upcoming specs ahead of time. You've got to keep your eyes peeled to make sure you're not using something that has not quite yet been officially adopted.

A: Your code is considered in ECMAscript 6.This is called array destructuring. You can see its features here
https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7
your code will run on current version of Firefox (28) but not Google chrome (33)
you can check the compatibility of you browser from this site
http://kangax.github.io/es5-compat-table/es6/
If you want to run it in Google-chrome there's a flag named Enable Experimental JavaScript appeared in the chrome://flags ==> make this flag = true then you can run it
NodeJs support ECMASript 6 but you will run it using the following command
node --harmony yourapp.js


text:
Q: Crash caused by firebase java.lang.IllegalStateException My app users have been getting this error for quite sometime. I cannot replicate it myself with physical or virtual devices. It occurs in the on create method. This exception is only thrown for the first firebase instance in the activity.
java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (Unknown Source:621)
  at android.app.ActivityThread.handleLaunchActivity (Unknown Source:47)
  at android.app.servertransaction.LaunchActivityItem.execute (Unknown Source:63)
  at android.app.servertransaction.TransactionExecutor.executeCallbacks (Unknown Source:77)
  at android.app.servertransaction.TransactionExecutor.execute (Unknown Source:73)
  at android.app.ActivityThread$H.handleMessage (Unknown Source:43)
  at android.os.Handler.dispatchMessage (Unknown Source:19)
  at android.os.Looper.loop (Unknown Source:249)
  at android.app.ActivityThread.main (Unknown Source:98)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (Unknown Source:11)
  at com.android.internal.os.ZygoteInit.main (Unknown Source:282)
Caused by: java.lang.IllegalStateException:
  at com.google.android.gms.common.internal.Preconditions.checkState (Unknown Source:29)
  at com.google.firebase.FirebaseApp.initializeApp
  at com.pocketchunk.pocketchunk.ui.login.PanelActivity.getClientId (PanelActivity.java:922)
  at com.pocketchunk.pocketchunk.ui.login.PanelActivity.onCreate (PanelActivity.java:175)
  at android.app.Activity.performCreate (Unknown Source:19)
  at android.app.Activity.performCreate (Unknown Source:1)
  at android.app.Instrumentation.callActivityOnCreate (Unknown Source:3)
  at android.app.ActivityThread.performLaunchActivity (Unknown Source:376)

This exception is only thrown by this specific firebase instance even though there is five others in the activity and when I remove it there are no crashes.
Method call at line 175:
getClientId(uid);
Method at line 922:
public void getClientId(String uid){
    FirebaseOptions options66222 = new FirebaseOptions.Builder()
            .setApplicationId(appID)
            .setApiKey(key)
            .setDatabaseUrl(url)
            .build();
    FirebaseApp.initializeApp(PanelActivity.this, options66222, "client_id");
    FirebaseApp DB2123 = FirebaseApp.getInstance("client_id");
    FirebaseDatabase DB2123Intance = FirebaseDatabase.getInstance(DB2123);
    FirebaseDatabase.getInstance().setPersistenceEnabled(false);

    DatabaseReference DB2123Reference = DB2123Intance.getReference().child("clientid").child(uid);
    // Read from the database
    DB2123Reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
    // This method is called once with the initial value and again
            // whenever data at this location is updated.
            String clientid = dataSnapshot.getValue(String.class);
            Log.i("TAG", "Value is: " + clientid);
            final SharedPreferences userPrefs = getSharedPreferences("USER_PREFS", MODE_PRIVATE);
            SharedPreferences.Editor editor = userPrefs.edit();
            editor.putString("whmcsClientid", clientid);
            editor.commit();
        }

        @Override
        public void onCancelled(DatabaseError error) {
    // Failed to read value
            Log.i("TAG", "Failed to read value.", error.toException());
        }
    });
}

Any insight would be greatly appreciated!


text:
Q: Remove beginning of file without rewriting the whole file I have an embedded Linux system, that stores data in a very large file, appending new data to the end. As the file size grows near filling available storage space, I need to remove oldest data.
Problem is, I can't really accept the disruption it would take to move the massive bulk of data "up" the file, like normal - lock the file for an extended period of time just to rewrite it (plus this being a flash medium, it would cause unnecessary wear to the flash).
Probably the easiest way would be to split the file into multiple smaller ones, but this has several downsides related to how the data is handled and processed - all the 'client end' software expects single file. OTOH it can handle 'corruption' of having the first record cut in half, so the file doesn't need to be trimmed at record offsets, just 'somewhere up there', e.g. first few iNodes freed. Oldest data is obsolete anyway so even more severe corruption of the beginning of the file is completely acceptable, as long as the 'tail' remains clean, and liberties can be taken with how much exactly is removed - 'roughly several first megabytes' is okay, no need for 'first 4096KB exactly' precision.
Is there some method, API, trick, hack to truncate beginning of file like that?

A: The easiest solution for your old applications would be a FUSE filesystem which gives them access to the underlying file, but with the offset cyclically shifted. This would allow you to implement a ringbuffer at the physical level. The FUSE layer would be fairly trivial as it only needs to adjust all filepositions by a constant, modulo filesize.

A: You can achieve the goal with Linux kernel v3.15 above for ext4/xfs file system.
int ret = fallocate(fd, FALLOC_FL_COLLAPSE_RANGE, 0, 4096);

See here
Truncating the first 100MB of a file in linux

A: What about setting up a separate process that renames the output file when it reaches a predefined size (for instance by adding the linux time at the end of the file name).
This would allow you to keep the old data and the main process will recreate the output file the next time it writes to it.
Another cron job may remove the old file every now and then.


text:
Q: Android Parcel: Writing an array list Does writing an ArrayList to a parcel create a copy of the list when you read it back? My custom objects are Parcelable and I make sure I don't create copies. I need to be able to pass an ArrayList forward to other activities through intents and I need to be able to add and remove elements in the ArrayList in other activities.
Right now it seems like Parcel creates a copy of the ArrayList therefore I am not able to easily update the elements.

A: Using Parcel serializes and deserializes the data. This makes copies. If you need to share the original objects then you can declare references to them as static, which can be accessed from all classes.


text:
Q: ssh to Unix servers in Java by jsch I am really stamped and running out of ideas as of why my ssh connection from one Unix server to another Unix server, this is my java code to establish ssh connection between to unix server:
import com.jcraft.jsch.*;
import java.util.Properties;

public class ScpFiles {
  public static void main(String[] arg){
    // TODO code application logic here
    JSch jsch = null;
    Session session = null;
    Channel channel = null;

    String userName = "a_user";
    String host = "unixserver1";
    String pass = "";
    String phrase = "";
    String knownHostFile = "/home/a_user/.ssh/known_hosts";
    String rsa = "/home/a_user/.ssh/id_rsa";

    try{
        jsch = new JSch();
        session = jsch.getSession(userName, host, 22);
        session.setPassword(pass);
        jsch.addIdentity(rsa, phrase.getBytes());
        jsch.setKnownHosts(knownHostFile);
        //Properties prop = new Properties();
        //prop.put("StrictHostKeyChecking", "no");
        //session.setConfig(prop);
        session.connect();
        channel.connect();
        String command = "an unix command";
        channel = session.openChannel("exec");
        ((ChannelExec)channel).setCommand(command);
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        channel.disconnect();
        session.disconnect();
    }
  }
}

as you can see, it is pretty straight forward, but somehow it always ended with this error:
com.jcraft.jsch.JSchException: Auth cancel
    at com.jcraft.jsch.Session.connect(Session.java:463)
    at com.jcraft.jsch.Session.connect(Session.java:158)
    at ScpFiles.main(ScpFiles.java:43)

Exception in thread "main" java.lang.NullPointerException
        at ScpFiles.main(ScpFiles.java:53)
I even tried to compromise the security for test purpose by setting the StrictHostKeyChecking to no, but i still can't ssh to the remote unix server.
i was googling this error a few days, but sounds like the answer posted there doesnt resolve my issue, would someone in here please shed me a light on what went wrong.
Thanks heaps.

A: As I can see from your code, you're using channel when is still null:
channel.connect();

And 2 line after:
channel = session.openChannel("exec");

I think you need to remove the channel.connect(); line, and your program should work.


text:
Q: How can I include in my program that the integers entered must be between 0 and 100? The exercise asked me to calculate the average, maximum, and minimum. My code fulfills that purpose, however I need to include somewhere in my code that the exam grades entered by the user MUST be between 0 and 100. What is the best way to include this?
Here is my code.
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;

public class hw
{
public static void main ( String[] args )
{
    int maxGrade = Integer.MIN_VALUE;
    int minGrade = Integer.MAX_VALUE;
    int count=0;
    int total=0;
    final int SENTINEL = -1;
    int score;

    Scanner scan = new Scanner( System.in);
    System.out.println( "To calculate the class average, enter each test
    score.");
    System.out.println( "When you are finished, enter a -1.");

    System.out.print( "Enter the first test score > ");
    score = scan.nextInt();

    while (score != SENTINEL )
    {
        total += score;
        count ++;
        if( score > maxGrade)
            maxGrade = score;
        if( score < minGrade)
            minGrade = score;

        System.out.print("Enter the next test score > ");
        score = scan.nextInt();
    }
    if (count != 0)
    {
        DecimalFormat oneDecimalPlace = new DecimalFormat("0.0");
        System.out.println( "\nThe class average is "
                + oneDecimalPlace.format( (double) (total) / count ));
        System.out.println( "The minimum value is " + minGrade);
        System.out.println( "The maximum value is " + maxGrade);
    }
    else
        System.out.println("\nNo grades were entered");

    }

    }

Thank you!

A: Create a nested loop that will stop executing once the user has met the criteria. Something like this:
while (score < 0 || score > 100)
 {
   System.out.println("please enter a number between 0 and 100.");

        while(!scan.hasNextInt())
        {
             scan.next();
        }
      score = scan.nextInt();
  }

Note that this code has not been tested, this is just an idea of what it should look like.


text:
Q: How can I work better with dates in Python to remove NaNs and identify workdays and holidays between two intervals? I have a dataframe with two date fields as shown below. I want to be able to use this data to calculate 'adjusted pay' for an employee - if the employee joined after the 15th of a month, they are paid for 15 days of March + April on the 10th of the month (payday), and equally if they leave in April, the calculation should only consider the days worked in April.
Hire_Date  | Leaving_Date
_________________________
01/02/2007 | NaN
02/03/2007 | NaN
23/03/2020 | Nan
01/01/1999 | 04/04/2020

Oh and the above data didn't pull through in datetime format, and there are of course plenty of NaNs in the leaving_date field :)
Therefore, I did the following:
Converted the data to datetime format, retained the date, and filled N/As with a random date (not too happy about this, but this is only missing in a few records so not worried about the impact).
df['Hire_Date'] = pd.to_datetime(df['Hire_Date'])
df['Hire_Date'] = [a.date() for a in df['Hire_Date']]
df['Hire_Date'] = df['Hire_Date'].fillna('1800-01-01')

Repeated for Leaving date. Only difference here is that I've filled the NaNs with 0, given that we don't have that many leavers.
    df['Leaving_Date'] = pd.to_datetime(df['Leaving_Date'])
    df['Leaving_Date'] = [a.date() for a in df['Leaving_Date']]
    df['Leaving_Date'] = df['Leaving_Date'].fillna('0')

I then ended up creating a fresh column to capture workdays, and here's where I run into the issue. My code is given below.
I identified the first day of the hire month, and attempted to work out the number of days worked in March, using a np.where() function.
df['z_First_Day_H_Month'] = df['Hire_Date'].values.astype('datetime64[M]')
df['March_Workdays'] = np.where((df['z_First_Day_H_Month'] >= '2020-03-01'),
(np.busday_count(df['z_First_Day_H_Month'], '2020-03-31')), 'N/A')

Similar process repeated, albeit a simpler calculation to work out the number of days worked in the termination month.
df['z_First_Day_T_Month'] = df.apply(lambda x: '2020-04-01').astype('datetime64[M]')
df['T_Mth_Workdays'] = df.apply(lambda x: np.busday_count(x['z_First_Day_T_Month'],
x['Leaving_Date'])

However, the above process returns the following error:
iterator operand 0 dtype could not be cast from dtype(' m8 [ns] ') to dtype(' m8 [d] according to rule 'safe' ')

Please can I get some help to fix this issue? Thanks!

A: I did a bit of research and seems like that the datetime format might be a problem. The [ns] format has precision of nanoseconds and np.busday_count asks for date format, which is [D], causing error. Take a look at this numpy document and check Datetime Units Section.
Numpy, TypeError: Could not be cast from dtype('<M8[us]') to dtype('<M8[D]')
Take a look at this post. It is exact same problem as yours!


text:
Q: Angular production release - dependency version mismatch with QA I am done with an Angular app development and trying to deploy the same in to production.
I have executed this command: ng build --prod --environment=prod. This creates a package in dist folder. In package.json, I use ^ with dependency versions. This way, it will take the latest patch version to build the release package.
Lets say, during QA, a dependent package version was 1.0.0. Then before prod release, a new patch 1.1.0 released for this dependency. So if I follow ^ approach, there can be different dependency versions in QA & Prod. Is specifying exact versions with no ^ the only solution for this? Any other better ways to handle this?


text:
Q: Insert Forename Surname (Joe Bloggs) into two separate columns I have a string that looks like:
$string = 'Joe Bloggs';

and in my database, i have 2 columns, forename and surname
how can i insert this string into the two separate columns
so Joe inserts into forename and Bloggs inserts into surname
Also, if the string looks like
$string = 'John B. Doe'; or
$string = 'John B Doe';

I would want to insert
John B or John B. into forename and Doe into surname
So everything in the string apart from the last word will insert into forename and then the last word will insert into surname

A: try explode combined with array_pop and implode:
$array = explode(" ",$string);
$surname = array_pop($array);
$forename = implode(" ",$array);

A: Try it simple using exploding a string with space
$string = 'Joe Bloggs';
$arr = explode(" ",$string);
echo $arr[0]; // this your forename
echo $arr[1]; // this your surname


text:
Q: SpecFlow - The name 'GenerationTargetLanguage" does not exists in the current context - build error I'm getting this error trying to build a project. It's highlighting words in my feature pages and giving me this error.
Error 1 The name 'GenerationTargetLanguage' does not exist in the current context
I tried to Run Custom Tool on each feature but that made my errors go from two of the same, to three of these errors.
Found one other person with the problem in the google groups.  No solution.

A: I had the same problem when i installed the newest version of specflow and tried to compile an example project because the example had a local copy of an older version of the specflow dll.
The new specflow - feature-file compiler generates sourcecode for a call to a non existing specflow-dll method signature.
I solved the problem by replacing the specflow-dll in the projects lib-directory with with the dll from my newer installation.

A: I ran into the exact same error under different circumstances.  I had originally (early 2011) installed Specflow v1.5.0.0 using the msi installer, but just today used NuGet to install version 1.8.1.0 for a particular project (using Install-Package SpecFlow -ProjectName MyProject).
I quit all instances of Visual Studio, downloaded and ran the msi installer for v1.8.1.0 and then fired up Visual Studio again, deleted my existing feature files and added new ones, and everything worked.

A: I found it was a breaking change. In the xyz.feature.cs the enum GenerationTargetLanguage.CSharp should now be replaced with ProgrammingLanguage.CSharp


text:
Q: Abstract algebra for $\mathbb Z_p[i]$ form a field For which value of $p$ does the ring $\mathbb Z_p[i]$ form a Integral domain? The answer is $p=4k+3$, where $k$ is an integer - but why? I do not understand.

A: To see why $p = 4k+1$ is impossible recall that every prime of that form can be written as a sum of two squares. So we have that:
$$p = a^2 + b^2 = (a + ib)(a - ib)$$
So in $\mathbb{Z}_p[i]$ we have that $a+ib, a-ib$ are zero divisors, so it can't be an integral domain.
Now it remains to prove that it's an integral domain for each $p=4k+3$. Assume it's not true, i.e. $a+ib$ is a zero divisor. Then for some $c+id \not = 0$ we have that
$$(a+ib)(c+id) = 0 \quad \text{ in } \mathbb{Z}_p[i]$$
This reduces to the equations:
$$ac - bd \equiv 0 \pmod p$$
$$ad + bc \equiv 0 \pmod p$$
As $a+ib$ is a zero divisor at least one of $a,b$ isn't $0$ in $\mathbb{Z}_p$. WLOG let it be $a$. Then we have that $ c \equiv bda^{-1} \pmod p$ and substituting in the second equation we get:
$$ad + b^2da^{-1} \equiv 0 \pmod p$$
Obviously $d$ can't be $0$, as the first equation gives us that $c=0$ in $\mathbb{Z}_p$. So we can get rid of $d$ and multiply both sides by $a^{-1}$ to get that:
$$(ba^{-1})^2 \equiv -1 \pmod p$$
But for $p=4k+3$, this equation has no solution, as $-1$ isn't a quadratic residue modulo $p$. Hence such a zero divisor doesn't exists and $\mathbb{Z}_p[i]$ is an integral domain.

A: This depends on whether $-1$ is a quadratic residue mod $p$.
If $-1\equiv a^2 \pmod{p}$ for some $a \in \Bbb Z$, then $a^2+1 \equiv 0 \pmod{p}$, so $(a+i)(a-i) = 0$ in $\Bbb Z_p[i]$.
On the other hand, if the equation $-1 \equiv a^2 \pmod{p}$ has no solution for some $p$, then the polynomial $x^2+1$ has no root over $\Bbb Z_p$, so it is irreducible (because the degree is $2$), thus $\Bbb Z_p [x]/(x^2+1) \cong \Bbb Z_p[i]$ is an integral domain (and even a field).
So we need to determine the $p$ such that $-1$ is a square mod $p$.
There are multiple ways to do this: one is to use Euler's criterion: $\left( \frac{-1}{p}\right) \equiv (-1)^\frac{p-1}{2} \pmod{p}$, from this we get that $\left( \frac{-1}{p}\right) = 1$ if $p \equiv 1 \pmod{4}$ and $\left( \frac{-1}{p}\right) = -1$ if $p \equiv -1 \pmod{4}$.
Another way is to use the fact that the mulitplicative group $\Bbb Z_p^\times$ is cyclic and has order $p-1$, so it contains an element of order $4$ iff $ 4 \mid p-1 \Leftrightarrow p \equiv 1 \pmod{4}$. Now any element such that $a^2 \equiv -1 \pmod{4}$ must have order $4$ in $\Bbb Z_p^\times$ and conversely, any element $a$ of order $4$ satisfies $a^2 \equiv -1 \pmod{4}$, because $-1$ is the unique element of order $2$ in $\Bbb Z_p^\times$.


text:
Q: li as tabs, combine hover(or mouseenter and mouseleave) and click I have problem with tabs (using li). I dont know how to solve this situation: by click tab(tab link) not show tab content, but if i hover tab again to show tab content. (just first click not show the tab content)
Thanks in advance!
HTML:

Auto

Automk

Info

Teleko

Pamet

Računari

tab1 content

tab2 content

tab3 content

JQuery:
  $("#tabstest li").click(function() {

          ????

});

 $("#tabstest li").hover(function () {

$("#tabstest li").removeClass('active');

    $(this).addClass("active");

  var selected_tab = $(this).find("a").attr("href");

    $(selected_tab).fadeIn();

          }, function () {

$("#tabstest li").removeClass('active');

  var selected_tab = $(this).find("a").attr("href");

    $(selected_tab).hide();
});

A: You can do something like this.  On first click it wont do anything.  But after first click it will show the data.
var clickCount = 0;
$("#tabstest li").click(function() {
     if (clickCount > 1) {
        $(this).addClass("active");
        var selected_tab = $(this).find("a").attr("href");
        $(selected_tab).fadeIn();
     }
     clickCount++;
});

 $("#tabstest li").hover(function () {

$("#tabstest li").removeClass('active');

    $(this).addClass("active");

  var selected_tab = $(this).find("a").attr("href");

    $(selected_tab).fadeIn();

          }, function () {

$("#tabstest li").removeClass('active');

  var selected_tab = $(this).find("a").attr("href");

    $(selected_tab).hide();
});


text:
Q: Prevent small signal with noise I am designing a Conductivity Meter by using Arduino.
I used ad9850 to generate a sin wave with 1khz and peak to peak 20mV.
but there is a bit of noise with my output Signal

and after the voltage follower , The noise have been amplified
by voltage follower.(as shown below)

What I've Tried
I thought maybe I can use RC filter to get a clean sin wave(you can see the detail in two video link I post below), but I still have to put my out put Signal to another voltage follower.
Does anyone have good suggestion to filter the noise?
This is my Circuit:

before RC filter:
https://www.dropbox.com/s/22808bem0uizszn/rc%E6%BF%BE%E6%B3%A2%E5%89%8D.mp4?dl=0
after RC filter:
https://www.dropbox.com/s/0xebs8p84kpcm5q/rc%E6%BF%BE%E6%B3%A2%E5%BE%8C.mp4?dl=0
------------update at 2018/11/25
@WhatRoughBeast  , I have conducted an experiment
to make sure that the noise from my output signal is coming from my power supply .
The following link is my experiment video, I used 1kohm/0.1uF RC filter to keep
the noise out of my power supply.(which is similar function with the scheme you told me)
In oscilloscope of my video, The yellow line wave was measured across 1k ohm and 0.1uF.
The blue line wave  was measured across only 0.1uF capacitance.
I was wondering that the does the yellow line running like a sin wave is really the switching noise affecting my output signal?
Did my 1k/0.1F RC filter completely keep the noise out of my DC power?
It seems that the blue line is still floating because of some low-frequency.
Please see the detail in the following link and picture, thank you!

https://www.dropbox.com/s/0t1wef1mmjqot2a/%E6%BF%BE%E9%99%A4%E5%8E%9F%E4%B9%8B%E9%9B%9C%E8%A8%8A%E5%AF%A6%E9%A9%97.mp4?dl=0

A:
This is my Circuit:

No, it's not.
1) You show two different frequencies (1 kHz and 8 kHz) being applied. However, your scope FFT shows only a single frequency.
2) There is no sign of the 100 ohm/1 ohm divider.
3) The output of the RC filter seems to be coupled to the scope via another capacitor which is not shown. (Hint - there is no need to do this if you're looking at a small AC signal with a large DC offset. Simply change your scope input coupling from DC to AC. That sort of thing is exactly why the option exists.)
Additionally, you have no decoupling of your op amp power supplies, and any switching noise on the power supply will run through op amp like grease through a goose.
In general, you should use the long horizontal bus strips (like the two you've used for the power supply) for ground as well. At each IC, connect the vertical strips just below pins 4 and 5 of the IC to the ground strip, using bits of bare wire just long enough to jump from point to point at each end of the strips. Avoid long loops like the plague. Then you should run a 0.1 uF cap directly from the IC pin strips to the local ground strip, and likewise make your input and output ground connections to this local strip. And for a low-current setup like this, you should add a 1 to 10 ohm resistor in series from the power supply to the decoupling cap/op amp connection.
Since your Arduino/AD9850 is running from a separate power supply, connect the ground of this supply at the local ground strip of the op amp. Do not connect it at the op amp power supply.
So, overall, you connection scheme should look something like

simulate this circuit – Schematic created using CircuitLab
Here, the darker line is the local ground area formed by the two strips just below pins 4 and 5.


text:
Q: How to find and replace a line in a text file? This is my database named myDB.txt:
28273139
iPhone
5.50
30
5
35
81413852
Book
1.50
43
10
55

The text file database follows the format
Product Code
Product Name
Price
Current Stock
Reorder Stock (the lowest the stock can go)
Target Stock

Now, the I want to update the iPhone data.
This is the iPhone data.
28273139
iPhone
5.50
30
5
35

It uses the 8-digit product code to identify the product.
I have written the following code.
userCode = "28273139"
newstock = "29"

database = open('myDB.txt','r+')
while(str(userCode) not in next(database)):
    pass
else:
    for i in range(3):
        line = next(database)
        replace = line.replace(line,newstock)
        database.write(replace)

I want to change the 4th value of the list, the number 30 to the number 29, which I declared as the variable newstock.
The program moves 3 lines down, since the format is the same for every product in the database and replaces the line with this new value.
The result I need from updating the iPhone data -
28273139
iPhone
5.50
29
5
35

However, this method doesn't work.
I receive an error every time.
AttributeError: 'str' object has no attribute 'readlines'

Can someone help fix my problem? Is the code I have written correct to produce the required result?

A: This is a lot easier when you configure your text file to be key:value pairs (like the dict construct in python, or values in another DB like SQL). Then you can simply set a sentinel value when the value is met, then unset when you've replaced the correct line.
So, if changing the format of text to:
ProductCode <value>
ProductName <value>
Price <value>
CurrentStock <value>
ReorderStock <value>
Targetstock <value>

Then you can do something like this:
ProductCode = "28273139"
NewStock = "29"
SentinelValue = 0

with open('myDB.txt', 'r+') as database:
  for line in database:
  (key, val) = line.split()
  if key == "ProductCode":
    if val == ProductCode:
      SentinelValue = 1
  if key != "ProductCode":
    if key == "CurrentStock":
      if SentinelValue == 1:
        line = line.replace(val, NewStock)
    print line

It is a bit dirty and could surely be cleaned up, but it is much more verbose. Also, note that the space is important as it is used as the delimiter when splitting the lines.
You may also notice I didn't write to the file: At least for me in python 2.7, there seems to be an issue where I can't replace a line of text, only append with f.write(). This code works and replaces to stdout, the workaround for writing to a file is to simply write all lines to a new file:
ProductCode = "28273139"
NewStock = "29"
SentinelValue = 0
fout = open('newDB.txt', 'w')

with open('myDB.txt', 'r+') as database:
  for line in database:
  (key, val) = line.split()
  if key == "ProductCode":
    if val == ProductCode:
      SentinelValue = 1
  if key != "ProductCode":
    if key == "CurrentStock":
      if SentinelValue == 1:
        line = line.replace(val, NewStock)
    fout.write(line)
    print line

You could then write logic to replace the files as needed. However, I would very much suggest looking at how to write and read from an actual SQL database. I hope this helps! ^^

A: you should probably iterate over your file differently, something along the lines of:
database = open('myDB.txt','r+')
while(str(userCode) not in next(database)):
    pass
else:
    for i in range(3): line = next(database)

the above line is inspired by David Hoksza
at this point you should be at the desired line
im 100% sure there is a better pythonic way of doing this, but i dont have much experience with file manipulation in python
i think this should work in python 3


text:
Q: Is there any benefit to using Math.Floor over explicit integer casting? Question is pretty straightforward, is there any benefit or difference? I've noticed that in C# the function returns a double without any decimal places, while in java it keeps the decimal places, but other than that the result is the same.
Here is the code I used in Java and C#, and the output:
//Java                                        //C#

double a = 5.5;                               double a = 5.5;
System.out.println(Math.floor(a));            Console.WriteLine(Math.Floor(a));
System.out.println((int)a);                   Console.WriteLine((int)a);

//Output                                      //Output

5.0                                           5
5                                             5

A: Yes, for negative numbers, this works in the opposite way.
Example (using Mono's C# interactive shell csharp):
csharp> Math.Floor(-12.0d)
-12
csharp> Math.Floor(-12.5d)
-13
csharp> (int) -12.5
-12

(same for both Java/C#) and I guess most languages anyway.
Casting a floating-point number to an integer, is performed by throwing away the decimal part maintaining the integer part. The integer part of -12.5 is 12. Thus negative numbers do a Math.Ceil if converted to an int.
Furthermore as @Matthew argues, a float or double can reach numbers like 1.023e23 (Avogadro's constant). Simply because the mantisse can't represent digits after the comma anymore. Numbers that are considered to be an integer anyway, but can't be represented by an int. By performing a Math.floor operation, nothing happens, but the value is still maintained. While conversion to an int could result in overflow:
Example:
csharp> double ac = 1.023e23;
csharp> Math.Floor(ac);
1.023E+23
csharp> (int) ac;
0

Note: this may look far fetched, but there is thus a clear difference in semantics nevertheless. A difference that tends to lead to errors anyway.

In addition, it works differently for infinite numbers and NaN:
System.out.println(Math.floor(Double.POSITIVE_INFINITY)); // Prints Infinity
System.out.println((int)Double.POSITIVE_INFINITY);        // Prints 2147483647
System.out.println(Math.floor(Double.NaN));               // Prints NaN
System.out.println((int)Double.NaN);                      // Prints 0

But I would always use them nevertheless. Casting makes things way more unreadable. Rounding up/down/off is more some kind of (side-effect) of the cast. By using Math.Ceil/Floor/Round it is clear what you mean.
Sometimes a cast to an integer is indeed a bit more efficient than performing a floor/ceil operation first. But a smart compiler can sometimes derive that a variable will always store a positive number and thus optimize it itself. And furthermore for most applications this will result in an insignificant performance penalty.


text:
Q: A Lower Bound for Estimating a Bernoulli Mean I'm trying to understand this paper:
http://www.jmlr.org/proceedings/papers/v9/hanneke10a/hanneke10a.pdf
However, I get stuck at Lemma 1, which I will copy here. This lemma is about estimating the mean of a Bernoulli random variable by some estimator $\hat{p}_n$ using $n$ samples. The paper says this is a well-known result however I'm not familiar with it.

Lemma 1. For $0 ≤ a < b ≤ 1$, there exists a constant $c_{a,b} > 0$
  such that, for any $n ∈ N$, for any estimator $\hat{p}_n : \{0, 1\}^n
 \to [0, 1]$, there exists a value $p ∈ [a,b]$ such that, if $B_1,B_2,...
 ,B_n$ are independent $\mathrm{Bernoulli}(p)$ random variables, then
  $${\mathbb{E}}[(\hat{p}(B_1,B_2,\ldots,B_n) − p)^2] > c_{a,b}/n.$$

From the text I understand $c_{a,b}$ does not depend on $n$.
I'm trying to figure out where this lemma comes from, or at least what the conditions are on the estimator $\hat{p}_n$. It is too bad the paper does not refer to any sources and does not give any conditions on the estimator. Can anyone help me?


text:
Q: Border radius applied to td has no inner radius When I apply a border and border radius to a td, the inner radius is a right angle and not rounded at all.

A: Most likely the problem is a child element with opaque background which will clip the inner radius of the border.
To fix this you can apply overflow:hidden on your td .
You can play with the overflow in this Example fiddle to see the effect.


text:
Q: VS F# canopy test adding folder I want to ask you, if it´s somehow possible, to add folder, to sort out Test´s a little bit.. When i am doing in C# parts, there is normally option

right click-> add ->new folder

In F# case, it looks like it´s missing.
I tried to add it even out of VS, via the Win. explorer, but its not working.

Edit: I have found quite poor solution and that´s actually, that you create new folder in C# part and then cut it out and paste to F# section but it´s a bit weird, so any ideas are welcome.

A: It is not implemented in VS2013 but you can use F# Power Tools extension (http://fsprojects.github.io/VisualFSharpPowerTools/) or create it manually (http://marcinjuraszek.com/2014/03/folders-in-f-projects-how-to-do-it-what-to-avoid.html)

A: You can either use F# Project Extender or edit the project file manually. Details are here.
Edit: This article explains how to keep your project organized without folders.


text:
Q: How to add Element over fullscreen video on firefox I need help about adding content over a Fullscreen video (embed in iframe) on Firefox ... I 'm able to do it in chrome without any issue ! but FF is not allowing me to !
I don't understand why and I'm looking for a solution now for days ! :(
If someone can help me, here is a jsfiddle example try to run it in firefox and you will see ... no way to get this work correctly everything is behind, z-index does not work on ff but it does on chrome.
remember it's only in fullscreen mode.
(I did not make the example working for chrome but it does not matter because i was able to do it just with playing with z-index property.)
This is the example:
    Example
https://jsfiddle.net/7ccf5pgw/4/
Thanks for  everything.
Cheers


text:
Q: use apply file list for a function in R I've created this function to get some information from two different files
   create_distance_to_strand <- function(data, data2, nameCsv) {
      newData  <- data  %>%
        select(seqnames, start, end, V4, seqnames, geneStart, geneEnd, geneStrand, distanceToTSS, SYMBOL, geneLength)%>%
        rename(peak = V4)

      joined_df <- merge(newData , closest_dist, by.x = "peak",
                         by.y = "peak", all.x = TRUE, all.y = TRUE) %>% drop_na()

      write.table(joined_df , nameCsv, sep = "\t")

      return(joined_df)
    }

    closest_dist = read.csv("closest_distance", header = T, sep ="\t")
    annotation = read.csv("results_annotation", header = T, sep ="\t")
    myDistanceToStrand <- create_distance_to_strand(annotation,  closest_dist, "frame.csv")

It works as expected. However, I'm trying to make it more efficient in case I'd have different "closest_dist" files, in order to apply the function to all the files.
I've tried this:
    files <- list.files(pattern = "closest*")
    proof = lapply(files, create_distance_to_strand(annotation,  closest_dist, "proof.csv"))

But does not work
Error in h(simpleError(msg, call)) :
      error in evaluating the argument 'y' in selecting a method for function 'merge': object 'closest_dist' not found

Any advice?
Thank you

A: Since you have different closest_dist files which are saved in files, you can use lapply to pass them one by one. We can use an anonymous function here -
files <- list.files(pattern = "closest*")
proof = lapply(files, function(x) create_distance_to_strand(annotation,  x, "proof.csv"))

To have a separate output file you may pass different nameCsv value as well.
Map(function(x, y) create_distance_to_strand(annotation, x, y),
    files, sprintf('proof%d.csv', seq_along(files)))


text:
Q: addEventListener onClick not working I don't know what's wrong with my code, but when I use addEventListener() it doesn't do a thing.
Does anyone have another solution so that I can bind the #ibm button ID to compute() onClick event?
I plan to run this on Firfox OS, so setting an onClick attribute on the button itself is prohibited as stated on the CSP Violations.
    function compute()
    {
var w = parseInt(document.getElementById('weight').value);
var hf = parseInt(document.getElementById('height_ft').value);
var hi = parseInt(document.getElementById('height_in').value);

    if (!checker(w))
{

            showAndroidToast('Please input your weight');
    return;
}
else if (!checker(hf))
{

            showAndroidToast('Please input your height');
    return;
}

if (!checker(hi))
{
    var i = 0;
    document.getElementById('height_in').value = i;
}
else
{
    var i = parseInt(document.getElementById('height_in').value);
}

var comp_h = parseFloat((hf * 12) + (i * 1));
var tot_h = comp_h * comp_h;

comp = formula(w, tot_h);
document.getElementById('bmitot').value = comp;

if (comp > 30)
{
    document.getElementById('res').value = 'Severe Level! Thats too much FAT!      Go get some diet pills or something!';
    document.getElementById("bmitot").style.backgroundColor = "red";
    document.getElementById("zero").style.visibility = "hidden";
    document.getElementById("one").style.visibility = "hidden";
    document.getElementById("two").style.visibility = "hidden";
    document.getElementById("three").style.visibility = "visible";
}
if (comp > 25 && comp <=29.9)
{
    document.getElementById('res').value = 'Bad Level! You are too FAT!';
    document.getElementById("bmitot").style.backgroundColor = "yellow";
    document.getElementById("zero").style.visibility = "hidden";
    document.getElementById("one").style.visibility = "hidden";
    document.getElementById("two").style.visibility = "visible";
    document.getElementById("three").style.visibility = "hidden";
}
if (comp > 18.5 && comp <=24.9)
{
    document.getElementById('res').value = 'Nice! You are on the safe level!';
    document.getElementById("bmitot").style.backgroundColor = "green";
    document.getElementById("zero").style.visibility = "hidden";
    document.getElementById("one").style.visibility = "visible";
    document.getElementById("two").style.visibility = "hidden";
    document.getElementById("three").style.visibility = "hidden";
}
if (comp < 18.5)
{
    document.getElementById('res').value = 'Bad Level! Go get some nutrients!';
    document.getElementById("bmitot").style.backgroundColor = "yellow";
    document.getElementById("zero").style.visibility = "visible";
    document.getElementById("one").style.visibility = "hidden";
    document.getElementById("two").style.visibility = "hidden";
    document.getElementById("three").style.visibility = "hidden";
}
}

function formula(w, h)
{
var bmi = w/h * 703;
var a_bmi = Math.floor(bmi);
var dif = bmi - a_bmi;
dif = dif * 10;
diff = Math.round(dif);

if (dif == 10)
{
    a_bmi += 1;
    dif = 0;
}
bmi = a_bmi + "." + diff;
return bmi;
}

function checker(type)
{
  if (isNaN(parseInt(type)))
{
  return false;
}
else if (type < 0)
{
  return false;
}
else
{
return true;
}
}

function showAndroidToast(toast)
{
   Android.showToast(toast);
}

 document.getElementById('ibm').addEventListener('click', compute);

A: Your code is executing fine and compute function is triggering fine. There may be an issue with the code in execute function. Check this fiddle


text:
Q: when I launch my application then it crash when I launch my application then it crash and in log screen error show is "User cannot be cast to java.util.List"
    package com.example.harryproject;
    import androidx.appcompat.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    public class MainActivity extends AppCompatActivity {
    ListView mylist;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mylist=findViewById(R.id.list);
        User user=new User();
        user.setF_name("ali");
        user.setF_pic(R.drawable.ora);
        List<User> arr=new<User>ArrayList();
        arr.add(user);
        HarryAdapter ad=new HarryAdapter(this, (List<User>) user);// error here
        mylist.setAdapter(ad);
      }
   }
   //in logcat screen show this message "com.example.harryproject.User cannot be cast to
   //java.util.List"

A: I think this will fix your problem:
HarryAdapter ad=new HarryAdapter(this, arr);

If you are using List<User> user, it may be null because user it is not an instance of the list but it's an instance of User.


text:
Q: Why can't cocoapods install zxingobjc in my project Podfile, it contains this line - pod 'ZXingObjC', '~> 2.2.6'
then I execute this command: pod install --verbose --no-repo-update

Analyzing dependencies
Finding Podfile changes
    A ZXingObjC
Resolving dependencies of Podfile
  Resolving dependencies for target `Pods' (iOS 5.0)
    - ZXingObjC (~> 2.2.6)
Comparing resolved specification to the sandbox manifest
    A ZXingObjC
Downloading dependencies
-> Installing ZXingObjC (2.2.6)

GitHub download
    Creating cache git repo (/Users/leo/Library/Caches/CocoaPods/GitHub/460c72131c6f29c2d0f283a2dc9a9d7c7ff3388f)
    Cloning to Pods folder
           $ /usr/bin/git clone https://github.com/TheLevelUp/ZXingObjC.git /Users/leo/Library/Caches/CocoaPods/GitHub/460c72131c6f29c2d0f283a2dc9a9d7c7ff3388f --mirror
           Cloning into bare repository '/Users/leo/Library/Caches/CocoaPods/GitHub/460c72131c6f29c2d0f283a2dc9a9d7c7ff3388f'...

It hangs here for a long time, and finally give below error:

  error: RPC failed; result=56, HTTP code = 200
  fatal: The remote end hung up unexpectedly
  fatal: early EOF
  fatal: index-pack failed

Any one knows how to solve this? I want to use ZXingObjc in my project...ios


text:
Q: Cannot get data from real time database with anonymous authentication (React Native) - Permission Denied I am trying to implement anonymous authentication in my app. I have done it with React Native Firebase (https://rnfirebase.io/). So far the sign up is good. The user signs up and I get a user id for that particular case. This is my code for it:
const authenticate = async () => {
    await auth()
      .signInAnonymously()
      .then(() => {
        console.log('User signed in anonymously');
        console.log(user);
        firebase.auth().onAuthStateChanged(user => {
          if (user != null) {
            fetchData();
          }
        });
      })
      .catch(error => {
        if (error.code === 'auth/operation-not-allowed') {
          console.log('Enable anonymous in your firebase console.');
        }
        setFetching(false);
        console.error(error);
      });
  };

As you can see, if you check the part when the sign up is successful, we have a function called fetchData(). This function retrieved my data form the real time database. Here it is:
  const fetchData = async () => {
    try {
      await fetch(setLocale())
        .then(response => response.json())
        .then(responseJSON => {
          saveFavoritesFromAsync(responseJSON);
          setFetched(true);
          setFetching(false);
          fetchMedusa();
        });
    } catch (error) {
      console.log(error);
      setFetching(false);
    }
  };

The problem comes when I implement the rules in firebase. Before this, I had everything open (read: true, write: true) but to add a bit of security I am trying to add this anonymous authentication. My rules now are:
{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

Once I put this rules the data cannot be retrieved. I get no data basically, and my console log says "Permission Denied".
What am I doing wrong? Should I pass the user ID with the fetch? Please help
Thanks very much

A: I have solved it.
The packages that come from React Native Firebase are ment to be used together. What was happening was:
I was using the fetch method from react native. You have to use the firebase database package they give you to retrieve or write data.
See how my fetch looks now:
 await database()
        .ref(setLocale())
        .once('value')
        .then(responseJSON => {
          if (responseJSON.error) {
            setFetching(false);
            setFetched(false);
          } else {
            saveFavoritesFromAsync(responseJSON.val());
            setFetched(true);
            setFetching(false);
            fetchMedusa();
          }

Also important, the responseJSON data has to be saved with the .val() method or it won't be correct.
I hope it can help someone in need.