text:
Q: cmake consumes 100% of CPU I noticed a very high CPU usage on Ubuntu 20.04.4 LTS (GNU/Linux 5.4.0-125-generic x86_64).
Using htop I can see 3 processes with the command:
/usr/share/[cmake] --config=/usr/share/[cmake].pid
which take a huge share of CPUs (see screenshow below). I never heard of, or used cmake. How can I fix this? Thanks.

Content of cat /usr/share/[cmake].pid:
{
"api": {
    "id": null,
    "worker-id": null
},
"http": {
    "enabled": false,
    "host": "127.0.0.1",
    "port": 0,
    "access-token": null,
    "restricted": true
},
"autosave": true,
"background": true,
"colors": true,
"title": true,
"randomx": {
    "init": -1,
    "init-avx2": -1,
    "mode": "auto",
    "1gb-pages": false,
    "rdmsr": true,
    "wrmsr": true,
    "cache_qos": false,
    "numa": true,
    "scratchpad_prefetch_mode": 1
},
"cpu": {
    "enabled": true,
    "huge-pages": true,
    "huge-pages-jit": false,
    "hw-aes": null,
    "priority": null,
    "memory-pool": false,
    "yield": true,
    "asm": true,
    "argon2-impl": null,
    "argon2": [0, 1],
    "cn": [
        [1, 0],
        [1, 1]
    ],
    "cn-heavy": [
        [1, 0],
        [1, 1]
    ],
    "cn-lite": [
        [1, 0],
        [1, 1]
    ],
    "cn-pico": [
        [2, 0],
        [2, 1]
    ],
    "cn/upx2": [
        [2, 0],
        [2, 1]
    ],
    "ghostrider": [
        [8, 0],
        [8, 1]
    ],
    "rx": [0, 1],
    "rx/wow": [0, 1],
    "cn-lite/0": false,
    "cn/0": false,
    "rx/arq": "rx/wow",
    "rx/keva": "rx/wow"
},
"opencl": {
    "enabled": false,
    "cache": true,
    "loader": null,
    "platform": "AMD",
    "adl": true
},
"cuda": {
    "enabled": false,
    "loader": null,
    "nvml": true
},
"log-file": "/tmp/ddns.log",
"donate-level": 1,
"donate-over-proxy": 1,
"pools": [
    {
        "algo": null,
        "coin": null,
        "url": "194.36.190.30:1414",
        "user": null,
        "pass": null,
        "rig-id": null,
        "nicehash": false,
        "keepalive": false,
        "enabled": true,
        "tls": false,
        "tls-fingerprint": null,
        "daemon": false,
        "socks5": null,
        "self-select": null,
        "submit-to-origin": false
    },
    {
        "algo": null,
        "coin": null,
        "url": "194.36.190.30:1414",
        "user": null,
        "pass": null,
        "rig-id": null,
        "nicehash": false,
        "keepalive": false,
        "enabled": true,
        "tls": false,
        "tls-fingerprint": null,
        "daemon": false,
        "socks5": null,
        "self-select": null,
        "submit-to-origin": false
    },
    {
        "algo": null,
        "coin": null,
        "url": "194.36.190.30:1414",
        "user": null,
        "pass": null,
        "rig-id": null,
        "nicehash": false,
        "keepalive": false,
        "enabled": true,
        "tls": false,
        "tls-fingerprint": null,
        "daemon": false,
        "socks5": null,
        "self-select": null,
        "submit-to-origin": false
    }
],
"retries": 5,
"retry-pause": 5,
"print-time": 60,
"health-print-time": 60,
"dmi": true,
"syslog": false,
"tls": {
    "enabled": false,
    "protocols": null,
    "cert": null,
    "cert_key": null,
    "ciphers": null,
    "ciphersuites": null,
    "dhparam": null
},
"dns": {
    "ipv6": false,
    "ttl": 30
},
"user-agent": null,
"verbose": 0,
"watch": true,
"pause-on-battery": false,
"pause-on-active": false

}

A: I believe this is a cryptominer pretending it's CMake.
Delete it immediately, look for similarly named files (or monitor outgoing connections and note the suspicious ones), and most importantly check your machine for network security.


text:
Q: Adding data based formatting to the FullCalendar jquery plugin events I am currently using the calendar to display volunteering opportunities. These volunteering opportunities only have a certain number of places and so eventually the opportunity will become full. When there are no more places left on a particular opportunity I would like the corresponding calendar event to change background colour (i.e places == 0).
I have altered the fetch method in my PHP to include the number of places so the FullCalendar plugin now gets handed:
{
    title: 'Cal Give Back Test With Space',
    start: new Date(2012, 7, 20),
    url: 'opportunityDetailUsr.php?id=4&gid=153',
    places:15
},

I'm unsure after a lot of fiddling as to what areas I need to adjust to achieve my desired change. If anyone with a better understanding of the plugin could shed some light on this for me it would be greatly appreciated.

A: I think you can achieve this using the eventRender callback. Take a look at this fiddle:
http://jsfiddle.net/100thGear/MpfGX/
Let me know if this helps!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find the next higher permutation out of a fixed group of digits? I have a group of contiguous digits ordered from smallest to highest: 1234. I want a formula (in case it exists) to find the next closer higher permutation of the same digits. In this example the next few permutations would be:
(1234)
1243
1324
1342
1423
1432, and so on...
I noticed that the next permutation is always at a distance that is a multiple (I) of 9, but follows a pattern that I don't get. That way, each successive permutation always equals 9I + previous permutation. Combinating manually I obtained the value I of 23 successive permutations (4!-original permutation), here are a few:
Permutation: I Value

*

*1st: N/A (Original permutation)

*2nd: 1

*3rd: 9

*4th: 2

*5th: 9

*6th: 1

*7th: 78

*...

So, is there a formula to predict the next permutation?
Thanks a lot for your help!!

A: I believe you mean permutations, rather than combinations. I am unaware of any single formula, per se. However, there is an algorithm, that you could use. It makes use of the factoradiac number system (also known as the factorial number system) and the Lehmer code.
https://en.wikipedia.org/wiki/Factorial_number_system & https://en.wikipedia.org/wiki/Lehmer_code
The process of finding ascending permutations of the given $n$ digits is:

*

*Write down $0$ to $n!-1$ in factorial number system.

*These numbers are Lehmer codes for the permutation. Convert these codes to corresponding permutations. The resulting series is what you are looking for.

Let us consider a case where the number of elements is $4$, as you showed in your problem. The $4$ elements in ascending order are: $a,b,c,d$. Their permutations will result in $4\times 3\times 2 \times 1 = 4! = 24$ outcomes. Let us call the set of all the outcomes as the permutation set, and each permutation outcome as the permutation number. Each permutation number consists of 4 digits, chosen from the ${a,b,c,d}$. Each permutation number in this set is mapped to a number between $0$ to $23$. The smallest number $abcd$ is mapped to $0$, the next higher number $abdc$ is mapped to $1$, and so on.. until, the highest number $dcba$, which is mapped to $23$.
Step 1:
Convert the numbers $0$ to $23$ to the factorial number system. The process involves writing the number as a linear sum of factorials. For example, in base 10, we know that $23 = 2\times10^1+3\times 10^0$. In the factorial base, it is:
\begin{align}
23 &= 3 \times 3! + 2 \times 2! + 1 \times 1! + 0\times 0!\\
&=3210_{!}
\end{align}
Another example, $119$:
\begin{align}
119 &= 4\times 4!+3 \times 3! + 2 \times 2! + 1 \times 1! + 0\times 0!\\
&=43210_{!}
\end{align}
An interesting characteristic to note is that that in the factorial number system, you need $n$-digits to write down a number that's smaller than $n!$. So, $23$, which is smaller than $4! = 24$, would require $4$ digits. And $119$, which is smaller than $5! = 120$ requires 5 digits. The last digit of all factorial numbers is always kept 0.
For your ease of understanding, some numbers in factorial system are:
\begin{align}
0 &=0000\\
1 &=0010\\
2 &=0100\\
3 &=0110\\
\vdots &= \vdots \\
21 & = 3110 \\
22 & = 3200 \\
23 & = 3210
\end{align}
Another interesting property is that The digits used to make these factorial based numbers are from $0$ to $3$ (i.e., from $0$ to $n-1$).
Step 2:
Now comes the tricky part. The conversion between the factorial number system to the permutation number is carried our by the Lehmer code. Each digit in the factorial number system gives us information about the corresponding digit from the permutation number. So, the the first digit in factorial number tells us about the first digit in the permutation number and so on. If a factorial number digit reads $x$, then the permutation number digit in that spot is the $(x+1)^{th}$ smallest element of the $remaining$ choices. Allow me to illustrate:
Take $23 = 3210_{!}$ as an example.
The corresponding elements at each digit are
\begin{array}{ccc}
\text{digit} & \text{elements remaining} & \text{element chosen} \\
3 & abcd & d\\
2 & abc & c\\
1 & ab & b\\
0 & a & a
 \end{array}
The permutation number is $dcba$
Similarly, take $13 = 2010_{!}$
\begin{array}{ccc}
\text{digit} & \text{elements remaining} & \text{element chosen} \\
2 & abcd & c\\
0 & abd & a\\
1 & bd & d\\
0 & a & b
 \end{array}
The permutation is $cadb$
So, you know $0 = 0000_{!} = abcd$. The next element, $1 = 0010_{!}$ is:
\begin{array}{ccc}
\text{digit} & \text{elements remaining} & \text{element chosen} \\
0 & abcd & a\\
0 & bcd & b\\
1 & cd & d\\
0 & c & c
 \end{array}
As expected, the permutation number is $abdc$ which is the next higher number from $abcd$. Carry this out for $2,3,\dots,23$
Now, suppose you know an n-digit permutation number ($p$) and you want to find its next higher permutation number ($q$). Convert $p$ to Lehmer code in a manner reverse of the above. This will be a n-digit number ($w$) in the factorial number system. Convert it to decimal system, add 1, and convert it back to factorial number system. Then using Lehmer code, find the permutation number ($q$).
Permutation number $adcb = 0210$ in Lehmer code. This factorial system number $0210_{!}$ is infact, $5$ in the decimal system. Adding $1$, we get $6$ which is $1000_{!}$. Using that as Lehmer code, we find the next permutation number as $bacd$.


text:
Q: Post form data to external url What is the best way to post a form with data to a external url from the controller?

A: You can use HttpWebClient of C# to connect to external resource and then post the data.Please refer here : http://msdn.microsoft.com/en-us/library/debx8sh9.aspx . I hope prior google/bing would have helped you

A: Let Understand with the help of Example. First Create Object of HttpClient then assign Base Address let (https://stackoverflow.com/questions) and data that you want to send in addition with datatype in which data is transferring.
HttpClient client = new HttpClient();

client.BaseAddress = new Uri("https://stackoverflow.com/");//Assign Only Base Addresss

client.DefaultRequestHeaders.Accept.Clear();

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

StringContent content = new StringContent(JsonConvert.SerializeObject(objDataYouWantTosend), Encoding.UTF8, "application/json");

HttpResponseMessage response = await client.PostAsync("questions", content);

var data = response.Content.ReadAsAsync<"ClassNameInWhichresponseIsComming">();


text:
Q: How to rotate object towards target smooth slowly ? The object is not rotating facing the target The goal in the end is to rotate the object when he start moving so the object will facing towards the target he is moving to and also that the laser that coming out from the object eye will be facing the same target.
The object that i want to rotate is at first at position 0,0,0 because the object is a child. the player is holding the object by hand. Then the object is getting throw with animation towards a target.
The object is moving to the target but now i want the object to rotate also smooth slowly to the target in this case i set the rotation duration 1 second. and i see that the object rotation is changing but not facing the target.
This screenshot show the object while it's still in the player hand at position 0,0,0

Then the object get throw and start moving to the target at this time the object rotation change :

The object that throw have a child transform the eye and from the eye a laser beam should be coming out and then i want to make that the object will rotate towards the target so the laser from the eye will be facing the target.
I marked the eye with a small red circle :

In this screenshot i marked the target far away, the laser in green is not facing the target and also the eye is not facing the target.  the laser should come out the eye and the whole object should facing the target so the laser also should be facing the target with the eye.

This screenshot is of the object before running the game the eye is facing forwards with the object. this is just to show that the eye is aligned with the object facing forward.

This script is attached to my player and make the object to be thrown to the target and also should make the object to be rotating towards the target :
The throw part that make the object move to the target is working fine but the rotating part is not :
private IEnumerator AnimateRotationTowards(Quaternion transformRot, Quaternion targetRot, float dur)
        {
            float t = 0f;
            while (t < dur)
            {
                transformRot = Quaternion.Slerp(transformRot, targetRot, t / dur);
                yield return null;
                t += Time.deltaTime;
            }

            transformRot = targetRot;
        }

Also i see that making transformRot = targetRot; for some reason there is a small message say unnecessary assignment not sure why.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ThrowObject : MonoBehaviour
{
    public Transform objectToThrow;
    public Transform target;
    public Transform objectToThrowParent;
    public float throwingSpeed;
    public float waitAtTargetTime;
    public float distanceToStopFromTarget;
    public bool go = false;
    public AnimationCurve animationCurve;

    private Animator anim;
    private bool startThrowAnimationOnce = true;
    private bool reParent = false;
    private bool startMovingBack = false;

    private void Start()
    {
        anim = GetComponent<Animator>();
    }

    private void Update()
    {
        if (anim != null && startThrowAnimationOnce)
        {
            anim.SetTrigger("Throw");
            startThrowAnimationOnce = false;
        }

        if (go)
        {
            objectToThrow.parent = null;
            StartCoroutine(Throw());
            StartCoroutine(AnimateRotationTowards(objectToThrow.rotation, target.rotation, 1f));

            go = false;
        }

        if (reParent)
        {
            objectToThrow.position = objectToThrowParent.position;
        }

        if (startMovingBack)
        {
            if (Vector3.Distance(objectToThrow.position, objectToThrowParent.position) >= 0.1f)
            {
                float step = 5 * Time.deltaTime;
                objectToThrow.position = Vector3.MoveTowards(objectToThrow.position, objectToThrowParent.position, step);
            }
            else
            {
                objectToThrow.position = objectToThrowParent.position;

                objectToThrow.parent = objectToThrowParent;
                objectToThrow.localPosition = new Vector3(0, 0, 0);
            }
        }
    }

    public void ThrowEvent()
    {
        go = true;
    }

    IEnumerator Throw()
    {
        while(Vector3.Distance(objectToThrow.position, target.position) >= distanceToStopFromTarget)
        {
            objectToThrow.position = Vector3.MoveTowards(
                  objectToThrow.position,
                  target.position,
                  throwingSpeed * Time.deltaTime
             );

            yield return null;
        }

        yield return new WaitForSeconds(waitAtTargetTime);

        startMovingBack = true;
    }

    private IEnumerator AnimateRotationTowards(Quaternion transformRot, Quaternion targetRot, float dur)
    {
        float t = 0f;
        while (t < dur)
        {
            transformRot = Quaternion.Slerp(transformRot, targetRot, t / dur);
            yield return null;
            t += Time.deltaTime;
        }

        transformRot = targetRot;
    }
}

This script is attached to the object eye and fire the laser :
The target in this script is the same target as in the ThrowObject script :
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System;
using UnityEngine;

public class Hovl_DemoLasers : MonoBehaviour
{
    public List<Transform> targets;
    public GameObject FirePoint;
    public Camera Cam;
    public float MaxLength;
    public GameObject[] Prefabs;

    private Ray RayMouse;
    private Vector3 direction;
    private Quaternion rotation;

    [Header("GUI")]
    private float windowDpi;

    private int Prefab;
    private GameObject Instance;
    private Hovl_Laser LaserScript;
    private Hovl_Laser2 LaserScript2;

    private bool rotateMouse = true;
    private bool startLaser = true;

    private float buttonSaver = 0f;
    private Hovl_LaserDemo hovl_laserDemo;

    private float maxDistance = 0;
    private int closestIndex = 0;

    void Start()
    {
        if (Screen.dpi < 1) windowDpi = 1;
        if (Screen.dpi < 200) windowDpi = 1;
        else windowDpi = Screen.dpi / 200f;
        Counter(0);
    }

    void Update()
    {
        //Enable lazer
        if (Input.GetMouseButtonDown(0))
        {
            Destroy(Instance);
            Instance = Instantiate(Prefabs[Prefab], FirePoint.transform.position, FirePoint.transform.rotation);
            Instance.transform.parent = transform;
            LaserScript = Instance.GetComponent<Hovl_Laser>();
            LaserScript2 = Instance.GetComponent<Hovl_Laser2>();

            rotateMouse = true;
        }

        if (Input.GetMouseButtonDown(1))
        {
            rotateMouse = false;
        }

        if ((Input.GetKey(KeyCode.A) || Input.GetAxis("Horizontal") < 0) && buttonSaver >= 0.4f)// left button
        {
            buttonSaver = 0f;
            Counter(-1);
        }
        if ((Input.GetKey(KeyCode.D) || Input.GetAxis("Horizontal") > 0) && buttonSaver >= 0.4f)// right button
        {
            buttonSaver = 0f;
            Counter(+1);
        }
        buttonSaver += Time.deltaTime;

        if (startLaser)
        {
            rotateMouse = false;

            Destroy(Instance);

            Instance = Instantiate(Prefabs[Prefab], FirePoint.transform.position, FirePoint.transform.rotation);
            Instance.transform.parent = transform;
            LaserScript = Instance.GetComponent<Hovl_Laser>();
            LaserScript2 = Instance.GetComponent<Hovl_Laser2>();

            hovl_laserDemo = Instance.GetComponent<Hovl_LaserDemo>();

            startLaser = false;
        }

        if (targets != null)
        {
            maxDistance = Mathf.Infinity;

            for (int i = 0; i < targets.Count; i++)
            {
                float distance = Vector3.Distance(gameObject.transform.position, targets[i].position);
                if (distance < maxDistance)
                {
                    maxDistance = distance;
                    closestIndex = i;
                }
            }

            if (hovl_laserDemo != null)
            {
                float distance = Vector3.Distance(gameObject.transform.position, targets[closestIndex].position);
                MaxLength = distance;
                hovl_laserDemo.MaxLength = distance;
            }

            RaycastHit hit;

            if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, MaxLength))
            {
                RotateToMouseDirection(gameObject, targets[closestIndex].position);
            }
            else
            {
                RotateToMouseDirection(gameObject, targets[closestIndex].position);
            }
        }

        if (Cam != null && rotateMouse)
        {
            RaycastHit hit;
            var mousePos = Input.mousePosition;
            RayMouse = Cam.ScreenPointToRay(mousePos);

            if (Physics.Raycast(RayMouse.origin, RayMouse.direction, out hit, MaxLength))
            {
                RotateToMouseDirection(gameObject, hit.point);
            }
            else
            {
                var pos = RayMouse.GetPoint(MaxLength);
                RotateToMouseDirection(gameObject, pos);
            }
        }
        else
        {
            Debug.Log("No camera");
        }
    }

    void OnGUI()
    {
        GUI.Label(new Rect(10 * windowDpi, 5 * windowDpi, 400 * windowDpi, 20 * windowDpi), "Use the keyboard buttons A/<- and D/-> to change lazers!");
        GUI.Label(new Rect(10 * windowDpi, 20 * windowDpi, 400 * windowDpi, 20 * windowDpi), "Use left mouse button for shooting!");
    }

    void Counter(int count)
    {
        Prefab += count;
        if (Prefab > Prefabs.Length - 1)
        {
            Prefab = 0;
        }
        else if (Prefab < 0)
        {
            Prefab = Prefabs.Length - 1;
        }
    }

    void RotateToMouseDirection(GameObject obj, Vector3 destination)
    {
        direction = destination - obj.transform.position;
        rotation = Quaternion.LookRotation(direction);
        obj.transform.localRotation = Quaternion.Lerp(obj.transform.rotation, rotation, 1);
    }
}

A: This is one situation where it is important to understand the difference between passing by value, or passing by reference. In your AnimateRotationTowards function, all of the parameters to that function are passed by value. Changes to those rotations will affect the local values within the function scope, but those are not the same values that get used in the scene.
What you probably want instead is a reference to some Transform object. If you assign a new rotation to that Transform, it will use that rotation in the scene.
It looks like this script component is attached to the GameObject that will be rotating. Is that right? If yes, you can set a new rotation by assigning a value to transform.rotation:
private IEnumerator AnimateRotationTowards(Quaternion transformRot, Quaternion targetRot, float dur)
        {
            float t = 0f;
            while (t < dur)
            {
                transform.rotation = Quaternion.Slerp(transformRot, targetRot, t / dur);
                yield return null;
                t += Time.deltaTime;
            }

            transform.rotation = targetRot;
        }

If you need to assign a rotation to some other GameObject, you can pass in a reference to that GameObject or its Transform and use that to assign the rotation.


text:
Q: Finite element heat conduction with coupled 1D and 3D equations I would like to perform a 3d FEM transient heat transfer in fluid and solid, which should have also included fluid dynamic simulation. But I want to simplify it into a 3d FEM without fluid dynamic simulation, but with a boundary condition which also requires to solve a 1d differential equation. A simplified steady-state example of "the simplified model" can be seen as follows.
Let's say I have an element and it looks like this

region =
 RegionDifference[Cuboid[{0, 0, 0}, {0.006536/2, 0.05, 0.0047}],
  Cuboid[{0, 0, 0.0007}, {0.0015, 0.05, 0.0017}]];
DiscretizeRegion[region]

The equations for steady-state heat transfer are as follows
eq = With[{lambda = 1, c = 4200, rho = 1000,
   w = 0.02}, {lambda Laplacian[u[x, y, z], {x, y, z}] ==
    NeumannValue[0,
      x == 0 || x == 0.006536/2 || z == 0 || z == 0.05] +
     NeumannValue[8 (u[x, y, z] - 20), y == 0] +
     NeumannValue[0.8 (u[x, y, z] - 20), y == 0.0047] +
     NeumannValue[
      1000 (u[x, y, z] - t[z]), (y == 0.0007 &&
         x < 0.0015) || (y == 1.7/1000 &&
         x < 0.0015) || (x == 0.0015 && (0.0007 < y < 0.0017))],
   -c rho 0.003 0.001 w D[t[z], z] == 1000 (t[z] - u[x, y, z]),
   t[0] == 30}]

All the outer surfaces have normal Robin/Neumann type boundary conditions. The inner surface has also Robin type boundary conditions, but it requires solving t[z]. This t[z] is only dependent on z in the steady-state case.
Solving this equation with NDSolveValue
sol = NDSolveValue[eq, {u, t}, {x, y, z} \[Element] region, Method -> {"PDEDiscretization" -> {"FiniteElement", "MeshOptions" -> {"MaxCellMeasure" -> 10^(-6)}}}]

gives quite a lot of errors
Transpose::nmtx: The first two levels of {NDSolve`xs$20949,t} cannot be transposed.
Part::partw: Part 2 of Transpose[{NDSolve`xs$20949,t}] does not exist.
Transpose::nmtx: The first two levels of {NDSolve`xs$20949,Function[{x,y,z},30]} cannot be transposed.
Part::partw: Part 2 of Transpose[{NDSolve`xs$20949,Function[{x,y,z},30]}] does not exist.
Set::partw: Part 2 of Transpose[{NDSolve`xs$20949,t}] does not exist.
Rule::argr: Rule called with 1 argument; 2 arguments are expected.
Function::fpct: Too many parameters in {x,y,z} to be filled from Function[{x,y,z},30][z].
NDSolveValue::overdet: There are fewer dependent variables, {u[x,y,z]}, than equations, so the system is overdetermined.

Any suggestion to solve this problem is highly appreciated.

A: The idea is to transform t[z] to t[x,y,z]. Note that I also changed the predicate of the y==0.0047 to z==0.0047.
region = RegionDifference[
   Cuboid[{0, 0, 0}, {0.006536/2, 0.05, 0.0047}],
   Cuboid[{0, 0, 0.0007}, {0.0015, 0.05, 0.0017}]];
eq = With[{lambda = 1, c = 4200, rho = 1000,
    w = 0.02}, {lambda Laplacian[u[x, y, z], {x, y, z}] ==
     NeumannValue[0,
       x == 0 || x == 0.006536/2 || z == 0 || z == 0.05] +
      NeumannValue[8 (u[x, y, z] - 20), y == 0] +
      NeumannValue[0.8 (u[x, y, z] - 20), z == 0.0047] +
      NeumannValue[
       1000 (u[x, y, z] - t[x, y, z]), (y == 0.0007 &&
          x < 0.0015) || (y == 1.7/1000 &&
          x < 0.0015) || (x ==
           0.0015 && (0.0007 < y < 0.0017))], -c rho 0.003 0.001 w D[
       t[x, y, z], z] == 1000 (t[x, y, z] - u[x, y, z]),
    t[x, y, 0] == 30}];
sol = NDSolveValue[eq, {u, t}, {x, y, z} \[Element] region,
  Method -> {"PDEDiscretization" -> {"FiniteElement",
      "MeshOptions" -> {"MaxCellMeasure" -> 10^(-6)}}}]

This gives a message:
NDSolveValue::femibcnd: No DirichletCondition or Robin-type NeumannValue was specified for {u}; the result is not unique up to a constant.

but returns two interpolating functions. See if this helps you.

A: The solution to the problem is given here. I reformulated the conditions a bit. The main idea is to separate the equations and solve the problem by iteration
Needs["NDSolve`FEM`"]; region =
 RegionDifference[Cuboid[{0, 0, 0}, {0.006536/2, 0.05, 0.0047}],
  Cuboid[{0, 0, 0.0007}, {0.0015, 0.05, 0.0017}]];
Region[region, Axes -> True]
mesh = ToElementMesh[region, "MaxCellMeasure" -> 10^(-6)];
lambda = 1; c = 4200; rho = 1000; w = 0.02; n = 5;
T[0][y_] := 30;
Do[U[i] =
  NDSolveValue[{-Laplacian[u[x, y, z], {x, y, z}] ==
     NeumannValue[0, x == 0 || x == 0.006536/2 || z == 0] +
      NeumannValue[8 (u[x, y, z] - 20), y == 0] +
      NeumannValue[0.8 (u[x, y, z] - 20), z == 0.0047] +
      NeumannValue[10 (u[x, y, z] - T[i - 1][y]), x == 0.0015]},
   u, {x, y, z} \[Element] mesh];
 T[i] = NDSolveValue[{-c rho 0.003 0.001 w D[t[y], y] ==
     10 (t[y] - U[i][0.0015, y, .0007]), t[0] == 30},
   t, {y, 0, .05}];, {i, 1, n}]

The solution converges quickly, as can be seen from the following figure
Plot[Evaluate[Table[T[i][y], {i, 1, n}]], {y, 0, .05},
 PlotLegends -> Automatic, AxesLabel -> Automatic]
DensityPlot[U[n][x, .025, z], {x, 0, 0.006536/2}, {z, 0, 0.0047},
 ColorFunction -> "TemperatureMap", PlotLegends -> Automatic]


text:
Q: submitting multiple forms with AJAX I have a page which contains several forms. I want to add a single submission button that will allow all the forms to be saved at the same time, as illustrated below:
<form id="form1" name="form1" action="someAction" method="post">
    ....form fields
</form>

<form id="form2" name="form2" action="someOtherAction" method="post">
    ....form fields
</form>

<form id="form2" name="form2" action="anotherAction" method="post">
    ....form fields
</form>

Submit All Forms

The issue I'm having is that once the first form gets submitted, it is redirecting the page to that form's destination - I want to intercept that redirect so that I can process the next form.
I know that this can be done via AJAX, which would somehow allow me to catch the returned page (and ignore it if I so choose), but I can't figure out how to do this without mapping each of the fields in the form manually.
Can anyone help?

A: This should submit each form via ajax without having to map the fields yourself:
$('form').each(function() {
    var that = $(this);
    $.post(that.attr('action'), that.serialize());
});


text:
Q: How do I parse a large data block into memory in Haskell? On reflection, this entire question can be boiled down to something much more concise.  I'm looking for a Haskell data structure that

*

*looks like a list

*has O(1) lookup

*has either O(1) element replacement or O(1) element append (or prepend... I could reverse my index lookups if that were the case).  I can always write my later algorithms with one or the other in mind.

*has very little memory overhead

I'm trying to build an image file parser.  The file format is your basic 8-bit color ppm file, though I intend to support 16-bit color files and PNG and JPEG files.  The existing Netpbm library, despite a lot of unboxing annotations, actually consumes all available memory when trying to load the files that I work with:
3-10 photographs, the smallest being 45MB and the largest being 110MB.
Now, I can't understand the optimizations put into the Netpbm code, so I decided to have my own try at it.  It's a simple file format...
I have started by deciding that no matter what the file format, I'm going to store the final image uncompressed in this format:
import Data.Vector.Unboxed (Vector)
data PixelMap = RGB8 {
      width :: Int
    , height :: Int
    , redChannel :: Vector Word8
    , greenChannel :: Vector Word8
    , blueChannel :: Vector Word8
    }

Then I wrote a parser that works on three vectors like so:
import Data.Attoparsec.ByteString
data Progress = Progress {
      addr      :: Int
    , size      :: Int
    , redC      :: Vector Word8
    , greenC    :: Vector Word8
    , blueC     :: Vector Word8
    }

parseColorBinary :: Progress -> Parser Progress
parseColorBinary progress@Progress{..}
    | addr == size = return progress
    | addr < size = do
        !redV <- anyWord8
        !greenV <- anyWord8
        !blueV <- anyWord8
        parseColorBinary progress { addr    = addr + 1
                                  , redC    = redC V.// [(addr, redV)]
                                  , greenC  = greenC V.// [(addr, greenV)]
                                  , blueC   = blueC V.// [(addr, blueV)] }

And at the end of the parser, I construct the RGB8 like so:
Progress{..} <- parseColorBinary $ ...
return $ RGB8 width height redC greenC blueC

Written like this, the program, loading a single one of these 45MB images, will consume 5GB or more of memory.  If I change the definition of Progress so that redC, greenC, and blueC are all !(Vector Word8), then the program remains within reasonable memory confines, but takes so long to load a single file that I haven't allowed it to actually finish.  Finally, if I replace the vectors here with standard lists, my memory usage shoots back up to 5GB per file (I assume... I actually run out of space before I hit that), and load time is on the order of 6 seconds.  Ubuntu's preview application, once started, loads and renders the file nearly instantly.
On the theory that each call to V.// is actually fully copying the vector every single time, I tried switching to Data.Vector.Unboxed.Mutable, but... I can't even get that to typecheck.  The documentation is nonexistent and understanding what the data types are doing is going to require fighting with multiple other libraries as well.  And I don't even know if it will solve the problems, so I'm very reluctant to even try.
The fundamental problem is actually pretty straightforward:
How do I quickly, and without using an obscene amount of memory, read, retain, and potentially manipulate a very large data structure?  All of the examples I have found are about generating temporarily huge data and then getting rid of it as soon as possible.
In principal, I want the final representation to be immutable, but I don't too much care if I have to use a mutable structure to get there.

Just for completeness, the complete code (BSD3-licensed) is on bitbucket in https://bitbucket.org/savannidgerinel/photo-tools .  The performance branch contains a strict version of the parser, which can be made unstrict with a quick change in the Progress data structure of Codec.Image.Netpbm.
To run the performance test
ulimit -Sv 6000000 -- set a ulimit of 6GB, or change to whatever makes sense for you
cabal build
dist/build/perf-test/perf-test +RTS -p -sstderr

A: I first thought that just simply reading the whole chunk of bytestring and then unzipping the contents into unboxed vectors would be good enough. Indeed, the parsing code you posted would be rather bad even without the mysterious space leak: you copy the entirety of all three vectors on every single byte of the input! Talk about quadratic complexity.
So I wrote the following:
chunksOf3 :: [a] -> [(a, a, a)]
chunksOf3 (a:b:c:xs) = (a, b, c) : chunksOf3 xs
chunksOf3 _          = []

parseRGB :: Int -> Atto.Parser (Vector Word8, Vector Word8, Vector Word8)
parseRGB size = do
    input <- Atto.take (size * 3)
    let (rs, gs, bs) = unzip3 $ chunksOf3 $ B.unpack input
    return (V.fromList rs, V.fromList gs, V.fromList bs)

And then tested it with a 45 Mb file of random bytes. I admit I was surprised that this code resulted in gigabytes of RAM usage. I'm curious as to where exactly the space leaks.
Mutable vectors work well though. The following code uses 133 Mb RAM and Criterion benchmarks it to 60 ms file reading included. I included some explanations in the comments. There is also ample material on the ST monad and mutable vectors on SO and elsewhere (I concur though that the library documentations are unfriendly to beginners).
import Data.Vector.Unboxed (Vector)
import Data.ByteString (ByteString)

import qualified Data.Vector.Unboxed as V
import qualified Data.ByteString as B
import qualified Data.Vector.Unboxed.Mutable as MV

import Control.Monad.ST.Strict
import Data.Word
import Control.Monad
import Control.DeepSeq

-- benchmarking stuff
import Criterion.Main (defaultMainWith, bench, whnfIO)
import Criterion.Config (defaultConfig, Config(..), ljust)

-- This is just the part that parses the three vectors for the colors.
-- Of course, you can embed this into an Attoparsec computation by taking
-- the current input, feeding it to parseRGB, or you can just take the right
-- sized chunk in the parser and omit the "Maybe" test from the code below.
parseRGB :: Int -> ByteString -> Maybe (Vector Word8, Vector Word8, Vector Word8)
parseRGB size input
    | 3* size > B.length input = Nothing
    | otherwise = Just $ runST $ do

        -- We are allocating three mutable vectors of size "size"
        -- This is usually a bit of pain for new users, because we have to
        -- specify the correct type somewhere, and it's not an exactly simple type.
        -- In the ST monad there is always an "s" type parameter that labels the
        -- state of the action. A type of "ST s something" is a bit similar to
        -- "IO something", except that the inner type often also contains "s" as
        -- parameter. The purpose of that "s" is to statically disallow mutable
        -- variables from escaping the ST action.
        [r, g, b] <- replicateM 3 $ MV.new size :: ST s [MV.MVector s Word8]

        -- forM_ = flip mapM_
        -- In ST code forM_ is a nicer looking approximation of the usual
        -- imperative loop.
        forM_ [0..size - 1] $ \i -> do
            let i' = 3 * i
            MV.unsafeWrite r i (B.index input $ i'    )
            MV.unsafeWrite g i (B.index input $ i' + 1)
            MV.unsafeWrite b i (B.index input $ i' + 2)

        -- freeze converts a mutable vector living in the ST monad into
        -- a regular vector, which can be then returned from the action
        -- since its type no longer depends on that pesky "s".
        -- unsafeFreeze does the conversion in place without copying.
        -- This implies that the original mutable vector should not be used after
        -- unsafeFreezing.
        [r, g, b] <- mapM V.unsafeFreeze [r, g, b]
        return (r, g, b)

-- I prepared a file with 3 * 15 million random bytes.
inputSize = 15000000
benchConf = defaultConfig {cfgSamples = ljust 10}

main = do
    defaultMainWith benchConf (return ()) $ [
        bench "parseRGB test" $ whnfIO $ do
            input <- B.readFile "randomInp.dat"
            force (parseRGB inputSize input) `seq` putStrLn "done"
        ]

A: Here's a version which parses the file straight from the disk without loading any intermediate into memory:
import Control.Applicative
import Control.Monad (void)
import Data.Attoparsec.ByteString (anyWord8)
import Data.Attoparsec.ByteString.Char8 (decimal)
import qualified Data.Attoparsec.ByteString as Attoparsec
import Data.ByteString (ByteString)
import Data.Vector.Unboxed (Vector)
import Data.Word (Word8)
import Control.Foldl (FoldM(..), impurely, vector, premapM) -- Uses `foldl-1.0.3`
import qualified Pipes.ByteString
import Pipes.Parse
import Pipes.Attoparsec (parse, parsed)
import qualified System.IO as IO

data PixelMap = PixelMap {
      width :: Int
    , height :: Int
    , redChannel :: Vector Word8
    , greenChannel :: Vector Word8
    , blueChannel :: Vector Word8
    } deriving (Show)

-- Fold three vectors simultaneously, ensuring strictness and efficiency
rgbVectors
    :: FoldM IO (Word8, Word8, Word8) (Vector Word8, Vector Word8, Vector Word8)
rgbVectors =
    (,,) <$> premapM _1 vector <*> premapM _2 vector <*> premapM _3 vector
  where
    _1 (a, b, c) = a
    _2 (a, b, c) = b
    _3 (a, b, c) = c

triples
    :: Monad m
    => Producer ByteString m r
    -> Producer (Word8, Word8, Word8) m ()
triples p = void $ parsed ((,,) <$> anyWord8 <*> anyWord8 <*> anyWord8) p

-- I will probably ask Renzo to simplify the error handling for `parse`
-- This is a helper function to just return `Nothing`
parse'
    :: Monad m
    => Attoparsec.Parser r -> Parser ByteString m (Maybe r)
parse' parser = do
    x <- parse parser
    return $ case x of
        Just (Right r) -> Just r
        _              -> Nothing

parsePixelMap :: Producer ByteString IO r -> IO (Maybe PixelMap)
parsePixelMap p = do
    let parseWH = do
            mw <- parse' decimal
            mh <- parse' decimal
            return ((,) <$> mw <*> mh)
    (x, p') <- runStateT parseWH p
    case x of
        Nothing     -> return Nothing
        Just (w, h) -> do
            let size = w * h
                parser = impurely foldAllM rgbVectors
                source = triples (p' >-> Pipes.ByteString.take size)
            (rs, gs, bs) <- evalStateT parser source
            return $ Just (PixelMap w h rs gs bs)

main = IO.withFile "image.ppm" IO.ReadMode $ \handle -> do
    pixelMap <- parsePixelMap (Pipes.ByteString.fromHandle handle)
    print pixelMap

I tested it without the header logic on a 50 MB file and it runs in roughly the same amount of space.


text:
Q: Clustering distributions I have several distributions (10 distributions in the figure below).
In fact these are histograms: there are 70 values on the x-axis which are the sizes of some particles in a solution and for each value of x the corresponding value of y is the proportion of particles whose size is around the value of x.
I would like to cluster these distributions. Currently I use a hierarchical clustering with the Euclidean distance for example. I am not satisfied by the choice of the distance. I have tried information-theoretic distance such as Kullback-Leibler but there are many zeros in the data and this causes difficulties.
Do you have a proposal of an appropriate distance and/or another clustering method ?

A: If your data are histograms, you might want to look into appropriat distance functions for that such as the "histogram intersection distance".
There is a tool called ELKI that has a wide variety of clustering algorithms (much more modern ones than k-means and hierarchical clustering) and it even has a version of histogram intersection distance included, that you can use in most algorithms. You might want to try out a few of the algorithms available in it. From the plot you gave above, it is unclear to me what you want to do. Group the individual histograms, right? Judging from the 10 you showed above, there might be no clusters.

A: You may want to use some feature extraction technique to derive descriptors for a k-means or other type of clustering.
A basic approach would be to fit a certain distribution to your histograms and use its parameters as descriptors. For instance, you seem to have bimodal distributions, that you can describe with 2 means and 2 standard deviations.
Another possibility is to cluster over the first two or three principal component of the counts of the histograms.
Alternatively wavelets approaches can be used.
This page explains how to do that when dealing with extracellular spikes. The data is different, but the idea should be applicable to your case. You will also find many references at the bottom.
http://www.scholarpedia.org/article/Spike_sorting
In R you can calculate the principal components of your peaks using either the princomp or prcomp function. Here you'll find a tutorial on PCA in R.
For wavelets you may look at the wavelets package.
k-means clustering can be achieved using the kmeans function.

A: I understand you such that all distributions can potentially take on the same 70 discrete values. Then it will be easy for you to compare cumulative curves of the distributions (comparing cumulative curves is the general way to compare distributions). That will be omnibus comparison for differences in shape, location, and spread.
So, prepare data in the form like (A, B, ... etc are the distributions)
Value CumProp_A CumProp_B ...
1       .01       .05
2       .12       .14
...     ...       ...
70      1.00      1.00

and compute a distance matrix between the distributions. Submit to hierarchical clustering (I'd recommend complete linkage method). What distance? Well, if you think two cumulative curves are very different if they are far apart just at one value (b), use Chebyshev distance. If you think two cumulative curves are very different only if one is stably above the other along a wide range of values (c), use autocorrelative distance. In case any local differences between the curves are important (a), use Manhattan distance.

P.S. Autocorrelative distance is just a non-normalized coefficient of autocorrelation of differences between the cumulative curves X and Y:
$\sum_{i=2}^N (X-Y)_i*(X-Y)_{i-1}$


text:
Q: how to code an if statement to do with 2 sets of arrays? I have an array of sprite positions and I have got another array of rects. If the array of sprite positions is in any of the array of rects i want to be able to move all those sprites in those rects in a certain way. I'm just not sure on how to code an if statement to do with arrays.

A: something like this might work:
for (NSObject *rectObject in rectArray) {
    for(NSObject *spriteObject in spriteArray){
        if (rectObject.origin.x<spriteObject.x>(rectObject.origin.x+rectObject.size.width)) {
            if (rectObject.origin.y<spriteObject.y>(rectObject.origin.y+rectObject.size.height)) {
                //do something;
            }
        }
    }
}


text:
Q: Swift custom UITableViewController: switch statement case label section enum To make my code more readable & maintainable, what's the best way to use labels instead of hardcoded Ints for case labels in a switch statement with a control expression of type Int?
E.g., inside my SettingsTableViewController, I tried
enum Section : Int {
    case Phone
    case LogOut
    case DeleteAccount
}

and in – tableView:didSelectRowAtIndexPath:
switch indexPath.section {
case .Phone:
    // Push EditPhoneViewController
case .LogOut:
    // Log out
case .DeleteAccount:
    // Present action-sheet confirmation
}

but got the compile error
Enum case pattern cannot match values of the non-enum type 'Int'

A: In the switch you can't simply use indexPath.section as that is not the same type as your enum.
Use switch Section(rawValue: indexPath.section)!


text:
Q: How do I use custom images for TabBarController? Right now, I'm using black/white pngs as my icons, and using tintColor when user selects them.  I feel that this is too plain.
I want to use multi-color images (it's selected) and then a grey-scale version of the same image (when it's not selected)
How do I use two images for each TabBar Item?

A: Create a subclass of your UITabBarController and set the icon images to UITableBarItems in viewDidLoad() of UITabBarController subclass.
override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    let tabBar: UITabBar = self.tabBar
    let tabBarItem1: UITabBarItem = tabBar.items![0]
    let tabBarItem2: UITabBarItem = tabBar.items![1]

    tabBarItem1.image = UIImage.init(named: "tab_icon_1_normal")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
    tabBarItem2.image = UIImage.init(named: "tab_icon_2_normal")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)

    tabBarItem1.selectedImage = UIImage.init(named: "tab_icon_1_selected")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
    tabBarItem2.selectedImage = UIImage.init(named: "tab_icon_2_selected")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
}


text:
Q: Force an application to use 90% of the cpu, mac a software that I downloaded is kinda running slow and I guess it could run a bit faster, so I wondered: Can you force an application to use 90% of the cpu (90% not 100% {leave 10% for other stuff})?
Any answers appreciated.

A: Applications will normally use whatever processing power is available.  If your application is consuming very little processing time, then it's probably because it's waiting for other processes (e.g., waiting for information from a web site, a slow disk, etc.).
Some modern Operating Systems may allow you to set a maximum limit on processor utilization on a per-application/process basis.  If you're using the newer generation Unix-based MacOS, there's a command called "nice" which will be of interest to you -- if you can get to a shell (command-line prompt) Console, you can type this command to view the documentation:  man nice

A: Simple... This is very possible and I use it all the time for crunching videos and other stuff. Basically you want to use process-renicer (noxeos). This application can control the processing for any process.
But be careful, you may seriously impact the operating system if you don't watch out!
Have fun.


text:
Q: I add pagination in my data table but some columns data not search In my model I am join other table branch after join my from to data are present but not search and other data search successfully.

view:

                  Dispatch Challan No
                  Date
                  From
                  To
                  Lorry No.
                  Pan Card
                  Driver
                  Owner
                  Remark

controller:
 public function getData()
  {
           // POST data
           $postData = $this->input->post();
           $data = $this->dispatchModel->viewData($postData);
           echo json_encode($data);
  }

Model :
function viewData($postData=null){
     $response = array();
     ## Read value
     $draw            = $postData['draw'];
     $start           = $postData['start'];
     $rowperpage      = $postData['length']; // Rows display per page
     $columnIndex     = $postData['order'][0]['column']; // Column index
     $columnName      = $postData['columns'][$columnIndex]['data']; // Column name
     $columnSortOrder = $postData['order'][0]['dir']; // asc or desc
     $searchValue     = $postData['search']['value']; // Search value

    ## Search
     $searchQuery = "";
     if($searchValue != ''){

         $searchQuery = " (b.disp_ch_no like '%".$searchValue."%' or b.disp_ch_date like '%".$searchValue."%' or b.disp_ch_from like'%".$searchValue."%' or b.disp_ch_to like'%".$searchValue."%' or b.disp_ch_lorryno like'%".$searchValue."%' or b.disp_ch_pan like'%".$searchValue."%' or b.disp_ch_driver like'%".$searchValue."%' or b.disp_ch_owner like'%".$searchValue."%' or b.disp_ch_remark like'%".$searchValue."%') ";
     }

     if($searchValue != '')
     $this->db->where($searchQuery);
     $records = $this->db->get('dispatch_challan b')->result();
     $this->db->select('bn.branch_name as from_branch_name,bn1.branch_name as to_branch_name,vn.vehicle_no as vehicle,b.*,vn.*,');
             $this->db->from('dispatch_challan b');
             $this->db->join('vehicle vn', 'b.disp_ch_lorryno=vn.vehicle_id','left');
             $this->db->join('branch  bn', 'b.disp_ch_from=bn.branch_id','left');
             $this->db->join('branch  bn1','b.disp_ch_to=bn1.branch_id','left');
             $this->db->where('b.status','active');

     if($searchValue != '')
     $this->db->where($searchQuery);
     $this->db->order_by($columnName, $columnSortOrder);
     $this->db->limit($rowperpage, $start);

     $records = $this->db->get()->result();

     $data = array();
     foreach($records as $record ){

        $data[] = array(
           "disp_ch_no"          =>$record->disp_ch_no,
           "disp_ch_date"        =>$record->disp_ch_date,
           "from"                =>$record->from_branch_name,
           "to"                  =>$record->to_branch_name,
           "vehicle"             =>$record->vehicle,
           "disp_ch_pan"         =>$record->disp_ch_pan,
           "disp_ch_driver"      =>$record->disp_ch_driver,
           "disp_ch_owner"       =>$record->disp_ch_owner,
           "disp_ch_remark"      =>$record->disp_ch_remark
        );
     }
     ## Response
     $response = array(
        "draw" => intval($draw),
        "aaData" => $data
     );
     return $response;
   }


text:
Q: Can't get ValueInjecter to map COM objects See the following code. The test passed when using AutoMapper, but failed when using ValueInjecter:
using NetFwTypeLib;

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        INetFwPolicy2 policy = (INetFwPolicy2)Activator.CreateInstance(
                Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
        INetFwRules fwRules = policy.Rules;
        Rule rule = new Rule();

        foreach (INetFwRule fwRule in fwRules)
        {
            if (fwRule.Name == "HomeGroup Out")
            {
                //AutoMapper.Mapper.CreateMap<INetFwRule, Rule>();
                //AutoMapper.Mapper.Map(fwRule, rule);
                rule.InjectFrom(fwRule);
                break;
            }
        }
        Assert.IsTrue(rule.Name == "HomeGroup Out");
    }
}

public class Rule
{
    public string Name { get; set; }
}

Any ideas? Thanks.
Edit:
Based on Omu's answer, it seems the problem is related to COM objects, not only FirewallAPI.dll classes. So I changed title from "Can't get ValueInjecter to map FirewallAPI.dll classes" to "Can't get ValueInjecter to map COM objects".

A: it doesn't work because doing:
fwRule.GetType().GetProperties().Count()// is 0

or doing the same using PropertyDescriptor also return zero, it's like the object doesn't has properties
the solution is to write an injection that will take the type from where to get the properties:
public class Same<T> : ValueInjection
{
   protected override void Inject(object source, object target)
   {
       var props = typeof (T).GetInfos().ToArray();
       var tp = target.GetInfos().ToArray();
       for (var i = 0; i < props.Count(); i++)
       {
          var prop = props[i];
          for (var j = 0; j < tp.Count(); j++)
          {
            if(prop.Name == tp[j].Name && prop.PropertyType == tp[j].PropertyType)
            tp[j].SetValue(target,prop.GetValue(source, null),null);
          }
        }
      }
  }

and the usage:
rule.InjectFrom<Same<INetFwRule>>(fwRule);

this is the same as the default InjectFrom() but it reads the target properties from the supplied Type


text:
Q: Alternative to etsy/statsd Is there any alternative to etsy's statsd? Maybe even a complete dashboard-like solution? My research only found proprietary SaaS solutions.
For those who do not know: statsd is a deamon which collects app and system metrics via UDP and sends them to Graphite to generate more or less beautiful plots. There is an API for all important languages available.
I need:

*

*must run on my servers without a third party collecting the data

*should be able to collect data both from the system, Java and Perl

*should be lightweight and flexible

*FOSS

*may require additional programming, may be only a framework

A: Check out the following two projects:

*

*batsd

*batsd-dash
batsd is a daemon for aggregating and storing statistics, while batsd-dash is a configurable dashboard the present the data you have stored in batsd.
About batsd

Batsd is a ruby-based daemon for aggregating and storing statistics.
  It targets "wireline" compatibility with Etsy's StatsD implementation,
  which they described in a blog post.
Batsd differs from etsy's statsd implementation primarily in how it
  stores data -- data is stored to a combination of Redis and flat files
  on disk. You can read more about persistence in About: Persistence.
Batsd grew out of usage at 37signals, where it has been used for the
  last year. An earlier form was inspired by quasor.

A: This seems perilously close to a shopping question, which aren't permitted on SF (see the FAQ).  I also don't know statsd, but from the list of capabilities I can say that munin fulfils them all.  Rrdtool is used as the data aggregation and graphing engine.  Since it's plugin-based, it can collect and process any statistic that you can locally source on the server with an atomic operation.

A: I do not think you should try to replace statsd since it is almost a standard for most metric tools. The big problem when building your metrics system tends to be the default backend: graphite. It is a pain to install unless you are familiar with Django apps.
With batsd and its dashboard you can get started rather quick, specially if you know Ruby. However the dashboard is quite limited.
My choice was using influxdb as backend for statsd and rendering graphs with Grafana. Initially I was tempted to send my metrics directly to influxdb, but could not deny the variety of clients in multiple languages for Statsd. That and you will need it also to aggregate data with time.


text:
Q: sparql how to count variable pairs I have the following query that gets instances of a class and their label/names. I want to count how many total results there are. However, I do not know how to formulate the count statement.
select ?s ?l {
   ?s a <http://dbpedia.org/ontology/Ship> .
   {?s <http://www.w3.org/2000/01/rdf-schema#label> ?l}
   union
   {?s <http://xmlns.com/foaf/0.1/name> ?l}
}

I have tried
select ?s ?l (count (?s) as ?count) {
   ?s a <http://dbpedia.org/ontology/Ship> .
   {?s <http://www.w3.org/2000/01/rdf-schema#label> ?l}
   union
   {?s <http://xmlns.com/foaf/0.1/name> ?l}
}

But that gives the counting for each ?s ?l pair, instead I need to know how many of the ?s ?l pairs there are. Or maybe I should not use count at all? As mentioned all I need to know is how many results in total a query returns (regardless of the hard limit that is put by the server, e.g., DBPedia returns a maximum of 50000 results for each query).
Any suggestions please?
Many thanks!

A: To count the number of matches, use
SELECT (COUNT(*) AS ?count)
WHERE {
   ?s <http://www.w3.org/2000/01/rdf-schema#label> | <http://xmlns.com/foaf/0.1/name> ?l .
}

Note I'm using the property path "or" (|) to get the union of the properties.


text:
Q: Arrays in Macros in SAS %macro test ;
%array factors(7) &ordered_col ;
%array names(7) &ordered_col2 ;
%do i = 1 %to 7 ;
%let factorname = factors(&i) ;
%let output = names(&i) ;
proc sort data=actshare.policy out=&output nodupkey ;
by &factorname ;
quit ;
%end ;

%mend ;

%test

where ordered_col and ordered_col2 are my respective arrays. how can I run this program.
please help with a suitable suggestion.

A: There is no such thing as a macro array or a %ARRAY statement.
If you have a list of values in a macro variable then use the %SCAN() function to select items from the list.
%macro test(varlist,dslist);
%local factorname output i ;
%do i = 1 %to %sysfunc(countw(&varlist)) ;
  %let factorname = %scan(&varlist,&i) ;
  %let output = %scan(dslist,&i) ;
proc sort data=actshare.policy out=&output nodupkey ;
  by &factorname ;
run ;
%end ;
%mend test;

%test(var1 var2 var3,ds1 ds2 ds3)

If instead you have created a series of macro variables with same base name and a numeric suffix you will need to know number of them to make your %DO loop. So if you had done:
%let varname1=var1;
%let varname2=var2;
%let dsname1=ds1;
%let dsname2=ds2;
%let n=2;

Then your loop might look like this instead:
%do i=1 %to &N;
  %let factorname = &&varname&i ;
  %let output = &&dsname&i ;
...
%end;


text:
Q: Assignment not allowed in while expression? In Java we can usually perform an assignment within the while condition. However Kotlin complains about it. So the following code does not compile:
val br = BufferedReader(InputStreamReader(
        conn.inputStream))

var output: String
println("Output from Server .... \n")
while ((output = br.readLine()) != null) { // <--- error here: Assignments are not expressions, and only expressions are allowed in this context
    println(output)
}

According to this other thread, this seems the best solution:
val reader = BufferedReader(reader)
var line: String? = null;
while ({ line = reader.readLine(); line }() != null) { // <--- The IDE asks me to replace this line for while(true), what the...?
  System.out.println(line);
}

But is it?

A: No, the best way, IMO, would be
val reader = BufferedReader(reader)
reader.lineSequence().forEach {
    println(it)
}

And if you want to make sure the reader is properly closed (as you would with a try-with-resources statement in Java), you can use
BufferedReader(reader).use { r ->
    r.lineSequence().forEach {
        println(it)
    }
}

A: In cases you just want to replace while ((x = y.someFunction()) != null) you may use the following instead:
generateSequence { y.someFunction() }
          .forEach { x -> /* what you did in your while */ }

generateSequence will extract you all the values one by one until the first null is reached. You may replace the .forEach with a reduce or fold (or anything else that seems appropriate ;-)) if you want to keep the last value or sum up the values to something else.
For your specific use case however you may just use what JB Nizet in his answer has shown or use useLines:
reader.useLines {
  it.forEach(::println)
}

.forEachLine is probably the next best short-hand solution to that specific readLine-problem (already answered here) if you know you just want to read all lines and then stop.

A: And here is a short Kotlin-style general solution by Roman Elizarov:
while (true) {
    val line = reader.readLine() ?: break
    println(line);
}

Here break has Nothing type that also helps to promote type inference for the line as non-nullable string.

A: Here is the shortest solution powered by stdlib that also safely closes the reader:
reader.forEachLine {
    println(it)
}

A: I found that these days IntelliJ converts your Java code into the following kotlin code:
val br = BufferedReader(InputStreamReader(
        conn.inputStream))

var output: String
while (br.readLine().also { output = it } != null) {
    println(output)
}

This is still confusing but it's quite readable. It uses the fact that also returns the receiver instance (the result of br.readLine() here).

A: (This Example for while loop ) Hope this example will help you..
Change from
while ((c = is.read(buffer)) > 0) {
            sb.append(String(buffer, 0, c, Charset.forName(UTF8)))
}
to
while ({c = is.read(buffer);c}() > 0) {
            sb.append(String(buffer, 0, c, Charset.forName(UTF8)))
}


text:
Q: Network request failed with fetch and expo? In a new expo app I wrote actions identical to a normal react-native app but they do not work.
In the past fetch worked just fine on non expo apps.
const f = await fetch(
    `${server}/u/login/app`,
    {
      cache: 'no-cache',
      credentials: 'same-origin',
      body: JSON.stringify({
        username: login,
        password,
      }),
      headers: {
        accept: 'application/json',
        'content-type': 'application/json',
      },
      method: 'POST',
    }
  );

I expected to get a 200 response with a json object.
Instead it throws
TypeError: Network request failed
    at XMLHttpRequest.xhr.onerror


text:
Q: Getting current position of PyAudio stream? I'm currently working on a project which involves processing an audio file using FFMpeg, and then pipelining this into a PyAudio instance.
I cannot see anywhere in the documentation on how to retrieve the current position of the audio stream. I'm writing to the PyAudio instance in chunks of (44100 * 2).
Does this imply that 1 second of audio, would correspond to 1 of these chunks, or am I mistaken?


text:
Q: getView nullPointerException for custom List View Android I have 2 custom list view which I use to display different categories. However when the second list view is created, I get this NullPointerException when returning from getView. I am unable to figure out the reason for that.
Here is the code:
CustomListAdapter:
public class CustomListAdapter extends ArrayAdapter<String>{

    Context context;
    String[] stringList;
    TextView medium, small;

    public CustomListAdapter (Context con, String[] sL)
    {
        super(con, R.layout.my_list, R.id.mediumTextInList, sL);
        context = con;

        stringList = sL;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View newRowView = inflator.inflate(R.layout.my_list, parent,false);

        medium = (TextView) newRowView.findViewById(R.id.mediumTextInList);
        small = (TextView) newRowView.findViewById(R.id.smallText);

        medium.setText(stringList[position]);

        return super.getView(position, newRowView, parent);
    }

}
ListActivity:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

        Bundle myBasket = new Bundle();

        myBasket.putString("name", categoryName);

        Intent myIntent = new Intent(myFirstList.this, mySecondList.class);

        myIntent.putExtras(myBasket);
        startActivity(intent);
 }

StackTrace:
07-28 17:04:46.551: E/AndroidRuntime(2290): FATAL EXCEPTION: main
07-28 17:04:46.551: E/AndroidRuntime(2290): java.lang.NullPointerException
07-28 17:04:46.551: E/AndroidRuntime(2290):     at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:355)
07-28 17:04:46.551: E/AndroidRuntime(2290):     at android.widget.ArrayAdapter.getView(ArrayAdapter.java:323)
07-28 17:04:46.551: E/AndroidRuntime(2290):     at com.umer.androiduetproject.CustomListAdapterForDeptAndSemesters.getView(CustomListAdapterForDeptAndSemesters.java:53)
07-28 17:04:46.551: E/AndroidRuntime(2290):     at android.widget.AbsListView.obtainView(AbsListView.java:1430)
07-28 17:04:46.551: E/AndroidRuntime(2290):     at android.widget.ListView.makeAndAddView(ListView.java:1745)
07-28 17:04:46.551: E/AndroidRuntime(2290):     at android.widget.ListView.fillDown(ListView.java:670)
07-28 17:04:46.551: E/AndroidRuntime(2290):     at android.widget.ListView.fillFromTop(ListView.java:727)
07-28 17:04:46.551: E/AndroidRuntime(2290):     at android.widget.ListView.layoutChildren(ListView.java:1584)
07-28 17:04:46.551: E/AndroidRuntime(2290):     at android.widget.AbsListView.onLayout(AbsListView.java:1260)
07-28 17:04:46.551: E/AndroidRuntime(2290):     at android.view.View.layout(View.java:7175)
07-28 17:04:46.551: E/AndroidRuntime(2290):     at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
07-28 17:04:46.551: E/AndroidRuntime(2290):     at android.view.View.layout(View.java:7175)
07-28 17:04:46.551: E/AndroidRuntime(2290):     at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
07-28 17:04:46.551: E/AndroidRuntime(2290):     at android.view.View.layout(View.java:7175)
07-28 17:04:46.551: E/AndroidRuntime(2290):     at android.view.ViewRoot.performTraversals(ViewRoot.java:1140)
07-28 17:04:46.551: E/AndroidRuntime(2290):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1859)

Regards

A: You aren't supposed to call super.getView, just return newRowView.

A: Is there null value in stringList? Method toString() may be called in super.getView().

A: You can use this way.
@Override
    public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder holder;
    View newRowView = convertView;

    if (convertView == null) {
        LayoutInflater inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        newRowView = inflator.inflate(R.layout.my_list, parent,false);
        holder = new ViewHolder();
        holder.medium = (TextView) newRowView.findViewById(R.id.mediumTextInList);
        holder.small = (TextView) newRowView.findViewById(R.id.smallText);

        newRowView .setTag(holder);
       }

     else {

          holder = (ViewHolder) newRowView .getTag();
          }

         holder.medium.setText(stringList[position]);

        return newRowView ;
    }


text:
Q: How to count rows for all existing tables in Azure Synapse SQL Pool? I'd like to generate a table that consists of list of all available tables and number of rows for each of them.

Table Name
Number of rows

SCHEMA.TABLE_NAME1
30

SCHEMA.TABLE_NAME2
40

I've used the query below:
select schema_name(tab.schema_id) + '.' + tab.name as [table],
sum(part.rows) as [rows]
   from sys.tables as tab
        inner join sys.partitions as part
            on tab.object_id = part.object_id
where part.index_id IN (1, 0) -- 0 - table without PK, 1 table with PK
group by schema_name(tab.schema_id) + '.' + tab.name
order by sum(part.rows) desc

but unfortunately, the number of rows for all tables with more than 1000 rows is 1000 for some reason.
Is there any other way to do that?

A: The query that you are using is also giving incorrect results for me. For some reason, the rows column in sys.partitions has its value as 1000 when the table is created (even though the tables are empty).

Is there any other way to do that?

*

*As an alternative, I tried using the following query. I created a temporary table called #rows_for_tables which will be used to store our result.

*Then I have used while loop, where we loop through table names collected in a temporary table req_tables, to calculate the number of rows for each table available in sys.tables.

*We get a table_name, insert it in rows_for_tables, update the no_of_rows field with count of table_name for that particular table and delete that table_name from #req_tables (Since its is inserted and we don't need it).

*Once the above procedure is executed, the required results will be present in #rows_for_tables temporary table.
Total Query:
CREATE TABLE #rows_for_tables
(
    table_name varchar(50),
    no_of_rows int
)

select top(1000) name into #req_tables from sys.tables

declare @t_name varchar(50)

while exists (select * from #req_tables)
begin

    select @t_name = (select top 1 name
                       from #req_tables
                       order by name asc)

    insert into #rows_for_tables(table_name) values(@t_name)

    exec('update #rows_for_tables set no_of_rows = (select count(*) from '+@t_name+') where table_name='''+@t_name+'''')

    delete from #req_tables
    where name = @t_name

end

select * from #rows_for_tables

Output:

A: Here is the code that will do it for you:
CREATE TABLE #temp_row_count

    (   row_num INT,
        table_name VARCHAR(100),
        row_count INT
    )

INSERT INTO #temp_row_count
(row_num, table_name)
(SELECT
    ROW_NUMBER() OVER(ORDER BY SCHEMA_NAME(tbl.schema_id)+'.'+tbl.name ASC),
    SCHEMA_NAME(tbl.schema_id)+'.'+tbl.name
FROM sys.tables AS tbl
WHERE SCHEMA_NAME(tbl.schema_id) = 'dbo')

DECLARE @Counter INT
DECLARE @Table VARCHAR(100)
SET @Counter = 1

WHILE @Counter <= (SELECT COUNT(*) FROM #temp_row_count)
BEGIN
    SET @Table = (SELECT table_name FROM #temp_row_count WHERE row_num = @Counter)
    EXEC('UPDATE #temp_row_count SET row_count = (SELECT COUNT(*) FROM '+ @Table +') WHERE row_num='''+ @Counter +'''')
    SET @Counter = @Counter + 1
END

SELECT * FROM #temp_row_count
DROP TABLE #temp_row_count


text:
Q: iOS "Data Protection" depends on user passcode set or not? When developing iOS Apps one can chose to add the Capability "Data Protection", which then offers more "protection".
What, after a lot of searching and reading, is still unclear to me: will the files declared to be secured with "complete protection" be encrypted even if the user doesn't set a passcode?
Every thing I found always somehow involves the passcode of the user. I need to have things encrypted even though the user has no passcode set.
Thx in advance!

A: From the iOS documentation (Protecting Data Using On-Disk Encryption):

Data protection is available on most iOS devices and is subject to the following requirements:

*

*The file system on the user's device must support data protection. Most devices support this behavior.

*The user must have an active passcode lock set for the device.

I'd say the 2nd bullet point answers your question.


text:
Q: React Bootstrap Accordion on table Hi is anyone know how to implement accordion on react table? im trying to hide my entire table upon clicking a title ( tag). thank you

                    <FormLabel className="btn-success d-flex justify-content-center m-0">

PF1 AS Alert

                    </FormLabel>

                        Time
                        Job Name
                        Result
                        Alarm Switch

                      Latest Update Time:
                          {new Date().toDateString()}
                          {new Date().toLocaleTimeString()}

A: Basically, you maintain a state say open and have an onClick on the title and toggle the state open
Working demo in codesandbox
The example uses a simple div without styles but you get the idea.
Example snippet:
class App extends React.Component {
  constructor() {
    super();
    this.state = {
      data: makeData(),
      open: true
    };
  }
  toggleAccordian = () => {
    this.setState(prev => ({ ...prev, open: !prev.open }));
  };
  render() {
    const { data } = this.state;
    return (

          toggle table

          <ReactTable
            data={data}
            columns={[
              {
                Header: "First Name",
                accessor: "firstName",
                className: "sticky",
                headerClassName: "sticky"
              },
    ......

Also as mentioned in the comments, if you are using any library you can make use of ready-made accordions


text:
Q: Null value in v-model I have a Nativescript-Vue app where I make a REST call to return a response to be displayed.  It may not always be fully populated, and when that happens I get an error such as:

[Vue warn]: Error in render: "TypeError: null is not an object
  (evaluating '_vm.office.address.addressLine1')"

Here is the REST response I get from the server:
{
   "officeId":2,
   "name":null,
   "beginDate":[
      2020,
      4,
      18
   ],
   "endDate":null,
   "officeType":null,
   "address":null
}

And here is the Vue code that has problems:
<StackLayout class="nt-input">
   <Label text="Address Line 1" class="m-b-5"/>
   <TextField :editable="!isViewOnly" v-model="office.address.addressLine1"  v-shadow="2" hint="Enter address line 1" class="-border"/>
</StackLayout>

Because the address hasn't been established, it will be null for new records.  Is there any way to get this to render so users can populate?

A: If office.address is null, then accessing office.address.addressLine1 will always result in that error. You have to ensure that address is not null before doing so.
After fetching the data, you can check if address is null and then setting it to a new empty address object that you need:
// Make the request
const office = await fetchOffice()

// Ensure that address is defined
if (!office.address) {
  office.address = {
    addressLine1: ''
  }
}

// Now that we have defined all properties on the object, we
// can assign it to the component instance to make it reactive
this.office = office

It is important you define any new properties on the object before you assign it to the component otherwise Vue won't make the new properties reactive (read Change Detection Caveats).


text:
Q: Disable high watermark-Log entries in sonarqube 5.6 I have a little problem with sonarqube 5.6 I got the error:
high disk watermark [90%] exceeded on [dGbc0mfEQmOT5LXYQU45aQ][sonar-1498565081006] free: 931mb[5.1%], shards will be relocated away from this node
high disk watermark [90%] exceeded on [dGbc0mfEQmOT5LXYQU45aQ][sonar-1498565081006] free: 931mb[5.1%], shards will be relocated away from this node

in the sonar.log which I would like to disable (or at least decrease the limit). And after a little search I found out that I have to run this command
curl --noproxy '*' --u admin:admin -vvvv -XPUT http://localhost:9004/_cluster/settings -d '{"persistent" : {"cluster.routing.allocation.disk.threshold_enabled": False}}'

but when I do this I got a 404-Error and I have no idea why this don't work. That's why I would very thanksful if someone can give me a little hint what I am doing wrong? The sonarqube-Installation is running on SuSE.
best regards
Dan

A: This message indicates than there is not enough free disk space on your server, so the best fix is to free some space.
Your curl request is not working because you need to start SonarQube with this property set :
sonar.search.httpPort=10000
and use this port (without any authentication -u admin:admin) in your curl request.
And then remove this property and restart SonarQube.
Please note that overriding this value is not supported.


text:
Q: XML xs::assert in complex type I am trying to introduce conditional mandatory fields in my XML schema but I am getting an error that xs:assert isn't valid in context... any suggests to help please?
Additional information: I am using Xerces 3.11 (C++) to parse the xml)
<?xml version="1.0" encoding="iso-8859-1" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="configuration" type="configurationType"/>

  <xs:complexType name="configurationType">
    <xs:sequence>
      <xs:element name="application" minOccurs="1" maxOccurs="unbounded" type="appType" />
      <xs:element name="command" minOccurs="1" maxOccurs="unbounded" type="commandType"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="appType">
    <xs:attribute name="name" type="xs:string" use="required" />
    <xs:attribute name="hostname" type="xs:string" use="required" />
    <xs:attribute name="port" type="xs:positiveInteger" use="required" />
    <xs:attribute name="group" type="xs:string" use="required" />
    <xs:assert test="@hostname or @port != 4"/>
  </xs:complexType>

  <xs:complexType name="commandType">
    <xs:attribute name="name" type="xs:string" use="required" />
    <xs:attribute name="target" type="xs:string" use="required" />
    <xs:attribute name="parameter" type="xs:string" use="optional" />
  </xs:complexType>

</xs:schema>

A: Xerces 3.1.1 C++ does not support XSD 1.1. This is the root cause.
XSDL 1.1 experimental processor was introduced at Xerces-J (Java only) starting from version 2.10.0.


text:
Q: Cannot start MySQL cluster with single node For some testing I have installed MySQL Cluster.
I can get it to work with configuration suggested in Lunix guick start guide.
My configuration:
[ndb_mgmd]
hostname=localhost
datadir=/home/vmUser/my_cluster/ndb_data
NodeId=1
[ndbd default]
noofreplicas=2
datadir=/home/vmUser/my_cluster/ndb_data
[ndbd]
hostname=localhost
NodeId=3
[ndbd]
hostname=localhost
NodeId=4
[mysqld]
NodeId=50

And start script:
#/bin/bash
echo "" > mysql_cluster_start_script.log
$HOME/mysqlc/bin/ndb_mgmd -f conf/config.ini --initial --configdir=$HOME/my_cluster/conf/ >> mysql_cluster_start_script.log
$HOME/mysqlc/bin/ndbd -c localhost:1186 >> mysql_cluster_start_script.log
$HOME/mysqlc/bin/ndbd -c localhost:1186 >> mysql_cluster_start_script.log
$HOME/mysqlc/bin/ndb_mgm -e show >> mysql_cluster_start_script.log
$HOME/mysqlc/bin/mysqld --defaults-file=conf/my.cnf > mysqld.log 2>&1 &

And it works.
Now I want to start it with only one node. So I changed noofreplicas to 1, deleted second node configuration from conf and starting second node from start script.
New config file:
[ndb_mgmd]
hostname=localhost
datadir=/home/vmUser/my_cluster/ndb_data
NodeId=1
[ndbd default]
noofreplicas=1
datadir=/home/vmUser/my_cluster/ndb_data
[ndbd]
hostname=localhost
NodeId=3
[mysqld]
NodeId=50

New startup script:
#/bin/bash
echo "" > mysql_cluster_start_script.log
$HOME/mysqlc/bin/ndb_mgmd -f conf/config.ini --initial --configdir=$HOME/my_cluster/conf/ >> mysql_cluster_start_script.log
$HOME/mysqlc/bin/ndbd -c localhost:1186 >> mysql_cluster_start_script.log
$HOME/mysqlc/bin/ndb_mgm -e show >> mysql_cluster_start_script.log
$HOME/mysqlc/bin/mysqld --defaults-file=conf/my.cnf > mysqld.log 2>&1 &

With one configuration I get strange error when trying to operate on database:
mysql> CREATE TABLE `test_table` (
    ->   `id` int(11) NOT NULL,
    ->   `data` blob NOT NULL,
    ->   PRIMARY KEY (`id`)
    -> )
    -> engine=ndb;
ERROR 157 (HY000): Could not connect to storage engine
mysql> SHOW WARNINGS;
+---------+------+---------------------------------------------------------------------------------+
| Level   | Code | Message                                                                         |
+---------+------+---------------------------------------------------------------------------------+
| Warning | 1296 | Got error 4009 'Cluster Failure' from NDB. Could not acquire global schema lock |
| Warning | 1296 | Got error 4009 'Cluster Failure' from NDB                                       |
| Error   |  157 | Could not connect to storage engine                                             |
| Error   | 1499 | Too many partitions (including subpartitions) were defined                      |
+---------+------+---------------------------------------------------------------------------------+
4 rows in set (0.00 sec)

I have no idea what I am doing wrong.
I want to start only one node because ram saving during tests.
EDIT:
Ok, I have no idea which one of logs I should investigate first.
vmUser@DB-38:~/my_cluster/ndb_data$ ll
total 1024
drwxrwxrwx 4 mysql  mysql    4096 Aug 15 09:20 ./
drwxrwxrwx 6 mysql  mysql    4096 Aug 15 09:20 ../
-rw-rw-r-- 1 vmUser vmUser 205438 Aug 15 09:20 ndb_1_cluster.log
-rw-r--r-- 1 vmUser vmUser   1316 Aug 15 09:15 ndb_1_out.log
-rw-rw-r-- 1 vmUser vmUser   3063 Aug 15 09:15 ndb_3_error.log
drwxr-x--- 9 vmUser vmUser   4096 Apr  3 10:54 ndb_3_fs/
-rw-r--r-- 1 vmUser vmUser 133015 Aug 15 09:15 ndb_3_out.log
-rw-r--r-- 1 vmUser vmUser      4 Aug 15 09:15 ndb_3.pid
-rw-rw-r-- 1 vmUser vmUser 136828 Aug 11 10:17 ndb_3_trace.log.1
-rw-rw-r-- 1 vmUser vmUser  76253 Aug 11 11:08 ndb_3_trace.log.2
-rw-rw-r-- 1 vmUser vmUser  79854 Aug 11 11:08 ndb_3_trace.log.3
-rw-rw-r-- 1 vmUser vmUser  79406 Aug 11 11:11 ndb_3_trace.log.4
-rw-rw-r-- 1 vmUser vmUser  80864 Aug 11 11:14 ndb_3_trace.log.5
-rw-rw-r-- 1 vmUser vmUser  84115 Aug 15 09:15 ndb_3_trace.log.6
-rw-rw-r-- 1 vmUser vmUser      1 Aug 15 09:15 ndb_3_trace.log.next
drwxr-x--- 9 vmUser vmUser   4096 Apr  3 10:54 ndb_4_fs/
-rw-r--r-- 1 vmUser vmUser 103650 Aug 15 09:10 ndb_4_out.log
-rw-r--r-- 1 vmUser vmUser      4 Aug 15 09:05 ndb_4.pid

EDIT2:
Ok, I think I get actual error from ndb_3_error.log:
Time: Thursday 15 August 2013 - 09:15:30
Status: Permanent error, external action needed
Message: Invalid configuration received from Management Server (Configuration error)
Error: 2350
Error data: Illegal configuration change. Initial start needs to be performed  when changing no of replicas (2 != 1)
Error object: DBDIH (Line: 4826) 0x00000002
Program: ndbd
Pid: 1836
Version: mysql-5.5.30 ndb-7.2.12
Trace: /home/vmUser/my_cluster/ndb_data/ndb_3_trace.log.6 [t1..t1]
***EOM***

And from ndb_1_cluster.log I have:
2013-08-15 09:15:30 [MgmtSrvr] ALERT    -- Node 3: Forced node shutdown completed. Occured during startphase 1. Caused by error 2350: 'Invalid configuration received from Management Server(Configuration error). Permanent error, external action needed'.
2013-08-15 09:15:30 [MgmtSrvr] ALERT    -- Node 1: Node 3 Disconnected

I do not exactly understand what I am doing wrong. It says: Initial start needs to be performed  when changing no of replicas, but I am starting engine from scratch.
Do I need to put this option also in some other place than my.conf file? Or maybe my starting script is not proper?


text:
Q: Silverstripe add/save object to has_one relation I cannot find a clue on how to correctly save a has_one relation in Silverstripe.
class Car extends DataObject {
  $has_one = array(
     'garage'=>'Garage';
  );
}

class Garage extends DataObject {
  $has_many = array(
     'cars'=>'Car';
  );
}
// let's say I have these records in the DB
$g = Garage::get()->ByID(111);
$c = Car::get()->ByID(222);

// I want to do sth like this to define the relation
$c->Garage = $g;
$c->write();

But this code does nothing, no error, but also the relation is not created in the DB.
What I could to is this:
$c->GarageID = $g->ID;
$c->write();

But this does not seem very ORM like...

A: there doesn't seem to be an extra method for adding has_one relations, but if you want to stick with the ORM, you could do it the other way around:
$g->cars()->add($c);

A: This question is especially relevant if you have no corresponding has_many relationship, but want to establish an unsaved relationship between two objects.
What worked for me was creating a property, under the initial class, and assigning the unsaved relating object against that. The major limitations are:

*

*Your reference to the most current instance of the object needs to always be the property, otherwise you'll get concurency issues.

*Large objects being asigned will weigh down your available memory.

Fortunately, my case was a very simple object.
Example:
Car.php:
. . .

private static $has_one = array(
    'Garage' => 'Garage'
);

private $unsaved_relation_garage;

protected function onBeforeWrite() {

    parent::onBeforeWrite();

    // Save the unsaved relation too
    $garage = $this->unsaved_relation_garage;

    // Check for unsaved relation
    // NOTE: Unsaved relation will override existing
    if($garage) {

        // Check if garage already exists in db
        if(!$garage->exists()) {

            // If not, write garage
            $garage->write();
        }

        $this->GarageID = $garage->ID;
    }
}

/**
 * setGarage() will assign a written garage to this object's has_one 'Garage',
 * or an unwritten garage to $this->unsaved_relation_garage. Will not write.
 *
 * @param Garage $garage
 * @return Car
 */
public function setGarage($garage) {

    if($garage->exists()) {
        $this->GarageID = $garage->ID;
        return $this;
    }

    $this->unsaved_relation_garage = $garage;
    return $this;
}

/**
 * getGarage() takes advantage of the variation in method names for has_one relationships,
 * and will return $this->unsaved_relation_garage or $this->Garage() dependingly.
 *
 * @return Garage
 */
public function getGarage() {

    $unsaved = $this->unsaved_relation_garage;

    if($unsaved) {
        return $unsaved;
    }

    if($this->Garage()->exists()) {
        return $this->Garage();
    }

    return null;
}

. . .


text:
Q: Java Library for converting a long IPv6 address into its compressed form I would like to know, whether there is a library which I can use to convert a represenation of a long IPv6 address (such as 2002:9876:57AB:0000:0000:0000:0000:0001) into the compressed IPv6 form (in this case: 2002:9876:57AB::1).
I was not able to find such a library. This library should not use any IP Api, a network connection must not be made.
I already tried
return Inet6Address.getByName(longAdress).toString();

but this just replaces the 4 zeros with 1 zero (in this case 2002:9876:57AB:0:0:0:0:1).
any suggestions?

A: java-ipv6 is a very decent library for that. It also handles address ranges well.

A: public class Ipv6AddressCompressor {
    public static String getCompressedAddress(String longAddress) throws UnknownHostException {
        longAddress = Inet6Address.getByName(longAddress).getHostAddress();
        return longAddress.replaceFirst("(^|:)(0+(:|$)){2,8}", "::");
    }
}

This should protect you against invalid addresses (throws the UnknownHostException), and will properly compress trailing ipv4 addresses (i.e. 0:0:0:0:0:0:255.255.255.255 -> ::FFFF:FFFF).  This will also protect against already compressed addresses.

A: The open-source IPAddress Java library can do ip address parsing and produce a variety of strings.  Disclaimer: I am the project manager of that library.
Example code:
    String ipv6 = "2002:9876:57AB:0000:0000:0000:0000:0001";
    try {
        IPAddressString str = new IPAddressString(ipv6);
        IPAddress addr = str.toAddress();
        String compressed = addr.toCompressedString();
        System.out.println(compressed); //
    } catch(IPAddressStringException e) {
        //e.getMessage has validation error
    }

output:
2002:9876:57ab::1

A: You can try this code. It'll probably perform better than the regex equivalent (not that I have benchmarked it, or anything). It's pretty well tested too.
Note that you will need to use a numeric representation (in byte[]) of the IP address. To get it you can either do InetAddress.getByName(ip).getAddress() if you need to resolve host names, or use sun utility class IPAddressUtil.textToNumericFormatV6(ip) to parse from an IP address without host resolution.
private static final char[] ipv6conseqZeroFiller = { ':', ':' };
private static final char ipv6hextetSeparator = ':';

/*
 * Convert numeric IPv6 to compressed format, where
 * the longest sequence of 0's (with 2 or more 0's) is replaced with "::"
 */
public static String ipv6toCompressedForm(byte[] src) {
    assert src.length == 16;
    //Find the longest sequence of 0's
    int cmprHextet = -1; //start of compressed region (hextet index)
    int cmprSize = 0; //length of compressed region
    for (int hextet = 0; hextet < 8;) {
        int curByte = hextet * 2;
        int size = 0;
        while (curByte < src.length && src[curByte] == 0
                && src[curByte + 1] == 0) {
            curByte += 2;
            size++;
        }
        if (size > cmprSize) {
            cmprHextet = hextet;
            cmprSize = size;
        }
        hextet = (curByte / 2) + 1;
    }
    if (cmprHextet == -1 || cmprSize < 2) {
        //No compression can be applied
        return ipv6toStr(src);
    }
    StringBuilder sb = new StringBuilder(39);
    ipv6toStr(sb, src, 0, cmprHextet);
    sb.append(ipv6conseqZeroFiller);
    ipv6toStr(sb, src, cmprHextet + cmprSize, 8);
    return sb.toString();
}

/*
 * Convert numeric IPv6 to standard (non-compressed) format.
 *
 * Borrowed from Inet6Address.java #numericToTextFormat(byte[])
 * Changed StringBuffer -> StringBuilder and ":" -> ':' for performance.
 */
public static String ipv6toStr(byte[] src) {
    assert src.length == 16;
    StringBuilder sb = new StringBuilder(39);
    ipv6toStr(sb, src, 0, 8);
    return sb.toString();
}

private static final void ipv6toStr(StringBuilder sb, byte[] src,
        int fromHextet, int toHextet) {
    for (int i = fromHextet; i < toHextet; i++) {
        sb.append(Integer.toHexString(((src[i << 1] << 8) & 0xff00)
                | (src[(i << 1) + 1] & 0xff)));
        if (i < toHextet - 1) {
            sb.append(ipv6hextetSeparator);
        }
    }
}


text:
Q: Load json file from git package by composer I develop git repository, that contains only one useful file data.json. Another repo which I develop in parallel is php implementation of idea.
And now I need to load list from data.json, parse it and then use. First and most obvious idea was write some Loader class, which will try to access this file by 2 ways:

*

*__DIR__ . '/../vendor/ely/anti-tempmail-list/data.json. That case will be worked if we have library itself with its dependencies.

*__DIR__ . '/../../anti-tempmail-list/data.json. That case will be worked if library is included as another composer dependency.
But it's a bit horrible, 'cause crawl on file system is "dirty". And in case of package replacement (hello forks) it will stop working.
Another solution is create in reference repository some language-dependent Loader classes, which will be implement loading for data file. But I'm not sure that this is also a good solution...
So I ask you, how should I organize communication with the reference repository (data.json) to implementation by some programming language?
P.S. reference repo contains russian README, but on release it will be translated as it should be ;)

A: If you develop a PHP package, you should provide a simple PHP class that can be used to get the list from that JSON file:
require `vendor/autoload.php`;

$list = \Elyby\Json::getList();

Implementation:
<?php
namespace Elyby;

class Json
{
    /**
     * @return array
     */
    public static function getList()
    {
        return json_decode(__DIR__.'/data.json', true);
    }
}

Autoloading has to be configured as well.


text:
Q: Runtime error: Unable to get property 'toLowerCase' of undefined or null reference? I am working on Visual-Studio 2013 "MVC" project.
I am using a "Bootstrap-select" plug-in to search and select options in drop-down. It is a multi-select drop-down with a search functionality init.
Initially, I am using a multi-select checkbox which stores the values. But as the requirement changed I used Bootstrap plugin.
The problem is after storing the drop-down values in database, the values are not being displayed in the drop-down in "Edit-Mode". I used ViewBag property to store values in the controller. The values are being stored in the ViewBag in the controller but not being displayed (kept selected) in Front-End.
When I open the drop-down edit link, a pop-up is being displayed in the visual- studio that " Unable to get property 'toLowerCase' of undefined or null reference?"
Pop-Up error box
And when I click continue the page goes to browser and the drop-down doesn't display the selected values.
The code-line where error occurs is
$('li > a').each(function () {
    if ($(this).attr('href').toLowerCase() == pathname.toLowerCase()) {
        $(this).parent().addClass('active');
        $(this).parents('li').addClass('active');
    }
});

I guess the problem lies with the occurring of pop-up.
I searched for similar answers in stack-overflow but I see any of those are not concerned with my answer.


text:
Q: How do I decide if a set is a vector subspace? Let's say we have the set $M = \{ x \in \mathbb R^3 : 3x_1 - x_2 -2x_3 = 1 \}$ and I have to test if M is a vector subspace of $\mathbb R^3$ .
How do I proceed? Going after my intuition, I would say it isn't since the expression pretty much looks like a plane, but how do I prove that formally?

A: To check that a set $M$ is a subspace, you usually need to check that the answer to all of the following three questions is "yes":
a) Is $(0,0,0)$ an element of $M$?
b) If $v_{1}$ and $v_{2}$ are in $M$, is $v_{1} + v_{2}$?
c) If $v$ is in $M$, and $c$ is any real number, is $cv$ in $M$?
Hint: I listed the things you have to check in this order for a reason.  Check a.  If a fails to hold, then you don't need to do any more work because you will know that $M$ is not a subspace!

A: If $M$ is a subspace, then it contains the zero vector of $\mathbb R^3$: $\;\;\begin{pmatrix} x_1\\x_2\\x_3\end{pmatrix} = \begin{pmatrix} 0\\0\\0\end{pmatrix}$.
Does $$3(0) - (0) - 2(0) = 1\;\;?$$
I.e., Does $M$ contain the zero vector? If no, then $M$ cannot be a vector space.

A: Subset $M\subseteq V$ is subspace of $V$ if it is vector space with operations from $V$. One could assume that all axioms of vector space need to be checked, but this is not the case; to prove that $M\subseteq V$ is a subspace, it is actually enough to check this condition:

$(1)$ For any $\alpha,\beta\in\mathbb{R}$ and for any vectors
  $v,w\in M$, linear combination $\alpha v + \beta w\in M$.

This is because all the axioms of vector space are satisfied for any subset $M$ of a vector space $V$ except that $M$ contains zero vector, additive inverses and that subset $M$ is closed under scalar multiplication and addition (which means I could potentially multiply by scalar or add vectors in $M$ but produce a vector not in $M$; this is actually essential for any set to be a vector space and it might be obscured by the fact that this is implicitly assumed for any vector space because scalar multiplication and addition are usually given as functions with codomain $V$, but nevertheless, all vector spaces must satisfy this criteria). These are all implied by $(1)$. Hence, you do not need to check any axioms for your subset, except the condition $(1)$ which can be broken down in two pieces:

$(2)$ For any vectors $v,w\in M$, their sum $v+w$ is in $M$.
  $(3)$
  For any $\alpha\in\mathbb{R}$ and any $v\in M$, we have $\alpha v\in M$.

It might be a good exercise for you to show that:

*

*$(1)$ implies $(2)$ and $(3)$

*$(2)$ and $(3)$ (together) imply $(1)$

*$(1)$ and $(3)$ (separately) imply that $0\in M$

*$(1)$ and $(3)$ (separately) imply that $M$ contains additive inverses

In addition, these conditions ensure that if I multiply by scalar or add vectors in $M$, I will always stay in $M$, and thus making $M$ a vector space.
Now, $(1)$ is the most compact way to check that some subset is a subspace, but it might not be the best approach to show that it is not. To see that something is not a subspace, I recommend that you follow user46944's answer, first checking if $0$ is in your subset, then checking conditions $(2)$ and $(3)$ and to try to find counterexamples using these, instead of $(1)$.

A: To check if a set ($M$) is a subspace of a vector space (E,K) (where $K=\mathbb{R}$ or $\mathbb{C}$) you must check if $0\in M$, $x\in M \implies \lambda x \in M \ \ \ \forall \lambda \in K$ and $x,y\in M \implies x+y\in M$, or for short for all $\alpha ,\beta \in K$ and all $x,y\in M$ you hace $$\alpha x+ \beta y \in M$$
in your case since the zero (of $\mathbb{R}^3$) isn't in M, M isn't a subspace of $\mathbb{R}^3$


text:
Q: How can I convert a date to format "dd/mm" in oracle? I have the query:
select date_open
from vw_jira_jiraissues@con_jira.cit
where issue_key = 'IBA-1642'

How can I convert a date to format "dd/mm" in oracle ?

A: select to_char(date_open, 'dd/mm') from ...

A: I believe you want
TO_CHAR(date_open, 'DD/MM')

A: select to_char(date_open,'dd/mm') date_open from vw_jira_jiraissues@con_jira.cit where issue_key = 'IBA-1642'


text:
Q: Connecting to database through python I am connecting Oracle in python through subprocess Here I am trying to provide the input through console and get the output from db from table all_db_links I am getting no result in this code, not even a error. What could be wrong in it ? Thanks already :)
from subprocess import Popen, PIPE
value = raw_input()

def runSqlQuery (sqlCommand, connectString):
    session = Popen(['sqlplus', '-S', connectString],
    stdin = PIPE,
    stdout= PIPE,
    stderr = PIPE)

    session.stdin.write(sqlCommand)
    return session.communicate()

connectString = 'user/pwd@db' sqlCommand =""" SET HEADING OFF ( select * from all_db_links where OWNER ='?' , (value))"""
outcome = runSqlQuery (sqlCommand connectString) for i in outcome: print(i)


text:
Q: How to find if and when two volumetric 2d objects (balls) will collide I have a situation of two 2d objects (balls with radii of 5 each) moving along straight lines. I know their velocity, their acceleration, initial coordinates and direction.
Please note, I'm not 100% sure that it is possible to answer this at all. This is not a homework and not an exercise from a textbook. So if anyone thinks that there is no way to solve this, please let me know.
If they were dots, I would know how to find the answer: simply find their trajectories intersection, distances from their initial positions to the point of the intersection and solve the equation with a time variable:
$$
V_{i1} * t + \frac{1}{2} a_1 t^2 = V_{i2} * t + \frac{1}{2} a_2 t^2
$$
That would answer the question if and when would the objects collide.
But since I have balls this approach doesn't help. They can collide much sooner then the intersection of their centers would occur.
The only thing I was able to come up with is to find an inequality of distance between the balls' centers and try to find when the distance will become less than two times a ball's radius:
$$
\sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2} <= 10 \\
\sqrt{(x_2 - x_1)^2 + (kx_2 + b_2 - kx_1 - b_1)^2} <= 10
$$
Trying to solve the equation
$$
\sqrt{(x_2 - x_1)^2 + (kx_2 + b_2 - kx_1 - b_1)^2} = 10\\
(x_2 - x_1)^2 + (kx_2 + b_2 - kx_1 - b_1)^2 = 100
$$
to find values of $x_1$ and $x_2$ is hopeless, since there are two variables $x_1$ and $x_2$ and only one equation.
So I have no idea, where should I proceed now. Could anyone either tell me how to solve this exactly or at least suggest in what direction should I proceed?
Thank you.

A: If you know the balls' velocities and acceleration, then your only variable is really time:
$$ x= x_{initial} + vt + \frac{1}{2} a t^2$$
Substitute this for $x_1$ and $x_2$, and you can theoretically solve for the time of collision. Albeit the algebra could get messy...