text:
Q: Chrome back button: only giving cached version of initial page, without any Ajaxed content I have two pages, A and B. The flow is as follows:

*

*Go to A

*javascript Ajaxes a bunch of content to add to A, forming A'

*go to B

*pressing [Back] goes back to A, not A', without all the Ajaxed content

Has anyone else noticed this, and if so, how do you fix it?
If Chrome was caching the A' state just before going to B, and reproduces A' upon back, that would be acceptable. If Chrome simply re-loaded the entirety of A (including the Ajax requests that transformed it into A') that would work too. The current behaviour, which is loading an old, incomplete version of A, is not what I want.
EDIT: I know it's loading a cached version because the server isn't receiving any new requests when i hit [Back].

A: This topic is old but thought I would share my solution. To get Firefox, Chrome and Safari to behave consistently, you have to set an unload handler on the page that needs to be reloaded when going back, and also use cache busting headers.
Example
In HTTP Headers
Cache-Control: must-revalidate, no-store, no-cache, private
And in the javascript for the page
$(window).unload(function(){}); // Does nothing but break the bfcache

Read here for more info: http://madhatted.com/2013/6/16/you-do-not-understand-browser-history

A: I know that  topic is old but solution to this problem is not so easy to find I've just wasted few hours to solve it. These two lines solved the Chrome problem for me:
Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.Cache.SetNoStore();

A: Well, if you are using xhr request and not hidden frames the back and forward buttons do not tie in to xhr request


text:
Q: Can I disable chat in Star Wars: Uprising? Basically I don't want to keep seeing the yellow exclamation mark every time someone posts in the general chat. Can this be done?

A: Looking at the forums there doesn't seem to be any way to stop global chat or even default to cartel chat. Interestingly this post came up in a search, though:
http://community.kabam.com/forums/showthread.php?413961-Turn-off-chat&styleid=-1
In the link (for a different game) somebody that is speaking as though they work at Kabam says you can request chat turned of by submitting an in-game help request. Might be worth a try in case they can do it in Uprising as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Square of value VB 2010 How do i write a program that square the value in the textbox and add it in the listbox each time the button is click. from 0 to 100000. thanks
This is what I have so far
Public Class frmSquare
Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click
    Dim x As Double
    Dim number As Double = txtNumber.Text

    lstSquare.Items.Add(number * number)
    x = number

End Sub

Private Sub btnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStop.Click
    Me.Close()
End Sub

End Class

A: Here's another way to do this, hope this helps:
If IsNumeric(TextBox1.Text) Then
            Dim dbl As Double = CDbl(TextBox1.Text)
            dbl *= dbl
            ListBox2.Items.Add(dbl)
        Else
            MessageBox.Show("Value entered is not a Number")
        End If


text:
Q: Speech Recognition Issue on Windows Phone 8.1 I'm working on an app that is trying to use Speech Recognition to enter text. I don't have a particular grammar, I just want to dump the spoken text into a text box on Windows Phone 8.1
So I'm using the Windows.Media.SpeechRecognition libraries.
My code is basically this
SpeechRecognizer sr = new SpeechRecognizer();
SpeechRecognitionResult result = await sr.RecognizeAsync();
if(result.Confidence == SpeechRecognitionConfidence.High || result.Confidence == SpeechRecognitionConfidence.Medium)
    txtBox.Text = result.Text;
else
    txtBox.Text = "Huh?";

sr.Close()

I'm getting an error when I press the button to start the voice recognition: "Operation is not valid due to the current state of the object"
I've done some searching but the big results seem to be about some issues with ASP.NET years ago.
Anybody done some simple Speech Recognition for Windows Phone that can point me in the right direction?
UPDATE
I eventually found the answer. Even though there are no additional constraints you need still need to compile the defaults.
sr.CompileConstraintsAsync();

And then you can do the
sr.RecognizeAsync()

function.
Thanks.

A: Have you checked the microphone function in your app manifest?

A: I eventually found the answer. Even though there are no additional constraints you need still need to compile the defaults.
sr.CompileConstraintsAsync();
And then you can do the
sr.RecognizeAsync()
function.


text:
Q: Does compiler need to care about other threads during optimizations? This is a spin-off from a discussion about C# thread safety guarantees.
I had the following presupposition:

in absence of thread-aware primitives (mutexes, std::atomic* etc., let's exclude volatile as well for simplicity) a valid C++ compiler may do any kinds of transformations, including introducing reads from the memory (or e. g. writes if it wants to), if the semantics of the code in the current thread (that is, output and [excluded in this question] volatile accesses) remain the same from the current thread's point of view, that is, disregarding existence of other threads. The fact that introducing reads/writes may change other thread's behavior (e. g. because the other threads read the data without proper synchronization or performing other kinds of UB) can be totally ignored by a standard-conform compiler.

Is this presupposition correct or not? I would expect this to follow from the as-if rule. (I believe it is, but other people seem to disagree with me.) If possible, please include the appropriate normative references.

A: Yes, C++ defines data race UB as potentially-concurrent access to non-atomic objects when not all the accesses are reads.  Another recent Q&A quotes the standard, including.

[intro.races]/2 - Two expression evaluations conflict if one of them modifies a memory location ... and the other one reads or modifies the same memory location.

[intro.races]/21 ... The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other, ...
Any such data race results in undefined behavior.

That gives the compiler freedom to optimize code in ways that preserve the behaviour of the thread executing a function, but not what other threads (or a debugger) might see if they go looking at things they're not supposed to.  (i.e. data race UB means that the order of reading/writing non-atomic variables is not part of the observable behaviour an optimizer has to preserve.)

introducing reads/writes may change other thread's behavior

The as-if rule allows you to invent reads, but no you can't invent writes to objects this thread didn't already write.  That's why if(a[i] > 10) a[i] = 10; is different from a[i] = a[i]>10 ? 10 : a[i].
It's legal for two different threads to write a[1] and a[2] at the same time, and one thread loading a[0..3] and then storing back some modified and some unmodified elements could step on the store by the thread that wrote a[2].
Crash with icc: can the compiler invent writes where none existed in the abstract machine? is a detailed look at a compiler bug where ICC did that when auto-vectorizing with SIMD blends.  Including links to Herb Sutter's atomic weapons talk where he discusses the fact that compilers must not invent writes.
By contrast, AVX-512 masking and AVX vmaskmovps etc, like ARM SVE and RISC-V vector extensions I think, do have proper masking with fault suppression to actually not store at all to some SIMD elements, without branching.

*

*When using a mask register with AVX-512 load and stores, is a fault raised for invalid accesses to masked out elements? AVX-512 masking does indeed do fault-suppression for read-only or unmapped pages that masked-off elements extend into.

*AVX-512 and Branching - auto-vectorizing with stores inside an if() vs. branchless.

It's legal to invent atomic RMWs (except without the Modify part), e.g. an 8-byte lock cmpxchg [rcx], rdx if you want to modify some of the bytes in that region.  But in practice that's more costly than just storing modified bytes individually so compilers don't do that.

Of course a function that does unconditionally write a[2] can write it multiple times, and with different temporary values before eventually updating it to the final value.  (Probably only a Deathstation 9000 would invent different-valued temporary contents, like turning a[2] = 3 into a[2] = 2; a[2]++;)
For more about what compilers can legally do, see Who's afraid of a big bad optimizing compiler? on LWN.  The context for that article is Linux kernel development, where they rely on GCC to go beyond the ISO C standard and actually behave in sane ways that make it possible to roll their own atomics with volatile int* and inline asm.  It explains many of the practical dangers of reading or writing a non-atomic shared variable.


text:
Q: Error in printing common elements of two linked lists I am trying to print common elements in two linked lists but my function is printing only the first element if it is common
  void common()
    {

//head and head1 are respectively the head pointers of first and second list
      node1 *ptr=head;
      node2 *ptr2=head1;
      while(ptr!=NULL||ptr2!=NULL)
      {
          while(ptr!=NULL&&ptr2!=NULL)
          {
         if(ptr->info==ptr2->info)
            {
             printf("Common Elements are-%d\n",ptr2->info);
             ptr2=ptr2->next;
            }
          }
      ptr=ptr->next;
      ptr2=head1;

     }
  }

A: You need to move the increment of ptr2 node out of if condition.
Whether the value of ptr2->info matches that of ptr->info is not the deciding condition for moving to the next node in ptr2. So, you have to move to next node unconditionally.
Something like
while(ptr!=NULL&&ptr2!=NULL)
      {
     if(ptr->info==ptr2->info)
        {
         printf("Common Elements are-%d\n",ptr2->info);
        }
      ptr2=ptr2->next;   //move to next node unconditionally.
      }

should do the job.
Also, as suggested by @Gopi, you can get rid of the redundant checks in your code. The outer while can check for not-NULL value of ptr whereas the inner while can check for not-NULL ptr2.

A: Remove ptr2=head1 line, with this line you are reassigning the ptr2 to 1st value of head1 again every time.
So every time same linked list node is getting compared.

A: Check the below code:
  while(ptr!=NULL)
  {
      ptr2 = head1;
      while(ptr2!=NULL)
      {
        if(ptr->info==ptr2->info)
        {
         printf("Common Elements are-%d\n",ptr2->info);
        }
        ptr2=ptr2->next;
      }
     ptr=ptr->next;
 }


text:
Q: Android Activity not working I have this activity,
package org.dewsworld.ui;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Main extends Activity {

    TextView textView ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        textView = (TextView) findViewById(R.id.textView1) ;
        textView.setText("hello ") ;
    }

}

And main.xml is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:id="@+id/textView1">
    <TextView android:layout_height="wrap_content" android:id="@+id/textView1"
        android:layout_width="wrap_content" android:text="TextView" />
</LinearLayout>

And the logcat is
And I can't find the error... :(

A: <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <TextView android:layout_height="wrap_content" android:id="@+id/textView1"
        android:layout_width="wrap_content" android:text="TextView" />
</LinearLayout>

try now

A: You have 2 views with the same ids Linearlayout and TextView. remove the id for the LinearLayout and try it again. It will work.


text:
Q: Modifying home page of tomcat server while using servlets in java Hi I'm using Eclipse Luna and Apache-Tomcat server 8.0.15.
When I run a servlet program in the web browser the path of the servlet has to mentioned.
For Example: http://localhost:8080/DemoServletPrj/DemoServlet
Is it possible that by just typing http://localhost:8080 I can see my servlet running in the browser?
If so how do i go about it?

A: This is answered already here.
Just find your web.xml in your site folder and change the root path;
<servlet-mapping>
  ..
  <url-pattern>/</url-pattern>
</servlet-mapping>


text:
Q: is this formula provable in predicate logic? ⊢ (∀x)(∀y)(f(x1) = y1 → ((∀z)g(z) = f(x1) ≡ (∀z)g(z) = y1)) "Can you prove ⊢ (∀x)(∀y)(f(x1) = y1 → ((∀z)g(z) = f(x1) ≡ (∀z)g(z) = y1)) in predicate logic? explain."
I'm saying no, but I'm not sure why. Is it because it's not a tautology? and how would Godel's incompleteness theorems come to play here?
Please help, thanks.

A: In first order logic, there are validities in addition to tautologies. These statements are statements that are true in every possible interpretation, and just not being a tautology isn't enough to tell you if it's a valid statement or not. Gödel's incompleteness theorems suggest that for every system that's powerful enough to represent arithmetic, there are statements that are undecidable... that is the truth value might be true in a particular model but not be a theorem of the formal system, but that doesn't say that validity is undecidable directly.
Church's theorem does however. That's the answer to the Entscheidungsproblem, the question on whether there's an algorithm to decide the validity of a first order statement. Church answered this in the negative for statements that are sufficiently complex.
I can't say for sure in your particular statement, since the statement looks a bit ambiguous, with quantifiers not matching any variables, and syntactic identity symbol being used where I think biconditional is meant. However if I take your statement to be this one in prenex normal form:
$\forall$x$\forall$y$\forall$z$\forall$u : ((f(x) = y) $\implies$ (g(z) = f(x)) $\iff$ (g(u) = y))
Then we can say some things about it. First, it is decidable since the only dyadic predicate is equality. This means we can determine whether it's a valid statement though several ways. We can negate the statement and use resolution. If we come up with the empty clause, it's a contradiction and hence it's unsatisfiable. The negation of an unsatisfiable statement is a valid statement. If you run out of rules, you've saturated the search and proven it satisfiable.
But satisfiable doesn't mean valid. A formula can be satisfiable and it's negation can be satisfiable as well, and what that means is there are models for each instance. This opens another way to find out if the statement is provable or not: finite model generation. I think that since the statement has only equality and monadic functions that if there's a model of it the model is finite so we can generate interpretations of the statement to see if it applies. If there's a finite model for the statement and the negation of the statement, the statement is unprovable also.
You can prove, through saturation of resolution or finite model generation that the statement isn't logically valid. It is satisfiable though.


text:
Q: Python errors using "%matplotlib inline" I am working on a python program that using matplotlib. I have it installed into the program, but when I try to add "%matplotlib inline" I am getting syntax errors.
import matplotlib.pyplot as plt

%matplotlib inline

When I test with just these two lines, I am returning a syntax error on the "%". I have tried reinstalling matplotlib through pip to no avail. Any help would be appreciated.

A: %matplotlib inline

is not a Python command, it's so-called IPython magic command that is working in Jupyter or pure IPython environment only. IDLE doesn't support it, and it cannot show you figures inline.


text:
Q: TFS 2012 with azure I am new to TFS, we have the below requirement.
We need to create simple dot net application which need to be checked in TFS 2012 then we need to build the solution in the TFS and place it in X location (on local machine). and in post build script we need to run the powershell command which upload the files to cloud.
We have written the poowershell command but our concern is how to write build script which will call this powershell script to upload the complied files from local machine to cloud

A: Visual Studio Online - Getting Started
Best place to get you started with Visual Studio Online basics and specifically for a Build


text:
Q: Posting Inventory Movement Journal to D365 Finance and Operations via OData API and InventoryMovementJournalHeaders Entity I am trying to create an Inventory Movement Journal in D365 using the OData API and the InventoryMovementJournalHeaders / InventInventoryMovementJournalHeaderEntity.
I have managed to do similar for the Counting Journal using InventoryCountingJournalHeaders as the starting point but get the following error when I try to raise an Inventory Movement Journal with InventoryMovementJournalHeaders entity:

Write failed for table row of type 'InventInventoryMovementJournalHeaderEntity'. Infolog: Warning: Field 'Journal' must be filled in.; Warning: validateWrite failed on data source 'InventJournalTable (InventJournalTable)'.

Full error message:
{
  "error": {
    "code": "",
    "message": "An error has occurred.",
    "innererror": {
      "message": "Write failed for table row of type 'InventInventoryMovementJournalHeaderEntity'. Infolog: Warning: Field 'Journal' must be filled in.; Warning: validateWrite failed on data source 'InventJournalTable (InventJournalTable)'.",
      "type": "Microsoft.Dynamics.Platform.Integration.Services.OData.AxODataWriteException",
      "stacktrace": "   at Microsoft.Dynamics.Platform.Integration.Services.OData.Update.UpdateProcessor.CreateEntity_Save(ChangeOperationContext context, ChangeInfo changeInfo)\r\n   at Microsoft.Dynamics.Platform.Integration.Services.OData.Update.UpdateManager.<>c__DisplayClass10_0.<CreateEntity>b__1(ChangeOperationContext context)\r\n   at Microsoft.Dynamics.Platform.Integration.Services.OData.Update.ChangeInfo.ExecuteActionsInCompanyContext(IEnumerable`1 actionList, ChangeOperationContext operationContext)\r\n   at Microsoft.Dynamics.Platform.Integration.Services.OData.Update.ChangeInfo.TrySave(ChangeOperationContext operationContext)\r\n   at Microsoft.Dynamics.Platform.Integration.Services.OData.Update.UpdateManager.SaveChanges()\r\n   at Microsoft.Dynamics.Platform.Integration.Services.OData.AxODataDelegatingHandler.<SaveChangesAsync>d__3.MoveNext()"
    }
  }
}

The field 'Journal' referred to in the error message does not exist in the data entity or the InventJournalTable table and I am not sending it (I have also tried to send it a field called 'Journal' but that raises an error also).  This is a standard, out of the box, data entity provided by Microsoft.
Has anyone come across this error / solved it please?

A: I'm able to replicate your issue. After a closer look at the entities of both counting and movement journals, turns out that indeed the counting journal entity does support creating a new journal without specifying the value for the primary natural key, the journal number. It does this with the following code in the initValue method of the entity:
public void initValue()
{
    if (!this.skipNumberSequenceCheck())
    {
        NumberSeqRecordFieldHandler::enableNumberSequenceControlForField(
            this, fieldNum(InventInventoryCountingJournalHeaderEntity, JournalNumber), InventParameters::numRefInventJournalId());
    }

    super();
}

This code is missing in the entity for movement journals. This means that the entity does not support creation of new journals without specifying the journal number.
You can easily customize the entity to add this support. I added the following code in a code extension for the entity. Afterwards, I was able to create new movement journals using the entity.
[ExtensionOf(tableStr(InventInventoryMovementJournalHeaderEntity))]
final class InventInventoryMovementJournalHeaderEntity_Tutorial_Extension
{
    public void initValue()
    {
        if (!this.skipNumberSequenceCheck())
        {
            NumberSeqRecordFieldHandler::enableNumberSequenceControlForField(
                this, fieldNum(InventInventoryMovementJournalHeaderEntity, JournalNumber), InventParameters::numRefInventJournalId());
        }

        next initValue();
    }

}


text:
Q: javascript: value of "this" inside of a function called by a method I'm attempting to use the keyword this inside of a function which is called by a method of an object. In the scope of the method, the value of this is the object. However, in the scope of the function called by that method, the value of this is not the object.
I've figured out that if I pass this as a parameter, the function works. The function does not work when this is used literally.
I know that the value of this inside of a method is the method's object. What rule determines the value of this in the scope of a function called by that method? Is it the value of this at the time/scope the function is defined (rather than at the time/scope that it is called)?
Erroneous code:
var setHeightTop = function(h,t){
  var prevWellHeight = $(this).parent().prev().height();
  $(this).css({
    "height": function() {return (prevWellHeight - h);},
    "top": function() {return -(prevWellHeight - t);}
  });
};

var recalcConnectorLines = function() {
  $(".well + .well > .connectLine").each(function() {
    setHeightTop(1,28);
  });
};

Functioning code:
var setHeightTop = function(obj,h,t){
  var prevWellHeight = $(obj).parent().prev().height();
  $(obj).css({
    "height": function() {return (prevWellHeight - h);},
    "top": function() {return -(prevWellHeight - t);}
  });
};

var recalcConnectorLines = function() {
  $(".well + .well > .connectLine").each(function() {
    setHeightTop(this,1,28);
  });

EDIT: SOLUTION.
Based on Mentok's link, I've figured out two things:

*

*The value of this in a function is set at the time the function is
defined. This explains the behavior I was seeing in my erroneous
code.

*However, if I invoked my function as a method, this would be defined at the
time the method was called.
As explained here in the jQuery documentation, it is possible to add new methods to the jQuery object.
My improved DRY code is:
$.fn.setHeightTop = function(h,t) {
  $(this).each(function() {
    var prevWellHeight = $(this).parent().prev().height();
    $(this).css({
      "height": function() {return (prevWellHeight - h);},
      "top": function() {return -(prevWellHeight - t);}
    });
  });

};

var recalcConnectorLines = function() {
  $(".well + .well > .connectLine").setHeightTop(1,28);
};

It works!

A: What's wrong with the existing setHeightTop(obj,h,t)
.each(function(el,idx) {
    setHeightTop(el,1,28);
})

setHeight(h,t) has no context for a "this" object. The existing function should work fine.


text:
Q: Pass function as Lazy argument in scala similar to lazy parameter I am adding caching in my scala code and using ScalaCache. I liked memoization in which you basically call function from inside of memoization. What I want is, I want to write a generic function withCache which accept other function like lazy arguments and want to call that to the memoization body. I tried as follow but it did not work
import scalacache.{Cache, _}
import scalacache.redis._
import scalacache.serialization.binary._
import _root_.redis.clients.jedis._
import scalacache.memoization.memoize
import scalacache.modes.try_.mode

import scala.concurrent.duration.DurationInt
import scala.util.Try

object LearningMemoization extends App {

  val jedisPool = new JedisPool("localhost", 6379)
  implicit val customisedRedisCache: Cache[String] = RedisCache(jedisPool)

  def getStringById(id:Int) = s"Hi there I am $id"

  def withCache[A](callback: => A)(implicit cache:Cache[A]):A = Try{
    memoize[Try, A](Some(20.seconds)) {
      callback
    }.getOrElse(callback)
  }.getOrElse(callback)

  println(withCache(getStringById(5)))
}

What I am expecting is after calling  println(withCache(getStringById(5))) It should cache Hi there I am $id for 20 seconds though I change the content from getStringById(id:Int) method but It did not.. Basically what I want is getStringById(5) called when callback is declared.


text:
Q: When creating new programming languages, do you lose performance? This is proving to be a very difficult question for me to figure out how to properly ask.
For example, the Python interpreter is written in C. Say you wrote another interpreter in Python, that got compiled through CPython. And you then intend to run a program through your interpreter. Does that code have to go through your interpreter and then CPython? Or would the new interpreter be self-contained and not require CPython to interpret it's output. Because if it is not a standalone interpreter, then there would be a performance loss, in which case it would seem like all compilers would be written in low level languages until the end of time
EDIT:
PyPy was the very thing that got me wondering about this topic. I was under the impression that it was an interpreter, written in Python, and I did not understand how it could be faster than CPython. I also do not understand how bytecode gets executed by the machine without being translated to machine code, though I suppose that is another topic.

A: You seem to be confused about the distinction between compilers and interpreters, since you refer to both in your question without a clear distinction. (Quite understandble... see all the comments flying around this thread :-))
Compilers and interpreters are somewhat, though not totally, orthogonal concepts:
Compilers
Compilers take source code and produce a form that can be executed more efficiently, whether that be native machine code, or an intermediate form like CPython's bytecode.
c is perhaps the canonical example of a language that is almost always compiled to native machine code. The language was indeed designed to be relatively easy and efficient to translate into machine code. RISC CPU architectures became popular after the C language was already well-adopted for operating system programming, and they were often designed to make it even more efficient to translate certain features of C to machine code.
So the "compilability" of C has become self-reinforcing. It is difficult to introduce a new architecture on which it is hard to write a good C compiler (e.g. Itanium) that fully takes advantage of the hardware's potential. If your CPU can't run C code efficiently, it can't run most operating systems efficiently (the low-level bits of Linux, Unix, and Windows are mainly written in C).
Interpreters
Interpreters are traditionally defined as programs that try to run source code directly from its source representation. Most implementations of BASIC worked like this, back in the good ol' days: BASIC would literally re-parse each line of code on each iteration through a loop.
Modern languages
Modern programming languages and platforms blur the lines a lot. Languages like python, java, or c# are typically not compiled to native machine code, but to various intermediate forms like bytecode.
CPython's bytecode can be interpreted, but the overhead of interpretation is much lower because the code is fully parsed beforehand (and saved in .pyc file so it doesn't need to be re-parsed until it is modified).
Just-in-time compilation can be used to translate bytecode to native machine code just before it is actually run, with many different strategies for exactly when the native code compilation should take place.
Some languages that have "traditionally" been run via a bytecode interpreter or JIT compiler are also amenable to ahead-of-time compilation. For example, the Dalvik VM used in previous versions of Android relies on just-in-time compilation, while Android 4.4 has introduced ART which uses ahead-of-time compilation intsead.
Intermediate representations of Python
Here's a great thread containing a really useful and thoughful answer by @AlexMartelli on the lower-level compiled forms generated by various implementations of Python.
Answering the original question (I think...)
A traditional interpreter will almost certainly execute code slower than if that same code were compiled to "bare metal" machine code, all else being equal (which it typically is not), because the interpreter imposes an additional cost of parsing every line or unit of code every time it is executed.
So if a traditional interpreter were running under an interpreter, which was itself running under an interpreter, etc., ... that would result in a performance loss, just as running a VM (virtual machine) under a VM under a VM will be slower than running on "bare metal."
This is not so for a compiler. I could write a compiler which runs under an interpreter which runs under an interpreter which has been compiled by a compiler, etc... the resulting compiler could generate native machine code that is just as good as the native code generated by any other compiler. (It is important to realize that the performance of the compiler itself can be entirely independent of the performance of the executed code; an aggressive optimizing C compiler typically takes much more time to compile code than a non-optimizing compiler, but the intention is for the resultant native code to run significantly faster.)


text:
Q: How to use Flask url_for in a CSS file? I'm using Flask with HTML and CSS. When this is possible:
<img src="{{ url_for('static', filename='images/planets.jpeg' ) }}">

What do I have to write here to address the same image?
.bgimg-1 { background-image: url('https://i.ytimg.com/vi/J9QOB6hSI-c/maxresdefault.jpg'); }

The solution should look similar to this:
.bgimg-1 { background-image: url('{{ url_for('static', filename='images/planets.jpeg' ) }}'); }

Thank you.

A: You are serving css statically, via /static/css/style.css. When you do this, then Flask does not use Jinja to parse the CSS file as though it were a template.
If, however, you had a route (eg @app.route('/css/<file>')) then you could use the render_template() method to render your CSS file as though it were a jinja template, which would then parse the jinja directives (such as {{url_for()}})

A: You can simply refer to the generated URL in your url_for function.
As an example:
.bgimg-1 {
   background-image: url('/static/images/planets.jpeg');
   min-height: 100%;
}

Also, please note that the CSS itself can be referenced with:
<link rel="stylesheet" href="{{ url_for('static', filename='css/planets.css') }}">

UPDATE:
Alternatively, you can embed your Jinja2 in the style attribute. For example:
<body style="background-image: url({{ url_for('static', filename='images/planets.jpeg') }});">
<!-- HTML TEMPLATE CODE -->
</body>

A: You can't use Jinja directly in the CSS file since you normally don't render it as a template, but there is 3 alternate way to achieve your need:
Method 1
Use correct relative path in your CSS file:
background: url("/static/images/bg.jpg") no-repeat 0px 0px;

Method 2
Put your background line into the template:
<style>
    background: url("{{ url_for('static',filename='images/bg.jpg') }}") no-repeat 0px 0px;
</style>

Method 3
Define a CSS variable in your template:
<style>
    :root {
        --background-url: {{ url_for('static', filename='images/bg.jpg') }}
    }
</style>

Then use it in your CSS file:
background: url("var(--background-url)") no-repeat 0px 0px;

A: I don't have enough reputation points to comment on Grey Li answer.   Method 3 is good - modified to make it work
HTML template
<style>
:root {
    --background-url: url('{{ url_for('static', filename='img/lightning.jpg', _external=True) }}');
}
</style>

CSS
background: var(--default-bg-color) var(--background-url);

A: My requirement was to add a font file in a CSS file.
The static folder structure I used was like:
static
├── css
|   ├── main.css
├── fonts
|   ├── NotoSans-Regular.ttf
├── js
|   ├── index.js

If I used Flask's url_for() function in the main.css file as follows
@font-face {
  font-family: 'NotoSans';
  src: url("{{url_for('static', filename='fonts/NotoSans-Regular.ttf')}}");
}

The request was being sent to

http://127.0.0.1:5000/static/css/static/fonts/NotoSans-Regular.ttf
(Assuming that the server was running on PORT 5000)

So, I replaced it with the following and it worked fine.
@font-face {
  font-family: 'NotoSans';
  src: url("/static/fonts/NotoSans-Regular.ttf");
}


text:
Q: Is Maven better than the ant building tool for deploy an EAR project I am now using Ant 1.8 in my EAR project with JBoss 4.0.5
Technology I am using is JEE 1.5 with Struts 1.2
I have 3 Jars deployed in my EAR directory of JBoss.
Currently ant is used for building the project and it takes around 30second to build the 1GB project.
I want to change my building tool from ANT to Maven ?
Will Maven be more help full and faster ?

A: I think, in that case, that Gradle suits your particular needs better than Maven.
Faster builds

Will Maven be more help full and faster ?

Incremental Builds is a feature the helps making build faster, but Maven itself doesn't support them. I know there exists some plugins that offers out of the box Incremental Builds but I have not use them.
Instead Gradle scales very well and offers you the state-of-art in incremental building: together with "Incremental builds" the other Multi-project builds feature is a big time saver for larger builds.
Reusing your Ant deploy targets

I have 3 Jars deployed in my EAR directory of JBoss.

Don't worry if you think that Gradle isn't as mature as Maven when it comes release deployment: Gradle is the first build integration tool. You can reuse your favourite reliabile Ant deploy targets from Gradle, and moreover you can extend them by importing them in Gradle and writing the extension directly in the Gradle domain specific language, without touching your Ant script
When will comes more mature days in deploying with Gradle you can modify your task in build.gradle deleting the ant deploy target import and using the new deploy gradle plugin: your Gradle task chain will remain the same as it was when you used Ant.


text:
Q: Objective-C version of serviceSubscriberCellularProvidersDidUpdateNotifier for iOS12+? There is this link however it leaves out the iOS 12+ Objective C method. Here's what I have attempted:
Added to the application delegate:
@property (strong, nonatomic) CTTelephonyNetworkInfo *telephonyInfo;

Then in
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    ...

    self.telephonyInfo = [[CTTelephonyNetworkInfo alloc] init];

    self.telephonyInfo.serviceSubscriberCellularProvidersDidUpdateNotifier = ^(NSString *entry) {
        dispatch_async(dispatch_get_main_queue(), ^{
            qDebug() << "User did change SIM" << entry;
        });
    };
    ...
}

But the code never gets executed (by breakpoint or log message) when I remove the SIM. How can i get the notifications in Obj-C in iOS 12+?


text:
Q: What does the console output for 'Object($)' mean? I have a simple html page with nothing but a jquery include..
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
  HELLO WORLD JQUERY
</body>

When I run this page and open developer tools in Chrome and do 'Object($)' on the console, I get the following...
function (a,b){return new m.fn.init(a,b)}

whereas in Firebug I see..
function(a, b)

Could someone tell me what I am looking at here and why its different per browser when they are both reading the same jQuery library?


text:
Q: How to display JavaScript variables in a HTML page without document.write I am trying to display some JavaScript variable on my HTML page.
I was first using document.write() but it use to overwrite the current page when the function was called.
After searching around, the general consensus was that document.write() isn't liked very much. What are the other options?
I found a page suggesting using .innerHTML but that was written in 2005.
A jsFiddle illustrating my problem http://jsfiddle.net/xHk5g/

A: there are different ways of doing this.
one way would be to write a script retrieving a command.
like so:
var name="kieran";
document.write=(name);

or we could use the default JavaScript way to print it.
var name="kieran";
document.getElementById("output").innerHTML=name;

and the html code would be:

i hope this helped :)

A: You could use jquery to get hold of the html element that you want to load the value with.
Say for instance if your page looks something like this,

     ...

And if your javascript (I hope) looks something as simple as this,
function somefunction(){
  var somevalue = "Data to be inserted";
  $("#SecondDiv").text(somevalue);
}

I hope this is what you were looking for.

A: innerHTML is fine and still valid. Use it all the time on projects big and small. I just flipped to an open tab in my IDE and there was one right there.
 document.getElementById("data-progress").innerHTML = "";

Not much has changed in js + dom manipulation since 2005, other than the addition of more libraries. You can easily set other properties such as
   uploadElement.style.width = "100%";

A: If you want to avoid innerHTML you can use the DOM methods to construct elements and append them to the page.
var element = document.createElement('div');
var text = document.createTextNode('This is some text');
element.appendChild(text);
document.body.appendChild(element);

A: You can use javascript to access elements on the page and modify their contents. So for example you might have a page with some HTML markup like so:

    This text will change

You can use javascript to change the content like so...
document.getElementById("MyEdit").innerHTML = "My new text!";

Here is a working example

You can also look at using the JQuery javascript library for DOM manipulation, it has some great features to make things like this very easy.
For example, with JQuery, you could do this to acheive the same result...
$("#MyEdit").html("My new text!");

Here is a working example of the JQuery version

Based on this example you provided in your post. The following JQuery would work for you:
var x = "hello wolrd";
$("p").html(x);

Here is the working version
Using a P tag like this however is not recommended. You would ideally want to use an element with a unique ID so you can ensure you are selecting the correct one with JQuery.

A: Element.innerHTML is pretty much the way to go. Here are a few ways to use it:
HTML

JavaScript
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.results').innerHTML = 'Hello World!';

// Using the jQuery library
$('.results').html('Hello World!');

If you just want to update a portion of a
 I usually just add an empty element with a class like value or one I want to replace the contents of to the main
. e.g.

Hello

Then I'd use some code like this:
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.content .value').innerHTML = 'World!';

// Using the jQuery library
$(".content .value").html("World!");

Then the HTML/DOM would now contain:

Hello World!

Full example. Click run snippet to try it out.

// Plain Javascript Example
var $jsName = document.querySelector('.name');
var $jsValue = document.querySelector('.jsValue');

$jsName.addEventListener('input', function(event){
  $jsValue.innerHTML = $jsName.value;
}, false);

// JQuery example
var $jqName = $('.name');
var $jqValue = $('.jqValue');

$jqName.on('input', function(event){
  $jqValue.html($jqName.val());
});
html {
  font-family: sans-serif;
  font-size: 16px;
}

h1 {
  margin: 1em 0 0.25em 0;
}

input[type=text] {
  padding: 0.5em;
}

.jsValue, .jqValue {
  color: red;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Setting HTML content example</title>

  Enter your name: <input class="name" type="text" value="World"/>

Plain Javascript Example
Hello World

jQuery Example
Hello World

A: hi here is a simple example:
content
 and
var test = 5;
document.getElementById('test').innerHTML = test;

and you can test it here : http://jsfiddle.net/SLbKX/

A: Add an element to your page (such as a div) and write to that div.
HTML:

        <title>Page Title</title>

jQuery:
$('#myDiv').text('hello world!');

javascript:
document.getElementById('myDiv').innerHTML = 'hello world!';

A: Similar to above, but I used (this was in CSHTML):
JavaScript:
var value = "Hello World!"

$('.output').html(value);

CSHTML:


text:
Q: How to get value in object based on another value I could use some help cycling through an object and getting the difference in price between two products.  For example, what is the difference in price between the big hammer and the small hammer?
Here's what I have so far
var myarray = [{product: "big hammer", price: 32},{product: "small hammer", price: 22},{product: "wrench", price: 15},{product: "saw", price: 55}];

getPriceDifference(myarray[0].product);

function getPriceDifference(currentProduct){

   if(currentProduct === "Big Hammer"){

     //do something...this is where I am stuck

   }

}

Thanks in advance.

A: There are multiple ways of iterating over arrays
myarray.map(item => {

})

myarray.foreach(item => {

})

Or if you change the structure of your data to the following, you do not have to iterate.
var products = {
  "big hammer": { price: 32 },
  "small hammer": { price: 22 },
  "wrench": { price: 15 },
  "saw": { price: 55 },
};

function getPriceDifference(product_1, product_2) {
  return Math.abs(products[product_1].price - products[product_2].price);
}

var difference = getPriceDifference("big hammer", "small hammer");
console.log(difference);

A: This works:

var myarray = [{product: "big hammer", price: 32},{product: "small hammer", price: 22},{product: "wrench", price: 15},{product: "saw", price: 55}];

function getPriceDifference(first, second){

   for(var i = 0; i < myarray.length; i++){

   if(myarray[i]['product'] == first) price_first = myarray[i]['price'];
   if(myarray[i]['product'] == second) price_second = myarray[i]['price'];

   }

   return Math.abs(price_first - price_second);
}

console.log(getPriceDifference('small hammer', 'big hammer'));


text:
Q: AngularDart with AngularJS libraries Recently I've started to learn Dart language (purely for fun) and yesterday I read CodeLabs for AngularDart. I went throught all 10 chapters and I've felt in love. Till now I wrote many angularJS apps so I know what are principles of this framework.
But my question is - is there any way to combine AngularJS libraries like RestAngular or Angular-Translate in AngularDart applications? Or even directives like Angular-material or AngularUI?

A: Angular needs full control of the DOM tree it sees as the app (ng-app) It should be possible to use Angular.js and Angular.dart to use non-overlapping parts of the DOM and run one subtree with Angular.dart and another with Angular.js.
It might be possible to call Angular.js services from Angular.dart using dart-js-interop but besides that I don't think they can work together.


text:
Q: Asymptotic behavior of tricky coupled ODE system I am trying to solve numerically the following real-valued system $(f,h)$ on $[0,\infty]$:
$$-h''-\frac{1}{r}h'+\lambda_c h(f^2-1)+4\lambda_h h^3=0$$
$$-f''-\frac{1}{r}f'+\frac{1}{r^2}f+ f(-\lambda_f+2\lambda_c h^2)+\lambda_f f^3=0$$
where $\lambda_h, \lambda_f, \lambda_c $ are positive constants, and with boundary conditions $f(0)=0, f(\infty)=1, h'(0)=0, h(\infty)=0$.  The condition $h'(0)$ is necessary for $h$ to be finite at the origin. We may assume without loss of generality $h(0)>0$, and for simplicity we can set $\lambda_f=\lambda_h=1$.
In order to solve this system, it is helpful to know the asymptotic behavior of $(f,g)$ at $r=0$ and $r=\infty$.
My question is: what is the asymptotic behavior of $(f,h)$ as $r\to \infty$.

I find that at small $r$, $f(r) \sim \alpha r $ and $h(r) \sim a +br^2 +cr^4$ for constants $\alpha, a,b,c$.
At large $r$, if there is no coupling between $f$ and $h$ (i.e $\lambda_c=0$) then it's easy to show $f(r)=1-C / r^2+\mathcal{O}\left(1 / r^4\right)$.
Assuming $f$ has the same form when the coupling is turned on, and assuming $h$ admits a  large-$r$ expansion in powers of $1/r$, I find necessarily to leading order $h \sim K/r$ for some constant $K$. Substituting this and the form for $f$  in the first equation I find $K^2 = (1+2C\lambda_c)/(4\lambda_h)$. The second equation then gives $C = (1+2\lambda_cK^2)/(2\lambda_f)$. There is a real solution $(C,K)$ as long as $\lambda_c^2 < 2\lambda_h\lambda_f$. If no mistakes, this suggests the ansatz $h \propto 1/r$ at large $r$ is inaccurate for larger $\lambda_c$. This likely means $h$ must not admit a power expansion at large $r$.
Nonetheless, numerically solving the system by imposing that $h\propto 1/r$ at large $r$, I find the solution for $\lambda_c=\lambda_f=\lambda_h=1$ looks like this


text:
Q: Encoding tagged unions (sum types) in LLVM I'm trying to encode a tagged union (also known as a sum type) in LLVM and it doesn't seem possible while keeping the compiler frontend platform agnostic. Imagine I had this tagged union (expressed in Rust):
enum T {
    C1(i32, i64),
    C2(i64)
}

To encode this in LLVM I need to know know the size of the largest variant. That in turn requires that I know the alignment and size of all fields. In other words, my frontend would need to

*

*track the size and alignment of all things,

*create a dummy struct (properly padded) to represent the biggest type that can fit any variant (e.g. {[2 x i64]}, assuming the tag can fit in the same word as the i32 field),

*and finally either used packed structs or tell LLVM which "data layout" I assumed, so my computations matches LLVMs

What is the best way currently to encode tagged unions in LLVM?

A: Conceptually, I don't think there's a better way than what you described, except that I wouldn't bother with using the constructed type at the declaration site, since actually accessing the union would be easiest to do through a bitcast anyway.
Here's a code snippet from Clang's getTypeExpansion(), showing it also does this - manually finding the largest field:
const FieldDecl *LargestFD = nullptr;
CharUnits UnionSize = CharUnits::Zero();

for (const auto *FD : RD->fields()) {
  // Skip zero length bitfields.
  if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
    continue;
  assert(!FD->isBitField() &&
         "Cannot expand structure with bit-field members.");
  CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
  if (UnionSize < FieldSize) {
    UnionSize = FieldSize;
    LargestFD = FD;
  }
}
if (LargestFD)
  Fields.push_back(LargestFD);


text:
Q: Does Sitecore's Web Forms For Marketers module offer a way for email subscribers to manage subscriptions? Has anybody had luck using Sitecore's Web Forms For Marketers to manage email subscriptions? I am looking for a solution to allow subscribers a way to opt-out of an email list that they're already subscribed to.
Also, I need to offer them a way to manage multiple subscriptions on one page. Ultimately, they'd just be managing which list/database they're in.
(Ideally, I usually prefer that my clients use a third party email marketing platform, but unfortunately - this is not the case here.)

A: You can check here :
http://sdn.sitecore.net/Products/ECM.aspx Email Campaigner has a form ascx for subscribers .
It can be used on multisites solutions


text:
Q: Android: discard events perceived after a button click At the push of a button the application tries to send a data to a server. If the connection is active, the data is immediately sent, but if the link is down, the system attempts to send for x seconds. In fact, in that period of time, the interface is (intentionally) blocked (the button is illuminated to highlight the current operation). The problem is that if the user starts to press other buttons, the events are heard and when the connection becomes active, it performs all the operations related to those events.
How can I prevent it?
How to prevent that How to prevent each event related to other buttons to be processed?
Any suggestions would be very appreciated.
EDIT
I've already tried to check a flag when the button is pressed, unfortunately when the flag is re-setted, all events are catched and executed:
public void onClick(View v) {
    switch(v.getId())
    {

    case R.id.button1:  //when sendData() is trying to send the message, I don't want to that this code is executed
       if(flagConf  == 1)
       {
                ...do something...
       }
       break;
    case R.id.buttonConfirm:

        if(myFlag  == 1)    //to avoid multiple touch of this button
        {
            ...do something...
            myFlag = 0;
            sendData();
            if(dataSent)
             ...do something...
            else
            ...do something...
            myFlag = 1;  //I set this flag to 1 because, if message is not sent, the user have to re-pressed the buttonConfirm and try again
        }
     break;
    }
 }

And on other button listeners:
Thanks

A: You could simply use a flag that is set to something like boolean = true; while the data is processing. Then check in each Button in the onClick
public void onClick(View v)
{
     if (!sending)
     {
         // do stuff
     }
}

if sending is true then the Button will do nothing. Remember to set the flag back to false when you are done processing your data or whatever. You also could use buttonName.setEnabled(false);then back totrue` after after you are done.
Side Note: if this operation takes very long at all (maybe more than a second or two), I would discourage against not allowing them to do anything as people have become very impatient creatures. No one wants to sit and look at a spinning circle for several seconds. However, if you choose to do this then you may want to show some message so they know why the Buttons aren't working

A: I had a similar problem. And there's a nice and neat way to solve that.
My connections to the server was done through a class that extended AsyncTask. That way, every time I pressed the button, I would check if the task was running. If it wasn't, it would generate a new task and would execute that.
public void onClick(View v) {
    if (updateThread == null){

        updateThread = new UpdateThreadClass();
        updateThread.execute();
    }
}

Then create the AsyncTask like:
   public class UpdateThreadsClass extends AsyncTask<String, Void, Boolean> {
    @Override
    protected Boolean doInBackground(String... params) {

        // Your code
    }

    @Override
    protected void onPostExecute(final Boolean success) {

        // Execute after completing the connection
    }
}

Declare the variable updateThread as global then your good to go.
If you want, you can either activate a progressive bar on your XML by changing the visibility ( .setVisibility(View.VISIBLE) or .setVisibility(View.Gone) inside the onClick )before and after the task is done, or you can can do the same for the button.
Edit
You can put the progressive bar in the XML like so:
<ProgressBar
            android:id="@+id/loading_screen"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:gravity="center_vertical|center_horizontal"
            android:visibility="gone"/>

Then after clicking the button, just do like loadingScreen = (ProgressBar) findViewById(R.id.loading_screen) and set the visibility VISIBLE.


text:
Q: Android - connect to MySQL I know, there will be duplicates on this topic, but solutions I found were like 2 years old, and not working for me, so thats why I am asking for topic update.
Question is simple: How to connect my Android device to MySQL database?
I have followed this old topic from Feb 2013 (ofc with a comparsion to other related topics, which were actually almost the same).
https://stackoverflow.com/a/14982316/4256313
I have found library from the solution, the mysql-connector-java-3.0.17-ga-bin.jar
After beeing not succesfull, I also tried newer version of this library, mysql-connector-java-5.1.23-bin.jar
Both libraries were added to project following this video-guide:
https://www.youtube.com/watch?v=dpuJPoXkFG4
And now my personal solution:
I have 4 fields in Main Activity, for Host, port, name and password.
Main activity looks like this (nothing really special here):
            TextView txtHost;
            TextView txtPort;
            TextView txtLoginName;
            TextView txtPassword;
            Button login;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                txtHost = (TextView) findViewById(R.id.txtHost);
                txtPort = (TextView) findViewById(R.id.txtPort);
                txtLoginName = (TextView) findViewById(R.id.txtLoginName);
                txtPassword = (TextView) findViewById(R.id.txtPassword);
                login = (Button) findViewById(R.id.btnLogin);

            }

        //this is function bind to Login Button.
        // I need to do a connection in static class to preserve it for another activities

public void klik(View view){

                ConnCore.ConnCoreStatic.servername = txtHost.getText().toString();
                ConnCore.ConnCoreStatic.port = txtPort.getText().toString();
                ConnCore.ConnCoreStatic.name = txtLoginName.getText().toString();
                ConnCore.ConnCoreStatic.pass = txtPassword.getText().toString();

                if(ConnCore.ConnCoreStatic.DBConn(MainActivity.this)==true){
                Intent inent = new Intent(this, TableRows.class);

                startActivity(inent);

                }

            }

And here is my static method handling the connection:
public  class ConnCore {
 public static class ConnCoreStatic{

     static String servername;
     static String port;
     static String name;
     static String pass;
     static Connection mysqlConn;
     static List<String> DBResponse;

static boolean DBConn(Context c){

        try{
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            }
        catch(Exception e){
        AlertDialog alertDialog = new AlertDialog.Builder(c).create();
        alertDialog.setTitle("Error");
        alertDialog.setMessage("Could not initialize driver");
        alertDialog.show();
        return false;
            }

        try{ //Toast just for me, checking if data for conn function is correct
           Toast.makeText(c, "jdbc:mysql://"+servername+":"+port+name+pass,
                     Toast.LENGTH_LONG).show();
           mysqlConn = DriverManager.getConnection(servername+":"+port,name,pass);

             return true;
         }
         catch(Exception e){
             AlertDialog alertDialog = new AlertDialog.Builder(c).create();
             alertDialog.setTitle("Error");
             alertDialog.setMessage("Could not login to database");
             alertDialog.show();
             return false;
         }

     }

 }

}

I have also added INTERNET permission to android manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

I have also included (hopefully) all needed libraries in my static class.
import java.sql.*;

And where is actually my problem?
Android is not connecting. This part always ends in catch block. And I am pretty sure, I have right connection access, for testing purposes, I use db I am frequently connecting to from my PC.
  try{
        mysqlConn = DriverManager.getConnection(servername+":"+port,name,pass);

                     return true;
        }

   catch(Exception e){
          AlertDialog alertDialog = new AlertDialog.Builder(c).create();
          alertDialog.setTitle("Error");
          alertDialog.setMessage("Could not login to database");
          alertDialog.show();
          return false;
                 }

As an adress, I tried I think all combinations I have found in examples in this problem:
jdbc:mysql://XXX.XXX.XXX.XXX:YYYY
jdbc:mysql://XXX.XXX.XXX.XXX:YYYY/database_name (dont want that, just trying)
XXX.XXX.XXX.XXX:YYYY
XXX.XXX.XXX.XXX:YYYY/database_name (dont want that, just trying)

Also just for eliminating mistake from some conversion of strings from UI elements, I wrote down the connection data in code.
Still not working. Still no access.
Nor connected to PC (where phone gets internet through USB from PC), nor disconnected from pc, running on wifi directly or on mobile data directly.
I dont know, if it is just my feeling, but even on PC, it takes 0.5 - 2 sec to  get connected. Here, it seems like the alert dialog is shown almost immediately, like it have not even tried to get connected.
What is wrong here?
Please, can you help?
Thak you in advance.
//EDITS BASED ON COMMENTS:
Try/catch block throws
"java.sqlException: No suitable Driver"

//FROM ONE ERROR TO ANOTHER
I have succesfully added a driver.
3.0.17 is outdated, need to use mysql-connector-java-5.1.23-bin.jar
In Adress, there has to be "jdbc:mysql://" prefix
Now have this error:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
  Communications link failure
The last packet sent successfully to the server was 0 milliseconds
  ago. The driver has not recived any packets form the server

Still have the right connection data, and still looks like android does not even try to connect. Same error on wifi, phone data, shared computer internet acces, or even disconnected from internet.
//After more digging:
I have found a different way, how to pass connection data to JDBC:
jdbc:mysql://XXX.XXX.XXX.XXX:YYYY?user=root&password=test&autoReconnect=true&failOverReadOnly=false&maxReconnects=10
Well, now, it says, it tries to connect to this IP 10 times, now with error:

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
  Could not create connection to database server. Attempted reconnect 10
  times. Giving up.

Also the Android studio in "Android monitor" says:

I/System.out: [CDS]connect[/XX.XX.XXX.XX:3306] tm:90

But I checked the log on my MySQL server, and there is no incomming connection.
Any suitable for android?


text:
Q: jquery modal box in jsp page with dynamic ajax content I want to create modal popup box using jquery depending on the clicked tr element of the page.
but I couldn't put together my mind to use jquery with this purpose.
the structure of tr is
<image></image>
 each  element sends my jsp page with the id. ( let's say <a href ="target.jsp?id=<dynamic_id_here>">
what should I do to show user the target.jsp's result on the same page with a modal popup ?
thanks in advance..

A: Here's how I'd approach it...
For the modal dialog, I really recommend using "JQuery UI", which comes with a nice-looking modal dialog.
http://jqueryui.com/demos/dialog/#modal
For the ajax call, most of what you need is here within jQuery already:
http://api.jquery.com/jQuery.ajax/
So, in brief, you'd create a div somewhere invisible on the page, ready to receive your text:

Loading

You'd need the anchor to look something like this.
For custom_id = 123:

Then, to launch the dialog, you'd need to have something like this inside a script tag.
$( "#anchor_123" )
.click(function() {
    $( "#dialog-modal" ).dialog({
        height: 140,
        modal: true
    });
            $.ajax({
                    url: "target.jsp?id=123",
                    success: function(data){
                        $('#dialog-modal p').html(data);
                    }
            });

    });

I'll leave you to work out how to dynamically set the custom_id in jquery. This should set you on your way.
HTH


text:
Q: Win32 GUI change value with button I'm working with CSV files. I have little program that shows data with ID, but I need to change ID with button and input field. Right now i can mannualy change int i = #; But I need field, where user enter his number, and then programm show or change data.
case WM_PAINT:
    {

        hdc = BeginPaint(hwnd,&ps);
        TextOut(hdc,    5,        5,      txt_companyName,    _tcslen(txt_companyName));
        TextOut(hdc,    110,      5,      txt_programName,    _tcslen(txt_programName));
        /* Headers */
        TextOut(hdc,    5,        23,     txt_opened,         _tcslen(txt_opened));
        TextOut(hdc,    250,      23,     txt_time,           _tcslen(txt_time));
        TextOut(hdc,    290+15,   23,     txt_input,          _tcslen(txt_input));
        TextOut(hdc,    428+15,   23,     txt_time,           _tcslen(txt_time));
        TextOut(hdc,    468+25,   23,     txt_timeSpent,      _tcslen(txt_timeSpent));
        TextOut(hdc,    578+25,   23,     txt_timeRemain,     _tcslen(txt_timeRemain));
        /* Data printing in row */

        int i = 3;
        std::string data_component_label = getElementFromFileLine("data.csv",i,8,0);
        std::string data_component_mslLvl = getElementFromFileLine("data.csv",i,8,1);
        std::string data_component_opened = getElementFromFileLine("data.csv",i,8,2);
        std::string data_component_timeOpened = getElementFromFileLine("data.csv",i,8,3);
        std::string data_component_input = getElementFromFileLine("data.csv",i,8,4);
        std::string data_component_timeInput = getElementFromFileLine("data.csv",i,8,5);
        std::string data_component_timeSpent = getElementFromFileLine("data.csv",i,8,6);
        std::string data_component_timeRemain = getElementFromFileLine("data.csv",i,8,7);
        //std::string data_component_Status = getElementFromFileLine("data.csv",2,8,2);

        //TextOut(hdc,    5,        23+18,    data_component_opened,         _tcslen(data_component_opened));
        TextOut(hdc,    5,        23+18,    data_component_opened.c_str(),         _tcslen(data_component_opened.c_str()));
        TextOut(hdc,    250,      23+18,    data_component_timeOpened.c_str(),     _tcslen(data_component_timeOpened.c_str()));
        TextOut(hdc,    290+15,   23+18,    data_component_input.c_str(),          _tcslen(data_component_input.c_str()));
        TextOut(hdc,    428+15,   23+18,    data_component_timeInput.c_str(),      _tcslen(data_component_timeInput.c_str()));
        TextOut(hdc,    468+25,   23+18,    data_component_timeSpent.c_str(),      _tcslen(data_component_timeSpent.c_str()));
        TextOut(hdc,    578+25,   23+18,    data_component_timeRemain.c_str(),     _tcslen(data_component_timeRemain.c_str()));
        EndPaint(hwnd,&ps);
    }
    break;

I have a button and input in WM_CREATE and WM_COMMAND, but when I trying to use buffer in WM_PAINT, for example print it in MessageBox, expected a message box with data, user input, however, there is compile error -

main.cpp|error: 'buffer' was not declared in this scope

so I need somehow get data from WM_COMMAND to WM_PAINT
case WM_CREATE:
    {

        hEdit=CreateWindowEx(WS_EX_CLIENTEDGE,
            "EDIT",
            "",
            WS_CHILD|WS_VISIBLE|
            ES_MULTILINE|ES_AUTOVSCROLL|ES_AUTOHSCROLL,
            95,
            80,
            200,
            30,
            hwnd,
            (HMENU)IDC_MAIN_EDIT,
            GetModuleHandle(NULL),
            NULL);
        HGDIOBJ hfDefault=GetStockObject(DEFAULT_GUI_FONT);
        HWND hWndButton=CreateWindowEx(NULL,
            "BUTTON",
            "NEXT",
            WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_DEFPUSHBUTTON,
            5,
            80,
            75,
            30,
            hwnd,
            (HMENU)IDC_MAIN_BUTTON,
            GetModuleHandle(NULL),
            NULL);

            SendMessage(hWndButton,
                WM_SETFONT,
                (WPARAM)hfDefault,
                MAKELPARAM(FALSE,0));

    }
        break;
case WM_COMMAND:
    switch(LOWORD(wParam))
    {
        case IDC_MAIN_BUTTON:
        {
            char buffer[265];

            SendMessage(hEdit,
                        WM_GETTEXT,
                        sizeof(buffer)/sizeof(buffer[0]),
                        reinterpret_cast<LPARAM>(buffer));

break;


text:
Q: Can't get the right answer while finding angle in C# I am doing this Introduction To Unity course from coursera. I have reached at first programming assignment which is to find the hypotenuse and angle of two points. I almost got the code right but a few answers are right and a few are wrong! I don't know what is wrong.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProgrammingAssignment1
{
    // IMPORTANT: Only add code in the section
    // indicated below. The code I've provided
    // makes your solution work with the
    // automated grader on Coursera

    /// <summary>
    /// Programming Assignment 1
    /// </summary>
    class Program
    {
        // x and y coordinates for points
        static float point1X;
        static float point1Y;
        static float point2X;
        static float point2Y;

        /// <summary>
        /// Calculates angle and distance between two points
        /// </summary>
        /// <param name="args">command-line args</param>
        static void Main(string[] args)
        {
            // loop while there's more input
            string input = Console.ReadLine();
            while (input[0] != 'q')
            {
                // extract point coordinates from string
                GetInputValuesFromString(input);

                // Add your code between this comment
                // and the comment below. You can of
                // course add more space between the
                // comments as needed

                float deltaX = point1X - point2X;
                float deltaY = point1Y - point2Y;

                float hypotenuse = (float)Math.Sqrt(Math.Pow(deltaX, 2) + Math.Pow(deltaY, 2));

                float angleInRadians = (float)Math.Atan2(deltaY, deltaX);
                float angleInDegrees = angleInRadians * 180 / (float)Math.PI - 180;

                Console.WriteLine(hypotenuse + " " + angleInDegrees);

                // Don't add or modify any code below
                // this comment
                input = Console.ReadLine();
            }
        }

        /// <summary>
        /// Extracts point coordinates from the given input string
        /// </summary>
        /// <param name="input">input string</param>
        static void GetInputValuesFromString(string input)
        {
            // extract point 1 x
            int spaceIndex = input.IndexOf(' ');
            point1X = float.Parse(input.Substring(0, spaceIndex));

            // move along string and extract point 1 y
            input = input.Substring(spaceIndex + 1);
            spaceIndex = input.IndexOf(' ');
            point1Y = float.Parse(input.Substring(0, spaceIndex));

            // move along string and extract point 2 x
            input = input.Substring(spaceIndex + 1);
            spaceIndex = input.IndexOf(' ');
            point2X = float.Parse(input.Substring(0, spaceIndex));

            // point 2 y is the rest of the string
            input = input.Substring(spaceIndex + 1);
            point2Y = float.Parse(input);

            #region Unfortunately, Mono doesn't have a Split method!
            //string[] values = input.Split(' ');
            //point1X = float.Parse(values[0]);
            //point1Y = float.Parse(values[1]);
            //point2X = float.Parse(values[2]);
            //point2Y = float.Parse(values[3]);
            #endregion

        }
    }
}

You can see the code I added after the Add Your Code comment, so I have succeeded in finding the hypotenuse correctly but angle is where I am going wrong!
float angleInRadians = (float)Math.Atan2(deltaY, deltaX);
float angleInDegrees = angleInRadians * 180 / (float)Math.PI - 180;

These are the two lines to find the angles. So when I input points 5 5 4 4 it gives me correct angle with  Math.PI - 180 in the second line but at the same time when I input 2 2 4 4 it gives me wrong answer.
So I played with it for a while and added Math.PI + 180, so this time I got the right angle for 2 2 4 4 and wrong answer for 5 5 4 4. I just don't know where I am going wrong!
Some help would be highly appreciated!

A: Try this:
//radians into degrees
var angle = (radians * (180 / Math.PI) + 360) % 360;


text:
Q: a.s convergence of $X_n=X^n$, where $X\sim U(0,1)$ Study the a.s convergence of $X_n=X^n$, where $X\sim U(0,1)$
My attemp:
My definition of a.s convergence is : A sequence of r.v $X_n$converges a.s to $X$ $\iff$ $\mathbb{P}(X_n\not\to X)=0$.
$\mathbb{P}(X_n\not\to X)=\mathbb{P}(X^n\not\to X)=0$
If $X \in [0,1), X^n\to 0$
If $X =1, X^n\to 1$
If $X \in [1,+\infty), X^n\to \infty$
If $X \in [-\infty,0),  X^n\to +\infty,$ if $n$ is even and to $-\infty $if $n$ is odd$
I am on the right track here?
should I say that  $(X^n\not\to X) = \mathbb{R}\setminus (0,1)$ ? or is it just $(X^n\not\to X) = \{1\}$  because a uniform variable takes values only on $[0,1]$ and I should not be analyzing the values outside of it? I am also not sure if there is convergence to 1 for X=1, an to 0 for X in [0,1)

A: You are making it too complicated. $1=P(0<X<1)\leq P(X^{n} \to 0)$ because $t^{n}\to 0$ whenever $0<t<1$. This finishes the proof.


text:
Q: I'm trying to use antd's Table component in 18.1.0 to no avail, even though I can successfully in version 17 I'm trying to use ant design table in 18.1.0.  However I can't get the table to render when I use it as prescribed in the documentation
<Table columns={columns} dataSource={data} />
I've ruled out all of the obvious things (I did use columns and data earlier when grabbing the data from the API, etc.)
I'm actually getting no errors at all when running it in localhost (npm start launches fine, no browser or VS code terminal warnings or errors), it's just not rendering.
If I put something else like 'testing' in the return for that table component, it renders just fine. I think I've narrowed it dow to the difference between react 17 and 18 versions:
it'll work in 17.x.x. using ReactDOM.render  in index.js (that's literally the only change between the code I have in 17 vs 18, the component's code is identical in both).
but I can't use ReactDOM.render  in 18. when I tried it, it shows error that 18 doesn't support  ReactDOM.render ).so it seems I have to use 18's way of rendering?:
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render
But again, it won't render antd's table comp  data.
I have no clue how to fix. I assume I somehow need to change 18's index.js so it'll render data from antd's table comp?
Any ideas are much appreciated.


text:
Q: Calculating day of the week XSL Trying to calculate day of the week number from date. Found some examples in the internet, but  instead of day of the week number i see this : NaN.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:strip-space elements="*"/>
  <xsl:output indent="yes"/>

  <xsl:template match="node()">
    <xsl:copy>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="date">
    <xsl:copy>
      <xsl:call-template name="date-format">
        <xsl:with-param name="date-time" select="."/>
      </xsl:call-template>
    </xsl:copy>
  </xsl:template>

  <xsl:template name="date-format">
    <xsl:param name="date-time"/>
    <xsl:param name="date" select="substring-before($date-time,'T')"/>
    <xsl:param name="year" select="substring-before($date,'-')"/>
    <xsl:param name="month"
          select="substring-before(substring-after($date,'-'),'-')"/>
    <xsl:param name="day" select="substring-after(substring-after($date,'-'),'-')"/>

    <xsl:variable name="a" select="floor((14 - $month) div 12)"/>
    <xsl:variable name="y" select="$year - $a"/>
    <xsl:variable name="m" select="$month + 12 * $a - 2"/>

    <xsl:value-of select="($day + $y + floor($y div 4) - floor($y div 100)
    + floor($y div 400) + floor((31 * $m) div 12)) mod 7"/>

  </xsl:template>

</xsl:stylesheet>

.
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="test2.xsl" type="text/xsl" ?>

<document>
  <date>2013-01-01</date>
  <date>2013-05-24</date>
  <date>2013-12-25</date>
  <date>1957-07-13</date>
  <date>1776-07-04</date>
</document>

A: The following stylesheet:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="date">
    <xsl:call-template name="day-of-week">
        <xsl:with-param name="date" select="."/>
    </xsl:call-template>
</xsl:template>

<xsl:template name="day-of-week">
    <xsl:param name="date"/>

    <xsl:variable name="year" select="substring($date,1, 4)"/>
    <xsl:variable name="month" select="substring($date, 6, 2)"/>
    <xsl:variable name="day" select="substring($date, 9, 2)"/>

    <xsl:variable name="a" select="floor((14 - $month) div 12)"/>
    <xsl:variable name="y" select="$year + 4800 - $a"/>
    <xsl:variable name="m" select="$month + 12*$a - 3"/>

    <xsl:variable name="JDN" select="$day + floor((153*$m + 2) div 5) + 365*$y + floor($y div 4) - floor($y div 100) + floor($y div 400) - 32045" />

    <xsl:value-of select="($JDN + 1) mod 7" />
</xsl:template>

</xsl:stylesheet>

when applied to your input example:
<document>
  <date>2013-01-01</date>
  <date>2013-05-24</date>
  <date>2013-12-25</date>
  <date>1957-07-13</date>
  <date>1776-07-04</date>
</document>

will return the following result:
<?xml version="1.0" encoding="UTF-8"?>
25364

Note:
The main problem with your attempt is this:
<xsl:param name="date" select="substring-before($date-time,'T')"/>

Your input has dates, not date-times, and they do not contain "T".


text:
Q: DAVID enrichment analysis using R version 4.1.2 I need to run DAVID enrichment analysis on list of genes I got after differential expression analysis and I found that the package 'RDavidWebService' is not available any more for the new releases of R and bioconductor.
Is someone know about an alternative way to run DAVID analysis on list of genes ?
[I also found the clusterProfiler package but its DAVID function uses RDavidWebService so I cant use it).
Thanks a lot :)
run DAVID enrichment analysis with the new version of R


text:
Q: Can't find virtualization option in BIOS So I have an AMD Ryzen 5 3600 and an Asus Motherboard Prime B550-K. I've tried updated the bios and enabling and disabling hyper-v but still can't find the optio. Running Windows 10 Pro btw

A: I finally found the option I was looking for, it was under SVM, once I enabled it my problem was solved.

A: I was looking up ASUS motherboards and noticed that they mostly use Asus UEFI BIOS (somewhat same layout as click bios) and to enable virtualization follow these steps.

*

*Press F2 key at startup to go into the BIOS.

*Press the right arrow key to go into the Advanced tab then select Virtualization Technology then press the enter key.

*Select Enabled and press the enter key.

*Press the F10 key and select Yes and press the Enter key to save changes and reboot.


text:
Q: How can I pass a CustomButton component to createAnimatedComponent? I'm trying to make a CustomButton animate! I use createAnimatedComponent and ref. The button shows up but the animation does not work! I tried to comment out the colors in the CustomButton just in case the animated colors from the createAnimatedComponent didn't show up because of them, but nothing.
Any help would be appreciated.
CustomCreateAnimatedComp.js
const AnimatedButton = Animated.createAnimatedComponent(CustomButton);

export default class CustomCreateAnimatedComp extends Component {
  state = {
    animation: new Animated.Value(0)
  };
  // for the ref button
  // Here our customButton gets detected by animated,
  // and we forward the setNativeProps to native button
  setNativeProps = props => {
    this.button.setNativeProps(props);
  };

  startAnimation = () => {
    Animated.timing(this.state.animation, {
      toValue: 1,
      duration: 1500
    }).start(() => {
      Animated.timing(this.state.animation, {
        toValue: 0,
        duration: 300
      }).start();
    });
  };

  render() {
    const animatedColor = this.state.animation.interpolate({
      inputRange: [0, 1],
      outputRange: [["white", "black"]
    });

    return (
      <View style={styles.container}>
        {/* Animated works also on props (like color) not only styles */}
        <AnimatedButton
          ref={(ref) => (this.button = ref)}
          title="Press Me"
          onPress={this.startAnimation}
          color={animatedColor}
        />
      </View>
    );
  }
}

CutomButton.js
export default class CustomButton extends React.Component {
  render() {
    return (
      <TouchableWithoutFeedback
        onPress={this.props.onPress}
        style={{ ...this.props.touchableStyle }}
      >
        <View
          onPress={this.props.onPress}
          style={{ ...styles.buttonStyle, ...this.props.style }}
        >
          <Text style={{ ...styles.text, ...this.props.textStyle }}>
            {this.props.title}
          </Text>
        </View>
      </TouchableWithoutFeedback>
    );
  }
}

const styles = StyleSheet.create({
  buttonStyle: {
    marginVertical: 5,
    paddingBottom: 3,
    borderRadius: 15,
    alignSelf: "center",
    backgroundColor: "tomato",
    elevation: 7
  },
  text: {
    color: "white",
    textAlign: "center"
  }
});

Thanks in advance.

A: After a hint from @Jaydeep Galani I checked the styles in the CustomButton and I did the following changes and now the title of the button animates.
Thanks Jaydeep!
  <Text style={[ styles.text, {color: this.props.color} ]}>
            {this.props.title}
  </Text>

Here are the final changes so the backgroundColor would also work.
export default class CustomButton extends React.Component {
  render() {
    return (
      <TouchableWithoutFeedback
        onPress={this.props.onPress}
      >
        <View
          onPress={this.props.onPress}
          style={[ styles.buttonStyle, {backgroundColor: this.props.backgroundColor}]  }
        >
          <Text style={[ styles.text, {color: this.props.color} ]}>
            {this.props.title}
          </Text>
        </View>
      </TouchableWithoutFeedback>
    );
  }
}

render() {
    const animatedColor = this.state.animation.interpolate({
      inputRange: [0, 1],
      outputRange: ["white", "black"]
    });

    const animatedBackgroundColor = this.state.animation.interpolate({
      inputRange: [0, 1],
      outputRange: ["tomato", "lightblue"]
    });

    return (
      <View style={styles.container}>
        {/* Animated works also on props (like color) not only styles */}
        <AnimatedButton
          ref={(ref) => (this.button = ref)}
          title="Press Me"
          onPress={this.startAnimation}
          color={animatedColor}
          backgroundColor={animatedBackgroundColor}
          // textStyle={animatedColor}
        />
      </View>
    );
  }


text:
Q: how to add mongodb replica Set in spring boot project i am new to mongodb repleca set

spring boot 2.2.2
mongo db driver 3.12.1

spring.data.mongodb.uri=mongodb://user:pass@server1:27017,server2:27017,server3:27017/DB?replicaSet=mongodb_rs

always getting the following error while fetching data from DB

19-02-2020 12:05:27.753 [http-nio-2053-exec-1] INFO  org.mongodb.driver.cluster.info - No server chosen by com.mongodb.client.internal.MongoClientDelegate$1@594215be from cluster description ClusterDescription{type=REPLICA_SET, connectionMode=MULTIPLE, serverDescriptions=[]}. Waiting for 30000 ms before timing out


text: Q: How to order pages in redirect page selection We have thousands of pages in our CQ repository and the repository is not (or doesn't appear to be) ordered. When we're creating redirect pages the page selection dialog is not ordered and it makes it extremely difficult to find the page we're interested in. Is there some way to tell CQ to order the results in the built-in components?


text:
Q: Unable to date range query results in MySQL I am having trouble querying the correct date range. My query does not seem to consider the Where clause for post_date > (date provided).
            SELECT `code`,
                `description`,
                SUM( IF( month = 3 && year = 2018, monthly_quantity_total, 0 ) ) AS monthlyqt,
                SUM( IF( month = 3 && year = 2018, monthly_price_total, 0 ) ) AS monthlypt,
                SUM( monthly_quantity_total ) AS yearlyqt,
                SUM( monthly_price_total ) AS yearlypt
            FROM (
                SELECT `invoices_items`.`code`,
                    `invoices_items`.`description`,
                    SUM( invoices_items.discounted_price * invoices_items.quantity_supplied ) AS monthly_price_total,
                    SUM( invoices_items.quantity_supplied ) AS monthly_quantity_total,
                    YEAR( invoices_items.datetime_created ) AS year,
                    MONTH( invoices_items.datetime_created ) AS month
                FROM `invoices_items`
                JOIN `invoices` ON `invoices`.`id` = `invoices_items`.`invoice_id`
                WHERE `invoices`.`is_finalised` = 1
                AND `invoices`.`post_date` > 2018-02-28
                AND `invoices_items`.`type` = 1
                GROUP BY `year`, `month`, `invoices_items`.`code`

                UNION ALL

                SELECT `credit_notes_items`.`code`,
                    `credit_notes_items`.`description`,
                    SUM( credit_notes_items.discounted_price * credit_notes_items.quantity_supplied * -1 ) AS monthly_price_total,
                    SUM( credit_notes_items.quantity_supplied ) AS monthly_quantity_total,
                    YEAR( credit_notes_items.datetime_created ) AS year,
                    MONTH( credit_notes_items.datetime_created ) AS month
                FROM `credit_notes_items`
                JOIN `credit_notes` ON `credit_notes`.`id` = `credit_notes_items`.`credit_note_id`
                WHERE `credit_notes`.`is_finalised` = 1
                AND `credit_notes`.`post_date` > 2018-02-28
                AND `credit_notes_items`.`type` = 1
                GROUP BY `year`, `month`, `credit_notes_items`.`code`
            ) AS sub
            GROUP BY code;

There are basically 4 tables being queried here. invoices, invoices_items, credit_notes and credit_notes_items.
table 1 - invoices
id    post_date    is_finalised
1     2018-01-01   1
2     2018-02-01   1
3     2018-03-01   1

table 2 - invoices_items
id    invoice_id    code    description    discounted_price    quantity_total    type
1     1             TEST-01 Test product   9.99                1                 1
2     1             TEST-01 Test product   9.99                2                 1
3     2             TEST-01 Test product   9.99                5                 1
4     3             TEST-01 Test product   9.99                5                 1

I have give some example rows above. From the table 1 and 2 above the desired result should be;
Desired Output
code    description    monthyqt    monthlypt    yearlyqt    yearlypt

TEST-01 Test product   5           49.95        5           49.95

However the output I am receiving is as below;
Received Output
code    description    monthyqt    monthlypt    yearlyqt    yearlypt

TEST-01 Test product   5           49.95        13          129.87

The query works as intended except for the date range I am trying to achieve by using the Where clause. You can see I am trying to filter out any row which are not matching invoices.post_date > 2018-02-28 (and also credit_notes.post_date > 2018-02-28).
I am not sure what I have done wrong here but any help will be much appreciated.
Thanks in advance.

A: I worked it out. Basically the variable which was parsing the date value needed to be encapsulated in single quotes.
e.g.
invoices.post_date > '2018-02-28'

It's always something this simple which throws you off.


text:
Q: Serves images with low resolution custom logo WordPress in my theme I use custom logo WordPress and set the with=108px and height=49 in mobile version of site give me Serves images with low resolution Expected size=324 x 258 how can fix this ?
<img src="http://127.0.0.1/wp-content/uploads/2021/01/flashing-logo.png" alt="" title="flashing-logo" width="108" height="86" srcset="http://127.0.0.1/wp-content/uploads/2021/01/flashing-logo.png" size="(max-width: 100px) 100vw, 100px">


text:
Q: Prove that $pe^{\alpha q} + qe^{- \alpha p} \le e ^ {\alpha^2/2}$ Prove that,
$$pe^{\alpha q} + qe^{- \alpha p} \le e ^ {\alpha^2/2}$$
where $p$ and $q$ are the probabilities of success and failure in a Bernoulli trial ($0 \le p \le 1, 0 \le q \le 1, p + q = 1$) and $\alpha > 0$.
I tried a bunch of things, but I cannot figure out how to approach it.

A: let $f(x)=e^{\frac{x^2}{2}}-(pe^{qx}+qe^{-px})$, we will prove $f(x)$ is mono increasing function when $x\ge0$,ie:
$f'(x)>0 \iff xe^{\frac{x^2}{2}}-(pqe^{qx}-pqe^{-px})>0$, it is not trivial,then we prove $f'(x)$ is also mono increasing function, ie:
$f''(x)=e^{\frac{x^2}{2}}+x^2e^{\frac{x^2}{2}}-pq(qe^{qx}+pe^{-px})>0 \iff e^{\frac{x^2}{2}} > pq(qe^{qx}+pe^{-px}) \iff pq \le \frac{1}{4} $
$e^{\frac{x^2}{2}}> \dfrac{1}{4}(qe^{qx}+pe^{-px}) \iff 4e^{\frac{x^2}{2}}>e^{qx}+e^{-px} \iff 4e^{\frac{x^2}{2}}>e^x+1 \iff e^{\frac{x^2}{2}}\ge 1, 3e^{\frac{x^2}{2}}>e^x \iff 3e^{\frac{x^2}{2}-x}>1 \iff 3e^{\frac{(x-1)^2}{2}-\frac{1}{2}}>1 \iff 3>\sqrt{e}$
$f'(0)=0 \implies f'(x)\ge 0 \implies f(0)=0,f(x)\ge0$
QED.


text:
Q: get all the contact name from Account Query list acc=[select id,name,(select name from contacts) from Account];
 For(Account Act:acc){
List con=Act.contacts;
system.debug('The Contact Name Is'+ con.name );
}
I want to debug all the contact name without using for loop to parse the contacts data from the "acc".
I am new at salesforce and don't know how to do this so plzz help. Plzz Ignore If any Mistakes u notice above

A: The child records are a collection.
for (Account record : [/*query*/])
{
    List<Contact> children = record.Contacts;
    for (Contact child : children)
    {
        system.debug(child);
    }
}


text:
Q: Not able to start Kafka-Minion container Not able to start kafka-minion container.
Getting
{"level":"fatal","msg":"Error parsing env vars into opts. required key KAFKA_BROKERS missing value","time":"2020-12-19T05:16:32Z"}

I am running below command:

docker run -ti --rm -p 9408:9408 toomasj/kafka-minion --kafka.server=XXX.XXX.XX.X:9092 --KAFKA_BROKERS=0:9092

here:
9408 is the port where i am exposing the minion for Prometheus.
and in "KAFKA_BROKERS=0:9092" 0 is the broker id.

A: The way to pass env variables to docker containers is using one of these:

*

*--env <KEY>=<VALUE>

*-e <KEY>=<VALUE>
So the correct syntax for your command would be:
docker run -ti --rm -p 9408:9408 --env KAFKA_BROKERS=0:9092
toomasj/kafka-minion  --kafka.server=XXX.XXX.XX.X:9092

or
docker run -ti --rm -p 9408:9408 -e KAFKA_BROKERS=0:9092
toomasj/kafka-minion --kafka.server=XXX.XXX.XX.X:9092

Check the documentation here for more info about docker run commands.
Thanks to OneCricketeer for correcting me, I initially put the env part at the end of the command, which is incorrect. The syntax is docker run [OPTIONS] IMAGE [COMMAND] [ARG...]. Setting the env is part of the OPTIONS block. My bad!


text:
Q: Counting Documents in Mongo Cursor with C & BSON. I'm working on a project and need to count the amount of documents (MongoDB) in a cursor with BSON and C.
Here is my code:
        bson_buffer_init(query_buf);
        bson_append_string(query_buf, "url", bson_iterator_string(it));
        bson_from_buffer(query, query_buf);
        similar = mongo_find(conn, "testing.test", query, NULL, 0, 0, 0);
        while(mongo_cursor_next(similar))
        {
            bson_iterator it2[1];
            if(bson_find(it2, &similar->current, "url"))
            {
                printf("%s\n", bson_iterator_string(it2));
            }

        }

How would I alter this in order to count the documents in each cursor (the above is in a loop, url is different each pass)?

A: Have you tried the mongo_count method?
According to the source, it's right about here:
https://github.com/mongodb/mongo-c-driver/blob/master/src/mongo.c#L385
Note that the C drivers are still considered Alpha quality. If you find any bugs, please let the MongoDB team know: http://jira.mongodb.org/


text:
Q: Center-tap transformer current calculation I have a transformer with two secondaries, one is 24 V / 500 mA and the other is 12 V / 200 mA. I want to wire them in series to make a center-tap transformer:

simulate this circuit – Schematic created using CircuitLab
I know the voltage is going to be sum of two winding.
How do I calculate the current?

A:
How do I calculate the current?

Those currents aren't currents that will flow, they are the winding's maximum rating. That means the current should not exceed that value or you'll overload the transformer.
The maximum current when using 36 V will be 200 mA as that is limited by the 200 mA rated 12 V winding.

A: If you look closely, you will see the primaries are wired out of phase. Hence the output voltage would be 12VAC only.
The primaries would need to be connected this way to get 36VAC. The load current would be required to be limited to 200mA.

A: Bear in mind that if you are sticking a bridge rectifier/smoothing capacitor on the output of that transformer then the output voltage will be about 1.414*36V minus a couple of volts drop across the bridge rectifier (also allow for ripple) and the maximum dc load current which can be drawn will be about 200mA/1.7.
200mA is the secondry RMS rating.


text:
Q: How to cleanly unbind a service if there is no "exit()" method A service (S1) is bound in the constructor of a "plain class" C (i.e. C does not have any lifecycle methods like (onCreate(), onDestroy() etc.) using an Intend. The context is provided on construction time in C's constructor. C is instantiated by other services (Sx) using themselves as arguments for new C(context). in fact, that is eqivalent to using their respective contexts' I guess.
Sx1 ->
      C -> S1
Sx2 ->

Question is: What's the best method/location to unbind from S1?

*

*As there are no lifecycle methods in C, should I create an "artificial" onDestroy() method in C that is called once Sx's onDestroy method is called? I dislike this a bit because I am lazy and might forget calling the onDestroy() method at some point in time as complexity grows.

*Or could I rely on the fact (don't know if that really happens) that Android will manage a clean lifecycle and "automatically unbinds" from S1 once Sx or its context is destroyed?

A:
A service (S1) is bound in the constructor of a "plain class" C

Not really. Sx1 and Sx2 are binding to S1. They are responsible for those bindings. You just happen to have put the bindService() call in C, for whatever reason.

What's the best method/location to unbind from S1?

Sx1 and Sx2 have to unbind from S1 when they are done with S1. Whether they unbind themselves or call a method on C to unbind, Sx1 and Sx2 are responsible for the bindings and therefore are responsible for unbinding.


text:
Q: Testing lambdas (Python) with aws-cdk? I want to setup unit tests for my lambdas that are written in Python. I am using aws-cdk to develop and deploy my lambdas. How do I propperly setup these unit tests? Which libraries do I use? How to put it in a packet structure? Maybe an example can clarify.
I was looking into the library 'unittest'. I set up a folder names 'test' and put a test file in there named: test_first.py. I could then execute all test files in this folder by using the command: python -m unittest discover ./test
test_first.py
import unittest

class FirstTest(unittest.TestCase):
    def test_default(self):
        self.assertEqual(10, (5+5))

if __name__ == '__main__':
    unittest.main()

Is this the right way to do this?
I now have the problem that I don't know how to import another python file and test its methods in this file. This would be the lambda I have written and test its methods. How do I do this?

A: Lambda python files are just like any other python files whose methods can be tested as unit tests.
Below is a simple example
import unittest

from my_sum import sum

class TestSum(unittest.TestCase):
    def test_list_int(self):
        """
        Test that it can sum a list of integers
        """
        data = [1, 2, 3]
        result = sum(data)
        self.assertEqual(result, 6)

if __name__ == '__main__':
    unittest.main()

You can import your lambda method like we imported sum from my_sum and then write some asserts on it.
This document is a good read for the same.


text:
Q: D3.js Tree View collapse not working in my application I added a d3.js library to project and i have few other libraries like jQuery, kendo ui, jQuery ui etc.
but collapse is not working on click of node of tree view. It is working in js fiddle but not in my application. is there are any conflicts?
<!DOCTYPE html>
<meta charset="utf-8">

see the elements

A: Your file may conflict with jquery.min.js or with other libraries and so that it may be in conflict. So you need to keep the d3.js file just above to all library files. It will work fine.


text:
Q: How to drag a bitmap with page curl effect in android? I am using android page curl in my project. Each bitmap is working fine with page curl effect. But I need to have drag functionality also. I want that when a user long click on a bitmap the page curl animation will be off and that bitmap start dragging with user's finger.
Can any one suggest me with a piece of code, how can I achieve above functionality?


text:
Q: Can I write a screen magnifier in RealBasic? I want to create a screen magnifier in RealBasic but don't see any classes or APIs for reading areas of the screen that I can then render to my window.
Anything?
Side-question: If I can't read entire areas, can I at least do per-pixel reading to simulate an eye-dropper tool that reads the pixel's color under the cursor?

A: There are several ways that both a magnifier and a eye-dropper can be made with Realbasic (shameless plug: I wrote an eyedropper in RealBasic a while ago.) It's very simple, just call the System.Pixel function using System.MouseX and System.MouseY as its parameters. System.Pixel returns a Color corresponding to the color of the pixel at the screen coordinates you specify.
With this color information you can (obviously) show the color at a larger scale by drawing to a Picture object or a Canvas control (as with an eyedropper.)
This method can be used for something like a magnifier, but probably shouldn't be. Drawing pixel-by-pixel in RealBasic can be quite slow, which with realtime tasks like a magnifier will lead to performance issues and flickering.
Under Windows, and likely under Mac OS X and GTK+, there are API functions which allow you to capture an area of the screen, which is useful for screenshots, and for manipulating bitmap images using a number of standard algorithms.
Here is a simple function which calls the Windows API to capture an 800x600 portion of the screen, magnify it by 3, and copy it into a Picture object:
 Function GetZoomedPic() As Picture
  Declare Function GetDesktopWindow Lib "User32" () As Integer
  Declare Function GetDC Lib "User32" (HWND As Integer) As Integer
  Declare Function StretchBlt Lib "GDI32" (destDC As Integer, destX As Integer, destY As Integer, destWidth As Integer, destHeight As Integer, _
  sourceDC As Integer, sourceX As Integer, sourceY As Integer, sourceWidth As Integer, sourceHeight As Integer, rasterOp As Integer) As Boolean
  Declare Function ReleaseDC Lib "User32" (HWND As Integer, DC As Integer) As Integer

  Const CAPTUREBLT = &h40000000
  Const SRCCOPY = &HCC0020
  Dim coordx, coordy As Integer
  Dim magnifyLvl As Integer = 3
  Dim screenCap As New Picture(800, 600, 32)
  coordx = System.MouseX - (screenCap.Width \ (magnifyLvl * 2))
  coordy = System.Mousey - (screenCap.Height \ (magnifyLvl * 2))
  Dim rectWidth, rectHeight As Integer
  rectWidth = screenCap.Width \ magnifyLvl
  rectHeight = screenCap.Height \ magnifyLvl

  Dim deskHWND As Integer = GetDesktopWindow()
  Dim deskHDC As Integer = GetDC(deskHWND)
  Call StretchBlt(screenCap.Graphics.Handle(1), 0, 0, screenCap.Width, screenCap.Height, DeskHDC, coordx, coordy, rectWidth, _
  rectHeight, SRCCOPY Or CAPTUREBLT)
  Call ReleaseDC(DeskHWND, deskHDC)

  Return screenCap
End Function

Around the same time I wrote that Eyedropper, I also wrote a basic magnifier project. You can download the project file here. In addition to demonstrating the above function, it can also serve as a basic demonstration of drawing to a Canvas without flickering, of using a RealBasic Picture object with Windows GDI Device Contexts and the use of threads to offload work from the main thread.

A: Take a look at this thread on the Real Software forums on this very topic.  Looks like there are a number of solutions you can try.
http://forums.realsoftware.com/viewtopic.php?f=10&t=7818&hilit=screen+magnifier


text:
Q: Material design table with checkboxes I got table with checkboxes but I don't know how to do something while checkbox is checked.
<md-table-container>

                        ID
                        Username

                        {{ user.id }}
                        {{ user.username }}

        </md-table-container>

How Can I check that checkbox is checked and do something?

A: add $scope.$watch on the variable that you are interested in (or watchcollection)
https://docs.angularjs.org/api/ng/type/$rootScope.Scope
Do not forget that variable you are watching is in $scope and propagation of variable into ng-if scopes happen by copying not reference. You can wrap variable into some container object, otherwise changes will happen in another scope and you never notice them.