Use one DataContext.ExecuteCommand to execute query for multiple tables

Question: I need to delete all data from my tables in database. So I use DataContext.ExecuteCommand.
db.ExecuteCommand("DELETE From Products");

This method causes a new request to the database for each table. I want to clear data from my tables in one query. But all my attempts so far were unsuccessful.
Is it possible to use DataContext.ExecuteCommand to delete data from multiple tables (multiple SQL queries)?

        try
        {
            using (var context = new DataContext())
            {
                context.DeleteAll();
            }
        }
        catch (Exception exception)
        {
            LogHelper.Log(exception);
        }

private static void DeleteAll(this DataContext context)
        {
            var ctx = ((IObjectContextAdapter)context).ObjectContext;

            ctx.ExecuteStoreCommand("DELETE FROM [RegionProducts]; DELETE FROM [ProductTypes]; DELETE FROM [Measurements]; DELETE FROM [Sizes]; " +
                                    "DELETE FROM [Regions]; DELETE FROM [Types]; DELETE FROM [Categories]; DELETE FROM [Images] where Product_Id is not null; DELETE FROM [Products]; " +
                                    "DELETE FROM [Brands]; DELETE FROM [Images];");
        }

Answer: That will heavily depend on the actual database system you're using - but in the case of e.g. SQL Server, you should be able to have multiple DELETE statements - separated by a semicolon - like this:
string deleteQuery = "DELETE FROM dbo.Products; DELETE FROM dbo.OtherTable; DELETE FROM dbo.YetAnotherTable;";

db.ExecuteCommand(deleteQuery);

Of course, you need to pay attention to any possible FK relationships that might cause one delete to fail, if other tables still reference its data - but it should be possible to do this in a single db.ExecuteCommand call
Update: unfortunately, in SQL Server Compact Edition v4 that you're using, you cannot have multiple SQL statements in a single command - it is just not supported. This approach works just fine in the real SQL Server - but it will not work in SQL Server CE ...
Comment: about FK - I've found correct way of deleting data from tables when I make `ExecuteCommand` for separate server. I hope it will work in query as in your example?
Comment: Don't know why, but I get error : `There was an error parsing the query. [ Token line number = 1,Token line offset = 31,Token in error = DELETE ]`
Comment: Would be better to use `context.Database.ExecuteSqlCommandAsync` if `context is DataContext` ?
Comment: What **version** and **edition** of SQL Server are you using? Is this SQL Server **CE** (Compact Edition) by any chance??
Comment: **AHHHH!!!!** That explains it (and you didn't ever mention that before - please **do tell us** what system you're using - always - and just "SQL" isn't a product - it's a language - so that doesn't usually help....). Unfortunately, SQL Server **COMPACT** doesn't allow multiple SQL statements in a single command - you cannot delete from all tables in a single command in SQL Server CE (the *real* SQL Server can do this, no problem)


Eclipse Gradle plugin fails to retrieve Gradle distro on fresh Luna install

Question: I'm really getting frustrated with the Gradle and Groovy plugins in Luna.  I first started with STS 3.6.4 and I got to a state where many of the bindings in my Groovy views simply didn't work, and I haven't gotten a single response to any of my postings about this.
I then decided to try a fresh Eclipse Luna install, and then install the Groovy and Gradle plugins over that.  When I finally imported my Groovy projects I saw weird errors along the lines of this:
org.gradle.jvm.tasks.Jar
Could not fetch model of type 'EclipseProject' using Gradle distribution 'https://services.gradle.org/distributions/gradle-2.2.1-bin.zip'.

I know that Eclipse Mars will completely replace this Gradle tooling, I just hope I can survive until then.
The stacktrace in the log is this:
org.gradle.tooling.BuildException: Could not fetch model of type 'EclipseProject' using Gradle distribution 'https://services.gradle.org/distributions/gradle-2.2.1-bin.zip'.

    at org.gradle.tooling.internal.consumer.ResultHandlerAdapter.onFailure(ResultHandlerAdapter.java:57)

    at org.gradle.tooling.internal.consumer.async.DefaultAsyncConsumerActionExecutor$1$1.run(DefaultAsyncConsumerActionExecutor.java:57)

    at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)

    at java.lang.Thread.run(Thread.java:745)

    at org.gradle.tooling.internal.consumer.BlockingResultHandler.getResult(BlockingResultHandler.java:46)

    at org.gradle.tooling.internal.consumer.DefaultModelBuilder.get(DefaultModelBuilder.java:48)

    at org.springsource.ide.eclipse.gradle.core.modelmanager.ToolinApiUtils.buildModel(ToolinApiUtils.java:103)

    at org.springsource.ide.eclipse.gradle.core.modelmanager.DefaultModelBuilder.doBuild(DefaultModelBuilder.java:30)

    at org.springsource.ide.eclipse.gradle.core.modelmanager.AbstractModelBuilder.buildModel(AbstractModelBuilder.java:40)

    at org.springsource.ide.eclipse.gradle.core.modelmanager.HierarchicalProjectBuildStrategy.buildReferenceModel(HierarchicalProjectBuildStrategy.java:179)

    at org.springsource.ide.eclipse.gradle.core.modelmanager.HierarchicalProjectBuildStrategy.buildModels(HierarchicalProjectBuildStrategy.java:65)

    at org.springsource.ide.eclipse.gradle.core.modelmanager.GradleProjectModelManager.getModelInternal(GradleProjectModelManager.java:141)

    at org.springsource.ide.eclipse.gradle.core.modelmanager.GradleProjectModelManager.getModel(GradleProjectModelManager.java:100)

    at org.springsource.ide.eclipse.gradle.core.modelmanager.GradleModelManager.getModel(GradleModelManager.java:77)

    at org.springsource.ide.eclipse.gradle.core.GradleProject.getModel(GradleProject.java:576)

    at org.springsource.ide.eclipse.gradle.core.classpathcontainer.ClassPathModel.getClassPathModel(ClassPathModel.java:66)

    at org.springsource.ide.eclipse.gradle.core.classpathcontainer.GradleClassPathContainer$1.doit(GradleClassPathContainer.java:134)

    at org.springsource.ide.eclipse.gradle.core.util.GradleRunnable$1.run(GradleRunnable.java:53)

    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)

Caused by: org.gradle.internal.exceptions.LocationAwareException: A problem occurred configuring root project 'YangUsingProject'.

    at org.gradle.initialization.DefaultExceptionAnalyser.transform(DefaultExceptionAnalyser.java:77)

    at org.gradle.initialization.MultipleBuildFailuresExceptionAnalyser.transform(MultipleBuildFailuresExceptionAnalyser.java:47)

    at org.gradle.initialization.StackTraceSanitizingExceptionAnalyser.transform(StackTraceSanitizingExceptionAnalyser.java:30)

    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:108)

    at org.gradle.initialization.DefaultGradleLauncher.getBuildAnalysis(DefaultGradleLauncher.java:97)

    at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.configure(InProcessBuildActionExecuter.java:84)

    at org.gradle.tooling.internal.provider.BuildModelAction.run(BuildModelAction.java:45)

    at org.gradle.tooling.internal.provider.BuildModelAction.run(BuildModelAction.java:30)

    at org.gradle.tooling.internal.provider.ConfiguringBuildAction.run(ConfiguringBuildAction.java:119)

    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:36)

    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)

    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:47)

    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:34)

    at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)

    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:35)

    at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)

    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:24)

    at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)

    at org.gradle.launcher.daemon.server.exec.StartStopIfBuildAndStop.execute(StartStopIfBuildAndStop.java:33)

    at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)

    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:71)

    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:69)

    at org.gradle.util.Swapper.swap(Swapper.java:38)

    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:69)

    at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)

    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)

    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:34)

    at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)

    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:70)

    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:34)

    at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)

    at org.gradle.launcher.daemon.server.exec.DaemonHygieneAction.execute(DaemonHygieneAction.java:39)

    at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)

    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:46)

    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:246)

    at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)

Caused by: org.gradle.api.ProjectConfigurationException: A problem occurred configuring root project 'YangUsingProject'.

    at org.gradle.configuration.project.LifecycleProjectEvaluator.addConfigurationFailure(LifecycleProjectEvaluator.java:91)

    at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:86)

    at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:65)

    at org.gradle.api.internal.project.AbstractProject.evaluate(AbstractProject.java:504)

    at org.gradle.api.internal.project.AbstractProject.evaluate(AbstractProject.java:83)

    at org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:42)

    at org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:35)

    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:129)

    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)

    ... 32 more

Caused by: org.gradle.listener.ListenerNotificationException: Failed to notify project evaluation listener.

    at org.gradle.listener.BroadcastDispatch.dispatch(BroadcastDispatch.java:94)

    at org.gradle.listener.BroadcastDispatch.dispatch(BroadcastDispatch.java:31)

    at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)

    at com.sun.proxy.$Proxy12.afterEvaluate(Unknown Source)

    at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:79)

    ... 39 more

Caused by: java.lang.NoClassDefFoundError: org/gradle/jvm/tasks/Jar

    at com.att.opnfv.yang.gradle.YangPlugin$_apply_closure1.doCall(YangPlugin.groovy:51)

    at org.gradle.listener.ClosureBackedMethodInvocationDispatch.dispatch(ClosureBackedMethodInvocationDispatch.java:40)

    at org.gradle.listener.ClosureBackedMethodInvocationDispatch.dispatch(ClosureBackedMethodInvocationDispatch.java:25)

    at org.gradle.listener.BroadcastDispatch.dispatch(BroadcastDispatch.java:83)

    ... 43 more

Caused by: java.lang.ClassNotFoundException: org.gradle.jvm.tasks.Jar

    ... 47 more

Answer: It appears that I've managed to fix this, although I'm not sure exactly what's going on here.
I realized that perhaps this "org.gradle.jvm.tasks.Jar" class may not be in the version of Gradle it's trying to download (2.2.1), but something in the Gradle plugin or my build script expects this to be there.  I do reference that task in my custom Gradle plugin, so perhaps that's the reference that causes a problem.
I finally went into the Gradle preferences to see what version of Gradle it thought it was using, and it only said "Use Gradle Wrapper Default", whatever that is.  I tried changing that property to point to my Gradle 2.3 distribution, and now that error has gone away.


JAVA, NodeList XML get all the children without knowing the content of te XML

Question: I'm working with Vaadin, a Java framework.
I work with XML content and I want to make a tree with this information, but I can't know how long will be the XML content. I send a call to get the XML, but with different IP addresses.
I know how to get the child, and the next child again. But I want to automated this function, like, check how long is the XML and make a loop until the end.
Here my code for now :
private void getData(NodeSet data)
{
    InputStream dataXml = new ByteArrayInputStream(data.toXMLString().getBytes(StandardCharsets.UTF_8));
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try
    {
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document document = builder.parse(dataXml);
        final Element racine = document.getDocumentElement();
        final NodeList racineNoeuds = racine.getChildNodes();
        final int nbRacineNoeuds = racineNoeuds.getLength();

        for (int i = 0; i < nbRacineNoeuds; i++)
        {
                    //System.out.print(nbRacineNoeuds);
            //System.out.print(racineNoeuds);
            if (racineNoeuds.item(i).getNodeType() == Node.ELEMENT_NODE)
            {
                final Element child = (Element) racineNoeuds.item(i);
                final NodeList racineChild = child.getChildNodes();
                final int nbRacineChild = racineChild.getLength();

                for (int y = 0; y < nbRacineChild; y++)
                {
                    if (racineChild.item(y).getNodeType() == Node.ELEMENT_NODE)
                    {
                        final Element child2 = (Element) racineChild.item(y);
                        final NodeList children = child2.getChildNodes();
                        final int nbChildren = children.getLength();

                        for (int a = 0; a < nbChildren; a++)
                        {
                            if (children.item(a).getNodeType() == Node.ELEMENT_NODE)
                            {

                                final Element child3 = (Element) children.item(y);

                            }
                        }
                    }
                }
                        //System.out.print(child);

                //tree.setParent(racineChild, child);
            }
            /*tree.addItem(racine);
             tree.addItem(racineNoeuds);
             tree.setParent(racineNoeuds, racine);
             tree.addItem(child);
             tree.setParent(child, racine);
             tree.addItem(child2);
             tree.setParent(child2, child);
             tree.addItem(child3);
             tree.setParent(child3, child2);*/
        }
    } catch (final ParserConfigurationException e)
    {
        e.printStackTrace();
    } catch (final SAXException e)
    {
        e.printStackTrace();
    } catch (final IOException e)
    {
        e.printStackTrace();
    }

}

Thank you !
Comment: How about using a recursive method to traverse all the children of the children of the children... until there are no more children?
Comment: Yes I was thinking about that, but I don't know how to do. Which element I have to use to make this recursive
Answer: As my answer comes rather late, I guess it's mostly for posterity :)
Indeed, as pointed out by @Morfic, a recursive method might be the simplest thing you can implement to get things done right now.
I've created a tiny project to illustrate a very basic solution. It contains a DataSource class providing some test data and a main Vaadin UI whose content is a Tree being filled in by the recursive method you need.
/**
 * If parentId is null then the element's
 * name or value gets added directly under tree.
 */
private void loadTree(Tree tree, Object parentId, Node element) {
    if (tree == null || element == null) {
        return;
    }

    // 1. We add to the tree what's given to us as argument:

    final String itemId =
        (element.getNodeType() == Node.TEXT_NODE ? element.getNodeValue() : element.getNodeName()).trim();
    if (itemId.length() == 0) {
        return; // skip eventual white spaces...
    }
    tree.addItem(itemId); // a tree item's label defaults to its ID

    // 2. If a parent ID is also provided as argument, we set that as parent for the newly added item

    if (parentId != null) {
        tree.setParent(itemId, parentId);
    }

    // 3. We then _recursively_ add to the tree every child of the given element (if any):

    NodeList children = element.getChildNodes();
    for (int i = 0, n = children.getLength(); i < n; i++) {
        loadTree(tree, itemId, children.item(i));
    }

    // 4. Optionally we can expand an item if it has any children or force hiding the arrow if not:

    if (children.getLength() > 0) {
        tree.expandItem(itemId);
    } else {
        tree.setChildrenAllowed(itemId, false);
    }
}

The method first adds to the provided Tree an item whose label / ID is created based on the Node's content or name. If a parent ID is given as well, we set that as parent for the newly added node. Then, if the given Node has any children, we recursively call the method for each one, providing the ID of the newly created item as parent.
This should do the trick. Having said that, there are things you should (re)consider:

While simple, the recursive implementation might get you in trouble if the XML is (very) large; you might then opt for an iterative implementation of the same method (usually not very difficult to obtain, once the recursive one is provided)
Obviously, upon first call, the parentId argument can / should be left null. Since this tends to make the code harder to understand (usually, a null argument is not very clear), you could overload the method with private void loadTree(Tree tree, Node element) { loadTree(tree, null, element); } in which you hide the ugly argument; just a bit more caller-friendly...
I've obviously used, directly in the UI, the XML DOM model / API -- usually not the best idea (i.e. to couple the app's UI with the low-level model); in a more involved app, we do have better models (domain model, UI model, etc.); as well, one might like to use a HierarchicalContainer
The Tree component does not (yet) have an equivalent in Vaadin 8; therefore, the project only works with versions of Vaadin up to (and not including) 8

Bon courage alors ;)
Comment: Thanx a lot for this answer, this will help me to change what I have done before in a better way !


Rearranging a formula with e in it

Question: $$V_C = V_S\left(1-e^{\left(\frac{-t}{RC}\right)}\right)$$
This is the formula I have to rearrange to find 't'.
This is what I have so far:
$$t = -\ln\left(\frac{V_C}{V_S} + 1\right)RC$$
When I input my numbers into a calculator it comes up whis a math error, if anyone can see what I've done wrong please could you help?
Thanks!
Comment: Check the signs of what are inside of the logarithm.
Answer: It should be
$$t= -\ln\left(1-\frac{V_C}{V_S}\right)RC.$$
The first step is:
$$\frac{V_C}{V_S}=1-e^{-\frac{t}{RC}}$$
so subtracting $\frac{V_C}{V_S}$ and adding $e^{-\frac{t}{RC}}$ to each side gives
$$e^{-\frac{t}{RC}}= 1-\frac{V_C}{V_S}.$$
I think you can continue from here.

Rearranging a formula with e in it


How to: Multilingual site with one front page that makes user choose a language first

Question: I want to have a front page like www.mysite.com/frontpage that shows up for every new visitor and helps him select a language and then move on to whatever language homepage the user selected.
Answer: You can create a custom block to display the language enable into site and a link to respective page of particular language.
To display the custom block in home page, you can use panels, create different template for the home page (page--front.tpl.php).
Answer: Read https://drupal.org/documentation/multilingual
Install https://drupal.org/documentation/multilingual
One configured your site will have /es and /en,  for example. Simply add now a front end ui linking to each one and that's it :-)


Inverting logarithmic output from VAR model

Question: I'm working on a VAR model and am doing a log transformation of the raw data.
x = log(x)

After differencing, running various tests and running a VAR(2) model, I add the predicted differences cumulatively to the original time series (logged) like this:
prd.diffs <- as.ts(prd$mean$d.x1)
U <- tail(undiff,2)
cumu <- cumsum(prd.diffs) + U[1]

However, while the output now looks as it should, it is still in logged values.
My question is as follows:
How does one return the logged output to original values? I'm under the impression that using exp() will not give the correct results, and having tried some variations it hasn't worked for me.
Does the fact that it is a VAR($p$) model (and possibly what lag it has) influence the method, and how should that be implemented to get the correct output?
P.S. I realise that the above code does not constitute a replicable example as I didn't deem that necessary for the question, but should that be desired I can add some more code.
Answer: The actual question seems to be, if one has an optimal (say, in mean-square sense) forecast $\widehat{\log(x)}$ of $\log(x)$, is $e^{\widehat{\log(x)}}$ an optimal forecast of $x$?
The answer is generally no.
Here is Dave Giles' excellent blog post "More on Prediction From Log-Linear Regressions" explaining the issue and suggesting a remedy -- the smearing estimator of Duan (1983) (the details are a little tedious but they are explained very well in the said blog post).
In a special case where the errors in the model for $\log(x)$ are normally distributed, the optimal (in mean-square sense) prediction of $x$ is
$$ \hat x^* = e^{\widehat{\log(x)}} + \frac{\hat\sigma^2}{2} $$
where $\hat\sigma^2$ is an unbiased estimator of error variance from the model for $\log(x)$. However, this result is sensitive to normality and should be used with care.
Now the good news for an applied forecaster: there is some evidence that empirically the simple way of exponentiating the prediction $\widehat{\log(x)}$ may be superior to using the formula given above for the case of Normal errors -- once specification and estimation uncertainty are taken into account; see Bårdsen & Lütkepohl (2011).
References

Duan, N., 1983. Smearing estimate: A nonparametric retransformation method. Journal of the American Statistical Association, 78, 605-610.
Bårdsen, G., and H. Lütkepohl, 2011. Forecasting levels of log variables in vector autoregressions. International Journal of Forecasting, 27, 1108-1115.
Comment: Thanks very much for this! A naive forecast seems to fit pretty well.
Comment: You are welcome! I was happy to find the article by Bårdsen and Lütkepohl myself since it provides some consolation for choosing the simple solution and saves some coding time.


Using variables with JSON with Python Requests

Question: I'm trying to use requests to send JSON using variables to an API. When hard coded it works fine (I.E. "videos" : "30" , or "views" : "100") but now that I replaced it with variables the server responds with:

{u'message': u"'vars' parameter is not a valid JSON"}

Here is my code:
return requests.post(
    "https://api.website.com",
    auth=('api', 'XXXXXXXXXXXXX'),
    data={'subscribed': True,
          'address': email,
          'name': username,
          'description': profile,
          'vars': '{"logo" : logo , "status" : status , "videos": videos , "views": views , "likes": likes}'  })

Comment: It's because you didn't really replace it with variables, they're still strings. the `logo` inside the string is just the character sequence 'logo' not a reference to your variable.
Answer: Don't produce json manually. Use the built in json module.
import json
data={'subscribed': True,
      'address': email,
      'name': username,
      'description': profile,
      'vars': json.dumps({"logo" : logo , "status" : status , "videos": videos , "views": views , "likes": likes})  })


Data Conversion in SQL Server 2008

Question: I need to concatenate 2 columns and show as a single field in my stored procedure.
Column Batch - int
Column AdmissionNo - nvarchar

I tried querying like so
select (a.AdmissionNo + ' - ' + a.BatchID) as RollNo

But I get the following error

Msg 245, Level 16, State 1, Procedure usp_GetAdmittedStudents, Line 7
  Conversion failed when converting the nvarchar value '13-01 - ' to data type int.

What am I missing?
Answer: Both column datatypes must be same or casted to same type.
select (a.AdmissionNo + ' - ' + CAST(a.BatchID as nvarchar) ) as RollNo

Note :
All int datatype values can be casted to varchar / nvarchar but not vice versa.
So its safer to CAST int column to varchar/nvarchar
Comment: could you please elaborate? I am kind of new to SQL.
Comment: check now , i am assuming batchID is of type int

Data Conversion in SQL Server 2008


Joke list question got to Hot Network Questions but looks like it should be closed

Question: Jokes in Economics; Challenging Assumptions in the Dismal Science

This question, if asked on any other site on StackExchange that I participate in, ("what are some good programming jokes", etc), would get downvoted and closed so hard. But here, it has gotten upvotes and is apparently being tolerated.
Since this completely throws my idea of this site's scope off the rails, would anyone be willing to enlighten me on why this question is on-topic here?

The reason I think it would get closed quickly on another SE site is that the question, as is:

Invites subjective answers
Contradicts the help center guidelines: https://economics.stackexchange.com/help/dont-ask says you should avoid avoid asking subjective questions where "every answer is equally valid" and that questions should be "more than just mindless social fun"
The asker is not looking for understanding of something
The asker is looking for jokes (technically speaking, this would be "product recommendation" of sorts, most sites don't allow this, some do, but nearly all of them require that you state your requirements, so that answers will be usable from the perspective of "this is what I was looking for")
It looks like a "boat programming" question, where you slap "programming" (or, in this case, "economics") onto the question so that it is on-topic, where-as the version of the question without the applied label would be off-topic without a doubt.

I do not have an isse with the fact that this is a list-question, as there are great questions available in that format, primarily historical, "what were the reasons that led to X happening" is secretly a list question but can be explained quite in an answer.
It might have been on-topic on Humor if that goes into beta.
Comment: I think that because this site is less mature than something like S.O., and because the community here is less well-developed it takes longer to reach consensus on what is and is not on topic (that's a big part of what this beta is about). This question may yet end up being closed.
Comment: @Ubiquitous I do **not** have a problem with list-questions. My issue is with the jokes themselves - it reads like boat programming, and without well-defined criteria, that's likely to devolve in everybody just posting their own opinion, which is harmful to a site that wants to build reputation as a place where you can get expert factual information.
Comment: I am still not sure I get what your exact problem is. Bad jokes will just slap the word economics in there but good jokes will incorporate economic logic. Any question can have bad answers. I think your other point, that the aim of the OP is not the understanding a specific thing is much better.
Comment: But I don't think we should have a *per se* prohibition on list questions because there are some great examples of such questions around the network. One of my favorites is http://tex.stackexchange.com/questions/339/latex-editors-ides The challenge is ensuring the question is sufficiently well-curated and are on a topic where an exhaustive list is really valuable.
Comment: @denesp I'll try editing the question so it lists each reason separately
Comment: Did you make an Econ SE account 2 days ago just to make a case against my post lmao??? Well I'll be editing it shortly with some of the suggestions from here to improve it.
Comment: @KitsuneCavalry Does it matter if I did?
Comment: Well it means you must've been pretty revolted at the audacity of my question. ¯\_(ツ)_/¯
Answer: Other Stack Exchange sites have tried these joke questions. In almost all cases, they've turned out to be a bad idea. They're junk magnets.
They do not incentivise new high-quality content.
They do, however, incentivise jokey rubbish. This becomes a self-reinforcing cycle, where more jokey junk gets posted, attracting more jokey junk.
This particular question is problematic for several reasons. It's not about economic theory or applications, so is explicitly off-topic. It's a big-list  question, so there's no single right answer, thus working against the whole structure of the site. And as per above, it's a junk magnet.
And so it should be deleted.
Comment: So? What course of action do you recommend?
Comment: I agree, close vote for off-topic reasons. Just because something is within the the fields of economics, doesn't mean it's on-topic regarding the science of economics.
Comment: You ought to add your course of action to the answer
Comment: (+1) These are good, pragmatic points.
Answer: Because humour may be a very effective way to convey the core essence of something.
What is probably missing from the answers already posted, is an explanation, or a hint, on what "core essence" does each "joke" allude to, just to make sure that everybody will get it.
"Get downvoted and closed so hard" in other sites- why? What's so unhelpful, un-educational and unscientific about humour?
Comment: @Pimgd That is a different issue from the one you raised in your question, which was about principle, not delivery.
Comment: explained in question
Comment: Aside from question explanation, whilst your point is valid, the question as is right now is bad and warrants closing. It's unhelpful in that the question doesn't have a purpose other than "fun" at the moment.
Comment: I strongly agree with Alecos and therefore voted to reopen the question. A joke collection could be very useful for researchers and teachers for presentations/teaching purposes.
Answer: I find the argument that

Jokes in Economics; Challenging Assumptions in the Dismal Science

is problematic to be persuasive, mostly because this question is opinion-based.
I think the question is salvageable if

it is edited to have a more specific and less opinion-based criterion by which answers might be assessed. One approach, for example, would be to ask "what jokes can be used to make important ideas in economics clear and easy to understand?" (along the lines suggested by Alecos Papadopoulos);
we impose a bit more structure on the formatting (perhaps along the lines described here). In particular, one joke per answer and consistent formatting across all answers will make the list more navigable and useful to future visitors of the site.
Comment: Criteria fixes point 1 and 2. The example approach fixes point 3. Criteria again fixes point 4... and point 5 is likely to go away once the question reads more like a search for material rather than a bored person looking for amusement.
Comment: removed accept because I thought there was consensus, but apparently not, will check later today


Commutator subgroup of $S_n$ generated by commutators of transpositions

Question: Is it true that the commutator group $[S_n, S_n]$ is generated by elements of the form $[\tau_1, \tau_2]$ for $\tau_1, \tau_2$ transpositions?
I know that in general, when a group $G$ is generated by a set $S$, then one has to take the normal closure of the group generated by commutators of elements in $S$ to obtain $[G,G]$.
Comment: Yes, because $A_n$ is generated by $3$-cycles, and $(1,2,3) = [(1,2),(2,3)]$ (or possibly $[(2,3),(1,2)]$, depending on your convention).
Answer: Every element of $S_n$ is a product of transpositions.
I use the definition $[x,y]=x^{-1}y^{-1}xy$; if you use the other convention, the identities below need to be tweaked, but they are essentially the same.
Now notice that
$$\begin{align*}
[xy,z] &= [x,z]^y[y,z] = [x^y,z^y][y,z]\\
[x,yz] &= [x,z][x,y]^z = [x,z][x^z,y^z].
\end{align*}$$
Since the conjugate of transposition is a transposition, this allows you to decompose any commutator into a product of commutators of transpositions.
Note that this does not require you to know that the commutator subgroup is $A_n$, or how $A_n$ can be generated, just that every element of $S_n$ is a product of transpositions, and that the conjugate of a transposition is a transposition.
Answer: The commutator of $(1,3)$ and $(2,3)$ is $(1,2)(2,3)=(1,2,3)$, so any $3$ cycle is a commutator of two transpositions.
For $S_3$ we are done.
Now for $n\geq 4$, it is know that every prouct of an even number of transposition (an alternate permutation) is a product of 3 cycle.
Indeed if the two transpositions have disjoint support $(12)(34)= (123)(234)$, and if not $(12)(23)=(123)$
Now it is known that the derived group of $S_n, n\geq 4$  (the alternate group) is generated by the 3-cycles.
So any product of an even number of transposition is a product of 3 cycles, and a product of commutator of transposition. But the derived group of $S_n$ is the kernel of the signature, so the set of permutation which are the product of an even number of transposition..


struggling with linux permissions (again)

Question: I have a script on my Centos server that is supposed to delete newly created log files. It contains the following:
cd /var/log/kloxo
rm maillog-* courier-* pureftp.log-* smtp.log-*

.. this script has the following ownership / permissions:
-bash-3.2# ls -l /home/admin/cronscripts/logDeleteCronJob.sh
-rwxr-xr-x 1 root root 79 Jan 16 12:26 /home/admin/cronscripts/logDeleteCronJob.sh

.. the target folder looks like this:
drwxr-xr-x 2 root     root        4096 Jan 20 03:39 kloxo

.. and the folder contents look like this (these permissions are automatically set by the server when the log files are created):
-bash-3.2# ls -l /var/log/kloxo/
total 562064
-rw-r--r-- 1 root root 127423120 Jan 20 08:57 courier
-rw-r--r-- 1 root root 127145668 Jan 19 03:42 courier-1
-rw-r--r-- 1 root root 127375976 Jan 20 03:39 courier-2
-rw------- 1 root root  49875972 Jan 20 08:55 maillog
-rw------- 1 root root  49699233 Jan 19 03:42 maillog-1
-rw------- 1 root root  49857831 Jan 20 03:38 maillog-2
-rw------- 1 root root   7925642 Jan 20 08:58 pureftpd.log
-rw-rw-r-- 1 root root  11889944 Jan 20 08:57 smtp.log
-rw-r--r-- 1 root root  11842503 Jan 19 03:42 smtp.log-1
-rw-r--r-- 1 root root  11884360 Jan 20 03:39 smtp.log-2

The problem is that the script executes on schedule but fails to delete the files and I receive the following email from the cron daemon:
rm: cannot remove `maillog-1': Permission denied
rm: cannot remove `courier-1': Permission denied
rm: cannot remove `pureftp.log-*': No such file or directory
rm: cannot remove `smtp.log-1': Permission denied

Please could someone show me how to do this properly. Thanks
Comment: Wich user is the cron running as, root? If so, please paste the output from "crontab -l -u root"
Comment: How do I know which user cron is running as?
Comment: I found it! The cron user is 'admin' and the crontab is: 0       0       *       *       *       /home/admin/cronscripts/logDeleteCronJob.sh
Comment: [Administration panels are off topic](http://serverfault.com/help/on-topic). [Even the presence of an administration panel on a system,](http://meta.serverfault.com/q/6538/118258) because they [take over the systems in strange and non-standard ways, making it difficult or even impossible for actual system administrators to manage the servers normally](http://meta.serverfault.com/a/3924/118258), and tend to indicate low-quality questions from *users* with insufficient knowledge for this site.
Answer: You're running the cron script as the user "admin", while the file system permission only permits root to write files.
Either run the cron job as root, or chown+chmod all the files/folders so that admin can write/delete/etc.
Comment: Thanks. The log files are autoatically created by the server with root ownership and 600 permissions and I've no idea how to change that - I imagine I would have to edit the config for each of these services which sounds complex. The cron job is created by the Kloxo server panel which runs under admin user. How do I change it so it runs under root user?
Comment: Remove the cron job from user admin, and insert it to root user. (crontab -e -u admin, cut out the lines, crontab -e -u root, insert the lines)
Comment: That makes sense. I just did what you suggested and will find out if it works tonight at midnight when the job is scheduled to run...
Answer: The scipt permissions does not matter here as long as it is executeable. What matters is the user the script executed as.
Show the cron job entry. It this a user cronjob or a systemwide one?
Answer: If you look at the permissions of the files your scripts is failing to delete you'll see that they're 600 for user root, which means that root and only root can delete those files.
Either fix the permissions or run your script as root instead of using the admin user, that'll do the job


Change text between tags in HTML document

Question: Basically I was wondering if anybody knows how to make Visual Basic change automatically what is in
1

change what is between > and <  (for example a digit or text).
How can I do that?
Comment: You mean VB.NET (with ASP.NET) or vbscript (with ASP) or some other environment?
Comment: I've rewritten the post to be more readable. However, I *still* have no idea what exactly you want to achieve, and where your problem is. You need to provide way more details: How is the input provided? How does it look like? How does the output happen? What have you tried? Where have you got problems?
Comment: ok so i have 1, i want to change what ever is in the >and< in visual basic, so when ever a webpage loads it looks up the id which i know and changes the number or text between >and<
Comment: i also been Visual basic 2010 Express
Comment: It sounds like you want a server-side process to look up a product id in a database and put a value into that `` element. But you haven't given any of that context.
Comment: what do i need to give, i just want to change whatever is in the >"<      meaning a number or a digit, where i have put the number 1 right now. if that make sense
Comment: Are you trying to change code that has already been rendered on the page?
Comment: um, basically it is a drop down box, which you can select on a web page and then it sends it to a textbox, it looks like this       http://imageshack.us/photo/my-images/577/screenshot20120623at154.png/
Comment: i have this code which selects from the dropdown box                       If TextBox1.Text = ("weburl") Then
WebBrowser1.Document.GetElementById("price_category").SetAttribute("value", "4")
End If                                                                  by i am trying to edit the textbox on the site because when the code selects it from the drop-down it doesn't change the text box this is what i am trying to do in vb
Comment: I recommend using javascript to do any modification on the page after it has been rendered.  Jquery has a few solutions for things like this.

http://api.jquery.com/change/
http://api.jquery.com/replaceWith/
Comment: so, um what is this for changing the drop down or...
Answer: If you have many tasks that involve manipulating HTML, I would recommend HTML Agility Pack


Removing the breadcrumb from frontpage

Question: I'd like to remove the breadcrumb from the frontpage and haven't been able to find a solution in the configuration settings of the theme or custom breadcrumbs. So I am thinking of modifying the page.tpl.php
Do you see a problem with this?
Replace:
<?php print $breadcrumb; ?>

With:
<?php if ($_GET["q"] == variable_get("site_frontpage",
"node")){}
else if ($breadcrumb) {print $breadcrumb;} ?>

Answer: You don't have to do it the hard way. There is a variable (bool) $is_front that you can use in this case.
<?php if (!$is_front && $breadcrumb) {
  print $breadcrumb;
}
?>

You can read more about page.tpl.php variables here.
Comment: There is also a function [drupal_is_front_page()](http://api.drupal.org/api/drupal/includes!path.inc/function/drupal_is_front_page/7).

Removing the breadcrumb from frontpage


Doctrine 2 Concurrency issues

Question: I'm writing unit tests for a Symfony 2 / Doctrine 2 application and I'm encountering what looks like a concurrency issue.
The code looks like this:
$obj = new Obj();
$obj->setName('test');

... etc ...

$em->persist($obj);
$em->flush();

...

$qb = $em->getRepository('Obj');
// Select object using DQL

$this->assertTrue($obj !== null);

At this point $obj is often null. I.e. the DQL query has failed to find it. If I add breakpoint and pause execution somewhere before executing the DQL, $obj is always found. If not it's usually not found but occasionally it is found.
I have tried wrapping the insertion in a transaction:
$em->getConnection()->beginTransaction();

$obj = new Obj();
$obj->setName('test');

... etc ...

$em->persist($obj);
$em->flush();

$em->getConnection()->commit();

This doesn't seem to help.
I have tried adding a pause between the insert and the DQL query:
sleep(1);

This results in the expected behaviour consistently. Thus my conclusion that this is a concurrency issue. Or at least something to do with Doctrine not immediately writing through on flush.
Is there any way with Doctrine 2 to force a write to the database to complete? Or an event to listen for? Or am I doing something else wrong here?
Comment: Enable query log for your database server and see how queries are emitted. For what you observe to be a concurrency problem you must have 2 connections that run concurrently. The first is possible but unlikely, the second is impossible in php (by default).
Comment: You better post the answer with explanation of the problem
Comment: It looks like concurrency isn't the problem after all. I found a time dependent error that was causing my inconsistent results. If you want to add your comment about logging as an answer I'll mark that as the answer since I found my bug straight away having followed your advice.
Comment: I've posted an answer, but I was wanting to give you the reputation points... thanks for the tip.
Answer: Having followed zerkms' advice to enable logging I quickly tracked the problem down to a fault in my own code. There was no concurrency issue.
On my Mac I did the following:
Edit: /usr/local/etc/my.cnf
Add these lines:
general_log_file = /tmp/query.log
general_log      = 1

Then:
brew services restart apache2

Next I tailed the file:
tail -f /tmp/query.log

I saw the two queries - an insert and a select - executing in the right order. Running those queries directly in MySQL client revealed the error in my code.
Note: putting the log into /tmp/ ensures the logs are deleted everytime I log out.

Doctrine 2 Concurrency issues


Sorting Complex object Structure with values using JavaScript

Question: I have a complex object which looks like below.

{
  "PartNumber": "A123456",
  "Components": [{
      "Part": {
        "Number": "123"
      },
      "Components": []
    },
    {
      "Part": {

        "Number": "300"
      },
      "Components": [{
          "Part": {
            "Number": "444"
          },
          "Components": [{
              "Part": {
                "Number": "A123"
              },
              "Components": [{
                "Part": {

                  "Number": "1234"
                }
              }]
            },
            {
              "Part": {
                "Number": "443"
              },
              "Components": []
            }
          ]
        },
        {
          "Part": {
            "Number": "H123"
          },
          "Components": []
        }
      ]
    },
    {
      "Part": {
        "Number": "120"
      },
      "Components": []
    }
  ]
}

I am trying to Sort the object using the values of Number key. I have tried using different sort functions and those were not working for my complex object.
Can someone help in achieving the sort of Complex objectusing JavaScript?
The object when simplified will be like
A123456
    123
    300
        444
            A123
                1234
            443
        H123
    120

I need to sort the object and the expected simplified object output will be
A123456
    120
    123
    300
        444
            443
            A123
                1234
        H123

Comment: Welcome to Stack Overflow! Visit the [help], take the [tour] to see what and [ask]. Please first ***>>>[Search for related topics on SO](https://www.google.com/search?q=javascript+sort+nested+object+value+site%3Astackoverflow.com)<<<*** and  if you get stuck, post a [mcve] of your attempt, noting input and expected output using the [`[<>]`](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. I made you such a snippet. Please add the script you tried
Comment: [There is no such thing as a JSON](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/)
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: const sortedComponents = Components.sort(
  (component1, component2) => component1.Part.Number - component2.Part.Number
);

I think this solves your problem.
Comment: Please provide additional details in your answer. As it's currently written, it's hard to understand your solution.


How do I create a recursive function below?

Question: So each person is represented as a tuple. The first element of the tuple is this person's name. The second element of
the tuple is a list that contains this person's children. Each child is represented as a tuple itself. If a person has no
child, the list of his/her children is empty.
For example, if Mary has no child, she is represented as
 ('Mary', [])

If Jane has two children named Nick and Wendy, and neither Nick nor Wendy has any child, then Jane is represented
('Jane', [('Nick', []), ('Wendy', [])])

If Mary and Jane are Frank's children, and Jon is Mary's child, while Nick and Wendy are Jane's children, then Frank is represented as
('Frank', [('Mary', [('Jon', [])]), ('Jane', [('Nick', []), ('Wendy', [])])])

Thus, how do I write a function that will return a list of members in the family in a hierarchal order? For example
get_family_members(('Mary', []))
['Mary']

get_family_members(('Jane', [('Nick', []), ('Wendy', [])]))
['Jane', 'Nick', 'Wendy']

get_family_members(('Frank', [('Mary', [('Jon', [])]), ('Jane', [('Nick', []), ('Wendy', [])])]))
['Frank', 'Mary', 'Jane', 'Jon', 'Nick', 'Wendy',]

My attempt:
def get_family_members(fam_list):

    result = []

    if type(fam_list) != list:
        fam_list = [fam_list]

    for i in range(len(fam_list)):

        result.append(fam_list[i][0])

    for i in range(len(fam_list)):

        if fam_list[i][1] != []:

            li = get_family_members(fam_list[i][1])
            result += li

    return result

Comment: It's just BFS, right? So a loop over a queue.
Comment: Why a *recursive* function? That makes no sense. And where is your attempt?
Comment: Does [Given a flat list of (parent,child), create a hierarchical dictionary tree [closed]
](https://stackoverflow.com/questions/45460653/given-a-flat-list-of-parent-child-create-a-hierarchical-dictionary-tree) answer your question?
Comment: @itprorh66 How? That's completely different.
Comment: Just uploaded my attempt. If not recursive function, then what do you recommend?
Comment: I'm a newbie so forgive me
Answer: Your desired output is BFS order, for which a recursive function is inappropriate. So here's a non-recursive one:
def get_family_members(person):
    queue = [person]
    return [queue.extend(children) or name
            for name, children in queue]

Less hacky non-listcomp version:
def get_family_members(person):
    names = []
    queue = [person]
    for name, children in queue:
        names.append(name)
        queue += children
    return names

Iterator version:
def iter_family_members(person):
    queue = [person]
    for name, children in queue:
        yield name
        queue += children

def get_family_members(person):
    return list(iter_family_members(person))

Or with a proper queue:
from collections import deque

def iter_family_members(person):
    queue = deque([person])
    while queue:
        name, children = queue.popleft()
        yield name
        queue += children


How many ways to colorize the table

Question: Each cell of a square table of 3 × 3 can be painted black, white or red. How many different colorings of this table? If we do not consider the turnings of the board, we get $3^9$ variants. How many variants of coloring will be, if you consider the possibility of turning the board?
I can sort through all the options for a 2 × 2 table and two colors (16 variants without rotation and 6 variants with turns), but for 3 × 3 variants too much.
Answer: The formula is Burnside's Lemma. You take a group, in this case the group of rotations of a square: $0, 90, 180, 270$ degree rotations, and look at which colourings are fixed by each rotation. The formula is

$$ \frac{1}{\text{size of group}}\left( \text{colourings fixed by the first group element} + \text{colourings fixed by the second group element} + \cdots \right) $$

In this case

$3^9$ colourings are fixed by a $0$ degree rotation
$3^3$ colourings are fixed by a $90$ or $270$ degree rotation (such colourings are determined by how the top-left, top-centre and centre squares are coloured)
$3^5$ colourings are fixed by a $180$ degree rotation (determined by the top three squares and the centre-left and centre squares)

Applying Burnside's Lemma, there are
$$ \frac14 \left( 3^9 + 2 \cdot 3^3 + 3^5 \right) = 4995 $$
distinct colourings.
Comment: Page 30 of lecture note http://www.ist.tugraz.at/aichholzer/teaching/eca/eca2017.pdf helped me to understand your answer.
Answer: If you are interested in the number of "essentially different" colorings, then you may want to note that in the $2 \times 2$ table with two colors considering rotations is enough, but in general, there are 8 symmetries of the square.
Besides the rotations by multiples of 90 degrees, there are four "flips:" horizontal, vertical, and along the two main diagonals. The method described by @TrevorGunn still applies, but you also need to compute the number of colorings that are fixed under each flip, which turns out to be $3^6$ for each flip.  All in all,
$$ \frac{3^9 + 2 \cdot 3^3 + 3^5 + 4 \cdot 3^6}{8} = 2862 \enspace. $$
For the $2 \times 2$ table with two colors, there are $2^2$ colorings fixed under horizontal and vertical flips, and $2^3$ colorings that are fixed under diagonal flips.  Compared to rotations only, the four flips double both numerator and denominator, leaving the final number of colorings unchanged:
$$ \frac{2^4 + 2 \cdot 2^1 + 2^2 + 2 \cdot 2^2 + 2 \cdot 2^3}{8} = 6 \enspace. $$
Finally, note that you cannot apply Burnside's lemma to flips only, because, unlike rotations, they do not form a group (they are not closed under composition).

How many ways to colorize the table


what actually compiler does when we declare variable?

Question: let have an example.
public class test {
  public static void main(String args[]) {
    int a=5,b=4;
    int c=a+b;
    int d=9;
    System.out.println("ANSWER PLEASE..");
  }
}

Now when we execute this code what os does?
It first create a variable named a and alocates a memory address similar things for b and c.
now what happen to d. os creates a new memory address or it just reffer to the address of c as the value is same.
Comment: Comment rather than an answer because I'm just guessing: In this specific example the compiler (javac?, version?) can reason that all variables will remain unread and therefore erase them. The resulting bytecode would be exactly as if you never declared any ints at all. I look forward to the answer.
Answer: First of all, the compiler doesn't do much. It basically translates it into class-files / bytecode. In the bytecode there is a number called "max locals" which tells how many local variables are required to run the method.
The JVM on the other hand, which reads this information and runs the code makes sure memory is allocated on the stack frame to fit the required variables. How much it asks for is highly implementation dependent, and it may very well optimize the whole thing, and allocate fewer bytes than what's indicated by the code.
Comment: Isn't the stack space for threads pre-allocated (at the latest when the stack is created), and does not grow after that?
Comment: If we write it in C then does the c compiler allocates some memory for each int?
Comment: Depends on the compiler (and probably the optimization level you set). That's quite easy to find out using a disassembler though.
Comment: @Thilo, that's probably true actually... was a while ago I read up on this. Updated.
Comment: @Thilo if we print the value of all variables what happens to d it will create a new memory address or it just refer to c?
Comment: @ManishSasmal, it depends on which compiler / JVM you're using.
Comment: @aioobe well if i use jdk 1.6 then what happen and what happen to the latest version?? plz explain. thnks
Answer:
what happen to d. os creates a new memory address or it just reffer to the address of c as the value is same.

This is tagged Java. So let's keep the OS out of it. Everything happens in memory managed by the JVM, which is allocated in big chunks in advance.
You are talking about primitive data types. Those are easy, as they are stored by value, not as references to objects living elsewhere.
You are talking about local variables. Those are allocated on the running thread's call stack (not in heap memory). Since they are primitive here, too, this does not involve the heap at all.
In your case, there is memory allocated (on the stack), for the four integers. Each of them contains the value assigned to it, not a reference. Even if the same value is assigned to all of them, they exist separately. The memory is "freed" (not really freed, but no longer used by the thread) when the method returns.
If those were not integers, but Objects, you could "share pointers" (to objects on the heap), but integers are stored by value (four bytes each).
Comment: thank you. now i can understand. primitive data type are stored by value and objets such as String types are stored as object reference. right?
Comment: Yes. For a String, you would have an object on the heap in addition to the variable storing the pointer to that object. You can have all four String variables pointing to the same object on the heap.


Theming CCK field

Question: I want to alter CCK field in theme layer so I use Theme Developer to find candidate function for this:
template.php:
function omega_starterkit_email_formatter_contact($element) {
    firep($element, 'element');
    return $element;
}

firep gives me this output:
Array
(
    [#formatter] => contact
    [#node] => stdClass Object
        (
            [nid] => 15
            [type] => opiekun
            [language] =>
            [uid] => 0
            [status] => 1
            [created] => 1306400895
            [changed] => 1307955137
            [comment] => 0
            [promote] => 0
            [moderate] => 0
            [sticky] => 0
            [tnid] => 0
            [translate] => 0
            [vid] => 15
            [revision_uid] => 1
            [title] => Magna Volutpat
            [body] =>
            [teaser] =>
            [log] =>
            [revision_timestamp] => 1307955137
            [format] => 0
            [name] =>
            [picture] =>
            [data] =>
            [path] => opiekun/magna-volutpat
            [field_phone] => Array
                (
                    [0] => Array
                        (
                            [value] => vKaqmxdNJZAALXErcWBi2qkKcZZneTVXNjmye6LBoe6zccGDFj
                            [safe] => vKaqmxdNJZAALXErcWBi2qkKcZZneTVXNjmye6LBoe6zccGDFj
                        )

                )

            [field_email] => Array
                (
                    [0] => Array
                        (
                            [email] => email
                            [safe] => email
                        )

                )

            [taxonomy] => Array
                (
                )

            [referencing_node] => stdClass Object
                (
                    [nid] => 385
                    [type] => page
                    [language] => pl
                    [uid] => 0
                    [status] => 1
                    [created] => 1307101436
                    [changed] => 1307362258
                    [comment] => 0
                    [promote] => 0
                    [moderate] => 0
                    [sticky] => 0
                    [tnid] => 0
                    [translate] => 0
                    [vid] => 385
                    [revision_uid] => 1
                    [title] => Maszyny
                    [body] =>
                    [teaser] =>
                    [log] =>
                    [revision_timestamp] => 1307362258
                    [format] => 1
                    [name] =>
                    [picture] =>
                    [data] =>
                    [path] => maszyny
                    [field_opiekun] => Array
                        (
                            [0] => Array
                                (
                                    [nid] => 15
                                    [safe] => Array
                                        (
                                            [nid] => 15
                                            [title] => Magna Volutpat
                                            [status] => 1
                                        )

                                )

                        )

                    [field_photos] => Array
                        (
                            [0] =>
                        )

                    [taxonomy] => Array
                        (
                        )

                    [files] => Array
                        (
                        )

                    [build_mode] => 0
                    [readmore] =>
                    [content] => Array
                        (
                            [field_opiekun] => Array
                                (
                                    [#type_name] => page
                                    [#context] => full
                                    [#field_name] => field_opiekun
                                    [#post_render] => Array
                                        (
                                            [0] => content_field_wrapper_post_render
                                        )

                                    [#weight] => -4
                                    [field] => Array
                                        (
                                            [#description] =>
                                            [items] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [#formatter] => full
                                                            [#node] => stdClass Object
 *RECURSION*

Before this function I display link to e-mail contact form page.
All I want to do with this link is change label from 'Email Contact Form' to something different.
Comment: Which function is `firep()`?
Comment: This is debug from Drupal for Firebug module
Answer: There are generally two ways of controlling the output of a field.

Create a field formatter in a module which you can then activate for the field of the type it's made for.
Overwrite the theming function that the field formatter uses to render the output.

It seems like you are trying to do #2, but what you have posted doesn't look like a theming function. Are you sure you have named it correctly, have you cleared cache? If you name your theme function correctly and clear the theme cache, it will always take precedence, if done in your site's theme.
Answer: Content Template or Custom Formatters

Theming CCK field


Erro "Illegal string offset" ao chamar usort em dados do banco

Question: Estou tentando ordenar o resultado por uma coluna específica de uma array de dados do banco.
 function cmp($a, $b) {
 return strcmp($a['usu_codigo'], $b['usu_codigo']);
  };

usort($usu_info_coluna, "cmp");

Dando um var_dump em $usu_info_Coluna, ele retorna:
array(21) { ["usu_codigo"]=> int(1) ["usu_nome"]=> string(5) "LUANN" ["usu_senha"]=> string(60) "$2y$10$I4RqdKD/cOwRDNpFgtIbWeVirNIfxHPREMEklGaBuONGRZMtQfUgq" ["usu_sobrenome"]=> string(5) "SOUSA" ["usu_cpf"]=> string(11) "12345678998" ["usu_rg"]=> string(9) "123456789" ["usu_nasc"]=> string(10) "2018-10-22" ["usu_endereco"]=> string(4) "AV 2" ["usu_numero"]=> string(2) "97" ["usu_bairro"]=> string(8) "BLOCO D2" ["usu_cep"]=> string(8) "11900000" ["usu_cidade"]=> string(11) "REGISTRO-SP" ["usu_uf"]=> string(2) "SP" ["usu_tel"]=> string(10) "1338226293" ["usu_cel"]=> string(11) "13997821923" ["usu_genero"]=> string(9) "Masculino" ["usu_situacao"]=> string(5) "ativo" ["usu_email"]=> string(22) "firstname.lastname@example.com" ["usu_indicador_codigo"]=> NULL ["usu_datacadastro"]=> string(10) "2018-10-22" ["usu_nivel"]=> string(3) "adm" }

No que eu errei usando o usort? Mudei e mudei o código do usort, mas sempre me retorna um erro diferente, e acredito que isso foi o mais próximo que cheguei.
UPDATE 0:
Essa é a query preparada que utilizo para a consulta:
$_SESSION['codigo'] = 1;
$usu_codigo = $_SESSION['codigo'];
$usu_situacao = 'ativo';

$stmt3 = $conexao->prepare('SELECT * FROM esc_usuarios WHERE usu_indicador_codigo = ?');
$stmt3->bind_param('i', $usu_codigo);
$stmt3->execute();
$usu_ult5_cad = $stmt3->get_result();

Exibindo através de uma tabela:
<?php

$limit = 2;
while($limit -- && $coluna_ult5 = $usu_ult5_cad->fetch_array()){

    ?>

      <?php echo $coluna_ult5['usu_codigo']; ?>

      <?php echo $coluna_ult5['usu_nome']; ?>
      <?php echo $coluna_ult5['usu_sobrenome']; ?>

<?php }

?>
Answer: O primeiro passo de tudo é tentar traduzir o erro para saber do que se trata.
Illegal string offset é retornado quando você tenta obter um offset de uma string, passando uma string por parâmetro.
Veja:
$a = 'wallace';

var_dump($a[0]); // string 'w'

var_dump($a['string']); // Erro: Illegal string offset 'string' on line 1

Veja o teste no ideone.
Isso é porque o operador [] funciona tanto para array, como para string em PHP. No caso da string você consegue obter o caractere de acordo com a posição passada.
Porém, se você passar uma string, isso gera um erro. Isso é algo que o PHP permite para strings e poucas pessoas sabem.
O que está acontecendo dentro da sua função é basicamente isso.
Quando você passa o seu array para usort, ele vai pegar os itens do seu array de 2 e 2 e passá-los por parâmetro do callback de usort.
Exemplificando o caso do seu array, ele está assim:
  ['a' => 1, 'b' => 2, 'c' => 3]

Se você passar esse array para usort, o callback colocaria 1 em $a e 2 em $b.
E por isso está dando erro Illegal string offset. Pois você assumiu que dentro do callback estava passando um array, mas na verdade está passando strings ou inteiros.
Para poder dar certo do jeito que está tentando fazer, o seu array deveria estar assim:
  [
        ['usu_codigo' => 1, /** resto do array **/],
        ['usu_codigo'   => 2, /** resto do array **/],
        ['usu_codigo'   => 3, /** resto do array **/],
  ]

Veja um exemplo no ideone
Comment: Só que essa ordenação do array vai fazer com que eu tenha que alterar a query original?
Comment: Depende. Qual é a query original? Se achar viável, edite sua pergunta e coloque ela  lá, pra eu dar uma analisada
Comment: O que eu realmente quero fazer é filtrar os resultados da tabela, por exemplo, limitar a 2 registros (tudo ok) e ordenar por ordem crescente/decrescente por uma coluna, "usu_codigo" por exemplo. Não quero ordenar pela query utilizando um order by porque não quero ter que fazer uma query que busque os mesmos resultados só pra ordenar, quero só fazer uma pesquisa no banco pra ir exibindo pelo site.
Comment: Mas pense numa dificuldade de encaixar esse usort no meu código.
Comment: Não consegui entender o motivo de não usar order by.
Comment: Como você faz o retorno da function "get_result"?
Comment: Não quero usar o order by em uma segunda query porque quero fazer só uma busca no banco, eu já tenho os dados em um SELECT *, entende? Quero otimizar o código pra utilizar a menor quantidade de buscas no banco
Comment: Bom, é tudo que está aí, eu pego o resultado da busca, uso o fetch array e exibo os dados em uma tabela, escolhendo quais colunas e quantos registros quero exibir, só que como vou utilizar uma query, preciso ordenar os dados fora da query.
Comment: Está difícil entender o seu código, ele está muito picado. A onde necessariamente você esta chamando o usort? Porque no "while" você esta pegando direto os resultados do banco. E também não entendi porque você teria quer fazer uma segunda query, não tem como já ordenar a primeira?
Comment: Não chamei o usort ainda, porque antes mesmo de chamar, dá esse erro, quero utilizar ele nesse while. Eu não vou fazer uma segunda query, quero ordenar a primeira mesmo.
Comment: "SELECT * FROM esc_usuarios WHERE usu_indicador_codigo = ? order by usu_indicador_codigo" não rola?
Comment: E você só quer mostrar 2 resultados?
Comment: não rola porque eu não quero alterar a query original,quero ordenar no while, só isso mesmo, ordenar os resultador por alguma coluna SEM SER na query
Answer: Edit: Como corrigido nos comentários, o erro "Illegal string offset" acontece quando tenta acessar o índice de uma string usando outra string (como explicado melhor na outra resposta).
E o erro "Undefined offset" (que eu havia erroneamente confundindo antes) acontece quando você tentar acessar um índice que não existe no array.
Neste erro é possível usar o "isset" para checar e testar o valor do array antes de executar qualquer operação.
Comment: Removeu o erro, mas não retornou nenhum valor, preciso de algum while?
Comment: Não sei se influencia em algo, mas eu estou tentando fazer isso dentro uma session utilizando:
isset($_SESSION['codigo']);
$_SESSION['codigo'] = 1;
$usu_codigo = $_SESSION['codigo'];
Comment: Como assim não retornou nenhum valor? o usort retorna um boolean, e a variável ordenada é a própria variável passada ($usu_info_coluna). Se puder, atualize a pergunta colocando as informações da session.
Comment: Perdão, erro meu. Como eu faço para usar esse resultado num while? Porque se eu usar assim:  while ($row = mysqli_fetch_assoc($usu_info_coluna)), ele vai dizer que precisa de um result ao invés de um array
Comment: Errado. Geralmente, Illegal offset está relacionado com o tipo de valor passado para índice do `array`. O que aparece quando o offset não existe é "Undefined offset"
Comment: @LuannSousa não retornou valor nenhum porque, como eu disse na minha resposta, o seu `array` passado para `usort` está iterando sobre cada item. E cada item é um valor `int` ou `strng`, e não um `array`. Você terá que revisar como os dados do banco são retornados pra você.
Comment: Obrigado pela correção, confusão minha realmente.


preprocessing directives to prevent a project from release and debug symbols

Question: Is there anyway to restrict by using pre-processing directives to prevent a project from compiling when both the Release and Debug symbols are defined?
Please let me know.
Answer: See here. According to this it works in VC++ as well.
Answer: Assuming C/C++:
<code>#if defined (Debug) && defined (Release)
  #error Debug and Release are both defined !
#endif
</code>


InApp Purchase - Expiration and Start Date details

Question: I have implemented the InApp purchase in android for first time using
<code>Android In-App Billing v3 Library
</code>
The subscription are successfully charged and displaying subscribed on Playstore, but not able to get the subscription expiry date and other information. The info am getting from respose is
<code>**{
    "orderId": "GPA.3338-1902-5576-33309",
    "packageName": "XXXXXXXXXXXX",
    "productId": "XXXXXXXXXX",
    "purchaseTime": 1568890677033,
    "purchaseState": 0,
    "developerPayload": "XXXXXXXXX",
    "purchaseToken": "nablcikpknhkbfdkekhghiii.AO-J1OzE4eRePSXFnfV3ME-Gf50pkU6PzbSU3PKOmkR3Iwag040piJGUng9MLdUSylWRf1X8Mw5HlTMw_diU3_2Ez7-gja68tZm9iNkIu7A3IQfIqFmrthiXktwd_zlpukAhqSu9K5w6",
    "autoRenewing": true
}
</code>
Comment: Please check this link https://stackoverflow.com/questions/30620506/how-to-get-subscription-expire-date-in-inapp-v3-android
Comment: Possible duplicate of [how to get subscription expire date in inapp v3 android](https://stackoverflow.com/questions/30620506/how-to-get-subscription-expire-date-in-inapp-v3-android)
Comment: Not able to find billingService interface in above library
Answer: Why would you worry about the subscription expiration date? Every time upon your app launches, you should call queryPurchases API from Play Billing Library.
This API will return a list of active SKUs (in-app and subs). If the subscription has expired, it won't be returned by this API. With that, you know the users is no long subscribed.
Comment: Thank you for your suggestion.I got exipre date


How can we read all cell values from an Excel file using crealytics library

Question: I am trying to read data from a Excel file like below using crealytics library
df=spark.read.format("com.crealytics.spark.excel").option("inferschema",False).option("header", False).option("dataAddress","'sheet name'!").load(excel_file_path)
and it returns a dataframe which considers merged cells as single cells.
my question here is how can we read all cell values?
Is there any option need to enable to return cell values as rows? or do we need to use anyother api to return data instead of DF?
I added a sample screenshot of Excelfile here.

while reading the data observed that F and G columns from the excel sheet are not returning by data frame. Not able to understand the logic on why it is not returning  if someone can help on it will be greatly appreciated
Thanks a lot for your response.
Answer: Merged cells in excel is just cosmetic.
If you do this, you'll understand :

Create an Excel Sheet
Put 1 in A1, in A2 and in B2
Merge A1 and B1
Sum(A:A) and Sum(B:B) - First one is 2, seconde one is 1.

So your dataframe is just what excel gives.

If you want the same value every where, do not use merged cells.
Comment: When reading the above kind of Excel sheet using Crealytics library it does not return a few columns. for example in your screenshot values of the first column i.e SUM. I wanted to understand reason for it


How to loop through a list of strings with SQL SEVER stored procedure and update a table

Question: I am trying to loop through a list of email addresss with a SQL stored procedure
-Get the first part of the email addresses and query another table where the part matches a a field
DECLARE @channelName char(100)
DECLARE @EmailAddress char(100)
DECLARE @ParsedEmailID char(100)

DECLARE gpluscursor  CURSOR for Select email from Accounts
OPEN gpluscursor
Fetch NEXT from gpluscursor
into @EmailAddress
While @@Fetch_Status=0
Begin
 While @EmailAddress is not NULL
  Begin
  PRINT @EmailAddress
    set @ParsedEmailID = (SELECT  SUBSTRING(email,0,CHARINDEX('-',email)) from Accounts where email = @EmailAddress)
    PRINT @ParsedEmailID
    set @channelName = (SELECT channelname FROM channel where channelname like '%'+@ParsedEmailID+'%')
    PRINT 'mychannel'+@channelName
    update Accounts set channel = @channelName where email like @EmailAddress
  End
 Fetch Next from gpluscursor
 into @EmailAddress
  PRINT @EmailAddress
End
close gpluscursor

Here is the result from the output:
firstname.lastname@example.com
test

firstname.lastname@example.com
test

email@example.com
test

It appears that the cursor is not moving to the next record . What am I doing wrong here?
Comment: This can be achieved without using a cursor, do you have a specific reason to use one?
Comment: I would rather not use a cursor
Answer: SELECT channelName,SUBSTRING(email,0,CHARINDEX('-',email))
from Accounts as A
INNER JOIN channel AS c ON channelname like SUBSTRING(email,0,CHARINDEX('-',email))

Isnt the most efficient but it will get you there. It would be better if we could remove the like comparison but if thats what you have that is what we will use.
Answer: As far as your Cursor is concerned, Change your WHILE to an IF. Your code is getting into an infinite loop...
But as others have mentioned, a more optimized approach would be to not use a Cursor
DECLARE @channelName char(100)
DECLARE @EmailAddress char(100)
DECLARE @ParsedEmailID char(100)

DECLARE gpluscursor  CURSOR for Select email from Accounts
OPEN gpluscursor
Fetch NEXT from gpluscursor
into @EmailAddress
While @@Fetch_Status=0
Begin
 IF (@EmailAddress is not NULL)
  Begin
  PRINT @EmailAddress
    set @ParsedEmailID = (SELECT  SUBSTRING(email,0,CHARINDEX('-',email)) from Accounts where email = @EmailAddress)
    PRINT @ParsedEmailID
    set @channelName = (SELECT channelname FROM channel where channelname like '%'+@ParsedEmailID+'%')
    PRINT 'mychannel'+@channelName
    update Accounts set channel = @channelName where email like @EmailAddress
  End
 Fetch Next from gpluscursor
 into @EmailAddress
  PRINT @EmailAddress
End
close gpluscursor

Comment: sometimes answering the question isn't the right thing to do. In instances like these if you see OP doing something the wrong way, sometimes it is better to suggest a better way of doing it instead of fixing OP's issue.
Answer: I think your variable type, char, might be part of your issue.
Run this:
DECLARE @ParsedEmailID char(100)
SELECT @ParsedEmailID = 'test'
PRINT '%' + @ParsedEmailID + '%'

What is the output? It is this (scroll to the right to see the end %):
%test                                                                                %

Probably not what you wanted. Switch char to varchar:
DECLARE @ParsedEmailID varchar(100)
SELECT @ParsedEmailID = 'test'
PRINT '%' + @ParsedEmailID + '%'

Now, what is the output? It is this:
%test%

I suspect that this is what you were going for.


How To Calculate Torrent Info Hash In VB6

Question: I understand that you must calculate the SHA1 of the info dict in the torrent file,
I am struggling Parsing the info dict, Do i Need to decode the bencoded info dict before calculating the sha1 hash??
How do I do it?
Answer: The info hash is the SHA-1 hash of the info dictionary in bencoded format.
The torrent file contains a bencoded representation of the meta info dictionary which in turn contains the info dictionary.
You have to get the info dictionary part of the file in order to compute its hash. Assuming you have access to a bencode encoder and decoder you could:

decode the whole file
take the info dictionary part of it
re-encode it for hashing.

In pseudo code:
<code>metainfo = b_decode(contents_of("file.torrent"))
info = metainfo.getValue("info")
encoded_info = b_encode(info)
info_hash = sha1(encoded_info)
</code>
Comment: That would be wrong in some cases, because it would sort a unsorted info-dict and the agreed convention when a info-dict for some reason is unsorted, is to hash the info-dict raw as it is (unsorted). A more safe metod is described by Arvid here: http://stackoverflow.com/questions/19749085/calculating-the-info-hash-of-a-torrent-file/19800109#19800109


Proving $Y = aX + b$ given correlation coefficient $|\rho(X, Y)| = 1$

Question: With correlation coefficient defined as:

$$\rho(X, Y) = \frac{\text{Cov}(X, Y)}{\sqrt{\text{Var}(X)}\sqrt{\text{Var}(Y)}}$$

can you help me prove
$$|\rho(X, Y)| = 1 \implies Y = aX + b$$
Comment: I believe you want to write $Y=aX+b$ almost surely.
Comment: Just a comment... if data is $\{(0,0),(1,1)\}$ then the correlation coefficient is 1 I imagine. Now while all the data obeys $Y=X$ it doesn't prove that this is in fact the law. I assume this is obvious to you but just pointing it out.
Answer: Hint: In order for the correlation to be well-defined we must assume that $X$ and $Y$ are not degenerate ($X$ being degenerate meaning that $X=a$ almost surely). Now, show that
$$
\exists a,b\in\mathbb{R}:Y=aX+b\quad\text{a.s.}\iff \exists a\in\mathbb{R}\setminus\{0\}:\,\mathrm{Var}(Y-aX)=0.
$$
Then you just need to show that
$$
|\rho(X,Y)|=1\;\;\Longrightarrow\;\; \exists a\in\mathbb{R}\setminus\{0\}:\,\mathrm{Var}(Y-aX)=0,
$$
so start out by assuming that $\rho(X,Y)=1$ and then expand $\mathrm{Var}(Y-aX)$ and show that it is indeed zero for some $a\neq 0$.
Comment: I think you meant to say the variance of $Y-aX$ not $Y-bX$.
Comment: @DilipSarwate: Indeed, thanks for pointing out the mistake.


How do I hide an area in a template or layout if multiple regions have no content?

Question: I am able to set this up using a single check for a content in a region, but what if say 3 regions must all have content before the area is displayed?
Here's what I use in my templates when checking for a single region:
<?php if ($content['region-1']): ?>

Region 1 Content

  <?php print render($content['region-1']); ?>
<?php endif; ?>

But for checking multiple regions, Something like this?
<?php if ($content['region-1']['region-2']['region-3']): ?>

Region 1 Content

  <?php print render($content['region-1']); ?>

Region 2 Content

  <?php print render($content['region-1']); ?>

Region 3 Content

  <?php print render($content['region-1']); ?>
<?php endif; ?>

Answer: Your solution will work, but I think the best practice will be to make this check by preprocess 'theme_preprocess_page' and pass the result ( e.g. 'isRegionsEmpty') to the template. Then, in the template you only check one variable.
Answer: This is what I tried just now & it's working --
<?php if ($page['footer_firstcolumn'] && $page['footer_secondcolumn']): ?>

    <?php print render($page['footer_firstcolumn']); ?>

<?php endif; ?>

So I hope if you also try like this with your code with &&, it will work. Something like this--
<?php if ($content['region-1'] && $content['region-2'] && $content['region-3']): ?>

Region 1 Content

  <?php print render($content['region-1']); ?>

Region 2 Content

  <?php print render($content['region-1']); ?>

Region 3 Content

  <?php print render($content['region-1']); ?>
<?php endif; ?>

Otherwise you can take a look here on this documentation to see how you can check whether they are occupied or not in template.php and pass some value with variable to tpl. Then it will be easy to put in condition just like D6.
Comment: Thanks, I should have thought of that but didn't trust my php ability. This works for me, also I appreciate the advice.


Riemann integral $\underline{\int_a^b} \alpha f = \alpha \underline{\int_a^b} f$

Question: During our introduction to Riemann integrals and Darboux sums we recieved we encountered this theorem:

Let $f$ be a bounded function in $[a,b]$, Then if $\alpha >0$ then $\underline{\int_a^b} \alpha f = \alpha \underline{\int_a^b}  f$.

So far I've proven by contradiction that $$\alpha  \inf f  = inf (\alpha f)$$.
I've used this fact to show that for some partition $P$: $$L(\alpha f, P)= \alpha L(f,P)$$
But I'm not sure how to translate my findings to arguments regarding lower integarls.
$$ \underline{\int_a^b} \alpha f = \sup \,L( \alpha f,P) $$
and
$$ \alpha \underline{\int_a^b} = \alpha \sup \,L(f,P) $$
Comment: I think you want to use sup here because you are discussing lower Riemann integrals
Comment: Yes, you are correct. Thank you for pointing this out. I used the wrong one for the lower integrals. but using inf for function values is still correct I think, because the Darboux sums use the infimum of each section of the partition.
Answer: For each partition $P$, we have$$L(\alpha f,P)=\alpha L(f,P)$$and therefore\begin{align}\underline{\int_a^b}\alpha f&=\sup_PL(\alpha f,P)\\&=\sup_P\alpha L(f,P)\\&=\alpha\sup_PL(f,P)\\&=\alpha\underline{\int_a^b}f.\end{align}
Comment: Thank you for taking your time to address my questions! I would like to ask for clarification. Why does $ \sup_P\alpha L(f,P) = \alpha \sup_PL(f,P) $ ?  How can you take $\alpha$ out of the $\sup$ ?
Comment: This has nothing to do with integrals. If $\alpha\geqslant0$, if $S$ is a bounded set of real numbers and if $\alpha S=\{\alpha s\mid s\in S\}$, then [$\sup\alpha S=\alpha\sup S$](https://math.stackexchange.com/q/1516757/446262).
Answer: You can take out $\alpha$ because of the following results.
Let $\{x_i\}_{i \in I}$ be a bounded collection of real numbers.
Then for every $\alpha \in [0,\infty)$ it holds the following:
$$\sup_I{\alpha x_i} = \alpha \sup_I{x_i}$$
Proof:
$$\alpha x_i \leq \alpha \sup_I {x_i}$$
for every $i$ so we can pass to the supremum and we get
$$\sup_I{\alpha x_i} \leq \alpha \sup_I{x_i}$$
For the converse inequality let $i^*$ be such that $\sup_I{x_i} - x_{i^*} < \frac{\epsilon}{\alpha}$
Now:
$$\alpha \sup_I {x_i} \leq \epsilon + \alpha x_{i^*} \leq \epsilon + \sup_I {\alpha x_i}$$
Since $\epsilon$ is arbitrary we get:
$$\alpha \sup_I {x_i} \leq  \sup_I {\alpha x_i}$$


Formulário responde Ocorreu um erro ao enviar a mensagem!

Question: Criei um formulário que no ambiente de homologação está respondendo e indo para página de destino de agradecimento. Quando subo ao servidor do domínio ele está respondendo negativamente. Alguém me diz onde estou errando?

<?php

 /* Valores recebidos do formulário  */
 $nome = $_POST['nome'];
 $email = $_POST['email']; // Email que será respondido
 $empresa = $_POST['empresa'];
 $fone = $_POST['fone'];
 $opcoes = $_POST['opcoes'];
 $escolha = $_POST['escolha'];
 $produto = $_POST['produto'];
 $mensagem = $_POST['mensagem'];

/* Destinatário e remetente - EDITAR SOMENTE ESTE BLOCO DO CÓDIGO */
$to = "";
$to = "";
$remetente = ""; // Deve ser um email válido do domínio

/* Cabeçalho da mensagem  */
$boundary = "XYZ-" . date("dmYis") . "-ZYX";
$headers = "MIME-Version: 1.0\n";
$headers.= "From: $remetente\n";
$headers.= "Reply-To: $email\n";
$headers.= "Content-type: multipart/mixed; boundary=\"$boundary\"\r\n";
$headers.= "$boundary\n";

/* Layout da mensagem  */
$corpo_mensagem = "

Formulário via site

--------------------------------------------

NOME: $nome

EMAIL: $email

EMPRESA: $empresa

TELEFONE: $fone

SEGMENTO: $opcoes

ONDE NOS CONHECEU: $escolha

INTERESSE NO PRODUTO: $produto

MENSAGEM: $mensagem

--------------------------------------------
";

/* Função que envia a mensagem  */
if(mail($to, $nome, $mensagem, $headers))
{
 echo "";

}
 else
 {
  echo "

Ocorreu um erro ao enviar a mensagem!";
}
?>

                         <form class="contact-form" action="contact.php" method="post" enctype="multipart/form-data">

                                        <input type="text" name="nome" id="name" class="input-md round form-control" placeholder="Nome" pattern=".{3,100}" required>

                                        <input type="text" name="empresa" id="company" class="input-md round form-control" placeholder="Empresa" pattern=".{3,100}" required>

                                        <select class="input-md round form-control" name="opcoes" id="select" placeholder="Segmento" pattern=".{3,100}">
                                        <option value="">Segmento</option>
                                        <option value="Adm de Cartões">Adm de Cartões</option>
                                        <option value="Atacado">Atacado</option>
                                        <option value="Banco/Financeiras">Banco/Financeiras</option>
                                        <option value="Cobrança">Cobrança</option>
                                        <option value="E-Commerce">E-Commerce</option>
                                        <option value="Indústria">Indústria</option>
                                        <option value="Seguradora">Seguradora</option>
                                        <option value="Serviços">Serviços</option>
                                        <option value="Utilities">Utilities</option>
                                        <option value="Varejo">Varejo</option>
                                        <option value="Outros">Outros</option>
                                    </select>

                                        <input type="email" name="email" id="email" class="input-md round form-control" placeholder="Email" pattern=".{5,100}" required>

                                        <input type="text" name="fone" id="phone" class="input-md round form-control" placeholder="Telefone" pattern=".{3,100}" required>

                                        <select class="input-md round form-control" id="00Ni000000A7cey" name="escolha">
                                        <option value="">Onde nos conheceu</option>
                                        <option value="Anúncio">Anúncio</option>
                                        <option value="Evento/Feira">Evento/Feira</option>
                                        <option value="Indicação">Indicação</option>
                                        <option value="Sites de Busca">Sites de Busca</option>
                                        <option value="Outros">Outros</option>
                                        </select>

                                        <input type="text" id="00Ni000000A7tt7" name="produto" class="input-md round form-control" placeholder="Interesse no produto" pattern=".{3,100}" >

                                        <textarea name="mensagem" id="message" class="input-md round form-control" style="height: 158px;" placeholder="Mensagem"></textarea>

                                        <button class="submit_btn btn btn-mod btn-medium btn-round" id="submit_btn">Enviar Mensagem</button>

                            </form>

Comment: qual erro que dá ?
Comment: Exatamente este: else
 {
  echo "Ocorreu um erro ao enviar a mensagem!";
}
Comment: @Bulfaitelo o código php não encaminha para a página de agradecimento e o email não é enviado.
Answer: if(mail($to, $nome, $mensagem, $headers))
{
    echo "";

}
    else
    {
        echo "

Ocorreu um erro ao enviar a mensagem!";
}

O que está a aconter é que a função mail($to, $nome, $mensagem, $headers) está a dar erro logo vai para o else. Verifique os parâmetros que passa para lá para ver se está tudo correcto.


Unable to send user-entered data to PayPal along with credit card info

Question: I need help. I used this as a guide. When my user fills out and pays for something on my site using a product form the information they supplied in the form (other than their payment) is not being sent to PayPal. So I built this module to send the information using the module I'm supposed to hook into. However, it throws no errors but still sends no data to PayPal.

    if ($payment_method['base'] == 'commerce_paypal_wpp') {

    $order_wrapper = entity_metadata_wrapper('commerce_order',
$order);
    $shipping_info = $order_wrapper->customer_profile_billing-
>commerce_customer_address->value();

             $nvp += array(
                    'ORGANIZATION' => $shipping_info['field_organization'],
            'NAME' => $shipping_info['field_name'],
         );
    }
}

Am I perhaps referencing my user-entered data incorrectly?
Here's how the fields show with dpm($form) [before the user submits the form]:
Name:
$form['customer_profile_billing']
['commerce_customer_address']['und'][0]'name_block']['name_line']

Organization:
$form['customer_profile_billing']['field_organization']
Answer: From your above code i have seen that dpm($form) showing 2 fields. when you submit your data in form please ensure that your order is created or not. Becuase in your code you are getting customer order details and pass it to the array() (which is empty). Thats why it not going to Paypal website. Please check your custom code.
hook_commerce_paypal_api_request_alter(&$nvp, $order, $payment_method):  What this function will do, it will alter the array before pass this data to paypal website. So you must ensure that array data you are passing to paypal is not empty or you can check the condition for it.
Comment: Interesting. I see what you mean. But let me add: the payment is going through to PayPal just fine (so it's getting the credit card data the user is filling out) - just not the rest of their information. Do you still think it's the array not getting the information?


Squared reverse triangle inequality

Question: Is there a possibility to obtain a bound on the difference of squared norm $\left\lvert\Vert x \Vert^2 - \Vert y \Vert^2\right\rvert$ in terms of the norm of the difference $\Vert x - y \Vert$?
I have tried to adapt the usual proof of the reverse triangle inequality as follows.
$$
    \Vert x \Vert^2 = \Vert x - y + y \Vert^2 \le (\Vert x - y \Vert + \Vert y \Vert)^2 = \Vert x - y \Vert^2 + 2 \Vert x - y \Vert \, \Vert y \Vert + \Vert y \Vert^2 \\
    \iff \Vert x \Vert^2 - \Vert y \Vert^2 \le \Vert x - y \Vert^2 + 2 \Vert x - y \Vert \, \Vert y \Vert
$$
$$
    \Vert y \Vert^2 = \Vert y - x + x \Vert^2 \le (\Vert y - x \Vert + \Vert x \Vert)^2 = \Vert x - y \Vert^2 + 2 \Vert x - y \Vert \, \Vert x \Vert + \Vert x \Vert^2 \\
    \iff \Vert x \Vert^2 - \Vert y \Vert^2 \ge -\Vert x - y \Vert^2 - 2 \Vert x - y \Vert \, \Vert x \Vert
$$
At this point, I do not know how to convert the bounds including $\Vert x \Vert$, $\Vert y \Vert$ into anything useful.
Comment: $| \| x \|^2 - \|y \|^2 | = | \| x \| - \|y \| || \| x \| + \|y \| |$. Hence there is no global Lipschitz constant, but there is on any bounded set.
Comment: You could say that $(\|x\|-\|y\|)\cdot\|x+y\|\leq|\|x\|^2-\|y\|^2|\leq\|x-y\|\cdot(\|x\|+\|y\|)$
Answer: In $\Bbb R$, consider $x=y+1$ with $y>0$. Then $\|x-y\|=1$, but $\bigl|\|x\|^2-\|y\|^2\bigr|=2y+1$ can be arbitrarily large.
However, we do have
$$\|x\|^2-\|y\|^2=(\|x\|-\|y\|)(\|x\|+\|y\|)$$
if that helps you.
Comment: This example helped me understand that it is not actually $\left\lvert\Vert x \Vert^2 - \Vert y \Vert^2 \right\rvert$ that I care about, bur rather the relative size wrt. $\Vert x\Vert$, $\Vert y \Vert$.

Squared reverse triangle inequality


iframe form killing my table - html

Question: I am using a contact form on my website for customers to provide some initial information. In order to try and make it pretty, I am inserting the form (a PHP file) in the right column of a html table, with the information for the customer to read in the left column.
The iframe and form seems to be pushing all the content in the left column down below it's frame.
So far I have tried adding a halign and valign code but Joomla seems to take them out.
Oh yeah, It's a Joomla based website and this is all happening inside an article.
http://purpledevils.com/index.php/services/family-photography
Any help would be muchly appreciated.
Comment: Can you include some code with the specific haligns and valigns that Joomla is not honoring?
Comment: long time browser should know we need to see actual code
Answer: Looking at your code, on your template.
If you add a inline css style to your table column "td" that contains the iframe like position:relative
And add the iframe tag a css style for position:absolute, your content now should be properly aligned.

Here is an example - http://jsfiddle.net/0yvmt235/

iframe form killing my table - html


Which statistic test should I use?

Question: For a task on data cleaning and analysis using SPSS I have two research questions for which I should pick an appropriate statistical test. It's been over a few years though since my last statistics course and I feel like some sources are contradicting each other. The analysis is done on a set of 5000 women giving birth.
The first question is whether there's a relationship between the Apgar-scores at 1 minute and 5 minutes, I interpreted this as two paired ordinal variables.
My first intention was to use Wilcoxon signed-ranks test, due to the description of the variables. But my statistics notes of back in the days mention a few times that when searching a relationship it is preferred to use correlation, rather than Wilcoxon, which would be more preferred when searching a difference. If it is correct to search correlation, I assume this would be the Spearman's rank correlation coefficient, due to the ordinal character of the variables.
As for the second question, is to find whether there's a difference in the need of extra care (nominal) when the duration of pregnancy is accounted for. The duration of pregnancy is divided into two categories, either less than 37 weeks or between 37 and 42 weeks. Due to the rather obvious greater than/lesser than character of the latter, I interpreted this as an ordinal variable.
Because I'm working with two categorical variables here, I was rooting for a Chi-squared test, but, as I heard from my colleagues, a binary logistic regression would also be possible, I never learnt anything about the latter in the past, so I don't know if this would be a better fit.
Thanks in advance.
Answer: For the first question, I agree with you. Rank correlation is what I'd do.
For the second question, first, if at all possible, I would try to the actual number of weeks or days of the pregnancy.  Dividing it into two categories is a really bad idea. Similarly, I'd try to get a better measure of care needed that "extra vs. not".
But, whether or not you can get that, this is a regression type problem. If your DV has two categories (extra care, no extra care) then logistic regression is a good choice.
Comment: Thank you Peter!

It was part of the assignment to transform the length of pregnancy from a continuous variable to the one as described above, for which I thought ordinal was rather better than nominal.

Would it be possible to explain the motivation for logistic regression rather than Chi-squared, or why Chi-squared wouldn't be the best fit here?
Comment: For example, there was another optional question, which was to find whether there's a difference between a spontaneous delivery or a cesarean section in transfer to the intensive care for babies that had a breech presentation. As the method of delivery and whether or not there was a transfer are both nominal variables, wouldn't it be appropriate to use Chi-squared or Fisher's exact in this case?
Comment: I have been reading up on this and I think I came to the conclusion that both the question in the main post and the optional question I posed just above should be approached through binary logistic regression because I'm trying find if one variable can predict the other, rather than just "looking" at a possible relationship they might have?
Comment: Chi-square _can_ be appropriate with two nominal variables, but here it seems like regression (in this case, logistic regression) is more suited to what you want to find out because you have a dependent variable.
Answer: Agree with you and Peter regarding the first question.
Will comment more on the biology regarding the second one: categorizing gestational age into term/pre-term is a bad idea both statistically and biologically. Firstly, you end up treating a very wide range of gestational length as equal (25 weeks of pregnancy is very different from 37); secondly, a lot of deliveries are in the range 37-38 weeks, and gestational age estimation is usually not precise, so you will have a lot of misclassification; thirdly, it has been shown that a lot of subsequent health outcomes in fact have a smoother monotonous relationship with gestational age, as opposed to a threshold effect at GA of 37 weeks.
Source: been working on pregnancy phenotypes for the past few years.

Which statistic test should I use?


probability of intersection of events

Question: Let $A$ and $B$ be two events such that $P(A)\geq P(B)$. Let $R$ be any other event. Is $P(A\cap R)\geq P(B\cap R)$? If yes, how to prove this?
Comment: Not true. For example, let's consider the event  that during a dice roll, $A = \{ 1,2,3,4\}$, $B = \{5,6\}$, $R = \{ 5\}$, that is to say, each event has happened when one of the numbers in the set  has come up. $A \cap R = \{ \}$, while $B \cap R = R$, which has non-zero probability. Even $R = \{ 4,5,6\}$ would work, since $A \cap R = \{4\}$, while $B \cap R = \{ 5,6\}$.
Comment: Why isn't an answer accepted?
Answer: Counterexample: In the plane, draw a square $B$ with side length 1, then draw a square $A$ with side length two so that the two squares intersect, but neither contains the other completely. Draw a square $R$ with side length 1 intersecting only the other square of side length 1, and not the other. Next, draw a square of side length 5 which contains all of these shapes. Assign to each rectangle $S$ a number $P(S)$ which is the surface area of the shape divided by 25.
Answer: No.
$P(A\cap R)$ can be at most the larger of the two sets(If either $A\subseteq R$ or $R\subseteq A$). But there is no reason why it cannot be the empty set; that is $A$ and $R$ are mutually exclusive.
Then certainly $P(A\cap R) \leq P(B\cap R)$.

probability of intersection of events