text:
Q: What Are The Uses of Algebraic Data Types? I'm reading about Algebraic Data Types (thanks to Richard Minerich I found this excellent explanation of the concept).  While I think I understand the notion of sum types and product types etc., what I'm not quite understanding is how Algebraic Data Types are useful beyond specifying pattern matching. What other things can one do with ADT's beyond pattern matching?

EDIT: I'm not asking what can a developer do with ADT's that can't be done with objects.  I'm asking if there are other operations that ADT's allow; for example, can one do additional reasoning about the types involved if ADT's are employed?  Do ADT's facilitate some sort of type analysis that wouldn't be possible without them?

A: I am not so sure the explanation is all that excellent.
Algebraic Data Types are used to create data structures, such as lists and trees.
For example parse trees are easily represented with algebraic data structures.
data BinOperator = Add
                 | Subtr
                 | Div
                 | Mult
                 | Mod
                 | Eq
                 | NotEq
                 | GreaterThan
                 | LogicAnd
                 | LogicOr
                 | BitAnd
                 | BitOr
                 | ...

data UnOperator = Negate
                | Not
                | Increment
                | Decrement
                | Complement
                | Ref
                | DeRef

data Expression = Empty
                | IntConst Int
                | FloatConst Float
                | StringConst String
                | Ident String
                | BinOp BinOperator Expression Expression
                | UnOp UnOperator Expression Bool //prefix or not
                | If Expression Expression Expression
                | While Expression Expression Bool //while vs. do while
                | Block List<Expression>
                | Call Expression List<Expression>
                | ...

It wouldn't actually take awfully much more to represent the C language.
But really, you can do about EVERYTHING with algebraic data types. Lisp proves, you can do everything with pairs and ADTs simply provide a more granular and type safe way to this approach.
Of course, if you ask, "What can you do with ADTs, that you can't do with objects?", the answer is "nothing". Only sometimes (mostly) you will find the solutions on ADTs are significantly less verbose, while those based on objects are arguably more flexible. So to put it in a parse tree represented with ADTs:
If(Call(Ident('likes_ADTs'),[Ident('you')]),
   Call(Ident('use_ADTs'),[Ident('you')]),
   Call(Ident('use_no_ADTs'),[Ident('you')]))

A: Algebraic Data Types are distinct in that they can be constructed from several types of "things". For instance, a Tree can contain either nothing (Empty), a Leaf, or a Node.
data Tree = Empty
          | Leaf Int
          | Node Tree Tree

Since a Node is composed of two Trees, algebraic data types can be recursive.
Pattern matching allows algebraic data types to be deconstructed in a way that maintains type safety. Consider the following implementation of depth and its pseudocode equivalent:
depth :: Tree -> Int
depth Empty = 0
depth (Leaf n) = 1
depth (Node l r) = 1 + max (depth l) (depth r)

compared to:
switch on (data.constructor)
  case Empty:
    return 0
  case Leaf:
    return 1
  case Node:
    let l = data.field1
    let r = data.field2
    return 1 + max (depth l) (depth r)

This has the disadvantage that the programmer must remember to case Empty before Leaf so that field1 is not accessed on an Empty tree. Likewise, the Leaf case must be declared before the Node case so that field2 is not accessed on Leaf. Thus type safety is thus not maintained by the language but rather imposes additional cognitive load on the programmer. By the way, I'm grabbing these examples directly from the wikipedia pages.
Of course, a duck-typing langauge could do something like this:
class Empty
  def depth
    0
  end
end

class Leaf
  def depth
    1
  end
end

class Node
  attr_accessor :field1, :field2

  def depth
    1 + [field1.depth, field2.depth].max
  end
end

So algebraic data types may not be strictly better than their OOP equivalent, but they do provide a different set of tensions to work with when constructing software.


text:
Q: Why fails the following OpenMP program to reduce my variable? Consider the following minimal C code example. When compiling and executing with export OMP_NUM_THREADS=4 && gcc -fopenmp minimal.c && ./a.out (GCC 4.9.2 on Debian 8), this produces five lines with rho=100 (sometimes also 200 or 400) on my machine. Expected output is of course rho=400 for all five printed lines.
The program is more likely to produce the correct result if I insert more code at // MARKER or place a barrier just there. But even with another barrier, it sometimes fails and so does my program. So the problem seems to be that a is not properly initialized when going into the reduction loop.
The OpenMP 4.0.0 manual even states on page 55 that there is an implicit barrier at the end of a loop construct unless a nowait clause is specified. So a should be set up at this point. What is going wrong here? Am I missing something?
#include <stdio.h>
#ifdef _OPENMP
#include <omp.h>
#define ID omp_get_thread_num()
#else
#define ID 0
#endif

double a[100];

int main(int argc, char *argv[]) {
    int i;
    double rho;
    #pragma omp parallel
    {
        #pragma omp for
        for (i = 0; i < 100; i++) {
            a[i] = 2;
        }
        // MARKER
        rho = 0.0;
        #pragma omp for reduction(+: rho)
        for (i = 0; i < 100; i++) {
            rho += ((a[i])*(a[i]));
        }
        fprintf(stderr, "[%d] rho=%f\n", ID, rho);
    }
    fprintf(stderr, "[%d] rho=%f\n", ID, rho);
    return 0;
}

A: OK I've got the answer, but I sweat to get it...
This is a race condition due to the fact that rho is shared and that you initialise it inside the parallel region like this rho = 0.0;
Either initialising it outside of the parallel region, or using a #pragma omp single right before will fix the code...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Kubernetes service access internal service I have 2 services

*

*eclipse-mosquitto

*golang project consumer mqtt

I'm running in kubernetes
My mosquitto service
$ kubectl describe svc mosquitto -nproduction

Name:              mosquitto
Namespace:         production
Labels:            app.kubernetes.io/instance=mosquitto
                   app.kubernetes.io/managed-by=Helm
                   app.kubernetes.io/name=mosquitto
                   helm.sh/chart=mosquitto-2.4.1
Annotations:       meta.helm.sh/release-name: mosquitto
                   meta.helm.sh/release-namespace: production
Selector:          app.kubernetes.io/instance=mosquitto,app.kubernetes.io/name=mosquitto
Type:              ClusterIP
IP Family Policy:  SingleStack
IP Families:       IPv4
IP:                10.98.173.157
IPs:               10.98.173.157
Port:              mqtt  1883/TCP
TargetPort:        mqtt/TCP
Endpoints:         10.44.0.1:1883
Port:              websocket  9090/TCP
TargetPort:        websocket/TCP
Endpoints:         10.44.0.1:9090
Session Affinity:  None
Events:            <none>

When I try acess with a golang sub
network Error : dial tcp: lookup mosquitto on 10.96.0.10:53: read udp 10.36.0.1:49071->10.96.0.10:53: i/o timeout
Edit
I create a new VM and using docker-compose I run a mosquito, if I use external IP in my local machine it works, but if I use inside kubernetes mais golang project using a external IP don't works
Edit 2
I create demo chart using
helm create demo
After that I installed using
helm upgrade -i demo demo --values demo/values.yaml
My result
$ kubectl get pods

NAME                  READY   STATUS    RESTARTS   AGE
demo-fdf6f77b-fbb4c   1/1     Running   0          22s

So I tested
helm test demo
My result
NAME: demo
LAST DEPLOYED: Sat Jan 14 11:20:26 2023
NAMESPACE: default
STATUS: deployed
REVISION: 1
TEST SUITE:     demo-test-connection
Last Started:   Sat Jan 14 11:20:59 2023
Last Completed: Sat Jan 14 11:21:05 2023
Phase:          Failed
NOTES:
1. Get the application URL by running these commands:
  export POD_NAME=$(kubectl get pods --namespace default -l "app.kubernetes.io/name=demo,app.kubernetes.io/instance=demo" -o jsonpath="{.items[0].metadata.name}")
  export CONTAINER_PORT=$(kubectl get pod --namespace default $POD_NAME -o jsonpath="{.spec.containers[0].ports[0].containerPort}")
  echo "Visit http://127.0.0.1:8080 to use your application"
  kubectl --namespace default port-forward $POD_NAME 8080:$CONTAINER_PORT
Error: pod demo-test-connection failed

When I try see the logs
$ kubectl logs -f demo-test-connection
wget: bad address 'demo:80'

I don't where I need to search
This problem occurs when I try access external services


text:
Q: Jenkins PHP Sample Test Project Running ubuntu and followed the directions from here: http://edorian.posterous.com/setting-up-jenkins-for-php-projects
But when I save the configuration I get 500 Error:
Exception: java.lang.RuntimeException: Failed to instantiate class hudson.plugins.git.GitSCM
Any ideas? Jenkins git plugin is installed.
Here is the full stack trace:
Status Code: 500

Exception: java.lang.RuntimeException: Failed to instantiate class hudson.plugins.git.GitSCM from {"":["hudson.plugins.git.util.DefaultBuildChooser","7"],"authorOrCommitter":false,"branches":{"name":"**"},"browser":{"stapler-class":"hudson.plugins.dry.DryPublisher","url":"http://dev.evanta.com/gitweb/?p=mydemo.git"},"buildChooser":{"stapler-class":"hudson.scm.browsers.FishEyeSVN"},"clean":false,"disableSubmodules":false,"excludedRegions":"","excludedUsers":"","gitConfigEmail":"","gitConfigName":"","gitTool":"Default","ignoreNotifyCommit":false,"includedRegions":"","localBranch":"","pruneBranches":false,"recursiveSubmodules":false,"reference":"","relativeTargetDir":"","remotePoll":false,"scmName":"","skipTag":false,"userRemoteConfigs":{"name":"","refspec":"","url":"file:///home/mirey/mydemo"},"value":"1","wipeOutWorkspace":false}
Stacktrace:
javax.servlet.ServletException: java.lang.RuntimeException: Failed to instantiate class hudson.plugins.git.GitSCM from {"":["hudson.plugins.git.util.DefaultBuildChooser","7"],"authorOrCommitter":false,"branches":{"name":"**"},"browser":{"stapler-class":"hudson.plugins.dry.DryPublisher","url":"http://dev.evanta.com/gitweb/?p=mydemo.git"},"buildChooser":{"stapler-class":"hudson.scm.browsers.FishEyeSVN"},"clean":false,"disableSubmodules":false,"excludedRegions":"","excludedUsers":"","gitConfigEmail":"","gitConfigName":"","gitTool":"Default","ignoreNotifyCommit":false,"includedRegions":"","localBranch":"","pruneBranches":false,"recursiveSubmodules":false,"reference":"","relativeTargetDir":"","remotePoll":false,"scmName":"","skipTag":false,"userRemoteConfigs":{"name":"","refspec":"","url":"file:///home/mirey/mydemo"},"value":"1","wipeOutWorkspace":false}
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:616)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:659)
    at org.kohsuke.stapler.MetaClass$6.doDispatch(MetaClass.java:241)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:53)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:574)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:659)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:488)
    at org.kohsuke.stapler.Stapler.service(Stapler.java:162)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:45)
    at winstone.ServletConfiguration.execute(ServletConfiguration.java:248)
    at winstone.RequestDispatcher.forward(RequestDispatcher.java:333)
    at winstone.RequestDispatcher.doFilter(RequestDispatcher.java:376)
    at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:95)
    at hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:87)
    at winstone.FilterConfiguration.execute(FilterConfiguration.java:194)
    at winstone.RequestDispatcher.doFilter(RequestDispatcher.java:366)
    at hudson.security.csrf.CrumbFilter.doFilter(CrumbFilter.java:47)
    at winstone.FilterConfiguration.execute(FilterConfiguration.java:194)
    at winstone.RequestDispatcher.doFilter(RequestDispatcher.java:366)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84)
    at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:76)
    at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:164)
    at winstone.FilterConfiguration.execute(FilterConfiguration.java:194)
    at winstone.RequestDispatcher.doFilter(RequestDispatcher.java:366)
    at org.kohsuke.stapler.compression.CompressionFilter.doFilter(CompressionFilter.java:50)
    at winstone.FilterConfiguration.execute(FilterConfiguration.java:194)
    at winstone.RequestDispatcher.doFilter(RequestDispatcher.java:366)
    at hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:81)
    at winstone.FilterConfiguration.execute(FilterConfiguration.java:194)
    at winstone.RequestDispatcher.doFilter(RequestDispatcher.java:366)
    at winstone.RequestDispatcher.forward(RequestDispatcher.java:331)
    at winstone.RequestHandlerThread.processRequest(RequestHandlerThread.java:215)
    at winstone.RequestHandlerThread.run(RequestHandlerThread.java:138)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at winstone.BoundedExecutorService$1.run(BoundedExecutorService.java:77)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:679)
Caused by: java.lang.RuntimeException: Failed to instantiate class hudson.plugins.git.GitSCM from {"":["hudson.plugins.git.util.DefaultBuildChooser","7"],"authorOrCommitter":false,"branches":{"name":"**"},"browser":{"stapler-class":"hudson.plugins.dry.DryPublisher","url":"http://dev.evanta.com/gitweb/?p=mydemo.git"},"buildChooser":{"stapler-class":"hudson.scm.browsers.FishEyeSVN"},"clean":false,"disableSubmodules":false,"excludedRegions":"","excludedUsers":"","gitConfigEmail":"","gitConfigName":"","gitTool":"Default","ignoreNotifyCommit":false,"includedRegions":"","localBranch":"","pruneBranches":false,"recursiveSubmodules":false,"reference":"","relativeTargetDir":"","remotePoll":false,"scmName":"","skipTag":false,"userRemoteConfigs":{"name":"","refspec":"","url":"file:///home/mirey/mydemo"},"value":"1","wipeOutWorkspace":false}
    at hudson.model.Descriptor.newInstance(Descriptor.java:575)
    at hudson.plugins.git.GitSCM$DescriptorImpl.newInstance(GitSCM.java:1508)
    at hudson.plugins.git.GitSCM$DescriptorImpl.newInstance(GitSCM.java:1438)
    at hudson.scm.SCMS.parseSCM(SCMS.java:63)
    at hudson.model.AbstractProject.submit(AbstractProject.java:1790)
    at hudson.model.Project.submit(Project.java:197)
    at hudson.model.Job.doConfigSubmit(Job.java:990)
    at hudson.model.AbstractProject.doConfigSubmit(AbstractProject.java:699)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:288)
    at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:151)
    at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:90)
    at org.kohsuke.stapler.MetaClass$1.doDispatch(MetaClass.java:111)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:53)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:574)
    ... 39 more
Caused by: java.lang.IllegalArgumentException: Failed to instantiate class hudson.plugins.git.GitSCM from {"":["hudson.plugins.git.util.DefaultBuildChooser","7"],"authorOrCommitter":false,"branches":{"name":"**"},"browser":{"stapler-class":"hudson.plugins.dry.DryPublisher","url":"http://dev.evanta.com/gitweb/?p=mydemo.git"},"buildChooser":{"stapler-class":"hudson.scm.browsers.FishEyeSVN"},"clean":false,"disableSubmodules":false,"excludedRegions":"","excludedUsers":"","gitConfigEmail":"","gitConfigName":"","gitTool":"Default","ignoreNotifyCommit":false,"includedRegions":"","localBranch":"","pruneBranches":false,"recursiveSubmodules":false,"reference":"","relativeTargetDir":"","remotePoll":false,"scmName":"","skipTag":false,"userRemoteConfigs":{"name":"","refspec":"","url":"file:///home/mirey/mydemo"},"value":"1","wipeOutWorkspace":false}
    at org.kohsuke.stapler.RequestImpl$TypePair.convertJSON(RequestImpl.java:633)
    at org.kohsuke.stapler.RequestImpl.bindJSON(RequestImpl.java:377)
    at org.kohsuke.stapler.RequestImpl.bindJSON(RequestImpl.java:373)
    at hudson.model.Descriptor.newInstance(Descriptor.java:566)
    ... 56 more
Caused by: java.lang.IllegalArgumentException: Failed to convert the buildChooser parameter of the constructor public hudson.plugins.git.GitSCM(java.lang.String,java.util.List,java.util.List,hudson.plugins.git.UserMergeOptions,java.lang.Boolean,java.util.Collection,boolean,boolean,hudson.plugins.git.util.BuildChooser,hudson.plugins.git.browser.GitRepositoryBrowser,java.lang.String,boolean,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,boolean,boolean,boolean,boolean,java.lang.String,java.lang.String,boolean,java.lang.String,boolean)
    at org.kohsuke.stapler.RequestImpl$TypePair.convertJSON(RequestImpl.java:627)
    ... 59 more
Caused by: java.lang.IllegalArgumentException: Failed to instantiate class hudson.plugins.git.util.BuildChooser from {"stapler-class":"hudson.scm.browsers.FishEyeSVN"}
    at org.kohsuke.stapler.RequestImpl$TypePair.convertJSON(RequestImpl.java:633)
    at org.kohsuke.stapler.RequestImpl.bindJSON(RequestImpl.java:377)
    at org.kohsuke.stapler.RequestImpl$TypePair.convertJSON(RequestImpl.java:625)
    ... 59 more
Caused by: java.lang.IllegalArgumentException: Specified type class hudson.scm.browsers.FishEyeSVN is not assignable to the expected class hudson.plugins.git.util.BuildChooser
    at org.kohsuke.stapler.RequestImpl$TypePair.convertJSON(RequestImpl.java:603)
    ... 61 more

A: I don't have a Jenkins instance to check this on at the moment, but this line in the stacktrace caught my eye:

Caused by: java.lang.IllegalArgumentException: Specified type class hudson.scm.browsers.FishEyeSVN is not assignable to the expected class hudson.plugins.git.util.BuildChooser

Did you configure a code browser such as FishEye for your job?  If so, does it work if you remove that?

A: I ran into this problem because I was running the task on a (Windows) slave. The slave instance had not been started as an administrator, so it couldn't run administrator-level commands.
After logging into the slave as administrator and restarting the instance, the error seemed to be solved.


text:
Q: Как вернуть true или false из промиса? Как поменять данный метод так, чтобы он при успешном запросе возвращал true или false
const isClient = () => {

    return new Promise((resolve, reject) => {
        stop();
            request('sign')
                .then((data) => {
                    if (data.payload.response) {
                        const level = data.payload.accessLevel;
                        const isClient = level === CLIENT;

                        if (isClient) {
                            startPing();
                     //метод должен возвращать true
                        }
                    }
                     //метод должен возвращать false
                    resolve(isClient);
                })
                .catch(() => {
                  //метод должен возвращать false
                    reject(' error');
                });

    });
}


text:
Q: Finder drops connection to server / network attached storage I am trying to transfer data that takes days to complete and would like to have a permanent connection to my Network Attached Storage device. I can open finder, then go--> connect to server in order to connect to my network attached storage. However, if I return to my computer and there is a login screen, the connection has been dropped. I would like for the data transfer to continue even while I am logged out, and for the disk to be remounted even if the network connection is temporarily dropped.
I have enabled the connection as a login item as described in https://apple.stackexchange.com/a/20667/1942, but it still doesn't automatically mount the device. An answer to another question, https://apple.stackexchange.com/a/210960/1942, suggests writing an AppleScript to automate this, referencing a blog post from 2008 (>10y ago).
What are my options for automating the mounting in 2019?
I have a MacBook Pro + macOS Mojave 10.14.3

A: I resolved the issue of keeping the disk mounted by using the caffeinate command. Caffeinate keeps the system from sleeping as described in the man page.


text: Q: Upload build from itune's testflight for iOS I have uploaded the build to testflight and testing ok but I would like to release testflight build to public use (Public release), Will I have to upload the build again with different build number or I can upload the app from testflight section?


text:
Q: How to synchronize a method in javascript? I am trying to synchronise a singleton.
I would need to make this method like the equivalent of synchronized in java.
What happens to me is that because the socket takes a while, if the first two requests are very close together I get two websockets created. (Then from the third one onwards it takes the instance correctly).

import io from 'socket.io-client';

export default class SocketIo {
  static socket = null;

  static instance = null;

  async initialize() {
    this.socket = await io(`http://${ip}:10300/`, {
      transports: ['websocket'],
    });
  }

  static async getInstance() {
    logger.info('socketIo.api.getInstance: BEGIN');
    if (!this.instance) {
      logger.info('socketIo.api.getInstance: creating new socket instance...');
      try {
        const o = new SocketIo();
        await o.initialize();
        this.instance = o;
        logger.info('socketIo.api.getInstance: socket instance created SUCCESSFULLY');
      } catch (e) {
        moaLog('socketIo.api.getInstance: ERROR: ', e);
        throw e;
      }
    } else {
      logger.info('socketIo.api.getInstance: a socket instance already exists, reusing that one');
    }
    logger.info('socketIo.api.getInstance: END');
    return this.instance;
  }
}

in main.js
var socket1 = SocketIo.getInstance();
var socket2 = SocketIo.getInstance();

// ... after a while
var socket3 = SocketIo.getInstance();

2022-06-16T17:53:40.658Z: socketIo.api.getInstance: BEGIN
2022-06-16T17:53:40.660Z: socketIo.api.getInstance: creating new socket instance...
2022-06-16T17:53:41.140Z: socketIo.api.getInstance: BEGIN
2022-06-16T17:53:41.141Z: socketIo.api.getInstance: creating new socket instance...
2022-06-16T17:53:41.379Z: socketIo.api.getInstance: socket instance created SUCCESSFULLY
2022-06-16T17:53:41.382Z: socketIo.api.getInstance: END
2022-06-16T17:53:41.411Z: socketIo.api.getInstance: socket instance created SUCCESSFULLY
2022-06-16T17:53:41.415Z: socketIo.api.getInstance: END
...
2022-06-16T17:56:13.076Z: socketIo.api.getInstance: BEGIN
2022-06-16T17:56:13.078Z: socketIo.api.getInstance: a socket instance already exists, reusing that one
2022-06-16T17:56:13.079Z: socketIo.api.getInstance: END

And from server view I see two websocket connections.
Any ideas?

A: Below is an attempt to synchronize your singleton. The idea is to store the o.intitialize promise and check if it already has been acquired before.
I added an uid, a random value set in initialize to show that only single instance is created.

class SocketIo {
    static instance = null;
    static _lock = null;

    async initialize() {
        this.uid = Math.random();
    }

    static async getInstance() {
        console.log('socketIo.api.getInstance: BEGIN');
        if (!this.instance) {
            console.log('socketIo.api.getInstance: creating new socket instance...');

            const o = new SocketIo();
            if (!this._lock) {
                this._lock = o.initialize();
                await this._lock;
                this.instance = o;
                console.log('socketIo.api.getInstance: socket instance created SUCCESSFULLY');
                this._lock = null;
            } else {
                await this._lock;
            }
        }
        console.log('socketIo.api.getInstance: END');
        return this.instance;
    }
}

async function Main() {
    var socket1 = SocketIo.getInstance();
    var socket2 = SocketIo.getInstance();

    console.log((await socket1).uid);
    console.log((await socket2).uid);
}

Main()

Compare it to your version:

class SocketIo {
    static instance = null;

    async initialize() {
        this.uid = Math.random();
    }

    static async getInstance() {
        console.log('socketIo.api.getInstance: BEGIN');
        if (!this.instance) {
            console.log('socketIo.api.getInstance: creating new socket instance...');

            const o = new SocketIo();
            await o.initialize();
            this.instance = o;
            console.log('socketIo.api.getInstance: socket instance created SUCCESSFULLY');
        }
        console.log('socketIo.api.getInstance: END');
        return this.instance;
    }
}

async function Main() {
    var socket1 = SocketIo.getInstance();
    var socket2 = SocketIo.getInstance();

    console.log((await socket1).uid);
    console.log((await socket2).uid);
}

Main()

Hope this is what suits you.

A: I solved using async-lock.

import AsyncLock from 'async-lock';
const lock = new AsyncLock();

export default class SocketIo {
  // ...

  static async getInstance() {
    logger.info('socketIo.api.getInstance: BEGIN');
    if (!this.instance) {
      logger.info('socketIo.api.getInstance: creating new socket instance...');
      try {
        await lock.acquire('socketIo', async () => {
          if (!this.instance) {
            const o = new SocketIo();
            await o.initialize();
            this.instance = o;
            logger.info('socketIo.api.getInstance: socket instance created SUCCESSFULLY');
          }
        });
      } catch (e) {
        moaLog('socketIo.api.getInstance: ERROR: ', e);
        throw e;
      }
    } else {
      logger.info('socketIo.api.getInstance: a socket instance already exists, reusing that one');
    }
    logger.info('socketIo.api.getInstance: END');
    return this.instance;
  }
}


text:
Q: SQL: An alternative to Group By approach using Partion By I have a table in a DW system (say AWS SnowFlake):
UPC_CODE    A_PRICE     A_QTY    DATE       COMPANY_CODE    A_CAT
1001        100.25       2     2021-05-06      1             PB
1001        2122.75      10    2021-05-01      1             PB
1002        212.75       5     2021-05-07      2             PT
1002        3100.75      10    2021-05-01      2             PB

What I am looking for is :
For each UPC_CODE and COMPANY_CODE the latest data should be picked up

So the resultant table should be like below:
UPC_CODE    A_PRICE     A_QTY    DATE       COMPANY_CODE    A_CAT
1001        100.25       2     2021-05-06      1             PB
1002        212.75       5     2021-05-07      2             PT

Approach: Below SQL string
SELECT  UPC_CODE,A_PRICE,A_QTY,MAX(DATE) AS F_DATE,COMPANY_CODE,A_CAT
FROM <table_name>
GROUP BY 1,2,3,5,6

Can I have an alternative approach using partionby()?

A: Your current GROUP BY query doesn't really do what you have in mind.  One canonical approach here uses ROW_NUMBER:
WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY UPC_CODE, COMPANY_CODE ORDER BY DATE DESC) rn
    FROM yourTable
)

SELECT UPC_CODE, A_PRICE, A_QTY, DATE, COMPANY_CODE, A_CAT
FROM cte
WHERE rn = 1;

If you did want to use a GROUP BY approach, here is one way to do that:
SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT UPC_CODE, COMPANY_CODE, MAX(DATE) AS MAX_DATE
    FROM yourTable
    GROUP BY UPC_CODE, COMPANY_CODE
) t2
    ON t2.UPC_CODE = t1.UPC_CODE AND
       t2.COMPANY_CODE = t1.COMPANY_CODE AND
       t2.MAX_DATE = t1.DATE;

A: In Snowflake (which your first line suggests), you would use QUALIFY:
SELECT UPC_CODE, A_PRICE, A_QTY, DATE AS F_DATE, COMPANY_CODE, A_CAT
FROM <table_name>
QUALIFY ROW_NUMBER() OVER (PARTITION BYUPC_CODE, A_PRICE, A_QTY, COMPANY_CODE, A_CAT
                           ORDER BY DATE DESC
                          ) = 1;


text:
Q: Why does "Inflator" algorithm fails for UTF-8 encoding? I wrote the following code in order to decompress messages that were zipped using the Deflator algorithm:
  def decompressMsg[V: StringDecoder](msg: String): Try[V] = {
    if (msg.startsWith(CompressionHeader)) {
      logger.debug(s"Message before decompression is: ${msg}")
      val compressedByteArray =
        msg.drop(CompressionHeader.length).getBytes(StandardCharsets.UTF_8)
      val inflaterInputStream = new InflaterInputStream(
        new ByteArrayInputStream(compressedByteArray)
      )
      val decompressedByteArray = readDataFromInflaterInputStream(inflaterInputStream)

      StringDecoder.decode[V](new String(decompressedByteArray, StandardCharsets.UTF_8).tap {
        decompressedMsg => logger.info(s"Message after decompression is: ${decompressedMsg}")
      })
    } else {
      StringDecoder.decode[V](msg)
    }
  }

private def readDataFromInflaterInputStream(
      inflaterInputStream: InflaterInputStream
  ): Array[Byte] = {
    val outputStream = new ByteArrayOutputStream
    var runLoop = true
    while (runLoop) {
      val buffer = new Array[Byte](BufferSize)
      val len = inflaterInputStream.read(buffer) // ERROR IS THROWN FROM THIS LINE!!
      outputStream.write(buffer, 0, len)
      if (len < BufferSize) runLoop = false
    }
    outputStream.toByteArray
  }

The input argument 'msg' was compressed using the Deflator. The above code fails with the error message:

invalid stored block lengths java.util.zip.ZipException: invalid
stored block lengths

After I saw this thread, I changed StandardCharsets.UTF_8 to StandardCharsets.ISO_8859_1 and surprisingly, the code passed and returned the desired behaviour.
I don't want to work with an encoding different than UTF_8. Do you have an idea how to make my code work with UTF_8 encoding?


text:
Q: Dump Assembly of given c++ line(s) Say I have code like this (notice that in the editor I can see line numbers)
//File example_optimization.cpp

#1 int spreadi = (d_ai - d_bi);
#2 int transactionCosti = spreadi / (spreadi < 10 ? 1 : 10);

If the compiler is an optimizing compiler and the correct flags are set, I want to prove to myself that the division by 1 is not actually taking place.
Is there a tool in linux (or a combination of tools that can be used through a pipe) where I can say something like:
ctoassembler -c g++ -l 1 2 example_optimization.cpp

So this command says, call ctoassembler use compiler and linker gnu g++, and dump lines 1 through 2 of c++ file example_optimization.cpp. The default is to output the assembler code to stdout.
I don't really care what the usage is. I am interested in being able to see what my code is turned into by a compiler without having to search for it myself.
I don't mind using object files if that makes it easier, but somehow it is preferable to display the c++ source code and the corresponding assembler code "side-by-side".

A: GCC will will stop with the produced assembler files:

-S Stop after the stage of compilation proper; do not assemble. The output is in the form of an assembler code file for each non-assembler
  input file specified. By default, the assembler file name for a source
  file is made by replacing the suffix '.c', '.i', etc., with '.s'.
Input files that don't require compilation are ignored.

Source: https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#Overall-Options
Your other option is just to debug the program and have a look at the assembler.

A: Run the code through gdb, putting a break point at the line of C you want, run, then type disassemble to view the next few lines of code.


text:
Q: Angular: Reference singleton in validator from library I have multiple Angular applications which all reference the same GraphQL API (using Apollo) and decided to migrate the API service layer to a shared library.  As part of this service layer, I am exporting a validation function called "ApiValidator" which is used to trigger an error state in forms.
The way it works is whenever an error is encountered from the API, the response will register it to an observable in an ErrorService singleton.  The ApiValidator function returns a promise checks ErrorService for any errors that have a matching "field" property, and returns the errors if so.
This worked perfectly when everything was at an app level, however after migrating to the library, the validator creates a new instance of the singleton each time.  This is because I'm using Injector.create with "useClass" to get a reference to the service in the validator.  I cannot get "useExisting" to work, however, without a circular dependency and run into the same issues trying to use DI via a constructor in a wrapper service as well.
I wasn't sure how to effectively set this up to provide a working example on stackblitz or something given that it is across a private library and application - happy to post the code on there if it would help.  For now, I've posted all the relevant parts below.
Thank you so much for any insight or help in advance!
Library Code
ErrorService
@Injectable({
  providedIn: 'root'
})
export class ErrorService {
  /**
   * An observable list of response errors returned from the graphql API
   */
  private errors: BehaviorSubject<GraphQLResponseError[]> = new BehaviorSubject<GraphQLResponseError[]>([]);

  /**
   * Get any errors on the page
   * @return An observable of the current errors on the page
   */
  public getErrors(): Observable<GraphQLResponseError[]> {
    return this.errors;
  }

  /**
   * Get only field message errors for forms
   * @return An observable of current field errors on the page
   */
  public getFieldErrors(): Observable<GraphQLResponseError[]> {
      return this.errors.pipe(map((error: GraphQLResponseError[]) => {
          return error.filter((err: GraphQLResponseError) => err.context === 'field');
      }));
  }

  /**
   * Get only page message errors
   * @return An observable of current page errors on the page
   */
  public getPageErrors(): Observable<GraphQLResponseError[]> {
      return this.errors.pipe(map((error: GraphQLResponseError[]) => {
          return error.filter((err: GraphQLResponseError) => err.context === 'page');
      }));
  }

  /**
   * Records a response error in the list of errors
   * @param error The error to add to the page
   */
  public recordError(error: GraphQLResponseError): void {
      this.errors.pipe(take(1)).subscribe(errors => {
          if (!errors.includes(error)) {
              errors.push(error);
              this.errors.next(errors);
          }
      });
  }
}

ApiValidator
import { Injector } from '@angular/core';
import { AbstractControl, ValidationErrors } from '@angular/forms';
import { GraphQLResponseError } from '../interfaces/graphql-response-error.interface';
import { take, map } from 'rxjs/operators';
import { ErrorService } from '../services/error.service';

/**
 * Validator which triggers validations based on field errors recorded in the page service
 * @param control The form control which should be validated against this validator
 * @return A promise with the errors associated with the form or null if there are none
 */
export function ApiValidator(control: AbstractControl): Promise<ValidationErrors | null> {
    const injector = Injector.create({
        providers: [{ provide: ErrorService, useClass: ErrorService, deps: [] }]
    });
    const errorService = injector.get(ErrorService);
    // get the name of the control to compare to any errors in the service
    const controlName = (control.parent) ? Object.keys(control.parent.controls).find(name => control === control.parent.controls[name]) : null;

    // return any errors that exist for the current control, or null if none do
    return errorService.getFieldErrors().pipe(take(1), map((errors: GraphQLResponseError[]) => {
        if (errors && errors.length > 0) {
            const fieldErrors = errors.filter((error: GraphQLResponseError) => error.field === controlName);
            return (fieldErrors.length > 0) ? { api: fieldErrors.map(error => error.message).join()} : null;
        }
        return null;
    })).toPromise();
}

ApiModule
import { HttpClientModule } from '@angular/common/http';
import { CommonModule, DatePipe } from '@angular/common';
import { NgModule, Optional, SkipSelf, ModuleWithProviders } from '@angular/core';
import { Apollo, ApolloBoost, ApolloBoostModule, ApolloModule } from 'apollo-angular-boost';
import { GraphQLService } from './services/graphql.service';
import { ApiValidator } from './validators/api.validator';

@NgModule({
  declarations: [
  ],
  imports: [
    HttpClientModule,
    CommonModule,
    ApolloBoostModule,
    ApolloModule
  ],
  providers: [
    DatePipe,
    {
      provide: GraphQLService,
      useClass: GraphQLService,
      deps: [Apollo, ApolloBoost, DatePipe]
    }
  ]
})
export class ApiModule {
  constructor(@Optional() @SkipSelf() parentModule?: ApiModule) {
    if (parentModule) {
      throw new Error(
        'ApiModule is already loaded. Import it in the AppModule only');
    }
  }
}

GraphQLService (relevant part)
import { Injectable, Injector, Inject } from '@angular/core';
import { ApolloBoost, Apollo, gql, WatchQueryFetchPolicy } from 'apollo-angular-boost';
import { Observable, BehaviorSubject } from 'rxjs';
import { map, take } from 'rxjs/operators';
import { GraphQLResponse } from '../interfaces/graphql-response.interface';
import { GraphQLRefetchQuery } from '../interfaces/graphql-refetch-query.interface';
import { DatePipe } from '@angular/common';
import { GraphQLResponseError } from '../interfaces/graphql-response-error.interface';
import { AbstractControl, ValidationErrors } from '@angular/forms';
import { ErrorService } from './error.service';

@Injectable({
  providedIn: 'root'
})
export class GraphQLService {
  /**
   * @var API_DATE_FORMAT The format to use for representing dates
   */
  protected readonly API_DATE_FORMAT = 'yyyy-MM-dd HH:mm:ss';

  /**
   * @ignore
   */
  constructor(
    protected apollo: Apollo,
    protected apolloBoost: ApolloBoost,
    protected datePipe: DatePipe,
    protected errorService: ErrorService
  ) {
  }

  /**
   * Initializes the connection with the graphql API
   * @param url The graphql API endpoint
   * @param token The authorization token to use for requests
   */
  public connect(url: string, token: string = null): void {
    // set environment variables to app context
    this.apolloBoost.create({
      uri: url,
      request: async (operation) => {
        if (token !== null) {
          operation.setContext({
            headers: {
              authorization: token
            }
          });
        }
      },
      onError: ({ graphQLErrors, networkError }) => {
          // if the gql request returned errors, register the errors with the page
          if (graphQLErrors) {
              graphQLErrors.forEach(error => {
                  // if the error has an extensions field, consider it a field-level error
                  if (error.hasOwnProperty('extensions') && error.extensions.hasOwnProperty('field')) {
                      this.errorService.recordError({
                          context: 'field',
                          message: error.message,
                          field: error.extensions.field
                      });
                  }
                  // else, consider a page level error
                  else {
                      this.errorService.recordError({
                          context: 'page',
                          message: error.message
                      });
                  }
              });
          }
          // if there were network errors, register those with the page
          // note, it doesn't seem to work correctly with true network errors
          // and we catch these in the api.interceptor for now
          if (networkError) {
              this.errorService.recordError({
                  context: 'page',
                  message: networkError.message
              });
          }
      }
    });
  }
}

Application Code
AppModule
import { HttpClientModule, HttpClient, HTTP_INTERCEPTORS } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { NgModule, APP_INITIALIZER, Injector } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule } from '@angular/router';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MAT_FORM_FIELD_DEFAULT_OPTIONS } from '@angular/material/form-field';
import { CookieService } from 'ngx-cookie-service';
import { environment } from '../environments/environment';
import { GraphQLService, ApiModule } from '@angular/library';
import { initializeAuthentication, AppContextService, AuthInterceptor } from '@application/core';
import { SharedModule } from '@application/shared';
import { LayoutModule } from './layout/layout.module';
import { routes } from './app.routing';
import { AppComponent } from './app.component';
import { DashboardComponent } from './pages/dashboard/dashboard.component';

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent
  ],
  imports: [
    RouterModule.forRoot(routes),
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    CommonModule,
    SharedModule,
    LayoutModule,
    MatTooltipModule,
    ApiModule
  ],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: (appContextService: AppContextService) => function() { appContextService.setEnvironmentVariables(environment); },
      deps: [AppContextService],
      multi: true
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    },
    {
      provide: APP_INITIALIZER,
      useFactory: initializeAuthentication,
      multi: true,
      deps: [HttpClient, AppContextService, CookieService]
    },
    {
      provide: MAT_FORM_FIELD_DEFAULT_OPTIONS,
      useValue: {
        appearance: 'outline'
      }
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor(private gqlService: GraphQLService, private cookieService: CookieService) {
    // if using authorization set token
    const token = (environment.useAuthorization) ? this.cookieService.get('auth') : null;

    // initialize connection with api
    this.gqlService.connect(environment.apiUrl, token);
  }
}

UserForm (relevant part)
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup, FormBuilder, FormArray } from '@angular/forms';
import { take, finalize, catchError } from 'rxjs/operators';
import { ToastrService } from 'ngx-toastr';
import { User, GraphQLResponse, UserService, ApiValidator } from '@application/library';
import { PageMode, PageService } from '@application/core';

@Component({
    selector: 'sm-user-form',
    templateUrl: './user-form.component.html',
    styleUrls: ['./user-form.component.scss']
})
export class UserFormComponent implements OnInit {
    /**
     * @ignore
     */
    constructor(
        private fb: FormBuilder,
        private activatedRoute: ActivatedRoute,
        private router: Router,
        public pageService: PageService,
        private userService: UserService,
        private toastService: ToastrService
    ) {
        // define form structure
        this.form = this.fb.group({
            email: ['', null, ApiValidator],
            password: ['', null, ApiValidator],
            prefix: ['', null, ApiValidator],
            firstName: ['', null, ApiValidator],
            middleName: ['', null, ApiValidator],
            lastName: ['', null, ApiValidator]
        });
    }
}

UserFormTemplate (relevant part)
<div fxLayout="row">
        <mat-form-field fxFlex="10">
            <mat-label>Prefix</mat-label>
            <input matInput formControlName="prefix">
            <mat-error *ngIf="form.get('prefix').hasError('api')">{{form.get('prefix').getError('api')}}</mat-error>
        </mat-form-field>
        <mat-form-field fxFlex="30">
            <mat-label>First Name</mat-label>
            <input matInput formControlName="firstName">
            <mat-error *ngIf="form.get('firstName').hasError('api')">{{form.get('firstName').getError('api')}}</mat-error>
        </mat-form-field>
        <mat-form-field fxFlex="20">
            <mat-label>Middle Name</mat-label>
            <input matInput formControlName="middleName">
            <mat-error *ngIf="form.get('middleName').hasError('api')">{{form.get('middleName').getError('api')}}</mat-error>
        </mat-form-field>
        <mat-form-field fxFlex="30">
            <mat-label>Last Name</mat-label>
            <input matInput formControlName="lastName">
            <mat-error *ngIf="form.get('lastName').hasError('api')">{{form.get('lastName').getError('api')}}</mat-error>
        </mat-form-field>
        <mat-form-field fxFlex="10">
            <mat-label>Suffix</mat-label>
            <input matInput formControlName="suffix">
            <mat-error *ngIf="form.get('suffix').hasError('api')">{{form.get('suffix').getError('api')}}</mat-error>
        </mat-form-field>
    </div>

A: I was finally able to solve this.  No combination of approaches using providers configurations, injector metadata, etc. was stopping the issue with the validator creating new instances of the ErrorService.
The main issue was that since I was using Injector.create(), it was creating a new instance of the injector itself - which meant that any reference to singletons didn't exist in that injector forcing a new instance every time.  I was not able to successfully get the service into the validator function, however, via providers/etc.
So, to fix the problem, I used a service locator pattern and created a static reference to the injector from the module, then directly used that static reference to access the singleton service (Originally discovered this approach a couple years back from Inject a service manually ).
First, I created a new utility class:
import {Injector} from '@angular/core';

export class ServiceLocator {
    static injector: Injector = null;
}

Then, in the constructor in ApiModule:
  constructor(private injector: Injector, @Optional() @SkipSelf() parentModule?: ApiModule) {
    if (parentModule) {
      throw new Error(
        'ApiModule is already loaded. Import it in the AppModule only');
    }

    // create a static reference to the module injector that can be used to reliably retrieve singleton classes throughout the library
    ServiceLocator.injector = this.injector;
  }

And in ApiValidator, replace this part:
    const injector = Injector.create({
        providers: [{ provide: ErrorService, useClass: ErrorService, deps: [] }]
    });
    const errorService = injector.get(ErrorService);

with the reference to the static injector:
    const errorService = ServiceLocator.injector.get(ErrorService);

Finally, updated the GraphQLService to also use the same static injector:
  constructor(
    protected apollo: Apollo,
    protected apolloBoost: ApolloBoost,
    protected datePipe: DatePipe
  ) {
    this.errorService = ServiceLocator.injector.get(ErrorService);
  }

... and now everything shares the same instance of ErrorService, letting the validator correctly reference errors triggered by graphqlservice (or anything else).
I'm sure there's probably a more elegant or "correct" way to do this - so if there is a better way, I'm certainly appreciative of suggestion.  Otherwise, I hope someone can find this useful.


text:
Q: Setting values in feature class attribute table to null I've created a point-data feature class (fc) containing data from a simple .txt file using ArcPy as follows:
arcpy.CreateFeatureclass_management(out_path= outPath, out_name= 'fcTest', geometry_type= "POINT", spatial_reference= spatRef, has_m= m, has_z= z)

I've read the text file to create fields and fill each field with data:
#lstFields= data from the text file
#fNames= list of fieldnames
#fClass= list of datatypes
for i in range(len(fNames)):
    arcpy.AddField_management(fcTest, fieldN, fieldT)

Let's say the .txt file contains the xy coordinates and two fields: fA and fB
with arcpy.da.InsertCursor('fcTest', ("SHAPE@XY", "fA", "fB")) as cursor:
    for point in lstFields:
        vals= point.split(";")
        x= float(vals[0])
        y= float(vals[1])
        a= int(vals[2])
        b= float(vals[3])
        rowValue= [(x, y), a, b]
        cursor.insertRow(rowValue)

So far so good. However, some values of fA and fB have value 9999, which actually means 'no data'.
How do I convert the 9999 values to a 'real' NoData value?
I thought
setNull(field_name)

might be it, but I can't get it to work. See ArcGIS help here. I tried something like:
with arcpy.da.UpdateCursor('fcTest', ("fA", "fB")) as cursor:
    for row in cursor:
        for i in range(len(row)):
            if row[i] == 9999:
                row.setNull(row[i])
                cursor.updateRow(row)
except Exception as e:
    print e.message

Which gives:
'list' object has no attribute 'setNull'

I'm new to ArcPy and have based most of the above on the Programming ArcGIS10.1 with Python Cookbook by E. Pimpler.

This works flawlessly:
with arcpy.da.UpdateCursor('fcTest', ("fA", "fB")) as cursor:
    for row in cursor:
        for i in range(len(row)):
            if row[i] == 9999:
                row[i] = None
                cursor.updateRow(row)
except Exception as e:
    print e.message

A: You could try:
if row[i] == 9999:
   row[i] = None
   cursor.updateRow(row)

A: The original error is indicating that setNull is not a method for arcpy.da.UpdateCursor, but it is a method for arcpy.UpdateCursor (no "da").


text:
Q: SQL Server 2012 database 3 mirroring questions I've been looking for the answer to these three questions but just cant find a straight answer..

*

*When mirroring with a witness, does all three SQL Server editions have to have the same name? I.E at the moment I have 3 servers labeled ABC-SERVER1, ABC-SERVER2, ABC-SERVER3. My main server is called SQL-SERVER3 on server3, would I then have to have the named instance SQL-SERVER3 running on ABC-SERVER2 and 1?

*If the SQL Server instances don't have to be labeled all the same i.e they can be (SQL ABC-SERVER1), (ABC SQL-SERVER2) etc... If you are using a program for example MS Access and you connect to a server for example server3, how would access know where to go if server3 was offline?

*As I understand it you can have 2 SQL Server versions running at any one time from the 1 licence, as long as only 1 instance of SQL Server is in use at any one time. To get a witness running I would have to use a SQL Server Express edition or buy another licence, is that correct?
Thanks in advance for taking your time out to read this....

A: You can use SQL Server Express for the witness.
You only need a single license so long as you never use the mirror server for anything other than a mirror, and only failover at most once in 90 days.
The names of the servers, and the names of the SQL instances are irrelevant.
Access can somewhat automatically use the failover server as long as the connection string for the linked tables uses the SQL Native Client and the correct syntax:
Failover Partner=myMirrorServerAddress;

See http://www.connectionstrings.com for more info.


text:
Q: Account email verification - what to check for? I have it working to a point where I think it's usable and I'm quite happy with it.
With that said, I noticed a few things. Most if not all places validate against email or username along with an auto-generated hash code that's X chars long. The URL I send the user looks like the following.
http://www.example.com/account/confirm/bob/cbv54c09023DpW
However, you wouldn't want to verify the account unless the user logs in successfully. So if  hit that URL and I'm not logged in, it's going to force me to log in prior to validation. My question is, if that's the case, I would rather validate the account by using the "logged in" username (or email) and the confirmation code that gets sent out.
I ask because I noticed sites like Twitter and Facebook will send such notices but if you attempt to modify the URL (i.e. example.com/account/confirm/sue/cbv54c09023DpW), it'll log you in but will tell you "Can't validate Sue's account while logged in as Bob" or something similar. How are you guys accomplishing this? Does it make sense to pass the username/email into the URL string?

A: Why not? It's looking for a combination of both datas to confirm; so there's less a chance of security flaws in it. You could check if they're logged in or not, AND check if the username and auth code match the database data.

A: I'm just going to send the hash code only


text:
Q: Mac GridLabD installation error at % make -j8 I am trying to build GridLabD on my mac, but get a range or warnings and errors at the step "% make -j8". It is a long log, but below is how it starts (couldn't find gridlabd tag). I followed steps in Is it possible to run GridLab-D on macOS Catalina?, but got the same error at the "make" command.  I appreciate any help.
% make -j8
/bin/bash -c "source utilities/build_number . gldcore/build.h"
Updating gldcore/build.h: revision 19053 (d7f83006:develop:Mod)
/Users/hei06j/Documents/repositories/remote/gridlab-d
/Applications/Xcode.app/Contents/Developer/usr/bin/make  all-am
  CXX      gldcore/gridlabd-convert.o
  CC       gldcore/gridlabd-instance_slave.o
  CC       gldcore/gridlabd-interpolate.o
  CXX      gldcore/gridlabd-job.o
  CC       gldcore/gridlabd-kml.o
  CC       gldcore/gridlabd-legal.o
  CC       gldcore/gridlabd-linkage.o
  CXX      gldcore/gridlabd-link.o
  CC       gldcore/gridlabd-load.o
  CC       gldcore/gridlabd-loadshape.o
  CXX      gldcore/gridlabd-load_xml.o
  CXX      gldcore/gridlabd-load_xml_handle.o
  CC       gldcore/gridlabd-local.o
  CXX      gldcore/gridlabd-lock.o
  CC       gldcore/gridlabd-main.o
  CC       gldcore/gridlabd-match.o
  CC       gldcore/gridlabd-matlab.o
  CC       gldcore/gridlabd-module.o
  CC       gldcore/gridlabd-object.o
  CC       gldcore/gridlabd-output.o
  CC       gldcore/gridlabd-property.o
  CC       gldcore/gridlabd-random.o
  CC       gldcore/gridlabd-realtime.o
  CXX      gldcore/gridlabd-sanitize.o
  CC       gldcore/gridlabd-save.o
  CC       gldcore/gridlabd-schedule.o
  CC       gldcore/gridlabd-server.o
  CXX      gldcore/gridlabd-setup.o
In file included from gldcore/load_xml.cpp:15:
In file included from ./gldcore/platform.h:57:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/math.h:309:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/type_traits:420:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/cstddef:37:
./version:1:3: error: invalid preprocessing directive
# $Id: VERSION 858 2008-08-28 21:06:13Z d3g637 $
  ^
./version:2:1: error: C++ requires a type specifier for all declarations
MAJOR=3
^
./version:2:8: error: expected ';' after top level declarator
MAJOR=3
       ^
In file included from gldcore/convert.cpp:15:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/math.h:309:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/type_traits:420:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/cstddef:37:
./version:1:3: error: invalid preprocessing directive
# $Id: VERSION 858 2008-08-28 21:06:13Z d3g637 $
  ^
./version:2:1: error: C++ requires a type specifier for all declarations
MAJOR=3
^
In file included from gldcore/load_xml_handle.cpp:18:
In file included from ./gldcore/platform.h:57:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/math.h:309:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/type_traits:420:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/cstddef:37:
./version:./version1::32:: 8: error: error: invalid preprocessing directive
expected ';' after top level declarator
MAJOR=3
       ^
# $Id: VERSION 858 2008-08-28 21:06:13Z d3g637 $
  ^
./version:2:1: error: C++ requires a type specifier for all declarations
MAJOR=3
^
./version:2:8: error: expected ';' after top level declarator
MAJOR=3
       ^
In file included from gldcore/setup.cpp:4:
In file included from ./gldcore/gridlabd.h:91:
In file included from ./gldcore/platform.h:57:
In file included from
...


text:
Q: Is it possible to submit a standard HTML form (using jQuery/Ajax) to another standard HTML form on another website? I would be really grateful for an answer to this question. Is this actually possible?
Let's say website1.com has a very simple form:
<form id="form1" name="form1" method="post">
  <input type="text" name="textfield2" id="textfield2">
  <input type="text" name="textfield" id="textfield">
  <input type="submit" name="submit" id="submit" value="Submit">
</form>

I then duplicate this on website2.com:
<form id="form1" name="form1" method="post">
  <input type="text" name="textfield2" id="textfield2">
  <input type="text" name="textfield" id="textfield">
  <input type="submit" name="submit" id="submit" value="Submit">
</form>

If you change the form action on website2.com to point to website1.com, you can easily submit the form data. That's really easy. However, what solutions could you use if you still wanted to submit the data, but not be taken to website1.com on submitting the form? For example you may want to display a custom success page.
I can only think of using jQuery/Ajax, but then you run into the problems of cross-domain security and if you try and circumvent this by using jsonp, you end up getting errors such as "Uncaught SyntaxError: Unexpected token < ". I can only guess, because you are submitting data to a standard HTML form and there is nothing at the other end to give a proper response.
How on earth would you do this? I've become a bit stuck. Or is it simply a case that this isn't actually possible unless using a server side scripting language such as PHP?

A: I added the following to an htaccess file on the Apache server:
Header set Access-Control-Allow-Origin "*"

Ref: http://enable-cors.org/server_apache.html
I could then just do a standard Ajax call without having to worry about jsonp.
Thank you to @JohnnyAW for the suggestion.


text:
Q: How to assert on callback when using jest.useFakeTimers I'm trying to understand how to correctly unit test a custom debounce method we have:
// function we want to test
function debounce(func, wait = 100) {
  let timeout;

  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(this, args);
    }, wait);
  };
}

Here is the Jest unit test that is failing:
describe('DebounceExample', () => {
  beforeAll(jest.useFakeTimers);
  afterAll(jest.useRealTimers);

  it('should debounce', () => {
    // given
    const data = 'Chuck Norris is faster than you think';
    const debounceTime = 5000;
    const callback = jest.fn();
    const debouncedFunction = debounce(callback, debounceTime);

    // when
    debouncedFunction(data);

    // then
    expect(callback).not.toHaveBeenCalled();

    // when
    jest.runAllTimers(); // jest.advanceTimersByTime(debounceTime);

    // then
    expect(callback).toHaveBeenCalled();
  });
});

Failure:
Error: expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0  Jest

I've also tried the solution here: https://stackoverflow.com/a/52638566/704681 without success
Workaround: the only way I'm able to test it so far:
  it('should denounce - workaround', (done) => {
    // given
    const data = 'Chuck Norris is faster than you think';
    const debounceTime = 5000;
    const callback = jest.fn((param) => {
      // then
      expect(param).toEqual(data);
      done();
    });
    const debouncedFunction = debounce(callback, debounceTime);

    // when
    debouncedFunction(data);

    // then
    expect(callback).not.toHaveBeenCalled();

    // when (see 'then' inside callback implementation)
    jest.runAllTimers(); // jest.advanceTimersByTime(debounceTime);
  });


text:
Q: Objective C why format string as string While working on project code left to me by a previous dev, I have encountered the following construct
-(NSString *)StringCheckWithString:(NSString *)string{

    NSString *string2 = [NSString stringWithFormat:@"%@", string];

    if([string2 length] == 0){
        return @"none";
    }
    else {
        return string2;
    }
}

Can anyone explain why you would do this, it seems significantly overengineered to me and I don't understand why it has been done this way (for clarity, I don't understand why the string is formatted like this, I understand the length check)

A: The argument that is passed in could be any subclass of string, including NSMutableString. This code creates an immutable copy of it. This means that you can store the returned string without having to worry about someone else modifying it.
A better way of doing this would be:
NSString *string2 = [string copy];

According to the NSCopying Protocol reference:

The copy returned is immutable if the consideration "immutable vs.
  mutable" applies to the receiving object.


text:
Q: WAMS can hide some columns? I am using Windows Azure Mobile Services in my Windows 8.1 project, What I need is to hide some columns so that they wont generated at run time to the table at Azure DB.
I tried searching for this but couldn't find any solutions.

A: Do you mean you have some properties in your type in the client which you don't want to be sent to the runtime so that they don't become columns in the corresponding table? If this is the case, you can decorate those properties with the [JsonIgnore] property, and they won't be serialized when the client sends the object to the server (via insert or update), and as such the columns won't be created.
Another option is to make the change in the server side itself, by explicitly deleting the properties of the inserted / updated item in the server script. That would have the same effect. This is an example of such an insert script (the update script would be similar):
function insert(item, user, request) {
    delete item.propertyWhichIDoNotWantToBecomeAColumn;
    request.execute();
}


text:
Q: Manipular arquivo .txt em Ruby e pupular BD? Preciso abrir um arquivo .txt qualquer que tenha um sequência de strings separadas por  ";" e preciso colocar a cada ";" em um vetor para depois criar um laço e inserir no banco.
O que eu tenho:
require 'pg'
require 'active_record'

 = File.open('teste.txt')
f_lines = f.read.split(";")

Conexão com o banco
conn = ActiveRecord::Base.establish_connection(:adapter => 'postgresql',
                                                :username => 'root',
                                                :password => "123",
                                                :host => "127.0.0.1",
                                                :database => "db")

#query = "insert into students (name, registration, room, password) values "+ vetor[]
#simulated = ActiveRecord::Base.connection.execute(query)

PS.: Meu arquivo .txt terá várias linhas.

A: Você estava bem no caminho certo, faltou só o pulo do gato srsrs
Vou utilizar um arquivo de entrada para demonstração
grupos.txt
'Administradores'; 'adm'; true
'Redatores'; 'red'; false
'Editores'; 'edt'; false
'Leitores'; 'lei'; false

Aqui a conexão que você já fez:
require 'pg'
require 'active_record'

file = File.open('grupos.txt')

ActiveRecord::Base.establish_connection(:adapter => 'postgresql',
                                                :username => 'root',
                                                :password => "123",
                                                :host => "127.0.0.1",
                                                :database => "db")

E o pulo do gato:
file.each_line do |line|
  values = line.split(';').join(',')
  insert_sql = "insert into grupos (nome, slug, padrao) values ( #{values} )"
  ActiveRecord::Base.connection.execute insert_sql
end

Resultado:

OTIMIZANDO
Caso seu arquivo não seja pequeno, vale muito a pena usar transaction , esse mesmo exemplo com 1000 linhas demorou 26.221072s para rodar, utilizando transaction levou apenas  0.343375s
Exemplo com transaction:
   ActiveRecord::Base.connection.transaction do
    file.each_line do |line|
      values = line.split(';').join(',')
      insert_sql = "insert into grupos (nome, slug, padrao) values ( #{values} )"
      ActiveRecord::Base.connection.execute insert_sql
    end
  end


text:
Q: Solve: $\sin x - y\cos x = z$ for $x$. I am working on programming a series of algorithms into a project, however I have run into trouble trying to solve this equation for $x$:
$$
\sin x - y\cos x = z
$$
It should be noted that $y$ and $z$ will be known at runtime and that $0 < x < \pi/2$.
I remember doing something like this in calculus, but it has been a while and searching the web has failed to enlighten me.

A: This is possible, but it is certainly not trivial. What we need to do to solve it is turn the left hand $\sin(x)-y\cos(x)$ into something of the form $c\sin(x+b)$ for some constants $c$ and $b$ which can be computed from $y$. This is because there is no way we can invert two "special functions" like $\sin$ and $\cos$ at the same time and thus need to find a different identity.
However, it turns out that this is fairly easy to do; using the identity
$$\sin(x+b)=\sin(x)\cos(b)+\cos(x)\sin(b)$$
which, gives, when multiplied by $c$
$$c\sin(x+b)=c\sin(x)\cos(b)+c\cos(x)\sin(b)$$
and we want the above to equal $\sin(x)-y\cos(x)$ - thus, if we get the coefficients of $\sin(x)$ and $\cos(x)$ right, we are really requiring a simultaneous solution to:
$$c\cos(b) = 1$$
$$c\sin(b) = -y$$
What can be seen by squaring and adding the above two equations is
$$c^2(\cos(b)^2+\sin(b)^2)=c^2=1^2+(-y)^2$$
which yields $c=\sqrt{1+y^2}$. Taking the ratio of the two equations gives
$$\tan(b)=-y$$
so $b=\tan^{-1}(-y)$.
This tells us that we can write
$$\sin(x)-y\cos(x)=\sqrt{1+y^2}\sin(x-\tan^{-1}(y))$$
and to solve for the above equalling $z$ we simply undo the operations in order to receive:
$$x=\sin^{-1}\left(\frac{z}{\sqrt{1+y^2}}\right)+\tan^{-1}(y).$$

A: If
$$
\sin x-y\cos x=z
$$
then
$$
x = \arcsin {z\over\sqrt{1+y^2}}+\arccos {1\over\sqrt{1+y^2}}
$$
To see why, rewrite the top equation as
$$
r(\sin x \cos q - \cos x\sin q) = z.
$$
where $y=r\sin q$ and $r\cos q = 1$. Then $r^2=1+y^2$ and $\cos q=1/r$.
This is equivalent to
$$
\sin(x-q)=z/r
$$
Also notice that $\sqrt{1+y^2}\leq z$ or there is no solution, in other words $y^2\leq z^2-1$.
Numerical check:
package main

import (
    "fmt"
    "math"
)

func main() {
    incx := 0.01
    incy := 0.1
    for x := 0.0; x < math.Pi/2.0; x+=incx {
        for y := 0.0; y < 10.0; y+=incy {
            z := math.Sin(x) - y*math.Cos(x)
            r := math.Sqrt(1 + math.Pow(y, 2))
            q := math.Acos(1/r)
            x2 := math.Asin(z/r) + q
            if x - x2 > 0.0001 {
                fmt.Println(x, x2)
            }
        }
    }
}

A: In general, when you add two sinusoids of the same frequency, you get back another sinusoid of that frequency.  Their phases and amplitudes don't have to be the same.
So first write:
$$\sin(x) - y\cos(x) = z$$
as a more standard amplitude/phase form:
$$\sin(x) - y\sin(\pi/2 - x) = \sin(x) + y\sin(x - \pi/2)$$
$$1~\sin(x + 0) + y~\sin(x - \pi/2) = z$$
And now we have the sum of two sinusoids with amplitude/phase being $1, 0$ and $y, -\pi/2$ (and both have frequency $\frac{1}{2\pi}$).
To add them using polar form , $\angle$, use the formula

$$f(x) = A_1\sin(fx + p_1) + A_2\sin(fx + p_2)$$
  can be simplified as
  $$f(x) = A_3\sin(fx + p_3)$$
  given that
  $$A_1 ~\angle~p_1 + A_2 ~\angle~p_2 = A_3 ~\angle~p_3$$

So we have
$$A_3 \sin(x + p_3) = z$$
for
$$A_3~\angle~ p_3 = 1~\angle~0 + y~\angle~-\pi/2$$
This is a basic trig problem:

And you get $A_3 = \sqrt{1 + y^2}$ and $p_3 = \arctan(-y)$ so
$$\sqrt{1 + y^2}\sin(x + \arctan(-y)) = z$$
$$x = \arcsin\left(\frac{z}{\sqrt{1 + y^2}}\right) + \arctan(y)$$


text:
Q: Using tflearn, getting ModuleNotFoundError: No module named 'tensorflow.contrib' I'm working with tensorflow==2.2.0rc1 and tflearn==0.3.2 and I keep getting the same error when importing:
ModuleNotFoundError: No module named 'tensorflow.contrib'

Although I import the packages:
import tflearn
import tensorflow

A: From TFLearn's documentation and your error, it's probably only compatible with Tensorflow < 2, so reinstall tensorflow of version 1.x.
tensorflow.contrib was deprecated in Tensorflow 2.


text:
Q: How do I group a list of numeric values into ranges? I do have a big list of numeric values (including duplicates) and I do want to group them into  ranges in order to see if how do they distribute.
Let's say there are 1000 values ranging from 0 to 2.000.000 and I do want to group them.
How can I achieve this, preferably in Excel or SQL.

A: Why group them? Instead, how about estimate the probability density function (PDF) of the distributions from which the data arise? Here's an R-based example:
set.seed(123)
dat <- c(sample(2000000, 500), rnorm(100, 1000000, 1000),
         rnorm(150, 1500000, 100),rnorm(150, 500000, 10),
         rnorm(180, 10000, 10), rnorm(10, 1000, 5), 1:10)
dens <- density(dat)
plot(dens)

If the data are strictly bounded (0, 2,000,000) then the kernel density estimate is perhaps not best suited. You could fudge things by asking it to only evaluate the density between the bounds:
dens2 <- density(dat, from = 0, to = 2000000)
plot(dens2)

Alternatively there is the histogram - a coarse version of the kernel density. What you specifically talk about is binning your data. There are lots of rules/approaches to selecting equal-width bins (i.e. the number of bins) from the data. In R the default is Sturges rule, but it also includes the Freedman-Diaconis rule and Scott's rule. There are others as well - see the Wikipedia page on histograms.
hist(dat)

If you are not interested in the kernel density plot or the histogram per se, rather just the binned data, then you can compute the number of bins using the nclass.X family of functions where X is one of Sturges, scott or FD. And then use cut() to bin your data:
cut.dat <- cut(dat, breaks = nclass.FD(dat), include.lowest = TRUE)
table(cut.dat)

which gives:
> cut.dat
  [-2e+03,2.21e+05] (2.21e+05,4.43e+05] (4.43e+05,6.65e+05] (6.65e+05,8.88e+05]
                247                  60                 215                  61
(8.88e+05,1.11e+06] (1.11e+06,1.33e+06] (1.33e+06,1.56e+06] (1.56e+06,1.78e+06]
                153                  51                 205                  50
   (1.78e+06,2e+06]
                 58

in R.
However, binning is fraught with problems, most notably; How do you know that your choice of bins hasn't influenced the resulting impression you get of the way the data are distributed?

A: I'll assume that you've already determined the number of categories you'll use. Let's say you want to use 20 categories. Then they will be:

*

*Category 1: [0 - 100,000)

*Category 2: [100,000 - 200,000)

*Category 3: [200,000 - 300,000)

*...

*Category 19: [1,800,000 - 1,900,000)

*Category 20: [1,900,000 - 2,000,000]

Note that the label of each category can be defined as
FLOOR (x / category_size) + 1

This is trivial to define as a computed column in SQL or as a formula in Excel.
Note that the last category is infinitesimally larger than the others, since it is closed on both sides. If you happen to get a value of exactly 2,000,000 you might erroneously classify it as falling into category 21, so you have to treat this exception with an ugly "IF" (in Excel) or "CASE" (in SQL).

A: Another option using Excel that gives you a fair amount of flexibility over the number & size of bins is the =frequency(data_array, bins_array) function. It is an array function that expects two arguments. The first argument is your data, the second is your bins that you define.
Let's assume your data is in cells A1 - A1000 and create bins in cells B1 - B20. You would want to highlight cells C1 - C21 and then type something like =FREQUENCY(A1:A100, B1:B21). Unlike normal functions, array functions must be entered with the key combination SHIFT + CTRL + ENTER. You should see the counts fill down for all bins, if not - you most likely only hit enter and the first cell is calculated.
There are plenty of good tutorials online explaining this in more detail, here's a decent one.

A: You have requested an Excel or SQL solution.  The easiest way in Excel is to use its "Analysis" add-in to create a histogram.  It will automatically create the bins (ranges of values) but, optionally, accepts a list of bin cutpoints as input and uses them.  The output includes a parallel list of bin counts.  This is especially handy for irregular-width bins.
This is a one-off calculation: if the data change or the cutpoints change, you have to go through the entire dialog again.  A more flexible option is to use COUNTIF to count all values less than or equal to any given bin cutpoint.  The first differences of such an array give the bin counts.
Here is a working example.  The data are in a column named "Simulation_Z" (which in this particular case is defined to be an entire column, such as $C:$C).  The formulae shown below are copied from columns L2:N10 of a sheet in the same workbook.  They were created by copying the first one downward (but notice the special formula for the first count in N3).
Cut Count up                            Count
-3.0    =COUNTIF(Simulation_Z, "<=" & L3)   =M3
-2.0    =COUNTIF(Simulation_Z, "<=" & L4)   =M4-M3
-1.0    =COUNTIF(Simulation_Z, "<=" & L5)   =M5-M4
 0.0    =COUNTIF(Simulation_Z, "<=" & L6)   =M6-M5
 1.0    =COUNTIF(Simulation_Z, "<=" & L7)   =M7-M6
 2.0    =COUNTIF(Simulation_Z, "<=" & L8)   =M8-M7
 3.0    =COUNTIF(Simulation_Z, "<=" & L9)   =M9-M8
=MAX(Simulation_Z)  =COUNTIF(Simulation_Z, "<=" & L10)  =M10-M9

Column L ("Cut") stipulates the upper limits of each bin.
This procedure simultaneously defines the bins and computes their counts, which are then available for further testing (e.g., $\chi\text{-squared}$) or plotting.

A: In Excel, a simple way to group numeric data into bins is via the Pivot Table. Pull the numeric variable into the "row labels". Now right-click on any of the values in this right column and choose "Group". You can set the min and max of the overall range and the bin size (equal bins widths for all data).

A: Although the FLOOR answer is probably nicer, you can do this with a vlookup.
The first column of the lookup table (shown below) is the lower bound of each of your bins. Then you enter a formula to make the labels in the second column (formula shown, and result of the formula in the third column -- obviously you'd only have two columns.) Note the last two rows of the table are wonky -- the second last has a different formula because you want it to be the unbounded "greater than" case (unless you don't want that, then change the formula - you can set this up however you like).
You would enter this formula (assuming the values you want to bin are in Col A, and the lookup table is in cols F:G somewhere. Note the TRUE parameter, so vlookup doesn't need to find an exact match.
=VLOOKUP(A2,$F$2:$G$24,2,TRUE)

This is what the lookup table would look like:
Floor   Formula             Result of Formula (label)
    0   =F2 & " - " &F3-1   0 - 49999
50000   =F3 & " - " &F4-1   50000 - 99999
100000  =F4 & " - " &F5-1   100000 - 149999
150000  =F5 & " - " &F6-1   150000 - 199999
200000  =F6 & " - " &F7-1   200000 - 249999
250000  =F7 & " - " &F8-1   250000 - 299999
300000  =F8 & " - " &F9-1   300000 - 349999
....
1100000 =" >= " &F25        >= 1100000

A: To answer this for SQL, you really need to have a database that understands a window function (part of SQL:2003), such as MS SQL Server or PostgreSQL.
To group val from table data into, say, 13 equal-width bins, use the ntile window function:
SELECT val, ntile(13) OVER (ORDER BY val)
FROM data;

       val        | ntile
------------------+-------
 8908.96283090115 |     1
 9090.72533249855 |     1
  9620.1803535223 |     1
  11068.768799305 |     1
...
 1994248.56621772 |    13
 1994786.21594608 |    13
 1995945.97052783 |    13
 1997640.62557369 |    13
(1000 rows)

A: that is simply to use this formula in excel:
Ceiling(Cell(i,j),1000)/1000
Then you have group of 1000: 1, 2, 3, ...


text:
Q: Simple PyQt5 GUI Looks Like GTK When Compiling with PyInstaller on macOS and Windows I used to build using PyInstaller and everything was working perfectly. I don't know what has changed. I had a pre-configured VM that I used to compile and now it doesn't work as expected.
When I build now, the GUI looks like GTK (very old looking GUI) for some reason.
I've made a VERY simple PyQt5 app and made a clean VM with Python 3.6.4, PyInstaller, PyQt5, and six.
I've tried on macOS 10.10, 10.13, Windows 10, Windows 10 VM.
I've tried --hidden-import=PyQt5
I've tried everything again using Python 3.6.3 and PyInstaller 3.3
I've tried everything again using Python 3.6.3 and PyInstaller dev
I'm running out of things to test.
Here is the simple PyQt5 app sample app:
PROBLEM.zip
Here is the build output:
    C:\Users\Admin\Desktop\PROBLEM>C:\Python\python -m PyInstaller --paths C:\Python\Lib\site-packages\PyQt5\Qt\bin --add-binary *.dll;. --clean --noupx --name "TEST" main.py
250 INFO: PyInstaller: 3.4.dev0+1652c1968
265 INFO: Python: 3.6.4
265 INFO: Platform: Windows-10-10.0.16299-SP0
265 INFO: wrote C:\Users\Admin\Desktop\PROBLEM\TEST.spec
265 INFO: UPX is not available.
265 INFO: Removing temporary files and cleaning cache in C:\Users\Admin\AppData\Roaming\pyinstaller
296 INFO: Extending PYTHONPATH with paths
['C:\\Users\\Admin\\Desktop\\PROBLEM',
 'C:\\Python\\Lib\\site-packages\\PyQt5\\Qt\\bin',
 'C:\\Users\\Admin\\Desktop\\PROBLEM']
296 INFO: checking Analysis
312 INFO: Building Analysis because out00-Analysis.toc is non existent
312 INFO: Initializing module dependency graph...
312 INFO: Initializing module graph hooks...
312 INFO: Analyzing base_library.zip ...
3421 INFO: running Analysis out00-Analysis.toc
3437 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
  required by C:\Python\python.exe
3609 INFO: Caching module hooks...
3609 INFO: Analyzing C:\Users\Admin\Desktop\PROBLEM\main.py
3640 INFO: Loading module hooks...
3640 INFO: Loading module hook "hook-encodings.py"...
3718 INFO: Loading module hook "hook-pydoc.py"...
3718 INFO: Loading module hook "hook-PyQt5.py"...
3718 INFO: Loading module hook "hook-PyQt5.Qt.py"...
3718 INFO: Loading module hook "hook-PyQt5.QtCore.py"...
3782 INFO: Loading module hook "hook-PyQt5.QtGui.py"...
4125 INFO: Loading module hook "hook-PyQt5.QtPrintSupport.py"...
4171 INFO: Loading module hook "hook-PyQt5.QtWidgets.py"...
4187 INFO: Loading module hook "hook-xml.py"...
4422 INFO: Looking for ctypes DLLs
4437 INFO: Analyzing run-time hooks ...
4437 INFO: Including run-time hook 'pyi_rth_qt5.py'
4437 INFO: Looking for dynamic libraries
5187 INFO: Looking for eggs
5187 INFO: Using Python library C:\Python\python36.dll
5187 INFO: Found binding redirects:
[]
5203 INFO: Warnings written to C:\Users\Admin\Desktop\PROBLEM\build\TEST\warnTEST.txt
5250 INFO: Graph cross-reference written to C:\Users\Admin\Desktop\PROBLEM\build\TEST\xref-TEST.html
5281 INFO: Appending 'binaries' from .spec
5328 INFO: checking PYZ
5328 INFO: Building PYZ because out00-PYZ.toc is non existent
5328 INFO: Building PYZ (ZlibArchive) C:\Users\Admin\Desktop\PROBLEM\build\TEST\out00-PYZ.pyz
5890 INFO: Building PYZ (ZlibArchive) C:\Users\Admin\Desktop\PROBLEM\build\TEST\out00-PYZ.pyz completed successfully.
5906 INFO: checking PKG
5906 INFO: Building PKG because out00-PKG.toc is non existent
5906 INFO: Building PKG (CArchive) out00-PKG.pkg
5937 INFO: Building PKG (CArchive) out00-PKG.pkg completed successfully.
5953 INFO: Bootloader C:\Python\lib\site-packages\PyInstaller\bootloader\Windows-32bit\run.exe
5953 INFO: checking EXE
5953 INFO: Building EXE because out00-EXE.toc is non existent
5953 INFO: Building EXE from out00-EXE.toc
5953 INFO: Appending archive to EXE C:\Users\Admin\Desktop\PROBLEM\build\TEST\TEST.exe
5984 INFO: Building EXE from out00-EXE.toc completed successfully.
6000 INFO: checking COLLECT
6000 INFO: Building COLLECT because out00-COLLECT.toc is non existent
6000 INFO: Building COLLECT out00-COLLECT.toc
8703 INFO: Building COLLECT out00-COLLECT.toc completed successfully.

Any help is greatly appreciated.

A: Currently PyInstaller 3.3.1 is not compatible with the latest version of PyQt5 (after version 5.9.2). They are working on a new PyInstaller hook for PyQt5.
If you are using Pyinstaller 3.3 or 3.3.1 then you have to use these versions of SIP and PyQt5 (order of installation matters).
On Windows:
sip-4.19.6-cp36-none-win32.whl
PyQt5-5.9.2-5.9.3-cp35.cp36.cp37-none-win32.whl
pyqt5_tools-5.9.0.1.2-cp36-none-win32.whl (if you need the PyQt designer)

On macOS:
sip-4.19.8-cp36-cp36m-macosx_10_6_intel.whl
PyQt5-5.9.2-5.9.3-cp35.cp36.cp37-abi3-macosx_10_6_intel.whl


text:
Q: Flex Combobox Binding Issues In my application i used combobox and adding value using dataprovider like
   id="teamComboBox" dataProvider="{xml_teamcoupon.lastResult.coupon.teamcoupon_name}

my xml like this
<pick15>
<coupon>
<teamcoupon_id>1</teamcoupon_id>
<teamcoupon_name>teamcoupon1</teamcoupon_name>
coupon></pick15>

so comobobox shows team coupon name . But what i want, ifi  choose team coupon name then Correspond teamcoupon id how can i get . i trid teamComboBox.selectedItem.teamcoupon_id but shows error

A: Bind to the coupon element, rather than the teamcoupon_name element, and then use the labelField attribute of the combobox to reference teamcoupon_name.
<mx:ComboBox dataProvider="{xml_teamcoupon.lastResult.coupon}" labelField="teamcoupon_name" />

Now, you can get the currently selected element using combobox.selectedItem, and the id by referencing combobox.selectedItem.teamcoupon_id.

A: Since the id node is on the same level as the name node, you'll need to reference the parent node first.
Something like:
teamComboBox.selectedItem.parent().teamcoupon_id


text:
Q: When does computation of Euler characteristic of structural sheaf require non-singular algebraic surface? This is related to Ueno's Algebraic Geometry 2, Chpt 6, Thm 6.25.
Let $X$ be a non-singular algebraic surface. $C_1,C_2$ 2 algebraic curves over $X$ do not have a common component. Then $C_1\cdot C_2$ intersection is defined by $\chi(X,O_X)+\chi(X,O_X(-C_1-C_2))-\chi(X,O_X(-C_1))-\chi(X,O_X(-C_2))$.
It is not too hard to see the following exact sequence is exact.
$0\to O_X(-C_1-C_2)\to O_X(-C_1)\oplus O_X(-C_2)\to O_X\to O_{C_1\cap C_2}\to 0$
$O(-D)$ is the ideal sheaf associated to curve $D$. The first map on affine chart is obviously given by $x\to (x,x)$. The second map is given by difference for comparison.
$\textbf{Q1:}$ The book says above exact sequence follows from $0\to O_X(-C_1)\to O_X\to O_{C_1}\to 0$ (1) and $0\to O_X(-C_2)\to O_X\to O_{C_2}\to 0$ (2). My guess is considering $(1)\otimes_{O_X}O_{C_2}$. Then I have $O_X(-C_1)\otimes O_{C_2}\to O_{C_2}\to O_{C_1\cap C_2}\to 0$. Now $O_X\to O_{C_2}$ is surjection. The only trouble is to find out kernel of total composition $O_X\to O_{C_1\cap C_2}\to 0$. I do not see how to splice sequence to obtain the exact sequence. However, given the sequence above, I can easily check exactness.
$\textbf{Q2:}$ When is $X$ non-singularness used in the computation? Computation of $\chi(X,O_X)$ uses only Cech covering. This computation does not seem to invoke non-singularness of $X$. Ueno has done cohomology computation of $P^n_k$ over a field $k$ so far. However, it does not seem to be the case that the computation truly invokes $P^n_k$ smooth, though smoothness is already tangled with polynomial ring structural locally.


text:
Q: linkedin media upload using curl command as binary data I am trying to post media to linkedin using curl command, how can i pass media as binary data instead of passing filepath?
 let header = '';
        if (fileType === 'image') {
          header = `Authorization: Bearer ${token}`;
        } else if (fileType === 'video') {
          header = 'Content-Type:application/octet-stream';
        }
const curlCommand = `curl -i --upload-file ${media.filepath} -H '${header}' '${url}'`;
    child.exec(curlCommand, (error, stdout, stderr) => {
          if (error) {
            console.log(`error: ${error.message}`);
            return false;
          }
          if (stderr) {
            return true;
          }
    });


text:
Q: Derivatives question involving tangent Find the derivative of $2^{\tan(1/x)}$. I know that I should replace $\frac1x$ with $u$ and such, but then I can't continue it...

A: Hint: $2^{\tan(1/x)}=e^{(\ln 2)(\tan(1/x)}$.
If $y=e^u$, then by the Chain Rule, $\dfrac{dy}{dx}=e^u \dfrac{du}{dx}$.
Now let $u=(\ln 2)\tan(1/x)$. I think you know how to find $\dfrac{du}{dx}$.
Another way: Let $y=2^{\tan(1/x)}$. Take the natural logarithm of both side. We get
$$\ln y=(\ln 2)\tan(1/x).$$
Now differentiate both sides with respect to $x$. On the left we get $\dfrac{1}{y}\dfrac{dy}{dx}$.


text:
Q: c++ method address vector I'm new at using vector, I need a method that return the addres of the vector, this is the semplifide code:
class:
#include<vector>

class A
{
private:
    std::vector<int> v;
public:
    A()
    {
        for (int i = 0; i < 5; i++)
            v[i] = i;
    }

    std::vector<int> give()
    {
          return v;
    }

    ~A() {}
};

main:
#include <iostream>
#include "class.cpp"

int main(int argc, char **argv)
{
    A a;

    int *vptr = NULL;

    vptr = &a.give()[0];

    std::vector<int> b;

    return 0;
}

this code compile but during the execution a segmentation fault is given

A: This constructor
A(){
    for(int i = 0; i < 5; i++)
        v[i] = i;
}

is invalid because the vector has no yet elements that you could use the subscript operator. More correctly would be to write
A() : v( 5 ) {
    for(int i = 0; i < 5; i++)
        v[i] = i;
}

As for your question then std::vector has member function data that returns the address of its internal buffer with elements.
So you could write
int * give(){ return v.data(); }

or
const int * give() const { return v.data(); }

In main you could write
int *vptr = a.give();

A: You have several big problems here.
First, in the constructor you're trying to access elements of the vector that don't yet exist:
A(){
    for(int i = 0; i < 5; i++)
        v[i] = i;
}

vector isn't the same as map where if the element you are looking for with operator[] doesn't exist a new one is created.  In vector if you use operator[] with an index that doesn't exist you get Undefined Behavior, and a verly likely crash.  You should be inserting items here.  On way is push_back:
A(){
  for (int i = 0; i < 5; ++i)
    v.push_back (i);
}

Next, give() returns a vector by-value:
std::vector<int> give(){
    return v;
}

Which makes a copy of v and returns that copy.  Well that's technically OK, but when you call give() you don't assign the return value to a variable.  What ends up happening is the copy of the vector becomes a temporary object.  As soon as the so-called "full-expression" where the temporary was created is done, the temporary is destroyed.
That full-expression is this:
vptr = &a.give()[0];

So, vptr was assigned the address of the first element of that temporary vector, but as soon as the end of this expression is reached that vector is destroyed and vptr now points to hyperspace.  If you attempt to dereference this wild pointer, you get Undefined Behavior and a very likely segmentation fault.
To fix this, you could let A tell you the address of the first element of the vector:
class A
{
// [...]
public:
  void*  give() { return v.data(); }
};


text:
Q: Instagram Approval I was tasked to develop a web application that has an instagram module in it. The module is supposed to do the following:
1. Display the logged in user timeline
2. Allow user to like and unlike a photo
3. Allow user to comment on a photo
My question is: will the app get approved upon submission or will it be rejected  because it replicates original features?
Thanks

A: There is no API to get user timeline any more, it was deprecated June 1, 2016.
You probably wont get approval since you can do the same on instagram.com, why dont you just use that?
If your app is doing something significant that cannot be done with Instagram app, then there is a chance you will get approved


text:
Q: How to write an if statement in access? I want to state a condition in a new field that if the Date of row 2 is greater than row 1 then Subtract field from row 2 - field from row 1 else leave blank.

A: Try implementing the iif function , which you can insert your conditions in with the general form:
iif ( condition, value_if_true, value_if_false )


text:
Q: Can the inverse Laplace transformation of these functions be found by using the residue theorem? While solving a partial differential equation, I came across the following four functions:
$$ F_1(s) = e^{  k \sqrt{ q^2 + cs^2 } } \tag 1$$
$$ F_2(s) = e^{ -k \sqrt{ q^2 + cs^2 } } \tag 2$$
$$ F_3(s) = e^{  k \sqrt{ q^2 - cs^2 } } \tag 3$$
$$ F_4(s) = e^{ -k \sqrt{ q^2 - cs^2 } } \tag 4$$
where $k$, $q$ and $c$ are constants, and $s$ is the Laplace transformation variable. Because these are not tabular expressions for the inverse Laplace transformation, I started researching ways to evaluate the inverse Laplace transformations in such cases.
Currently, I am studying the residue theorem (along with other parts of complex analysis). According to that theorem, I need to find the poles of my function so I can use it. As I understand it, poles are points at which functions are not defined. This is a problem for my case because all four functions I wrote down are defined for every value of $s$. Does this mean I can not find the inverse Laplace transform for any one of them by using the residue theorem?
To summarize, I am trying to find the inverse Laplace transformation of the functions $(1)$,  $(2)$, $(3)$, and $(4)$. My questions are:
$1.$ Can I use the residue theorem to do that (at least for one of them)?
$2.$ If not, is there some other way I can find the inverse Laplace transformation of these functions?


text:
Q: How to use a method inside service in a child component in angular 6 In backend API some data is there. From front-end, i generate to get a request to read those backend data and show in front-end. For this, i created an Offer component and two child components of this offer component i.e general & special component. I created one service, within that i created one method, inside the method i generate to get a request to connect with backend API. Now when i am trying to import this service to that child component i am getting compilation to fail error in visual studio code saying "ERROR in app/offers/general/general.component.ts:2:30 - error

TS2307: Cannot find module '../event.service'

. Now my question "how to use a service by a child component in the angular application"?
in general.component.ts ->

import { Component, OnInit } from '@angular/core';
import { EventService } from '../event.service';

@Component({
  selector: 'app-general',

  templateUrl: './general.component.html',
  styleUrls: ['./general.component.css']
})
export class GeneralComponent implements OnInit {
  events = [];
  constructor(private _eventservice: EventService ) { }

  ngOnInit() {
    this._eventservice.showGeneralOffers().subscribe(
      res => this.events = res,
      err => console.log(err)
    );
  }

}

in event.service.ts ->

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class EventService {
  private _generalOffersUrl = 'http://localhost:3000/api/general';
  private _specialOffersUrl = 'http://localhost:3000/api/special';

  constructor(private http: HttpClient) { }

  getGeneralOffers() {
    return this.http.get<any>(this._generalOffersUrl);
  }
  getSpecialOffers() {
    return this.http.get<any>(this._specialOffersUrl);
  }
}

A: Seems like issue with the importing service path. (import { EventService } from '../event.service';). Check given path is correct or not.

A: It seems a simple path problem.
Delete import of service in generalComponent costructor, go over EventService, a popup will come out, and click on quick fix, automatically will write the right path.

A: Your relative path to import is wrong, change it to,
import { EventService } from './event.service';


text:
Q: Is there a way to take a fixed date and change it into a date table in Lua without specifically assigning each value? I have a date which is being fed into my script in the following format:
dateTime = "Fri Oct 18 10:08:02 UTC 2019"

Is there a way to reformat this so that I can quickly call each element as I like without explicitly splitting out using string.sub (for example)?
E.g. So that I can:

*

*Subtract one date from another to find out age (using current time and birth/established date)

*Add hours dependant on the timezone (given that I have a timezone in the format "+3")

*Find if the time was between a range (e.g. the request was sent between 9am and 5pm GMT)

A: Lua does not have a built-in date or time type like other languages.
Lua 5.3 Reference Manual 2.1 Values and Types

There are eight basic types in Lua: nil, boolean, number, string,
  function, userdata, thread, and table.

Lua 5.3 Reference Manual 6 Standard Libraries
Either implement them yourself or find existing modules that suit your needs.
A simple way would be to parse your date time string using captures
Checkout http://lua-users.org/wiki/DateAndTime for suggestions.