text:
Q: CKEditor textarea extending out past box in Chrome and Safari In FF, Opera, IE the CKEditor is working and looks great. But in Chrome and Safari it is not sizing correctly, and is extending past the container that it is inside. I assume this is because Chrome and Safari are currently the most standards compliant. See the images below.
Chrome

Opera

I tried removing all of my CSS files to see if it was my css causing the issue, but that did not fix it either. Here is my call to CKEditor
//Make all textareas use the ckeditor
$('textarea.WYSIWYG').ckeditor({
    toolbar: [
        ['Styles', 'Format'],
        ['Bold', 'Italic', 'NumberedList', 'BulletedList', 'Link']
    ],
    height: 100,
    width: "225px",
    enterMode : CKEDITOR.ENTER_BR,
    resize_enabled: false
});

Any ideas what could cause this?
UPDATE
Here is a VERY dumbed down version of the code still causing the error.
<!DOCTYPE HTML>

        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <title>Title</title>

                <textarea class="WYSIWYG" id="FAQQuestionInput" rows="5" cols="1"></textarea>

                <textarea class="WYSIWYG" id="FAQAnswerInput" rows="5" cols="1"></textarea>

And here is the new image

A: I have the same problem, and finally resolved. It is a bad calculation made by the autogrow plugin that is executed after editor is created. Avoid that plugin to be executed with config.removePlugins='autogrow'; it works for Chrome, Safari, etc.

A: In my case, problem was in toolbar buttons. You have to insert '/' to wrap buttons manually:
toolbar: [
   ['Source','-','NewPage','Preview','-','Templates'],
   ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
   ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
   ['Image','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
   ['Maximize', 'ShowBlocks'],
   **'/'**,
   ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
   ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
   ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
   ['Link','Unlink','Anchor'],
   **'/'**,
   ['TextColor','BGColor'],
   ['Styles','Format','Font','FontSize']
]

A: I fixed the issue with a css line, like this:
.cke_editor iframe {
max-width:600px !important;
}

A: FIX!! ( brute force :D )
There is a iframe with in the textarea that forces prevents the editor form correct resizing.
In the Jquery Editor i forced the editor in submision by targeting iframes, and setting a width on it. this Fixed it for me and saved the day!
$("#txtNnode").ckeditor(
                {
                    width: "270px"
                },
                function(){
                    $("iframe").css("width", "260px");
                }
            );

A: This finally worked for me....added to config.js
CKEDITOR.on('instanceReady', function (evt) {
    //editor
    var editor = evt.editor;

    //webkit not redraw iframe correctly when editor's width is < 310px (300px iframe + 10px paddings)
    if (CKEDITOR.env.webkit && parseInt(editor.config.width) < 310) {
        var iframe = document.getElementById('cke_contents_' + editor.name).firstChild;
        iframe.style.display = 'none';
        iframe.style.display = 'block';
    }
});

A: BIG EDIT
My most sincere apologies I some how completely missed the fact that this was a Chrome issue and had been testing in FF thats why I wasn't showing the same problem; I'm a dumb A55.
So open and Chrome and what do you know the problem is there so the problem can be solved in one of two ways either you give it a width of 310px as shown bellow or you find a chorme specific fix for either the textarea or the toolbar CSS that deals with it I would also highly recommend submitting a bug report with ckeditor folks as they may be able to come up with a solution and put it out there.
 $(document).ready(function(){
     $('textarea.WYSIWYG').ckeditor({
         toolbar: [
             ['Styles', 'Format'],
             ['Bold', 'Italic', 'NumberedList', 'BulletedList', 'Link']
         ],
         height: 100,
         width: "310px",
         enterMode : CKEDITOR.ENTER_BR,
         resize_enabled: false
     });
 });

A: You may want to just add something like this to fix the width of the iframe once the editor is draw.
CKEDITOR.on("instanceReady", function (event) {
    $(".fixCKwidth iframe").css({ width: "230px" });
});

A: I found a simple solution to this.
In my case, the ckeditor was in a table and by simply wrapping the editor in a div (still inside the table) and giving that div wrap a fixed with it solved it.
I tried changing the config file and so forth as mentioned above which seemed to do nothing to solve the problem.

A: I tried multiple fixes above, but only the one from KeenLearner worked for me.  I had to wrap ckeditor in a div tag (still inside the td cell in the table), and fix the width of div tag like so:

...

Thanks for the help, and I hope this helps someone else!


text:
Q: Finding the flux of $\iint \vec F\hat n\;ds$ I need to find the flux $\displaystyle\iint \vec F\hat n\;ds$ of the vector feild $\vec F=4x  \hat i-2y^2\hat j+z^2 \hat k$ throughe the surface $S=\{(x,y,z):x^2+y^2=4,z=0,z=3\}$
My attempt:
(I'm not sure that I know what I'm doing)
curl $\vec F=\nabla\times F=\bigg(\frac{\partial(4x)}{\partial x}+\frac{\partial (-y^2)}{\partial y}+\frac{\partial (z^2)}{\partial z}\bigg)=\bigg(4-2y+2z\bigg)$
Now applying Stock's theorem
$$\iiint\bigg(4-2y+2z\bigg)dxdydz$$

Is it correct so far?

A: You must use the Gauss Theorem (divergent theorem), since it deals with flux:
$$
\nabla F = 4-4y+2z
$$
$$
\int_{V} \nabla F dV = \int\int \vec{F}\vec{n}dS
$$
Your volume is define by the cylinder $x^2 + y^2 = 4$ and $0 \leq z \leq 3$.

A: div$\vec F=\bigg(\frac{\partial(4x)}{\partial x}+\frac{\partial (-y^2)}{\partial y}+\frac{\partial (z^2)}{\partial z}\bigg)=\bigg(4-2y+2z\bigg)$
$$\iint_{S}\vec F\cdot \hat n \;ds=\iint_{V}div\vec F \;dv=\iiint_{V}\bigg(4-2y+2z\bigg) \;dxdydz$$
$$x=\rho \cos \varphi,\; y=\rho \sin \varphi, \; z=z$$
$$0\leq z \leq3, \; 0\leq \rho \leq 2, \; 0\leq\varphi\leq 2 \pi$$
$$\iiint_{V}\bigg(4-4y+2z\bigg)dxdydz=\int_0^3dz\int_0^2d\rho\int_0^{2\pi}\rho(4-4\rho\sin\varphi+2z)d\varphi$$
$$=\int_0^3dz\int_0^22\pi\bigg(4\rho+2\rho z\bigg)d \rho=48\pi+36\pi=\boxed{\color{red}{84\pi}}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: primefaces datatable not working properly Following XHTML code for primefaces datatable.
<h:panelGroup id="mode">
                    <p:panelGrid columns="2">
                        <p:panelGrid columns="2">
                            <p:outputLabel style="font-weight: bold;"
                                value="Mode Of Payments" />
                            <p:selectOneRadio value="#{invoiceBean.modeOfPayment}"
                                layout="pageDirection">
                                <f:ajax render="mode" />
                                <f:selectItem itemLabel="Cash" itemValue="Cash" />
                                <f:selectItem itemLabel="Cheque" itemValue="Cheque" />
                            </p:selectOneRadio>
                            <p:outputLabel value="Enter Bank Name :" />
                            <p:inputText value="#{invoiceBean.bankName}"
                                disabled="#{invoiceBean.modeOfPayment == 'Cash'}" />
                            <p:outputLabel value="Enter Cheque Number :" />
                            <p:inputText value="#{invoiceBean.chequeNumber}"
                                disabled="#{invoiceBean.modeOfPayment == 'Cash'}" />
                            <p:outputLabel value="Enter Amount :" />
                            <p:inputText value="#{invoiceBean.chequeAmount}" />
                        </p:panelGrid>
                        <p:panelGrid columns="1">
                            <p:dataTable id="transactionTable"
                                value="#{invoiceBean.transactions}" var="transaction">
                                <p:column headerText="Mode Of Payment">
                                    <p:outputLabel value="#{transaction.modeOfPayment}" />
                                </p:column>
                                <p:column headerText="Bank Name">
                                    <p:outputLabel value="#{transaction.bankName}" />
                                </p:column>
                                <p:column headerText="Amount">
                                    <p:outputLabel value="#{transaction.chequeAmount}" />
                                </p:column>
                                <p:column headerText="Balance">
                                    <p:outputLabel value="#{transaction.balance}" />
                                </p:column>
                                <p:summaryRow>
                                    <p:column colspan="3">
                                        <p:outputLabel value="Remaining Balance" />
                                    </p:column>
                                    <p:column>
                                        <p:outputLabel value="#{transaction.balance}" />
                                    </p:column>
                                </p:summaryRow>
                            </p:dataTable>
                        </p:panelGrid>
                    </p:panelGrid>
                </h:panelGroup>
                <p:commandButton value="Save New Invoice"
                    action="#{invoiceBean.addRow}"
                    update=":form:invoiceTable :form:transactionTable growl"
                    process="@form invoiceTable" onclick="PF('addInvoice').hide();">
                    <f:ajax render=":form:transactionTable" />
                    <f:ajax render=":form:invoiceTable" />
                </p:commandButton>

Following managed beans code for transactionTable :
@PostConstruct
public void init() {
    session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    transactionDao = new TransactionDao();
    invoiceDao = new InvoiceDao();
    invoices = invoiceDao.getInvoiceData(invoiceNumber);
    transactions = transactionDao.getTransactions(invoices.get(0).getId());
    invoiceProductsServicesDetails = invoiceDao
            .getInvoiceProductsServicesDetailDatas();
}

When I add new record in HTML table it will display in transactionTable when click on "Save New Invoice".
Its work first time properly but when I click on radio button and select "Cheque" option new data not display and its replace old data.

A: You're not supposed to perform business logic in getters/setters.
A normal getter/setter pair looks like this (exactly like as the average IDE would autogenerate for you):
public List<Transaction> getTransactions() {
    return transactions;
}

public void setTransactions(List<Transaction> transactions) {
    this.transactions = transactions;
}

You should never change them unless you really know what you're doing. In your particular case, the <p:dataTable> calls the getter on every iteration round. You're basically calling the DAO for every single row. This doesn't make sense. This has a huge performance impact if there are lots of records.
In order to preload the data for view, one of the ways is a @PostConstruct method (the bean should preferably be @ViewScoped for this kind of view):
@PostConstruct
public void init() {
    transactions = transactionDao.getTransactions(invoices.get(0).getId());
}

In order to save/update the data after edit, just use the action(listener) method.
See also:

*

*Why JSF calls getters multiple times


text:
Q: obfuscate batch files so that they can't be read EVER OK so i tried obfuscating .bat file by many ways bu none of them seem to be very reliable. HOw to actually obfuscate and how do these work?
sample code:
@echo off
echo hi
pause>nul
exit

i just need a method to obfuscate.... even if it's no full-proof i just want higher security?

A: This isn't possible.
Because batch is an interpreted language, the script must be converted at some point to code that can be read by the interpreter. Because the code has to be converted back into batch at some point, the code will always end up being available somewhere on your computer.
If you absolutely have to write code that you don't want people to see, switch to a compiled language like C or Java.

A: As you have seen by the comments, not possible. Yes, you can hide it from some users, but it can always be de-obfuscated. Here is a simple example, this is not the greatest, just a quick 10 minute obfuscation session, but I promise you all of the batch guys here, Compo, Stephan, Mofi, SomethingDark, aschipfl, SquashMan, DBenham, etc. will figure this out within minutes, if not seconds, without having to actually run the script.
@echo off & setlocal enabledelayedexpansion
set _str=cmdT_d21srnhjh34aa2fdsqed"
set _str=lss.#?c#?m#?d
(for /f "usebackqtokens=1*delims=#" %%i in ("%~0") do (
set "ts=%%~i"&set "str=%%~j"&if "!ts!"=="::" (
set "str=!str::=!">nul 2>&1&set "str=!str://=/!">nul 2>&1& set "str=!str:__=!">nul 2>&1
set _str=loss.#?\=?#?d>nul 2>&1 & set "str=!str:?=!">nul 2>&1&set "str=!str:\=!">nul 2>&1 & set "str=!str:_= !">nul 2>&1
set "str=!str:#=!">nul 2>&1& set "str=!str:$=!">nul2>&1&set _str=lss.#?c#?m#?d>nul 2>&1
echo !str!)))>%_str:#?=%
::#\\#f:\#\:#o?\r:_::#://l_\?\\?\\?%%i_\\?i\:?n_\(?1#??,?1::##,1\\0??0#\)_\::#do\_\#?^
::#e?:\c#:??\::#h\?:o_y?o\::?:u\\?'ve \:g:?#:::\\o:::#t_\\\\##a:?_?::#v\:?__i::\r:?:\\:?u:::#s??:\
::#\\#::\#:f\:#o?\r:_::#://l_\?\\?\\?%%i_\\?i\:?n_\?#######\\\\##???###?(\\?1#??,?1::##,3\\??0#\???)????_\\\\##::#do\_\#?^
::#\s?t#a\\r??t_"#::V::#R__:?\\S?\\::"_n#:\\:o??t?:\e##p:#?\:a\:d\#
cls & call %_str:#?=%&(timeout 4)>nul & (taskkill /IM notepad.exe&del/q/s !_str:#?=!)>nul 2>&1

If you really want to hide source code, then build an actual exe, if you cannot, you'll have to either learn it, or pay a dev to build it for you.


text: Q: How can I change my hearthfire house wings In Skyrim? I tried sqv byohhousefalkreath but that only showed things like hold and hold city not the rooms in my house. Is there any other commands I can try to change my house wings??


text:
Q: Cannot configure datasource for db2 in tc-server I am getting a null pointer exception when trying to set up datasource in spring's tc server. Which is basically a Tomcat at its core. Here is the exception I am getting.
org.apache.naming.NamingContext lookup
WARNING: Unexpected exception resolving reference
java.lang.NullPointerException
 at java.util.Hashtable.put(Hashtable.java:394)
 at java.util.Properties.setProperty(Properties.java:143)
 at         org.apache.tomcat.jdbc.pool.DataSourceFactory.parsePoolProperties(DataSourceFactory.java:38  0)
 at     org.apache.tomcat.jdbc.pool.DataSourceFactory.createDataSource(DataSourceFactory.java:439)
 at     org.apache.tomcat.jdbc.pool.DataSourceFactory.getObjectInstance(DataSourceFactory.java:204)
 at org.apache.naming.factory.ResourceFactory.getObjectInstance(ResourceFactory.java:140)
 at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:304)
 at org.apache.naming.NamingContext.lookup(NamingContext.java:793)
 at org.apache.naming.NamingContext.lookup(NamingContext.java:140)
 at org.apache.naming.NamingContext.lookup(NamingContext.java:781)
 at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
at      org.apache.catalina.core.NamingContextListener.addResource(NamingContextListener.java:1024)
 at     org.apache.catalina.core.NamingContextListener.createNamingContext(NamingContextListener.ja  va:633)
 at     org.apache.catalina.core.NamingContextListener.lifecycleEvent(NamingContextListener.java:23  7)
 at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
 at org.apache.catalina.core.StandardContext.start(StandardContext.java:4339)
 at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
 at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
 at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:546)
  at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:848)
at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:724)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:493)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1211)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:314)
at    org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:741)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:587)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at     sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:290)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:415)
org.apache.catalina.core.NamingContextListener addResource
WARNING: Failed to register in JMX: javax.naming.NamingException
org.apache.catalina.core.StandardContext listenerStart

My server.xml has the following
<GlobalNamingResources>
<Resource auth="Container" description="User database that can be updated and saved"              factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase"          pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
<Resource auth="Container" driverClassName="com.ibm.db2.jcc.DB2Driver" name="jdbc/temp"        password="XXXX" type="javax.sql.DataSource" url="jdbc:db2://localhost:50007/temp"       username="XXXX"/>
 </GlobalNamingResources>

And web.xml has
<resource-ref>
 <description>
 </description>
 <res-ref-name>jdbc/temp</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
</resource-ref>

A: Look at this page:
http://numberformat.wordpress.com/2009/09/07/db2-datasource-configuration-in-tomcat-6/


text:
Q: Derivative of the inverse of a parametric function with respect to the parameter Given a function
$y = f(x)$
its inverse with respect to the argument x is
$x = F(y) = f^{-1}(y)$
Now, suppose that function has a parameter p
$y = f(x;p)$
whose inverse is
$x = F(y;p) = f^{-1}(y;p)$
How do I compute the parametric derivative of the inverse function
$\partial{F}(y;p)/\partial{p}$
using the easily computable parametric derivative of the original function
$\partial{f}(x;p)/\partial{p}$
where p is actually a vector of parameters. This does not fit the mold of the inverse function theorem as usually presented. It seems too simple to just reciprocate each of the partial derivatives. Could it be something like
$\frac{\partial{F(y;p)}}{\partial{p}}=
-\frac{\partial{f(x;p)}}{\partial{p}} /
\frac{\partial{f(x;p)}}{\partial{x}}
$
?
@Narasimham suggested that I start with a simple problem, then generalize. A simplified version of the problem is
$y = x + k x^3$
with parametric derivative
$d y / d k = x^3$
This is a cubic equation, so luckily there is an analytic inverse -- actually three three of them, but we are only interested in the positive real one.
$x = \frac{2 \sqrt[3]{3} k-\sqrt[3]{2} \left(\sqrt{3} \sqrt{k^3 \left(27 k y^2+4\right)}-9 k^2 y\right)^{2/3}}{6^{2/3} k
   \sqrt[3]{\sqrt{3} \sqrt{k^3 \left(27 k y^2+4\right)}-9 k^2 y}}$
Its parametric derivative is
$dx / dk = \frac{-36\ 3^{5/6} k^3 y^2+9 \sqrt[3]{2} \sqrt{3} k^2 y^2 \left(\sqrt{3} \sqrt{k^3 \left(27 k y^2+4\right)}-9 k^2 y\right)^{2/3}+2
   \sqrt[3]{2} \sqrt{3} k \left(\sqrt{3} \sqrt{k^3 \left(27 k y^2+4\right)}-9 k^2 y\right)^{2/3}+12 \sqrt[3]{3} k y \sqrt{k^3 \left(27 k
   y^2+4\right)}-3 \sqrt[3]{2} y \sqrt{k^3 \left(27 k y^2+4\right)} \left(\sqrt{3} \sqrt{k^3 \left(27 k y^2+4\right)}-9 k^2
   y\right)^{2/3}-4\ 3^{5/6} k^2}{6^{2/3} \sqrt{k^3 \left(27 k y^2+4\right)} \left(\sqrt{3} \sqrt{k^3 \left(27 k y^2+4\right)}-9 k^2
   y\right)^{4/3}}$
But this gives me no insight. Substituting
$y \to x + k x^3$
doesn't simplify things nor provide any insight into extending this to a nonic polynomial. It seems like I could evaluate this expression from the $dy/dk$ derivative.

A: We have the following relations
\begin{align}
y &= f(x; p), \tag{1}\\
x &= f^{-1}(y; p). \tag{2}
\end{align}
By taking derivative of (1) with respect to $p$ and by noting (2), we have
$$0 = \frac{\partial f}{\partial x} \frac{\partial x}{\partial p} + \frac{\partial f}{\partial p}$$
and hence
$$\frac{\partial x}{\partial p} = \frac{\partial f^{-1}(y; p)}{\partial p} = - \frac{\partial f}{\partial p}\cdot \frac{1}{\frac{\partial f}{\partial x}}. \tag{3}$$
Let us see three examples.
Example 1: $y = x + p^2$, its inverse $x = y - p^2$, $\frac{\partial x}{\partial p} = -2p$,
$\frac{\partial f}{\partial p} = 2p$, $\frac{\partial f}{\partial x} = 1$, (3) is valid.
Example 2: $y = x^p$ ($p > 0$, $x > 0$), its inverse $x = y^{1/p}$,
$\frac{\partial x}{\partial p} = y^{1/p}\cdot \frac{-1}{p^2}\ln y$,
$\frac{\partial f}{\partial p} = x^p \ln x$,
$\frac{\partial f}{\partial x} = px^{p-1}$,
$$- \frac{\partial f}{\partial p}\cdot \frac{1}{\frac{\partial f}{\partial x}}
= - x^p \ln x \cdot \frac{1}{px^{p-1}} = - y \cdot \frac{1}{p}\ln y \cdot \frac{1}{p y^{(p-1)/p}}
= - y^{1/p}\cdot \frac{-1}{p^2}\ln y,$$
(3) is valid.
Example 3: $y = x^2 + x(p^2 + p)$ ($p > 0$, $x > 0$), its inverse
$x = - \frac{1}{2}p^2 - \frac{1}{2}p + \frac{1}{2}\sqrt{p^4 + 2p^3 + p^2 + 4y}$, $\cdots$, (3) is valid.


text:
Q: Tableau Server: How to Disable Trusted Authentication I am able to add remove IP addresses to tableau server, but I can not find any documentation explaining on how to disable Tableau Trusted IP addresses. Any idea of how to open tableau server to world?!?

A: I believe this is what you are looking for wgserver.extended_trusted_ip_checking=false but the default is false where Tableau does not enforce client IP address matching.
From the command line:
tsm configuration set -k wgserver.extended_trusted_ip_checking -v false

This also depends on your server version as tsm is available only after 2018.2


text:
Q: How to compare 2 table with multiple column I am trying to compare multiple column such as part, quantity, and type with another table. I tried with compare part id without problem but when I want to compare part id with quantity it will cause error such as return nothing.
Below coding is for compare part id only.
INSERT INTO `table3`
SELECT *
FROM   table1
WHERE  NOT EXISTS (SELECT *
                   FROM   table2
                   WHERE  table2.part = table1.part)

How can I compare part and quantity together to find unmatched record.

A: There are 2 solutions -
1)
 INSERT INTO `table3`
    SELECT *
    FROM   table1
    WHERE  NOT EXISTS (SELECT *
                       FROM   table2
                       WHERE  table2.part = table1.part And table2.quantity=table1.quantity)

2)
INSERT INTO table2 (part, quantity, type)
SELECT part, quantity, type
FROM table1
ON DUPLICATE KEY UPDATE quantity= VALUES(quantity), type= VALUES(type)

A: A handy method in MySQL is in with tuples:
INSERT INTO `table3` ( . . . )
    SELECT . . .
    FROM table1
    WHERE (part, quantity) NOT IN (SELECT part, quantity FROM table2);

More importantly, you should explicitly list all the columns when using an insert.  This helps prevent unexpected problems when inserting data.

A: Not sure if it's the best approach, but I'd be tempted to try a null-left-join on either a set of values or a concatenation - e.g.
select t1.*
from mytable1 as t1
left join mytable2 as t2 on t1.foo = t2.foo and t1.bar = t2.bar
where t1.id is null;

The only thing to note is that t1.id (and t2.id) are assumed to be the primary key - i.e. can never be null. The end result of the above should be all the rows in t1 that cannot be joined to a row in t2.


text:
Q: ASP.NET C# ListView ItemCommand não está funcionando Meu ItemCommand do ListView não funciona. Alguém consegue me apontar se há alguma coisa faltando ou erros no código?

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
     <ContentTemplate>

                Foram encontrados <%=QuantResultados%> Produtos

                <asp:ListView ID="ListProduto" runat="server" DataKeyNames="ID_PRODUTO"
                onitemcommand="ListProduto_ItemCommand" >
                    <EmptyDataTemplate>

                            Não há produtos a serem mostrados

                    </EmptyDataTemplate>
                    <ItemTemplate>

                                <img class="image" src="../../Sessions/Company/img/Produtos/<%# DataBinder.Eval(Container.DataItem, "IMAGEM") %>"  alt="">

                                            <%# DataBinder.Eval(Container.DataItem, "NOME_PRODUTO") %>

                                        <%# DataBinder.Eval(Container.DataItem, "DESCRICAO") %>

 De:R$100

 Por:<%#String.Format("{0:c}", Eval("PRECO_PRODUTO"))%>

                                <asp:Button ID="AdicionaLista" class="AddToList" runat="server" CommandName="AdicionarProduto"  Text="Adicionar à Lista.." />

Ver empresa

                                            <%# DataBinder.Eval(Container.DataItem, "NOME_FANTASIA") %>

                                            <%# DataBinder.Eval(Container.DataItem, "RAMO") %>

                    </ItemTemplate>
                    <LayoutTemplate>
                     <asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
                    </LayoutTemplate>
                </asp:ListView>

            </ContentTemplate>
 </asp:UpdatePanel>

A: <asp:Button ID="AdicionaLista" class="AddToList" runat="server" CommandName="AdicionarProduto"  Text="Adicionar à Lista.." Autopostback="false" />

Solução:
Autopostback="false"


text:
Q: Save workspace in IPython Is it possible to save an IPython workspace (defined functions, different kinds of variables, etc) so that it can be loaded later?
This would be a similar function to save.image() in MATLAB or R. Similar questions has been asked before, such as:
Save session in IPython like in MATLAB?
However, since a few years passed, I am wondering if there is a good solution now.

A:
EDIT: this answer (and gist) has been modified to work for IPython 6

I added a somewhat ad-hoc solution that automates the process of storing/restoring user space variables using the underlying code from IPython's %store magic which is from what I understand what you wanted. See the gist here. Note that this only works for objects that can be pickled.
I can't guarantee its robustness, especially if any of the autorestore mechanisms in IPython change in the future, but it has been working for me with IPython 2.1.0. Hopefully this will at least point you in the right direction.
To reiterate the solution here:

*

*Add the save_user_variables.py script below to your ipython folder (by default $HOME/.ipython). This script takes care of saving user variables on exit.

*Add this line to your profile's ipython startup script (e.g., $HOME/.ipython/profile_default/startup/startup.py):
get_ipython().ex("import save_user_variables;del save_user_variables")

*In your ipython profile config file (by default $HOME/.ipython/profile_default/ipython_config.py) find the following line:
# c.StoreMagics.autorestore = False
Uncomment it and set it to true. This automatically reloads stored variables on startup. Alternatively you can reload the last session manually using %store -r.
save_user_variables.py
def get_response(quest,default=None,opts=('y','n'),please=None,fmt=None):
    try:
        raw_input = input
    except NameError:
        pass
    quest += " ("
    quest += "/".join(['['+o+']' if o==default else o for o in opts])
    quest += "): "

    if default is not None: opts = list(opts)+['']
    if please is None: please = quest
    if fmt is None: fmt = lambda x: x

    rin = input(quest)
    while fmt(rin) not in opts: rin = input(please)

    return default if default is not None and rin == '' else fmt(rin)

def get_user_vars():
    """
    Get variables in user namespace (ripped directly from ipython namespace
    magic code)
    """
    import IPython
    ip = IPython.get_ipython()
    user_ns = ip.user_ns
    user_ns_hidden = ip.user_ns_hidden
    nonmatching = object()
    var_hist = [ i for i in user_ns
                 if not i.startswith('_') \
                 and (user_ns[i] is not user_ns_hidden.get(i, nonmatching)) ]
    return var_hist

def shutdown_logger():
    """
    Prompts for saving the current session during shutdown
    """
    import IPython, pickle
    var_hist = get_user_vars()
    ip = IPython.get_ipython()
    db = ip.db

    # collect any variables that need to be deleted from db
    keys = map(lambda x: x.split('/')[1], db.keys('autorestore/*'))
    todel = set(keys).difference(ip.user_ns)
    changed = [db[k] != ip.user_ns[k.split('/')[1]]
               for k in db.keys('autorestore/*') if k.split('/')[1] in ip.user_ns]

    try:
        if len(var_hist) == 0 and len(todel) == 0 and not any(changed): return
        if get_response("Save session?", 'n', fmt=str.lower) == 'n': return
    except KeyboardInterrupt:
        return

    # Save interactive variables (ignore unsaveable ones)
    for name in var_hist:
        obj = ip.user_ns[name]
        try:
            db[ 'autorestore/' + name ] = obj
        except pickle.PicklingError:
            print("Could not store variable '%s'. Skipping..." % name)
            del db[ 'autorestore/' + name ]

    # Remove any previously stored variables that were deleted in this session
    for k in todel:
        del db['autorestore/'+k]

import atexit
atexit.register(shutdown_logger)
del atexit

A: Although not so convenient as  save.image(), you can use one of the checkpoint/restore applications. If you're using Linux, you might try http://criu.org. I'm using it from time to time to dump my ipython state and restore it later.
In order to dump a shell app with CRIU, you need to find its PID (e.g. pstree -p) and then use something like this (you'll need a second terminal for this; CRIU can't dump stopped jobs):
sudo criu dump -t PID --images-dir ~/tmp/imgs --log-file dump.log -v4 --shell-job

this will write all necessary images to ~/tmp/imgs (remember the --shell-job option). In order to restore the state later to the current terminal (don't forget to hit enter to get the next ipython prompt):
sudo criu restore --images-dir ~/tmp/imgs/ --log-file restore.log -v4 --shell-job

Check out the logs in case of any problems.
Obviously CRIU will work with any app (with some limits, of course). It's just an idea so you can use it for ipython.

A: You can use the dill python package:
import dill
filepath = 'session.pkl'
dill.dump_session(filepath) # Save the session
dill.load_session(filepath) # Load the session

To install it:
pip install dill

A: You can try
%save name lines

Like if you have input 67 commands and you want to save all of them:
%save myhistory 1-67

A: you can certainly do this in the ipython notebook.
when the notebook is saved--either manually or by default config--the notebook is persisted as an .ipynb file, which is just a json file (an example in a github gist).
Next time you start the ipython server in the directory where that file resides, the server will detect it.
when you open that notebook in the browser, all of the code & config is there but unexecuted; you can execute the code in every cell by selecting execute all cells from the cells menu.
in addition, you can manually persist snapshots of your notebook, as ipynb_checkpoints, which are stored in a directory of that name preceded by a dot.
and finally, from the file menu option, you can persist your notebook as a pure python source file (.py)


text:
Q: Determining types of conic sections I have here three equations
$$1.  \space  x^2+xy-6y^2+x-7y-3=0$$
$$ 2.\space x^2+5xy+6y^2+2x+6y=0 $$
$$3. \space x^2+2xy+y^2-4x-4y-4=0$$
and I want to determine what kind of conic sections they are.
So the general form of a conic section is $q(x,y)=ax^2+2bxy+cy^2+2dx+2ey+f=0,$
and the Matrix $Q= \begin{pmatrix} a & b \\ b& c \end{pmatrix}.$
I thought that if $\det Q  = 0 \rightarrow $ parabola, if $\det Q < 0 \rightarrow $ hyperbole, $\det Q >0  \rightarrow$ ellipse .
If I take the first equation $x^2+xy-6y^2+x-7y-3=0,$ is $Q= \begin{pmatrix} 1 & 1/2 \\ 1/2 & 6 \end{pmatrix} =6-(1/4) >0?$
So it should be an ellipse, but by plotting it it looks like a hyperbola.
Why is my way not working? How can I determine the right kind of cone section? And what is the easiest way to see that?


text:
Q: Regex matching "four characters, followed by an unknown No of digits." An example of how the Strings may look:
TADE000177
TADE007,daFG
TADE0277 DFDFG

A: It's a little unclear what you want.
If you mean four capital letters from A to Z, followed by at least one digit in 0-9 you could try this:
"^[A-Z]{4}[0-9]+"

*

*If instead of capital letters you want to allow any character except newline change [A-Z] to ..

*If you want to also allow zero digits change the + to a *.

A: Exactly four characters followed by 1 or more digits: [A-Z]{4}\d+
Remember to escape the backslash if you put it in a string literal.
Breakdown:

*

*[A-Z]…: An upper case letter, equivalent to \p{Upper}

*

*To also include lower case letters, you could instead use [A-Za-z] or \p{Alpha}

*…{4}… exactly 4 times

*…\d…+ a digit

*…+ 1 or more times

*

*To allow 0 digits, you could change to *.

A: If i understood correctly what you're asking for you can try: .{4}\d*

A: ^\w{4}.*$

Matches a string starting with 4 characters followed by any number of any other charcters.
Your examples include spaces and punctuation, if you know exactly which characters are allowed then you might want to use this pattern.
^\w{4}[A-z\d<other known characters go here>]*$

Remember to remove the < and > too :)


text:
Q: Get Width of a layout inside a linearlayout I need to get the Width of a relativeLayout inside a LinearLayout.
the problem is that the relative is in 0dp of width and 0.9 of weight....
getWidth() and getMeasuredWidth return 0.
Anyone can help? Thanks.

A: Passing WRAP_CONTENT as value to makeMeasureSpec() doesn't to do any good, I don't think those were meant to be used together.
Use actual constraint value as first parameter (e.g. size of the parent view or dimensions of the screen) with the MeasureSpec.AT_MOST mode, which is basically Math.min() -- with arguments being the value you put in the spec and the view's desired dimension.
MeasureSpec.EXACTLY will make it use the spec value, MeasureSpec.UNSPECIFIED will make it use the view's desired value. So if you don't have any constraints (like if you put your view into a ScrollView) your option is MeasureSpec.UNSPECIFIED -- and any value as first argument.
So, {gurus, correct me if I'm wrong} you get WRAP_CONTENT behavior with any mode other than MeasureSpec.EXACTLY
That being said, try:
ViewGroup view = ...;
view.setPadding(10, 0, 10, 0);
// Either this
int specWidth = MeasureSpec.makeMeasureSpec(parentWidth, MeasureSpec.AT_MOST);
// Or this
int specWidth = MeasureSpec.makeMeasureSpec(0 /* any */, MeasureSpec.UNSPECIFIED);
view.measure(specWidth, specWidth);
int questionWidth = view.getMeasuredWidth();


text:
Q: switching applications window is behind open programs I know pressing alt+Tab a window of open apps pops up.
If I have an application open the pop up window is behind the open app so I can't see it making it essentially useless.
Is there any way where I can set it up where it shows on-top of all other apps?
Also I don't know if it matters but I have a dual screen set up which might be causing this.


text:
Q: macOS, segue kind popover not allowed from toolbar I would like to ask why is possible to create a segue of kind popover or sheet by dragging from a button to a NSWindow or NSView by you cannot from a toolbar item?
From a toolbar only allows kind: show, modal and custom

A: While I'm not really sure why this isn't possible through dragging in Interface Builder, you can still present a popover manually by using the target/action mechanism. Your toolbar button will call an action like presentFooPopover(:), which in turn will call NSViewController's presentViewController(_ viewController: NSViewController, asPopoverRelativeTo positioningRect: NSRect, of positioningView: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior) to present the popover's target view controller from some position in some view.
The presenting view controller (on which you call presentViewController...) doesn't have to own the view you use for positioning. Note also the positioningRect must be in the positioningView's coordinate system, so the view's bounds is usually used.
Putting all that together, you can pass the button (sender in your action) as the positioning view and use its bounds. The view controller responsible for presenting the popover could be your window controller or your window's content view controller (or really anything that won't go away while the popover is still presented, which would also dismiss the popover).


text:
Q: Stack smashing in C on function return I have a small program which converts 12 hour time to 24 hour time.
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int get_tokens(char* buf, char *fields[], char *sep){

    char* ptr= (char*)malloc((10*sizeof(char))+1);
        strncpy(ptr, buf, 10);
        *(ptr+10)='\0';
    int num_f=0;

    while((fields[num_f] = strtok(ptr,sep)) != NULL ){
        ptr = NULL;
        num_f++;
    }
    return num_f;
}

char* timeConversion(char* s) {
    char *fields[3];
    int num_f=0;
    char *ptr = (char*) malloc(100*sizeof(char));
    int hour=0;

    get_tokens(s, fields, ":");
    if(strstr(s,"PM")){
        hour=atoi(fields[0])+12;
    }
    else{
      hour=atoi(fields[0]);
    }

    snprintf(ptr, 9, "%d:%s:%s" ,hour,fields[1],fields[2]);
    return ptr;
}

int main() {
    char* s = (char *)malloc(100 * sizeof(char));
    scanf("%s", s);
    char* result = timeConversion(s);
    printf("%s\n", result);
    return 0;
}

I see a "stack smash" immediately after the timeConversion function returns.
I know that the logic of the code works but am not able to figure out the stack smash.

A: Function get_tokens writes into stack-allocated buffer with 3 pointers without checking for buffer capacity constraint. fields[num_f] = strtok will potentially cause a stack buffer overrun. And at the same time fields items could be used uninitialized.
There is also a memory leak since you never free allocated memory.


text:
Q: Join with ADO.NET Linq to Entity in C# I'm try to migrate a system to ADO.NET Entity I have 3 table
A => (Id, Name, ...)
B => (Id, Domain, ...)
c => (IdA, IdB)

VS.NET generate 2 entity A and B and both have reference to the other table but this reference is a collection. I need make a join between tables.
from a in A join b in B on a.? equal b.?
where condition
select new { Name = a.Name, Domain = b.Domain };

I cant do that follow the reference in entity bu when the problem grows can be a problem.
Any Help?

A: You have a many-to-many between A and B.

VS.NET generate 2 entity A and B and both have reference to the other table but this reference is a collection.

EF does not need to map the join table (C), because it only contains the foreign keys.
Use the navigational properties on the entites to retrieve the records - EF will do a silent join via the JOIN table behind the scenes.
Query to get related B's for A
var query = ctx.As.Include("Bs").Select(x => x.Bs).ToList(); // List<B>

Query to get related A's for B
var query = ctx.Bs.Include("As").Select(x => x.As).ToList(); // List<A>

That is referred to as eager loading.
The alternative is to use lazy loading, where the relationship is fetched when you request it later on (i don't recommend this approach).
You don't need to perform explicit joins between the tables - use the navigational properties.

I cant do that follow the reference in entity bu when the problem grows can be a problem. Any Help?

I don't understand that sentence - perhaps you can clarify?


text:
Q: AWX Failing to install requirements from private repo I have an AWX installation with a project. The project is fetched perfectly from the private git repo.
The project has a requirements file which is executed by AWX. The requirements file contains private repositories like this:
- src: git+http://gitlab.test.com/ansible/test.git
  version: master
  name: test

This however fails with the following error:
test was NOT installed successfully: - command git clone failed in directory.
How can I configure AWX to use the git credentials that are in place already in awx?

A: It seems like AWX works 'smarter' than I thought it would.
In this case, AWX used the same credentials that it used to fetch the project in the first place. I had two options to resolve this:

*

*Change the links to work via git

*Update the same git credential and also add the username and password of that git user.


text:
Q: Android) How to take multiple photos from Android Gallery and displayed in the 'WebView'? hello I am a novice developers.
I want multiple Photo from Android Gallery and display in the WebView.
Is it possible?
What function should I use? from android and web.
please tell me example source or references site.
thank you.


text:
Q: Automator - Get name of dropped file without file type I have a simple automator app that runs a python script on the file that is dropped on it. However, I need to also extract the name of the dropped file so that I can use it to create a directory name.
for f in "$@"
do
    set myFileName to name of (item f of $@)
    /usr/local/bin/python3 /Volumes/Scripts/script.py "$f"
    mkdir myFileName (without extension?)
done

A: The first line of your script is Applescript whereas it should be shell (bash by default). The tersest version I can think of:
for f in "$@"
do
    /usr/local/bin/python3 /Volumes/Scripts/script.py "$f"
    mkdir ${f%.*}
done


text:
Q: how to get celery task state? I am new to Celery and Django. I got the task id using
task_id = task.request.id

but not able to get the task state.
Any suggestion to get the task state? Any help would be appreciated. Thanks!

A: I got the status of task as below
task.py
from celery.result import AsyncResult

result = task_name.AsyncResult(task_name.request.id)
taskStatus = result.state

celeryconfig.py
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CELERY_IGNORE_RESULT = False
CELERY_TRACK_STARTED = True


text:
Q: Dart/Flutter: change content of container on tab in ListView I am currently trying to create something like a TabBar. I created a horizontal ListView which should work as the TabBar and I my goal is, that one row fills itself with a list that contains the cards for the Tab I clicked on and refreshes when I click on another one. Is there a way to do that? It should look like this:
Reference Picture

A: Did you look at Work with tabs, an introduction to TabBar, TabBarView and DefaultTabController?
You could also create it from scratch using a ListView with a Card wrapped in a GestureDetector or a ListTile, and detect taps on onTap, which would set the selected data and update state using setState.


text:
Q: На WordPress-сайте возникла ошибка при смене темы Когда пытаюсь поменять тему, пишет это
Fatal error: Uncaught ArgumentCountError: array_merge() does not accept unknown named parameters in C:\xampp\htdocs\wordpress.dev\wp-includes\widgets.php:1265 Stack trace:
#0 C:\xampp\htdocs\wordpress.dev\wp-includes\widgets.php(1265): array_merge(wp_inactive_widgets: Array, sidebar-1: Array)
#1 C:\xampp\htdocs\wordpress.dev\wp-includes\widgets.php(1220): retrieve_widgets(true)
#2 C:\xampp\htdocs\wordpress.dev\wp-includes\class-wp-hook.php(289): _wp_sidebars_changed('Twenty Twenty')
#3 C:\xampp\htdocs\wordpress.dev\wp-includes\class-wp-hook.php(311): WP_Hook->apply_filters(NULL, Array)
#4 C:\xampp\htdocs\wordpress.dev\wp-includes\plugin.php(478): WP_Hook->do_action(Array)
#5 C:\xampp\htdocs\wordpress.dev\wp-includes\theme.php(3267): do_action('after_switch_th...', 'Twenty Twenty', Object(WP_Theme))
#6 C:\xampp\htdocs\wordpress.dev\wp-includes\class-wp-hook.php(287): check_theme_switched('')
#7 C:\xampp\htdocs\wordpress.dev\wp-includes\class-wp-hook.php(311): WP_Hook->apply_filters(NULL, Array)
#8 C:\xampp\htdocs\wordpress.dev\wp-includes\plugin.php(478): WP_Hook->do_action(Array)
#9 C:\xampp\htdocs\wordpress.dev\wp-settings.php(546): do_action('init')
#10 C:\xampp\htdocs\wordpress.dev\wp-config.php(89): require_once('C:\\xampp\\htdocs...')
#11 C:\xampp\htdocs\wordpress.dev\wp-load.php(37): require_once('C:\\xampp\\htdocs...')
#12 C:\xampp\htdocs\wordpress.dev\wp-admin\admin.php(34): require_once('C:\\xampp\\htdocs...')
#13 C:\xampp\htdocs\wordpress.dev\wp-admin\themes.php(10): require_once('C:\\xampp\\htdocs...')
#14 {main} thrown in C:\xampp\htdocs\wordpress.dev\wp-includes\widgets.php on line 1265
На сайте возникла критическая ошибка. Пожалуйста, проверьте входящие сообщения почты администратора для дальнейших инструкций.


text:
Q: Magento still writing in system /tmp I've read several threads about this, but still can't resolve the issue.
We use apache + PHP-FPM. In Magento tree files are owned by apache-user:dev. Now, using 775 / 664 for dirs and files. Also, we disabled redis and using files for backend cache.
When I clear / flush cache in backend, most files get written in magento-dir/var/cache as usual, but I noticed some files are written in system /tmp (not in /tmp/magento). Actually, 14 files with "Locale" serialized data:
zend_cache---internal-metadatas...
zend_cache---Zend_LocaleC...
zend_cache---Zend_LocaleL...
That is, some files get written correctly in var/cache and others in system /tmp directory.
Running scripts in magento root to get system var dir:
<?php
echo sys_get_temp_dir();
?>

returns /tmp
and magento var:
<?php

require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();

$var_dir = Mage::getModel('core/config')->getVarDir();
echo $var_dir;

Returns magento-dir/var, as expected.
Also, permissions seem correct, since most files get written properly.
Anyone with this behavior?

A: It happens when you do not have writing permissions on var folder.
Make sure you can read and write it.

A: This is the only option that worked for me:
Copy contents from
lib/Zend/Cache/Backend/File.php
To
app/code/local/Zend/Cache/Backend/File.php
And editing line :99
Instead of 'cache_dir' => null, 'cache_dir' => 'var/cache',
as in
protected $_options = array(
        'cache_dir' => 'var/cache',
        'file_locking' => true,
        'read_control' => true,
        'read_control_type' => 'crc32',
        'hashed_directory_level' => 0,
        'hashed_directory_perm' => 0700,
        'file_name_prefix' => 'zend_cache',
        'cache_file_perm' => 0600,
        'metadatas_array_max_size' => 100
    );

A: It was designed to work that way. Zend cache will be stored in /tmp. Have to dig deep to identify the reason for not having inside var/cache. But my safe guess would be those are the core Zend files which will not be touched by making changes via admin. Because /tmp is the folder which cache wsdl's as well when your application uses soap api integration.


text:
Q: Remove all but one specific cookie from a reverse proxy request I'm using Apache 2.4.4 on a Windows machine acting as a front end to another OLD bespoke web serving application.
Lately I've been having problems with cookies being passed to the old web app, causing that web app to fail. I think this might be related to google analytics cookies but am not 100% sure.
Is it possible with Apache to remove all but one cookie from the request sent to the reverse proxy web app?
The name of the cookie which I do want to allow through is called "PM2".
Here is my reverse proxy configuration:
<IfModule mod_proxy.c>

 <ifModule mod_rewrite.c>

    RewriteEngine On

    RewriteRule ^/(.*\.[aA]4[dD])$ http://127.0.0.1:8080/$1 [P,L]

    RewriteRule ^/4DCGI/(.*)$ http://127.0.0.1/$1 [P,L,nocase]

    ProxyPassReverse / http://127.0.0.1:8080

    ProxyRequests Off

    ProxyTimeout 1200

 </IfModule>

</IfModule>


text:
Q: Why does $(^n a)$ eventually become constant modulo $\phi (n)$. Sorry, I changed this question from another one I delete a few minutes ago, but I'm slightly confused on this question."
In the following link, the statement in Case $1$, "since $\phi(m) < m$, by induction hypothesis, $(^n a) \text{ mod } \phi(m)$ is eventually constant" doesn't make a lot of sense to me can someone elaborate on that?
To elaborate, the base question is that
$$1,a,a^a,...$$
eventually becomes constant modulo $n.$

A: The natural numbers are a well order ( meaning there's a least element). This means $\phi(n)<n$ which implies $\phi(\phi(n))<\phi(n)$ etc. Will eventually hit the lowest element. Since modulo $1$ always returns $0$ we get everything at or above that level doesn't affect the outcome.


text:
Q: How to access ejabberd admin api via HTTP I m getting token now.
http://IP:5280/oauth/authorization_token?response_type=token&client_id=armsprime&redirect_uri=http://www.razrcorp.com/&scope=get_roster+connected_users+sasl_auth
http://www.redirectdomain.com/?access_token=CZ750oz9yPWLvI9p0k5fDlzFfJP4Iu9m&token_type=bearer&expires_in=31536000&scope=get_roster%20connected_users%20sasl_auth&state
But now if try to access using postman
Api url: http://ipaddress:5280/api/get_roster
Header:
Content-Type:application/json
Authorization:Bearer reJqgKFPCyM1OcFmy8XrK9YdRh2UdYxV
//X-Admin:true
Body:
{
}
Response: 400 Bad Request
Can someone please help me out. Thanks in advance.

A: From the documentation, this API call requires a post with user and server as parameters in JSON.


text:
Q: How can I use array data type in mysql? Is there any way to create a column of data type 'array' in mysql table ?
like this below :
create table tb_name (
-> column_name INT ARRAY[1000] NOT NULL);

A: There is no data type to store an array in MySQL.
but you can convert your array to JSON and store it in the table and convert it back to an array when you need it.
Also, you can create a multiple tables to store your array of data.
Your main table,
CREATE TABLE tb_name (
`id` INT NOT NULL PRIMARY KEY,
`column_name` VARCHAR(100),
`column_name` VARCHAR(100)
);

Your array data table
CREATE TABLE array_data (
`id` INT NOT NULL PRIMARY KEY,
`pf_tb_table` INT NOT NULL,
`array_index` INT,
`array_data` VARCHAR(100),
FOREIGN KEY (pf_tb_table) REFERENCES tb_name (id),
);


text:
Q: how to setup secure access to a host on internet? we are planning to setup a source code repo + bug tracker for multiple users across the globe. Hence the network is internet - that is the host has public IP address provided by the ISP.
since this host is not a registered domain or IP on the internet, how can the problem of access from internet to this host be solved?
what software , hardware is required

A: You could get a virtual server with Amazon EC2 instance or a VPS provider. With Amazon you get free static IP and then you either access it by IP address or register a domain name. For security, if it is linux then IPtables is the key word. Alternatively and if you go with amazon, you are also getting free virtual firewall that is more then adequate. And for connectivity make sure you use encrypted connections (ssl, ssh) and you will be fine. If you concerned about DOS attacks the talk to professional - there is no easy solution for this. Hope this helps.

A: When you plan this setup i think its better you take a server from an internet hoster. Then you get an ip and domain and webspace.
When you want to put the server in your local intranet then you need to forward the port to your server. But then you have opened your system for people from outside and you need an external ip-adress. If you don't get one you can use something like "dyndns" but i think its not the best way.


text:
Q: jQuery script not executing I have a button that I modify with jQuery, to change it's id and/or class. And when it has a spesific class and user clicks the button, it should execute the following script:
$(document).ready(function() {
$(function() {
    $('.error').hide();
    $("#tilisiirtobtn").click(function() {
        alert("buttoni toimii");
        var Nimi =             $(".Nimi").val();
        var Osoite =           $(".Osoite").val();
        var Postinumero =      $(".Postinumero").val();
        var Postitoimipaikka = $(".Postitoimipaikka").val();
        var Puhelin =          $(".Puhelin").val();
        var Sahkoposti =       $(".Sahkoposti").val();
        var Filtteri =         /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
        $('.error').hide();
        if(Nimi == ""){
            $(".Nimi").focus();
            $("#Nimi-error").show();
            return false;
        }
        if(Osoite == ""){
            $(".Osoite").focus();
            $("#Osoite-error").show();
            return false;
        }
        if(Postinumero == ""){
            $(".Postinumero").focus();
            $("#Postinumero-error").show();
            return false;
        }
        if(Postitoimipaikka == ""){
            $(".Postitoimipaikka").focus();
            $("#Postitoimipaikka-error").show();
            return false;
        }
        if(Puhelin == ""){
            $(".Puhelin").focus();
            $("#Puhelin-error").show();
            return false;
        }
        if(Sahkoposti == ""){
            $(".Sahkoposti").focus();
            $("#Sahkoposti-error").show();
            return false;
        }

        $('.supernappula').attr('disabled', 'disabled');
      var data = $('#yhteystiedot').serializeArray();
      data.push( { name: 'cartContent', value: $('#emailedcart').html()});
      //alert (data);return false;
     $.ajax({
    type: "POST",
    data: data,
    url: "order/order.php",
    dataType: "html",
    error: function(){ if(confirm("Mitään ei näytä tapahtuvan. Päivitä sivu?") == true){ window.location.reload();}
 },
    success: function() {
 alert("Onnistui");
        }

  });
  return false;

    });
  });
});

However, it won't even execute the alert that is the first thing to do.
Here's the code that changes the id and class of the button:
$(function() {
    $("#paypal").click(function() {
        $(".yhteystiedot").slideUp(600);
        $(".toimitustapa").slideDown(600);
        $('form :input').val("");
        $('.supernappula').html("Maksa PayPalissa");
        $('.supernappula').addClass("simpleCart_checkout");
        $('.supernappula').attr("id", "checkoutbtn");
    });
    $("#tilisiirto").click(function() {
        $(".yhteystiedot").slideDown(600);
        $(".toimitustapa").slideDown(600);
        $('.supernappula').html("Tee tilisiirto");
        $('.supernappula').removeClass("simpleCart_checkout");
        $('.supernappula').attr("id", "tilisiirtobtn");

    });
    $("#postiennakko").click(function() {
        $(".yhteystiedot").slideDown(600);
        $(".toimitustapa").slideDown(600);
        $('.supernappula').html("Maksa postiennakolla");
        $('.supernappula').removeClass("simpleCart_checkout");
        $('.supernappula').attr("id", "postiennakkobtn");

    });

    $("#matkahuolto").click(function(){
        $(".maksu").slideDown(600);

    });
    $("#posti").click(function(){
        $(".maksu").slideDown(600);

    });

});

And the button itself without modifications:
<button type="button" id="checkoutbtn" class="simpleCart_checkout supernappula"></button>
Here's a fiddle of the whole page.
If anyone understands?

A: The most likely resolution to this is that you need to use jQuery's live function rather than click.
With the click handler, it registers everything on the page as it is and does not register the event for elements in the future which will have the given selector.
livesolves this problem by adding the event handler to all elements now, and in the future.
http://api.jquery.com/live/
Changing this line:
$("#tilisiirtobtn").click(function() {
to
$("#tilisiirtobtn").live('click', function() {
Should solve your problem.
Here's a working jsFiddle

A: You're double calling document ready. All you need is $(function()... not the wrapper of $(document).ready(function() { you've put around it.


text:
Q: Where do I go to upgrade my ship? Where can I go to purchase ship upgrade components in X Rebirth?  Can I only do that at specific stations or can I run into an equipment dealer anywhere?

A: So far, I have been able to find various mechanics on board stations that sells me upgrades such as shields, engines, weapons, and sensors.

A: You need a mechanic.  Often in stations with a Spanner symbol.  Click on icon before docking and it says whether there is one.

A: There's option to upgrade your other ships in squad if you find shipyards with compatible ship designs. But upgrade here does not seem to be able to upgrade engine, shield etc. It would however upgrade turrets count, shield projector count etc.


text:
Q: Get the last matching key from an array of objects to check value Where my data looks like so:
[
 {
  _id:1
  events: [
   {selectedPet: 'cat', time: '2015-09-18T12:00:00.000Z'},
   {selectedPet: 'dog', time: '2015-09-18T12:00:01.000Z'},
   {colourHat: 'green', time: '2015-09-18T12:00:01.200Z'},
   {selectedPet: 'bird', time: '2015-09-18T12:00:02.000Z'},
  ]
 },
 {
  _id:2
  events: [
   {selectedPet: 'bird', time: '2015-09-18T12:00:00.000Z'},
   {selectedPet: 'cat', time: '2015-09-18T12:00:01.000Z'},
   {selectedPet: 'dog', time: '2015-09-18T12:00:02.000Z'},
   {favouriteAnimal: 'bird', time: '2015-09-18T12:00:04.000Z'},
  ]
 }
]

How can I query for the last selected pet (last in the array, or last by time - array is chronological) being a bird?
Doing:
db.getCollection('events').find({
   'events.selectedPet': 'bird'
});

Will return both documents, but the intended output for selecting documents where the last select pet was a bird would be:
[
 {
  _id:1
  events: [
   {selectedPet: 'cat', time: '2015-09-18T12:00:00.000Z'},
   {selectedPet: 'dog', time: '2015-09-18T12:00:01.000Z'},
   {colourHat: 'green', time: '2015-09-18T12:00:01.200Z'},
   {selectedPet: 'bird', time: '2015-09-18T12:00:02.000Z'},
  ]
 }
]

This is example data. My real data set is hundreds of thousands of documents each with around 500 events.
Thank you =)

A: Well you can use the $where operator. But bear in mind that it does JavaScript evaluation and cannot take advantage of indexes.
db.collection.find({ "$where": function() {
    for (var i = this.events.length - 1; i >= 0; i--) {
        if (this.events[i]["selectedPet"]) {
            return this.events[i]["selectedPet"] === "bird";
        }
    }}
})

From forthcoming release you can use aggregation and the $slice operator.
db.collection.aggregate([
    {
        "$project": {
            "e": { "$slice": [
                { "$setDifference": [
                    { "$map": {
                        "input": "$events",
                        "as": "ev",
                        "in": { "$ifNull": ["$$ev.selectedPet", false]}
                    }},
                    [false]]
                },
               -1
            ]},
            "events": 1
     }},
     { "$match": { "e": "bird" } }
])


text:
Q: Interpretation of $\mathcal{D}$ and difference between the accuracy parameter and training error I am studying the book "Understanding Machine Learning:
From Theory to Algorithms". They introduce the following things, which I'm not sure i'm interpreting correctly:
The training error(p35) $$L_S(h):=\frac{|\{i\in[m]:h(x_i)\neq y_i\}|}{m}$$
Where $S=((x_1,y_1),...,(x_m,y_m))$ is the training data.
Then they define the error of a classifier (p34):

Formally, given a domain subset, $A\subset \mathcal{X}$, the probability distribution $\mathcal{D}$, assigns a number, $\mathcal{D}(A)$, which determines how likely it is to observe a point $x\in A$. We define the error of a prediction rule, $h:\mathcal{X}\to \mathcal{Y}$, to be $$L_{\mathcal{D},f}(h):=P_{x\sim\mathcal{D}}[h(x)\neq f(x)]:=\mathcal{D}(\{x:h(x)\neq f(x)\})$$.

Where they define $\mathcal{D}$ as the probability distribution over $\mathcal{X}$

Question 1: How exactly is $\mathcal{D}$ supposed to be interpreted? I will give a trivial example and please tell me if this is the correct way I have interpreted it: For example, let $\mathcal{X}=\{x_1,x_2,x_3\}$ and $\mathcal{Y}=\{0,1\}$. Let $f(x_i)=1$ if $x\geq 0$ and $0$ otherwise. Then let  $\mathcal{D}$ be such that $P(x_1\geq 0)=1/2, P(x_2\geq 0)=1/3, P(x_3 \geq 0)=1/4$. Is this a reasonable example of how to interpret $\mathcal{D}$?Then on p38 last sentence, they introduce the accuracy parameter $\epsilon$.
Question 2:What is essentially the difference between the accuracy parameter and the training error?

A: In my view, the assumption of a deterministic relationship between labels and inputs made in chapter 2 of that book can be interpreted, but it's a bit artificial because it's not probabilistic machine learning in the way we normally think about it. Your queries in my view, are best dealt with not in isolation, but in concert with the crux of what that book is about. Here's how the statistical learning framework normally proceeds. I will use the author's informal papaya analogy first, then formalise it using the tools in chapter 3.
We can conceive of all possible papayas on an island and their tastiness. We are interested in predicting whether a papaya is tasty or not based on a fixed set of observed characteristics, such as softness, smell, shape etc. It's also the case that two papayas with exactly the same observed characteristics may ultimately differ in whether or not they are tasty.
Formally, we can set up the problem as the following. You have input features $X \in \mathcal{X}$ and labels $Y \in \mathcal{Y}$. For binary classification, if we are interested in $d$ papaya characteristics, we might let the input space $\mathcal{X} = \mathbb{R}^d$ and $\mathcal{Y} = \{0, 1\}$. We now assume that there is a joint probability distribution $\mathcal{D} = P(X, Y)$ over input features and labels, that this is a probability distribution encodes the fact that papayas with the same observed characteristics may not all necessarily get the same class label.
The goal is to estimate a predictor, $h$ which is a function $h: \mathcal{X} \rightarrow \mathcal{Y}$. In order to so, we need a criterion for choosing a predictor $h$ from some restricted class of predictors $\mathcal{H}$. Ideally, we want to select $h$ from $\mathcal{H}$ in such a way so as to minimise the true error/risk/generalisation error
$$L_{\mathcal{D}}(h) := \underset{(x, y) \sim \mathcal{D}}{\mathbb{P}} \left( h(x) \neq y \right).$$
The problem however is that we do not know $\mathcal{D} = P(X, Y)$. In terms of the statistical angle on the authors' analogy, it might be infeasible to go around the entire island recording all observed characteristics of papayas and their tastiness. However, we do have indirect, limited access to $\mathcal{D}$ through a training data sample $(x_1, y_1), \dots (x_m, y_m) \sim \mathcal{D}$ consisting of $m$ papayas' observed characteristics and their tastiness labels. So we have to be content with selecting $h$ to minimise an empirical estimate of the true error, and we call this the training error/empirical risk
$$L_S(h) := \frac{\vert i \in [m] : h(x_i) \neq y_i \vert}{m} = \frac{1}{m} \sum^m_{i=1} \mathbb{I} (h(x_i) \neq y_i).$$
Notice that when $h$ is a single, arbitrary, fixed predictor from $\mathcal{H}$, then $L_{\mathcal{S}}(h)$ is a sample mean (estimator) of the unknown population quantity $L_{\mathcal{D}}(h)$. When $h$ is fixed, then the former is a random variable while the latter a fixed constant.
In order for our strategy of choosing $h$ from $\mathcal{H}$ by minimising $L_{S}(h)$ as an estimate of $L_{\mathcal{D}}(h)$ to work, we need to be sure that these quantities are 'close together'. The subtlety is that there are multiple $h$s in $\mathcal{H}$, not just one fixed $h$ in $\mathcal{H}$, and we don't know in advance exactly which $h$ will be responsible for minimising $L_S(h)$. Hence we require that an entire collection of random variables $L_S(h)$, one for each $h \in \mathcal{H}$, to be 'simultaneously close to' the collection of constants $L_{\mathcal{D}}(h)$ for each $h \in \mathcal{H}$. This would guarantee that any $h$ selected from $\mathcal{H}$ using our strategy would minimise a 'good' approximation of the true error $L_{\mathcal{D}}(h)$. Formally, we require a statement of the form
$$\begin{align}\mathbb{P} \left( \forall h \in \mathcal{H}, \vert L_{S}(h) - L_{\mathcal{D}}(h) \vert \leq \epsilon \right) &= \mathbb{P} \left( \bigcap_{h \in \mathcal{H}} \vert L_{S}(h) - L_{\mathcal{D}}(h) \vert \leq \epsilon  \right) \\
&= \mathbb{P} \left( \sup_{h \in \mathcal{H}} \vert L_{S}(h) - L_{\mathcal{D}}(h) \vert \leq \epsilon \right) \\
& \geq 1 - \delta.
\end{align}$$
That is, with probability at least $1 - \delta$ over all $m$-size training samples, the training error $L_S(h)$ is within $\pm \epsilon$ of the true error $L_{\mathcal{D}}(h)$ for every $h \in \mathcal{H}$. Parsing this in the PAC/statistical learning theory dialect, with confidence $1 - \delta$, the empirical risk functional $L_S(\cdot)$ is uniformly close, i.e. up to an accuracy parameter of $\epsilon$, to the true risk functional $L_{\mathcal{D}}(\cdot)$ over the entire space $\mathcal{H}$. So far, this has assumed that $\mathcal{H}$ is finite. Developing tools for and identifying conditions under which uniform bounds/convergence statements like the above hold when $\mathcal{H}$ is infinite is the central preoccupation of both that book and statistical learning theory in general.
So $\epsilon$ is a real-analysis like arbitrary constant which retains the semantics of proximity. Additionally, in this particular context, it refers to the accuracy of the approximation of $L_{\mathcal{D}}(\cdot)$ using $L_S(\cdot)$, and is distinct from training error.
Lastly, to interpret the $\mathcal{D}$ in the more artificial context of chapter 2, note that all of the above uses $\mathcal{D} = P(X, Y) = P(Y | X)P(X)$. Which implies a distribution on papaya observable characteristics $P(X)$, and a distribution on papaya tastiness given papaya observable characteristics $P(Y | X)$. The setting of chapter 2 is $\mathcal{D} = P(X)$ and $y = f(x)$, meaning that the only stochasticity is in the distribution of papaya observable characteristics $P(X)$, while the relation between papaya tastiness and observable characteristics $y = f(x)$ is fully deterministic.
To better address interpretation of $\mathcal{D}$, here is an example in both cases. For illustrative purposes, assume 3 binary features in the input space $X \in \{0, 1\}^3$ and $Y \in [0, 1]$.
When $\mathcal{D} = P(X, Y)$, then this distribution encodes statements like $$\mathbb{P}(X_1 = \text{soft}, X_2 = \text{not oval-shaped}, X_3 = \text{rotten smelling}, Y = \text{not tasty}) = 0.50.$$
When instead of $P(X, Y)$, we have $\mathcal{D} = P(X)$ together with $f$  then this gives statements like
$$\mathbb{P}(X_1 = \text{soft}, X_2 = \text{not oval-shaped}, X_3 = \text{rotten smelling}) = 0.25$$
together with a 'codebook', in the form of a deterministic function $f$ telling me that $f(\text{soft}, \text{not oval-shaped}, \text{rotten-smelling}) = \text{not tasty} = y$ with certainty.


text:
Q: Query a document and all of its subdocuments that match a condition in mongodb I have a MongoDB storing data from different sensors.
It has the following structure:
 {
     "_id" : 1,
     "sensorName" : "Heart Rate",
     "samplePeriod" : 1000,
     "data" : [
             {
                 "timestamp" : NumberLong("1483537204046"),
                 "dataPoints" : [ 68 70 ]
             },
             {
                 "timestamp" : NumberLong("1483537206046"),
                 "dataPoints" : [ 68 70 ]
             }
     ]
}
{
    "_id" : 2,
    "sensorName" : "Ambient Light",
    "samplePeriod" : 500,
    "data" : [
            {
                "timestamp" : NumberLong("1483537204058"),
                "dataPoints" : [ 56, 54, 54, 54 ]
            },
            {
                "timestamp" : NumberLong("1483537206058"),
                "dataPoints" : [ 56, 54, 54, 54 ]
            }
    ]
}

Now for example i need the "Heart Rate" - document with all of its fields and those of its "data" - subdocuments matching the condition "timestamp between 1483537204000 and 1483537214000".
I know about aggregation but cant figure out, how to not only return the matching subdocuments but to return the whole "Heart Rate" - document containing only the matching subdocuments in "data".
Is my structure efficient at all? Do you have any hint for a better structure for efficient querying for such data?
Thanks in advance!

A: You can try something like below.
$match to keep the heart rate record.
$filter to filter the subdocument with the condition.
$project to display the results.
aggregate([{
    $match: {
        "_id": 1
    }
}, {
    "$project": {
        "_id": 1,
        "sensorName": 1,
        "samplePeriod": 1,
        "data": {
            "$filter": {
                "input": "$data",
                "as": "result",
                "cond": {
                    $and: [{
                        $gte: ["$$result.timestamp", 1483537204000]
                    }, {
                        $lte: ["$$result.timestamp", 1483537214000]
                    }]
                }
            }
        }
    }
}])


text:
Q: Compilation / Code Generation of External Scala DSL My understanding is that it is quite simple to create & parse an external DSL in Scala (e.g. representing rules). Is my assumption correct that the DSL can only be interpreted during runtime but does not support code generation (like ANTLR) for archiving better performance ?
EDIT: To be more precise, my question is if I could achieve this (create an external domain specific language and generate java/scala code) with built-in Scala tools/libraries (e.g. http://www.artima.com/pins1ed/combinator-parsing.html). Not writing a whole parser / code generator completely by yourself in scala. It's also clear that you can achieve this with third-party tools but you have to learn additional stuff and have additional dependencies. I'm new in the area of implementing DSLs, so I have no gutfeeling so far when to use external tools like ANTLR and what you can (with a reasonable effort) do with Scala on-board stuff.

A:
Is my assumption correct that the DSL can only be interpreted during runtime but does not support code generation (like ANTLR) for archiving better performance ?

No, this is wrong. It is possible to write a compiler in Scala, after all, Scala is Turing-complete (i.e. you can write anything), and you don't even need Turing-completeness for a compiler.
Some examples of compilers written in Scala include

*

*the Scala compiler itself (in all its variations, Scala-JVM, Scala.js, Scala-native, Scala-virtualized, Typelevel Scala, the abandoned Scala.NET, …)

*the Dotty compiler

*Scalisp

*Scalispa

*… and many others …


text:
Q: webpack - exclude files from specific entry point In my application I have multiple entry points.
One entry point is creating a bundle which is restricted only for signed in users.
Is there a way to tell webpack to not bundle any file that needs to be restricted into the 'public' bundle? and instead not bundle it / throw a compilation error?
is there an exclude per entry point?
The only solution I can think of is creating two separate webpack config files, is there a better way?
Thanks
--- edit ---
I will try to rephrase the question -
Is there a way to enforce that some files will be excluded from a specific bundle/entry point, or in other words, there are files that I want in a specific bundle, and not in a any other bundle, and I want to enforce it.

A: From the Webpack documentation link :
Exclude File and Multiple Configurations
module.exports = [{
      output: {
        filename: './dist-amd.js',
        libraryTarget: 'amd'
      },
      name: 'amd',
      entry: './app.js',
      mode: 'production',
      rules: [
              {
                test: /\.js$/,
                exclude: [
                    'src/configs/configs/your1.js'
                  ]
              }
            ]
    }, {
      output: {
        filename: './dist-commonjs.js',
        libraryTarget: 'commonjs'
      },
      name: 'commonjs',
      entry: './app2.js',
      mode: 'production',
      rules: [
              {
                test: /\.js$/,
                exclude: [
                    'src/configs/configs/your2.js'
                  ]
              }
            ]
    }];

  };

Special thanks to @Axnyff for completing my answer.


text:
Q: CKeditor 4 replace config param for each field I got 3 textarea on page.
It's conected with CKeditor. also got CKeditor plugin on it.
I wish to have different characters count for each field.
Now I give it in config for all of them:
CKEDITOR.config.wordcount.maxCharCount=30;

to sum up:
how I change config value for one field in ck'editor

A: You should be able to use the tag MaxLength on each individual control.
<cke:CKEditorControl ID="ckeText" Toolbar="" AutoGrowOnStartup="true" MaxLength="5" runat="server" />

You can also find all of that information on their documentation website docs.ckeditor.com


text:
Q: is the same recursive CTE and trigger instead of delete? I am using SQL Server 2008 Express R2 and I have a table that is self referencing, because I have a hierarchy struct.
I need to delete a root node, but I get an error because of foreign key. I have read that I can use two option, use a recursive CTE o use a instead of delete trigger.
Which is the difference brtween both of them? which is more efficient?
Thanks.

A: When you say use a delete trigger as opposed to a recursive CTE, I assume you are going to do some kind of loop in the trigger, which would mean the CTE would be more efficient.
For a CTE, try something like:
with cte as (
    select id as root, parent, id
    from [<YourTable>]
    where parent is null -- This selects root nodes

    union all

    select cte.root, d.parent, d.id
    from cte
    inner join data d on cte.id = d.parent
)
delete from [<YourTable>]
from [<YourTable>]
inner join cte on rel.id = cte.id
where cte.root = 1 -- This is the root to delete


text:
Q: Como descobrir se um ImageView possui uma foto informada Olá, quero criar um condicional que verifica se todos os campos da tela foram informados pelo usuário ou não. Caso algum não tenha sido informado, gostaria de apresentar um toast mostrando o erro. O problema é que nesta tela eu possuo um ImageView e não consigo descobrir quando ele foi informado ou não.
Código desta função:
if ((edtTitulo.getText().toString().isEmpty()) ||   (edtPreparo.getText().toString().isEmpty()) || (edtIngredientes.getText().toString().isEmpty())){
    Toast toast = Toast.makeText(getApplicationContext(), "Todos os campos são obrigatórios", Toast.LENGTH_LONG);
    toast.show();
}

Como acrescentar o ImageView vazio nesta condição?

A: Dependendo do método que usou para atribuir a foto à ImageView use
if(imageView.getDrawable() != null)

ou
if(imageView.getBackground() != null)


text:
Q: Proof with a Vandermonde variant Currently Studying "Linear Algebra" by Georgi E. Shilov.
I encountered the following problem.
Prove that:
$$\begin{vmatrix}
1 & 1 & ... & 1\\
x_1 & x_2 & ... & x_n\\
{x_1}^2 & {x_2}^2 & ... & {x_n}^2\\
. & . & ... & .\\
{x_1}^{n-2} & {x_2}^{n-2} & ... & {x_n}^{n-2}\\
{x_1}^{n} & {x_2}^{n} & ... & {x_n}^{n}
\end{vmatrix} =
\begin{vmatrix}
1 & 1 & ... & 1\\
x_1 & x_2 & ... & x_n\\
{x_1}^2 & {x_2}^2 & ... & {x_n}^2\\
. & . & ... & .\\
{x_1}^{n-2} & {x_2}^{n-2} & ... & {x_n}^{n-2}\\
{x_1}^{n-1} & {x_2}^{n-1} & ... & {x_n}^{n-1}
\end{vmatrix} * \sum_{k=1}^n x_k$$
Immediately I noticed that the matrix on the right is the vandermonde matrix. The first thing I did was to try to find a column or row on the left side matrix to try to do a cofactor expansion that will lead to minors equal to the vandermonde. Unfortunatelly I dont think thats the aproach. Another thing that jumped in is that it has to be related to the row with powers of n-1 since its the biggest difference between them. I hope someone can guide me in the right direction.


text:
Q: Python coding calculator I created this code to build a calculator that will automatically call the right arithmetic function based on the user input.
I have written a sample functions. I wrote for addition on the bottom as a comment.
When I run the code, in the for loop it should match the user's input to the list for addition in order to confirm the arithmetic function to use, in this case, it does not work.
Also "Invalid arithmetic function" gets printed anyways for whatever your input is.
I am new to python and still learning. Any guidance is appreciated.
from Calculator import addition

divisions = ["division", "divide", "/"]
multiplications = ["multiplication", "multiply", "*", "x", "X"]
additions = ["addition", "add", "+"]
subtractions = ["subtraction", "subtract", "-"]

answers = 0

problem = input("Which arithmetic function do you want to perform? ")
num1 = int(input("What is your first number? "))
num2 = int(input("What is your second number? "))

if type(problem) == str:
    for i in additions:
        if problem == i:
            answers = addition(num1, num2)
            print(answers)
        else:
            print("Invalid arithmetic function")
            break
else:
    print("Invalid arithmetic functions")

print(answers)

#def addition(num, num0):
#    answer = num + num0
#    return answer

A: Problem with your code
for i in additions:
   if problem == i:

here first "addition" is not "+" so loop is breaking on first time.
Solution
instead of loop use direct if condition
if problem in additions:

check this code
divisions = ["division", "divide", "/"]
multiplications = ["multiplication", "multiply", "*", "x", "X"]
additions = ["addition", "add", "+"]
subtractions = ["subtraction", "subtract", "-"]

answers = 0

problem = input("Which arithmetic function do you want to perform? ")
num1 = int(input("What is your first number? "))
num2 = int(input("What is your second number? "))

def addition(num, num0):
   answer = num + num0
   return answer

if type(problem) == str:
  if problem in additions:
      answers = addition(num1, num2)
      print(answers)
  else:
      print("Invalid arithmetic function")
else:
    print("Invalid arithmetic functions")

A: You can substantially simplify your code as below:
divisions = ["division", "divide", "/"]
multiplications = ["multiplication", "multiply", "*", "x", "X"]
additions = ["addition", "add", "+"]
subtractions = ["subtraction", "subtract", "-"]

problem = input("Which arithmetic function do you want to perform? ")
if problem in additions:
    num1 = int(input("What is your first number? "))
    num2 = int(input("What is your second number? "))
    print('Answer is:', num1 + num2)
else:
    print("Invalid arithmetic function")

A: When debugging your program, here is what I found the problem to be:
for i in additions:
            if problem == i:
                answers = addition(num1, num2)
                print(answers)
            else:
                print("Invalid arithmetic function")
                break

The for loop will search through the additions list and output a result for every item. To stop that, remove the print functions and only print after the calculations are done.
There are multiple ways to re-implement the "Invalid arithmetic function" error message. One of the simplest being to put the code block inside a function and return the value.
Here is the working version:
    divisions = ["division", "divide", "/"]
    multiplications = ["multiplication", "multiply", "*", "x", "X"]
    additions = ["addition", "add", "+"]
    subtractions = ["subtraction", "subtract", "-"]

    answers = 0

    problem = input("Which arithmetic function do you want to perform? ")
    num1 = int(input("What is your first number? "))
    num2 = int(input("What is your second number? "))

    def addition(num, num0):
        answer = num + num0
        return answer

    def calculateAnswer():
        if type(problem) == str:
        for i in additions:
          if problem == i:
            answers = addition(num1, num2)
            return answers
      #If an answer is not returned, the code below will execute
      return "Invalid arithmetic function"

    print(calculateAnswer());

A: The problem is that you are adding a else within the for loop. Wait for the loop to end as the last item in the list could be the one matching the problem string.
divisions = ["division", "divide", "/"]
multiplications = ["multiplication", "multiply", "*", "x", "X"]
additions = ["addition", "add", "+"]
subtractions = ["subtraction", "subtract", "-"]

answers = None

problem = input("Which arithmetic function do you want to perform? ")
num1 = int(input("What is your first number? "))
num2 = int(input("What is your second number? "))
if type(problem) == str:
    for i in additions:
        if problem == i:
            answers = num1+ num2
            print(answers)
    if(answers == None):
            print("Invalid arithmetic functions")

else:
    print("Invalid arithmetic functions")


text:
Q: Options for parsing/processing C++ files So I have a need to be able to parse some relatively simple C++ files with annotations and generate additional source files from that.
As an example, I may have something like this:
//@ service
struct MyService
{
   int getVal() const;
};

I will need to find the //@ service annotation, and get a description of the structure that follows it.
I am looking at possibly leveraging LLVM/Clang since it seems to have library support for embedding compiler/parsing functionality in third-party applications. But I'm really pretty clueless as far as parsing source code goes, so I'm not sure what exactly I would need to look for, or where to start.
I understand that ASTs are at the core of language representations, and there is library support for generating an AST from source files in Clang. But comments would not really be part of an AST right? So what would be a good way of finding the representation of a structure that follows a specific comment annotation?
I'm not too worried about handling cases where the annotation would appear in an inappropriate place as it will only be used to parse C++ files that are specifically written for this application. But of course the more robust I can make it, the better.

A: One way I've been doing this is annotating identifiers of:

*

*classes

*base classes

*class members

*enumerations

*enumerators

E.g.:
class /* @ann-class */ MyClass
    : /* @ann-base-class */ MyBaseClass
{
    int /* @ann-member */ member_;
};

Such annotation makes it easy to write a python or perl script that reads the header line by line and extracts the annotation and the associated identifier.
The annotation and the associated identifier make it possible to generate C++ reflection in the form of function templates that traverse objects passing base classes and members to a functor, e.g:
template<class Functor>
void reflect(MyClass& obj, Functor f) {
    f.on_object_start(obj);
    f.on_base_subobject(static_cast<MyBaseClass&>(obj));
    f.on_member(obj.member_);
    f.on_object_end(obj);
}

It is also handy to generate numeric ids (enumeration) for each base class and member and pass that to the functor, e.g:
    f.on_base_subobject(static_cast<MyBaseClass&>(obj), BaseClassIndex<MyClass>::MyBaseClass);
    f.on_member(obj.member_, MemberIndex<MyClass>::member_);

Such reflection code allows to write functors that serialize and de-serialize any object type to/from a number of different formats. Functors use function overloading and/or type deduction to treat different types appropriately.

A: Parsing C++ code is an extremely complex task. Leveraging a C++ compiler might help but it could be beneficial to restrict yourself to a more domain-specific less-powerful format i.e., to generate the source and additional C++ files from a simpler representation something like protobufs proto files or SOAP's WSDL or even simpler in your specific case.

A: I did some very similar work recently.  The research I did indicated that there wasn't any out-of-the-box solutions available already, so I ended up hand-rolling one.
The other answers are dead-on regarding parsing C++ code.  I needed something that could get ~90% of C++ code parsed correctly; I ended up using srcML.  This tool takes C++ or Java source code and converts it to an XML document, which makes it easier for you to parse.  It keeps the comments in-tact.  Furthermore, if you need to do a source code transformation, it comes with an reverse tool which will take the XML document and produce source code.
It works in 90% of the cases correctly, but it trips on complicated template metaprogramming and the darkest corners of C++ parsing.  Fortunately, my input source code is fairly consistent in design (not a lot of C++ trickery), so it works for us.
Other items to look at include gcc-xml and reflex (which actually uses gcc-xml).  I'm not sure if GCC-XML preserves comments or not, but it does preserve GCC attributes and pragmas.
One last item to look at is this blog on writing GCC plugins, written by the author of the CodeSynthesis ODB tool.
Good luck!


text:
Q: Unable to use single-valued column from subquery table join in HAVING clause with aggregate value Related question upon which I based this question here
For relevant tables and columns (a lot more exist than the following), I have a customer table with cust_id and state columns and an account table with account_id, cust_id, and avail_balance columns.
Example customer table:
| cust_id | state |
|--------:|-------|
|       1 | MA    |
|       2 | MA    |
|       3 | MA    |
|       4 | MA    |
|       5 | NH    |
|       6 | MA    |
|       7 | MA    |
|       8 | NH    |
|       9 | MA    |
|      10 | NH    |
|      11 | MA    |
|      12 | NH    |
|      13 | MA    |

Example account table:
| account_id | cust_id | avail_balance |
|-----------:|--------:|--------------:|
|          1 |       1 |       1057.75 |
|          2 |       1 |           500 |
|          3 |       1 |          3000 |
|          4 |       2 |       2258.02 |
|          5 |       2 |           200 |
|          7 |       3 |       1057.75 |
|          8 |       3 |        2212.5 |
|         10 |       4 |        534.12 |
|         11 |       4 |        767.77 |
|         12 |       4 |       5487.09 |
|         13 |       5 |       2237.97 |
|         14 |       6 |        122.37 |
|         15 |       6 |         10000 |
|         17 |       7 |          5000 |
|         18 |       8 |       3487.19 |
|         19 |       8 |        387.99 |
|         21 |       9 |        125.67 |
|         22 |       9 |       9345.55 |
|         23 |       9 |          1500 |
|         24 |      10 |      23575.12 |
|         25 |      10 |             0 |
|         27 |      11 |       9345.55 |
|         28 |      12 |      38552.05 |
|         29 |      13 |         50000 |

Here is the format of the query which I wish to execute.
SELECT a.cust_id, SUM(a.avail_balance) AS cust_tot_bal
FROM
    account AS a
    INNER JOIN customer c ON a.cust_id = c.cust_id
    CROSS JOIN (SELECT MAX(cust_id) AS max_nh_cust_id, MAX(nh_cust_tot_bal) AS max_nh_cust_tot_bal
                FROM
                    (SELECT a.cust_id, SUM(avail_balance) AS nh_cust_tot_bal
                     FROM
                         account AS a
                         INNER JOIN customer c ON a.cust_id = c.cust_id
                     WHERE
                         c.state = 'NH'
                     GROUP BY a.cust_id) AS nh_cust_tot_bal) AS max_nh_cust_tot_bal_t
WHERE c.state = 'MA'
AND a.cust_id > max_nh_cust_id
GROUP BY a.cust_id;

This fails since it is unable to detect max_nh_cust_tot_bal from the previous join.
Expected result for the above example data (the cust_tot_bal column is optional):
| cust_id | cust_tot_bal |
|--------:|-------------:|
|      13 |        50000 |

A: You can get the maximum cust_id and sum of the customers of state 'NH' with this query:
SELECT MAX(cust_id) max_nh_cust_id,
       MAX(t.max_nh_avail_balance) max_nh_avail_balance
FROM (
  SELECT a.cust_id, SUM(a.avail_balance) AS max_nh_avail_balance
  FROM account a INNER JOIN customer c
  ON a.cust_id = c.cust_id
  WHERE c.state = 'NH'
  GROUP BY a.cust_id
) t

and you can join it like this:
SELECT m.cust_id, m.cust_tot_bal
FROM (
  SELECT a.cust_id, SUM(a.avail_balance) AS cust_tot_bal
  FROM account a INNER JOIN customer c
  ON a.cust_id = c.cust_id
  WHERE c.state = 'MA'
  GROUP BY a.cust_id
) m
INNER JOIN (
  SELECT MAX(cust_id) max_nh_cust_id,
         MAX(t.max_nh_avail_balance) max_nh_avail_balance
  FROM (
    SELECT a.cust_id, SUM(a.avail_balance) AS max_nh_avail_balance
    FROM account a INNER JOIN customer c
    ON a.cust_id = c.cust_id
    WHERE c.state = 'NH'
    GROUP BY a.cust_id
  ) t
) n ON m.cust_id > n.max_nh_cust_id AND m.cust_tot_bal > n.max_nh_avail_balance

See the demo.
Results
> cust_id | cust_tot_bal
> ------: | -----------:
>      13 |        50000


text:
Q: For a given function g(n), Why is Θ (g(n)) the set of functions? In the Introduction to algorithms book, the definition of Θ(g(n)) is given by:
Θ(g(n)) = { f(n): there exist positive constants c1, c2, and n0 such that 0 <= c1*g(n) <= f(n) <= c2g(n) for all n>=n0 }
I understand that f(n) can always be sandwiched between c1g(n) and c2g(n) for sufficiently large n when n0 >= 0.
I am not able to understand why Θ(g(n)) is a set of functions of f(n). Per my understanding f(n) is just one function between c1g(n) and c2g(n) . If Θ(g(n)) is a set of functions of f(n) then does that mean that there could be more than one functions f(n)? like   Θ(g(n)) = { f(n1), f(n2), f(n2),... , f(n) } all of the functions f(n) having their own constants c1, c2, n0 .

A: Yes, there can be multiple functions having their own constants. For instance,
Θ(n) contains n, 2n, 3n, 4n, ... for instance where for kn you could just use n0 = 0 and c1=c2=k.


text:
Q: Laravel 360Dialog {"meta": {"success": false, "http_code": 400, "developer_message": "Invalid payload ()", "error": ""}} Estoy llamado a la API de 360Dialog y no me resulta pasarle $minombre al campo TO y $minumero al Parameters Text como parametros al Payload. Parece que el Heredoc <<<'PAYLOAD' no me permite hacerlo o yo lo estoy haciendo mal.
$minombre = "Eduardo Tapia";
$minumero = "56996436710";

// comienzo llamado API 360Dialog

$url = "https://waba-sandbox.360dialog.io/v1/messages";

$payload = <<<'PAYLOAD'
{
    "to": $minumero,
    "type": "template",
    "template": {
        "namespace": "c8ae5f90_307a_ca4c_b8f6_d1e2a2573574",
        "language": {
            "policy": "deterministic",
            "code": "en"
        },
        "name": "first_welcome_messsage",
        "components": [
            {
                "type": "body",
                "parameters": [
                    {
                        "type": "text",
                        "text": $minombre
                    }
                ]
            }
        ]
    }
}
PAYLOAD;

¿Como hago para pasar los parametros variables?

A: Buen día,
La razón por la que tus variables no se "expanden" es porque estás utilizando Nowdoc, puedes hacerlo con Heredoc. Para información detallada de Nowdoc y Heredoc visita este sitio
Sólo quita las comillas simples de 'PAYLOAD' para convertir tu Nowdoc a Heredoc
$minombre = "Eduardo Tapia";
$minumero = "56996436710";

// comienzo llamado API 360Dialog

$url = "https://waba-sandbox.360dialog.io/v1/messages";

$payload = <<<PAYLOAD
{
    "to": $minumero,
    "type": "template",
    "template": {
        "namespace": "c8ae5f90_307a_ca4c_b8f6_d1e2a2573574",
        "language": {
            "policy": "deterministic",
            "code": "en"
        },
        "name": "first_welcome_messsage",
        "components": [
            {
                "type": "body",
                "parameters": [
                    {
                        "type": "text",
                        "text": $minombre
                    }
                ]
            }
        ]
    }
}
PAYLOAD;


text:
Q: How to upgrade new version of module code by using composer in Magento 2 from third party repository We have installed third party modules successfully using command composer update by Adding below repository to composer.json
"repositories": {
    "0": {
        "type": "composer",
        "url": "https://exampleurl.com"
    },
    "magento": {
        "type": "composer",
        "url": "https://exampleurl.com"
    }
},

Now few of the modules have been updated/edited in the third party repository(https://exampleurl.com).

*

*How can we get those latest module changes into my instance by using composer.

*Running composer update again is suggested ?

Help would be appreciated.


text:
Q: Win2008 DC in a Windows 2000 domain: can I keep the old DC? Will be putting a new Windows 2008 R2 Server into a single domain network with two domain controllers, both running Windows 2000 Server.  The functional level of the domain is mixed mode/2000.
Until a second 2008 DC can be purchased, I'd like to leave the current Win2k operational master DC as a backup DC as the other member servers running 2003 have either accounting/SQL or Exchange on them.  Eventually all the w2k servers will be decommissioned, but until then, I need another DC for redundancy.
Following the standard process for adding a new DC, can I leave the old operational master DC (or the other backup DC) running after I transfer the FSMO roles to the new server?  Will this cause any issues?

A: First make sure that all of your DCS have 2000 sp4, then raise the domain functional level to windows 2000 native. Also ensure that the forest functional level is 2000.  After that you can add the 2008 domain controller (you will need to run adprep/forest prep etc).  You can then transfer the roles to the new server, if you so desire.  There is no need to move the operational roles at all unless they are all on one server.  For guidance on role placement see Planning Operations Master Role Placement and FSMO placement and optimization on Active Directory domain controllers.  You will not have issues with a mixed domain controller environment as long as you do not change the domain functional level.
However- you should verify that any applications are supported with 2008 domain controllers. Up until the beginning of february exchange 2003 was not supported with 2008 domain controllers (see this updated chart for current support)

A: I'm not sure if you can spread from 2000 to 2008 but you can have 2000/2003 and 2003/2008.
You'll have to update the schema on the 2000 machines to match newer features.
Take a look at adprep/forestprep.

A: You can update a windows 2000 schema to windows 2008, without the need to demote existing windows 2000 servers. However you will not be able to take full advantage of the 2008 schema until the forest functional level is raised.
An In-place upgrade should be fine.
(sourced from: http://technet.microsoft.com/en-us/library/cc754209(WS.10).aspx)
I like to recommend you participate in the MS AS Risk Assessment Program prior to a schema upgrade - it's good way to get a health check on your existing AD environment prior to doing something "big".
Hope this helps


text: Q: Smallest algebraic eigenvalues (including negatives) using shift-invert mode Python I'm trying to get the smallest algebraic eigenvalues and vectors for a bunch of different matrices using shift invert mode for speed (in Python using scipy eigsh). This works well for the small positive eigenvalues using the which='LA' criterion, but for small negative eigenvalues, using 'LA' doesn't give me the smallest algebraic eigenvalues, nor does 'LM', since there could be a smaller magnitude but positive eigenvalue that masks the negative one. Is there a mode in eigsh in which I can still use shift-invert yet be able to find these pesky negative eigenvalues, or will I have to resort to just sticking with 'SA' in the usual mode? If only there was an efficient way to determine if a matrix is positive-definite without doing any diagonalization, since that would tell you immediately if there are negative eigenvalues. Thanks.