text:
Q: How is this Map of String to String possible as a Map of String to a list of String in Groovy? Saw some working code in a project that is like the one below (of course that's just an example) but I'm extremely confused at how this is possible as a Map<String, String> and not Map<String, List<String>>?
Looked it up in the Groovy doc but I didn't see anything that explains this concept. Could someone explain if this is indeed a legit concept in Groovy?
static final Map<String, String> NAMES = [
   "Male": ["Bill", "Bryant", "Jack"],
   "Female": ["Lily", "Haley", "Mary"]
]

A: It happens because of Java's Generic Type Erasure. If you look at the internal type signatures, you will see that NAMES field is just a type of java.util.Map. Take a look at the descriptor of that field.
$ javap -s -p SomeClass
Compiled from "SomeClass.groovy"
public class SomeClass implements groovy.lang.GroovyObject {
  private static final java.util.Map<java.lang.String, java.lang.String> NAMES;
    descriptor: Ljava/util/Map;
  private static org.codehaus.groovy.reflection.ClassInfo $staticClassInfo;
    descriptor: Lorg/codehaus/groovy/reflection/ClassInfo;
  public static transient boolean __$stMC;
    descriptor: Z
  private transient groovy.lang.MetaClass metaClass;
    descriptor: Lgroovy/lang/MetaClass;
  private static java.lang.ref.SoftReference $callSiteArray;
    descriptor: Ljava/lang/ref/SoftReference;
  public SomeClass();
    descriptor: ()V

  public static void main(java.lang.String...);
    descriptor: ([Ljava/lang/String;)V

  protected groovy.lang.MetaClass $getStaticMetaClass();
    descriptor: ()Lgroovy/lang/MetaClass;

  public groovy.lang.MetaClass getMetaClass();
    descriptor: ()Lgroovy/lang/MetaClass;

  public void setMetaClass(groovy.lang.MetaClass);
    descriptor: (Lgroovy/lang/MetaClass;)V

  static {};
    descriptor: ()V

  public static java.util.Map<java.lang.String, java.lang.String> getNAMES();
    descriptor: ()Ljava/util/Map;

  private static void $createCallSiteArray_1(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V

  private static org.codehaus.groovy.runtime.callsite.CallSiteArray $createCallSiteArray();
    descriptor: ()Lorg/codehaus/groovy/runtime/callsite/CallSiteArray;

  private static org.codehaus.groovy.runtime.callsite.CallSite[] $getCallSiteArray();
    descriptor: ()[Lorg/codehaus/groovy/runtime/callsite/CallSite;
}

Now, that' not all. If you decompile the Groovy bytecode to the Java readable code, you will find something like this.
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import groovy.transform.Generated;
import java.util.Map;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.runtime.callsite.CallSite;

public class SomeClass implements GroovyObject {
    private static final Map<String, String> NAMES;

    @Generated
    public SomeClass() {
        CallSite[] var1 = $getCallSiteArray();
        super();
        MetaClass var2 = this.$getStaticMetaClass();
        this.metaClass = var2;
    }

    public static void main(String... args) {
        CallSite[] var1 = $getCallSiteArray();
        var1[0].callStatic(SomeClass.class, var1[1].call(NAMES));
    }

    static {
        Map var0 = ScriptBytecodeAdapter.createMap(new Object[]{"Male", ScriptBytecodeAdapter.createList(new Object[]{"Bill", "Bryant", "Jack"}), "Female", ScriptBytecodeAdapter.createList(new Object[]{"Lily", "Haley", "Mary"})});
        NAMES = var0;
    }

    @Generated
    public static Map<String, String> getNAMES() {
        return NAMES;
    }
}

At this level, NAMES field signature matches Map<String, String>. But look at the static constructor and how this field gets initialized. The NAMES field of type Map<String, String> gets initialized with a raw Map type. Also, the ScriptBytecodeAdapter.createMap method returns a raw map, but it could return a parameterized map as well - you will see the same effect. If that map wasn't a raw map, the compiler would complain and throw an error because of incompatible types. But a raw map essentially allows you to assign a map that stores values that are incompatible with the parameters.
You can get the same effect in pure Java. Take a look at the following example:
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

final class SomeJavaClass {

    private static final Map<String, String> NAMES;

    static {
        final Map map = new HashMap();
        map.put("Male", Arrays.asList("Bill", "Brian", "Jack"));

        NAMES = map;
    }

    public static void main(String[] args) {
        System.out.println(NAMES);
        System.out.println(((Object) NAMES.get("Male")).getClass());
    }
 }

When we execute its main method, we will get the following output:
{Male=[Bill, Brian, Jack]}
class java.util.Arrays$ArrayList

In this example, we had to cast NAMES.get("Male") to Object, because otherwise, we would get a ClassCastException - an ArrayList cannot be cast to String. But when you cast to Object explicitly, you can get an ArrayList from a map that, by definition, should keep only string values.
This is known Java behavior - generic types get erased so the raw types can be compatible with pre Java 1.5 versions. Groovy for its dynamic capabilities operates often on raw classes like Map, or List, and thus it can silently overcome some of those limitations.
If you want to use more restricted type checks, you can use @groovy.transform.TypeChecked annotation to keep Groovy's dynamic behavior and add more restrictive type checks. With this annotation added, your class won't compile anymore.


text:
Q: Converting a string into date time I have the following date in python, as a string which I want to convert to datetime
I tried using strptime function, but due to the format with decimals and a marginal value, it keeps failing. Any idea on how to convert it?
The date string structure is like this example:
2022-02-08 17:12:35.667000+00:00

A: The dateutil module has something just for this. You can use its parser to create a datetime object from a string like this.
from dateutil import parser

date_obj = parser.parse("2022-02-08 17:12:35.667000+00:00")

EDIT:
I don't believe that this is a default python library, so you can type this code into the terminal  to install it with pip: pip install python-dateutil

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to handle session in socket.io and express in node.js I'm new to socket.io. I'm developing a website with a chat subpage. Before someone enters chat he must fill form with email, name and so on. After logging you can chat with a consultant. Unfortunatelly I can not go to any other subpage because when I enter my chat subpage again it requires logging again and starts new conversation. My question is how to handle user chat session?
Any help will be appreciated.
Thanks!


text:
Q: Mean square of a random variable is bounded Let $(X_n)_n$ be a sequence of random variables and in $L^2.$
Suppose the existence of $M$ such that for all $n$ we have $$P(X^2_n\ge M)<P(X^2_n\ge E(X^2_n)),$$
Does it follow that $E(X_n^2)\le M$ for all $n$ ?
I tried to find a counter exemple but I didn't succeed, and for a proof if it is correct I am stuck.

A: In general if $Z$ is a random variable and $a,b\in\mathbb R$ then: $$P(Z\geq a)<P(Z\geq b)\implies b<a\tag1$$
Observe that: $$b\geq a\implies P(Z\geq a)=P(Z\in[a,b))+P(Z\geq b)\geq P(Z\geq b)$$
Taking the contrapositive of that we find $(1)$.


text:
Q: Factory vs Abstract Factory Design Pattern I was looking at design pattern, but got confused between Factory and Abstract Factory Pattern. will any one please explain the differences when to follow which pattern.
Thanx

A: The factory pattern "Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses".
Where as abstract factory pattern "Provide an interface for creating families of related or dependent objects without specifying their concrete classes".
You can think of abstract pattern as factory of factories. As @deadalnix said, it lets you choose the right factory. for more details, read the following links:

*

*Factory Pattern on Wikipedia

*Abstract Factory Pattern on Wikipedia
The Factory Method pattern is a method on a class, used to build
other instances. You can implement a Factory Method on just about any
class that happens to be handy at the time.
The Abstract Factory pattern is about creating a class that has
nothing (of interest) other than Factory Method(s) on it. Use abstract factory when you need to create a suite of different but matching objects, or
if the act of controlling object creation rises to the point of being
the primary function of the class.

A: The abstract factory doesn't build anything. It just choose the right factory and make it build something.
From the outside it looks like a standard factory and can be used the same way.
It allow you to build object with severals stages in the process.

A: Real Life Example. (Easy to remember)
Factory
Imagine you are constructing a house and you approach a carpenter for a door. You give the measurement for the door and your requirements, and he will construct a door for you. In this case, the carpenter is a factory of doors. Your specifications are inputs for the factory, and the door is the output or product from the factory.
Abstract Factory
Now, consider the same example of the door. You can go to a carpenter, or you can go to a plastic door shop or a PVC shop. All of them are door factories. Based on the situation, you decide what kind of factory you need to approach. This is like an Abstract Factory.
http://www.dofactory.com/topic/1590/factory-pattern-vs-abstract-factory-pattern.aspx

A: An Abstract Factory is aimed at creating groups of related objects. The interface of an Abstract Factory will typically contain a number of Factory Methods, one for each type of object to be created.
Here's an example of an Abstract Factory:
public abstract class AnimalFactory
{
    public abstract Animal CreateFish();
    public abstract Animal CreateBird();
    public abstract Animal CreateMammal();
}

public class AfricanAnimalFactory : AnimalFactory
{
    public override Animal CreateFish()
    {
        return new Reedfish();
    }

    public override Animal CreateBird();
    {
        return new Flamingo();
    }

    public override Animal CreateMammal();
    {
        return new Lion();
    }
}

Related resources:

*

*Abstract Factory Design Pattern

*Factory Method Design Pattern


text:
Q: Finite sum of factorials, containing e, pi and bessel function In I.S. Gradshteyn and I.M. Rhyzhik's table of integrals, series and products, an interesting sum is given on page 2, formula 0.126:
\begin{equation}
\sum_{k=0}^{n}\frac{(n+k)!}{k!(n-k)!}=\sqrt{\frac{e}{\pi}}K_{n+\frac{1}{2}}\left(\frac{1}{2}\right)
\end{equation}

Where $K_v(z)$ are the Bessel functions of imaginary argument, which are equal to the integral

\begin{equation}
K_v(z)=\int_{0}^{\infty}e^{-z\cosh t}\cosh vt\,dt
\end{equation}

How can one prove the sum? You can reference the article containing the proof.

A: In fact, the first results comes from the fact that
$$\sum_{k=0}^{n}\frac{(n+k)!}{k!(n-k)!}x^k=\frac{e^{\frac{1}{2 x}}}{\sqrt{\pi x}   } K_{n+\frac{1}{2}}\left(\frac{1}{2 x}\right)$$
For $x=1$, this generates the sequence
$$\{1,3,19,193,2721,49171,1084483,28245729,848456353,28875761731,\cdots\}$$ which is $A001517$ in $OEIS$.
In the formula section, you could see an asymptotics proposed by Vaclav Kotesovec in $2014$
$$a_n \sim 2^{2 n+\frac{1}{2}}\, e^{\frac{1}{2}-n}\, n^n$$ For $n=10$, this gives
$$a_{9}\sim\frac{101559956668416 \sqrt{2}}{e^{17/2}}=29223646682$$
The relative error is less than $1.00$% if $n >10$, less than $0.10$% if $n> 105$ and less than $0.01$% if $n>1042$.


text:
Q: Slider with breaks in between (discrete) for react native I have to create a slider with breaks at discrete value points eg: 0, 5, 10
Here's an example
Slider Design
I'm not able to find any library that does this. I found one but it was for react web.
Does anybody have any experience with this or can point me in the right direction?
I need to create variants with Sliding at both ends (range), Discrete (mentioned above), and normal continuous slider. Any help is appreciated :)


text:
Q: Alternative to forward slash spring I need to create and capture the path using spring dynamic paths as following:
http://myHost/event/my/dynamic/path
In other words, I need capture whatever it comes after event. The path after event is dynamic. This means, I don't know neither what the the values in between the / neither how many / I will get. I know that the / cannot be capture. I'm searching alternatives to do this that doesn't force me to replace the /. Something like a query, but that works for POST and PUT.
Any ideas?


text:
Q: TFS (vNext) build randomly fails in step 'Publish Artifacts' Since some time already, our TFS 2015 builds fail randomly in Publish Artifacts step. The upload starts properly and after some uploaded files the process stops with this message: ##[error]A task was canceled. (see below).
Normally we can work around that issue by simply re-queue another build. However this is annoying and contradict the idea of CI/CD.
The generic error message give me no clue where to look for the problem. Any ideas?
  2016-10-26T12:47:47.8071677Z Files found locally 1772,
  2016-10-26T12:47:47.8071677Z Files evaluated 1772,
  2016-10-26T12:47:47.8071677Z Files left to evaluate 0.,
  2016-10-26T12:47:47.8071677Z Files created without upload 0,
  2016-10-26T12:47:47.8071677Z Files uploaded 796
  2016-10-26T12:47:47.8071677Z Files left to process 976
  2016-10-26T12:47:47.8071677Z ---------------------------
  2016-10-26T12:47:49.0421524Z Start: UploadArtifact
  2016-10-26T12:47:49.0577804Z ##[error]A task was canceled.
  2016-10-26T12:47:49.0577804Z End: UploadArtifact

Update
As proposed by @Patrick-MSFT, I enabled system.debug and got some more error details:
   ---------------------------
   Files found locally 1852,
   Files evaluated 1852,
   Files left to evaluate 0.,
   Files created without upload 0,
   Files uploaded 1316
   Files left to process 536
   ---------------------------
   Start: UploadArtifact
   System.Threading.Tasks.TaskCanceledException: A task was canceled.
   End: UploadArtifact
   ******************************************************************************
   Finishing task: PublishBuildArtifacts
   ******************************************************************************
   System.Exception: Task PublishBuildArtifacts failed. This caused the job to fail. Look at the logs for the task for more details.
   at Microsoft.TeamFoundation.DistributedTask.Worker.JobRunner.Run(IJobContext jobContext, IJobRequest job, IJobExtension jobExtension, CancellationTokenSource tokenSource)
   ******************************************************************************
   Finishing Build
   ******************************************************************************
   Worker Worker-89de22b8-0ad4-4541-ad73-a758c9783464 finished running job 89de22b8-0ad4-4541-ad73-a758c9783464

A: Finally, I solved the problem by simply updating the build agent to the latest version. The old version in use was 1.105.7. Now I updated to 2.105.6.

A: For the troubleshooting with a special build task, you can try this:

*

*On the variables tab, add system.debug and set it to true. Select to
allow at queue time.

*In the explorer tab, view your completed build and click the build
step to view its output.

The control options arguments described above can also be useful when you're trying to isolate a problem.
Please double check if you have set the Timeout in Control options of 'Publish Artifacts' which stands for this task in minutes. This may  cause the fail.
And also create a new  build definition with the same settings and try to reproduce your issue.


text:
Q: Show that there are $q,\,r\in\mathbb{N}$ with $rMy teacher of real analysis gave this question to us:
"Being $p,\,m\in\mathbb{N}$ such that $p>m$ and $p$ is not a multiple of $m$. How can we show that there are $q,\,r\in\mathbb{N}$ with $r<m$ such that $p=m\cdot q+r$ and that the natural numbers $q$ and $r$ that satisfy this situation are unique?"
She said that we will consider $0\notin \mathbb{N}$. This is ALL the information given to us. Probably we have to solve this with the Induction's Principle but I can't see how this is made.

A: I will give you some hints.

Lemma. Given $m,n \in \Bbb{N}$ with $n > m$ there is $q \in \Bbb{N}$ such that
$$qm \leq n < (q+1)m.$$

You can prove it using the Well-ordering Principle on $X = \{xm \mid xm > n; x \in \Bbb{N}\}$.

Euclidean Division. Given $n > m \in \Bbb{N}$ there are $r,q \in \Bbb{N}$ (and they are unique) such that
$$n = qm + r$$
where $0 \leq r < m$.

Now using the lemma for get $q \in \Bbb{N}$ such that
$$qm \leq n \leq (q+1)m.$$
Study the cases $qm = n$ and $qm < n$.

Note that this generalize your problem. More precisely, $``p$ is not multiple of $m"$ can be excluded, making the appropriate changes.

A: Uniqueness: If $mq+r=mq'+r'$ and $q'=q$, then immediately $r=r'$. So assume $q\ne q'$ and wlog $q'>q$. Then $r=m(q'-q)+r'>m$, contradiction.
Existence: There are solutions $(q,r)$ to $p=mq+r$ if we do not require $r<m$. For example, $q=1,r=p-m$ is such a solution because we are given that $p>m$. Among all such pairs, pick one that minimizes $r$. Show that $r<m$ for this pair.


text:
Q: Adding host without www not working with Ingress resource I have a couple of questions

*

*When we make changes to ingress resource, are there any cases where we have to delete the resource and re-create it again or is kubectl apply -f <file_name> sufficient?

*When I add the host attribute without www i.e. (my-domain.in), I am not able to access my application but with www i.e. (www.my-domain.in) it works, what's the difference?
Below is my ingress resource
When I have the host set to my-domain.in, I am unable to access my application, but when i set the host to www.my-domain.in I can access the application.
my domain is on a different provider and I have added CNAME (www) pointing to DNS name of my ALB.
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: eks-learning-ingress
  namespace: production
  annotations:
    kubernetes.io/ingress.class: alb
    alb.ingress.kubernetes.io/scheme: internet-facing
    alb.ingress.kubernetes.io/certificate-arn: arn:aws:a982529496:cerd878ef678df
  labels:
    app: eks-learning-ingress
spec:
  rules:
  - host: my-domain.in **does not work**
    http:
      paths:
        - path: /*
          backend:
            serviceName: eks-learning-service
            servicePort: 80

A: *

*First answering your question 1:

When we make changes to ingress resource, are there any cases where we have to delete the resource and re-create it again or is kubectl apply -f  sufficient?

In theory, yes, the kubectl apply is the correct way, either it will show ingress unchanged or ingress configured.
Other valid documented option is kubectl edit ingress INGRESS_NAME which saves and apply at the end of the edition if the output is valid.
I said theory because bugs happen, so we can't fully discard it, but bug is the worst case scenario.

*

*Now the blurrier question 2:

When I add the host attribute without www i.e. (my-domain.in), I am not able to access my application but with www i.e. (www.my-domain.in) it works, what's the difference?

To troubleshoot it we need to isolate the processes, like in a chain we have to find which link is broken. One by one:
Endpoint > Domain Provider> Cloud Provider > Ingress > Service > Pod.

*

*DNS Resolution (Domain Provider)

*DNS Resolution (Cloud Provider)

*Kubernetes Ingress (Ingress > Service > Pod)

DNS Resolution

Domain Provider:
To the Internet, who answers for my-domain.in is your Domain Provider.

*

*What are the rules for my-domain.in and it's subdomains (like www.my-domain.in or admin.my-domain.in)?
You said "domain is on a different provider and I have added CNAME (www) pointing to DNS name of my ALB."

*

*Are my-domain.in and my-domain.in being redirected to the ALB address instinctively?

*How does it handle URL subdomains? how the request is passed on to your Cloud?

Cloud Provider:
Ok, the cloud provider is receiving the request correctly and distinctly.

*

*Does your ALB have generic or specific rules for subdomains or path requests?

*Test with another host, a different VM with a web server.

*Check  ALB Troubleshooting Page
Kubernetes Ingress
Usually we would start the troubleshoot from this part, but since you mentioned it works with www.my-domain.in, we can presume that your service, deployment and even ingress structure is working correctly.
You can check the Types of Ingress Docs to get a few examples of how it should work.
Bottom Line: I believe  your DNS has a route for  www.my-domain.in but the root domain has no route to your cloud provider that's why it's only working when you are enabling the ingress for www.


text:
Q: Why does XmlNode to XmlElement works in VB This is something I noticed looking at while working with some of our old vb code.
This line will not throw any kind of cast exception...
Dim moduleElement As XmlElement = xmldoc.SelectSingleNode("/modules/module")

But this line will in C#...
XmlElement focusFieldsNode =  moduleNode.SelectSingleNode("ui/initial_focus_fields");

Now to resolve this I cast as an XmlElement, but why would that work in vb and not in C#?

A: Have a look at where they are from:

XmlNode
XmlElement
XmlLinkedNode

The XmlElement inherits from XmlLinkedNode which inherits from XmlNode.
So they are from the same type. Casting will provide you with the extra functionality that comes from the specific derived class.


text:
Q: Set base URL dynamically in angular app I am working on an AngularJS project. I removed # from the URL using  and $locationProvider.html5mode().
Depending upon environment, I want the href attribute for base tag to be dynamically updated from a config file. I created an env.js that contains simple configurations.
env.js
(function (window) {
  window.__env = window.__env || {};

  window.__env.baseUrl = '/';

  window.__env.enableDebug = true;
}(this));

I used this env file in my app.js and inside app.run() updated $rootScope.baseurl to baseUrl in env.js. It is working fine inside console.log() but not in my index.html. I am getting the uncompiled code i.e {{ $rootScope.baseurl }}
app.js
import controllers from './controllers';

        var env = {};

        if (window) {
            Object.assign(env, window.__env);
        }

        var app = angular.module('myapp', ['ui.router', controllers]);

        app.constant('__env', env);

        app.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {

            $urlRouterProvider.otherwise("/");

            $stateProvider.state("home", {
                url: "/",
                templateUrl: "app/components/home/home.view.html",
                controller: "HomeController"
            }).state("login", {
                url: "/login",
                templateUrl: "app/components/login/login.view.html",
                controller: "LoginController"
            });

            $locationProvider.html5Mode({
                enabled: true,
                requireBase: true
            });
        });

       app.run(function($rootScope, __env){
          $rootScope.baseurl = __env.baseUrl;
          console.log($rootScope.baseurl);
      });

Index.html
    <html ng-app="myapp">
        <head>
            <title>MYAPP</title>
            <base href="{{ baseurl }}">
        </head>

        <body>
            <div ui-view>
            </div>
        </body>

        <script type="text/javascript" src="public/lib/js/angular.min.js"></script>
        <script type="text/javascript" src="public/lib/js/angular-ui-router.min.js"></script>
        <script type="text/javascript" src="env.js"></script>
        <script type="text/javascript" src="public/app.js"></script>

    </html>

Please help me out . Thanks

A: You can't use angular to set it since it needs to be set before any requests are made for page resources like scripts, stylesheets, images etc since you are using relative paths
You could try replacing the <base> with something like:
<script type="text/javascript" src="env.js"></script>
<script>
      document.write('<base href="' + window.__env.baseUrl + '" />');
</script>

Or
<script type="text/javascript" src="env.js"></script>
<base id="base">
<script>
   document.getElementById('base').href = window.__env.baseUrl;
</script>


text:
Q: Probability question using combinations Bob and Alice are dinner guests at a party of eight, 4 male and 4 female. The hostess arranges the guests linearly along a table with the men on one side and the women on the other. The probability that Bob and Alice will be facing each other or be within one position of facing each other is...

A: There are $6$ forbidden places places that Alice and Bob could sit, illustrated below:

Once they are seated, the remaining people can be seated in $3!^2$ distinct ways.
The total number of seating arrangements (forbidden or not) is $4!^2$.
Hence the probability of a permissible seating arrangement is therefore $$1-\frac{6 \times 3!^2}{4!^2}=1-\frac{216}{576}=0.625.$$
(Note: I've assumed that there is a designated male side and a female side here; if the restriction is only that "the males are on one side", then both the numerator and denominator above should be multiplied by $2$.)


text:
Q: Makefile automatic variables I'm working on a library of (more or less random ) c functions that I use in projects. The previous incarnation of it had every .c, .o file listed and manually compiled in target:
$(CC) $(SRCDIR)/somefoo.c $(CFLAGS) ... -c -o $(OBJDIR)/somefoo.o

This became tiresome, inaccurate and a pain, and I wanted to create a friendlier, better Makefile I could use for any project. After googling, reading( O'Reily's "Managing Projects with GNU Make ) and thinking I came up with:
BIN = /usr/bin

SH  = $(BIN)/bash
CC  = $(BIN)/cc
AR  = $(BIN)/ar
RL  = $(BIN)/ranlib
RM  = $(BIN)/rm
CP  = $(BIN)/cp
RL  = $(BIN)/ranlib
TC  = $(BIN)/touch
MK  = $(BIN)/make
FND = $(BIN)/find
TAR = $(BIN)/tar
RM  = $(BIN)/rm

CFLAGS  = -Wall -Wextra -Wpedanitc -pedanitc-errors\
          -w -Waddress -Walloc-zero -Walloca -Warray-bounds\
          -Wno-deprecated -Wno-div-by-zero -Werror -Wfatal-errors\
          -Wduplicated-cond -Wduplicated-branches -Wlogical-op -Wdouble-promotion\
          -Wrestrict -Wnull-dereference -Wjump-misses-init -Wshadow\
          -Wformat=2 -Wformat -Wformat-security -pedantic --std=c99 --march=native
DEBUG   = -g -ggdb -gstabs
OPTIM   = -faggressive-loop-optimizations -fassociative-math -O3
LIBS    = -lm -lcommonC #add more here
INC     = -I/usr/include -I/usr/local/include -I$(INCDIR)
LIBPATH = -L/usr/lib -L/usr/lib64 -L/usr/local/lib -L/usr/local/lib64 -L$(LIBDIR)
MKFLAG  = -f

PACK = $(TAR) -cvs
EXTRACT = $(TAR) -xf

PREFIX = /path/to/project #root directory of the project
BINDIR = $(PREFIX)/bin #stores Makefile, shell scripts, README, LICENSE, data files...
INCIDR = $(PREFIX)/include #holds .h files for the project
SRCDIR = $(PREFIX)/src #holds source files
OBJDIR = $(PREFIX)/obj #holds generated object files
LIBDIR = $(PREFIX)/lib #holds generated or included .a files
EXEDIR = $(PREFIX)/exe #generated executable(s)
DESTDIR ?= #where the tar file will be unpacked, user defined.

SRC = $(wildcard $(SRCDIR)/*.c) #all .c source files
OBJ = $(patsubst %.c,%.o,$(wildcard *.c)) #.o files
LIB ?= $(wildcard $(LIBDIR)/*.a) #the .a
EXE = $(EXEDIR)/project #generated executable
MKE = $(BINDIR)/Makefile #Makefile, used for cleaning before packing the project
TARF ?= #tar file for project.tar, user defined

.PHONY: obj exe update test clean pack install

# up to $(EXE) updated thanks to "Renaud Pacalet"
obj: $(OBJ)
exe: $(EXE)

$(OBJ): %.o: %.c
  $(CC) $< $(CFLAGS) $(LIB) $(INC) $(LIBPATH) $(LIBS) $(OPTIM) -c -o $@

$(EXE): $(OBJ)
   $(CC) $^ $(CFLAGS) $(LIB) $(INC) $(LIBPATH) $(LIBS) $(OPTIM) -o $@

update: $(SRC)
    $(TC) $(SRC)

clean:
    $(RM) $(OBJ) $(EXE) $(LIB)

pack:
    $(MK) $(MKFLAG) $(MKE) clean && $(PACK) $(PREFIX) $(TARF)

install:
    cd $(DESTDIR) && $(TAR) $(EXTRACT) $(TARF)

My question is with the declaration of SRC, OBJ, and the target to compile .c -> .o The SRC = ... works fine, but for some reason the corresponding obj file is not being generated? Thank you for any and all input.
Update: Thanks to Renaud Pacalet, I have the OBJ/SRC variables figured out. I have been receiving an error:
make: Nothing to be done for 'obj'

Which usually means that the targets are up to date. It was brought to my attention that there is a lack of detail concerning my organization, so I added comments describing what each variable references. I have used this organization scheme before for most of my projects, and I have not had an issue with this until now.
Thank you for any and all input.
--Jordan.
-- Jordan.

A: What gets created by your compilation rule is the result of the expansion of $@, that is the target of the rule, that is... obj. So you probably have a file named obj containing the result of the compilation of the first source in $(SRC) (expansion of $<). Use a pattern rule, instead:
SRC = $(wildcard $(SRCDIR)/*.c)
OBJ = $(patsubst %.c,%.o,$(SRC))

%.o: %.c
    $(CC) $< $(CFLAGS) $(LIB) $(INC) $(LIBPATH) $(LIBS) $(OPTIM) -c -o $@

Or a static pattern rule:
$(OBJ): %.o: %.c
    $(CC) $< $(CFLAGS) $(LIB) $(INC) $(LIBPATH) $(LIBS) $(OPTIM) -c -o $@

If what you wanted was a shorthand named obj for the compilation of all sources, you can define a phony target:
.PHONY: obj

obj: $(OBJ)

and invoke:
make obj

Similarly, it would probably be better to define exe as phony and write a rule that explicitly creates a file. Make is always happier when the world it sees is made of recipes that create files:
.PHONY: exe

exe: $(EXE)

$(EXE): $(OBJ)
    $(CC) $^ $(CFLAGS) $(LIB) $(INC) $(LIBPATH) $(LIBS) $(OPTIM) -o $@

One last note: you use make in one of your recipes (pack) through one of your MK custom variable. You should really consider replacing MK by the already defined MAKE make variable:
pack:
    $(MAKE) $(MKFLAG) $(MKE) clean && $(PACK) $(PREFIX) $(TARF)


text:
Q: how can I read a zip file to stream? I have a method that gives a stream file and upload it to server.
I want read a zip file from my disk and put it into a stream file, then my method can upload it automatically.
I search too much but the results just helps me to read a text file to stream! just like this:
Dim fileReader As System.IO.StreamReader
fileReader =
My.Computer.FileSystem.OpenTextFileReader("C:\\testfile.txt")
Dim stringReader As String
stringReader = fileReader.ReadLine()
MsgBox("The first line of the file is " & stringReader)

but I want read a zip file to stream, not text file!


text:
Q: How to setup ember-simple-auth if rails is handling the login forms Im a bit stuck. I dont know how to setup ember-simple-auth with my current rails + ember-cli app.
Currently, the user has to login with steam, so they get redirected to steam's login page. When they press authorize, they get redirected back to my site. I then let rails process the request and if they successfully signed in with steam, I set a cookie with a randomly generated token.
Now I need to do two things for ember-simple-auth.

*

*Tell ember-simple-auth to check if the token exists, and if it does, make an api call to get the user's infor like the name, email, username, etc...

*Add a prefilter that passes the token in most requests.

For #2, I can just use the OAuth authorizer, but for #1, I have no idea.
Thanks.

A: You need to implement a custom authenticator and use that to authenticate the session in an initializer when the app starts. The authenticator would in its authenticate method read the token that the Rails app writes to the cookie, make the API call and resolve with a bearer token that the OAuth 2.0 authorizer would then inject into requests.


text:
Q: Combinatorics. Rook Placing Suppose that we want to place $8$ non-attacking rooks on a chessboard. In how many ways can we do this if the $16$ most 'northwest' squares must be empty? How about if only the $4$ most 'northwest' squares must be empty?
Question 1 : $4\cdot3\cdot2\cdot1\cdot4\cdot3\cdot2\cdot1 = (4!)^2$
Let's begin placing with 'northeast' corner $\Rightarrow$ $4\cdot3\cdot2\cdot1$, then let's place remaining 'southwest' corner $\Rightarrow$ $4\cdot3\cdot2\cdot1$
Question2: $6\cdot5\cdot6\cdot5\cdot4\cdot3\cdot2\cdot1 = 6\cdot5\cdot6!$
The same strategy. First place 'northeast' corner $\Rightarrow$ $6\cdot5$, then 'southwest' corner $\Rightarrow$ $6!$
I cannot find answers in the book or in internet, that is why are my solutions correct? If not, specify. Thank you.

A: Let's label the rows 1 through 8 and the columns a through h, as is standard in chess notation.
To place eight rooks in the case with the NW quadrant (rows 1-4, columns a-d) missing:
  - you must place four rooks in the NE quadrant (rows 1-4, columns e-h). There are 4! ways to do this.
  - you must then place four rooks in rows 5-8 - but you can't place them in any of columns e-h, so you essentially must place four rooks in the the 4-by-4 square of rows 5-8, columns a-d.  There are 4! ways to do this. This gives $4!^2$ as the answer.
If instead you have a 2-by-2 NW corner missing (say a1, a2, b1, b2):
 - you must first place two rooks in rows 1 and 2. There are $6 \times 5$ ways to do this.
 - now you must place six rooks in rows 3-8, but there are two columns struck out (the columns in which you places the rooks in the first two rows) so there are $6!$ ways to do this.  This gives $6 \times 5 \times 6!$ as the answer.
As a sanity check, if you have a 1-by-1 NW corner missing (say a1) this approach gives $7 \times 7!$.  So the probability that a random arrangement of rooks doesn't contain a rook in a1 is $(7 \times 7!)/8! = 7/8$, and the probability that a random arrangement of rooks does contain a rook in a1 is therefore $1 - 7/8 = 1/8$.  This is what you'd expect by symmetry.


text:
Q: Why does Numpy use the term "shape" inconsistently I'm learning numpy and getting very confused by the terminology.
>>> x = np.random.randint(20, size=(2, 10)) # 'size' here means number of rows and number of columns
>>> x.size # consistent with the above I expect an output of `(2,10)`
20
>>> x.shape
(2, 10)
>>> x = np.random.randint(20, shape=(2, 10)) # since the above did not work as expected let's see whether we can salvage anything...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "mtrand.pyx", line 910, in mtrand.RandomState.randint
TypeError: randint() got an unexpected keyword argument 'shape'

Why does numpy behave this way and what does numpy mean by an array's "shape" and an array's "size"? Is this an exception or are these terms used interchangeably and inconsitently in general?


text:
Q: Php Archives (Phar) do not uncompress text files I am deploying my Php application as a compressed Php Archive (Phar), I have noticed that when using gzip compression the css and other text files are not uncompressed and look like gibberish. When disabling compression they are fine.
I am using the default stub which sets the mime type for css files. Is there some setting I must enable in order for the Phar to uncompress non-php files? Or is the Phar working as intended and I need to echo out the contents of text files from within a Php script?


text:
Q: Matlab hit and miss of circle area It works for the most part until the end of the for loop but I get an error not sure how to fix or if its all just wrong.
Problem:
The USF math department has forgotten the value of pi and they want you to calculate it for them. Assume you have a quarter circle inside a square with sides of 1x1 unit. Then the radius of the circle is 1. The area of a circle is pir2. If r = 1, the area is pi and the area of a quarter circle is pi/4. Use a for loop beginning at 1 and ending at a number input from the keyboard to add random points in the square (use the MATLAB function rand() to get the points). If a point lands inside the circle, it is a hit else it is a miss. The approximate area of the circle (pi) is the (hits)/(total points)*4.
My attemp:
clear;clc
numP=input('Enter the number of points to test: ');
randNums=[rand(1,numP);rand(1,numP)]'
row=0;
hits=0;
total=0;
for i=1:numP
    while i<=numP
        dist=sqrt((randNums(row+1))^2 + (randNums(row+(numP+1))^2))
        if dist <= 1
            hits=hits+1
        end
        total=total+1
        row=row+1
    end
end
approx=(hits/total)*4

A: All you should need to do is remove the while loop.
I also got rid of the row variable since you didn't need it.
clear;clc
numP=input('Enter the number of points to test: ');
randNums=[rand(1,numP);rand(1,numP)];
hits=0;
total=0;
for i=1:numP

    dist=sqrt((randNums(i))^2 + (randNums(i+numP)^2));
    if dist <= 1
        hits=hits+1;
    end
    total=total+1;

end
approx=(hits/total)*4

A: clear; % Clear workspace.
clc; % Clear command line.
numP=input('Enter the number of points to test: ');
pi_c = 0; % Initialize the computed value of pi.
format long
count = 0; % Count resets to 0 after every value of m.
for j = 1:numP
    x = rand; % Choose a random number 0 and 1.
    y = rand; % Choose a random number 0 and 1.
    if (x^2 + y^2 - 1 <= 0) % If the point falls in a circle...
        count = count + 1; % Increment count.
    end
end
pi_c = 4 * count/numP; % Computed value of pi.
disp(pi_c)

pi_c gives you the computed pi value


text:
Q: Center one fixed 'arrow' element inside another fixed 'circle' element I am having trouble centering the arrow inside the red circle.
How can I center one fixed element inside another fixed element?
JsFiddle: https://jsfiddle.net/sebastian3495/xtj9cga2/4/
Code

html, body {
  height: 1000px;
  width: 100%;
}
#a {
  width: 100%;
  height: 100%;
  border: 1px solid black;
  position:relative;
}
#wrapper {
  position: absolute;
  top: 50vh;
}
#b {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: red;
  position: fixed;
}
#c {
  border: solid black;
  border-width: 0 3px 3px 0;
  position: fixed;
  width: 50px;
  height: 50px;
  transform: rotate(-45deg);
}

A: You can simply your code like below then you can easily center your arrow and also adjust the dimension:

.arrow {
  background:red;
  width:100px;
  height:100px;
  border-radius:50%;
  position:fixed;
  top:100px;
  left:50px;
}
.arrow::before {
  content:"";
  position:absolute;
  top:50%;
  left:50%;
  width:50%;
  height:50%;
  border-top:3px solid;
  border-right:3px solid;
  /*75% instead of 50% since we need to center half the shape so 50% then 25%*/
  transform:translate(-75%,-50%) rotate(45deg);

}

You can still simplify more without pseudo element:

.arrow {
  width:100px;
  height:100px;
  padding:35px 35px 0 0;
  border-radius:50%;
  position:fixed;
  top:100px;
  left:50px;
  background:
    linear-gradient(#000,#000) top right/77% 3px,
    linear-gradient(#000,#000) top right/3px 77%,
    red;
  background-repeat:no-repeat;
  background-origin:content-box;
  transform:rotate(45deg);
  box-sizing:border-box;
}

A: adjust top and left position for i tag with id="c"
#c {
    border: solid black;
    border-width: 0 3px 3px 0;
    position: fixed;
    width: 50px;
    height: 50px;
    left:3%;
    top:60vh;
    transform: rotate(-45deg);
}


text:
Q: How to share stubs for type hinting transitively? I am currently using a Python library (x) that does not come with type hints. I've opted to add stub files for the x methods that I use in my project like this:
MyProject_1/
  stubs/
    x/
      __init__.pyi  # Contains type hints for any attributes of `x`.

  package_1/
    package_1_main.py  # Imports `x`.
    __init__.py
    py.typed  # Indicates package 1 type hints are specified inline.

  setup.py  # Specifies `x` as a dependency under `install_requires` and `py.typed` under `package_data`.

Then in the MyProject_1 directory, I run MYPYPATH=stubs mypy ..
If package_1_main.py imports x, then mypy successfully type hints the x imports based on stubs/x. All is good here.
Now I've made another project MyProject_2 that depends on MyProject_1 My_Project_2 successfully uses the inline type hints specified in package_1_main.py because of the py.typed under package_1.
The problem is that MyProject_2 does not pick up on stubs/x. Since x is a transitive dependency of MyProject_2 through MyProject_1, I have the ability to use x in MyProject_2. However, this is without the type hints specified under stubs/x.
There are 3 ways I can imagine being able to use these stubs (and thus access the type hints of x):

*

*Add the stubs directory under MyProject_1 to the MYPYPATH when running mypy . in MyProject_2. Downside of this is it depends on how MyProject_1 was installed through pip, and stubs will have to be made as part of the distributed package data in setup.py.

*Copy the stubs directory under MyProject_1 to MyProject_2, keeping them manually in sync. Downside of this is overhead in maintenance.

*Make a third project called MyProject_Stubs, dedicated to keeping the stub files for any project depending on x, either transitively or directly. Downside of this is a dedicated project just for stubs.
Are there any other approaches I could consider? And for the slightly opinionated part: which one of these approaches seems to have the greatest net advantage?

A: There is, AFAIK, no way of sharing stubs transitively.
Instead, you'll have to focus on finding ways of making your stubs available to both projects/making it a dependency of both.
There are roughly six different ways to do so, which I'll list out in roughly increasing order of effort.

*

*Store your stubs somewhere on your local computer and have both your projects refer to it via the MYPYPATH environment variable or config file option.
This is relatively straightforward to do, but the downside is that your projects will only work on your local computer. If you plan for others to use this project, they'll need to obtain your stubs and also set up their MYPYPATH.

*Copy your stubs to your second project. As you said, the main downside here you now need to keep your stubs in sync manually.

*Create a separate git repo for your stubs and add them as a git submodule into your two projects.
This solves the code duplication problem option 2 has. The only real downside is you need to remember to bump your submodule pin in both projects every time you update your stub repo.

*Contribute type hints for your project to typeshed a repository of type hints for Python and either wait for the next mypy release or run mypy with the --custom-typeshed-dir flag/config option.
Note that Typeshed accepts partial stubs and is hoping on switching to a more iterative and rapid release cadence some time in the future.
This option would be the best if you want to open-source your work broadly, but don't necessarily want the burden of maintaining your stubs after you open-source them.
The main downside is you would be unable to unblock yourself immediately.

*Create an X-stubs package with a py.typed file. This is kind of like your option 3, except your new project is explicitly for just project X's stubs and is open-sourced.
You can then add your X-stubs package to your pip dependencies just like any pip package, and perhaps even eventually look into more broadly open-sourcing and distributing them.
This is basically the same as your option 3, except that the name of your package is different and less specific to your project.

*Submit a pull request to project X adding a py.typed file along with some type hints and convince them to land it.
This is easier said than done, of course -- not all projects are willing to accept type hints, of course, since it could lead to an increased maintenance burden for them.
If you care just about unblocking yourself, I'd pick options 1-3. The other options are better fits if you also want to try open-sourcing your work and helping improve the Python typing ecosystem.
I would avoid your option 1 -- it seems to involve roughly the same amount of work to set up as my options 3 and 5 while also requiring more work inside project 2 to use.


text:
Q: IIS rewrite subdomains to another subdomain I have a website, say www.xyz.com
I have another website hosted app.xyz.com
I am looking at redirecting all the subdomain requests to app.xyz.com.
e.g a.xyz.com - app.xyz.com
b.xyz.com - app.xyz.com
c.xyz.com - app.xyz.com
The url in the browser needs to remain a.xyz.com, b.xyz.com or c.xyz.com
Can you help me with the steps involved. What needs to be done in DNS and what rewrite rule needs to be written for IIS. ( For this I don't want to create any folders, sub-domains, binding rules, etc for every entry.)
Will the above work with http and https ?
TIA.

A: If you have the www.xyz.com  set up correctly, you may simply use the following ISAPI_Rewrite rule to resolve this:
RewriteEngine on
RewriteBase /

RewriteCond %{HTTP:Host} ^(?!www\.).+$ [NC]
RewriteCond %{HTTP:Host} ^[^.]+\.xyz\.com$ [NC]
RewriteRule .* http://app.xyz.com [NC,R=301,L]


text:
Q: Harmonic oscillator with squared damping term Does a solution exist for a harmonic oscillator with a squared damping term?
$$m\ddot{u}+c\dot{u}^2+ku=0$$

A: Yes, you can look at Smith (2012) who discusses how you might go about getting solutions to this non-linear differential equation. The results are mathematically very challenging to say the least. They are also not exact, but work as close approximations to what you would get from a brute force numerical technique.
The outcome appears to be that the quadratically damped oscillator undergoes a decaying oscillation, but that the decay rate is slower than exponential (see Fig.6). A second important conclusion is that such an oscillator can never be overdamped or critically damped.
Such systems are of interest when the damping is provided by (for instance) turbulence in a fluid or a damper where there is an opening that allows fluid to escape.

A: When I first learned about harmonic oscillators, I played with Mathematica and learned different solutions for different cases. I tried to solve this equation very long time ago, but unfortunately, I couldn't find any analytical solution for it.
So I have good news and bad news.
The bad news: I don't think analytical solutions exist. If such a model equation has a solution, I think Mathematica would have had it, and it doesn't, so most likely no analytical solutions exist.
The good news is: Analytical solutions are not the only way to solve such a problem. Depending on your application, you can solve this differential equation numerically. Software like Matlab, Mathematica and Maple, and even low programming languages like C/C++ and Fortran can very, very easily solve this equation numerically for any set of parameters you like. Then you can remodel the cases you need with algebraic equations, depending on the complexity of the numerical solutions.
More about such equations:
It may seem attractive to students to solve such equations just for the hell of it, but in reality, it's not important at all. In the physics of the real world, systems are usually linear with a very good approximation. Normally when such crazy, nonlinear terms show up, we don't try to solve their equations analytically (unless it's really easy). The way to go is by using something similar to what we do in quantum mechanics: Perturbation Theory. So we learn the analytical solution of the simple case, and then we add small nonlinear perturbations that make us understand our system better. So in your case, you could find a way to write this equation in a linear way, then make the quadratic term a small perturbation, which is solvable for some approximation.
The bigger challenge on differential equations is not such nonlinear equations, which don't occur in physics that often. Actually it's orders of magnitude more difficult to solve systems of differential equations that occur very often in nature, such as coupled systems of Bloch equations. Although such a system is linear, it's still not possible to generally get an analytical solution for it due to a theorem called the Abel-Ruffini theorem. Notice that the guys in that paper still found a solution to the problem they have in their lab. They simplified the system with an approximation from 6 to 4 equations. That worked well for them!
So the bottom line is: Depending on your application, you may find approximations that will get you the information you need from this differential equation.

A: Assuming we want to study the differential equation
$$\ddot{y} + \alpha\dot{y}^2 + \beta y = 0$$
Then we can easily get rid of $\alpha$ and $\beta$.
$$
\frac{d^2 y}{dt^2}+\alpha \left(\frac{d y}{dt} \right)^2+\beta y=0
$$
Replacing:
$$
t \rightarrow \frac{t}{\sqrt{ \beta }}~~~~~y \rightarrow \alpha y
$$
We will get.
$$
\frac{d^2 y}{dt^2}+\left(\frac{d y}{dt} \right)^2+y=0
$$
Now we make a replacement
$$
w(y)=\left(\frac{d y}{dt} \right)^2
$$
Then:
$$
\frac{d^2 y}{dt^2}=\frac{d \sqrt{w}}{dt} = \frac{d \sqrt{w}}{d y} \frac{d y}{d t} = \frac{d \sqrt{w}}{dy} \sqrt{w}=\frac{d w}{2dy}
$$
The equation transforms to:
$$
\frac{d w}{dy}+2 w+2 y=0
$$
We only need to solve two first order ODEs. The solution for $w$ can be found easily (I used Wolframalpha):
$$
w(y)=C_1 e^{-2y}-y+\frac{1}{2}
$$
Then we need to solve first order nonlinear equation:
$$
\left(\frac{d y}{dt} \right)^2=C_1 e^{-2y}-y+\frac{1}{2}
$$
$$
\frac{d y}{dt}=\pm \sqrt{C_1 e^{-2y}-y+\frac{1}{2}}
$$
Since this equation is fully separable, we can try to approximate the integral. For $C_1=0$ this ODE is exactly solvable.
$$
y=\frac{1}{2}-\left(\frac{t}{2}+C_2 \right)^2
$$

As for the best way to approximate the solution - it heavily depends on the context - if it was a simple pendulum in air for example, then you have harmonic oscillator motion with resistance proportional to velocity squared, and the second term can be interpreted as perturbation. However, since $\alpha$ is positive, it's apparently some other case. There is also the case of nonlinear Schrödinger, and there is a number of methods developed to solve this problem also.
My point is - there can be no 'general' approximate solutions, the appropriate approximation depends on the context of the original problem.


text:
Q: Tomcat multiple requests same user, same url (is that caching? thread keep-alive?) I am working with a new server which I have total control of my Tomcat 7 configurations.
I've optimized my memory usage, permgem space and bzip compression which really is making the difference... but I noticed something in my old server (which I can't control or see the configs)... it seems to be using some kind of caching? or maybe it is just the way the threads are being allocated to handle the requests, I don't know...
By using the Firebug, more specifically, at Net panel, I got this from my old server:

First request from a "tough" process took almost 6s and then the next 2 seems to be cached opening it a lot faster.
In my new server, however, each request seems to be handled by a new thread every time (my guess) and it is going through the tough process each time...

Well, my question is... what can I do in my Tomcat in order to achieve the same results from the old server? Besides my optimizations (memory, compression) is there anything else you could recommend?
That would be all by now, thanks in advance for the answers.

A: probably old server had expiry headers set. you can do that through a Tomcat Valve or if you have a fronting Apache Httpd you can do it there


text:
Q: Conditionally disable button based on reactive form or input state I have a reactive form trainingFeedbackForm with a textarea:
<textarea pInputTextarea appWhiteSpace inputField="{{not_attended_reason}}"
    [(ngModel)]="not_attended_reason" [disabled]="attended==='yes'"
    placeholder="The reason for not attending the traning"
    (inputValue)="removeWhitespace($event)"></textarea>

I want to disable this button when either the form is valid or the textarea is empty:
<button (click)="getFeedbackFormValue()" class="btn-gradient fill-btn ripple"
    [disabled]="trainingFeedbackForm.invalid || !not_attended_reason">
    Submit feedback
</button>

The approach I am using above is not working.
How can I achieve this?  Can somebody help?

A: component.html in
Replace disabled="checkDisbled()" this
add required in  <textarea required>
<button (click)="getFeedbackFormValue()" class="btn-gradient fill-btn ripple"
                disabled="checkDisbled()">
                Submit feedback
              </button>

Add in Component.ts  file
checkDisbled(){
  if(this.trainingFeedbackForm.invalid){ // <- add number of validation
  return true;
  }
  else {
  return false;
  }
}

A: This should do the trick, just added !trainingFeedbackForm.invalid
<button (click)="getFeedbackFormValue()" class="btn-gradient fill-btn ripple"
[disabled]="!trainingFeedbackForm.invalid">
Submit feedback
</button>

Also, make sure that you add Validators.required to each form in your .ts


text:
Q: 32 Bit ODBC ( MYOB ) Runs under IIS / ASP.NET MVC on one Machine but not another Spent a few hours on this. 2 seemingly identical machines with the same code , same operating system. I am trying to open a 32 bit ODBC connection ( MYOB ) that uses a .exe file to access it. It works on one machine fine - but not the other. I have looked at permissions , if 32 bit is allowed - but it just hangs when I try to open the connection - and the myobp.exe file does not start in process. It just hangs indefinietely.  No error message or anything.
any ideas why it is not working? I have given everyone full access to the exe and the exes directory - and all the code and machine is exactly the same. Firewall is completeley disabled even!
How can I get this ODBC driver to open?


text:
Q: QNetworkAccessManager, reset TCP connection I am writing a program in Qt to make HTTP request to an embedded device and using the QNetworkAccessManager to do this and it's working well except for the following case.
The embedded device only accepts 1 TCP connections. If the connection is dropped (cable pulled) while the TCP connection is active, the device gets into a hung state. It doesn't know the connection has dropped and can't accept anymore.
Is there a way to manually reset the QNetworkAccessManager so I can force a new connection on every request and close the connection gracefully when the request has completed?

A: In the reply, check if the QNetworkRequest::HttpPipeliningWasUsedAttribute attribute is set. If it is, then this is your problem: you must modify your request to force a false value on the QNetworkRequest::HttpPipeliningAllowedAttribute. Without pipelining, each request is sent on a separate connection.
Note that QNetworkAccessManager can initiate multiple requests in parallel. You'll have to make sure that you only ever allow one request to be outstanding, and to only place one new request when the previous one is finished.


text:
Q: Can i search for all product in search i'm looking for a way in magento search to display all products. it's for a quick search by attribute purpose, i implemented GET filters which adds attributes to filter to collection list, and i want to apply them to the full products collection.
if(count($_GET) > 0 && $isSearchPage){
$_productCollection = $_productCollection->clear()->addAttributeToSelect('*');
$suffix = array();
foreach($_GET as $filter => $value){
    $suffix[$filter] = $value;
    if($filter != 'q' && $filter != 'limit' && $filter != 'p'){
        $_productCollection->addAttributeToFilter($filter,$value);
    }
}
}

So far i tried
/catalogsearch/result/?q=%
/catalogsearch/result/?q=*

q=% return results, but not all of them. Is there a way to do what i'm trying to achieve ? Or am I heading in the wrong direction

A: Magento alreay have Advanced search feature where you can search the products based on the attribute .You can see the demo of this feature here .Maybe you can extend it according to your need.


text:
Q: Theorem 1.4. of Serge Lang´s Undergraduate Analysis Could somebody explain to me the boxed inequality. I have the feeling that the second member should be $L_1/2^{K-1}$. Thanks.

A: Yes, this looks like an error to me.
By construction, for $k,m\geq K, \space x_{n_k}$ and $x_{n_m}$ are both in $I_K$ which has length $L_K=\frac{L_1}{2^{K-1}}$. Thus, $|x_{n_k}-x_{n_m}|\leq \frac{L_1}{2^{K-1}}$.


text:
Q: How to avoid one condition if i pass a variable value null My question is if i pass value in a variable it should has to check the conditions if i pass a null value in variable it should not consider the condition.please help me..
ex:if i pass firstdateofservice variable as null it should not check the condition
DECLARE @FirstDateofService DATE;
DECLARE @LastDateofService DATE;

SET @FirstDateofService= '04/01/14'; --mm/dd/yyyy
SET @FirstDateofService= CONVERT(varchar(10),@FirstDateofService,21)
SET @ProcessDate  = '10/31/14'; --mm/dd/yyyy
SET @ProcessDate=CONVERT(varchar(10),@ProcessDate,21)

SELECT DISTINCT cs.*
    FROM   claimline cl(nolock)
           JOIN claimsummary cs(nolock)
             ON cs.claimsummaryuid = cl.claimsummaryuid
    WHERE  cisid IN(@Cisid,@cisid1)
           AND cs.firstdateofservice  >=@firstdateofservice
           and cs.lastdateofservice>=@lastdateofservice

A: You can add this condition:
  ...
   WHERE  cisid IN(@Cisid,@cisid1)
         AND (cs.firstdateofservice  >=@firstdateofservice
            OR @firstdateofservice IS NULL)
       and cs.lastdateofservice>=@lastdateofservice

OR add check like this:
SET @FirstDateofService = ISNULL(@FirstDateofService, '19000101')

SELECT DISTINCT cs.*
    FROM   claimline cl(nolock)
           JOIN claimsummary cs(nolock)
             ON cs.claimsummaryuid = cl.claimsummaryuid
    WHERE  cisid IN(@Cisid,@cisid1)
           AND cs.firstdateofservice  >=@firstdateofservice
           and cs.lastdateofservice>=@lastdateofservice

A: You can simply add the null check in the condition like so:
WHERE  cisid IN(@Cisid,@cisid1)
       AND (@firstdateofservice IS NULL OR cs.firstdateofservice  >=@firstdateofservice)
       and cs.lastdateofservice>=@lastdateofservice

A: simply add the null condition here like
SELECT DISTINCT cs.*
    FROM   claimline cl(nolock)
           JOIN claimsummary cs(nolock)
             ON cs.claimsummaryuid = cl.claimsummaryuid
    WHERE  cisid IN(@Cisid,@cisid1)
           AND
 (cs.firstdateofservice  >=@firstdateofservice  or  isnull(@firstdateofservice , '') = '')
 and (cs.lastdateofservice>=@lastdateofservice or isnull(@firstdateofservice , '') = '')

A: Is this what you are expecting ?.
DECLARE @FirstDateofService DATE;
DECLARE @LastDateofService DATE;

SET @FirstDateofService= '04/01/14'; --mm/dd/yyyy
SET @FirstDateofService= CONVERT(varchar(10),@FirstDateofService,21)
SET @ProcessDate  = '10/31/14'; --mm/dd/yyyy
SET @ProcessDate=CONVERT(varchar(10),@ProcessDate,21)

IF @FirstDateofService IS NULL
SELECT DISTINCT cs.*
    FROM   claimline cl(nolock)
           JOIN claimsummary cs(nolock)
             ON cs.claimsummaryuid = cl.claimsummaryuid
    WHERE  cisid IN(@Cisid,@cisid1)
           and cs.lastdateofservice>=@lastdateofservice
ELSE
SELECT DISTINCT cs.*
    FROM   claimline cl(nolock)
           JOIN claimsummary cs(nolock)
             ON cs.claimsummaryuid = cl.claimsummaryuid
    WHERE  cisid IN(@Cisid,@cisid1)
           AND cs.firstdateofservice  >=@firstdateofservice
           and cs.lastdateofservice>=@lastdateofservice

A: you can change your WHERE in this format (column = @filter OR @filter IS NULL) AND (column2 = @filter2 OR @filter2 IS NULL)
Something like this.
SELECT DISTINCT cs.*
    FROM   claimline cl(nolock)
           JOIN claimsummary cs(nolock)
             ON cs.claimsummaryuid = cl.claimsummaryuid
    WHERE  (cisid IN(@Cisid,@cisid1) OR (@Cisid IS NULL AND @cisid1 IS NULL ) )
           AND (cs.firstdateofservice  >=@firstdateofservice OR @firstdateofservice IS NULL)
           and (cs.lastdateofservice>=@lastdateofservice OR @lastdateofservice IS NULL)


text:
Q: Getting a new variables from a function I have 3 files
Main which contains a function call when the application is launched
void main() async {
  await FunctionCall().numberColumnFunction();
  runApp(const MyApp());
}

Function in which the called function and variables are located:
class FunctionCall {

  int numberColumn = 3;

  int columnsPositioned = 5;
  var visibilityColumn = false;

    numberColumnFunction(){
      if (numberColumn == 3) {
        columnsPositioned = 8;
        visibilityColumn = true;
      }
      else {
        null;
      }
    }
}

And ColumnView in which I get variables from the Function for further work with them:
// More code
     end: width / FunctionCall().columnsPositioned,
// More code
     visible: FunctionCall().visibilityColumn,
// More code

The problem is that in ColumnView the variables declared by me with default values are always called
  int columnsPositioned = 5;
  var visibilityColumn = false;

Even if the function conditions are met and the values in the variables change, the call still goes to the old values. How do I make ColumnView take values after executing the function ?

A: The traditional and programming way I can think of right now is making that class a singleton. You can search and do more research on singleton classes and factory pattern. But for now, this code should solve your problem ->
class FunctionCall {
 FunctionCall._sharedInstance(); //This is a private constructor.
 static final FunctionCall _shared = FunctionCall._sharedInstance(); // This is the instance we want to send every time.
 factory FunctionCall() => _shared; // This is where we send it every time the class is created!

 int numberColumn = 3;
 int columnsPositioned = 5;
 var visibilityColumn = false;

numberColumnFunction(){
  if (numberColumn == 3) {
    columnsPositioned = 8;
    visibilityColumn = true;
  }
  else {
    null;
    }
  }
}

Basically, the problem was, Every time you called the class like this FunctionCall() It was creating a new class. And a new class would always have the default class data. Bcz the function didn't get called inside the new class. So to stop making a new instance of your class you can try this way of making your class a singleton. And returning the exact same instance of your class when it is initiated! And Done!

A: You are creating the FunctionCall() object inside the main function. The Visibility Column for this object is true. However, you are creating a new FunctionCall() object inside the ColumnView widget. The visibilityColumn value of this object is initially set to false. They are two different objects.
My suggestion:
FunctionCall functionCall = FuncitonCall();

Define the above code globally.
Edit this object in main and use the same object in ColumnView widget.


text:
Q: Using list comprehension to create a list of lists in a recursive function I am experimenting with recursive functions. My goal is to produce:

A function combo that generates all non-increasing series that add up to n

Some sample inputs/outputs:
>>> print (combo(3))
[[3], [2, 1], [1, 1, 1]]
>>> print (combo(4))
[[4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]
>>> print (combo(5))
[[5], [4, 1], [3, 2], [3, 1, 1], [2, 2, 1], [2, 1, 1, 1], [1, 1, 1, 1, 1]]

After a lot of trial and error, I came up with the following function which does exactly what I want:
def combo(n, limit=None):
    if not limit:
        limit = n
    # return [ LIST COMPREHENSION HERE ]
    res = []
    for i in range(limit, 0, -1):
        if i == n:
            res.append([i])
        else:
            res.extend([i] + x for x in combo(n - i, min(n - i, i)))
    return res

My question: Is there a way (pythonic or not) to return this same result using a single list comprehension, without appending to and extending res?
Here are two things I've tried, along with their mangled results:
return [[i] if i == n else [[i] + x for x in combo(n - i, min(n - i, i))] for i in range(limit, 0, -1)]
# lists get deeper: [[4], [[3, 1]], [[2, 2], [2, [1, 1]]], [[1, [1, [1, 1]]]]]

return [[i if i == n else ([i] + x for x in combo(n - i, min(n - i, i))) for i in range(limit, 0, -1)]]
# parentheses interpreted as generator: [[4, <generator object combo.<locals>.<listcomp>.<genexpr> at 0x01D84E40>, etc.]]

I realize that the answer may be quite ugly, but I've spent enough time trying that I just want to know if it is possible.

A: Convert extending to appending and it becomes easier to grok how to convert this:
res = []
for i in range(limit, 0, -1):
    if i == n:
        res.append([i])
    else:
        # this is the generator expression pulled out of the res.extend() call
        for x in combo(n - i, min(n - i, i)):
            res.append([i] + x)

You can now move the i == n case into the other branch (using a helper items variable here for readability):
res = []
for i in range(limit, 0, -1):
    items = [[]] if i == n else combo(n - i, min(n - i, i))
    for x in items:
        res.append([i] + x)

If i == n, this causes the loop iterate once and produce an empty list, so you effectively get res.append([i]).
This can then trivially be converted to a list comprehension (inlining items into the for loop):
return [
    [i] + x
    for i in range(limit, 0, -1)
    for x in ([[]] if i == n else combo(n - i, min(n - i, i)))]

Wether or not you should is another matter; this is hardly easier to read.


text:
Q: XSLT html mixed table body I have a sample XML which needs to be rendered to html. When the OBX.5 is greater than 20 characters, I want to show it in a paragraph other wise the atomic values of the same need to be clubbed into a table. I tried the XSL below, but it produces empty table and nothing in the paragraph. What should be  corrected in the XSL  for the desired output?
I also want to assign the table header. So how do I detect the OBX.5 is a free-text(>30) or atomic type and setup the table in the XSLT?
XML file
    <?xml version="1.0" encoding="UTF-8"?>
    <ORU.ORC_OBR__OBX_NTE>
    <OBX>
        <OBX.5>Negative by specific anti-\.br\human haemoglobin antibody method.\.br\This suggests proximal G.I.T. bleed or diet/drug interference.\</OBX.5>
    </OBX>
    <OBX>
        <OBX.5>No Salmonella, Shigella, Campylobacter or Yersinia isolated</OBX.5>
    </OBX>
    <OBX>
            <OBX.5>THROAT</OBX.5>
    </OBX>
    <OBX>
            <OBX.5>NEGATIVE</OBX.5>
    </OBX>
    <OBX>
            <OBX.5>129</OBX.5>
    </OBX>

</ORU.ORC_OBR__OBX_NTE>

XSLT file
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">

      OBX.5

                        <xsl:for-each select="ORU.ORC_OBR__OBX_NTE/OBX">
                                <xsl:variable name="result">
                                    <xsl:value-of select="OBX.5"/>
                                </xsl:variable>

                                    <xsl:choose>
                                        <xsl:when test="string-length($result) < 30">

                                                <xsl:value-of select="$result"/>

                                        </xsl:when>
                                        <xsl:otherwise>

                                                <xsl:value-of select="$result"/>

                                        </xsl:otherwise>
                                    </xsl:choose>

                            </xsl:for-each>

    </xsl:template>
</xsl:stylesheet>

HTML I get is

                OBX.5

Negative by specific anti-\.br\human haemoglobin antibody method.\.br\This suggests proximal G.I.T. bleed or diet/drug interference.\

No Salmonella, Shigella, Campylobacter or Yersinia isolated

                THROAT

                NEGATIVE

                129

HTML I want as result is

Negative by specific anti-\.br\human haemoglobin antibody method.\.br\This suggests proximal G.I.T. bleed or diet/drug interference.\

No Salmonella, Shigella, Campylobacter or Yersinia isolated

                OBX.5

                THROAT

                NEGATIVE

                129

Additional examples:
Input XML
<?xml version="1.0" encoding="UTF-8"?>
<ORU.ORC_OBR__OBX_NTE>
    <OBX>
        <OBX.5>Negative by specific anti-\.br\human haemoglobin antibody method.\.br\This suggests proximal G.I.T. bleed or diet/drug interference.\</OBX.5>
    </OBX>
    <OBX>
        <OBX.5>No Salmonella, Shigella, Campylobacter or Yersinia isolated</OBX.5>
    </OBX>
    <NTE>
        <NTE.3>After the 5 dots is a Carat.....^\.br\</NTE.3>
    </NTE>
    <OBX>
        <OBX.5>THROAT</OBX.5>
    </OBX>
    <OBX>
        <OBX.5>NEGATIVE</OBX.5>
    </OBX>
    <OBX>
        <OBX.5>Yersinia isolated</OBX.5>
    </OBX>
    <NTE>
        <NTE.3>After the 5 dots is a Carat.....^\.br\</NTE.3>
    </NTE>
    <OBX>
        <OBX.5>129</OBX.5>
    </OBX>
    <OBX>
        <OBX.5>129</OBX.5>
    </OBX>
    <OBX>
        <OBX.5>130</OBX.5>
    </OBX>
    <OBX>
        <OBX.5>131</OBX.5>
    </OBX>
    <OBX>
        <OBX.5>132</OBX.5>
    </OBX>
    <NTE>
        <NTE.3>After the 5 dots is a Carat.....^\.br\</NTE.3>
    </NTE>
</ORU.ORC_OBR__OBX_NTE>

Output html

        Negative by specific anti-\.br\human haemoglobin antibody method.\.br\This suggests proximal G.I.T. bleed or diet/drug interference.\

        No Salmonella, Shigella, Campylobacter or Yersinia isolated

        After the 5 dots is a Carat.....^\.br\

                OBX.5

        THROAT

        NEGATIVE

        Yersinia isolated

        After the 5 dots is a Carat.....^\.br\

                OBX.5

        129

        129

        130

        131

        132

        After the 5 dots is a Carat.....^\.br\

A: The following stylesheet:
XSLT 1.0
<?xml version="1.0" encoding="UTF-8"?>
<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:template match="/">

            <xsl:apply-templates select="ORU.ORC_OBR__OBX_NTE/OBX[string-length(.) >= 30]" mode="p"/>

                    OBX.5

                <xsl:apply-templates select="ORU.ORC_OBR__OBX_NTE/OBX[string-length(.) < 30]" mode="tr"/>

</xsl:template>

<xsl:template match="OBX" mode="p">

        <xsl:value-of select="."/>

</xsl:template>

<xsl:template match="OBX" mode="tr">

            <xsl:value-of select="."/>

</xsl:template>

</xsl:stylesheet>

will return the required result in your example case. As I said in the comments, I am not sure what you want to do when the short and long values are interspersed.
Note also that the table is created without checking if any short values exist - you might want to add that yourself.


text:
Q: Convert Quarter + Year to a date I have two fields I need to combine and convert to a date. These two fields are i) Quarter &
ii) Year
For example Q2 2017
01/04/2018
I don't have a field for the day so I just want to keep it to the first of the month.
Please could someone help with the SQL. I need to add to a select statement.

A: In Microsoft SQL Server you can do this as followed:
First I create a date as varchar which I then convert to the Date datatype. After this I format it to the desired format. I use a CASE Clause to get the correct month by the quarter.
SELECT FORMAT(CONVERT(DATE,CAST([Year] AS VARCHAR(4))+'-'+
                    CAST(CASE
                         WHEN [Quarter] = 'Q1' THEN '01'
                         WHEN [Quarter] = 'Q2' THEN '04'
                         WHEN [Quarter] = 'Q3' THEN '07'
                         WHEN [Quarter] = 'Q4' THEN '10' END AS VARCHAR(2))+'-'+
                    CAST('01' AS VARCHAR(2))), 'dd-MM-yyyy', 'en-us')
                    from dates

A: If you are using SQL SERVER , then you can try something like this:
SELECT
  CONCAT(Quarter,
  CONVERT(date, DATEADD(MONTH, DATEDIFF(MONTH, 0, year), 0))) AS StartOfMonth
FROM Table1;

If you need some space in between Quarter and Year then, add ' '.
SELECT
  CONCAT(Quarter,' ',
  CONVERT(date, DATEADD(MONTH, DATEDIFF(MONTH, 0, year), 0))) AS StartOfMonth
FROM Table1;


text:
Q: IOS Framework Localization not working I have a framework created from our app, and the framework when added to a new project to be used, it works perfectly.
Now we want to add localization for different languages and we did that in the app, and everything works good, but now we want to update our framework to be also localized with multiple languages. So we added all the localized xib and its strings inside the framework, but only English is being shown all the time from the nib files in the framework.
I am not really familiar with frameworks, since it was done by anyother person, and we just follow how to change the files and create updated frameworks.
I have been trying to find some information on the internet, but all i have found is how to change the UILabel inside the code, and not by localizing the nib files.
Any suggestions?

A: I know this question was asked more than a year ago, but I encountered this issue recently and I would like to share what I did to resolve this.
Your framework's localization is probably working just fine, you just have to make sure that the project using your framework supports localization as well.
Go to your project's Info.plist and look for CFBundleLocalizations (add it if it doesn't exist). Add the language codes you want to support and run.
List language codes are available here:
http://www.ibabbleon.com/iOS-Language-Codes-ISO-639.html


text:
Q: New things and limitations in Version 12 numerical differential equation solver? This question is intended to be a place to summarize users' exemplary experience in solving differential equation with the NDSolve family in MMA's latest version 12.
Since there are so many differential equations and some are difficult, each time a major update may help resolve early bugs/issues and solve some new types. And certainly, many remain unable to be handled.
I personally have not yet tried much with the new solvers. Let me just list a few possible things of interest to get the ball rolling.

*

*At least it is now equipped with a nonlinear FEM solver. But it certainly cannot solve all and contains bugs as well. Any info
on that would be helpful to many of us.

*Is it possible to control DifferenceOrder in NDSolve or NDEigenvalue, say, when solving an ODE?

*What other new equations become solvable now?

Please feel free to edit this question.

A: I test nonlinear FEM using solutions obtained by other methods. I developed one of these methods for the problem of the nature convection, aerodynamics, and unsteady hydrodynamics, using linear FEM - see Solver for unsteady flow with the use of Mathematica FEM . Let me give an example. After the release of Mathematica version 12, I tested a non-linear FEM on the convection problem and compared it with my method. Surprisingly, the coincidence is one to one. The following code generates the same output as my code implementing the method of the false transient from the paper Vahl Davis, G.de (1983) : Natural convection of air in a square cavity : A bench mark numerical solution. Int. J. Numer. Methods Fluids 3, 249-264.
Code based on nonlinear FEM
Pr0 = .72; Ra = 10^5; R = Ra*Pr0; a = 0;
\[CapitalOmega] = ImplicitRegion[0 <= x <= 1 && 0 <= y <= 1, {x, y}];

{UX, VY, \[CapitalRho], TK, TX} =
  NDSolveValue[{{Inactive[
          Div][({{-\[Mu], 0}, {0, -\[Mu]}}.Inactive[Grad][
            u[x, y], {x, y}]), {x, y}] + D[p[x, y], x] +
        u[x, y]*D[u[x, y], x] + v[x, y]*D[u[x, y], y] -
        R*T[x, y]*Sin[a],
       Inactive[
          Div][({{-\[Mu], 0}, {0, -\[Mu]}}.Inactive[Grad][
            v[x, y], {x, y}]), {x, y}] + D[p[x, y], y] +
        u[x, y]*D[v[x, y], x] + v[x, y]*D[v[x, y], y] -
        R*T[x, y]*Cos[a], D[u[x, y], x] + D[v[x, y], y]} == {0, 0,
       0} /. \[Mu] -> Pr0, {
     DirichletCondition[{p[x, y] == 0}, y == 1 && x == 1],
     DirichletCondition[{u[x, y] == 0, v[x, y] == 0},
      y == 0 || y == 1]}, {u[x, y]*D[T[x, y], x] +
       v[x, y]*D[T[x, y], y] - (D[T[x, y], x, x] +
         D[T[x, y], y, y]) == NeumannValue[0, y == 0 || y == 1],
     DirichletCondition[{u[x, y] == 0, v[x, y] == 0, T[x, y] == 1},
      x == 0],
     DirichletCondition[{u[x, y] == 0, v[x, y] == 0, T[x, y] == 0},
      x == 1]}}, {u, v, p, T,
\!\(\*SuperscriptBox[\(T\),
TagBox[
RowBox[{"(",
RowBox[{"1", ",", "0"}], ")"}],
Derivative],
MultilineFunction->None]\)}, {x, y} \[Element] \[CapitalOmega],
   Method -> {"FiniteElement",
     "InterpolationOrder" -> {u -> 2, v -> 2, p -> 1, T -> 2},
     "MeshOptions" -> {"MaxCellMeasure" -> 0.0001}}];

Compare with a bench mark numerical solution
MaximalBy[Table[{x, VY[x, .5]}, {x, 0, 1, .0001}], Last]

(*Out[5]= {{0.066, 68.7316}}*)

(*BenchmarkCase={x=0.066,vmax=68.59}*)

MaximalBy[Table[{y, UX[0.5, y]}, {y, 0, 1, .0001}], Last]

(*Out[8]= {{0.8543, 34.6607}}*)

(*BenchmarkCase={y=0.855,umax=34.73}*)
 MaximalBy[Table[{y, -TX[0, y]}, {y, 0, 1, 0.0001}], Last]

(*Out[12]= {{0.0747, 7.73417}}*)

(*BenchmarkCase={y=0.081,Numax=7.717}*)

 NuAv =
 NIntegrate[UX[x, y]*TK[x, y] - TX[x, y], {x, 0, 1}, {y, 0, 1},
  WorkingPrecision -> 5]

(*Out[14]= 4.4880*)

(*BenchmarkCase=4.519*)

Nu0 = NIntegrate[-TX[0, y], {y, 0, 1}, WorkingPrecision -> 5]

(*Out[16]= 4.5274*)

(*BenchmarkCase=4.509*)

Nu05 =
 NIntegrate[UX[.5, y]*TK[.5, y] - TX[0.5, y], {y, 0, 1},
  WorkingPrecision -> 5]

(*Out[18]= 4.5252*)

(*BenchmarkCase=4.519*)

MinimalBy[Table[{y, -TX[0, y]}, {y, 0, 1, 0.0001}], Last]

(*Out[19]= {{1., 0.726786}}*)

(*BenchmarkCase={y=1,Numin=0.729}*)

Code based on linear FEM
k = 100; Pr0 = .72; Ra = 10^5; R = Ra*Pr0; t0 = 1/100; a = 0;
\[CapitalOmega] = ImplicitRegion[0 <= x <= 1 && 0 <= y <= 1, {x, y}];
UX[0][x_, y_] := 0;
VY[0][x_, y_] := 0;
\[CapitalRho][0][x_, y_] := 0;
TK[0][x_, y_] := 0; TX[0][x_, y_] := 0;
Do[
  {UX[i], VY[i], \[CapitalRho][i], TK[i], TX[i]} =
   NDSolveValue[{{Inactive[
           Div][({{-\[Mu], 0}, {0, -\[Mu]}}.Inactive[Grad][
             u[x, y], {x, y}]), {x, y}] + D[p[x, y], x] +
         UX[i - 1][x, y]*D[u[x, y], x] +
         VY[i - 1][x, y]*D[u[x, y], y] + (u[x, y] - UX[i - 1][x, y])/
          t0 - R*T[x, y]*Sin[a],
        Inactive[
           Div][({{-\[Mu], 0}, {0, -\[Mu]}}.Inactive[Grad][
             v[x, y], {x, y}]), {x, y}] + D[p[x, y], y] +
         UX[i - 1][x, y]*D[v[x, y], x] +
         VY[i - 1][x, y]*D[v[x, y], y] -
         R*T[x, y]*Cos[a] + (v[x, y] - VY[i - 1][x, y])/t0,
        D[u[x, y], x] + D[v[x, y], y]} == {0, 0, 0} /. \[Mu] -> Pr0, {
      DirichletCondition[{p[x, y] == 0}, y == 1 && x == 1],
      DirichletCondition[{u[x, y] == 0, v[x, y] == 0},
       y == 0 || y == 1]}, {UX[i - 1][x, y]*D[T[x, y], x] +
        VY[i - 1][x, y]*D[T[x, y], y] + (T[x, y] - TK[i - 1][x, y])/
         t0 - (D[T[x, y], x, x] + D[T[x, y], y, y]) ==
       NeumannValue[0, y == 0 || y == 1],
      DirichletCondition[{u[x, y] == 0, v[x, y] == 0, T[x, y] == 1},
       x == 0],
      DirichletCondition[{u[x, y] == 0, v[x, y] == 0, T[x, y] == 0},
       x == 1]}}, {u, v, p, T,
\!\(\*SuperscriptBox[\(T\),
TagBox[
RowBox[{"(",
RowBox[{"1", ",", "0"}], ")"}],
Derivative],
MultilineFunction->None]\)}, {x, y} \[Element] \[CapitalOmega],
    Method -> {"FiniteElement",
      "InterpolationOrder" -> {u -> 2, v -> 2, p -> 1, T -> 2},
      "MeshOptions" -> {"MaxCellMeasure" -> 0.0001}}], {i, 1, k}];

Compare with a bench mark numerical solution
MaximalBy[Table[{x, VY[k][x, .5]}, {x, 0, 1, .0001}], Last]

(*Out[9]= {{0.066, 68.7316}}*)

(*BenchmarkCase={x=0.066,vmax=68.59}*)

MaximalBy[Table[{y, UX[k][0.5, y]}, {y, 0, 1, .0001}], Last]

(*Out[12]= {{0.8543, 34.6607}}*)
(*BenchmarkCase={y=0.855,umax=34.73}*)

MaximalBy[Table[{y, -TX[k][0, y]}, {y, 0, 1, 0.0001}], Last]

(*Out[16]= {{0.0747, 7.73417}}*)

(*BenchmarkCase={y=0.081,Numax=7.717}*)

 NuAv =
 NIntegrate[
  UX[k][x, y]*TK[k][x, y] - TX[k][x, y], {x, 0, 1}, {y, 0, 1},
  WorkingPrecision -> 5]

(*Out[18]= 4.4880*)
In[19]:= (*BenchmarkCase=4.519*)

 Nu0 =
 NIntegrate[-TX[k][0, y], {y, 0, 1}, WorkingPrecision -> 5]

(*Out[20]= 4.5274*)

(*BenchmarkCase=4.509*)

 Nu05 =
 NIntegrate[UX[k][.5, y]*TK[k][.5, y] - TX[k][0.5, y], {y, 0, 1},
  WorkingPrecision -> 5]

(*Out[22]= 4.5252*)

(*BenchmarkCase=4.519*)

MinimalBy[Table[{y, -TX[k][0, y]}, {y, 0, 1, 0.0001}], Last]

(*Out[23]= {{1., 0.726786}}*)

(*BenchmarkCase={y=1,Numin=0.729}*)

Note that both methods nonlinear and linear FEM are consistent with each other and with the third method, published by Davis, G.de (1983) : Natural convection of air in a square cavity : A bench mark numerical solution. Int. J. Numer. Methods Fluids 3, 249-264.

A: Re question 3:
There are NBodySimulation and NBodySimulationData.
Related Q&A: (25562), (31094), (38478), (63571), (81340), (81340), (105342), (121035), (133349), (135857), (164196), (181275)

A: Re question 2 and NDSolve:
How to control "DifferenceOrder" at each step has been shown in this tutorial, which has been available for several versions.  Dynamic control of order is usually not simple, since you have to evaluate whether to change the order every step (or every $k^{\rm th}$ step).
One can control the order for certain method families, such as the Runge-Kutta ones (explicit, implicit, and symplectic).
The connection between difference order and interpolation order is explored in this answer.


text:
Q: When I run my code, i get a segfault, but when the debugger runs it, it says there is no issue I'm doing an assignment that is working with shared memory, and i'm getting segfaults whenever I run the code. So i tried using the GDB debugger to see where the fault is occurring,but when it runs the code, it exits normally and says its fine. i pasted what wasin the terminal below
./main
This is the cb 16669520, This is the dbInfo 2117869600, and this is the db 2117869608
this is the number of processes 1
Segmentation fault (core dumped)

the first two lines it prints out are fine, but the code never reaches the end of the main. THen when I run the debugger...
gdb ./main
(gdb) run
Starting program: /*path*/
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
This is the cb -8848, This is the dbInfo -243544032, and this is the db -243544024
this is the number of processes 2
The code got this far[Inferior 1 (process 15840) exited normally]
(gdb) backtrace
No stack.

A: Run your program with valgrind. It will detect invalid reads and writes to memory, tell you where they happen and, most likely, be helpful enough to tell you exactly what line caused them. One of these errors is what's causing your program to segfault.
Don't forget to add the -ggdb3 flag when compiling your program :)

A: If valgrind does not help (usually it wlll), consider enabling warning at compile time. If possible, the compile should be 'clean', without any warning. GCC can detect many common errors.
gcc -Wall ... file.c

# or even
gcc -Wall -Wextra ... file.c

from gcc man:

  -Wall
       This enables all the warnings about constructions that some users
       consider questionable, and that are easy to avoid (or modify to
       prevent the warning), even in conjunction with macros.  This also
       enables some language-specific warnings described in C++ Dialect
       Options and Objective-C and Objective-C++ Dialect Options.
  -Wextra
       This enables some extra warning flags that are not enabled by
       -Wall. (This option used to be called -W.  The older name is still
       supported, but the newer name is more descriptive.)


text:
Q: How to get the total time of an audio file? How to get the total time of an audio file? I am trying this:
QMediaPlayer* audioPlayer = new QMediaPlayer();
audioPlayer->setMedia(QUrl::fromLocalFile("F:/Audio/mysong.mp3"));
audioPlayer->duration(); // return 0

but all the time the function returns 0. I use the latest version Qt on Windows 8.

A: Yes, i found error, it was to type conversion (qint64)
In order to get the duration you need to use "durationChanged" signal.
//get duration in durationChanged signal.
connect(audioPlayer, SIGNAL(positionChanged(qint64)), this, SLOT(setPositionSlider(qint64)));
//Old function
void Widget::setPositionSlider(qint64 i)
{
    ui->PositionSlider->setValue(i / duration * 100); //0 I thought it was converted into double.
}
//New function
void Widget::setPositionSlider(qint64 i)
{
    ui->PositionSlider->setValue(i / 1000);
}


text:
Q: Image hover not working..on pure css

submenu2

submenu2

submenu2

submenu2

submenu2

submenu2

submenu2

submenu2

css
#headermenu ul ul {
    display: none;
}
#headermenu ul{
    padding:0;
    margin:0;
    white-space:nowrap;
}
#headermenu ul li{
    width: 20%;
    list-style-type:none;
    display:inline-block;
    margin-bottom:15px;
    float:left;
    left:0;
}
#menu1:hover{
    background: url('images/menu1hover.png');
}

Hover is not working, I wonder how to make a list with image hover, I also want to know how to make a sub list when a li is hover. And if there is another list on sub list how to make it.. on pure css..

A: As you haven't given us all the information we need to solve this I will take a guess. As I said in the comments. It could be caused by the  sitting on the background, so when you hover you cant see the background at all.
HTML:

CSS:
#headermenu ul ul {
    display: none;
}
#headermenu ul {
    padding:0;
    margin:0;
    white-space:nowrap;
}
#headermenu ul li {
    width: 20%;
    height: 50px;
    list-style-type:none;
    display:inline-block;
    margin-bottom:15px;
    float:left;
    overflow: hidden;
    border: 1px solid;
}
#menu1:hover {
    background: url('http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg');
}

Here is your code as is, the background image is changing but cannot be seen because of the  in front.
DEMO HERE

Now here is the same code but the  being removed.

DEMO HERE
We can see that the hover does work but the  was coving it up.

Solutions:
Just simply set a background on each li and then a background when on hover.
CSS:
#menu1 {
    background: url('http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg');
}
#menu1:hover {
    background: url('http://img.gawkerassets.com/img/19euo1gaaiau9jpg/original.jpg');
}

DEMO HERE
You could also set the display to none for the img when on hover.
CSS:
#menu1 {
    background: url('http://icdn4.digitaltrends.com/image/microsoft_xp_bliss_desktop_image-650x0.jpg');
}
#menu1:hover img {
    display: none;
}

DEMO HERE
There are many more ways but these are two that will work.

A: You need to use either a background image, or an actual img for both before and after states. In your example, when the mouse hovers over #menu1 the background behind the menu1.png image is changed but menu1.png is obscuring it from view.

A: try this code
DEMO

.urlImg { width: 140px; height:140px; display:block; background-image: url("http://imgsrc.ru/images/reco/140/windkitten_38083968.jpg"); } .urlImg:hover { background-image: url('http://placehold.it/140x140'); }


text:
Q: Understanding Matplotlib's quiver plotting I'm trying to understand how plt.quiver() works. My issue is as follows:
I plot a simple vector (1,1) as such:
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(2)
ax = fig.add_subplot(111)
ax.quiver(0,0, 1, 1, units = 'xy', scale = 1)
plt.xticks(range(-5,6))
plt.yticks(range(-5,6))
plt.grid()

I would expect the arrow to go from (0,0) to (1,1), but the result is slightly off from that:
Similarly, I try and plot an arrow for vector (0,3) and the resulting arrow seems to be for vector (0,3.5)...

My assumption is that this has something to do with the kwargs 'units', 'scale', 'angles', & 'scale_units'. I've read the docs on them but don't fully understand how they work. A sunday school explanation would be greatly appreciated!

A: If you adjust the aspect ratio of the figure to 1, the vectors are displayed to proper scale:
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.quiver((0,0), (0,0), (1,0), (1,3), units = 'xy', scale = 1)
plt.axis('equal')
plt.xticks(range(-5,6))
plt.yticks(range(-5,6))
plt.grid()
plt.show()

A: You can try this code.
import matplotlib.pyplot as plt

fig = plt.figure(2)
ax = fig.add_subplot(111)
ax.quiver(0,0, 1, 1,angles='xy', scale_units='xy', scale = 1)
plt.xticks(range(-5,6))
plt.yticks(range(-5,6))
plt.grid()
plt.draw()
plt.show()

Just remember that the first two arguments of quiver are the x and y coordinates of the tail of the vector, the next two are the lengths of the vector along x and y direction respectively. angle='xy' makes the arrow point from tail of the vector to its tip.
You can find out more about matplotlib.quiver at http://matplotlib.org/1.3.1/api/pyplot_api.html#matplotlib.pyplot.quiver


text:
Q: Select Not returning results when an Update statement is running on the same row? I have a table where it has columns as
Task_Track

*

*TaskID Number (PK AutoGeneratedSequence)

*TaskCd Varchar2

*RefCd Varchar2

*RefID varchar2

*Params varchar2

*...etc

I am working on a scenario where I run a select query on this table get the result set.

Select * from Task_Track where RefCd = ? and RefID = ? and TaskCd = ?;

If i don't have any results I will insert a new task with RefCd RefID TaskCd Params values. Params is ususaly a person_id related to the task.
If i get the resultset I will append the new param and update the resultset.

if(resultset!=null and resultSet.length()>0)
update params logic
else
insert new task logic.

This is working as expected in a sequential run.
But when I have 2 parallel queues running and get the same RefCd RefID TaskCd values at the same time.
My first bucket is finding the resultset and is going to perform the update logic as expected but the second queue is not able to find the result and is going into insert logic.
From what I understand even if the first queue has locked the row for the update, the second queue should not have any problems with the read and should fail while updating because of the lock if the first queue hasn't released the lock. But my read itself is failing where it is not throwing any exception but returning an empty resultset(length=0). Because of which it is moving into insert logic.
Is it possible that the read is affected by the update happening in parallel? If so how should I resolve it?
Note: I am using Oracle 11G and Java8 with Websphere 9
Thank you

A: You need to cache the resultSet before make another request. Try this:
CachedRowSet crs = RowSetProvider.newFactory().createCachedRowSet();
crs.populate(myResultSet);


text:
Q: Hiding JQuery Accordion Content From View I am trying to achieve the following using the JQuery Accordion code:

*

*Make sure content hidden within the accordion is not displayed (i.e. flashes up briefly) whilst the page is loading. I only want the user to see this content if they expand the accordion but in some browsers I can see this content whilst the page is loading.

*Display the accordion H1 tab (e.g. Accordion Test) but none of the content hidden beneath it if the user has Javascript disabled.

To give you an example this is the sort of thing I am trying to emulate:
http://www.outdoorgb.com/c/inflatable_boats_kayaks/
Try clicking on the Read More button, further info is displayed. Now try disabling Javascript. You will note that clicking the button does nothing and the further info is not displayed. You might say in response to this that it is not a good thing for this to happen as Google may not crawl that content etc. However, running this URL through Lynx it appears to read the content fine. Does anyone think this could be a problem?
Anyway, this is the code that I am looking to adapt to satisfy my points above:
 <!doctype html>

  <meta charset="utf-8" />
  <title>Accordion Test</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />

  <link rel="stylesheet" href="http://www.jqueryui.com/resources/demos/style.css" />

Accordion Test

Mauris mauris ante, blandit et, ultrices a, suscipit eget. Integer ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit amet, nunc. Nam a nibh.

Donec suscipit eros. Nam mi. Proin viverra leo ut odio.

Any help that any of you experts out there can provide would be gratefully appreciated.
Many thanks in advance
Jon
==============================================
Update
==============================================
Thanks to Pete's help I have solved the first of these issues. Anyone have any idea how to solve hiding the content if javascript is disabled? Current code looks like this:
<!doctype html>

  <meta charset="utf-8" />
  <title>Accordion Test</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />

  <link rel="stylesheet" href="http://www.jqueryui.com/resources/demos/style.css" />

Accordion Test

Mauris mauris ante, blandit et, ultrices a, suscipit eget. Integer ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit amet, nunc. Nam a nibh.

Donec suscipit eros. Nam mi. Proin viverra leo ut odio.

A: Google crawls my content when it's included in the DOM when the page loads even if the content is not displayed to the user 100% of the time (e.g. in accordions or rollover tooltips).
I don't see any problem with the "read more" text being unavailable if the person doesn't have Javascript enabled because the text isn't critical to use the page.  I have never heard from a single client or a report from their customers that an issue existed from disabled JS.
Here is some useful reading on disabled JS browsing Browser statistics on JavaScript disabled
If JS disabling is a real concern for your user group then another option is using CSS to handle your accordion with something like this
http://www.hongkiat.com/blog/css-content-accordion/

A: You can try something like

Accordion Test

Mauris mauris ante, blandit et, ultrices a, suscipit eget. Integer ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut odio.

and then on your document ready just call $('#hideAccordion').show() or better still if there is a function that gets called after your accordion has loaded call this in it
something like
 $(document).ready(function() {
    $( "#accordion" ).accordion({
      collapsible: true,
      active: false,
      heightStyle: "content"
    });
    $('#hideAccordion').show();
  });

EDIT
Sorry, I have just read your question again and as you are not bothered about showing the content when the javascript is disabled you can simply use the following styles in your style sheet:
#accordion div {display:none;}

Once the accordion loads it should then work as normal without any of the content showing whilst the page is loading.  One point I would make about this is that it isn't very accessible but it just depends on if you are bothered about coding to w3c standards, and some search engines look for large blocks of text that is display:none and can lower your search ranking if you have a lot of text hidden like this

A: The example you provide is simply toggling a class.
The content is actually there all along (look inside .side, you'll find .readmore_con).
.readmore_con is simply set to
display: none;

Upon clicking the "Read More' button, it adds a .readmore_open class to the .readmore_con div. The CSS for .readmore_open? ...You guessed it:
display: block;

If you really want to use accordion for this toggling, you can simply define an initial state of display: none; to your "more" content, and then toggle that during your accordion's .activate event:
http://api.jqueryui.com/accordion/#event-activate