text:
Q: ios6 facebook integration login always FBSessionStateClosedLoginFailed never opens this question is very similar to Facebook SDK for iOS , on iOS 4.0 device, but as I cannot make comments there, I open a new question. I think the questions are not the same:
When trying to update the facebook integration of my app to facebook 3.1 I am not getting the facebook session to open the sessionStateChanged Callback always ends up in FBSessionStateClosedLoginFailed. in my setup I have the callback in my appdelegate
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    // attempt to extract a token from the url
    //    return [self.session handleOpenURL:url];
    return [FBSession.activeSession handleOpenURL:url];
}

but it is never called! shouldn't it get called? I followed the facebook documentation and call
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
    NSArray *permissions = [NSArray arrayWithObjects:@"publish_actions", nil];
    return [FBSession openActiveSessionWithPublishPermissions:permissions
                                              defaultAudience:FBSessionDefaultAudienceFriends
                                              allowLoginUI:allowLoginUI
                                         completionHandler:^(FBSession *session,
                                                             FBSessionState state,
                                                             NSError *error) {
                                             [self sessionStateChanged:session
                                                                 state:state
                                                                 error:error];
                                         }];
}

I also tried
openActiveSessionWithReadPermissions with nil for the permissions as in the facebook tutorial example with the intention to reauthorize for the publish_actions permission later. same result: FBSessionStateClosedLoginFailed again.
I even tried calling
ACAccountStore *accountStore;
    ACAccountType *accountTypeFB;
    if ((accountStore = [[ACAccountStore alloc] init]) &&
        (accountTypeFB = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook] ) ){

        NSArray *fbAccounts = [accountStore accountsWithAccountType:accountTypeFB];
        id account;
        if (fbAccounts && [fbAccounts count] > 0 &&
            (account = [fbAccounts objectAtIndex:0])){

            [accountStore renewCredentialsForAccount:account completion:^(ACAccountCredentialRenewResult renewResult, NSError *error) {
                //we don't actually need to inspect renewResult or error.
                if (error){

                }
            }];
        }
    }

before trying to open the session, but I never get it open on my ios6 device (iphone 4s). in the app I am asked for the permission, but then nothing goes on because the session is always having the state FBSessionStateClosedLoginFailed! my callback for the session state is
- (void)sessionStateChanged:(FBSession *)session
                      state:(FBSessionState) state
                      error:(NSError *)error
{
    switch (state) {
        case FBSessionStateOpen:
            if (!error) {
                // We have a valid session
                NSLog(@"User session found");
            }
            break;
        case FBSessionStateClosed:
            NSLog(@"FBSessionStateClosed");
        case FBSessionStateClosedLoginFailed:
            NSLog(@"FBSessionStateClosedLoginFailed");
            [FBSession.activeSession closeAndClearTokenInformation];
            break;
        default:
            break;
    }

    [[NSNotificationCenter defaultCenter]
     postNotificationName:FBSessionStateChangedNotification
     object:session];

    if (error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"facebook Hinweis"
                                                        message:@"facebook Login nicht möglich, bitte versuchen Sie es erneut."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        NSLog(@"Facebook session error: %@", error.localizedDescription);
    }
}

with the facebook 3.0 on ios 5 I never had an issue so my facebook app is set up correctly. I would really appreciate any help wchich enables me to just open the facebook session, did not think to run into these problems with facebook 3.1 and the docs are not helping me at this point, thx

A: I had the same problem, and it was because I forgot to implement
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [FBSession.activeSession handleOpenURL:url];
}

in my AppDelegate

A: I had the same problem. If the user hadn't a Facebook account configured in the System Preferences the Facebook login dialog appeared and everything worked fine. But if the user had an account configured in the device I was always having a FBSessionStateClosedLoginFailed error.
It has nothing to do with handleOpenURL:url because in the "native login flow" for iOS 6 or greater there is no fast-app-change. So your app never goes to background and the URL redirection is not needed.
The problem was solved configuring the Facebook app. You need to enable the "Native iOS login" section and put the bundle ID of your app. If your app is not already in the Apple Store I'm afraid you need to set the sandbox mode to ON. Once your app is published in the Apple Store I think you need to put the sandbox mode to OFF and set the Apple Store ID in the Facebook configuration.

A: While JohnG's answer is correct, that particular delegate method has now been deprecated. The correct delegate method to use is this:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [FBSession.activeSession handleOpenURL:url];
}

Placing that in my application delegate solved the issue for me.  Without this, the iOS 6.0 native login would work but the Facebook app login would fail.

A: Even i can't comment so writing it as answer .
I am not sure , let me analyze potential reasons
1) you said: "but it is never called! shouldn't it get called?" -- for
- (BOOL)application:(UIApplication *)application
        openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication
     annotation:(id)annotation

to get called , in the info.plist file , url scheme should be set properly i.e go to URL types-->Item0-->URL Schemes--->Item 0 the value here should be fbAPPID i.e fb append with your actual facebookappID [FacebookAppID could also be present in the info.plist or hard coded in code].
2)You said:
"sessionStateChanged Callback always ends up in FBSessionStateClosedLoginFailed"
In the sessionStateChanged switch method check the state of session and if it  created or createdTokenLoaded then try to open the session.
Note:[FBSession openActiveSessionWithPublishPermissions ....] which is a static method will create a new session and is set to FBSession.activeSession  where as openWithCompletionHandler is an instance method which can work only if the session is already created .
    case FBSessionStateCreated:
    case FBSessionStateCreatedTokenLoaded:{
        [session openWithCompletionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
            //handle the updating of views according to the sate of session
        }];
        break;

A: I agree with JohnG, with the additional caveat of:
Note that if you have multiple cases inside of handleOpenURL:, you can filter for:
if ([sourceApplication isEqualToString:@"com.facebook.facebook"] ||
    [sourceApplication isEqualToString:@"com.facebook.Facebook"]){
  //Do Stuff
}

It's weird, but I was able to replicate on multiple devices the sourceApplication coming back as "Facebook" and "facebook".

A: On FB SDK 3.5, You can kill the token with this:
    [[FBSessionTokenCachingStrategy defaultInstance] clearToken];


text:
Q: Docker: mount image's original /docker-entrypoint.sh to a volume in read/write mode I try to mount image's original /docker-entrypoint.sh to a volume in read/write mode, in order to be able to change it easily from outside (without entering the container) and then restart the container to observe the changes.
I do it (in ansible) like this:
/app/docker-entrypoint.sh:/docker-entrypoint.sh:rw
If /app/docker-entrypoint.sh doesn't exist on the host, a directory /app/docker-entrypoint.sh (not a file, as wish) is created, and I get following error:
Error starting container e40a90eef1525f554e6078e20b3ab5d1c4b27ad2a7d73aa3bf4f7c6aa337be4f: 400 Client Error: Bad Request (\"OCI runtime create failed: container_linux.go:348: starting container process caused \"process_linux.go:402: container init caused \\\"rootfs_linux.go:58: mounting \\\\\\\"/app/docker-entrypoint.sh\\\\\\\" to rootfs \\\\\\\"/var/lib/docker/devicemapper/mnt/4d3e4f4082ca621ab5f3a4ec3f810b967634b1703fd71ec00b4860c59494659a/rootfs\\\\\\\" at \\\\\\\"/var/lib/docker/devicemapper/mnt/4d3e4f4082ca621ab5f3a4ec3f810b967634b1703fd71ec00b4860c59494659a/rootfs/docker-entrypoint.sh\\\\\\\" caused \\\\\\\"not a directory\\\\\\\"\\\"\": unknown: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type

If I touch /app/docker-entrypoint.sh (and set proper permissions) before launching the container - the container fails to start up and keeps restarting (I assume because the /app/docker-entrypoint.sh and therefore internal /docker-entrypoint.sh are empty).
How can I mount the original content of container's /docker-entrypoint.sh to the outside?

A: If you want to override docker-entry point it should be executable or in other words you have to set chmod +x your_mount_entrypoint.sh in the host then you can mount otherwise it will through permission error. As entrypoint script should be executable.
Second thing, As mentioned in the comment you can mount the file better to keep the entrypoint script in directory like docker-entrypoint/entrypoint.sh.
or if you want to mount specific file then both name should be same otherwise entrypoint script will not be overridden.
docker run --name test -v $PWD/entrypoint.sh:/docker-entrypoint/entrypoint.sh --rm my_image

or
docker run --name test -v $PWD/entrypoint.sh:/docker-entrypoint/entrypoint.sh:rw --rm my_image

See this example, entrypoint generated inside dockerfile and you can overide this from any script but it should be executable and should be mount to docker-entrypoint.
Dockerfile
FROM alpine
RUN mkdir -p /docker-entrypoint
RUN echo -e $'#!/bin/sh \n\
echo "hello from docker generated entrypoint" >> /test.txt \n\
tail -f /test.txt ' >> /docker-entrypoint/entrypoint.sh
RUN chmod +x /docker-entrypoint/entrypoint.sh
ENTRYPOINT ["/docker-entrypoint/entrypoint.sh"]

if you build and run it you will
docker build -t my_image .
docker run -t --rm my_image
#output
hello from docker generated entrypoint

Now if you want to overide
Create and set permission
host_path/entrypoint/entrypoint.sh
for example entrypoint.sh
#!/bin/sh
echo "hello from entrypoint using mounted"

Now run
docker run --name test -v $PWD/:/docker-entrypoint/ --rm  my_image
#output
hello from entrypoint using mounted

Update:
If you mount directory of the host it will hide the content of docker image.
The workaround

*

*Mount some directory other then entrypoint name it backup

*add instruction in entrypoint to copy entrypoint to that location at run time

*So it will create new file on the host directory instead

FROM alpine
RUN mkdir -p /docker-entrypoint
RUN touch /docker-entrypoint/entrypoint.sh
RUN echo -e $'#!/bin/sh \n\
echo "hello from entrypoint" \n\
cp /docker-entrypoint/entrypoint.sh /for_hostsystem/ ' >> /docker-entrypoint/entrypoint.sh
RUN chmod +x /docker-entrypoint/entrypoint.sh
ENTRYPOINT ["/docker-entrypoint/entrypoint.sh"]

Now if you run you will have the docker entrypoint in the host, as opposit as you want
docker run --name test -v $PWD/:/for_hostsystem/ --rm my_image

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the point of custom fields on external objects? If they are not mapped to the schema what's the point of creating custom fields on external objects? I have tested with a checkbox field and verified that my changes are not being preserved, as expected.

A: Refer Define External Objects documentation, where it specifies the need of creating custom fields.

If the external system allows it, we recommend that you sync the external data source to automatically create related external objects. You can instead choose to manually define external objects to customize the external object names and manually create the custom fields.

Also, think about creation of indirect lookup. Refer: Large Data Volume - Design your data model trailhead.

When you create an indirect lookup relationship field on an external object, you specify the parent object field and the child object field to match against each other, selecting a custom unique external ID field on the parent object to match against the child's indirect lookup relationship field, whose values are determined by the specified External Column Name.


text:
Q: How to assign a statement to a variable in Delphi? How could this following C code be done in Delphi? I tried to translate, but it seems that Delphi does not allowed this syntax. Basically, I need to assign a function to a variable like in the C code. How could this be done on Delphi?
Here is the C code of reference:
void EnumWindowsTopToDown(HWND owner, WNDENUMPROC proc, LPARAM param)
{
    HWND currentWindow = GetTopWindow(owner);
    if (currentWindow == NULL)
        return;
    if ((currentWindow = GetWindow(currentWindow, GW_HWNDLAST)) == NULL)
        return;
    while (proc(currentWindow, param) && (currentWindow = GetWindow(currentWindow, GW_HWNDPREV)) != NULL);
}

And here is my attempt:
type
  TFNWndEnumProc = function(_hwnd: HWND; _lParam: LPARAM): BOOL; stdcall;

    procedure EnumWindowsTopToDown(Owner: HWND; Proc: TFNWndEnumProc;
      _Param: LPARAM);
    var
      CurrentWindow: HWND;
    begin
      CurrentWindow := GetTopWindow(Owner);
      if CurrentWindow = 0 then
        Exit;

      CurrentWindow := GetWindow(CurrentWindow, GW_HWNDLAST);
      if CurrentWindow = 0 then
        Exit;

      while Proc(CurrentWindow, _Param) and (CurrentWindow :=  GetWindow(CurrentWindow, GW_HWNDPREV)) <> 0;
    end;

A: Delphi can't assign a variable inside of a while or if statement, like C/C++ can.  You need to break up the while statement, just like you had to break up the if statement on the call to GetWindow(GW_HWNDLAST), eg:
type
  TFNWndEnumProc = function(_hwnd: HWND; _lParam: LPARAM): BOOL; stdcall;

procedure EnumWindowsTopToDown(Owner: HWND; Proc: TFNWndEnumProc; Param: LPARAM);
var
  CurrentWindow: HWND;
begin
  CurrentWindow := GetTopWindow(Owner);
  if CurrentWindow = 0 then
    Exit;

  CurrentWindow := GetWindow(CurrentWindow, GW_HWNDLAST);
  if CurrentWindow = 0 then
    Exit;

  while Proc(CurrentWindow, Param) do
  begin
    CurrentWindow := GetWindow(CurrentWindow, GW_HWNDPREV);
    if CurrentWindow = 0 then Exit;
  end;
end;

A: In C and C++, an assignment is an expression, with as result the value that is assigned. That is why you can take the value of an assignment:
while ((a = getNextValue()) != 13)
{
   // code of loop
}

In Pascal and Delphi, an assighment is merely a statement, not something that returns a value. So you will first have to perform the assignment and query the variable to which the assignment was done in the next step:
a := getNextValue;
while (a <> 13) do
begin
  // code of loop;
  a := getNextValue;
end;

Remy's code is fine, but it can be simplified a little. I had already converted the code too, and came up with:
type
  WNDENUMPROC = function(hwnd: HWND; lParam: LPARAM): BOOL stdcall;

procedure EnumWindowsTopToDown(owner: HWND; proc: WNDENUMPROC; param: LPARAM);
var
  currentWindow: HWND;
begin
  currentWindow := GetTopWindow(owner);
  if currentWindow = 0 then
    Exit;
  currentWindow := GetWindow(currentWindow, GW_HWNDLAST);
  while (currentWindow <> 0) and proc(currentWindow, param) do
    currentWindow := GetWindow(currentWindow, GW_HWNDPREV);
end;


text:
Q: Question on Use of Y2 Saftey Capacitor in AA5 Style Tube Radio In a radio I am restoring, there is a 0.1 uF capacitor between B- and chassis, designated as C12. My thought process is that if this capacitor were to fail, I would not want B- shorted to chassis as this could create a significant shock factor due to the high B- voltage. My understanding is that a Y2 capacitor would fail open circuit if it failed. In this instance, while the radio would no longer work, B- would not be present on the chassis as a shock hazard.
There is an across the line capacitor elsewhere in the circuit, designated as C11, which I know needs to be an X2 safety capacitor.
My question is, does the C12 capacitor need to be a Y2 safety capacitor or can it be a regular capacitor?

A: Not only does it need to be a Y cap...
You are indeed bang-on that this needs to be a Y rated capacitor in order to provide the fail-safe and surge-withstanding properties needed in a line-to-chassis application such as yours.
it needs to shrink, too!
However, the IEC/UL/EN/... safety standards for equipment strictly limit the allowable leakage currents to exposed parts and to the mains earth, both to avoid shock hazards and to keep earth-leakage devices (ELCB, GFCI, RCD/RCBO/RCCB) from tripping when you plug your device in.  Assuming a 120V RMS, 60Hz mains input to your device, that 100nF capacitor would leak 4.5mA from the mains to the chassis in the worst case, which violates the 3.5mA limit set by the relevant safety standards for grounded-chassis equipment, and could cause nuisance trips of UL943 Class A personnel protection GFCIs under conditions where other leakage sources were present.
As a result, I would reduce the value of the capacitor in order to bring the equipment into some semblance of safety compliance.  Given the nature of the device (tube radio -- presumably of the "All American Five" design with a "floating" albeit not isolated chassis based on the schematic snippet shown), converting to a grounded chassis would be the safest route, allowing us to use the 3.5mA limit mentioned above (a true double insulated device is limited to half a milliamp leakage to exposed metal of any sort), and with that, that sets our Y capacitor in the 10-22nF range, total.  Such a capacitor is available through major electronics parts distributors (such as DigiKey, Mouser, Farnell/Newark, and RS-Electronics/Allied -- this is NOT the time for a Cheese-pipeline special from eBay or Amazon Marketplace), and should not pose a major cost obstacle ($1 in onesies through DigiKey for a 22nF, 300VAC, Y2-rated polypropylene film capacitor from Epcos/TDK, at the time of this writing.
While we're in there...
Two other things need to be done to the typical All American Five radio to make it meet even a semblance of modern safety standards.  First off, the existing cord needs to be removed completely and replaced with a grounding-type (3 prong) cord with strain relief.  Neutral goes directly to the B- bus, live lands on one terminal of the power switch, and ground is connected to the chassis using a ring terminal, screw, and star washer.  Second, to complete this, the wire that used to go to the hot side of the cord needs to go to the other power switch terminal.  This moves the power switch into the hot side, further reducing the shock hazard posed by this antique.

A: Your thinking is correct.  If safety of shock is at risk then it must be Y type which are bigger, more expensive and guaranteed to fail open.
X1 (impulse tested to 4000 Volts),
X2 (tested to 2500 V),
Y1 (tested to 8000 V) and
Y2 (tested to 5000 V )
Since was in the days of 2pronged outlets , change schematic to show Line & Neutral for America and use earth ground only for noise suppression if required 1nF max.


text:
Q: Exposed service on undefined port with Docker Desktop My environment: Windows 10 + WSL2 + Docker Desktop (k8s v1.19.7)
I have created a small sample application. It returns 'it works' on [ip:80]/Converter
I have packaged the app in a container. And when I run it like this:
docker run -d -p 80:80 [imagename]

It returns 'it works' on [ip:80]/Converter
Then I defined a deployment.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: escape
  namespace: default
spec:
  replicas: 3
  selector:
    matchLabels:
      bb: escape
  template:
    metadata:
      labels:
        bb: escape
    spec:
      containers:
      - name: escape
        image: [imagename]
        ports:
          - containerPort: 80
            protocol: TCP

This gives me 3 pods with my container running.
Then I create a service for my deployment:
kubectl expose deployment escape --type=LoadBalancer --name=escape-service

listing the services: kubectl get services
escape-service   LoadBalancer   10.105.198.65   localhost     80:32496/TCP   17m
kubernetes       ClusterIP      10.96.0.1       <none>        443/TCP        25m

This exposes the service but I cannot reach it on: http://localhost:32496/converter
So how do I reach my service outside my Kubernetes cluster?
What have I tried:
Googling led me to: Docker Desktop + k8s plus https proxy multiple external ports to pods on http in deployment?
But as that is running on Hyper-V it different I guess
I installed Lens (https://k8slens.dev/)
This gives an overview of the services:
screenshot
Clicking on the 80:32496/TCP link open browser to http://localhost:59394
When I manually postfix this to
http://localhost:59394/Converter

I get the "It works" response.
How does the converting of ports work on Docker Desktop for Windows + WSL2? And how can I find the port 59394 without resorting to Lens?
Also when I try to list ingress it seems I don't have any  kubectl describe ingress

Warning: extensions/v1beta1 Ingress is deprecated in v1.14+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress
No resources found in default namespace.

A: So the trick is that Lens will automatically create a tunnel for you when click on the service.
To properly expose a service specify the nodePort on the service definition.
ports:
  - nodePort: 30080
    protocol: TCP
    port: 80
    targetPort: 8080

This will expose the service on all nodes. This will not work on Docker for desktop or minikube, but it works fine if you set up a real cluster.


text:
Q: How to get min value from array in F#? This is F# code as close as I can write to find the min value of an array:
let temp = 0
let getArrayMinValue (a : Array) =
    if a.Length > 0 then (
                            for i = 0 to a.Length do
                               let temp =  ( if temp > a.[i] then a.[i] else temp )  in ()
                        )

I have two questions:
First, a.[i] has compiling error: The field, constructor or member 'Item' is not defined.
Second, the in () is requried, otherwise, there is compiling error "Block following this let is unfinished. Expect an expression". I do not quite understand this part.
Thanks in advance for your help.

A: Can't you use Array.min to find the minimum element, something like below:
let numbers =[|1..10|]

printfn "%A"  (numbers |> Array.min)

Coming to you program, you have to use something like:
let getArrayMinValue (a : int[]) =

and not a: Array You can even do a: 'T[] but since you are comparig the value of the elements against temp it will probably constraint it to int.
Coming to the other error, make temp mutable: let mutable temp = 0 and assign value using <- operator. Here is your whole code:
let mutable temp = 0

let getArrayMinValue (a : 'T[]) =
   if a.Length > 0 then (
                        for i = 0 to a.Length do
                           temp <-  ( if temp > a.[i] then a.[i] else temp )
                        )


text:
Q: Get a specific row data in CSV using Node.JS Given a specific row number, is there a way to get the data of that row in a CSV file, so that I can manipulate that data?
I want it to do in this way such that I can keep track of which rows I have got and manipulated.
Every CSV module actually reads the whole file and parse the data but I just need a reference rather than loading whole file as file gets changed.
How could I do that?
This is my Node.JS code:
var csv = require('csv');
var fs = require('fs');
var str = csv().from.stream(fs.createReadStream('test.csv'))
str.transform( function(row){
  row.unshift(row.pop());
  return row;
})
.on('record', function(row,index){
  console.log('#'+index+' '+JSON.stringify(row));
});

A: Might be what you need: https://www.npmjs.com/package/get-line
Get the first line for the headers of the csv (if there is any), get the line you want, concat both lines separated by \n and use your usual csv-parser to parse it and get a nice object back.


text:
Q: ESP32 panics every other HTTP POST request As the title suggests, my ESP32 panics every other HTTP POST request. For the first one it works fine, wuth the second one I get a 400 error, the ESP panics, and then restarts itself.
This wouldn't be this much of an issue if the ESP didn't power any other things, however, it does. The result is that the sensors it powers don't work properly and give wrong data. Below I have included the error code:
Verbonden met WiFi, met Ip adres: myip
Distance: 35 cm
Temperatuur: 19.70
Luchtvochtigheid: 74.00
Grondvochtigheid: 4095
Lichsterkte sensor 1: 432.00
Lichsterkte sensor 2: 288.00
Lichsterkte sensor 3: 0.00
HTTP Response code: 200
Test: {"Log":{}}
Distance: 35 cm
Temperatuur: 19.70
Luchtvochtigheid: 74.00
Grondvochtigheid: 4095
Lichsterkte sensor 1: 480.00
Lichsterkte sensor 2: 290.00
Lichsterkte sensor 3: 0.00
HTTP Response code: 400
Test: "Missing values"
Guru Meditation Error: Core  1 panic'ed (InstrFetchProhibited). Exception was unhandled.
Core 1 register dump:
PC      : 0xc000e82e  PS      : 0x00060430  A0      : 0x800d3002  A1      : 0x3ffb1d90
A2      : 0x3ffb1f10  A3      : 0xc000e82e  A4      : 0x00000001  A5      : 0x0000ff00
A6      : 0x00ff0000  A7      : 0xff000000  A8      : 0x8015dd02  A9      : 0x3ffc11dc
A10     : 0x3ffba818  A11     : 0x3f401763  A12     : 0x00000002  A13     : 0x0000ff00
A14     : 0x00ff0000  A15     : 0xff000000  SAR     : 0x0000000a  EXCCAUSE: 0x00000014
EXCVADDR: 0xc000e82c  LBEG    : 0x400014fd  LEND    : 0x4000150d  LCOUNT  : 0xffffffff

Backtrace: 0x4000e82e:0x3ffb1d90 0x400d2fff:0x3ffb1db0 0x400d3071:0x3ffb1dd0 0x400d1c4e:0x3ffb1df0
0x400d6625:0x3ffb1fb0 0x40088f69:0x3ffb1fd0

Rebooting...
ets Jun  8 2016 00:22:57

My C++ code is as follows:
// Includen van alle benodigde libraries
#include <Arduino.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <DHT.h>

// Definen van alle datapins van alle componenten
#define DHTPIN 14
#define DHTTYPE DHT11
#define echoPin 26
#define grondPin 33
#define trigPin 27
#define lichtPin1 32
#define lichtPin2 35
#define lichtPin3 34
//#define redPin 2
//#define greenPin 4

// magic number handlers
const int procentHulpwaarde = -1;
const int nulWaarde = 0;
const int potDiepte = 31;
const int grensWaardepostUpdate = 10;
const int procentRekenwaarde = 100;
const int sensorRekenwaarde = 4095;
const int timerDelaywaarde = 1000;

// Declaratie variabeles
String strluchtvochtigheid;
String strtemperatuur;
String strgrondvochtigheid;
String strlichtsterkte1;
String strlichtsterkte2;
String strlichtsterkte3;
String strwaterniveau;

double dblluchtvochtigheid = nulWaarde;
double dbltemperatuur = nulWaarde;
double lichtSterkte1;
double lichtSterkte2;
double lichtSterkte3;

int distance;
int sensorValueGrond;
int postCounter;

long duration;
unsigned long lastTime = nulWaarde;
unsigned long timerDelay = timerDelaywaarde;

// Aanroepen van benodigdheden voor miscellaneous functies binnen de code
DHT dht(DHTPIN, DHTTYPE);
StaticJsonDocument<200> doc;

// Declaratie van WiFi netwerken die gebruikt kunnen worden

//const char* ssid = "12connect";
//const char* password = "";

// Declaratie van de eindbestemming
const char* serverName = "my target";

void setup() {
  Serial.begin(115200);

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  //pinMode(redPin, OUTPUT);
  //pinMode(greenPin, OUTPUT);

  dht.begin();

  WiFi.begin(ssid, password);
  Serial.println("Connecting");

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Verbonden met WiFi, met Ip adres: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  // Ultrasonic sensor
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  // Natuurkundige berekening voor de hoeveelheid water in het reservoir
  distance = duration * 0.034 / 2;

  if ((millis() - lastTime) > timerDelay) {

    if (WiFi.status()== WL_CONNECTED) {

      //Lees alle sensoren uit

      // DHT sensor
      dblluchtvochtigheid = dht.readHumidity();
      dbltemperatuur = dht.readTemperature();

      // Grondvochtigheids sensor
      sensorValueGrond = analogRead(grondPin);

      // Ultrasonic sensor
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      // Natuurkundige berekening voor de afstand
      distance = duration * 0.034 / 2;

      // Lichtsterkte sensoren
      lichtSterkte1 = analogRead(lichtPin1);
      lichtSterkte2 = analogRead(lichtPin2);
      lichtSterkte3 = analogRead(lichtPin3);

      // Print alle waardes uit (voor debugging)
      Serial.print("Distance: ");
      Serial.print(distance);
      Serial.println(" cm");
      Serial.print("Temperatuur: ");
      Serial.println(dbltemperatuur);
      Serial.print("Luchtvochtigheid: ");
      Serial.println(dblluchtvochtigheid);
      Serial.print("Grondvochtigheid: ");
      Serial.println(sensorValueGrond);
      Serial.print("Lichtsterkte sensor 1: ");
      Serial.println(lichtSterkte1);
      Serial.print("Lichtsterkte sensor 2: ");
      Serial.println(lichtSterkte2);
      Serial.print("Lichtsterkte sensor 3: ");
      Serial.println(lichtSterkte3);

      HTTPClient http;
      http.begin(serverName);

      //procentuele omrekening van alle getallen
      sensorValueGrond = ((((sensorValueGrond  - sensorRekenwaarde) *
  procentHulpwaarde) * procentRekenwaarde) / sensorRekenwaarde);
      distance = ((distance * procentRekenwaarde) / potDiepte) -
  procentRekenwaarde;
      lichtSterkte1 = (lichtSterkte1 * procentRekenwaarde) / sensorRekenwaarde;
      lichtSterkte2 = (lichtSterkte2 * procentRekenwaarde) / sensorRekenwaarde;
      lichtSterkte3 = (lichtSterkte3 * procentRekenwaarde) / sensorRekenwaarde;

      // Omzetten van alle getallen naar strings, zo kunnen ze worden meegegeven in de JSON string
      strtemperatuur = strtemperatuur + dbltemperatuur;
      strluchtvochtigheid = strluchtvochtigheid + dblluchtvochtigheid;
      strwaterniveau = strwaterniveau + distance;
  strgrondvochtigheid = sensorValueGrond + strgrondvochtigheid;
      strlichtsterkte1 = strlichtsterkte1 + lichtSterkte1;
      strlichtsterkte2 = strlichtsterkte2 + lichtSterkte2;
      strlichtsterkte3 = strlichtsterkte3 + lichtSterkte3;

      // Toevoegen van headers aan de HTTP Post, zo kunnen we gebruik maken van gebruikersnamen en wachtwoorden
      http.addHeader("Content-Type", "application/json");
      http.addHeader("X-AUTH-TOKEN", "TEST");
      http.addHeader("X-AUTH-ID", "wajdhlawkjhdlawjkdhawkjdh");
      http.addHeader("Temperatuur", strtemperatuur);
      http.addHeader("Luchtvochtigheid", strluchtvochtigheid);
      http.addHeader("Grondvochtigheid", strgrondvochtigheid);
      http.addHeader("Waterniveau", strwaterniveau);
      http.addHeader("Lichtsterkte1", strlichtsterkte1);
      http.addHeader("Lichtsterkte2", strlichtsterkte2);
      http.addHeader("Lichststerkte3", strlichtsterkte3);

      // HTTP Post
      int httpResponseCode = http.POST("{\"Temperatuur\" : "+strtemperatuur+" ,
  \"Luchtvochtigheid\" : "+strluchtvochtigheid+" , \"Grondvochtigheid\" :
  "+strgrondvochtigheid+" , \"Waterniveau\" : "+strwaterniveau+" ,
  \"Lichtsterkte1\" : "+strlichtsterkte1+" , \"Lichtsterkte2\" :
  "+strlichtsterkte2+" , \"Lichtsterkte3\" : "+strlichtsterkte3+"}");
      String response = http.getString();
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
      Serial.print("Test: ");
      Serial.println(response);

      // Schoon alles op

      strtemperatuur = "";
      strluchtvochtigheid = "";
      strgrondvochtigheid = "";
      strlichtsterkte1 = "";
      strwaterniveau = "";
      strlichtsterkte1  = "";
      postCounter = nulWaarde;
      http.end();
    } else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
    }
  }
}

Does anyone know how to solve this?

A: Try declaring HTTPClient http globally just once, and take it out of the loop(). Recreating it over and over again could be messing with your heap which may already be Swiss cheese anyway because you use the String class so much.
Speaking of which: it would be better to compose most of your Strings only once, and not every time in the loop, where you could just add the measurements to prefabricated Strings.
Sterkte!


text:
Q: How to convert this linq from query syntax to method syntax I was able to get this to work like I wanted it to, but I prefer the method syntax to the query syntax.
How can this be written with method syntax?
var data = (from stat in this._applicationDbContext.Stats
            where stat.SupId == this.GetCurrentSupId() && stat.StatType == 1
            orderby stat.WeekEnding descending
            group stat by stat.WeekEnding into statGroup
            select new WeeklyStat
                       {
                           WeekEnding = statGroup.First().WeekEnding,
                           Amount = statGroup.Sum(a => a.StatValue)
                       }).Take(6);

This is the original SQL:
SELECT TOP (6)
    SUM([stat_value]) AS lessons_graded,
    CONVERT(DATE, [weekend]) weekending
FROM
    [dbo].[Stats]
WHERE
    stat_type = 1 AND sup_id = 1113
GROUP BY
    CONVERT(DATE, [weekend])
ORDER BY
    CONVERT(DATE, [weekend]) DESC

A: This exercise is very mechanical for queries that have no joins.
The basic rule is to extract stat variable from the from stat clause, and stick it into each separate clause, like this:
var data = this._applicationDbContext.Stats
    .Where(stat => stat.SupId == this.GetCurrentSupId() && stat.StatType == 1)
    .OrderByDescending(stat => stat.WeekEnding)
    .GroupBy(stat => stat.WeekEnding)
    .Select(statGroup => new WeeklyStat {
        WeekEnding = statGroup.First().WeekEnding,
        Amount = statGroup.Sum(a => a.StatValue)
    }).Take(6);

The same thing happens after GroupBy - now you start using statGroup for your lambda's parameter.
Note that this is only one possible naming scheme. Since parameter names in lambdas are local to the lambda, you can use different variable names inside Where, OrderBy, and GroupBy:
.Where(x => x.SupId == this.GetCurrentSupId() && x.StatType == 1)
.OrderByDescending(y => y.WeekEnding)
.GroupBy(z => z.WeekEnding)

Obviously, using a consistent naming scheme greatly improves readability.


text:
Q: Arrange .xhtml files in separate folder in war - JSF2 I am using Primefaces and JSF2 . All my .xhtml files are dumped in the war folder. Is it possible to arrange them in separate folder? When I tried, .xhtml didn't get loaded.Please help.

A: check your web.xml file.
make sure the Faces Servlet's url-pattern points to the new folder's path.
Or simply change the url-pattern to *.xhtml.

A: if you change the location of XHTML you also need to change the code that is associated with its path
For example : returning viewId
return "viewPerson"


text:
Q: Q&A Power BI, No direct way to plot multilayer map I am trying to plot a multilayer map in PowerBI using natural language processing.
Let's say I write something like show total sales by state, district, postal code by map to show sales at the state level first then when I click on state drill down it to the district and so on.
Is there any way to get this working?

A: Sorry, I don't quite understand what you mean by plotting a multi-layer map using natural language processing. Do you mean that you would like to use the "Ask a Question" button in Power BI and you hope to get a map in return?
You could just create a map using your requirements. The best one to use would be the ArcGIS map.

A: Currently there is no (built-in) way to drill down from a state level to a postal code level in Power BI.
You can however, display either a Us or State map with a Postal-Code level of granularity. Check out this thread:
https://community.powerbi.com/t5/Desktop/Choropleth-using-3-digit-US-zip-code/td-p/74982

A: Thanks for your responses I already have these charts created in power bi from visuals directly but I am interested in creating drillable charts using ask your question query.


text:
Q: Remove accents from string in LINQ loop - Ucommerce products I have to search for a key (product) from ucommerce products.
Here is the code -
string whatToSearch = "L'oreal";

var normalizedText = whatToSearch.Normalize(NormalizationForm.FormD);

whatToSearch = nonSpacingMarkRegex.Replace(normalizedText, string.Empty);

whatToSearch = Regex.Replace(whatToSearch, @"[^0-9a-zA-Z ]+", "");

var products = new List<UCommerce.EntitiesV2.Product>();

if (!string.IsNullOrWhiteSpace(whatToSearch))
{
    products = UCommerce.EntitiesV2.Product.Find(p =>
            p.VariantSku == null && p.DisplayOnSite &&
            (
                p.Sku.Contains(whatToSearch)
                || p.Name.RemoveDiacritics().Contains(whatToSearch)
                || p.ProductDescriptions.Any(
                    d => d.DisplayName.Contains(whatToSearch)
                         || d.ShortDescription.Contains(whatToSearch)
                         || d.LongDescription.Contains(whatToSearch)
                )
            )
    );
}

 var productIds = products.Select(x => x.Id).ToList();

And this is the extension method I am using inside the loop.
public static string RemoveDiacritics(this string s)
{
    var normalizedString = s.Normalize(NormalizationForm.FormD);
    var stringBuilder = new StringBuilder();

    foreach (var c in normalizedString)
    {
        if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
            stringBuilder.Append(c);
    }

    return stringBuilder.ToString();
}

I am getting this exception System.String RemoveDiacritics(System.String)
Can anyone help.
Thanks

A: Not clear from your question, but most probable cause is this line:
|| p.Name.RemoveDiacritics().Contains(whatToSearch)

I think this code is contacting to the database to fetch products based on the query and translator cannot find SQL analogue to RemoveDiacritics() functions.
EDIT:- Sure this will be a lot slower if it works, but lets try anyway:
if (!string.IsNullOrWhiteSpace(whatToSearch))
{
    //I've added call to ALL to fetch all products and then filter on
    //code side.
    products = UCommerce.EntitiesV2.Product.All().Where(p =>
            p.VariantSku == null && p.DisplayOnSite &&
            (
                p.Sku.Contains(whatToSearch)
                || p.Name.RemoveDiacritics().Contains(whatToSearch)
                || p.ProductDescriptions.Any(
                    d => d.DisplayName.Contains(whatToSearch)
                         || d.ShortDescription.Contains(whatToSearch)
                         || d.LongDescription.Contains(whatToSearch)
                )
            )
    );
}


text:
Q: Trying to plot a parametric curve Trying to plot the curve $x=t, y=\sqrt(1-t^2)$ on [-1,1],
\documentclass[tikz, border=2mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.4}

\begin{document}

\begin{figure}[h]
 \begin{tikzpicture}
        \begin{axis}
        [xlabel=$x$,ylabel=$y$,axis lines=middle,xtick={2},ytick={2},
no marks,axis equal,xmin=-1.4,xmax=1.2,ymax=1.2,ymin=-0.2,enlargelimits={upper=0.1}]
          \addplot[no markers,samples=100, domain=-1:1,variable=t]({t},{sqrt(1-(t)^2)});
        \end{axis}
 \end{tikzpicture}
\end{figure}

\end{document}

I get a PGF Math error: Sorry, an internal routine of the floating point...
Where do I wrong ?
Later Edit: I've written the full code, according to @Cragfelt 's comment.

A: \documentclass{article}

\usepackage{tikz,pgfplots}
\pgfplotsset{compat=1.15}
\begin{document}
\begin{tikzpicture}
        \begin{axis}
        [xlabel=$x$,ylabel=$y$,axis lines=middle,xtick={2},ytick={2},
no marks,axis equal,xmin=-1.4,xmax=1.2,ymax=1.2,ymin=-0.2,enlargelimits={upper=0.1}]
           \addplot[no markers,samples=100,
           domain=-1:1,variable=t]({t},{pow(1-t^2,1/2)});
        \end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Java run multiple threads from for loop with different names I am trying to start a variable number of threads within a for loop and want to name the threads prime1, prime2, [...].
The PrimeFinderThread Class extends from Thread.
[...]

    for (int i = 0; i <= numberThreads; i++) {
         PrimeFinderThread ("prime" + i) = new PrimeFinderThread (lowerBoundary, interval);
    }

[...]

I am getting the error:

The left-hand side of an assignment must be a variable.

from ("prime" + i)
What is a possible soloution to start X Threads with a seperate name for each?

A: Try the following:
Thread[] threads = new PrimeFinderThread[numberThreads];
for (int i = 0; i < numberThreads; i++) {
    threads[i] = new PrimeFinderThread (lowerBoundary, interval);
    threads[i].setName("prime" + i);
    threads[i].start();
}

It sets the name via the setName-method and then starts each thread via a call to start.
However, it is probably easier to make the constructor of PrimeFinderThread take an extra argument which is the name and invoke the super class constructor.
public PrimeFinderThread (String name, int lowerBoundary, int interval) {
    super(name); // instead of setName
    // Do the other stuff
}

IMO, an even better approach is to not extend the Thread class but rather provide a Runnable, preferably with some kind of ExecutorService - check e.g. the Executors JavaDoc or the concurrency trail from the Oracle website.

A: For an assignment in Java you cannot specify additional parameters on the left hand side of the = operator. So PrimeFinderThread ("prime" + i) is and will stay invalid.
Instead you should simply define an additional parameter for your constructor, and pass that to the parent class constructor using the super keyword construct.
You should assign the created threads to some variable
PrimeFinderThread[] threads = new PrimeFinderThread[numberThreads];
for (int i = 0; i < numberThreads; i++) {
    threads[i] = new PrimeFinderThread ("prime" + (i+1), lowerBoundary, interval);
    threads[i].start();
}

As for setting the name of each thread, that depends on what constructors your PrimeFinderThread class has. You can pass the thread name to the constructor of PrimeFinderThread, and from there, pass it to the constructor of Thread.
For example:
public PrimeFinderThread (String name, int lowerBoundary, int interval)
{
    super (name);
    ...
}

A: You cannot specify additional parameters with X in left side assignment in Java.
To give name to your threads you can call super(threadName) from the sub class of thread or thread.setName("threadName") can be used.
public class ThreadSubClass extends Thread{

    public ThreadSubClass(String threadName){
        super(threadName);
    }

    @Override
    public void run(){
        System.out.println("Entering : " + getName());
        //do Something
    }

    public static void main(String [] args){
        for(int i=0;i<5;i++){
            ThreadSubClass t = new ThreadSubClass("Prime"+i);
            t.start();
        }
    }

}


text:
Q: Show that $C(I)^n$ is a Banach space under the following norm Apologies if this question has been asked beforehand, the use of different norms in different (but similar) questions makes it really hard to filter out the relevant ones. Anyway:
Let $C(I)^n$ denote the set of functions $y:\mathbb{R} \rightarrow \mathbb{R}^n$ that are continuous in every coordinate in the open interval $I$ (which is what I take it to be, guessing from the lecture notes). Define the norm
$$||y|| := \max\limits_{i = \{1, \ldots, n\}} \max\limits_{x \in I} |y_i(x)|$$
on this space. To show this is a Banach space, we can rewrite the Cauchy condition as follows:
$$\forall \varepsilon > 0, k,l \geq N(\varepsilon): ||y^{k}-y^{l}|| < \varepsilon \iff \forall i \in \{1,\ldots,n\}, x \in I: |y^{(k)}_i(x)-y^{(l)}_i(x)| < \varepsilon$$
and because $\mathbb{R}$ is a complete space with respect to the norm $|\cdot|$, we know that the sequence $\{y^{(n)}_i(x)\}_{n \in \mathbb{N}}$ converges and we can define the limit functions $y_i$ for each $i \in \{1,\ldots,n\}$ and $y = (y_1,\ldots,y_n)^T$. My goal was to show that $\{y^{(n)}\}_{n \in \mathbb{N}}$ must necessarily converge to $y$ in $C(I)^n$ under this definition, but at the moment it is only pulling the knots in my brain even tighter.
Any help is appreciated!

A: Let me start from scratch. Let $I=[0,1]$. We have $C(I)^n:=C(I,\mathbb{R}^n)$, the continuous functions from $I$ to $\mathbb{R}^n$. Each continuous function $I\to\mathbb{R}^n$ can be identified with a $n$-tuple of functions $I\to\mathbb{R}$, namely the coordinate functions; i.e. if $f\in C(I,\mathbb{R}^n)$, then there exist unique continous functions $f_1,\dots,f_n\in C(I,\mathbb{R})$ such that $f(t)=(f_1(t),\dots,f_n(t))$ for all $t\in I$. Conversely, given any $n$-tuple of continous functions $f_1,\dots,f_n\in C(I,\mathbb{R}))$, the function defined by $f(t):=(f_1(t),\dots,f_n(t))$ is a function of $C(I,\mathbb{R}^n)$. We thus have an identification of $C(I,\mathbb{R}^n)$ with $C(I)\times\dots\times C(I)$ ($n$-times) as sets and this identification is easily seen to be linear, so this is an isomorphism of vector spaces.
The norm defined on on $C(I,\mathbb{R}^n)$ is given by $\|f\|=\max_{i=1,\dots,n}\|f_i\|_\infty$, where $f=(f_1,\dots,f_n)$ and for $g\in C(I)$, $\|g\|_\infty:=\max_{x\in I}|g(x)|$. So let's break the problem in 2 easier problems:

*

*Assuming that $(X_1,\|\cdot\|_1),\dots, (X_n,\|\cdot\|_n)$ are Banach spaces, consider their cartesian product $Y:=X_1\times \dots\times X_n$. This is trivially a vector space. Define the norm $\|(x_1,\dots,x_n)\|:=\max_{i=1,\dots,n}\|x_i\|_i$ for all $(x_1,\dots,x_n)\in Y$. Show that $(Y,\|\cdot\|)$ is also a Banach space (i.e. complete). I leave this as an exercise to you, I am pretty sure you can do it (do it for $n=2$ for simplicity, then induction proves it for a general $n$ as well)

*Prove that $(C(I),\|\cdot\|_\infty)$ is a Banach space, i.e. complete. But this is standard and well-covered fact, see for example the accepted answer on this post Space of bounded continuous functions is complete (and use the fact that continous functions over a compact set are automatically bounded to apply it to your case).
Combining (1) and (2), what you are trying to prove follows immediately.


text:
Q: How to delete ALL FILES in a specified directory on the app? Given a directory [[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"] how do I delete ALL FILES in this folder?
(assume a correct documents directory path)

A: Most of the older answers have you use contentsOfDirectoryAtPath:error: which will work, but according to Apple:

"The preferred way to specify the location of a file or directory is to use the NSURL class"

so if you want to use NSURL instead you can use the method contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error: so it would look something like this:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray<NSURL*> *urls = [fileManager contentsOfDirectoryAtURL:directoryURL includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey] options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];

    for (NSURL *url in urls)
    {
        NSError *error = nil;
        BOOL success = [fileManager removeItemAtURL:url error:error];
        if (!success || error) {
            // something went wrong
        }
    }

A: if you want to remove files and the directory itself then use it without for loop
NSFileManager *fm = [NSFileManager defaultManager];
NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"Photos"];
NSError *error = nil;
BOOL success = [fm removeItemAtPath:cacheImageDirectory error:&error];
if (!success || error) {
    // something went wrong
}

A: same for swift lovers:
let fm = FileManager.default
do {
  let folderPath = "...my/folder/path"
  let paths = try fm.contentsOfDirectory(atPath: folderPath)
  for path in paths
  {
    try fm.removeItem(atPath: "\(folderPath)/\(path)")
  }
} catch {
  print(error.localizedDescription)
}

A: NSFileManager *fm = [NSFileManager defaultManager];
NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"];
NSError *error = nil;
for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
    BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, file] error:&error];
    if (!success || error) {
        // it failed.
    }
}

I leave it up to you to do something useful with the error if it exists.

A: Swift 4
  do {

        let destinationLocation:URL = ...

        if FileManager.default.fileExists(atPath: destinationLocation.path) {
            try! FileManager.default.removeItem(at: destinationLocation)
        }

    } catch {
    print("Error \(error.localizedDescription)")
    }


text:
Q: How to synchronize different shell instances I want to synchronize / "sequentialize" multiple instances running simultaneously of a specific shell.
Optionally, a subset of arguments can determine if the process can be running immediately or must wait.
To be clear :
If I run the following three commands simultaneously (in this example schema and table option determine the lock):
loadTable --schema dev --table person --file mydata1.txt
loadTable --schema dev --table person --file mydata2.txt
loadTable --schema dev --table enterprise --file mydata3.txt

I want :

*

*the first and third commands can be run simultaneously
because partial arguments are different (schema and table)

*the second command must wait the end of the first one
because partial arguments are identical (schema and table)
For me 2 solutions :

*

*loadTable shell must manage a waiting queue himself.

*a parent proxy shell must manage it

I have some ideas, but it seems a little bit complex...
Thanks for your help

A: I have made a synchronize function.
I can now simply call at the beginning of my script (after args parsing):
synchronize $myTable-$mySchema

It does the job but we can maybe simplified it.
code :
function synchronize() {
    key=${1:-noKey};
    shell_fullname=$(readlink -f $0)
    shell_basename=$(basename $shell_fullname)
    hash=$(echo "${shell_fullname}-${key}" | md5sum | cut -b-32)
    delay=2
    pid_file=/tmp/${shell_basename}.${hash}.pid
    current_pid=$$

    echo "synchronize$shell_basename($key)"
    (
        # First step : lock file
        isUnLock=true
        echo "trying to acquire lock"
        while $isUnLock
        do
            # Wait for lock on file desciptor 200 for 10 seconds
            flock -x -w $delay 200 && isUnLock=false
            $isUnLock && echo "Waiting lock for"
        done

        # here : isUnLock must normally be false
        $isUnLock && echo "unable to acquire lock" # not possible for me
        $isUnLock && exit 255 # bad luck...
        $isUnLock || echo "lock OK"

        # Second step : waiting eventual previous process
        while [ -e ${pid_file} ] && kill -0 `cat $pid_file` > /dev/null 2>&1
        do
            echo "Another process already running with process_id $(cat ${pid_file})"
            sleep $delay
        done

        # here : previous shell stop and the current process has lock the pid_file
        echo $current_pid > ${pid_file}

        # now we can unlock the pid file and the current shell can be running alone safely
        # (just fail if somebody delete the pid_file...)

    ) 200>$pid_file.lock # add suffix, flock seems make empty file after lock...

}

key=$1 # construct key using args
synchronize$key

ligthest version
function synchronize() {
    key=${1:-noKey};
    shell_fullname=$(readlink -f $0)
    shell_basename=$(basename $shell_fullname)
    hash=$(echo "${shell_fullname}-${key}" | md5sum | cut -b-32)
    delay=10
    pid_file=/tmp/${shell_basename}.${hash}.pid
    current_pid=$$

    echo "synchronize $shell_basename($key) pid_file=$pid_file"
    (
        # First step : lock file, Wait for lock on file desciptor 200
        echo "trying to acquire lock"
        flock -x 200
        echo "lock acquired"

        # Second step : waiting eventual previous process
        [ -s $pid_file ] && previous_pid=$(cat $pid_file) || previous_pid=00 # 00 is an impossible pid
        [ -e /proc/${previous_pid} ] && echo "Another process already running with process_id $previous_pid"
        while [ -e /proc/${previous_pid} ]; do sleep $delay; done

        # here : previous shell is stop and the current process has lock the pid_file
        echo $current_pid > ${pid_file}
        echo "current pid $current_pid is running"

        # now we can unlock the pid file and the current shell can be running several minutes

    ) 200>$pid_file.lock # add suffix, flock seems make empty file after lock...

}

A: You can simplify and securise a little bit the second step
(securise => by this way it works even if $pid_file is delete during the previous execution)
# Second step : waiting eventual previous process
previous_pid=$(cat $pid_file)
previous_pid=${previous_pid:00} # 00 is an impossible pid
while [ -e /proc/${previous_pid} ]
do
    echo "Another process already running with process_id ${previous_pid}"
    sleep $delay
done

A: If I get it right, you need to do something like this:
loadTable --schema dev --table person --file mydata1.txt &
loadTable --schema dev --table enterprise --file mydata3.txt &
wait %1 && loadTable --schema dev --table person --file mydata2.txt &
wait

In this case you will run commands 1 and 3 in parallel, then wait first command to finish and run second one. After that you wait all of them to finish


text:
Q: Sort a unsorted list (li) with nested lists only on first level I have the following list that I would like to sort:

function sortUnorderedList(ul, sortDescending) {
  if (typeof ul == "string")
  var lis = $( "li", ".text-error" );
  var vals = [];
  for (var i = 0, l = lis.length; i < l; i++)
    vals.push(lis[i].innerHTML);
  vals.sort();
  if (sortDescending)
    vals.reverse();
  for (var i = 0, l = lis.length; i < l; i++)
    lis[i].innerHTML = vals[i];
}
window.onload = function() {
  var desc = false;
  sortUnorderedList("list", desc);
  desc = !desc;
  return false;
}

Brush your teeth

Wash your hands

Do your homework

Do not use curse-words

Act polite:

Say Hello

Say Goodbye

Always remember:

Think for yourself

Think twice

This works for the first level of list items, but the list items with nested lists are not sorted.
How can I sort all first level list items?

A: I think it would be easier to isolate each context (in your case it seems to be .text-error) first and then iterate over those individually.
This example will iterate nested li's on their respective level.

function sortUnorderedList(ul, sortDescending) {
  if (typeof ul == "string") {
    //Get each individual ul/li-context to sort inside
    var contexts = $('.text-error');

    //Iterarate over individual contexts
    contexts.each(function(i,ctx){
        //Get first level
 elements in specific context
        var lis = $(ctx).children('li');

        //Sort the results
        lis.sort(function(a, b){
          var sortResult = $(a).text().localeCompare($(b).text());
          if(sortDescending){ sortResult = 0 - sortResult }
          return sortResult;
        });

        //Append the items
        lis.each(function(i2, li){
            ctx.append(li);
        })
    })
  }
}

window.onload = function() {
  var desc = false;
  sortUnorderedList("list", desc);
  desc = !desc;
  return false;
}
/*CSS for exampe rendering clarity*/
ul{
  font-size: 0.85em;
  font-family: sans-serif;
  list-style-type: none;
  line-height: calc(1em + 2px);
}
li > ul{
  border-top:1px solid gainsboro;
}
li {
  border-left: 1px solid gray;
  width: 0;
  white-space: nowrap;
  padding: 1px;
}
  li li, li ul {
    border-color: silver;
    color:dimgray;
  }
    li li li, li li ul {
      border-color: gainsboro;
      color:gray;
    }

Brush your teeth

Wash your hands

Do your homework

Do not use curse-words

Act polite:

Say Hello

Say Goodbye

Always remember:

Think for yourself

Think twice

Bolow is an example illustrating the sorting on single individual levels.

C

F

A

G

B

D

D3

D1

D2

D2-1

D2-3

D2-2

D2-4

D5

D4

E

E1

E3

E4

E2

E5

E5-1

E5-4

E5-2

E5-3

A: You could create recursive function that will look for ul elements inside li and if it exists it will sort each nested ul.

function sortHTML(el) {
  const li = el.find('> li');

  const sorted = li.sort((a, b) => {
    return $(a).text().localeCompare($(b).text())
  })

  li.each(function() {
    const ul = $(this).find('ul');
    if (ul.length) {
      ul.each(function() {
        sortHTML($(this))
      })
    }
  })

  el.html(sorted)
}

sortHTML($('body > ul.text-error'))

Brush your teeth

Wash your hands

Do your homework

Do not use curse-words

Act polite:

Say Hello

Say Goodbye

Always remember:

Think for yourself

Think twice

A: You want to recursively work through the tree.
For that, you could depth-first or breadth-first search, but why over complicate matters?  jQuery has a recursive "find everything" function built-in!
Updated: Using your original sort function.  Why not! And added a cut-down code version.
I'm using a simple filter to only sort .sort items, so it doesn't take over the entire page.

function sortItems(parent, childSelector) {
  var items = parent.children(childSelector).sort(function(a, b) {
    return $(a).text().localeCompare($(b).text())
  });
  parent.append(items);
}

$().ready(function () {
  // ".sort" filter to limit what it sorts, could be "ul" instead
  $('body').find(".sort").each(function () {
    sortItems($(this), "li");
  });
});

Brush your teeth

Wash your hands

Do your homework

Do not use curse-words

Act polite:

Say Hello

Say Goodbye

Always remember:

Think for yourself

Think twice

A more minified version:
$().ready(function () {
  // ".sort" filter to limit what it sorts, could be "ul" instead
  // This is jQuery's recursive search function - "find(<filter>)".
  $('body').find(".sort").each(function () {
        // For each item we want to sort ("find().each()"), sort them.
        // Note: I'm explicitly filtering for "li" items to sort.
        var sortedChildren = $(this).children("li").sort(function(a, b) {
          return $(a).text().localeCompare($(b).text());
        });
        $(this).append(sortedChildren);
  });
});


text:
Q: Database script for Joomla upgrade from 1.7 to 2.5? I am looking for the script that does the database changes and upgrades the Joomla installation from Joomla 1.7 to Joomla 2.5. Thus I am not looking for changes in the code as I can check those from SVN. Having access to this script can allow me to just run these scripts on the server where I cannot run the automatic upgrade from Joomla admin.
Update: As @Elin indicated. Snapshot of the sql folder under com_admin. Which sql queries are executed from here?

Thanks.

A: Look in the sql folder of com_admin.


text:
Q: How do I convert a mobile phone GPS to x,y,z with origin at the center of the Earth? I need to accurately visualize points coming from iPhone (and other) GPS data in 3D.
So, what I'd like is to take a WGS84 (right?) point and transform that into an X,Y,Z vector with the origin at the center of the Earth.
I Googled for GPS/WGS84 to 3D but I think my search terms are not so great
Does someone have a pointer for where to start?
In future, I'll also need to take elevation information into account if available, but that isn't so important immediately.
Thanks!

A: what your looking for is representing your data in ECEF (Earth Centered Earth Fixed) notation.
Some good wikipedia stuff

A: Latitude and longitude are relatively easy, since they're just angles, however altitude is a bit tricky because the Earth isn't exactly round. If you don't need very great accuracy, this Wikipedia article has formulas for converting from a spherical coordinate system into a cartesian one. Be warned that this is not quite accurate because the Earth resembles an ellipsoid more than a perfect sphere.


text:
Q: CASE WHEN in SQL Server  SET @Result = @KriteriumTekst +
               CASE @Operator
                  WHEN 'LT' THEN '<'
                  WHEN 'GT' THEN '>'
                  WHEN 'NE' THEN '<>'
                  WHEN 'EQ' THEN '='
               + @Verdi +
               CASE @Tilstand
                  WHEN 'OG' THEN 'AND'
                  WHEN 'ELLER' THEN 'OR'

This statement is not compiling, what could be the issue.

A: You are miising the END of the CASE expressions:
 SET @Result= @KriteriumTekst+CASE @Operator WHEN 'LT' THEN '<'
                                        WHEN 'GT' THEN '>'
                                        WHEN 'NE' THEN '<>'
                                        WHEN 'EQ' THEN '='
                              END

                    +@Verdi+ CASE @Tilstand WHEN 'OG' THEN 'AND'
                                            WHEN 'ELLER' THEN 'OR'
                             END

A: As has been pointed out in comments, your cases needs to be terminated with END
Other than that, if @Operator is "LT" and @Tilstand is "OG", you'd have a result that looks like
@KriteriumTekst + '<' + @Verdi + 'OG'

Given values to @KriteriumTekst and @Verdi, you may end up with something like
@Result = '1<5OG'

It is difficult to see what you would want to do with that string.

A: You need to terminate the case statement:
SET @Result= @KriteriumTekst+CASE @Operator WHEN 'LT' THEN '<'
                                        WHEN 'GT' THEN '>'
                                        WHEN 'NE' THEN '<>'
                                        WHEN 'EQ' THEN '='
                                        END
                    +@Verdi+ CASE @Tilstand WHEN 'OG' THEN 'AND'
                                            WHEN 'ELLER' THEN 'OR'
                                            END

A: Each CASE requires the END keyword (MSDN reference):
declare @result nvarchar(256)
declare @KriteriumTekst nvarchar(256)
declare @Operator nvarchar(256)
declare @Verdi nvarchar(256)
declare @Tilstand nvarchar(256)

set @KriteriumTekst = 'Tekst '
set @Operator = 'LT'
set @Verdi = 'Verdi '
set @Tilstand = 'OG'
 SET @Result= @KriteriumTekst+CASE @Operator WHEN 'LT' THEN '<'
                                        WHEN 'GT' THEN '>'
                                        WHEN 'NE' THEN '<>'
                                        WHEN 'EQ' THEN '=' END
                    +@Verdi+ CASE @Tilstand WHEN 'OG' THEN 'AND'
                                            WHEN 'ELLER' THEN 'OR' END
select @result


text:
Q: Why should objects in Redux be immutable? Why should objects in Redux be immutable?
I know that some frameworks such as Angular2 will use onPush and can take advantage of immutability to compare states of views for faster rendering, but I am wondering if there are other reasons as Redux is framework agnostic and yet it mentions within its own docs to use immutability (regardless of the framework).
Appreciate any feedback.

A: The main reason Redux is using immutability is that it doesn't have to traverse an object tree to check for the changes in every key value. Instead, it will only check the object's reference is changed or not in order to update DOM on state change.

A: Redux is a small library that represents state as (immutable) objects. And new states by passing the current state through pure functions to create an entirely new object/application states.
If your eyes-glazed over there don't worry. To sum up, Redux does not represent changes in your application's state by modifying objects ( as you would with object-oriented paradigms). Instead state changes are represented as the difference between the input object and the output object (var output = reducer(input)). If you mutate either input or output you invalidate the state.
To sum up another way, immutability is a requirement of Redux because Redux represents your application state as "frozen object snapshots". With these discrete snapshots, you can save your state, or reverse state, and generally have more "accounting" for all state changes.
State of your app is only changed by a category of pure functions called reducers. Reducers have 2 important properties:

*

*They never mutate, returning newly built objects: This allows reasoning about input + output without side-effects

*Their signature is always function name(state, action) {}, so it makes it easy to compose them:

Assume the state looks like this:
    var theState = {
      _2ndLevel: {
        count: 0
      }
    }

We want to increment the count, so we make these reducers
const INCR_2ND_LEVEL_COUNT = 'incr2NdLevelCount';

function _2ndlevel (state, action) {
    switch (action.type) {
        case INCR_2ND_LEVEL_COUNT:
            var newState = Objectd.assign({}, state);
            newState.count++
            return newState;
        }
    }

function topLevel (state, action) {
    switch (action.type) {
        case INCR_2ND_LEVEL_COUNT:
            return Object.assign(
                {},
                {_2ndLevel: _2ndlevel(state._2ndlevel, action)}
            );
    }
}

Note the use of Object.assign({}, ...) to create an entirely new objects in each reducer:
Assuming we have wired up Redux to these reducers, then if we use Redux's event system to trigger a state change ...
    dispatch({type: INCR_2ND_LEVEL_COUNT})

...Redux will call:
    theNewState = topLevel(theState, action);

NOTE: action is from dispatch()
Now theNewState is an entirely new object.
Note: You can enforce immutability with a library (or new language features), or just be careful to not mutate anything :D
For a deeper look, I highly recommend you checkout this video by Dan Abramov (the creator). It should answer any lingering questions you have.

A: The following benefits of immutability are mentioned in Redux documentation:

*

*Both Redux and React-Redux employ shallow equality checking. In particular:

*

*Redux's combineReducers utility shallowly checks for reference changes caused by the reducers that it calls.

*React-Redux's connect method generates components that shallowly check reference changes to the root state, and the return values from the mapStateToProps function to see if the wrapped components actually need to re-render. Such shallow checking requires immutability to function correctly.

*Immutable data management ultimately makes data handling safer.

*Time-travel debugging requires that reducers be pure functions with no side effects, so that you can correctly jump between different states.

A: Greate article https://medium.cobeisfresh.com/how-redux-can-make-you-a-better-developer-30a094d5e3ec

Along with immutable data, pure functions are one of the core concepts
  of functional programming

A: Based on the official docs :
There are several reasons why you must not mutate state in Redux:

*

*It causes bugs, such as the UI not updating properly to show the latest values

*It makes it harder to understand why and how the state has been updated

*It makes it harder to write tests

*It breaks the ability to use "time-travel debugging" correctly

*It goes against the intended spirit and usage patterns for Redux

Reudx official docs


text:
Q: Google Maps API v3 Info Window setContent syntax error I am trying to set the content of an info window but I am having syntax errors accessing the JSON object.
Example from elsewhere on Stack Overflow I am following
JavaScript snippet:
        var localLayer = new google.maps.Data();
        localLayer.loadGeoJson('JSON/local.geojson');
        localLayer.setMap(map);

        var localInfoWindow = new google.maps.InfoWindow({
            var address = localLayer.features.properties.Address;
            content: "
" + address + "
"
        });

        google.maps.event.addListener(localLayer, 'click', function(event){
            localInfoWindow.setPosition(event.feature.getGeometry().get());
            localInfoWindow.open(map, localLayer);
        });

What am I doing wrong?
JSON snippet:
{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },

"features": [
{ "type": "Feature", "properties": { "OBJECTID": 1, "Address": "14300 McMullen Highway SW", "City": "Cumberland", "State": "MD", "Zip_Code": 21502, "Type": "Detention Center", "Agency_Nam": "Allegany County Detention Center", "County": "Allegany" }, "geometry": { "type": "Point", "coordinates": [ -78.823195987258302, 39.598971947812366 ] } },
{ "type": "Feature", "properties": { "OBJECTID": 2, "Address": "131 Jennifer Road", "City": "Annapolis", "State": "MD", "Zip_Code": 21401, "Type": "Detention Center", "Agency_Nam": "Anne Arundel County Detention Center", "County": "Anne Arundel" }, "geometry": { "type": "Point", "coordinates": [ -76.530041483218611, 38.988903980495373 ] } }, . . .

HTML:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Maryland Prisoner Map</title>

    <link href="style.css" rel="stylesheet" type="text/css">

Maryland Prisoner Map

CSS:
#header {
    text-align: center;
}

#map {
    height: 450px;
    width: 80%;
    margin: 0 auto;
    border: 1px solid black;
    box-shadow: 2px 2px 1px 2px gray;
}

* {
    margin: 0;
}
html, body {
    height: 100%;
}

JavaScript:
    $(document).ready(function() {
        var layer = "toner-lite";
        var map = new google.maps.Map(document.getElementById("map"), {
            center: new google.maps.LatLng(39.290385, -76.612189),
            zoom: 10,
            mapTypeId: layer,
            mapTypeControlOptions: {
                mapTypeIds: [layer, google.maps.MapTypeId.HYBRID]
            }
        });
        map.mapTypes.set(layer, new google.maps.StamenMapType(layer));
        //load data into map
        var localLayer = new google.maps.Data();
        localLayer.loadGeoJson('JSON/local.geojson');
        localLayer.setMap(map);

        var localInfoWindow = new google.maps.InfoWindow({
            var address = localLayer.features.properties.Address;
            content: "
" + address + "
"
        });

        google.maps.event.addListener(localLayer, 'click', function(event){
            localInfoWindow.setPosition(event.feature.getGeometry().get());
            localInfoWindow.open(map, localLayer);
        });

        var stateLayer = new google.maps.Data();
        stateLayer.loadGeoJson('JSON/state.geojson');
        stateLayer.setMap(map);

        var stateInfoWindow = new google.maps.InfoWindow({
            content: "I am a state level jail or prison"
        });

        google.maps.event.addListener(stateLayer, 'click', function(event){
            stateInfoWindow.setPosition(event.feature.getGeometry().get());
            stateInfoWindow.open(map, stateLayer);
        });

        var federalLayer = new google.maps.Data();
        federalLayer.loadGeoJson('JSON/federal.geojson');
        federalLayer.setMap(map);

        var federalInfoWindow = new google.maps.InfoWindow({
            content: "I am a federal level jail or prison"
        });

        google.maps.event.addListener(federalLayer, 'click', function(event){
            federalInfoWindow.setPosition(event.feature.getGeometry().get());
            federalInfoWindow.open(map, federalLayer);
        });

        var marylandLayer = new google.maps.Data();
        marylandLayer.loadGeoJson('JSON/maryland.geojson');
        //give the map style
        marylandLayer.setStyle(function(feature) {
            return {
                fillColor: getColor(feature.getProperty('Difference')), // call function to get color for state based on the COLI (Cost of Living Index)
                fillOpacity: 0.9,
                strokeColor: '#FFFFFF',
                strokeWeight: 1,
                zIndex: 1
            };
        });
        //set layer to map
        marylandLayer.setMap(map)
        //get some color
        function getColor(Difference) {
        return Difference >= 94 ? '#b10026' :
               Difference > 76 ? '#e31a1c' :
               Difference > 58 ? '#fc4e2a' :
               Difference > 38 ? '#fd8d3c' :
               Difference > 20 ? '#feb24c' :
               Difference > 7 ? '#fed976' :
               Difference > 1 ? '#ffffb2' :
               Difference > -1 ? '#FFFFFF' :
               '#000000';
        };

    // Add mouseover and mouse out styling for the GeoJSON Maryland data
    marylandLayer.addListener('mouseover', function(e) {
        marylandLayer.overrideStyle(e.feature, {
            strokeColor: '#2a2a2a',
            strokeWeight: 2,
            zIndex: 2
        });
    });
    marylandLayer.addListener('mouseout', function(e) {
        marylandLayer.revertStyle();
    });

    var polygonInfoWindow = new google.maps.InfoWindow({
        content: marylandLayer.features.properties.Difference
    });
    google.maps.event.addListener(marylandLayer, 'click', function(event){
        polygonInfoWindow.setPosition(event.feature.getGeometry().get());
        polygonInfoWindow.open(map, marylandLayer);
    });
});

A: You need to load the content into the infowindow inside the layer 'click' listener.  Inside that function evt is a reference to the feature and you can call the getProperty method to access that feature's properties:
localLayer.addListener('click', function (evt) {
    var address = evt.feature.getProperty("Address");
    localInfoWindow.setContent("
" + address + "
");
    localInfoWindow.setPosition(evt.feature.getGeometry().get());
    localInfoWindow.open(map);
});

proof of concept fiddle


text:
Q: Intermittent Firefox DNS-over-HTTPS failure Background & Configuration
I have enabled DNS-over-HTTPS (DoH) in Firefox, in order to hand a stream of sites I access over to Cloudflare and thence directly to government agencies in one convenient place. This is hidden away in Preferences, General tab, scroll down to the bottom right, Settings button, scroll down to the bottom again.
I noticed on attempting to search for a term containing a dot, that DNS-over-HTTPS was not being used. My ISP, BT, were still hijacking plain old DNS to redirect to their site. This is surprising given the wording provided by Firefox that indicates to any reasonable person that this would be safe. Firefox UX sign-off could do with bucking their ideas up, IMO.
So, after googling I have gone into about:config and changed network.trr.mode to 3 in order that Firefox does not fail unsafe on DoH.
This doesn't work at all.
Further googling, I have switched off the BT "Smart Setup" on my ADSL router. The steps for my BT Home Hub:

*

*Log in to the admin site 192.168.1.254.

*Advanced Settings

*Continue to Advanced Settings (!)

*Home Network

*"Smart Setup" (It seems "smart" is never smart.)

*No

*Apply
That seemed to work for a while, but then failed and kept failing.
It's an intermittent failure. Switching network.trr.mode back to 2 (fail open!) and then possibly loading something, allows setting network.trr.mode back to 3 for a while.
I suspected that Firefox may be doing all the lookups outside of DoH using just the poisoned DNS cache. However, sites I had not been to still worked.
Going to https://1.1.1.1/help during intermittent failures gives me:
 Connected to 1.1.1.1           No
 Using DNS over HTTPS (DoH)     No
 Using DNS over TLS (DoT)       No
 AS Name                     Checking...
 AS Number                   Checking...
 Cloudflare Data Center         LHR

When working that becomes:
 Connected to 1.1.1.1           Yes
 Using DNS over HTTPS (DoH)     Yes
 Using DNS over TLS (DoT)       No
 AS Name                     Cloudflare
 AS Number                     13335
 Cloudflare Data Center         LHR

Going to https://www.cloudflare.com/ssl/encrypted-sni/ I noticed that Encrypted SNI was not happening. As I understand it, SNI enabled a web server to provide the correct certificate for a site when a single IP address is mapped from multiple names. Unfortunately, by default, Firefox sends host names in plain text even when using DoH. Believable.
Yet more googling turns up setting network.security.esni.enabled to true in about:config to encrypt host names here. How this fails, I don't know.
I have also tried using a public access point (The Cloud), and the behaviour is much the same.
I have been using macOS Catalina. Seems to be the same on a Windows 10 cheap and very nasty laptop. Have tried flushing the Windows DNS cache with ipconfig /flushdns and also setting network.dnsCacheExpiration to 0. Neither makes it work when it is failing, nor makes it fail when it is working.
The question
What is causing fail-safe DoH that intermittently fail on Firefox and how do I fix it?
I notice that the www.cloudflare.com name is in the DoH configuration. Is it failing to bootstrap in a sensible fashion? Does it expire the lookup after a while and not use DoH in time?

A: I have now had a look at the wiki.
It turns out that it is indeed the issue of bootstrapping the name used in the resolver HTTPS URL. An IP of a DNSSEC server needs to be in network.trr.bootstrapAddress, probably using the same server as for DNS-over-HTTPS. The wiki suggest looking up with https://dns.google/query?name=mozilla.cloudflare-dns.com which can be checked with nslookup. For Cloudflare this gives the choice 104.16.249.249 or 104.16.248.249. The initial ticket also suggests the alternative of using an IP address in HTTPS URL (though I guess that means it would be using an IP address HTTPS certificate).
So beyond the preferences window, the configuration you need in about:config to make DNS-over-HTTPS work in Firefox appears to be:
 network.security.esni.enabled    true
 network.trr.mode                 3
 network.trr.bootstrapAddress     104.16.249.249

All I wanted was a ticky box.
Edit: It's difficult to reproduce, but I still see the intermittent problem. It occurs for one page then clears itself.


text:
Q: windowbuilder xwt design MalformedByteSequenceException: Invalid byte of UTF-8 sequence The problem is:
When we are trying to use russian characters in xml-attributes in .xwt file (label text for instance) WindowBuilder design view crashes with error:
com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 2 of 3-byte UTF-8 sequence.
It seems, that xml parser crashes because of the file encoding.

A: The problem is solved. WindowBuilder passes IOUtils.toInputStream(xwt_file_content) to XWTParser. XWTParser expects UTF8 encoded stream, but your Eclipse IDE uses default system encoding. Add JVM argument -Dfile.encoding=UTF8 to eclipse.ini.


text:
Q: Consecutive words with regex I am trying to add a new label (boolean value, true/false) if two words are repeated in a consecutive way:
For example:
d = {'test': ['test test ciao a todos']}
df = pd.DataFrame(data=d)

the output expected should be True:
pat = r'\b(\w+)\b.*\b\1\b'
df['C']=f['test'].str.contains(pat)

However, the output is also True when I run this:
d = {'test': ['test hola ciao a test']}
df = pd.DataFrame(data=d)

pat = r'\b(\w+)\b.*\b\1\b'
df['C'] = df['test'].str.contains(pat)

when my expected output should be False.
Can you please tell me what is wrong in the regex code? Thanks

A: The .* says that there can be an unlimited number of characters between the two words.
So simply removing the * should solve your problem
\b(\w+)\b.\b\1\b

try it


text:
Q: EMF Export text spacing defect How can I fix the EMF text spacing in Mathematica 11?
For example
Export["an.emf",
  a = Graphics[{{Yellow, Rectangle[{0, 0}, {240, 30}]},
     {Black,
      Inset[Style["Information table example",
        FontSize -> 20], {0, 15}, {Left, 0}]}},
    BaseStyle -> FontFamily -> "Franklin Gothic Book",
    ImageSize -> 240, PlotRange -> {{0, 240}, {0, 30}}]];
Print[a]

The EMF produced by Mathematica 11 has irregular spacing

On the same PC Mathematica 7 produces the expected result

I am running Mathematica 11.0.1 and 7.0.1 on Windows 10 Pro.
Edit
Here is a better example to further illustrate the problem.
These tables were produced with the code below.  Displayed in Mathematica they look fine.
First using the font "Franklin Gothic Book", then "Verdana".

However, when exported to EMF there are spacing problems.

*

*There is a big space between "Information" and "table" in the Franklin Gothic Book version.

*big spaces in "Category Item Text".

*irregular space between 1,234 and ,567.00

*big space between 123.456 and % which shouldn't be there at all

*big space between (123.120 and ) which shouldn't be there

*In the Verdana version no space in "CategoryItem" and no space in "CategoryText".

*the % and closing bracket in (123.12) are squashed to the preceding character.

As I mentioned earlier, the EMF exports from Mathematica 7 look perfect.
Code
a = Graphics[{GrayLevel[1],Rectangle[{-1,-60},{740,25}],
{{GrayLevel[1],Rectangle[{0,0},{739,25}]},
{Black,
Inset[Style["Information table example",FontSize->16,FontSlant->Italic],
{0,43/3},ImageScaled[{0,1/2}]]}},
{{GrayLevel[0.3],Rectangle[{0,0},{739,-35}]},
{GrayLevel[1],
{Inset[Style["Category Heading Text",FontSize->12,FontSlant->Italic],{6,-35/4},ImageScaled[{0,1/2}]],
Inset[Style["",FontSize->12,FontSlant->Italic],{6,-105/4},ImageScaled[{0,1/2}]]},
{{Inset[Style["First Column",FontSize->12,FontSlant->Italic],{190,-35/4}],
Inset[Style["Part One",FontSize->12,FontSlant->Italic],{190,-105/4}]},
{Inset[Style["Column Two",FontSize->12,FontSlant->Italic],{306,-35/4}],
Inset[Style["Part Two",FontSize->12,FontSlant->Italic],{306,-105/4}]},
{Inset[Style["%",FontSize->12,FontSlant->Italic],{404,-35/4}],
Inset[Style["",FontSize->12,FontSlant->Italic],{404,-105/4}]},
{Inset[Style["Column 4",FontSize->12,FontSlant->Italic],{989/2,-35/4}],
Inset[Style["",FontSize->12,FontSlant->Italic],{989/2,-105/4}]},
{Inset[Style["",FontSize->12,FontSlant->Italic],{1199/2,-35/4}],
Inset[Style["Type",FontSize->12,FontSlant->Italic],{1199/2,-105/4}]},
{Inset[Style["",FontSize->12,FontSlant->Italic],{1393/2,-35/4}],
Inset[Style["% Total",FontSize->12,FontSlant->Italic],{1393/2,-105/4}]}},
Inset[Style["Summary",FontSize->12,FontSlant->Italic],{642,-35/4}]}},
{{{GrayLevel[0.9],Rectangle[{0,-35},{739,-57}]},{Black,
Inset[Style["Category Item Text",FontSize->12],{6,-46},ImageScaled[{0,1/2}]],
{Inset[Style["1,234,567.00",FontSize->12],{233,-46},ImageScaled[{1,1/2}]],
Inset[Style["Category Text",FontSize->12],{349,-46},ImageScaled[{1,1/2}]],
Inset[Style["123.456%",FontSize->12],{429,-46},ImageScaled[{1,1/2}]],
Inset[Style["(123.120)",FontSize->12],{530,-46},ImageScaled[{1,1/2}]],
Inset[Style["Category Text",FontSize->12],{639,-46},ImageScaled[{1,1/2}]],
Inset[Style["10.7",FontSize->12],{724,-46},ImageScaled[{1,1/2}]]}}}},{GrayLevel[1],Rectangle[{652.9,-35},{655.1,-123}]},
{{GrayLevel[1],Rectangle[{130.9,0},{133.1,-123}]},
{GrayLevel[1],Rectangle[{246.9,0},{249.1,-123}]},
{GrayLevel[1],Rectangle[{362.9,0},{365.1,-123}]},
{GrayLevel[1],Rectangle[{442.9,0},{445.1,-123}]},
{GrayLevel[1],Rectangle[{543.9,0},{546.1,-123}]}}},
BaseStyle->FontFamily->"Franklin Gothic Book",ImageSize->739,
PlotRange->{{0,739},{-59,25}}]

Export["a.emf", a]

A: To make the EMF look OK when imported into Word use
Export["a.emf", a, ImageResolution -> 300]

This makes the EMF big, and the increased resolution isn't necessary in Mathematica 7 EMFs, but it fixes the appearance.
Font map editing was also required to fix the EMF rendering of % sign and brackets, as detailed here: Wrong font selection for some characters.
Word screenshot

EMFexplorer images

*

*Default resolution & original font map

*Resolution set to 300 & original font map

*Resolution set to 300 & edited font map
The % and ( ) font issues don't show up so much in EMFexplorer but they certainly show in Word and Paint (the default app from EMF on Windows).


text:
Q: How to create _users database when launching CouchDB in Docker container? I have created this Dockerfile:
FROM couchdb:latest
EXPOSE 5984
COPY local.ini /opt/couchdb/etc/

But even though I specified [admins] inside of the local.ini, I still get this error at launch:

[error] 2022-11-06T17:55:49.799365Z nonode@nohost emulator -------- Error in process <0.15793.0> with exit value:
{database_does_not_exist,[{mem3_shards,load_shards_from_db,"_users",[{file,"src/mem3_shards.erl"},{line,400}]},{mem3_shards,load_shards_from_disk,1,[{file,"src/mem3_shards.erl"},{line,375}]},{mem3_shards,load_shards_from_disk,2,[{file,"src/mem3_shards.erl"},{line,404}]},{mem3_shards,for_docid,3,[{file,"src/mem3_shards.erl"},{line,97}]},{fabric_doc_open,go,3,[{file,"src/fabric_doc_open.erl"},{line,39}]},{chttpd_auth_cache,ensure_auth_ddoc_exists,2,[{file,"src/chttpd_auth_cache.erl"},{line,198}]},{chttpd_auth_cache,listen_for_changes,1,[{file,"src/chttpd_auth_cache.erl"},{line,145}]}]}

What do I need to do in order to avoid this error?

A: Dockerfile
FROM couchdb:latest
EXPOSE 5984
COPY setup.sh setup.sh
RUN sh setup.sh

setup.sh
#!/bin/sh -xe

cat >/opt/couchdb/etc/local.ini <<EOF
[couchdb]
single_node=true

[admins]
dbadmin = $(base32 /dev/random |head -1|cut -c-24)
EOF

nohup bash -c "/docker-entrypoint.sh /opt/couchdb/bin/couchdb &"
sleep 15

curl -X PUT http://127.0.0.1:5984/_users
curl -X PUT http://127.0.0.1:5984/_replicator


text:
Q: Excel how to make one sum formula for entire colum which sums each row separately? I am completely new to excel, so I'd like to apologize in advance if this question seems silly. I do have a solid programming / logic background.
Situation:
Column B contains the sum of each row in this fashion
(=SUM(Cn:Ln)) where n is the row number.

I now have each field in column B filled with a formula (where n is the row number).
What I want:
One formula for column B that has the same result as described. Something like
=SUM(Cn:Ln)

Hope someone can help me out here!
Kevin

A: Excel range references can be absolute or relative. Relative references move as you copy the formula (or move or fill).  So, in A1, this formula
=SUM(B1:L1)

when copied to A2 becomes
=SUM(B2:L2)

You copied the formula one row down, so the range references (being relative) refer to the range one row down from the original.  The same is true for columns. Had you copied that formula to B2
=SUM(C2:M2)

The dollar sign makes a reference absolute. An absolute reference does not change when the formula is copied. You can make the row absolute, the column absolute, or both.  Copy the formula on the left from A1 to D10 to get the formula on the right
=$B$2   =$B$2    both row and column absolute, no change
=B2     =E11     both row and column relative, both change
=$B2    =$B11    column absolute, only the row changes
=B$2    =E$2     row absolute, only the column changes

A: try
=SUM(C$n:L$N)
where n is your first row and N is your Last row
so if you had a table such as
      A          B        C     D  >>>   L
1     Bob       Tom       1     1        1
2     sue       Mary      1     1        1
3     no         yes      1     1        1
4
5    Sum                                 9

of course, you could define a range in Excel too.


text:
Q: FOL equivalence, operations and usage of quantifiers I'll start by saying that I searched for a discussion about this topic but I couldn't find the exact answers I'm looking for, so if you have a link to a previous discussion with the relevant answers I'll be much obliged.
I'm a student and I'm taking an intro course about mathematical logic (among other topics such as set theory and group theory). Recently we started studying FOL and I'm having a bit of trouble understanding how to properly use and write WFFs. The part I'm struggling with is how much difference is there between FOL and propositional logic when it comes to the behaviour of variables, quantifiers and logical operations. Mainly:

*

*How much freedom do we have with the placement of quantifiers (while keeping them in proper order) in a given formula, and also how does this affect the logical operations we use. For example, are the following formulas equivalnet?
$$\exists x \forall y \bigr(\lnot P(x) \lor Q(y) \bigr) \equiv \exists x \forall y \bigr(P(x) \to Q(y)\bigr) \equiv \exists x \biggr(P(x) \to \Bigr(\forall y\bigr(Q(y)\bigr)\Bigr)\biggr) \equiv \biggr( \exists x \Bigr(P(x)\Bigr) \to \forall y\Bigr(Q(y)\Bigr)\biggr) $$

*This is sort of a follow up to the previous question. How do I properly "translate" from english to FOL when describing specific definitions or sentences. Let's take the definition of a limit for example: Let $f: \mathbb{R} \to \mathbb{R}$ be a function and let $L \in \mathbb{R}$ be a real number.
We say that $lim_{x\to\infty}f(x) = L$, if for every $\epsilon >0 $ there exists an $M >0$ s.t. for every $x>M$ it holds that: $|f(x) - L| < \epsilon$. Honestly, I'm not sure I could write this down properly as a WFF. Is there a relation between the placment of quantifiers and variables to their dependency on other variables? (in this example, x is dependent on M which is dependent on epsilon)
Techincally there are still a few things I'm not 100% sure about, but first I want to clear this because I feel like until I wrap my head around this I shouldn't move on to bigger questions.
Thanks in advance to all who share their wisdom and time!

A: For (1), the answer is yes (partially).
Since $(p \to q) \iff (\lnot p \lor q)$. En fact, this is true for any formula that if $\alpha$ was a sub-formula of a formula $\phi$, then obtaining a formula $\psi$ incurs if we replace one or more instances of $\alpha$ by some $\beta$; it follows that: $$(\alpha \iff \beta) ~ ~ ~ \iff ~ ~ ~ (\phi \, \iff \, \psi)$$ This is the called the substitution theorem. Here, us saying: $\exists x \; \forall y \; (\lnot \phi(x) \; \lor \; \psi(y)) \; \iff \; \exists x \; \forall y \; (\phi(x) \to \psi(y))$ is permissible.
"As for the third formula, this is wrong. Unless you say that: $\forall y \; \phi(y) \to \psi(x)$ when $\psi(y{\setminus}x)$ with $\lnot(x \in \text{free}(\psi))$, then that won't be true, and also no need for the quantifier anymore if it is not free. The same thing goes for the last formula too. (Thus, only the first one is logically equivalent.)", the last paragraph is obsolete upon an edit to the question, for any reader, check the comments to get context, and an apt answer.

For (2), the answer will be given, and then some notes; here:
$$\forall \epsilon \; \bigg(\epsilon > 0 \to \Big(\exists N \; \big(N > 0 \; \land \; \forall x \; (x > N \; \to \; |F(x) - \ell| < \epsilon)\big)\Big)\bigg)$$
It is largely self-explanatory, although note the order of the quantifiers, and also that the greater than & less than signs are relations (constant predicates) which give out Boolean values (as opposed to functions, which gives out variables [terms]).

A: Partial answer:

We say that $lim_{x\to\infty}f(x) = L$, if for every $\epsilon >0 $
there exists an $M >0$ s.t. for every $x>M$ it holds that: $|f(x) - L|
> < \epsilon$. Honestly, I'm not sure I could write this down properly
as a WFF.

Not standard ZFC or FOL, but this may help:
$~~~~~~\forall f, L: [\forall a \in \mathbb{R}: [f(a) \in \mathbb{R}] \land L\in \mathbb{R}$
$~~~~~~\to [\text{ Lim}_\infty(f, L)\leftrightarrow \forall \epsilon \in \mathbb{R}: [\epsilon > 0 \to \exists M\in \mathbb{R}:\forall x\in \mathbb{R}: [x>M \to|f(x)-L|< \epsilon]]]] $
where $f$ is a unary function, and $\text{ Lim}_\infty$ is a binary predicate.
Or equivalently:
$~~~~~~\forall f, L: [\forall a: [a \in \mathbb{R} \to f(a) \in \mathbb{R}] \land L\in \mathbb{R}$
$~~~~~~\to [\text{ Lim}_\infty(f, L)\leftrightarrow \forall \epsilon [\epsilon \in \mathbb{R}\to [\epsilon > 0 \to \exists M: [M\in \mathbb{R} \land \forall x:[x \in \mathbb{R} \to [x>M \to|f(x)-L|< \epsilon]]]]]]]] $


text:
Q: SpriteKit How to detect if node is moving or not For my game I need to detect if nodes are still moving or not. Now I try to compare old and new positions within a time interval. If positions have the same value, nodes are not moving. And vice versa. Something like that:
 if aStonesPositionsOld[index] == aStonesPositionsNew[index] {
                        print("# stone \(index) is not moving")
                    }

Does somebody know the better and easier way to check if node is moving or not?
Update. Answer to question of KnighOfDragon (How nodes begin moving?)
Nodes begin to move if being touched, or more exactly - moved with finger. Here is a code:
      if touching {

            let dt:CGFloat = 1.0/60.0
            let distance = CGVector(dx: touchPoint.x-aCuesMe[touchingNr].position.x, dy: touchPoint.y-aCuesMe[touchingNr].position.y)

            velocity = CGVector(dx: distance.dx/dt, dy: distance.dy/dt)
            aCuesMe[touchingNr].physicsBody!.velocity=velocity
        }

A: Since you are moving the object using the physics engine, all you have to do is check the velocity.
if let v = aCuesMe[someIndex].physicsBody?.velocity {
    if v == CGVector(dx: 0, dy: 0) {
        // Object has 0 velocity and is not moving
    }
}

A: You can use GKAgent2D for this purpose from GameplayKit. It has property velocity. For more information read Apple's documentation: https://developer.apple.com/library/archive/documentation/General/Conceptual/GameplayKit_Guide/Agent.html#//apple_ref/doc/uid/TP40015172-CH8
and watch video:
https://developer.apple.com/videos/play/wwdc2016/608/


text:
Q: JavaScript weird issue i have an issue with a site that i cool development over. I am working on a website that is using the same WordPress install and shares the same DB, however, it was built with the intention to display 3 different phone numbers in the header area. Since the 3 sites share the same WordPress install the original developer wrote a script in the header.php that user a set of var and id to reference the number in the header.
If you understand JavaScript this is very simple to read and understand. The code uses the set var to reflect the 3 numbers in the if statements and it works to a point. The website has the main header and then a sticky subheader once the user scrolls down the page, so the number goes from the main header into the sticky subheader. The problem is that instead of showing the set number the subheader displays the number I use as the reference and not the set number. So I cannot understand why it's doing that since its using the same reference code.
I would like to keep the website private, however here is the script below that is in the header.php file.
// GET BASE URL
var base_url = window.location.hostname;
var set_phone = '(602) 457-5857';

if(base_url === "www.website1.com" || base_url === "website1.com" || base_url === "www.website2.com" || base_url === "website2.com" || base_url === "www.website3.com" || base_url === "website3")
{

if(base_url === "website1" || base_url === "website1"){
    set_phone = '(602) 900-9399';
} else if(base_url === "website2" || base_url === "website2"){
    set_phone = '(602) 714-1527';
} else if(base_url === "website3" || base_url === "website3"){
    set_phone = '(602) 293-8086';
}
document.getElementById("number_link").innerHTML = set_phone;

jQuery(document).ready(function( $ ) {

    $("#number_link").attr("href", "tel:"+set_phone);

});
 // $("#number_link").html(set_phone);

}

and here is the code that is used in the header but changes in the subheader.
Call Us: 602-457-5857

if anyone can give me some ideas that be great!!! Thank you in advance


text:
Q: Running node.js script with forever I'm running a node script with forever and am curious about how reliable it is and if I should build some other kind of checkup if the script is still running. I'm using this command:
forever start server.js

The server is used as my websocket server and has to run even though there are errors thrown that would normally stop the script. I've made some tests and it seems to work, but it would be great to hear from someone who is using this combination for a while about how reliable this will really be in a production environment.

A: Yes, It is reliable but if your script contains some errors that can stop the script that means it will start every time the node is stopped. That can fill out the log to its extent and you will be out of memory soon. Better to test thoroughly before moving to production to keep other application on the same server up.
But you don't have to worry to keep the node up every time.
Also do check out the nodemon, it will restart the node automatically when there is a change in the node.

A: I'm running forever in a production environment and love it personally.  I use the node server to process images using ImageMagick.  Occasionally I'll get an ENOMEM error (out of memory) and Node crashes.  (I'm guessing this is a memory leak in my script I haven't tracked down yet)  When this happens, Forever kicks right in and within seconds the server is back up.  I have the browser return a message to the user asking them to try again - they do and it processes just fine.  I've seen other random errors happen as well, mainly during development, and Forever has caught those as well and rebooted the Node server without fail.  I can't recall a time that Node has crashed and the server never rebooted, so it does what it should.
Also what is great is in your Node scripts if you do a console.log() it outputs to the forever log.  I'll do a tail on this often times to keep a check on what is happening on the server, or even just look back at the logs from time to time to see how its performing.  It'll tell you in there if/when Forever rebotted the server.
Good luck!

A: I used to use forever, but I switched to PM2. It's much better and provides live monitoring and log access as well. Check it out: PM2.