text:
Q: jQuery-ui tabs CSS not functioning normally I'm working on an advanced database manager in PHP (essentially phpMyAdmin for dummies, giving only Administrators the ability to create tables, then admins create forms for users to input data). For most of this applications I'm more concerned with the back-end than the appearance, so I've been borrowing jQuery-UI to speed up coding.
As I was creating the administrative dashboard I ran into an issue. I used the default implementation of jQuery-UI tabs and the ui-tab-nav stretched itself to fill the page vertically.
I've traced the error to the following CSS rule of mine:
#sidebar { float:left; }

This shows the error that I'm having:

$(function() {
    $("#tabs").tabs();
});
html,body {
    height: 100%;
    margin: 0;
    padding: 0;
}
#sidebar {
    float: left;
    height: 100%;
    width: 200px;
    margin: inherit;
    padding: inherit;
    overflow: auto;
    border-right: solid 1px #000;
}
#sidebar .menu {
    margin: 10px;
    padding: inherit;
    list-style: none;
}
.title {
    font-size: 1.5em;
    font-weight: bold;
    margin: inherit;
    padding: inherit;
}
#sidebar .menu .nav-section {
    font-size: 1.5em;
    font-weight: bold;
    border-bottom: solid 1px #000;
    margin: 20px 0;
    padding: inherit;
}
#content {
    position: relative;
    margin-left: 201px;
    /* 200px width + 1px border */
    padding: inherit;
}
#header {
    margin: inherit;
    padding: inherit;
    background: #FF9;
}
#header label {
    margin-left: 20px;
}
#myForm th {
    background-color: #999;
    border: 1px #000 solid;
}
#myForm td {
    border: 1px #000 solid;
}

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/smoothness/jquery-ui.css" rel="stylesheet"/>

DBManager: Administrators

Forms

Demos - Edit

Reports

School Copy - Edit

Actions

phpMyAdmin

Dashboard

Logout

First

Second

Third

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Phasellus mattis tincidunt nibh. Cras orci urna, blandit id, pretium vel, aliquet ornare, felis. Maecenas scelerisque sem non nisl. Fusce sed lorem in enim dictum bibendum.

Nam dui erat, auctor a, dignissim quis, sollicitudin eu, felis. Pellentesque nisi urna, interdum eget, sagittis et, consequat vestibulum, lacus. Mauris porttitor ullamcorper augue.

JSFiddle Demo
With this rule commented out the jQuery-UI tabs display properly, however the entire content box is pushed below my sidebar. Options?

A: Float the #tabs div left as well:  http://jsfiddle.net/UCeLf/
#tabs { float:left; }


text:
Q: LibGDX - Dialog - how to remove the titlebar? I just started using LibGDX. I'm trying to create a notification system like on a video below. I've extended the Dialog class (cause Label can't have it's own background).
I learned some 'MoveToActions' and the dialogs slides. I need to remove the titlebar somehow, but 'getTitleLabel()' and 'getTitleTable()' don't want to work.
Any ideas? :) Thanks!
https://www.youtube.com/watch?v=ZVxfyVUAqCQ

A: If you would prefer to use Label instead of Dialog, Label actually can have its own background. LabelStyle has a parameter for setting a Drawable as the background and when creating a new Label use this constructor:
Label(java.lang.CharSequence text, Label.LabelStyle style)

Here is the API for LabelStyle:
https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/scenes/scene2d/ui/Label.LabelStyle.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Допустимые имена полей в БД Mysql Здравствуйте!
какие допустимые имена могут быть поля в таблице Mysql?
к примеру: section_title, sectionTitle, section-title
сейчас я использую такой вид: section_title, но слышал что можно использовать sectionTitle, но почему то у меня второй способ не работает.
подскажите пожалуйста как правильно.

A: Допустимые символы

Certain objects within MySQL, including database, table, index,
  column, alias, view, stored procedure, partition, tablespace, resource
  group and other object names are known as identifiers.

Идентификаторы могут состоять из базовых латинских символов, цифр 0-9, $ и подчеркивания. Могут начинаться с цифры, но не могут состоять только из них.
Регистр
Во избежании проблем в именах с разным регистром, лучше всего принять согласованное соглашение, например, всегда создавать и ссылаться на базы данных и таблицы с использованием строчных имен. Это соглашение рекомендуется для максимальной переносимости и простоты использования.
Также
Как имена таблиц и баз данных хранятся на диске и используются в MySQL, зависит от системной переменной lower_case_table_names, которую вы можете установить при запуске mysqld.


text:
Q: Are Lottie animations supported in Xamarin.Forms UWP projects? I am trying to add Lottie animations to my project.
So far I've only tested on android and I got it working.
Now I'm also trying to add them to my UWP app but I can't find a guide on how to do this.
There is this link that tells me lottie is supported on UWP.
And this post and (probably as a reaction) this post suggests it is possible within xamarin forms uwp.
I can't find a clear reference (or a tutorial) online if this is supported for Xamarin.Forms UWP projects. I'm mainly in doubt because I'm not sure if the Xamarin.Forms.UWP 'flavor' is the same as a 'normal' UWP application.
I could really appreciate a nudge in the right direction.

A: I think it has something to do with this bug.
Although this sample with an older version (2.5.4) was not built with "support" for UWP
I did get it working by adding the resources to the root dir and setting the build action to Content.
Downgrading the library in my own project to 2.5.4 fixed the problem for me.


text:
Q: Euler parameterization definition. I am given a parameterization $\vec{\gamma}(t) = \langle a \cos t, b \sin t \rangle$ of the ellipse $$ \frac{x^2}{a^2} + \frac{y^2}{b^2}=1$$
I am now asked to write this in terms of an Euler parameterization.
I can not find the definition of an Euler parameterization anywhere. Can somebody explain to me what is meant by this?

A: I guess this means that you have to find a parametrization of the form
$$
\varphi(t) = r(t)\binom{\cos t}{\sin t}.
$$

A: Identify $\Bbb R^2$ with $\Bbb C$, that is, write $$\gamma(t) = a\cos t + i b\sin t,$$and try to put that in the form $\gamma(t) = r(t) e^{i\theta(t)}$. This seems tricky, though. We can compute at once $$r(t) = \|\gamma(t)\| = \sqrt{a^2\cos^2t + b^2 \sin^2t}.$$ For the argument, use $\cos(\theta(t)) = {\rm Re}(\gamma(t))/\|\gamma(t)\|$ and $\sin( \theta(t)) = {\rm Im}(\gamma(t))/\|\gamma(t)\|$ (it won't look pretty).


text:
Q: Why am I unable to view stats in the WSO2 API Manager Store? Everyone please note that this question has been updated as I've recently had logs to work with.  Below the log is the original posting with my configs, and the behavior I was seeing.
Today, WSO2 APIM continues to send to BAM receivers which update the Stats database.  However when I click on any of the statistics link in the publisher I get:
TID: [0] [AM] [2014-03-04 13:43:18,815] ERROR {org.wso2.carbon.apimgt.hostobjects.APIProviderHostObject} -  Error while invoking APIUsageStatisticsClient for ProviderAPIUsage {org.wso2.carbon.apimgt.hostobjects.APIProviderHostObject}
org.wso2.carbon.apimgt.usage.client.exception.APIMgtUsageQueryServiceClientException: Error occurred while querying from JDBC database
        at org.wso2.carbon.apimgt.usage.client.APIUsageStatisticsClient.queryFirstAccess(APIUsageStatisticsClient.java:1747)
        at org.wso2.carbon.apimgt.usage.client.APIUsageStatisticsClient.getFirstAccessTime(APIUsageStatisticsClient.java:1675)
        at org.wso2.carbon.apimgt.hostobjects.APIProviderHostObject.jsFunction_getFirstAccessTime(APIProviderHostObject.java:2911)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.mozilla.javascript.MemberBox.invoke(MemberBox.java:126)
        at org.mozilla.javascript.FunctionObject.call(FunctionObject.java:386)
        at org.mozilla.javascript.optimizer.OptRuntime.call2(OptRuntime.java:42)
        at org.jaggeryjs.rhino.publisher.modules.statistics.c1._c_getFirstAccessTime_13(/publisher/modules/statistics/usage.jag:351)
        at org.jaggeryjs.rhino.publisher.modules.statistics.c1.call(/publisher/modules/statistics/usage.jag)
        at org.mozilla.javascript.ScriptRuntime.applyOrCall(ScriptRuntime.java:2430)
        at org.mozilla.javascript.BaseFunction.execIdCall(BaseFunction.java:269)
        at org.mozilla.javascript.IdFunctionObject.call(IdFunctionObject.java:97)
        at org.mozilla.javascript.optimizer.OptRuntime.call2(OptRuntime.java:42)
        at org.jaggeryjs.rhino.publisher.modules.statistics.c0._c_anonymous_13(/publisher/modules/statistics/module.jag:29)
        at org.jaggeryjs.rhino.publisher.modules.statistics.c0.call(/publisher/modules/statistics/module.jag)
        at org.mozilla.javascript.optimizer.OptRuntime.call1(OptRuntime.java:32)
        at org.jaggeryjs.rhino.publisher.site.blocks.stats.ajax.c0._c_anonymous_1(/publisher/site/blocks/stats/ajax/stats.jag:220)
        at org.jaggeryjs.rhino.publisher.site.blocks.stats.ajax.c0.call(/publisher/site/blocks/stats/ajax/stats.jag)
        at org.mozilla.javascript.optimizer.OptRuntime.call0(OptRuntime.java:23)
        at org.jaggeryjs.rhino.publisher.site.blocks.stats.ajax.c0._c_script_0(/publisher/site/blocks/stats/ajax/stats.jag:4)
        at org.jaggeryjs.rhino.publisher.site.blocks.stats.ajax.c0.call(/publisher/site/blocks/stats/ajax/stats.jag)
        at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:394)
        at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3091)
        at org.jaggeryjs.rhino.publisher.site.blocks.stats.ajax.c0.call(/publisher/site/blocks/stats/ajax/stats.jag)
        at org.jaggeryjs.rhino.publisher.site.blocks.stats.ajax.c0.exec(/publisher/site/blocks/stats/ajax/stats.jag)
        at org.jaggeryjs.scriptengine.engine.RhinoEngine.execScript(RhinoEngine.java:570)
        at org.jaggeryjs.scriptengine.engine.RhinoEngine.exec(RhinoEngine.java:273)
        at org.jaggeryjs.jaggery.core.manager.WebAppManager.execute(WebAppManager.java:432)
        at org.jaggeryjs.jaggery.core.JaggeryServlet.doPost(JaggeryServlet.java:29)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
        at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
        at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:379)
        at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
        at org.jaggeryjs.jaggery.core.JaggeryFilter.doFilter(JaggeryFilter.java:21)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
        at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178)
        at org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
        at org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:56)
        at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
        at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141)
        at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
        at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:744)
Caused by: java.sql.SQLException: Incorrect syntax near 'limit'.
        at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372)
        at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2988)
        at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2421)
        at net.sourceforge.jtds.jdbc.TdsCore.getMoreResults(TdsCore.java:671)
        at net.sourceforge.jtds.jdbc.JtdsStatement.executeSQLQuery(JtdsStatement.java:505)
        at net.sourceforge.jtds.jdbc.JtdsStatement.executeQuery(JtdsStatement.java:1427)
        at org.wso2.carbon.apimgt.usage.client.APIUsageStatisticsClient.queryFirstAccess(APIUsageStatisticsClient.java:1729)
        ... 63 more
TID: [0] [AM] [2014-03-04 13:43:18,836] ERROR {JAGGERY.modules.statistics.usage:jag} -  java.lang.NullPointerException: null {JAGGERY.modules.statistics.usage:jag}

I have configured WSo2 API Manager 1.6.0 and BAM 2.4.0 to both use the same datasource configuration for WSO2AM_STATS_DB.
For the store it is a single WSO2AM_STATS_DB entry that matches the entry on the BAM server (below) and API-Manager.xml is updated to:
  <APIUsageTracking>
        <Enabled>true</Enabled>
<PublisherClass>org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher</PublisherClass>
        <ThriftPort>7612</ThriftPort>
        <BAMServerURL>tcp://myBAMserver:7612/</BAMServerURL>
        <BAMUsername>user</BAMUsername>
        <BAMPassword>pwd</BAMPassword>
        <DataSourceName>jdbc/WSO2AM_STATS_DB</DataSourceName>
        <GoogleAnalyticsTracking>
             <Enabled>false</Enabled>
             <TrackingID>UA-XXXXXXXX-X</TrackingID>
       </GoogleAnalyticsTracking>
    </APIUsageTracking>

and now the datasource for APIM:
<datasource>
    <name>WSO2AM_STATS_DB</name>
    <description>The datasource used for getting statistics to API Manager</description>
    <jndiConfig>
        <name>jdbc/WSO2AM_STATS_DB</name>
    </jndiConfig>
    <definition type="RDBMS">
        <configuration>
            <defaultAutoCommit>false</defaultAutoCommit>
            <url>jdbc:jtds:sqlserver://mydbserver:1433/wso2_apiStatsdb</url>
            <username>wso2storeuser</username>
            <password>storepwd</password>
            <driverClassName>net.sourceforge.jtds.jdbc.Driver</driverClassName>
            <maxActive>50</maxActive>
            <maxWait>60000</maxWait>
            <testOnBorrow>true</testOnBorrow>
            <validationQuery>SELECT 1</validationQuery>
            <validationInterval>30000</validationInterval>
        </configuration>
    </definition>
 </datasource>

For the BAM server here are my datasources:
<datasource>
        <name>WSO2_CARBON_DB</name>
        <description>The datasource used for API Manager database</description>
        <jndiConfig>
            <name>jdbc/WSO2CarbonDB</name>
        </jndiConfig>
        <definition type="RDBMS">
            <configuration>
                <defaultAutoCommit>false</defaultAutoCommit>
                <url>jdbc:jtds:sqlserver://mydbserver:1433/wso2_carbondb</url>
                <username>user</username>
                <password>pwd</password>
                <driverClassName>net.sourceforge.jtds.jdbc.Driver</driverClassName>
                <maxActive>50</maxActive>
                <maxWait>60000</maxWait>
                <testOnBorrow>true</testOnBorrow>
                <validationQuery>SELECT 1</validationQuery>
                <validationInterval>30000</validationInterval>
            </configuration>
        </definition>
    </datasource>

    <datasource>
        <name>WSO2AM_STATS_DB</name>
        <description>The datasource used for getting statistics to API Manager</description>
        <jndiConfig>
            <name>jdbc/WSO2AM_STATS_DB</name>
        </jndiConfig>
        <definition type="RDBMS">
            <configuration>
                <defaultAutoCommit>false</defaultAutoCommit>
                <url>jdbc:jtds:sqlserver://mydbserver:1433/wso2_apiStatsdb</url>
                <username>user</username>
                <password>pwd</password>
                <driverClassName>net.sourceforge.jtds.jdbc.Driver</driverClassName>
                <maxActive>50</maxActive>
                <maxWait>60000</maxWait>
                <testOnBorrow>true</testOnBorrow>
                <validationQuery>SELECT 1</validationQuery>
                <validationInterval>30000</validationInterval>
            </configuration>
        </definition>
     </datasource>

    <datasource>
        <name>WSO2BAM_DATASOURCE</name>
        <description>The datasource used for analyzer data</description>
        <definition type="RDBMS">
            <configuration>
                <defaultAutoCommit>false</defaultAutoCommit>
                <url>jdbc:jtds:sqlserver://mydbserver:1433/wso2_apiStatsdb</url>
                <username>user</username>
                <password>pwd</password>
                <driverClassName>net.sourceforge.jtds.jdbc.Driver</driverClassName>
                <maxActive>50</maxActive>
                <maxWait>60000</maxWait>
                <testOnBorrow>true</testOnBorrow>
                <validationQuery>SELECT 1</validationQuery>
                <validationInterval>30000</validationInterval>
            </configuration>
        </definition>
    </datasource>

        <datasource>
        <name>WSO2BAM_CASSANDRA_DATASOURCE</name>
        <description>The datasource used for Cassandra data</description>
        <definition type="RDBMS">
            <configuration>
                <url>jdbc:cassandra://localhost:9161/EVENT_KS</url>
                <username>admin</username>
                <password>admin</password>
            </configuration>
        </definition>
    </datasource>

    <datasource>
        <name>WSO2BAM_UTIL_DATASOURCE</name>
        <description>The datasource used for BAM utilities, such as message store etc..</description>
        <definition type="RDBMS">
            <configuration>
                <url>jdbc:cassandra://localhost:9161/BAM_UTIL_KS</url>
                <username>admin</username>
                <password>admin</password>
            </configuration>
        </definition>
    </datasource>

    <!-- The URL configs are loaded from cassandra-component.xml -->
    <datasource>
        <name>WSO2BAM_HIVE_INCREMENTAL_DATASOURCE</name>
        <definition type="RDBMS">
            <configuration>
                <username>admin</username>
                <password>admin</password>
                <dataSourceProps>
                    <property name="replicationFactor">1</property>
                    <property name="strategyClass">org.apache.cassandra.locator.SimpleStrategy</property>
                    <property name="readConsistencyLevel">QUORUM</property>
                    <property name="writeConsistencyLevel">QUORUM</property>
                    <property name="keyspaceName">HIVE_INCREMENTAL_KS</property>
                </dataSourceProps>
            </configuration>
        </definition>
    </datasource>

When I look in mydbserver/wso2_apiStatsdb I see that the following tables were created and have been updated with data:
API_REQUEST_SUMMARY, API_Resource_USAGE_SUMMARY
update:  some additional tables have been added and updated...
API_FAULT_SUMMARY, API_RESPONSE_SUMMARY, API_VERSION_USAGE_SUMMARY
However when I go to the publisher page I get:

As far as I can tell I've updated the publisher/store and gateway/key manager to send data to the BAM server.  The BAM server appears to process and put that summarized data in the sql server database.  My entries for SQL server database match for the publisher/store config and the BAM server config.  Does anyone have any ideas what I'm missing that will enable me to see the stats when in the publisher?

A: Can u please check if the EnableBillingAndUsage is set to false. This is available in conf/api-manager.xml
<EnableBillingAndUsage>false</EnableBillingAndUsage>

A: Are you running the BAM on port offset 1? As far as I can see you have BAM running on a different server. Try running BAM with port offset 1. The default config provided in the site is for a usecase where API Manager and BAM runs on the same server with port offsets (API M -0 and BAM -1). Hence all the relevant thrift ports are also incremented by 1 in the default config. Hence I suggest you to run BAM on offset 1.
In the meantime pls check if the MQSQL DB that has summarized stats contain any data inside them.

A: This can also happen if you haven't configured the summarized database correctly in API Manager. From what you have mentioned, API Manager seems to publish data correctly, but it's not fetching summarized data. Please see if you have defined WSO2AM_STATS_DB in master-datasources.xml inside APIM directory.

A: Gammonster, this has been figured out. It appears that the devil is indeed in the details - the runtime was trying to execute a sql query using the 'limit' keyword in a SQL Server database and SQL Server does not support 'limit'. It has 'top' instead.
Would have appreciated if the product documentation expressly identified SQL Server to not be a preferred DB instance for BAM.


text:
Q: set transaction_subject PayPal IPN Does anyone know how to set the transaction_subject in the return IPN from PayPal.
At the moment it is returning with the same content as my custom field even though the PayPal doc's say the following:
"Pass-through variable for your own tracking purposes, which buyers do not see.
Default – No variable is passed back to you. "
I need this to be different from the custom field because the transaction_subject is showing in the email that the buyer gets, which means they are seeing the contents of the custom field.
Thanks

A: It seems the PayPal developers on X.commerce do not know the purpose of the  transaction_subject variable or how to set it. Even PayPal's sample IPN message (table near bottom) provides no notes about the variable. Finally, PayPal's IPN & PDT Variables and Payments Standard HTML Variable Reference do not list it.
In parsing our IPNs, transaction_subject always contains the value of the custom pass-through variable, but I am unaware that either are shown to the buyer.
Setting transaction_subject using NVP within the HTML form has no effect on its value.
Contact merchant technical support because a "pass-through" variable displaying to the buyer is a bug.

A: I am seeing the transaction_subject set to the value of either item_name or item_number, can't tell which, as I am setting both those to the same value. I'm not seeing it set to the value of 'custom', which has a different value (in fact the outgoing hosted_button_id). This is in association with Subscribe buttons.

A: I am using the /js/paypal-button.min.js? form method. if I set
data-custom="{mycustomvar:3}"
the IPN result shows "transaction_subject":"{mycustomvar:3}"


text:
Q: cannot update initalState in redux-toolkit with createAsyncThunk Im trying to set and update initialState in redux toolkit after fetch operation
pageSlice.js
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { deletePage, getPages, savePage, updatePage } from "../../services/page.service";
import { initialPage } from "../../components";

export const getUserPages = createAsyncThunk(
    "pages/getUserPages",
    async() => {
        const pages = await getPages();
        return pages
    }
)

export const saveUserPage = createAsyncThunk(
    "pages/saveUserPage",
    async(page) => {
        const savedPage = await savePage(page);
        return savedPage;
    }
)

export const pageSlice = createSlice({
    name: "pages",
    initialState: {
        pageStatus: "idle",
        pages: []
    },
    reducers: {},
    extraReducers: {
        [getUserPages.pending]: (state) => {
            state.pageStatus = "loading";
        },
        [getUserPages.fulfilled]: (state, action) => {
            state.pages = action.payload
            state.pageStatus = "pageLoaded"
        },
        [getUserPages.rejected]: (state) => {
            state.pageStatus = "error"
        },

        [saveUserPage.pending]: (state) => {
            state.pageStatus = "loading";
        },
        [saveUserPage.fulfilled]: (state, action) => {
            state.pages.push(action.payload)
            state.pageStatus = "pageLoaded"
        },
        [saveUserPage.rejected]: (state) => {
            state.pageStatus = "error"
        }
    }
})

export default pageSlice.reducer;

initialState: {
        pageStatus: "idle",
        pages: []
    },

Working on note app with redux-toolkit. pages array will contain array of objects.
In extraReducers
[saveUserPage.fulfilled]: (state, action) => {
       // console.log(state.pages) if empty( undefined ) else [{element}]
       state.pages.push(action.payload)
       state.pageStatus = "pageLoaded"
    }

if initailState pages array contain any single element [saveUserPage.fulfilled] work fine.
but if array is empty then i get error
Cannot read property 'push' of undefined at pages/saveUserPage/fulfilled
if console.log(state.pages) in s
What I'm doing wrong ?

A: Based on the Error message you have mentioned Cannot read property 'push' of undefined at pages/saveUserPage/fulfilled, state.pages is not an empty array, It is undefined. That is the reason you are seeing this error.
Array.push operation, all it expects the variable to be array i.e. [], It doesn't matter whether it is empty or it has items.
Please check the below code block or some other operation, whether it is assigning it as 'undefined' in the first place.
  [getUserPages.fulfilled]: (state, action) => {
        state.pages = action.payload
        state.pageStatus = "pageLoaded"
  },

Workaround solution:
[saveUserPage.fulfilled]: (state, action) => {
    if(state.pages === undefined){
         state.pages = [];
         if(action.payload && action.payload.length > 0){ / Make sure that payload is an array
              state.pages = action.payload; //
         }
    }
    else{
        state.pages.push(action.payload);
    }

        state.pageStatus = "pageLoaded"
  },


text:
Q: Analog mux with active low enable.I/P and O/P state when enable is High I am using this mux (74LV4051D,118)from Nxperia for one of my applications.The functional table is given below.
When the Enable is High S0, S1, S2 are don't care, and the switch is off.
May I know when Enable is high,can I assume both I/P (S0-S2) and O/P(Z) are at high impedance state.

A:
May I know when Enable is high, can I assume both I/P (S0-S2) and
O/P(Z) are at high impedance state.

Focus on the last line of the table in your question: -

A switch being off will mean high impedance. Inputs S0 to S2 will remain high impedance (because they are inputs) irrespective of the state of the enable input.

A: It seems you don't understand exactly what's the behavior of an analog switch (aka CMOS transmission gate) is. And this analog mux/demux conceptually is just 8 analog switch which have one terminal in common. The added complexity just comes from the selection/decode logic.
The high impedance state of a 3-state gate means the output is completely disconnected from the internal circuitry.
However, in this case, when the mux/demux is enabled, the selected "input" Y is electrically connected to the "output" Z.
I used quotes because what is input and what is output in an analog switch is arbitrary. In reality the selected terminal Y is connected to Z almost like a wire connected the two terminals.
Therefore there is no "high impedance state" as you would have in a 3-state output because Y is connected to Z and for the circuit to do anything sensible either Y or Z (or BOTH) must be connected to something.
IF your question is "once the chip is enabled, are Y and Z connected to something else internally", the answer is no.
You can understand the switch operation by looking at the internal
schematic (emphasis mine):

The connection between (any) Y and Z is done with a paralleled PMOS/NMOS pair (in yellow) and when the switch is enabled the current path is that in red.
Once both the PMOS and the NMOS are switched off, Y and Z are more or less insulated from the internal circuitry of the chip.


text:
Q: Put start and end tags in separate include files I want to include html codes from different files into my main.xhtml page. But this doesn't work with the <ui:include>. Because the codes are separated to different files and this makes that each file has invalid html codes.
What I mean:
html1.html

html2.html

main.xhtml
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
                xmlns:h="http://java.sun.com/jsf/html"
                xmlns:f="http://java.sun.com/jsf/core"
                xmlns:ui="http://java.sun.com/jsf/facelets"
                xmlns:p="http://primefaces.org/ui">

INCLUDE HTML1

<h:outputLabel value="blablabla" />

INCLUDE HTML2

</ui:composition>

Is there a way to accomplish this task?

A: This doesn't make sense. You're not allowed to have syntactically invalid XML in an individual Facelet file. Moreover, you can't include plain vanilla HTML via <ui:include> or whatever <ui:xxx> tag. Those have to be real Facelet compositions (and thus be syntactically valid XML).
I gather that you'd like to control the body of an include template. In that case, put them together in a single template file with an <ui:insert> representing the place where you'd like to insert the body:
<ui:composition
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
>

        <ui:insert/>

</ui:composition>

Then, use <ui:decorate> on it:
<ui:decorate template="html.xhtml">
    <h:outputText value="blablabla" />
</ui:decorate>

Note that <h:outputLabel> serves an entirely different purpose.
See also:

*

*What is the real conceptual difference between ui:decorate and ui:include?

*How to include another XHTML in XHTML using JSF 2.0 Facelets?

A: Divide your code into more files like this:
include file1_before_div

include file1_after_div
<h:outputLabel value="blablabla" />
include file2_before_div_close

include file2_after_div_close


text:
Q: How can I invalidate Chrome caching programmatically on client side? I have the following very specific bug in my web application, caused by a curious interaction between the History API and the way Chrome caches pages.

*

*User A logs in and uses a page like /home on the site. This page is an SPA type page that uses the History API to maintain a history stack as you navigate within the page. So as you do stuff, the url may change to /home/with/new/state This page also has a message like "Hello, User 1" on it.

*User A logs out of the application.

*On the same computer and browser, User B logs in and goes to /home, /home/with/new/state. Again, this is not a true navigation, just modifying the url via the history API.

*User 2 clicks some link to navigate (for real) to another page on the site.

*User 2 clicks the back button

*The browser goes back to /home/with/new/state, but to the cached version that still says "Hello, User 1" on it.

Naturally, this is really confusing for users.
I can fix this by setting a more aggressive cache-control policy, forcing a reload of the /home page, but that would increase bandwidth to the site. The vast, vast majority of the time, the existing caching is fine, because the user isn't changing, so I don't really want to do this server side, for all users, always. It also is only an issue in Chrome; somehow the other browsers handle this correctly. I'd prefer a mechanism to bust the cache ONLY when I have this situation of a user change.
How might I accomplish this?


text:
Q: Windows form actions like close through custom user control code? I have made a title bar (custom user control) that contains five controls. They are all labels but each one do different "job".
For example, one of them is an exit form button. If I put a click event into my custom user control's code, for example...
Private Sub ExitButton_Click(sender As Object, e As EventArgs) Handles ExitButton.Click
    Close()
End Sub

I get this error...
BC30451 'Close' is not declared. It may be inaccessible due to its protection level.

On the other hand I can't put it into my project's code cause it can't find ExitButton as "isolated" control and do close().
Any suggestions? I also want to do the same thing with minimize, maximize etc.

A: Let me guess; your button is in the user control. You try to call Close() on the UserControl class, which obviously is not a window and does not have it.
There are three solutions:

*

*Use the ParentForm property and call Close() on it (e.g. ParentForm.Close()). Easy but not too flexible; if you want to do other things than those which are implemented in the Form base class (like Close()), e.g. specific to the main form, you would have to cast it first and check if it's really the form you thought of. Also, all those things would need to be exposed with Public or Internal, don't expose what you don't have to expose.

*You pass the Form to the UserControl. Horrible because passing stuff around just ends up in spaghetti code.

*Better, raise an event by the UserControl which you handle in the form the UserControl is on. That's probably the most flexible approach.

Here's a small code example solving this with an event:
Open the code of the UserControl and add an event signature and raise that event when you click the button:
Public Class MyUserControl

    Public Event ButtonClicked(sender As Object, e As EventArgs)

    Private Sub MyButton_Click(sender As Object, e As EventArgs) Handles MyButton.Click
        RaiseEvent ButtonClicked(sender, e)
    End Sub

End Class

Then, in your Form, attach to the ButtonClicked event of the UserControl:
Public Class MyForm

    Private Sub MyUserControl1_ButtonClicked(sender As Object, e As EventArgs) Handles MyUserControl1.ButtonClicked
        Close()
    End Sub

End Class

If you re-use the event for multiple buttons, you can check which button it is through the sender passed to the event. (Of course this can be optimized by just passing a casted Button instance as the event parameter, this is just a simple example).

A: Where did you get "close" from? You exit an application with application.exit()

A: If you want to close Application you can use:
Application.Exit()
If you want to close Form:
Me.Close()

A: To close the form you use me.
me.close


text:
Q: ImportError for Django Piston handler that isn't tied to a model I have created a custom handler (CustomHandler) that isn't tied to a model in the ORM and I think it's rigged up correctly, but I'm getting an ImportError: cannot import CustomHandler when trying to import it into my resources.py. Here is my setup:
custom_handlers.py:
from piston.handler import BaseHandler

class CustomHandler(BaseHandler):
    allowed_methods = ('GET',)

    def read(self, request):
        return 'test'

resources.py:
from piston.resource import Resource
from piston.utils import rc
import simplejson as json
from api.authentication import DjangoAuthentication
from api.handlers import CustomHandler # ERROR THROWN HERE

auth = DjangoAuthentication(realm='...')

class JSONResource(Resource):
    def determine_emitter(self, request, *args, **kwargs):
        """
        Default to the json emitter.
        """
        try:
            return kwargs['emitter_format']
        except KeyError:
            pass
        if 'format' in request.GET:
            return request.GET.get('format')
        return 'json'

    def form_validation_response(self, e):
        """
        Turns the error object into a serializable construct.
        """
        resp = rc.BAD_REQUEST
        json_errors = json.dumps(
            dict(
                (k, map(unicode, v))
                for (k, v) in e.form.errors.iteritems()
            )
        )
        resp.write(json_errors)
        return resp

custom_handler = JSONResource(CustomHandler, authentication=auth)

urls.py:
from django.conf.urls.defaults import patterns, url

from api.resources import custom_handler

urlpatterns = patterns('',
    url(r'^things/$', custom_handler),
)

UPDATE: I've tried manually compiling the pys into pycs with no luck. I also read this in Piston's docs:

When you create a handler which is tied to a model, Piston will
  automatically register it (via a metaclass.)

But I can't find anything in the docs about creating a handler that isn't tied to a model, specifically how to register it.

A: Had to add from api.handlers.custom_handlers import CustomHandler to api/handlers/__init__.py


text:
Q: seleniumpython dropdown list div i whould like to select the element "aout" for example on the folloing dropdown list with python selenium

                    mars

                        janvier
                        février
                        mars
                        avril
                        mai
                        juin
                        juillet
                        août
                        septembre
                        octobre
                        novembre
                        décembre

                    <input type="hidden" name="date_m" value="4">

When I try this code…
driver.find_element_by_id("dob2_m").click()
driver.find_element_by_id("dob2_m").find_element_by_xpath('//*[@data-id="8"]').click()

I get this error…
error script picture
How to do it ?
Help me please
Thank you

A: The error snippet clearly says the error occurs when webdriver tries to interact with element with class="option-1-day". But this element is not present in the code you have shared. So i assume, you are facing issue while trying to select date from dropdown.
1.Before clicking dropdown element, try to add wait statement
wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, 'someid')))

2. It will occur when the webelement you trying to click, located at end of dropdown. So it can only clickable once scrolling it down.
Actions action = new Actions(driver);
action.moveToElement(element);

A: Use select class  for handling  dropdown.
s1= Select(driver.find_element_by_id('id_of_your_element'))//in this case it would be dob2_m
s1.select_by_visible_text('janvier')
Ignore formatting  using mobile to answer.
Option 2
Use javascriptexecutor to scroll and click on element
ele= self.web_driver.find_element_by_xpath('SOME_XPATH')
coordinates = ele.location_once_scrolled_into_view
self.web_driver.execute_script('window.scrollTo({}, {});'.format(coordinates['x'], coordinates

A: You have to use ActionChains.
When you call methods for actions on the ActionChains object, the actions are stored in a queue in the ActionChains object. When you call perform(), the events are fired in the order they are queued up.
More information.
Here is an example:
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import Select

...#navigate to page
el=driver.find_element_by_id("bxFormPesquisa") #here I get the dropdown element
ActionChains(driver).click(el).perform()
select = Select(driver.find_element_by_name('bxFormPesquisa')) #again
select.select_by_visible_text('AL') #it is the text in dropdown list
#dropdown should be selected with value from line above


text:
Q: After updating pod, I got this error. Invalid UIAccessibilityTraits 'tab' I'm using react-native-tab-view. I'm not sure this has something to do with this error.
 <TabView
            bounces={false}
            navigationState={this.state}
            swipeEnabled={false}
            renderScene={() => null}
            renderTabBar={props => (
              <TabBar
                {...props}
                indicatorStyle={{
                  backgroundColor: "#212121",
                  height: "100%",
                  width: "38%",
                  marginLeft: "5%"
                }}
                style={{ backgroundColor: "#FFD54F" }}
                inactiveColor="#757575"
                activeColor={"#212121"}
                pressOpacity={0.9}
                tabStyle={{
                  backgroundColor: "#FFD54F",
                  marginBottom: 3
                }}
                labelStyle={{ fontWeight: "bold" }}
              />
            )}
            onIndexChange={index => this.setState({ index })}
            initialLayout={{
              width: Dimensions.get("window").width
            }}
          />
          {pages}

Above code worked before updating.
This error occurs when I enter the screen using react-native-tab-view.
How can I solve this?
Thanks!

A: It was version issue. I just re-installed react-native-tab-view@2.11.0. and it worked! I hope this would be useful to others!


text:
Q: How to select single or multiple checkbox buttons? For each question, I want to compile an if statement where by checking through each question if the .ReplyType text input equals Single, then the user can only select a single checkbox button option, otherwise if the .ReplyType text input equals Multiple, then the user can select multiple checkbox button options.
My question is how to implement this if a single button or multiple buttons are selected depending on the .ReplyType text input? Is it better in PHP or JavaScript?
Below is relevant code:
<form action='results.php' method='post' id='exam'>

    <?php

//COMPILE OPTION BUTTONS

    function ExpandOptionType($option) {
        $options = explode('-', $option);
        if(count($options) > 1) {
            $start = array_shift($options);
            $end = array_shift($options);
            do {
                $options[] = $start;
            }while(++$start <= $end);
         }
         else{
            $options = explode(' or ', $option);
         }

         foreach($options as $indivOption) {
             echo '
<input type="checkbox" name="options[]" id="option-' . $indivOption . '" value="' . $indivOption . '" />' . $indivOption . '
';
         }

    }

    foreach ($arrQuestionId as $key=>$question) {

    ?>

//DISPLAY QUESTION NUMBER FOR EACH QUESTION

<?php echo htmlspecialchars($arrQuestionNo[$key]);?>

//DISPLAY OPTION CHECKBOX BUTTONS FOR EACH QUESTION
    <?php echo ExpandOptionType(htmlspecialchars($arrOptionType[$key])); ?>

//DISPLAY REPLY TYPE TEXT INPUT FOR EACH QUESTION

Reply Type: <input type='text' class='replyType' name='replytype' value='<?php echo htmlspecialchars($arrReplyType[$key]); ?>' />

    <?php

    }

    ?>

A: You should do both, JavaScript and PHP implementation.
JavaScript is better for the user to get a response before submitting the form.
PHP is important, because JavaScript validation can be bypassed (just deactivate JavaScript) in this case your PHP should still validate that you get consistent data.
Anyway: Use radio-buttons for single-select and checkboxes for multi-select. Not that it's already implemented in every browser and meant to be used that way, most users have already learned this behavious and won't be surprised by your JavaScript (or PHP) validation.


text:
Q: ADB / Android Studio not recognizing my physical device? In Android Studio, the list of devices and emulators doesn't list my physical device when I plug it in (Google Pixel 2). I've tried adding the device ID found w/ lsusb to the ~/.android/adb_usb.ini as described in the answer here, but to no avail :(
My only hint at what's going on is when I plugged the phone in for the first time, no dialog appeared asking if I trusted my computer. I recall this happened on my desktop computer where it works fine.
Any ideas greatly appreciated! Thanks!
Edit:
My pixel is running Android version 10, and when plugged in it's in 'File transfer/Android auto' mode. However I have tried switching it to PTP without any luck. Running adb devices returns an empty list of connected devices, USB debugging through chrome://inspect doesn't list my phone either, killing and restarting the adb server doesn't seem to change any of this.


text:
Q: Reduce image size of multiple images via ssh I have an e-commerce website I made for a client.
As with any e-commerce site, there are a lot of pictures.
About a hundred of these pictures were uploaded by me, provided by my client.
The other 400 were uploaded by client.
The problem is that the first set of images that my client provided me with were about 100kb each, which is not such a big deal. The second set of images, the ones my client uploaded, were about 5-9 MBs in size. Obviously I didn't see this until it was too late.
So my question is this: How can I reduce the image size of all those load-heavy images to something more around 100-200kb through ssh/commandline/php.
I'm also talking about re-scaling the images to something smaller (currently they are about 3700px x 5600px).
Please note: I don't need a solution to re-scale the images when they are being uploaded.
I need a solution to re-scale the images that are already on the server.

A: Assuming your server is a Unix, you can use imagemagick/convert tool:
 http://doc.ubuntu-fr.org/imagemagick
You can also use PHP+GD, see:
 http://fr.php.net/manual/en/book.image.php


text: Q: Should we can put multiple different object on a singlesurefaceview in ARCore? Should we can put multiple different objects on a singlesurefaceview in ARCore Android. And if possible than we can able to rotate that single particular object only and another all are remain as it is at same position.


text:
Q: scraping of all ios apps for testing i'm wondering how i could download all ios apps (.ipa files). i want to make a script (prefered: python). i know how to program but i have no clue how to download the apps!
apple provides a multi-gb list of all metadata, which is useful, but i can not download the apps itself without using itunes because there are no http links. automatization of the itunes gui would be a very crappy way of doing it. do you know how i could download all of them?
the only other way, which came to my mind was using unofficial ios app stores which provide http links, but i want to download them from the offical store.
sincerly trashy


text:
Q: NSFW proposal on Area51
See flags for deletion reason

There is a proposal on Area 51 that definitely does NOT fit with the family-friendly nature of StackExchange, given the current level of integration (site footer, multicollider, "all sites" list, merged accounts). I have flagged it for moderator attention several times, but it was ignored.
EDIT: Also see this

A:
There is a proposal on Area 51 that definitely does NOT fit with the family-friendly nature of StackExchange.

You can't build a family without having sex.  So long as the discussion is mature, why would it not be inherently "family-friendly"?  ;)
Really though...  there are channels on your TV that I assume you wouldn't want your hypothetical kids watch.  I would think it more productive to discourage their viewing of those channels, than to throw the TV out completely.
I'm sure every user here could list several SE sites that they don't find interesting or even borderline offensive.

A: As the proposed site is likely to be of more interest to adults, and there are even some adults who may not want to come across this site accidentally, the proposed site will have two unique features:

*

*A "warning" page requiring you to confirm that you are over 18 before you enter the site (this would set a cookie. See Reddit's various "not safe for work" sites for an example).

*Questions from this site would not flow into stackexchange.com's list of hot questions
The way the current proposal is written it's fairly safe to assume that the site in question will be "safe for work" and require the use of clinical language, which is already the policy when discussing questions of an adult nature on other sites in our network.

A: It seems apparent from your comments on the other answers that you aren't actually concerned about the network being "family friendly" or "safe for work" in the common sense of the terms.  Rather, you simply don't like the idea of sexuality being discussed openly.
Others have expressed their opinion of that attitude, so I will refrain.  But SE is not going to end a proposal or site simply because someone doesn't like its topic.  I have friends with no interest in programming who participate in other sites on the network, yet they do not clamor for Stack Overflow to be closed.  There are even people who reject advancements in technology that eliminate jobs and therefore oppose the creation of software, and they too would be ignored if they said SO should be closed.
It's your right to hold the opinions that you do.  It is also your right to leave if you find Stack Exchange objectionable.  It's even your right to express your opinion about SE.  But the idea that a site should be closed because a minority does not think the topic should be discussed is ridiculous.
If you feel you cannot participate in something that has a separate area for the clinical discussion of sexuality, then I must (seriously and in all good faith) urge you to stop using the internet.  The internet at large has no such clear dividing lines and if you have not stumbled across objectionable content yet, you will.  And it will be much worse than the proposal.

A:
There is a proposal on Area 51 that definitely does NOT fit with the family-friendly nature of StackExchange.

From the site description: Proposed Q&A site for a site for medical professionals, sex educators, counselors, and others to discuss both the physical and emotional aspects of sexual and/or romantic interactions
This site is for the kind people that are going to have to help your children adjust after 18 years of you keeping them under lock and key. You should be thankful.

A: I just posted this on the Movies SE which has raised similar concerns — all of which applies equally well to a Sexuality Stack Exchange …
Should adult themes be handled with care?

The Terms of Service prohibits usage of this site for users below the age of 13.
The content of all Stack Exchange sites must be "work safe." That means no explicit imagery or language is allowed on the sites. Beyond that, the ideas or themes expressed are not expected to be watered down to be consumed by an 8-year old. That's true of almost any literature, television program, radio program, or news outlet anywhere. Finding age-appropriate content for children — whether that is in literature, television, or web sites — is the responsibility of the parent.

A: I have to say, if you aren't interested in a particular proposal or site you just ignore it. I do this with sites like CS Theory (not singling them out for any reason other than I don't understand it so I find it very easy to ignore) and you can do the same for this one.
If enough people support it it will graduate, if it is marginal it won't - just let the proposal system work as it should and see where it goes.
I don't see Stack Exchange as a whole being family friendly or family unfriendly.


text:
Q: Poor accuarcy score for Semi-Supervised Support Vector machine I am using a Semi-Supervised approach for Support Vector Machine in Python for the image classification from PASCAL VOC 2007 data.
I have tried with the default parameters from the libraries and also tuned them but it get extremely bad accuracy of about only ~ 2%.
Below is my code:
import pandas as pd
import numpy as np
from sklearn import decomposition
from sklearn.model_selection import train_test_split
from numpy import concatenate
import numpy as np
from sklearn import datasets
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn import decomposition
import warnings
warnings.filterwarnings("ignore")

color_layout_features = pd.read_pickle("color_layout_descriptor.pkl")
bow_surf  = pd.read_pickle("bow_surf.pkl")
color_hist_features  = pd.read_pickle("hist.pkl")
labels  = pd.read_pickle("labels.pkl")

# Feat. Scaling
def scale(X, x_min, x_max):
    nom = (X-X.min(axis=0))*(x_max-x_min)
    denom = X.max(axis=0) - X.min(axis=0)
    denom[denom==0] = 1
    return x_min + nom/denom

# normalization
def normalize(x):
    return (x - np.min(x))/(np.max(x) - np.min(x))

color_layout_features_scaled = scale(color_layout_features, 0, 1)
color_hist_features_scaled = scale(color_hist_features, 0, 1)
bow_surf_scaled = scale(bow_surf, 0, 1)

features = np.hstack([color_layout_features_scaled, color_hist_features_scaled, bow_surf_scaled])

# define dataset
X, Y = features, labels
X = normalize(X)
pca = decomposition.PCA(n_components=100)
pca.fit(X)
X = pca.transform(X)

X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.30, random_state=1, stratify=Y)
# split train into labeled and unlabeled
X_train_lab, X_test_unlab, y_train_lab, y_test_unlab = train_test_split(X_train, y_train, test_size=0.30, random_state=1, stratify=y_train)
# create the training dataset input
X_train_mixed = concatenate((X_train_lab, X_test_unlab))
# create "no label" for unlabeled data
nolabel = [-1 for _ in range(len(y_test_unlab))]
# recombine training dataset labels
y_train_mixed = concatenate((y_train_lab, nolabel))

from semisupervised import S3VM

model = S3VM(kernel="Linear", C = 1e-2, gamma = 0.5, lamU = 1.0, probability=True)
#model.fit(X_train_mixed, _train_mixed)
model.fit(np.vstack((X_train_lab, X_test_unlab)), np.append(y_train_lab, nolabel))
#model.fit(np.vstack((label_X_train, unlabel_X_train)), np.append(label_y_train, unlabel_y))

# predict
predict = model.predict(X_test)
acc = metrics.accuracy_score(y_test, predict)
# metric
print("accuracy", acc*100)

accuracy 2.6692291266282298
I am using a Transductive version of SVM (TSVM) from the semisupervised library. But not sure what am I doing wrong so that even after tweaking the parameters I still get the same result. Any inputs would be helpful.
I refer https://github.com/rosefun/SemiSupervised/blob/master/semisupervised/TSVM.py to make the implementation. Any inputs would be helpful.

A: Please consider that according to link Documentation "The unlabeled samples should be labeled as -1".


text:
Q: Problemas com $resource Angularjs Estou com um problema usando $resource do angularjs. Os dados vindo da API só são exibidos no service mas quando chamo no controler a lista vem vazia.
//service
angular.module('core.rota').
    factory('Rota', function ($resource,$cookies, $location, $httpParamSerializer,LoginRequiredInterceptor) {
        var url =  '/api/rota/:id/'

                //Carregamento dos locais
        var locaisQuery = {
            url:'/api/core/local/',
            method:"GET",
            params: {},
            isArray: true,
            cache:false,
            interceptor: {responseError: LoginRequiredInterceptor},
            transformResponse: function (data, headersGetter, status) {
               var finalData = angular.fromJson(data)
                console.log(finalData)// ok os dados são exibidos
               return finalData.results
            }
        }

        var token = $cookies.get("token")
        if (token){
            minhasRotasQuery["headers"] = {"Authorization": "JWT " + token}
            rotasQuery["headers"] = {"Authorization": "JWT " + token}
            locaisQuery["headers"] = {"Authorization": "JWT " + token}
        }

        return $resource(url, {},{
            minhas:minhasRotasQuery,
            todas:rotasQuery,
            query:locaisQuery,
            get:getRota,
            create:createRota,
            createServ:createServico,
            // delete: commentDelete,
            update: updateRota,
        })
});

//component
angular.module('rotacreate').
        component('rotacreate',{
            templateUrl:'/api/templates/rotas/rotacreate.html',
            controller: function(Rota,User,$cookies, $http, $location, $routeParams, $scope,$filter,moment,LoginRequiredInterceptor){

            Rota.query(function(data){
                    console.log(data)//Array vazio Array[ ]
                    $scope.users = data
                },function (err_data) {
                    console.log(err_data)
                })
}

A: O seu código atual não está executando o método e aguardando a resolução da promise - na verdade está apenas passando objetos para o método.
Altere de
Rota.query(function(data){ [...]

para
Rota.query().then(function(data){ [...]

ou
Rota.query().$promise.then(function(data){ [...]

Dependendo de sua versão.


text:
Q: Why is this strange character included in emails sent from cakePHP running on my Ubuntu server? I am seeing some strange characters appearing in emails that are sent out form my CakePHP app running on an ubuntu server.
The characters are -
D with stroke through it - Đ - this appears where I am including a cakephp variable
O with tilde - Õ - instead of apostrophe
E with accute - É - instead of ... (3 dots)
Any idea why they would be appearing? The O with tilde appears in place of apostrophes so I assume its a character encoding issue..
I am using Cake to send html emails.
any leads appreciated
thanks

A: Try these
1) in config/core.php search this App.encoding, the line should look like this Configure::write('App.encoding', 'UTF-8');, set it to UTF-8 if it is not.
2) In your layout, in the head section add this,
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

3) Change your entire project's encoding to UTF-8 in your IDE(if you are using Zend Studio, just right click on the project and select 'properties', then select UTF-8 encoding).
Though sending email has nothing to do with database(of course if are you not fetching some data from there for sending), but you could perhaps add 'encoding' => 'utf8' line in your database.php file under $default configuration, to not have any encoding issues saving in db.
Hope it helps.


text:
Q: Elasticsearch NEST create case-insensitive index How can I create an index in NEST which compares case-insensitive with TermQuery?
I tried following (and many similar approaches) but my TermQuery only returns case-sensitive matching results.
Client.CreateIndex("my_index", (c) => c
    .Settings(s => s
        .Analysis(an => an
            .Analyzers(ans => ans
                .Custom("analyzer_keyword", cu => cu
                    .Tokenizer("keyword")
                    .Filters("lowercase")
                 )
                .Custom("analyzer_term", cu => cu
                    .Tokenizer("term")
                    .Filters("lowercase")
                 )
            )
        )
    )
);

A: I do not know how to do this with NEST but one thing I know - you have two options:

*

*you can specify default analyzer

or

*you need to use your analyzer_keyword and analyzer_term for your document's fields.

Because your code now only specifies some custom analyzers which are not used anywhere.
Take a look at specifying an index time analyzer:

At index time, if no analyzer has been specified, it looks for an analyzer in the index settings called default. Failing that, it defaults to using the standard analyzer.

and specifying a search time analyzer:

The analyzer to use to search a particular field is determined by looking for:

*

*An analyzer specified in the query itself.

*The search_analyzer mapping parameter.

*The analyzer mapping parameter.

*An analyzer in the index settings called default_search.

*An analyzer in the index settings called default.

*The standard analyzer.


text:
Q: Mouse not usable on specific USB port (Windows and Linux) This is an operating system-agnostic issue, but I have logs from Ubuntu 14.10.
I have this Perixx PERIMICE-710R USB wireless mouse:

It is not usable through a specific USB port on a Lenovo Y510p laptop:

The mouse works on the two USB ports on the other side of this laptop.
Here is why Linux says that mouse cannot be used (from /var/log/syslog):
Feb 12 19:53:10 Deltique kernel: [  165.657532] usb 3-2: new full-speed USB device number 15 using xhci_hcd
Feb 12 19:53:10 Deltique kernel: [  165.825757] usb 3-2: device descriptor read/64, error -71
Feb 12 19:53:10 Deltique kernel: [  165.929804] xhci_hcd 0000:00:14.0: Setup ERROR: setup context command for slot 15.
Feb 12 19:53:10 Deltique kernel: [  165.929816] usb 3-2: hub failed to enable device, error -22
Feb 12 19:53:10 Deltique kernel: [  166.041952] usb 3-2: new full-speed USB device number 16 using xhci_hcd
Feb 12 19:53:10 Deltique kernel: [  166.210149] usb 3-2: device descriptor read/64, error -71
Feb 12 19:53:10 Deltique kernel: [  166.314214] xhci_hcd 0000:00:14.0: Setup ERROR: setup context command for slot 16.
Feb 12 19:53:10 Deltique kernel: [  166.314227] usb 3-2: hub failed to enable device, error -22
Feb 12 19:53:10 Deltique kernel: [  166.426300] usb 3-2: new full-speed USB device number 17 using xhci_hcd
Feb 12 19:53:10 Deltique kernel: [  166.426598] usb 3-2: Device not responding to setup address.
Feb 12 19:53:11 Deltique kernel: [  166.630703] usb 3-2: Device not responding to setup address.
Feb 12 19:53:11 Deltique kernel: [  166.834618] usb 3-2: device not accepting address 17, error -71
Feb 12 19:53:11 Deltique kernel: [  166.946822] usb 3-2: new full-speed USB device number 18 using xhci_hcd
Feb 12 19:53:11 Deltique kernel: [  166.947120] usb 3-2: Device not responding to setup address.
Feb 12 19:53:11 Deltique kernel: [  167.151232] usb 3-2: Device not responding to setup address.
Feb 12 19:53:11 Deltique kernel: [  167.355159] usb 3-2: device not accepting address 18, error -71
Feb 12 19:53:11 Deltique kernel: [  167.355257] usb usb3-port2: unable to enumerate USB device

After setting the modprobe setting options usbcore old_scheme_first=y as suggested by this email, this line showed:
Feb 12 20:09:10 Deltique kernel: [  470.466364] usb 3-2: new low-speed USB device number 29 using xhci_hcd

After five seconds, presumably usbcore tried to fall back to its "new scheme" and the same errors above were logged again.
Here is Linux successfully recognizing the USB device on a different USB port on the same computer:
Feb 12 20:03:49 Deltique kernel: [  148.210664] usb 3-4: new full-speed USB device number 26 using xhci_hcd
Feb 12 20:03:49 Deltique kernel: [  148.341256] usb 3-4: New USB device found, idVendor=062a, idProduct=4101
Feb 12 20:03:49 Deltique kernel: [  148.341264] usb 3-4: New USB device strings: Mfr=1, Product=2, SerialNumber=0
Feb 12 20:03:49 Deltique kernel: [  148.341268] usb 3-4: Product: 2.4G Keyboard Mouse
Feb 12 20:03:49 Deltique kernel: [  148.341272] usb 3-4: Manufacturer: MOSART Semi.
Feb 12 20:03:49 Deltique kernel: [  148.341556] usb 3-4: ep 0x81 - rounding interval to 64 microframes, ep desc says 80 microframes
Feb 12 20:03:49 Deltique kernel: [  148.343354] input: MOSART Semi. 2.4G Keyboard Mouse as /devices/pci0000:00/0000:00:14.0/usb3/3-4/3-4:1.0/0003:062A:4101.0007/input/input19
Feb 12 20:03:49 Deltique kernel: [  148.343614] hid-generic 0003:062A:4101.0007: input,hidraw0: USB HID v1.10 Keyboard [MOSART Semi. 2.4G Keyboard Mouse] on usb-0000:00:14.0-4/input0
Feb 12 20:03:49 Deltique kernel: [  148.346032] input: MOSART Semi. 2.4G Keyboard Mouse as /devices/pci0000:00/0000:00:14.0/usb3/3-4/3-4:1.1/0003:062A:4101.0008/input/input20
Feb 12 20:03:49 Deltique kernel: [  148.346454] hid-generic 0003:062A:4101.0008: input,hiddev0,hidraw1: USB HID v1.10 Mouse [MOSART Semi. 2.4G Keyboard Mouse] on usb-0000:00:14.0-4/input1
Feb 12 20:03:49 Deltique mtp-probe: checking bus 3, device 26: "/sys/devices/pci0000:00/0000:00:14.0/usb3/3-4"
Feb 12 20:03:49 Deltique mtp-probe: bus: 3, device: 26 was not an MTP device

I am able to mount USB mass storage devices on the right USB port, so why can't I use a mouse on this port?

A: Your plugging your mouse into USB 3.0 Port,
Feb 12 19:53:11 Deltique kernel: [  167.355257] usb usb3-port2: unable to enumerate USB device

Your external drives have 3.0 USB support feature so it's working..
If your mouse need to work with USB 3 Port you need to install the driver for USB 3.

A: Similar type of bugs I also used to get, This might be because you are trying to connect to a High speed USB port by a low speed device.
Put your USB port informations from the system information.
usb 3-4: new full-speed USB device number 26 using xhci_hcd
Go through this links for further details
http://www.linux-usb.org/FAQ.html#ts6
http://ubuntuforums.org/showthread.php?t=1731989
https://bugs.launchpad.net/ubuntu/+source/linux-source-2.6.15/+bug/54273

A: The trouble might be because Windows 8.1 uses a generic driver for the USB 3 port.
Try to find a better driver on the manufacturer's website.
You can find out the make and driver details in the Device Manager under Universal Serial Bus controllers.
If this is for example an Intel USB hub, use the Intel Driver Update Utility
to automatically identify and find drivers for all Intel hardware on the computer.
If a non-generic driver does not help, the problem is probably due to poor hardware implementation
of the USB 3 port by Lenovo.
A simple google search for Lenovo Y510p "usb 3" has this in the first page of results:
USB 3.0 port does not work with Kingston 32 GB usb 3.0 stick
Y510p Usb 3.0 drop out
Lenovo IdeaPad Y510P USB 3.0 HDD connected to USB 3.0 port won't power off after unmounting
Intensity Shuttle USB 3.0 fix for Win 8 64
These articles imply that some devices have problems when plugged-in to this port,
problems that they do not experience when connected to a USB 2 port,
as is exactly your case.
The source of the problem can either be hardware or driver.
While the driver can be replaced, one cannot do that with the hardware.

A: They say violence never solved anything, but after prying open my laptop and punching the USB port senseless while shouting, "Work, you stupid thing!", this miracle happened:
Mar  8 20:48:56 Deltique kernel: [  712.368555] usb 3-2: new full-speed USB device number 62 using xhci_hcd
Mar  8 20:48:56 Deltique kernel: [  712.498967] usb 3-2: New USB device found, idVendor=062a, idProduct=4101
Mar  8 20:48:56 Deltique kernel: [  712.498972] usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=0
Mar  8 20:48:56 Deltique kernel: [  712.498974] usb 3-2: Product: 2.4G Keyboard Mouse
Mar  8 20:48:56 Deltique kernel: [  712.498976] usb 3-2: Manufacturer: MOSART Semi.
Mar  8 20:48:56 Deltique kernel: [  712.499161] usb 3-2: ep 0x81 - rounding interval to 64 microframes, ep desc says 80 microframes
Mar  8 20:48:56 Deltique kernel: [  712.500538] input: MOSART Semi. 2.4G Keyboard Mouse as /devices/pci0000:00/0000:00:14.0/usb3/3-2/3-2:1.0/0003:062A:4101.000F/input/input25
Mar  8 20:48:56 Deltique kernel: [  712.500728] hid-generic 0003:062A:4101.000F: input,hidraw0: USB HID v1.10 Keyboard [MOSART Semi. 2.4G Keyboard Mouse] on usb-0000:00:14.0-2/input0
Mar  8 20:48:56 Deltique kernel: [  712.502617] input: MOSART Semi. 2.4G Keyboard Mouse as /devices/pci0000:00/0000:00:14.0/usb3/3-2/3-2:1.1/0003:062A:4101.0010/input/input26
Mar  8 20:48:56 Deltique kernel: [  712.502908] hid-generic 0003:062A:4101.0010: input,hiddev0,hidraw1: USB HID v1.10 Mouse [MOSART Semi. 2.4G Keyboard Mouse] on usb-0000:00:14.0-2/input1
Mar  8 20:48:56 Deltique mtp-probe: checking bus 3, device 62: "/sys/devices/pci0000:00/0000:00:14.0/usb3/3-2"
Mar  8 20:48:56 Deltique mtp-probe: bus: 3, device: 62 was not an MTP device

In all seriousness, the reason the mouse was not usable was a hardware problem with the USB port.  The cause is unknown, but I probably tripped over a USB device that was connected to that port in the past.


text:
Q: Part with marking code "ZO" "607" Can anyone please identify part with marking code "ZO" "607" it has 6 pins and I think the package is WLCSP.

A: Could it  be ZQ? From what I can see the pinout looks like it could match.
"MIC94165YCS - ZQ - 1.5mm × 1mm 6-Ball WLCSP"
http://static6.arrow.com/aropdfconversion/49e0c46145f1e0fbafdc3eb2279f6f3a5b83b03c/141mic9416x.pdf


text:
Q: What is wrong with my python 2 code that incorporates a wii remote that activates a buzzer via GPIO on a raspberry pi zero w? Here is my python code that I am using. I am trying to use a wii remote to trigger a buzzer. I thought this would be an interesting use for my old wii remote. The code that interacts with the buzzer works fine because I used an example script to test it. However, when I try and run it I keep getting this one error (see bottom). I am new to python and would appreciate any help.
   import cwiid
   from gpiozero import LED
   import time
   import os

   Buzzer1 = LED(17)

   Buzzer2 = LED(27)

   def ConnectRemote():

        os.system("rfkill unblock bluetooth")

        print 'Press 1+2 On The Remote...'

        global wm

        wm = wiid.Wiimote()

        print 'Connection Established!\n'
        wm.led = 1
        wm.rumble = 1
        time.sleep(0.25)
        wm.rumble = 0
        time.sleep(0.5)
        wm.rpt_mode = cwiid.RPT_BTN

   def TryToConnect():

        while True:

            ConnectRemote()
            break

   while True:

        buttons = wm.state['buttons']

        #shutdown function using plus and minus buttons
        if (buttons - cwiid.BTN_PLUS - cwiid.BTN_MINUS == 0):
                print '\nClosing Connection To Wiimote'
                wm.rumble = 1
                time.sleep(0.25)
                wm.rumble = 0
                os.system("rfkill block bluetooth")
                TryToConnect()

    if (buttons & cwiid.BTN_A):
            print 'Buzzer On'
            Buzzer1.on()
            Buzzer2.on()
    else:
            Buzzer1.off()
            Buzzer2.off()

and yet I keep getting an error of
    Traceback (most recent call last):
    File "WiimoteLEDs.py", line 36, in <module>
    buttons = wm.state['buttons']
    NameError: global name 'wm' is not defined

Can anyone help? Thanks in advance

A: I think you should initialized variable wm before using this variable in function.
This bug is related to 'Global name not defined'


text:
Q: Spring Data Solr repositories using JavaConfig I'm trying to create a SpringBoot application which uses solr repositories. I'm following this tutorial:

http://docs.spring.io/spring-data/solr/docs/current/reference/html/#solr.repositories

which says to configure my application with the following class (Example 43):
@Configuration
@EnableSolrRepositories
class ApplicationConfig {

  @Bean
  public SolrClient solrClient() {
    EmbeddedSolrServerFactory factory = new EmbeddedSolrServerFactory("classpath:com/acme/solr");
    return factory.getSolrServer(); // getSolrServer does not exist
  }

  @Bean
  public SolrOperations solrTemplate() {
    return new SolrTemplate(solrClient());
  }
}

The problem is if I do that it doesn't recognise getSolrServer() as a method of factory. Indeed, if you look at the most recent API for EmbeddedSolrServerFactory you don't find that method, but it apparently existed in a previous version of the same class.
Maybe it was renamed from getSolrServer to getSolrClient, for some reason, from one version to another.
Here's my dependencies in the pom.xml
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-solr</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Anyway, I tried to change getSolrServer to getSolrClient, but the return type, i.e. SolrClient, is now incompatible. If I try to return org.apache.solr.client.solrj.embedded.EmbeddedSolrServer, it gives me an error because it doesn't find org.apache.solr.client.solrj.embedded...
Another problem using this would be that SolrTemplate doesn't require a EmbeddedSolrServer, so this is not a good option...

A: I am using eclipse not spring suite, Assuming spring suite using latest version of spring-boot-starter-data-solr ( 1.4.2 ) and you need to add an entry for solr-core 5.x in your pom.
Since EmbeddedSolrServer is extending SolrClient, follows Java IS-A relationship and it should be compatible with SolrClient. This binary is part of solr-core.
Your code need to use getSolrClient itself and it should be compatible with SolrClient

Dependencies in pom.xml is as follows

Here we go with our code base without any errors.

A: Instead of creating SolrClient bean, create EmbeddedSolrServerFactoryBean object and pass that object to solr template to create SolrTemplate object. Here is my config file:
@Configuration
@EnableSolrRepositories(basePackages = "com.ida.*.repository")
@Profile("dev")
public class SolrConfigDev {
    @Autowired
    private Environment environment;

    @Bean
    public EmbeddedSolrServerFactoryBean solrServerFactoryBean() {
        EmbeddedSolrServerFactoryBean factory = new EmbeddedSolrServerFactoryBean();

        factory.setSolrHome(environment.getRequiredProperty("solr.solr.home"));

        return factory;
    }

    @Bean
    public SolrTemplate solrTemplate() throws Exception {
        return new SolrTemplate(solrServerFactoryBean().getObject());
    }
}

In addition, you have to add solr-core to you pom.xml file.
<dependency>
    <groupId>org.apache.solr</groupId>
    <artifactId>solr-core</artifactId>
    <version>5.5.3</version>
</dependency>

More information about this topic, you can find here in this blog by Petri Kainulainen.


text:
Q: Which open-source Python or Java library provides an easy way to draw circles on a ESRI Shapefile? I need to write a software that creates an shapefile with various circles or circumferences on it.
The shapefile created should be readable by ESRI ArcMap.
I need a library that let me add circles or circular arc to it.
The library could be in for Python or in Java.

A: If you look at OpenMap, it may be possible to write some code using that set of libraries in Java to do what you are asking.
I don't know if its possible from a single call, but there is definitely code in OpenMap to generate circles and arcs and it also has code to read in a shapefile.  The jump to exporting a shape file shouldn't be too big.

A: Matt Perry has a short and sweet example of creating circles in a shapefile in Tissot Indicatrix - Examining the distortion of map projections. Not listed in the post is how to install the prerequiste gdal/ogr; for that see OSGeo4W on windows or a simple apt-get install gdal python-gdal on ubuntu linux.


text:
Q: No way to input data when the program is running in NetBeans I'm trying to execute a program from the book by K. N. King "C Programming, A Modern Approach, 2 Edition", in NetBeans 8.0.2, using MinGW compiler. The program looks like this:
#include <stdio.h>
int main(void) {
int height, length, width, volume, weight;

printf("Enter height of box: ");
scanf("%d", &height);
printf("Enter length of box: ");
scanf("%d", &length);
printf("Enter width of box: ");
scanf("%d", &width);
volume = height * length * width;
weight = (volume + 165) / 166;

printf("Volume (cubic inches): %d\n", volume);
printf("Dimensional weight (pounds): %d\n", weight);

return 0;
}

So, I press "Run Project", the program builds successfully without any errors, then it begins to run and nothing happens, no console or something like that appears to input data like height, length, etc.
In the output window, after the program builded, it begins to run and nothing is displayed in the window except for a thick cursor. When I press any button being in that window, the program ends and this is what is displayed:
Enter height of box: Enter length of box: Enter width of box: Volume (cubic inches): 0 Dimensional weight (pounds): 0
RUN SUCCESSFUL (total time: 6s)

I'm completely new to C, so I don't know, what should appear when the program runs. When launching programs written in Python the console appeared, and now I'm confused.
When I tried to debug, it builded successfully again and then the console appeared with the line: "Enter height of box: ", so it worked like I thought it should work, but I don't think this is the proper way to run programs.

A: stdio streams are buffered. You need to fflush() stdout before using stdin, if you want the output to be displayed before the program blocks waiting on input. Alternatively, you can end all output lines with '\n', as newline implicitly flushes the output.
Edit: If you're entering data that scanf() cannot match using %d, such as alphabetic characters, scanf() will fail. You can check for this failure by comparing the return value of scanf() with the number of matches you expected (one in this case). As it stands, you don't check for this, and the characters stay in the input buffer, where the next scanf() will again try and fail to match them.


text:
Q: Android - Make csv / txt file remain after update public void saveGame()   {
        String filename = "pdata.csv";
        System.out.println("Saving Game pdata...");
        File outFile = new File(filename);
        try {
            // Name + UserInfo + CVList+
            FileOutputStream os = openFileOutput(String.valueOf(outFile), Context.MODE_PRIVATE);
            PrintWriter printWriter = new PrintWriter(os); //set up a writer
            printWriter.println("47*4,Sound Name,Win,Total,Country,Name");//print it

~~~[Code skipped]~~~
            printWriter.flush();
            printWriter.close();
        }catch (FileNotFoundException e) {
            e.printStackTrace();
            e.getLocalizedMessage();
            System.out.println("Error saving");
        }
    }

This is the code that writes my array into .csv file.
Content doesn't matter much, but it contains user data and it is loaded/modified/saved everytime app runs.
But I figured if I save this file at "Context.MODE_PRIVATE", everytime app updates or reinstalls this file gets reset as well.
But I want this file not to be reset when Application gets updated.
(Like how SharedPreference data doesn't change or disappear after update)
How can I do that?


text:
Q: Set SPF to send email using Gmail (Disclaimer: I totally suck at being a sysadmin)
I am sending email for a domain using Gmail. The domain is partyboatcharters.com.au (I hope I am allowed to put domains here). Gmail is configured to send email as that. Emails sent to sales@partyboatcharters are forwarded straight away to partyboatchartersahs@gmail.com by the MX.
The MX is s412.syd5.hostingplatform.net.au (there is only one MX).
I can send email fine. However, sometimes (but only sometimes) emails are not getting through, with this error message (received by the SENDER):
partyboatchartersahs@gmail.com
host gmail-smpt-in.l.google.com [4004:6800:4003:c00::1a]
SMTP error from remote email server after end of data:

550-5.6.26 This message does not pass authentication checks [SPF and DKIM both[
550-5.6.26 SFP checl for [partyboatcharters.com.au] does not pass
550-5.6.26 with IP> [2400:b800:6::52]

I found this document:
https://support.google.com/googlecloud/answer/10756302?hl=en
Which reads:
**Problem**
I need to set up SPF on my domain to send emails with Gmail, not receive.

**Environment**
MX (mail exchange) entry is set to `v=spf1 a mx -all` with domain host
Set up a Sender Policy Framework (SPF) record to send emails with Gmail interface

**Solution**
Sign in to the management console for your domain host.
Locate the page where you update TXT records for your domain.
Create a custom TXT record for SPF: It should look like this: v=spf1 [IP ADDRESS] include:_spf.google.com include:[DOMAIN] ~all

I tried adding this TEXT entry to the DNS:
TXT @ v=spf1 [43.250.142.8] include:_spf.google.com include:[partyboatcharters.com.au] ~all

As 43.250.142.8 is the IP address of the MX server...) However, I don't really know what I am doing here. The article seems to cover sending emails with Gmail for another domain... not receiving them.
This other article:
https://support.google.com/a/answer/10685031
Seems to imply that the SPF should be:
v=spf1 include:_spf.google.com ~all

But I am NOT using Google Workspaces (I know, I know, I should...). I am simply 1) Forwarding emails from sales@partyboatcharters.com.au TO partyboatchartersahs@gmail.com 2) Configuring Gmail so that it sends emails from sales@partyboatcharters.com.au.
So, what should SPF be? What about DKIM?


text:
Q: Android TextView in ScrollView - Different color for each new line I am creating sort of terminal-like view, that would display received and transmitted messages over Bluetooth,e.g. received messages in blue, transmitted in red.
So far, i managed to put textView inside scrollView and by using .append() methdod add lines to scroll view.
Layout looks like this:
    <ScrollView
    android:id="@+id/scrollingView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/disconnectButton"
    android:layout_alignParentStart="true">

    <TextView
        android:text="Received and sent txt!!!\n"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/scrollTextView"
        android:minLines="11"
        android:maxLines="11"/>
</ScrollView>

And code for adding text to scrollView:
scrollView = (ScrollView) findViewById(R.id.scrollingView);
scrollTextView = (TextView) findViewById(R.id.scrollTextView);
scrollTextView.setGravity(Gravity.BOTTOM); scrollTextView.setTextColor(getResources().getColor(R.color.receivedBTColor));
scrollTextView.append("$"+dataInPrint+"\n");
scrollView.fullScroll(View.FOCUS_DOWN);

The problem is that each of the lines should be able to be in different colors. setTextColor() method sets color for whole textView, which is totaly not what i want since i need to temporarily save the lines which go upwards until scrollView overflows. I looked at the example of using Spannable class, but it is quite messy.
Could anyone suggest a way to make a scrollable colorful text? Something like this?
Example from Bluetooth terminal app
Thanks a lot!

A: You can do a little tricky editing utilizing HTML and Android's Html.fromHtml()...
String dataInPrint = "" //Whatever the output message is.

String redB = "";
String blueB = "";
String colorEnd = "";

if(//message is send){
    yourtextview.append(Html.fromHtml(redB + dataInPrint + colorEnd));
}
else{//message is recieve
    yourtextview.append(Html.fromHtml(blueB + dataInPrint + colorEnd));
}


text:
Q: How go full screen with QWebEngineView (PySide2) without crash? Has anyone managed to get PySide2 (v5.12) successfully go full screen on QWebEngineView  via fullScreenRequested command?
Every time I am executing the command Python 3.72 crashes. I also tried with 3.6 and receive similar result.
Screenshot

PyQt5.11.3 on the other hand seems to work fine.
Did I find a bug with PySide2 and QWebEngineView And Fullscreen?!
Thank you guys :)
Running this (swap PySide2 for PyQt5) fullscreenrequest under PyQt5.11.3 works.
It seems PySide2 either has a bug or the command changed.
from PySide2.QtWidgets import QApplication
from PySide2.QtWebEngineWidgets import QWebEngineView
from PySide2.QtCore import QUrl
from PySide2.QtWebEngineWidgets import QWebEngineSettings

app = QApplication([])
view = QWebEngineView()
view.settings().setAttribute(QWebEngineSettings.FullScreenSupportEnabled, True)
view.page().fullScreenRequested.connect(lambda request: request.accept())
view.load(QUrl("https://youtube.com"))
view.show()
app.exec_()


text:
Q: Reload Partial View using JQuery My main view is loading a list from a partial view. I'm using Jquery to search over it, and that's ok. However, I'm having troubles in clear the search results: the partial view is not reloaded. I'm sure that controller is returning the correct results. What am I doing wrong?
Main View Code:

        <form method="get" action="@Url.Action("GetJobOffersList", "JobOffers")" data-otf-ajax="true" data-otf-target="#jobOffersPartialViewDiv">
            <input type="search" name="searchTerm" data-otf-autocomplete="@Url.Action("Autocomplete", "JobOffers")" />
            <input type="submit" value="Search" />
            <input type="submit" value="Clear" id="clearSearchButton"/>
        </form>

    @Html.Partial("_JobOffersList")

JQuery Code:
$(document).ready(function () {
    autocomplete();
    search();
    clear();
});

function clear() {
    $("#clearSearchButton").click(function () {
        $("input[data-otf-autocomplete]").val("");

        $.ajax({
            url: '/JobOffers/GetJobOffersList',
            type: 'GET',
            cache: false,
            success: function (result) {
                $("form[data-otf-ajax='true']").attr("data-otf-target").replaceWith(result);
            }
        });
    });
}

A: You need to replace the actual element and not the "attribute string". Change:
$("form[data-otf-ajax='true']").attr("data-otf-target").replaceWith(result);

to
$($("form[data-otf-ajax='true']").attr("data-otf-target")).replaceWith(result);

If you "expand" your initial code to multiple lines it would be the following:
var formElement = $("form[data-otf-ajax='true']"); // jQuery element of the from
var target = formElement.attr("data-otf-target");  // "#jobOffersPartialViewDiv"
target.replaceWith(result);                        // 'replaceWith' on string

and after the change:
var formElement = $("form[data-otf-ajax='true']"); // jQuery element of the from
var target = formElement.attr("data-otf-target");  // "#jobOffersPartialViewDiv"
var targetElement = $(target)                      // jQuery element of the target
target.replaceWith(result);                        // 'replaceWith' on target element


text:
Q: Object of type 'System.Int32' cannot be converted to type 'System.UInt32&' When I execute the following line of code
dispatch.GetTypeInfoCount(ref typeInfoCount);

The following exception is thrown
Object of type 'System.Int32' cannot be converted to type 'System.UInt32&'
using System.Runtime.InteropServices;
using ComTypes2 = System.Runtime.InteropServices.ComTypes;

public class ComHelper
{

[ComImport(), Guid("00020400-0000-0000-c000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    private interface IDispatch
    {
        void GetTypeInfoCount(ref uint pctinfo);
        void GetTypeInfo(uint itinfo, uint lcid, ref IntPtr pptinfo);
        void stub_GetIDsOfNames();
        void Invoke(int dispIdMember,
            ref Guid riid,
            uint lcid,
            ushort dwFlags,
            ref ComTypes2.DISPPARAMS pDispParams,
            ref object pVarResult,
            ref IntPtr pExcepInfo,
            ref uint pArgErr);
    }

   public static bool CheckIfComPropertyOrMethodExists<T1>(T1 objectToCheck, string propertyOrMethodName)
    {

        ComTypes2.ITypeInfo objectTypeInfo = null;
        var objectITypeInfo = default(IntPtr);
        var pFuncDesc = default(IntPtr);

        try
        {

            //  Convert the object to IDispatch
            var dispatch = (IDispatch)objectToCheck;
            uint typeInfoCount = 0;

            //  Attempt to get the objects TypeInfo
            dispatch.GetTypeInfoCount(ref typeInfoCount);

            if (typeInfoCount < 1) throw new ApplicationException("No type info");

            dispatch.GetTypeInfo(0, 0, ref objectITypeInfo);

            if (objectITypeInfo == IntPtr.Zero) throw new ApplicationException("No ITypeInfo");

            objectTypeInfo = (ComTypes2.ITypeInfo)Marshal.GetTypedObjectForIUnknown(objectITypeInfo, typeof(ComTypes2.ITypeInfo));

            var pTypeAttr = default(IntPtr);
            objectTypeInfo.GetTypeAttr(out pTypeAttr);

            var typeAttr = (ComTypes2.TYPEATTR)Marshal.PtrToStructure(pTypeAttr, typeof(ComTypes2.TYPEATTR));

            objectTypeInfo.ReleaseTypeAttr(pTypeAttr);

            //  Find the method we're looking for in the list of COM objects methods
            for (var iFunc = 0; iFunc <= typeAttr.cFuncs - 1; iFunc++)
            {
                objectTypeInfo.GetFuncDesc(iFunc, out pFuncDesc);
                var funcDesc = (ComTypes2.FUNCDESC)Marshal.PtrToStructure(pFuncDesc, typeof(ComTypes2.FUNCDESC));

                string[] names = { string.Empty };
                int pcNames;

                objectTypeInfo.GetNames(funcDesc.memid, names, 1, out pcNames);

                var funcName = names[0];

                if (funcName == propertyOrMethodName)
                {
                    return true;
                }

                objectTypeInfo.ReleaseFuncDesc(pFuncDesc);
            }

            return false;

        }
        finally
        {
            if (objectTypeInfo != null)
            {
                objectTypeInfo.ReleaseFuncDesc(pFuncDesc);
            }
            Marshal.Release(objectITypeInfo);
        }

    }

}

I'm sure that the answer is simple but I can't work it out at the moment. The parameter for GetTypeInfoCount is a uint. The local variable typeInfoCount that is passed by reference to the GetTypeInfoCount method is also a uint. Why am I getting a type conversion exception?
This question relates to the following
How to check if a COM property or method exists without generating an exception?
Useful links so far
http://msdn.microsoft.com/en-us/library/ebbff4bc-36b2-4861-9efa-ffa45e013eb5%28VS.85%29
http://en.wikipedia.org/wiki/IDispatch

A: Try using out instead of ref:
void GetTypeInfoCount(out uint pctinfo);

and then:
uint typeInfoCount;
dispatch.GetTypeInfoCount(out typeInfoCount);

By the way you have the same issue with the GetTypeInfo method. You are using ref for the pointer but it should be out:
void GetTypeInfo(uint itinfo, uint lcid, out IntPtr pptinfo);

Here's the correct P/Invoke wrapper for the IDispatch interface:
[Guid("00020400-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IDispatch
{
    void GetTypeInfoCount(out uint pctinfo);
    void GetTypeInfo(uint iTInfo, int lcid, out IntPtr info);
    void GetIDsOfNames(ref Guid iid, [MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPWStr, SizeParamIndex=2)] string[] names, uint cNames, int lcid, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.I4, SizeParamIndex=2)] int[] rgDispId);
    void Invoke(int dispIdMember, ref Guid riid, int lcid, INVOKEKIND wFlags, ref DISPPARAMS pDispParams, IntPtr pvarResult, IntPtr pExcepInfo, IntPtr puArgErr);
}


text:
Q: How do I show my todos in React component Im making a simple todo app with fastapi and react.
How do I show my todos? I tried use {todo.data}, but it doesn't work.
That's my Todos.js component:
import React, { useEffect, useState } from "react";

export default function Todos() {
    const [todo, setTodo] = useState([])
    useEffect(() => {
        fetch('http://localhost:8000/todos')
            .then(response => response.json())
            .then(json => setTodo(json))
    }, [])
    return (

My Todos:

        <ui>

                my todos

        </ui>

    )
}

here's how http://localhost:8000/todos looks like:
{
   data: [
   {
      name: "buy bread",
      is_done: false,
      id: 1
   },
   {
      name: "clean kitchen",
      is_done: false,
      id: 2
   },
   {
      name: "string",
      is_done: false,
      id: 3
   }
   ]
}

A: First, you need to map over the returned data.
Then, you actually need to render it in your return statement.
import React, { useEffect, useState } from "react";

export default function Todos() {
    const [todo, setTodo] = useState([]);
    useEffect(() => {
        fetch("http://localhost:8000/todos")
            .then((response) => response.json())
            .then((json) => setTodo(json.data));
    }, []);
    return (

My Todos:

                {todo.map((todo) => (

                        {todo.name} <input type="checkbox" checked={todo.is_done} />

                ))}

    );
}


text:
Q: An unexpected UNDERSCORE appearing I was working with w3.css and font awesome icons. I created two links and used check and time icons for them. The first link (icon) is showing and underscore _ next to it. But it is not in the code. I have tried changing the icon but it is still there. I inspected it in Firefox and the underscore is part of  and not the icon. Can you help resolve this problem?
Here is a screenshot:
Here is the code:

            <a href="ajaxAction.php?aid=<?php echo $r['id']; ?>">

            <a href="ajaxAction.php?unid=<?php echo $r['id']; ?>">

A: The a link is underlined by default and contains the icon and empty spillover.
Add
 text-decoration: none; to the links to prevent the default underscore style on links.
EDIT: Full Example(without icons):

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">

            <a href="ajaxAction.php?aid=<?php echo $r['id']; ?>">

            <a href="ajaxAction.php?unid=<?php echo $r['id']; ?>">

            <a style="text-decoration:none;" href="ajaxAction.php?aid=<?php echo $r['id']; ?>">
                _

            <a style="text-decoration:none;" href="ajaxAction.php?unid=<?php echo $r['id']; ?>">
                _

            <a style="text-decoration:none;" href="ajaxAction.php?aid=<?php echo $r['id']; ?>">
                _

            <a style="text-decoration:none;" href="ajaxAction.php?unid=<?php echo $r['id']; ?>">
                _

A: apply hover in style tag separately then check it or in separate CSS file and include it and Remove &nbsp  user css instead

            <a href="ajaxAction.php?aid=<?php echo $r['id']; ?>">

            <a href="ajaxAction.php?unid=<?php echo $r['id']; ?>">


text:
Q: Find index j in a simple convex vector A vector V [0, n − 1] is a simple convex vector if a index j exists such that V [0] = V[1] = V[2] = ··· = V[j] and for each i > j, V[i] < V[i + 1]. Can you write pseudocode to solve this in O(log(n)) time complexity?
That's my solution, but I don't know if it works. I think it should but assuming for each i >= j, V[i] < V[i + 1]. I don't know if I have a wrong definition.
convex(A, l, r) {
  m = floor((l + r) / 2);

  if (A[m] == A[0] && A[m] != A[m + 1] {
    return m;
  }

  if (A[m] == A[0]) {
    return convex(A, m + 1, r);
  }
  else {
    return convex(A, l, m - 1);
  }
}


text:
Q: Control one circuit from a separate circuit What I am trying to do today is control one circuit using another, with no common ground or voltage between the two circuits. Basically what I am looking for is some way to have my Arduino, powered off of its own battery, control a 24V led circuit without using a voltage regulator.
It seems like I am looking for somewhat of a hybrid between a relay and a transistor, the relay providing the ability to control current in a circuit from a separate setup, and the transistor providing a solid-state variable current setup (in this case, hopefully also with signal amplification. If need be, though, I could always just use BJTs)
I apologize if there is something like this already on the forum but I could not think of what I should search for, and my searches turned up nothing.
Thanks in advance,
Trevor

A: First, if the controller is running from its own battery, then you can connect its ground and the 24 V ground together (or any one point on each one, but the grounds is usually what you'd connect).
Second, you don't need this device to have amplification on its own.  You need to get the signal from one circuit to the other, but the receiving circuit can amplify that as it needs to.
If you really need isolation, then a mechanical relay, solid state relay, or opto-coupler is what you want.  If you don't actually need isolation, and it sounds like this is the case, then have a digital signal control a transistor as usual.