text:
Q: Make assembly function exception safe My program is written in C++. The program generates assembly functions at runtime (with asmjit library). The assembly functions may call other C++ functions which my throw exceptions.
My question is how to make C++ exception safely propagate through my function. The platform is x86_64/Linux.
I did some test:
C++ file:
#include <stdexcept>
#include <iostream>

extern "C" void asm_function();

extern "C" void throws_exception() {
    throw std::runtime_error("exception incoming.");
}

int main() {
    try {
        asm_function();
        std::cout << "Whoops, asm_function returned unexpectedly\n";
    } catch (std::exception& e) {
        std::cout << "Got exception: " << e.what() << std::endl;
    }
    return 0;
}

If the assembly function is like this:
.global asm_function
asm_function:
    push %rbp
    mov %rsp, %rbp
    call throws_exception
    mov %rbp, %rsp
    pop %rbp
    ret

The program crashes, with error message like this:
terminate called after throwing an instance of 'std::runtime_error'
  what():  exception incoming.
Aborted (core dumped)

If the assembly function is as simple as a "jmp" instruction, the test function works, but my program cannot be so simple.


text:
Q: Automating data in autocad using VBA I have a drawing file in autocad dwg format which shows trees and their tree number in text. now i want to create a excel file having details of tree number and their coordinates. Till now i have achieved looping through the tree object and then user has to input the tree number. Can this process be automated using the proximity calculation i.e. the code search for nearest text and then attaches the tree number from the text to the tree on excel sheet.

A: You can use SelectionSet to select texts inside tree. More You can see for example here.
https://www.engram9.info/autocad-2006-vba/selecting-entities.html
It would be something like:
Dim p1 As Variant
Dim p2 As Variant

tree.GetBoundingBox p1, p2

Set objSS = ThisDrawing.SelectionSets.Add("TestSelectSS")
objSS.Select acSelectionSetWindow, p1 , p2

Be carefull please. It's just writen by hand, I don't even know if it will run, but just want to point You direction.
Then You need to iterate through objSS , and get text You want. You may also use SelectionSet filters, so objSS.Select will return only texts.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using rigid for reluctant attitude My friend wrote the following sentence to show her reluctance towards watching movies:

I am quite rigid towards watching movies in cinema halls.

I didn't find any definition in Oxford dictionary for "rigid" which means "a reluctant attitude".
Here, she meant that she always try to avoid going cinema halls for watching movies. Her full statement was as follows:

I am quite rigid towards watching movies in cinema halls. However, when my family pushed I got ready and joined them there.

Did she write a correct statement? I have found many other people using a similar statement.

A: Rigid means hard, stiff - the opposite of flexible.
It typically describes/implies a physical object.  To overcome this assumption you need a lot of literary or poetic-license type of context.  More than what you provide in your example.
The adverb form rigidly is somewhat more open to describe non-physical things:

I am rigidly insistent upon watching movies in cinema halls.

A better word for your situation would be particular about, which is used to talk about preferences or wants.

I am particular about watching movies in cinema halls


text:
Q: Connecting to myself using .NET sockets I'm creating a server client application. I have been able to connect to applications on the same network. For example I can connect to 10.0.0.3 and 10.0.0.4.
Now I have been trying to connect to my external IP and I recieve:

System.Net.Sockets.SocketException (0x80004005). No connection could be made because the target machine actively refused it.

 listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 write = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 end = new IPEndPoint(IPAddress.Parse(IP), 3212);
 write.Connect(end);

Is this a problem with my code or with my router settings? Or is it that you can't connect to yourself... however that wouldn't make sense considering I can connect to 127.0.0.1.

A: This is a common loopback error, because you're router gets confused when doing Internet NAT redirections. Your external IP is assigned to your modem/router...not your computer, remember that your router could be handling traffic for more than one device inside the network under one single external IP then it uses NAT to redirect traffic to specific local connected devices. One example is, your home network with 2 computers, one printer and 2 mobile devices, all of them connected to your home network via wi-fi, all of them will have a local IP address assigned possible via DHCP, however, the external IP address is the same for all local devices because the external IP address is assigned to your router.
When connecting to local network devices ALWAYS use a local IP address instead of the external one
Edit
I wanted to keep this answer as simple as possible but Scott's comment made me re-think that it is always useful to add details that can help the community out there.
Basically, you can actually set up Port Forwarding which allows your router to redirect incoming traffic received in a specific port to a designated device in your local network. This will make your device accessible from outside your network on that specific port and you can easily take advantage of this to connect to sockets from inside your local network using your external IP address. The flip side is that not all routers/modems support Port Forwarding, so you will have to refer to your modem's manual and check if it's supported or not.
But, if you want to set it up solely for the reason that you want to connect devices from your local network using the external IP, I would recommend you NOT to do it and use the internal IP address, you don't really want to go through the security risks that are involved in exposing your local devices to the internet. You can easily set up strict firewall rules to outsiders and a more relaxed security in your local network.

A: For my socket application I used port number from 10000, secondly I have created Windows Firewall Rule on socket server computer, which allows your external client to connect to the socket server. you can specify number of individual ip address or a range with a port number 10000. From Start -> All Programs -> Windows Firewall with Advance Security. Follow the prompts set the rule for your client IP. Good luck

A: I presume the IP address you want to connect to is not 127.0.0.1, but your own IP address as used on the internet (e.g. 80.110.140.30)? You can't do that. Try copy-and-pasting that same IP address in your browser, for example, and you'll see it either does not connect or redirects to your router.
From your own network, the only way to connect to yourself is through the loopback device (localhost or 127.0.0.1).


text:
Q: What are the uses of Null handler in python logging? According to python's documentation,

The NullHandler class, located in the core logging package, does not
  do any formatting or output. It is essentially a 'no-op' handler for
  use by library developers.

If it doesn't print to anything, what is the use of this handler at all? Why would one go to lengths to write loggers and then use null handler to not print anything?

A: So you can keep your logger.warning('Whatever') statements in your code, but conditionally inject a logger that entirely disregards them if you don't want a log in certain situations.


text:
Q: Check if user object is set inside Symfony expression language annotation I am using the @Security annotation to control which roles have access to certain routes in my Symfony 3.4 application, it works when I am logged in however when the user object doesn't exist such as when the session times out I get the following exception thrown.
Unable to get a property on a non-object.

vendor/symfony/symfony/src/Symfony/Component/ExpressionLanguage/ExpressionLanguage.php:78
  at
  Symfony\Component\ExpressionLanguage\ExpressionLanguage->evaluate('\'ROLE_MANAGER\'
  in user.getRoles()',

My method definition looks like this:
/**
 * @Route("/club/{id}/trophies", name="club_trophies", methods={"GET","POST"})
 * @IsGranted("IS_AUTHENTICATED_FULLY")
 * @Security("'ROLE_MANAGER' in user.getRoles()")
 * @param Club $club
 * @return Response
 */
public function trophies(Club $club): Response
{

Is there a way using the Symfony Expression Language, or similar, that I can check that user exists. Or is there a better way?

A: When you are not authenticated, the value of user is null, so it's normal that your check is throwing an exception (as you're trying to access the method getRoles() of a null object).
The proper ways to check if a user has a given role using annotations are :
@IsGranted("ROLE_MANAGER")

Or :
@Security("is_granted('ROLE_MANAGER')")

You can see more here : https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/security.html


text:
Q: Java threading JavaDoc I have written a method which should only be called on a particular thread.  Is there a standard annotation or note which should be added to the method's javadoc to denote this?

A: Don't know of any such standard annotations. Java Concurrency in Practice deals with the question in its section 4.5: Documenting Synchronization Policies. A few hints which hopefully help you make your documentation clear and useful:

At the very least, document the thread safety guarantees made by a class. Is it thread-safe? Does it make callbacks with a lock held? Are there any specific locks that affect its behavior? Don't force clients to make risky guesses. If you don't want to commit to supporting client-side locking, that's fine, but say so. If you want clients to be able to create new atomic operations on your class, as we did in Section 4.4, you need to document which locks they should acquire to do so safely. If you use locks to guard state, document this for future maintainers, because it's so easy - the @GuardedBy annotation will do the trick. If you use more subtle means to maintain thread safety, document them because they may not be obvious to maintainers.

They also use some annotations, which are not standard, but recommended by them (see Appendix A). However, for methods they only offer variations of @GuardedBy, which is not applicable to your case.
I recommend just clearly documenting the requirement in plain Javadoc.

A: In my opinion, the best way to handle it is to remove the requirement.  Change the method to private and rename it slightly by adding the word Workload or Internal or something.  Then create a new public method with the same signature.  Have this method check to see if you are on the correct thread.  If you are, you can just execute the private method.  If not, then schedule the private method to be executed on the correct thread.  This way, the user of the API doesn't have to worry about threading and can just call the method.
Then, there is nothing to specify in the javadoc, although it is still useful to include this information in the description of the public and private methods.
This is the pattern I use when I need something executed on the EDT:

/**
 * Executes something on the EDT with the crazy argument specified.  If this is
 * called outside of the EDT, it will schedule the work to be done on the EDT
 * as soon as possible. The actual work of this method is found in
 * {@link #executeSomethingInternal(int)}.
 *
 * @argument crazyArgument some crazy argument
 */
public void executeSomething(int crazyArgument) {
  if (SwingUtilities.isEventDispatchThread()) {
    this.executeSomethingInternal(crazyArgument);
  } else {
    Runnable r = new Runnable() {
      private int crazyArgument;

      public Runnable setCrazyArgument(int crazyArgument) {
        this.crazyArgument = crazyArgument;
        return this;
      }

      @Override
      public void run() {
        this.OuterClass.executeSomethingInternal(this.crazyArgument);
      }
    }.setCrazyArgument(crazyArgument);
    SwingUtilities.invokeLater(r);
  }
}

/**
 * This method actually does the work.  It is guaranteed by this class to
 * always get called on the EDT.  Users of this API should call
 * {@link #executeSomething(int)}.
 */

private void executeSomethingInternal(int crazyArgument) {
  // do work here
}


text:
Q: Is there a notion of an infinite "Rado graph-like" random algorithm? Disclaimer before starting: I'm not using "algorithm" in the usual sense, but I don't know what the right term for what I'm talking about is, if there even is one. Here, "algorithms" do not necessarily have a finite amount of instructions, and do not necessarily terminate. I know about Turing Machines, and it's probably equivalent to Turing Machines, only I'm not using any formal definition. As such, the description of the problem and the question will be very informal, and possibly flawed and/or inconsistent, the reason being that I'm asking if something "similar to that" but formalized exists, starting from a naive idea.
Motivation and context
After learning about the Rado graph, I wondered if such a thing existed for algorithms: an algorithm that does not necessarily terminate but that "embeds" an equivalent of every other algorithm (including those that don't terminate), more on that later. The reason behind the question is not mathematical but rather a philosophical itch (exploring the possible implications of the mathematical universe hypothesis).
Possibly among other things, this algorithm $U$ would have a set of variables $X$, and steps would still be numbered sequentially.
What I meant earlier by "embed" is that for any (possibly unending) algorithm $a$ with specific inputs, you can find a subset $Y \subset X$ of variables, and a subset $A\subset \mathbb{N}$ such that the algorithm only acts on the variables of $Y$ at precisely the steps in set $A$ (I'll shorten that to "at steps $A$" let me know if this is confusing, I'll edit), such that if you looked only at the variables from $Y$ at steps $A$, it would look like you are running $a$ with those specific inputs.
This is the rough idea. Now I'm aware that this naive idea already has obvious problems with it (mainly due to it not being formalized, and not being restricted enough) :

*

*I haven't defined what type of instructions could steps entail or correspond to.

*I haven't defined what kind of values the variables could take or be initialized with, which is a problem since for instance even a simple "algorithm" that at each step adds $1$ to a single variable, indefinitely, could be defined for any real number, which instantly makes the premise of the algorithm impossible because of a cardinality issue. A possible solution to that would be to restrict values to those that can be reached from natural numbers and a finite amount of instructions using a finite amount of variables. Obviously, this still is a downgrade from the initial, even more naive idea of "including every algorithms with every inputs", since now the inputs are restricted, but this is inevitable.

I'm already sure about the answers to (1) and (2), but the questions are:

(1) Is there something "kind of like this" which is a thing whose properties were studied? Possibly a Turing machine.

(2) Is there anything interesting about it? Is it anything more than just "all (not actually all) algorithms running in parallel, that's it"?

(3) Is there an alternative concept that could have interesting properties? By alternative concept I mean an idea that might differ on several points but is still close to the spirit of topic, i.e. one that would fit for the title question, that has a property even vaguely, very remotely similar to that of the Rado graph's extension property

(4) If the answer to (3) is "yes", what is it, what what interesting properties does it have?

I assume the answer to (1) is yes, and it'd be through some Turing machine.
The answer to (2) is most definitely "no", since because of the way it was defined, "sub-algorithms" are pretty much self contained and their variables remain isolated from the rest, whereas in the Rado graph, every vertex is pretty much garanteed to be connected to an infinite amount of other nodes.
I am also unsure what to tag this.
Edit : removed "If the answer to (2) is no" from question (3).

A: I would argue that this is exactly the right way to think about a universal Turing machine.
For simplicity, let's shift attention from algorithms to (partial) functions computed by those algorithms. It turns out that there is a binary function $U(x,y)$ with the following properties:

*

*$U$ is computable (in the Turing machine sense).

*For every computable unary partial function $f$ there is some $n$ such that $f(x)\simeq U(x,n).$

*In fact, $U$ satisfies the even stronger property that for every computable binary partial function $g(x,y)$ there is a total computable $t$ such that $g(x,y)\simeq f(x, t(y)).$
This turns out to be the right definition of a universal computable (binary) function. The point I want to make here is that the third clause above doesn't just strengthen the second clause and rule out some pathologies (see here), it also corresponds more accurately to the universal embedding property of the Rado graph: the objects being compared are the binary partial computable functions, and the third bulletpoint above says that we have the desired embedding property.


text:
Q: What is the algorithm applied by ImageAdjust[image,{c,b,gamma}] I want to know how ImageAdjust work to change the pixel values by specifying all parameters b,c and gamma.
In openCV, the transformation is linear g(x)=alpha*f(x)+beta where alhpa controls the contrast and beta controls the brightness with alpha>0. When I apply this function with an exemple, it does not fit .
imageoriginal={{0.492279, 0.413776}, {0.17979, 0.510059}}

ImageAdjust[imageoriginal,{1.,.5}]={{0.976837, 0.741327}, {0.0393686, 1.}}

A: This is stated in the documentation (third example in Properties & Relations)

ImageAdjust[image,{c,b,γ}] is equivalent to ImageApply[Clip[(b+1)(c+1)#^γ - c/2, {0, 1}]&, image]

A: Consider these examples:
ref = N @ Subdivide @ 255;
img = ref~Partition~10 // Image;

ImageAdjust[img, {1, 0, 1}];
ListLinePlot[{Flatten @ ImageData @ %, ref}]

ImageAdjust[img, {0, 1, 1}];
ListLinePlot[{Flatten @ ImageData @ %, ref}]

ImageAdjust[img, {0, 0, 2}];
ListLinePlot[{Flatten @ ImageData @ %, ref}]


text:
Q: Is it possible to transition placeholder text from beginning to end? I would like to transition a single line of dynamic placeholder text from beginning to end within a text input of known width (which hides overflow)
Now I know that for a regular container div I can make use of transforms to transition the correct length...
so for a container of length 100px I could transition to the end of the text with: transform: translateX(calc(100px - 100%)

div {
  width: 100px;
  border: 2px solid green;
  margin: 10px;
  padding: 5px;
}
div {
  white-space: nowrap;
  overflow: hidden;
}
span {
  display: inline-block;
  animation: 4s scrollText forwards;
}

@keyframes scrollText {
  to {
      transform: translateX(calc(100px - 100%));
  }
}

some really really really long text here

I was wondering if I could achieve the above effect with placeholder text using the placeholder pseudo element.
So I tried the following:

input {
  width: 100px;
  border: 2px solid green;
  margin: 10px;
  padding: 5px;
}

input::placeholder {
  color: red;
  animation: 4s scrollText;
  transform: translateX(0);
}

@keyframes scrollText {
  from {
      transform: translateX(0);
  }
  to {
      transform: translateX(calc(100px - 100%));
  }
}
<input type="text" placeholder="some really really really long text here">

... but the above snippet doesn't work because of a limitation of the properties available on the placeholder pseudo element

All properties that apply to the ::first-line pseudo-element also
  apply to the ::placeholder pseudo-element.

Unfortunately, transform1 doesn't appear in that list.
So I was wondering if there is another way of achieving this - possibly with other properties which are supported by the placeholder pseudo element.

*

*Strangely enough, the transform property did seem to (sort of) work on Chrome when used without the calc function and the animation.

input {
  width: 100px;
  border: 2px solid green;
  margin: 10px;
  padding: 5px;
}

input::placeholder {
  color: red;
  transform: translateX(-50%);
}
<input type="text" placeholder="some really really really long text here">

A: You can simulate this using an extra wrapper without really using a placeholder on the input element:

input {
  width: 100px;
  border: 2px solid green;
  padding: 5px;
  vertical-align:top;
  background:transparent; /* a transparent background to show the pseudo element */
}

.input {
  display:inline-block;
  margin: 10px;
  position:relative;
  z-index:0;
  overflow:hidden;
}

.input:before {
  content:attr(placeholder);
  position:absolute;
  left:5px;
  top:5px;
  white-space:nowrap; /* no line break */
  color: red;
  pointer-events:none; /* avoid any interaction */
  animation: 4s scrollText forwards;
  z-index:-1;
}

@keyframes scrollText {
  to {
      transform: translateX(calc(100px - 100%));
  }
}

/* hide the before on focus */
.input:focus-within:before{
   visibility:hidden;
}

/* add background to hide the before when there is text and no focus*/
input:not(:placeholder-shown) {
  background:#fff;
}

<input type="text" placeholder=" ">


text:
Q: How to define resource limits and calculate consumption when deploying applications in Kubernetes? I am trying to deploy a simple zookeeper ensemble following the tutorial from the official Kubernetes website. The tutorial states that I need

a cluster with at least four nodes and each node requires at least 2
CPUs and 4 GiB of memory.

I ignored this fact and created a cluster with 3 nodes of n1-standard-1 (1 vCPU, 3.73 GB Memory)
When I tried to apply .yaml file
apiVersion: v1
kind: Service
metadata:
  name: zk-hs
  labels:
    app: zk
spec:
  ports:
    - port: 2888
      name: server
    - port: 3888
      name: leader-election
  clusterIP: None
  selector:
    app: zk
---
apiVersion: v1
kind: Service
metadata:
  name: zk-cs
  labels:
    app: zk
spec:
  ports:
    - port: 2181
      name: client
  selector:
    app: zk
---
apiVersion: policy/v1beta1
kind: PodDisruptionBudget
metadata:
  name: zk-pdb
spec:
  selector:
    matchLabels:
      app: zk
  maxUnavailable: 1
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: zk
spec:
  selector:
    matchLabels:
      app: zk
  serviceName: zk-hs
  replicas: 3
  updateStrategy:
    type: RollingUpdate
  podManagementPolicy: OrderedReady
  template:
    metadata:
      labels:
        app: zk
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            - labelSelector:
                matchExpressions:
                  - key: "app"
                    operator: In
                    values:
                      - zk
              topologyKey: "kubernetes.io/hostname"
      containers:
        - name: kubernetes-zookeeper
          imagePullPolicy: Always
          image: "k8s.gcr.io/kubernetes-zookeeper:1.0-3.4.10"
          resources:
            requests:
              memory: "1Gi"
              cpu: "0.5"
          ports:
            - containerPort: 2181
              name: client
            - containerPort: 2888
              name: server
            - containerPort: 3888
              name: leader-election
          command:
            - sh
            - -c
            - "start-zookeeper \
          --servers=3 \
          --data_dir=/var/lib/zookeeper/data \
          --data_log_dir=/var/lib/zookeeper/data/log \
          --conf_dir=/opt/zookeeper/conf \
          --client_port=2181 \
          --election_port=3888 \
          --server_port=2888 \
          --tick_time=2000 \
          --init_limit=10 \
          --sync_limit=5 \
          --heap=512M \
          --max_client_cnxns=60 \
          --snap_retain_count=3 \
          --purge_interval=12 \
          --max_session_timeout=40000 \
          --min_session_timeout=4000 \
          --log_level=INFO"
          readinessProbe:
            exec:
              command:
                - sh
                - -c
                - "zookeeper-ready 2181"
            initialDelaySeconds: 10
            timeoutSeconds: 5
          livenessProbe:
            exec:
              command:
                - sh
                - -c
                - "zookeeper-ready 2181"
            initialDelaySeconds: 10
            timeoutSeconds: 5
          volumeMounts:
            - name: datadir
              mountPath: /var/lib/zookeeper
      securityContext:
        runAsUser: 1000
        fsGroup: 1000
  volumeClaimTemplates:
    - metadata:
        name: datadir
      spec:
        accessModes: [ "ReadWriteOnce" ]
        resources:
          requests:
            storage: 10Gi

And of course, I got the error PodUnschedulable
In this file, I cloud not find anything that says that I need a cluster of 4 nodes and with 2 CPUs and 4G Ram.
So:

*

*What defines how much of resources do my deployment needs?

*How to understand/calculate the required resources of applications and their respective deployments beforehand?

*Zookeeper runs on 2GB RAM according to requirements but this is only a recommended configuration.

A: By default, a kubernetes nodes will not come empty. Instead, it has running processes before even running your apps workload:

*

*kubelet is running ( in each node)

*kube-proxy is running as daemonset ( in each node)

*container-runtime (Docker) is running in each node

*other daemonset can be running (like aws-node DS in the case of EKS..).

We are here discussing Worker Nodes not Masters.

So imagine all that, you will end up by choosing a respectful resources for each Node.
Not all Nodes must be with the same size. However you decide which size you need according to the type of your apps :

*

*If your apps eats memory more than CPUs (Like Java Apps), you will need to choose Node of [2CPU, 8GB] is better than [4CPUs, 8GB].

*If your apps eats CPUs more than memory (Like ML workload), you will need to choose the opposite; computing-optimized instances.

*The golden rule  is to calculate the whole capacity is better than looking into the individual capacity for each  node.
This means 3 large nodes might be better than 4 medium nodes in term of cost but also in term of the best usage of capacity.

As conclusion, Node resource must be:

*

*no less than 2 CPUs

*no less than 4GB memory

Otherwise, you should expect capacity issues.

Now, we reach the half of the answer: Identify the capacity of the cluster.
The second half is about answering how to assign resources for the each app (pod).
This is fall into another question; How much your app consume ?
To answer this question, you need to monitor your app with APM tools like Prometheus + Grafana.
Once you get insight about the avergae of consumption, it's the time to set resources limits for your app (its pods).
Limits might throttle the app, that's why, you need to set up alongside other things for horizontal auto-scaling:

*

*Run Pods inside Deployment to manage replicas and deployment.

*HPA or  Horizontal Pod autoscaler: which monitors the pods of the deployment , then scale out/in according to thresholds (CPU, memory)

As conclusion for this part, we can say:
- Measure : start measure to identify resources.limits and resources.requests.
- Measure: measure after running the app to identify again the needed resources.
- Measure: Keep measure

A: resources section in the deployment yaml defines the resource requirement of a container in the pod.
resources:
  requests:
    memory: "1Gi"
    cpu: "0.5"

requests means a node need to have more than 1GB of memory and 0.5 CPU available for one of the replica pod to be schedulable on that node.
There is another concept of limits which defines maximum resource a pod is allowed to consume before it get's evicted from the node.
resources:
  requests:
    memory: "1Gi"
    cpu: "0.5"
  limits:
    memory: "2Gi"
    cpu: "2"

Although you have 3 nodes the master node is not schedule by default.
You can understand the resource availability of a node by kubectl describe nodename and checking the Capacity and Allocatable section.
Capacity:
  cpu:                4
  ephemeral-storage:  8065444Ki
  hugepages-1Gi:      0
  hugepages-2Mi:      0
  memory:             16424256Ki
  pods:               110
Allocatable:
  cpu:                4
  ephemeral-storage:  7433113179
  hugepages-1Gi:      0
  hugepages-2Mi:      0
  memory:             16321856Ki
  pods:               110

Regarding calculating resource requirement(requests and limits) of a pod there is no silver bullet. It depends on the application and should be determined and tuned by profiling it. But it's recommended best practice to define requests and limits when deploying a pod.


text:
Q: MinHeapify printing incorrect value I am trying to visualize why my minHeapify is isn't sorting correctly. Here is my code:
import java.util.List;
import java.util.ArrayList;

public class Heap {

    public void insert2(List<Integer> heap, int value) {
        if(heap.isEmpty()) {
            heap.add(value);
        }
        else {
            heap.add(value);
            for(int index = heap.size() / 2 - 1;index >= 0;index--) {
                minHeapify(heap, index);
            }
        }
    }

    public void minHeapify(List<Integer> heap, int index) {
        int smallest = index;
        int leftChildIndex = 2 * index + 1;
        int rightChildIndex = 2 * index + 2;

        if(leftChildIndex < heap.size() && heap.get(leftChildIndex) < heap.get(smallest)) {
            smallest = leftChildIndex;
        }
        if(rightChildIndex < heap.size() && heap.get(rightChildIndex) < heap.get(smallest)) {
            smallest = rightChildIndex;
        }
        if(smallest != index) {
            int temp  = heap.get(smallest);
            heap.set(smallest, heap.get(index));
            heap.set(index, temp);
            minHeapify(heap, smallest);
        }
    }

    public static void main(String[] args) {
        List<Integer> input2 = new ArrayList<Integer>();

        Heap heap2 = new Heap();
        heap2.insert2(input2, 3);
        heap2.insert2(input2, 4);
        heap2.insert2(input2, 48);
        heap2.insert2(input2, 9);
        heap2.insert2(input2, 5);
        heap2.insert2(input2, 2);

        System.out.println(input2);
    }

}

The output is [2, 4, 3, 9, 5, 48]
The output for min heap should always be sorted. Am I correct with this assumption and should it be [2, 3, 4, 5, 9, 48] ?

A: Your implementation is correct, and the result after your following insert steps is truely [2, 4, 3, 9, 5, 48].

The output for min heap should be always sorted

But you are getting a little wrong idea about MinHeap, which is every node is smaller than it left and right children node. BUT the right child node can be greater, smaller than it sibling as long as greater than its parent.
So the represented List of your heap can't be sort in correct order.
https://www.geeksforgeeks.org/heap-data-structure/


text:
Q: Android AccountManager, Oauth, getAccessToken() does nothing except ask for password After spending roughly two days on this, I'm getting a little rattled.  Although by now, having chosen OAuth2 over OpenID, I'm pretty well versed on the difference between Authenticate and Authorize.
I want my android app to provide several ways to authenticate users, one of them is google accounts, and later also facebook and twitter accounts.  I'm trying to use the AccountManager class to get an OAuth access token to (for now) just verify the user's email address.  The goal is that if the user already has a google account saved on the android device, they can authorize my app once, MAYBE even without typing a password, and never have to login again from their android.
I decided to use Google's own AccountManager as it promised to handle much of this natively in the Android framework, without even opening a browser window.  I am using the library / build target for google APIs version 7 (Android 2.1), the first level that supports AccountManager.
I have tried this two different ways, one using AccountManager.getAuthTokenByFeatures() where you do not specify an Account object, and the other using getAuthToken() where you do specify such an object.
In each case, the call completes (as I expect it to) and the application displays an authorization dialog asking if I want to authorize the app.  So far, so good.  If I refuse, the program throws the exception that I expect.  If I accept, a "Google sign-in" dialog appears asking me for the password to the account.  Note that I already entered the password when I added the account to the device.  If I type the password in the dialog, there is an "Authorizing" wait screen and then the same dialog re-appears.  Oddly enough, the "Authorizing" wait screen seems to take a little bit longer if I type the CORRECT password.  So it appears that I cannot get to the code path where I successfully obtain the token.
As tempting as it is to vent about google not being clear about what AUTH_TOKEN_TYPE is or the fact that the userinfo.email URL is undocumented, I would really just like to learn what I am doing wrong here and move past this.
Here is my code, I will monitor this and of course be happy to answer any questions.  Right now I am going to work on getting a capture of the network traffic, to see if that provides any further insight into what is going wrong.
Here are images showing the auth screen (ok) and the password dialog (less ok)
http://imageshack.us/g/707/device20120609020618.png/
    public void loginToGoogle() {
    System.out.println("Starting");
    AccountManagerFuture<Bundle> bundleFuture =
        AccountManager.get(_activity).getAuthTokenByFeatures(
                "com.google",
                "https://www.googleapis.com/auth/userinfo.email",
                null,
                _activity,
                null,
                null,
                new AccountManagerCallback<Bundle>() {

                      public void run(AccountManagerFuture<Bundle> future) {
                        Bundle bundle;
                        try {
                          bundle = future.getResult();
                          for (String s : bundle.keySet()) {
                              System.out.println("Found key: "+ s);
                          }

                          System.out.println(bundle.getString(AccountManager.KEY_ACCOUNT_NAME));
                          System.out.println(bundle.getString(AccountManager.KEY_AUTHTOKEN));
                          //Use Token

                        } catch (OperationCanceledException e) {
                          Log.e("e", e.getMessage(), e);
                          System.out.println("User appears to have denied auth request");
                        } catch (AuthenticatorException e) {
                          Log.e("e", e.getMessage(), e);
                        } catch (IOException e) {
                          Log.e("e", e.getMessage(), e);
                        }
                      }
                    },
                    null);
    System.out.println("Done with AccountManager call");
}

A: Your issue most likely lies in the Auth Token Type you pass into the getAuthTokenByFeatures. Since you're using oauth2, you need to add it to beginning of your auth type:
String AUTH_TOKEN_TYPE = "oauth2:https://www.googleapis.com/auth/userinfo.email"

However, I'm not positive that the Auth Token Type you are trying to use is valid. I've only dealt with calendars and tasks myself. Hope this works out, if not, just let me know and I'll find you the right Auth type


text:
Q: iOS while-loop reverting index back to zero I have a game with a board with 26 tiles. The player rolls a number between 1 and 12, and the player then moves that many tiles. I do this by having an array (indexes 0-25) of the tiles, in order. This is my way of moving the player across the tiles (this contains code from Sprite Kit, which I know is under NDA, but the question isn't about that)
NSInteger rolled_number = arc4random() % 12;
while (rolled_number == 0)
    rolled_number = arc4random() % 12;
NSLog(@"%d", rolled_number);
NSInteger new_index = self.player1.currentTileIndex + rolled_number;
if (!(new_index <= 25))
    new_index = new_index - 26;
NSMutableArray *actions = [NSMutableArray array];
while (self.player1.currentTileIndex < new_index) {
    SKSpriteNode *node = [_tiles objectAtIndex:self.player1.currentTileIndex];
    SKAction *move = [SKAction moveTo:node.position duration:1];
    [actions addObject:move];
    NSLog(@"currentTileIndex: %d", self.player1.currentTileIndex);
    if (self.player1.currentTileIndex + 1 > 25)
        self.player1.currentTileIndex -= 26;
    else
        self.player1.currentTileIndex++;
}

the problem with this code is if the player is on the tile at index 23 and rolls a 5, they should go to the tile at index 3, but instead it doesn't move, because it will instead make the currentTileIndex property 28 instead of 3. My question is how can I modify this while-loop so that it will still work even when the number has to go to 0 instead of 26?

A: First off, to get a number from 1 to 12 do:
NSInteger rolled_number = arc4random_uniform(12) + 1;

Then make proper use of the modulo operator to wrap your numbers:
NSInteger new_index = self.player1.currentTileIndex + rolled_number;
NSMutableArray *actions = [NSMutableArray array];
while (self.player1.currentTileIndex < new_index) {
    SKSpriteNode *node = _tiles[self.player1.currentTileIndex % _tiles.count];
    SKAction *move = [SKAction moveTo:node.position duration:1];
    [actions addObject:move];
    NSLog(@"currentTileIndex: %d", self.player1.currentTileIndex % _tiles.count);
    self.player1.currentTileIndex++;
}

self.player1.currentTileIndex = self.player1.currentTileIndex % _tiles.count;


text:
Q: How to pass data toTaggableManager django In my Django model have TaggableManager field, I want to store data in database, in which format I need to pass data to TaggableManager field.
tags=TaggableManager(through=Tags)

A: Like the documentation says, you can add tags like:
some_instance.tags.add(tag1, tag2, tag3)

Since you use a custom Tags model, these tags (tag1, tag2, etc.) are instances of the Tags model.
You can use the API as well to

*

*.remove(tag2, tag3): remove tag2 and tag3 from the instance;

*.clear(..): remove all the tags;

*.set(tag1, tag3) change the tags to tag1 and tag3 (equivalent to .clear(..) and .add(..));

and other functions described in the documentation.
It thus acts like a vanilla Django ManyToManyField when updating the relation with tags.


text:
Q: How to convert text into audio file and play in browser via python/django? How to convert text into audio file which can be played in browser via python/django views?
How can I do text-to-speech conversion in python? I want to convert a string to a .wav file, that will be played in a browser via python/django views.
For example:
text = "how are you?"
convert text to audio file (text.wav)
open text.wav file & play in browser via django view.

A: As Tichodroma says, you should always see if someone has already asked your question before asking it again.  Google search for python text to speech returns http://code.google.com/p/pyspeech/ and How to make Python speak, among others.

A: I have tried to do like following way & it works for me. Thanks.
#Write text to file
text_file_path = '/user/share/project/test.txt'
audio_file_path = '/user/share/project/test.wav'
text_file = open(text_file_path, "w")
text_file.write('How are you?')
text_file.close()

#Convert file
conv = 'flite -f "%s" -o "%s"' % (text_file_path, audio_file_path)
response = commands.getoutput(conv)

if os.path.isfile(audio_file_path):
    response = HttpResponse()
    f = open(audio_file_path, 'rb')
    response['Content-Type'] = 'audio/x-wav'
    response.write(f.read())
    f.close()
    return response


text:
Q: react-native-agora Warning 8, Warning 16 useEffect(() => {
    initEngine();

    return () => {
      engine?.destroy();
    };
  }, []);

  const initEngine = async () => {
    if (engine) return;
    engine = await RtcEngine.createWithContext(new RtcEngineContext(appId));

    addListeners();

    await engine?.enableVideo();
    await engine?.startPreview();
    await engine?.setChannelProfile(ChannelProfile.LiveBroadcasting);
    await engine?.setClientRole(ClientRole.Broadcaster);
}

  const addListeners = () => {
    engine?.addListener('Warning', warningCode => {
      console.info('Warning', warningCode);
    });
    engine?.addListener('Error', errorCode => {
      console.info('Error', errorCode);
    });
    engine?.addListener('JoinChannelSuccess', (channel, uid, elapsed) => {
      console.info('JoinChannelSuccess', channel, uid, elapsed);
      setIsJoined(true);
    });
    engine?.addListener('LeaveChannel', stats => {
      console.info('LeaveChannel', stats);
      setIsJoined(false);
      setRemoteUid([]);
    });
    engine?.addListener('UserJoined', (uid, elapsed) => {
      console.info('UserJoined', uid, elapsed);
      setRemoteUid([...remoteUid, uid]);
    });
    engine?.addListener('UserOffline', (uid, reason) => {
      console.info('UserOffline', uid, reason);
      setRemoteUid(remoteUid.filter(value => value !== uid));
    });
  };

This is my code example.
I take Warning 8 and Warning 16.
My camera doesn't come out.
But the other person can see my face.
I don't know how to solve the error code even if I look at it.


text:
Q: Using lambda to implement Singleton pattern I'm trying to figure out why this code works, producing only a unique instance of class A.
def singleton_function (c):
    print("singleton_function")
    x = c()
    return lambda : x

@singleton_function
class A:
    pass

def test2 () :
    x = A()
    y = A()
    assert x == y

test2()

Output:
python3 test.py
singleton_function

Why is singleton_function only accessed once? A is of type function, so my guess is that when calling A, A(), it returns x, which is the instance of class A, so, it should have printed two times "singleton_function", since I am accessing twice.
What am I thinking wrong?

A: Consider the decorator syntax:
def singleton_function (c):
    print("singleton_function")
    x = c()
    return lambda : x

@singleton_function
class A:
    pass

This is essentially saying that:
A = singleton_function(A)

And singleton_function() creates one instance of A and then returns a function that points to that instance.
So we get
A = lambda: x

Where x is an instance of the original class A. Calling A() returns x which is still that same instance  that singleton_function() first created.


text:
Q: bigquery error: "Could not parse '41.66666667' as INT64" I am attempting to create a table using a .tsv file in BigQuery, but keep getting the following error:
"Failed to create table: Error while reading data, error message: Could not parse '41.66666667' as INT64 for field Team_Percentage (position 8) starting at location 14419658 with message 'Unable to parse'"
I am not sure what to do as I am completely new to this.
Here is a file with the first 100 lines of the full data:
https://wetransfer.com/downloads/25c18d56eb863bafcfdb5956a46449c920220502031838/f5ed2f
Here are the steps I am currently taking to to create the table:
https://i.gyazo.com/07815cec446b5c0869d7c9323a7fdee4.mp4
Appreciate any help I can get!

A: As confirmed with OP (@dan), the error encountered is caused by selecting Auto detect when creating a table using a .tsv file as the source.
The fix for this is to manually create a schema and define the data type for each column properly. For more reference on using schema in BQ see this document.


text:
Q: SFML with apple silicon m1 I have MacBook Air with m1 chip and tried to install SFML according to the instructions on the official website however I can not compile the project for example
enter image description here
EDIT: I moved the Xcode app act via rosetta 2 and now it works I would love to know if there is a solution that will activate it natively

A: The error you are receiving is telling you that the version being linked is for MacOS on x32_64, while trying to compile for arm64. This is incompatible, given they're two different platforms.
Are you compiling SFML from source? It doesn't look like SFML has precompiled binaries for MacOS-arm64, but the source code does have arm compatibility. Compiling from source would be operating system agnostic as long as everything is there (and supports arm64.) SFML has an article on how to compile from source with CMake: https://www.sfml-dev.org/tutorials/2.5/compile-with-cmake.php
While I can't guarantee this will fix your issue, it's definitely worth a try if you haven't yet.
The reason using Rosetta made this work is because Rosetta emulates some parts of x32_64. Running these apps in Rosetta would essentially be the same as compiling your project on an Intel based Mac.

A: I found the solution if it can help some, just make your pc believe that you have an intel chip, by adding /usr/bin/arch -x86_64 before your order.
example:
/usr/bin/arch -x86_64 clang main.c -lcsfml-graphics -lcsfml-system


text:
Q: Cannot get Facebook Profile Picture Size I am trying to get the size of Facebook user's profile pictures by using the following code:
getimagesize('http://graph.facebook.com/XXXXXXXXXXXX/picture?type=large')
where XXXXXXXXXXXXXX is the Facebook's user ID.
When I tested the code on my local machine, I could get the image size back. However, when I tested on remote server with www.domain.com, the (http://graph.facebook.com/XXXXXXXXXXXX/picture?type=large) return nothing.
What's possible reason of this issue? Can anybody give me some hints?
Thanks.

A: The getimagesize() requires that allow_url_fopen is set to "1" in php.ini. You may want to check that setting on your remote server.


text:
Q: Modify database table best practices As my title states, I'm curious about the best practices for modifying an existing table in a (mysql) database. In my scenario, I have a table that is already full of data and has a column named product_id that is currently the primary key for the table. I'm working on a feature where I'm finding product_id doesn't necessarily need to be unique or the primary key, since I want to allow multiple records for the same product. Database design isn't a strength of mine yet, but in my head I feel like what I would want to do is run the command DROP PRIMARY KEY for the product_id column, then add a column called id and making this the new primary key. Then I would need to update the id column for each record with a unique id for it to be a valid primary key. As far as database design is concerned, is this the best practice for doing this or is it better to create a new table with the updated structure and copying the current records into the new table?
EDIT:
More about the feature I'm working on. The products are books and I'm trying to allow multiple sections of these books to be previewed. In order to do this, I'm storing page ranges that can be previewed. Right now, only one page range is allowed, which is why the product id doesn't need to be unique anymore.

A: A primary key is ALWAYS unique.
Why do you don't want it to be unique? It sounds like you are exposing the key outside the database, that the PK is visible somehow and some user(s) think it should behave differently. If this is the case then this is a really bad practice.
This is the typical case of the notorious "natural keys". They are a disaster waiting to happen; I don't like big time bombs. I've been strongly opposed to them for some time now. It's good they teach them in schools so you know what not to use in the real world.
Now for the solution. If product_id is exposed, then it shouldn't be the PK at all. Solution?

*

*Create a new column (id maybe?) that is internal, that is unique, and not exposed to the user, while keeping product_id. This new column could have the exact same value as product_id at first.

*Change all FK references from other tables to the new id column.

*Then, remove the PK constraint from product_id and do whatever you want to do with it.

*Add the PK contraint to the new id column.


text:
Q: pulsating circle in leaflet on click I have a leaflet map. I'm using circles for markers because I have some zooming built in, and I want the radius of the circles to animate during the zoom. I also, though, want the circles to "pulse" if they're clicked. I see a lot of documentation for pulsing leaflet markers online, but none for pulsing circles. Is there a simple solution here?
jquery:
var map = L.map('map').setView([40.449620, -79.939990], 13);

L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/terrain/{z}/{x}/{y}{r}.{ext}', {
    maxZoom: 19,
    ext: 'png',
    attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap'//,
}).addTo(map);

map.on('click', function(e) {
    var currentZoom = map.getZoom();
    if (currentZoom == 13) {
        map.flyTo(e.latlng, 15, { //zoom in on click
                animate: true,
                duration: 1,
                easeLinearity: 1
        });
    }
});
$.post('php/get-buildings.php', function(output){
    var obj = jQuery.parseJSON( output );

    var color;

    customCircle = L.Circle.extend({
       options: {
          //some more options here
       }
    });

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

        if (obj[i].there_2017 == 'No') {
            color = '#000';
        } else {
            color = '#1565C0';
        }
        //var circle = L.circle([obj[i].lat,obj[i].lng], {
        var circle = new customCircle([obj[i].lat,obj[i].lng], {
            color: '#000',
            weight: 0.5,
            fillColor: color,
            fillOpacity: 1,
            borderWidth: 2,
            radius: 40,
            //some more properties
        }).addTo(map).on("click", circleClick);

        function circleClick(e) {
          var clickedCircle = e.target;
          clickedCircle.setStyle({'weight': '3'});  want to animate this
        }

    }//end for
});

A: A solution to have a pulsating circle marker is to use a divIcon and create a pulsating marker you like with css.
js code :
    const generatePulsatingMarker = function (radius, color) {
      const cssStyle = `
        width: ${radius}px;
        height: ${radius}px;
        background: ${color};
        color: ${color};
        box-shadow: 0 0 0 ${color};
      `
      return L.divIcon({
        html: `<span style="${cssStyle}" class="pulse"/>`,
        // empty class name to prevent the default leaflet-div-icon to apply
        className: ''
      })
    }

    const pulsatingIcon = generatePulsatingMarker(10, 'red');
    L.marker([51.497, -0.09], {icon: pulsatingIcon}).addTo(map);

and the CSS pulsating marker :
    .pulse {
      display: block;
      border-radius: 50%;
      cursor: pointer;
      animation: pulse 2s infinite;
    }

    @keyframes pulse {
      0% {
        -moz-box-shadow: 0 0 0 0 rgba(0, 0, 0, 0.4);
        box-shadow: 0 0 0 0;
      }
      70% {
        -moz-box-shadow: 0 0 0 10px rgba(0, 0, 0, 0);
         box-shadow: 0 0 0 10px rgba(0, 0, 0, 0);
      }
      100% {
        -moz-box-shadow: 0 0 0 0 rgba(0, 0, 0, 0);
         box-shadow: 0 0 0 0 rgba(0, 0, 0, 0);
      }
    }

example fiddle here
Also, if you want the marker to pulse only when clicked, then add the corresponding "pulse" css class on click event.


text:
Q: Unable to use a native android plugin for Unity(FCM) ERROR

*

*Install unity apk file, two icons are created.(one is Call Android onCreate Function, another is not call)

*Unity and FireBase-related error logs are not visible, but they are not receiving push notifications.

ERROR LOG
04-04 15:51:23.256 1440-1949/? E/InputDispatcher: channel '9ad1a6f com.gcm.test/com.gcm.test.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
04-04 15:51:31.231 13391-13406/com.gcm.test E/LocationManager: [LGNSS] Disable_PrivacyLocation_Information [tOperator : LGU ] , [privacy_check : NA]
04-04 15:52:34.836 1440-5372/? E/UserRestrictionsUtils: Unknown restriction: com.gcm.test
04-04 15:52:36.419 1440-2244/? E/OverlayManager: Cannot found overlays for target: com.gcm.test
04-04 15:52:36.623 11556-11556/? E/AppInfoBase: Exception when retrieving package:com.gcm.test
android.content.pm.PackageManager$NameNotFoundException: com.gcm.test
    at android.app.ApplicationPackageManager.getPackageInfoAsUser(ApplicationPackageManager.java:155)
    at android.app.ApplicationPackageManager.getPackageInfo(ApplicationPackageManager.java:140)
    at com.android.settings.applications.AppInfoBase.retrieveAppEntry(AppInfoBase.java:168)
    at com.android.settings.applications.InstalledAppDetails.refreshUi(InstalledAppDetails.java:600)
    at com.android.settings.applications.InstalledAppDetails.onActivityResult(InstalledAppDetails.java:563)
    at android.app.Activity.dispatchActivityResult(Activity.java:7031)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4129)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4176)
    at android.app.ActivityThread.-wrap20(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1560)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6247)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
04-04 15:52:36.804 10511-10511/? E/PermissionPresenter: Error getting package:com.gcm.test
android.content.pm.PackageManager$NameNotFoundException: com.gcm.test
    at android.app.ApplicationPackageManager.getPackageInfoAsUser(ApplicationPackageManager.java:155)
    at android.app.ApplicationPackageManager.getPackageInfo(ApplicationPackageManager.java:140)
    at com.android.packageinstaller.permission.service.RuntimePermissionPresenterServiceImpl.onGetAppPermissions(RuntimePermissionPresenterServiceImpl.java:43)
    at android.permissionpresenterservice.RuntimePermissionPresenterService$MyHandler.handleMessage(RuntimePermissionPresenterService.java:120)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6247)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)

ERROR LOG(Resolved)
Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/iid/FirebaseInstanceId;
    at com.gcm.test.MainActivity.onCreate(MainActivity.java:16)
    at android.app.Activity.performCreate(Activity.java:6772)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2715)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2823)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6349)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)
 Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.iid.FirebaseInstanceId" on path: DexPathList[[zip file "/data/app/com.gcm.test-1/base.apk"],nativeLibraryDirectories=[/data/app/com.gcm.test-1/lib/arm, /data/app/com.gcm.test-1/base.apk!/lib/armeabi-v7a, /system/lib, /vendor/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at com.gcm.test.MainActivity.onCreate(MainActivity.java:16)
    at android.app.Activity.performCreate(Activity.java:6772)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2715)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2823)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6349)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)

This Error is solved by putting PlayerServices and Firebase plug-in files in Unity's Plugin folder.
Unity Code
public class TestCode : MonoBehaviour {
AndroidJavaClass andClass;
AndroidJavaObject andObj;
void Start () {
        andClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        andObj = andClass.GetStatic<AndroidJavaObject>("currentActivity");
}
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gcm.test">

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />"

<application
    android:allowBackup="true"
    android:label="@string/app_name"
    android:supportsRtl="true">
    <activity android:name="com.gcm.test.MainActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|mcc|mnc">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service
        android:name="com.gcm.test.MyFirebaseMessagingService">
        <intent-filter android:priority="1000">
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
    <service
        android:name="com.gcm.test.MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
</application>
</manifest>

build.grade(Modul:app)
apply plugin: 'com.android.library'
android {
compileSdkVersion 25
defaultConfig {
    minSdkVersion 16
    targetSdkVersion 25
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
    compileOnly fileTree(include: ['*.jar'], dir: 'libs')
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'com.google.firebase:firebase-core:11.8.0'
    implementation 'com.google.firebase:firebase-messaging:11.8.0'
    implementation 'com.google.firebase:firebase-iid:11.8.0'
    implementation 'com.google.firebase:firebase-common:11.8.0'
    implementation 'com.firebase:firebase-jobdispatcher:0.8.5'
    compileOnly files('libs/classes.jar')
    implementation 'com.android.support:support-v4:25.2.0'
    implementation 'com.android.support:appcompat-v7:25.2.0'
}
apply plugin: 'com.google.gms.google-services'

MainActivity.java
public class MainActivity extends UnityPlayerActivity {
private static MainActivity instance = null;

public static MainActivity getInstance() {
    if(instance == null) {
        instance = new MainActivity();
    }
    return instance;
}

@Override
protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    FirebaseApp.initializeApp(this);
    Log.d("unity", "StartActivity");
}
}

Another Code looks like this code.
https://github.com/firebase/quickstart-android/tree/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm


text:
Q: the last label is not setting according to the given setbound() eveybody I was creating a login page where i am face a issue the last label is not setting according to the given setbound so i created a label named fake and gave it a null value and put it at the last so the my design does not get effect but i need a solution for this why is it happening.i have inserted a image as a logo at the starting
 package com.MyBank;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class LoginDesign  extends JFrame implements ActionListener {
    JFrame f;
    JButton b1,b2,b3;
    JPasswordField pass;
    JTextField tx1;
    JLabel l1,l2,l3,img,fake;
    Font f1;

    public LoginDesign()
    {

        f1=new Font(Font.MONOSPACED,Font.BOLD,23);
        f=new JFrame("Automatic Teller Machine");
        f.getContentPane().setBackground(Color.WHITE);
        //label for Image
        img=new JLabel("");
        img.setIcon(new ImageIcon("C:\\Users\\vineet mendon\\Desktop\\bot\\bankLogo.png"));
        img.setBounds(135,10,270,70);
        f.add(img);

        //label for welcome to atm
        l1=new JLabel("⚜ WELCOME TO ATM ⚜");
        l1.setBounds(135,100,300,30);
        l1.setFont(f1);
        f.add(l1);
         //label for card no
        l2=new JLabel("Card No:");
        l2.setBounds(80,170,150,30);
        l2.setFont(f1);
        f.add(l2);
        //textfield for card no
        tx1=new JTextField(16);
        tx1.setBounds(210,170,200,30);
        tx1.setFont(f1);
        f.add(tx1);
        //create   pin no
        l3=new JLabel("Pin No :");
        l3.setBounds(80,230,150,30);
        l3.setFont(f1);
        f.add(l3);
        //creating password field
        pass =new JPasswordField(4);
        pass.setBounds(210,230,200,30);
        pass.setFont(f1);
        f.add(pass);
        //creating  for sign -in
        b1=new JButton("Sign In");
        b1.setBounds(80,290,160,30);
        b1.setBackground(Color.BLACK);
        b1.setForeground(Color.WHITE);
        b1.setFont(f1);
        f.add(b1);

        //creating button for clear
        b2=new JButton("Clear");
        b2.setBounds(250,290,160,30);
        b2.setBackground(Color.BLACK);
        b2.setForeground(Color.WHITE);
        b2.setFont(f1);
        f.add(b2);

        //creating button for sign-up
        b3=new JButton("Sign-Up");
        b3.setBounds(80,350,330,30);
        b3.setBackground(Color.BLACK);
        b3.setForeground(Color.WHITE);
        b3.setFont(f1);
        f.add(b3);

        //fake label i used==>this is problematic code
        fake=new JLabel("hiii");
        fake.setBounds(200,150,200,20);
        f.add(fake);

        //seting the frame size
        f.setSize(550,600);
        f.setVisible(true);
        f.setLayout(null);
        f.setLocation(400,70);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
    public void actionPerformed(ActionEvent e)
    {

    }

}
public class Login  {
    public static void main(String[] args) {
        new LoginDesign();
    }

}


text:
Q: Symfony 4: how to safely 'join' migrations together? / remove migrations in between the first and last? I was recently tweaking around with my DB and noticed that I made 5 migrations on top of my existing 2. So 7 in total, m1, m2, ..., m7. From these 5, I only want the latest version. So I was thinking I could remove m3, m4, m5, m6, m7 and migrate again, which will result in m3 that already contains the final version that I'm happy with. Now I have never done this before and was wondering what is the safest way to do it?
I'm using PHPStorm. Could I manually remove them (right click in PHPStorm then Delete) and then go to the command line and do php bin/console doctrine:migrations:migrate? Or do I need to do php bin/console doctrine:schema:update? Or is this really a bad idea?

A: No, generally you shouldn't do either of those. Let me start by clearing up what seems like a misconception: a migration doesn't contain a full database schema, only the queries necessary to bring the database from one version to the next. This system allows for database changes to be managed and versioned. So you should be starting to see some problems with this:

*

*A migration might depend on a previous one. E.g. v1 adds an entity and v2 adds a new field. If you remove v1, v2 will be broken and needs to be removed as well.

*Since a database migration usually goes hand in hand with an object model change, you will have to revert the model as well, otherwise you'll find mapping problems with non existent fields.

This might be acceptable during the design phase when you don't have any functionality yet. You can revert an individual migration using bin/console doctrine:migrations:execute --down <version>. This is usually done while testing changes if adjustments need to be made. But usually when that change hasn't been committed yet.
Doctrine keeps track of migrations using a database table called migration_versions. By naming them with a date, it can order them and apply them sequentially. Whenever a migration is executed, it adds the migration name to this table. When you roll it back, it deletes it from the table, along with the fields in the migration itself. Keep in mind that even though you can rollback a migration, it doesn't mean everything will be as it was. If a migration drops a column, the column will be recreated on rollback, but the data will be lost.
As for "can it be done"? Yes. If you really really want to, have read the documentation thoroughly and are aware of all this.
So, since your question is about merging migrations, let's tackle your actual options:

*

*Could I manually remove them (right click in PHPStorm then Delete) and then go to the command line and do php bin/console doctrine:migrations:migrate?

No, this won't work. migrate will apply available migrations. They won't be any and, as explained, the revisions will still be in the table and its changes applied.

*

*Or do I need to do php bin/console doctrine:schema:update?

This won't do anything either, since it will compare the model with the database and find that they match.
In any case, you will need to revert them first and then create an equivalent one. The command for that is doctrine:migrations:diff. This will compare the model with the schema and generate a migration to get the database in sync. And for this to work you will need to execute --down your migrations first, otherwise they won't be any changes, but potentially losing some data in the process.
If you work in a team, they will be seeing migrations disappear. Some might even be behind in the history and not applied all the migrations. This will soon become a management pain.
There is a rollup command that (with my understanding and never actually used it) cleans stale migrations from the table, dumps a full schema and applies it. This will be your best bet, but be aware that this most like will delete your data.
You could also combine your migrations manually. They are just classes with an up and down methods. Combine all function bodies, apply the cleanup process and call it a day.
Now, if you want to do this it shouldn't be much of a problem. Just replace your outdated versions with your new one and warn everybody about it. But if what you want is to do as they never existed at all and keep a neat commit history, then that's when your teammates will potentially want to kill you, as it will involve rewriting history. When you do that, they will have to rebase all their work.
If you want to do it:

*

*Make backups

*Introduce your changes as early as possible to avoid breaks. Is ok if there are some unused fields in the database for a while, until the model commits catch up. If you do it late and some object need it, someone might be forced to create a migration and break yours in the process.

*Get it right (preferably on the first try). Don't push until you have tested extensively.

*Make backups

Reference for the console commands

A: There isn't a "safe" way of doing it, but if you haven't deployed the migrations then you can safely throw away a series of auto-generated migrations and regenerate them. Just be careful you don't throw away manual migration SQL at the same time.
Normally during the design stage we will:

*

*Use doctrine:schema:update --force until things are fairly stable

*After they are stable, we reset the development database from a snapshot

*Run doctrine:migrations:diff and then add manually migration queries where necessary

A: May be you need to ignore all your migrations and focus on your last state of database schema. If this is what you are wondering to have in final, then you could just hit:
php bin/console doctrine:schema:update --dump-sql to get the corresponding SQL statement, or hit php bin/console doctrine:schema:update --force to apply it actually on database.

A: In general yes you can.
But you should know about that the  Doctrine/Migration save executed migrations in DB . So you should remove unnecessary migration files (possible combine all queries into one), after that update database.
Table name by default "doctrine_migration_version" just delete unnecessary version rows


text:
Q: How do we know that $F[\alpha]$ is a ring? Note that this question is not about the proposition $\alpha$ is algebraic over $F \iff F[\alpha] = F(\alpha)$
I've got the following note in my textbook (given without proof, suggesting the statement is rather trivial), but I've been having some difficulty with it:
Given field $F$, extension field $L/F$ and $\alpha\in L$ then $F[\alpha] = \{a_0 + \alpha a_1 + \cdots + \alpha^m a_m:a_1,\ldots,a_m \in F\}$ is the smallest subring of $L$ containing $\alpha$.
If this is indeed a ring, I agree that it is the smallest, but how do we know that this is indeed a ring? If we have some finite ring $R$ with $m$ elements, then $\alpha^{m+1} \not \in F[\alpha]$ (or so it seems to me), and thus $F[\alpha]$ isn't closed.
Thanks

A: There is an implicit quantification over $m$ here; it might be clearer to write $$F[\alpha]=\{a_0+\alpha a_1+\alpha^2a_2+...+\alpha^ma_m: \color{red}{m\in\mathbb{N}}, a_1,...,a_m\in F\}.$$ There are three key points here:

*

*$m$ is not fixed, and elements of $F[\alpha]$ are allowed to be "arbitrarily (finitely) long."

*There is no requirement that the $a_i$s be distinct.

*Different sequences may name the same element of $L$ (and so of $F[\alpha]$); more abstractly, the obvious homomorphism $F[X]\rightarrow F[\alpha]$ need not be injective.
This should eliminate your concerns about running out of elements if $F$ (or even $L$) is finite. For example, if $F=\mathbb{F}_2$, $L=\mathbb{F}_4$ (where for prime $p$ $\mathbb{F}_{p^n}$ is the unique-up-to-isomorphism finite field of cardinality $p^n$ - note that $\mathbb{F}_2$ sits inside $\mathbb{F}_4$ in a unique way), and $\alpha\in L\setminus F$, one of the elements of $F[\alpha]$ is the sum $$\gamma:=1+\alpha+\alpha^2+\alpha^3+\alpha^4+\alpha^5+\alpha^6+\alpha^7.$$ This element $\gamma$ is defined by a sequence of length longer than even the size of $L$, but that's not a problem; it still is an element of $F[\alpha]$.


text:
Q: How to plot Json data into Array? The Below is my JSON Format.
{
"Data": {
"-template": "Parallax",
"Explore": {
  "IslandLife": {
    "TourismLocation": [
      {
        "Title": "Langkawi",
        "Latitude": "6.350000",
        "Longitude": "99.800000",
        "YouTubePlaylistID": "UUnTJRksbHP4O8JSz00_XRQA",
        "VideosList": {
          "YouTubeVideoID": [
            "7HlMpaSspNs",
            "tzeRnbd77HU",
            "VkIAbDIVJCA",
            "ksJ6kwTe9wM"
          ]
        }
      },
      {
        "Title": "Rawa Island",
        "Latitude": "2.520278",
        "Longitude": "103.975833",
        "YouTubePlaylistID": "UUnTJRksbHP4O8JSz00_XRQA",
        "VideosList": { "YouTubeVideoID": "Kx0dUWaALKo" }
      },
      {
        "Title": "Perhentian Island",
        "Latitude": "5.903788",
        "Longitude": "102.753737",
        "YouTubePlaylistID": "UUnTJRksbHP4O8JSz00_XRQA",
        "VideosList": {
          "YouTubeVideoID": [
            "ZpcdGk5Ee0w",
            "TQTDOGpflZY"
          ]
        }
      },
      {
        "Title": "Sabah Marine Park",
        "Latitude": "4.623326",
        "Longitude": "118.719800",
        "YouTubePlaylistID": "UUnTJRksbHP4O8JSz00_XRQA",
        "VideosList": { "YouTubeVideoID": "VCDTEKOqpKg" }
      }
    ]
  }
}
  }
}

and using Below this function i am retriving data from Json
$.getJSON('json/explore.json', function(data) {
$.each(data, function(key, val) {
    for (var i = 0; i < val.Explore.IslandLife.TourismLocation.length; i++) {
       console.log(val.Explore.IslandLife.TourismLocation[i].Title);
        console.log(val.Explore.IslandLife.TourismLocation[i].Description);
         console.log(val.Explore.IslandLife.TourismLocation[i].Latitude);
         console.log(val.Explore.IslandLife.TourismLocation[i].Longitude);
        console.log(val.Explore.IslandLife.TourismLocation[i].YouTubePlaylistID);
    }
  });
 });

So how to plot "Latitude" and "Longitude" into Double Dimensial array ??
I want my Array Object like this  ??
var locations = [
['Langkawi', 6.350000, 99.800000, 4],
['Rawa Island', 2.520278, 103.975833, 3],
['Perhentian Island', 5.903788, 102.753737, 2],
['Sabah Marine Park', 4.623326, 118.719800, 1]
];

Thanx in Advance :)

A: var locations = [];

$.getJSON('json/explore.json', function(data) {
$.each(data, function(key, val) {
    for (var i = 0; i < val.Explore.IslandLife.TourismLocation.length; i++) {
       var currLoc = val.Explore.IslandLife.TourismLocation[i];
       locations.push([currLoc.Title, currLoc.Latitude, currLoc.Longitude];
    }
  });
});

console.log(locations);

But I can't imagine where do you retrieve the 4th element of every array: if it is a reversed counter, you may change into
...
$.each(data, function(key, val) {
    var t = val.Explore.IslandLife.TourismLocation,
        tLen = t.length;

    for (var i = 0; i < tLen; i++) {
       var currLoc = t[i];
       locations.push([currLoc.Title, currLoc.Latitude, currLoc.Longitude, (tLen - i)]);
    }
  });
});

A: Maybe use this one
$.each($.parseJSON(data), function(i,item)
{

    // item.Explore etc etc

});

A: Get the data and then iterate over the TourismLocation object, adding the values to an array, and then pushing that array to the containing array :
$.getJSON('json/explore.json', function(data) {
    var locations = [];
    $.each(data.Data.Explore.IslandLife.TourismLocation, function(key, val) {
        var loc = [val.Title, val.Latitude, val.Longitude];
        locations.push(loc);
    });
    // use "locations" here, async and all
});

Also note that ajax is asynchronous, so you can't use the newly created array outside the callback function, as it's not available yet.
Not sure what the fourth item in the array is either, but if it's just a number iterating in reverse, you can add that as well :
$.getJSON('json/explore.json', function(data) {
    var locations = [],
        num = data.Data.Explore.IslandLife.TourismLocation.length;

    $.each(data.Data.Explore.IslandLife.TourismLocation, function(key, val) {
        var loc = [val.Title, val.Latitude, val.Longitude, num--];
        locations.push(loc);
    });
    // use "locations" here, async and all
});


text:
Q: Check which 2d array elements are closer to each other if the index is represented as x y positions So I have a two dimensional array that holds some value that doesn't matter.
Let's say that the indexes represent x and y positions on a grid and that I have three points on that grid: The main point and two extra points how do I check which extra point is closest to the main point.
This is the code I tried but it didn't seem to quite work.
if(abs(mainX - extra1X) + abs(mainY - extra1Y) < abs(mainX - extra2X) + abs(mainY - extra2Y))
{
cout << "Extra point 1 is closer" << endl;
}
else if(abs(mainX - extra1X) + abs(mainY - extra1Y) > abs(mainX - extra2X) + abs(mainY - extra2Y))
{
cout << "Extra point 2 is closer" << endl;
}
else
{
cout << "They are equally close" << endl;
}

All help is greatly appreciated :)

A: You are looking for The Distance Formula:
double Distance = sqrt(pow((X1 - X2), 2) + pow((Y1 - Y2), 2));

Implement and execute that for both points, then check the value of Distance for each point to determine which point is closer.
This should work:
double DistanceOne = sqrt(pow((MainX - ExtraXone), 2) + pow((MainY - ExtraYone), 2));
double DistanceTwo = sqrt(pow((MainX - ExtraXtwo), 2) + pow((MainY - ExtraYtwo), 2));

if(DistanceOne < DistanceTwo)
    cout << "Point 1 is closer.\n";
else if (DistanceOne > DistanceTwo)
    cout << "Point 2 is closer.\n";
else
    cout << "Points 1 and 2 are on the same distance from Point Main.\n";

A: If you don't need distance but just need less or more, I want to recommend to
just use square of the two number. you can try this
double dSquare = (mainX - extra1X) * (mainX - extra1X) + (mainY - extra1Y)     * (mainY - extra1Y);
double dSquare = (mainX - extra1X) * (mainX - extra1X) + (mainY - extra1Y) *(mainY - extra1Y);
if(dSquare > dSquare2)
   cout << "point 2 is closer" << endl;
else if(dSquare < dSquare2)
   cout << "point 1 is closer" << endl;
else
   cout << "two point are on the same distance from the main point" << endl;


text:
Q: Integrating Github Enterprise with AWS Codepipeline I have a repository in a [company hosted] GitHub enterprise site that I need to integrate within a CI/CD pipeline in AWS using the CodePipeline service. The CodePipeline service then will connect with a Jenkins Service running in an EC2 instance. I am following this AWS documentation to do this.
Note that this is an enterprise GitHub repo and not hosted on GitHub.com.
I am unable to connect to the GitHub Enterprise site in the "Create a pipeline" wizard. Selecting GitHub as a source only lets me connect to GitHub.com, and not to my organization's enterprise site.
How do I connect to the enterprise GitHub site so that I can add the repo as a source for my codepipeline?

A:
UPDATE: An integration was finally released for github enterprise to work with AWS Codepipeline. Please see this answer by Pedreiro

As Sid Malani said in the comments, there's no straightforward or direct way to use a privately hosted GitHub Enterprise Repository in AWS CodePipeline.
One way would be to use CodeBuild, which allows to add custom github repositories which can then be used in CodePipeline. This, however, should only be considered as a stop-gap solution.
Thank you Sid Malani for the alternative strategy

A: I doubt AWS will ship this feature anytime soon (hopefully I eat my words) since the workaround is well-documented and works fine. The gist of it can be found here, which I'll summarize as follows:

*

*Create a CodeBuild project (which can take GitHub Enterprise as a source) which essentially just listens to a push event (webhook) of your development or master branch and outputs a .zip file of the source-code into an S3 bucket.

*Use the S3 bucket as the source of your CodePipeline.

A: The official integration was finally released.
https://aws.amazon.com/about-aws/whats-new/2020/09/aws-codepipeline-supports-github-enterprise-server
Here is the documentation:
https://docs.aws.amazon.com/codepipeline/latest/userguide/connections-ghes.html

A: There is a way to integrate 3rd party Git repos with AWS CodePipeline. AWS suggested the following process. It used S3 buckets and API Gateways and Lambdas to connected Github enterprise repos to CodePipeline. It's not ideal but it can work.
Unofficial: I've heard CodePipeline support for Github Enterprise will be out second half of 2019.


text:
Q: Convert two columns into two lists for plotting with Python I am a beginner programmer and I am having troubles with the following:
I have a dataset in a python file which I would like to plot. The data looks as follows:
0.00000000,0.00000000

1.00000000,2.92610390

2.00000000,2.91658800

3.00000000,2.90708989

4.00000000,2.89760956

I would like to plot the first number in each row as x-axis, and the second number in each row as y-axis. How would I go about this? I have tried using pandas and converting it to two lists, but this did not work for me.
Thanks in advance!

A: If file has no header you can pass names parameter to read_csv and then use DataFrame.plot:
df = pd.read_csv(file, names = ['x', 'y'])

df.plot(x= 'x', y= 'y')

#thank you Mr. T
plt.show()


text:
Q: Polygon/contour around subset of vertices on graph (more precise than mark.groups in igraph) Problem definition
I need to produce a number of specific graphs, and on these graphs, highlight subsets of vertices (nodes) by drawing a contour/polygon/range around or over them (see image below).

*

*A graph may have multiple of these contours/ranges, and they may overlap, iff one or more vertices belong to multiple subsets.

*Given a graph of N vertices, any subset may be of size 1..N.

*However, vertices not belonging to a subset must not be inside the contour (as that would be misleading, so that's priority no. 1). This is gist of my problem.

*All these graphs happen to have the property that the ranges are continuous, as the data they represent covers only directly connected subsets of vertices.

*All graphs will be undirected and connected (no unconnected vertices will ever be plotted).

Reproducible attempts
I am using R and the igraph package. I have already tried some solutions, but none of them work well enough.
First attempt, mark.groups in plot.igraph:
library(igraph)
g = make_graph("Frucht")
l = layout.reingold.tilford(g,1)
plot(g, layout=l, mark.groups = c(1,3,6,12,5), mark.shape=1)
 # bad, vertex 11 should not be inside the contour
plot(g, layout=l, mark.groups = c(1,6,12,5,11), mark.shape=1)
 # 3 should not be in; image below
 # just choosing another layout here is not a generalizable solution

The plot.igraph calls igraph.polygon, which calls convex_hull (also igraph), which calls xspline. The results is, from what I understand, something called a convex hull (which otherwise looks very nice!), but for my purposes that is not precise enough, covering vertices that should not be covered.
Second attempt with contour. So I tried implementing my own version, based on the solution suggested here:
library(MASS)
xx <- runif(5, 0, 1);yy <- abs(xx)+rnorm(5,0,0.2)
plot(xx,yy, xlim=c( min(xx)-sd(xx),max(xx)+sd(xx)), ylim =c( min(yy)-sd(yy),    max(yy)+sd(yy)))
dens2 <- kde2d(xx, yy, lims=c(min(xx)-sd(xx), max(xx)+sd(xx), min(yy)- sd(yy), max(yy)+sd(yy) ),h=c(bandwidth.nrd(xx)/1.5, bandwidth.nrd(xx)/ 1.5), n=50 )
contour(dens2, level=0.001, col="red", add=TRUE, drawlabels=F)

The contour plot looks in principle like something I could use, given enough tweaking of the bandwidth and level values (to make the contour snug enough so it doesn't cover any points outside the group). However, this solution has the drawback that when the level value is too small, the contour breaks (doesn't produce a continuous area) - so if I would go that way, controlling for continuity (and determining good bandwidth/level values on the fly) automatically should be implemented. Another problem is, I cannot quite see how could I plot the contour over the plots produced by igraph: the layout.* commands produce what looks like a coordinate matrix, but the coordinates do not match the axis coordinates on the plot:
# compare:
layout.reingold.tilford(g,1)
plot(g, layout=l, axes=T)

The question:
What would be a better way to achieve the plotting of such ranges on graphs (ideally igraphs) in R that would meet the criteria outlined above - ranges that include only the vertices that belong to their subset and exclude all else - while being continous ranges?
The solution I am looking for should be scalable to graphs of different sizes and layouts that I may need to create (so hand-tweaking each graph by hand using e.g. tkplot is not a good solution). I am aware that on some graphs with some vertex groups, meeting both the criteria will indeed be impossible in practise, but intuitively it should be possible to implement something that still works most of the time with smallish (10..20 vertices) and not-too-complex graphs (ideally it would be possible to detect and give a warning if a perfectly fitting range could not be plotted). Either an improvement of the mark.groups approach (not necessarily within the package, but using the hull-idea mentioned above), or something with contour or a similar suitable function, or suggesting something else entirely would be welcome, as long as it works (most of the time).
Update stemming from the discussion: a solution that only utilizes functions of core R or CRAN packages (not external software) is desirable, since I will eventually want to incorporate this functionality in a package.
Edit: specified the last paragraph as per the comments.

A: The comment area is not long enough to fit my answer there, so I'm putting this here, although I'd rather post it as a comment as it is not a full solution.
Quite a long throw, but the first thing that popped into my mind is support vector machines. The idea would be that you construct a support vector machine classifier that classifies your points into two groups (in or out) based on the coordinates of the vertices, using some non-linear kernel function (I would try the radial basis function). Then you plot the separating hyperplane of the trained support vector machine. One drawback is that the area that you obtain this way might be unbounded (i.e. go to infinity in some directions), so this idea definitely requires some further thinking, but at least that's one possible direction to go.


text:
Q: Exclude resources in JSF I'm using Primefaces. For some pages I want to exclude the resources which are included by primefacs, especially the theme resource.
<link type="text/css" rel="stylesheet" href="/context/javax.faces.resource/theme.css?ln=primefaces-owntheme" />

I try that with a SystemEventListener as following:
public class PrimeFacesResourceRemover implements javax.faces.event.SystemEventListener {

  @Override
  public void processEvent(SystemEvent event) throws AbortProcessingException {
    FacesContext context = FacesContext.getCurrentInstance();

    UIViewRoot viewRoot = context.getViewRoot();
    for (UIComponent resource : viewRoot.getComponentResources(context, "head")) {

        Map<String, Object> attrs = resource.getAttributes();
        String resourceLibrary = (String) attrs.get("library");
        String resourceName = (String) attrs.get("name");

        if ("primefaces-owntheme".equals(resourceLibrary) && "theme.css".equals(resourceName)) {

            // Remove resource from view
            context.getViewRoot().removeComponentResource(context, resource, HEAD);
        }
    }
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public boolean isListenerForSource(Object source) {
    return (source instanceof UIViewRoot);
  }
}

and in the faces-config.xml
    <application>
      <system-event-listener>
        <system-event-listener-class>
          com.mycompany.mavenproject1.PrimeFacesResourceRemover
        </system-event-listener-class>
        <system-event-class>
          javax.faces.event.PostAddToViewEvent
        </system-event-class>
      </system-event-listener>
    </application>

This works well, when I include a resouce on a page manually, but those not work with the resouces which are included by Primefaces. How can I remove those resouces?

A: The theme.css is not been added as a dynamic component resource, but it's been hardcoded in PrimeFaces' HeadRenderer. The OmniFaces CombinedResourceHandler was also struggling with this.
The solution is rather simple: override it with a custom HeadRenderer (without any @ResourceDependency on theme.css, of course!):
public class HeadRenderer extends Renderer {

    @Override
    public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
        context.getResponseWriter().startElement("head", component);
    }

    @Override
    public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
        // NOOP.
    }

    @Override
    public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
        for (UIComponent resource : context.getViewRoot().getComponentResources(context, "head")) {
            resource.encodeAll(context);
        }

        context.getResponseWriter().endElement("head");
    }

}

Register it as follows in webapp's faces-config.xml:
<render-kit>
    <renderer>
        <component-family>javax.faces.Output</component-family>
        <renderer-type>javax.faces.Head</renderer-type>
        <renderer-class>com.example.HeadRenderer</renderer-class>
    </renderer>
</render-kit>

A: For all of you who would like to remove theme.css on all pages (that's the first thing I am doing), and still don't know this trick.
You'll need to drop these few lines in your web.xml:
<context-param>
    <param-name>primefaces.THEME</param-name>
    <param-value>none</param-value>
</context-param>


text:
Q: How to edit questions without having to be peer-reviewed?
Possible Duplicate:
How does editing work?

I'm asking whether I can edit posts without having my edit to be peer-reviewed? I thought this will happen when my reputation reaches +1500. But I still have my edit to be peer-reviewed.

A: On Stack overflow, this requires 2000 rep: https://stackoverflow.com/privileges/edit
You can view the Privileges on any SE site and see the amount of rep needed (not sure if they are all the same).


text:
Q: Mysql Lock times in slow query log I have an application that has been running fine for quite awhile, but recently a couple of items have started popping up in the slow query log.
All the queries are complex and ugly multi join select statements that could use refactoring. I believe all of them have blobs, meaning they get written to disk. The part that gets me curious is why some of them have a lock time associated with them. None of the queries have any specific locking protocols set by the application. As far as I know, by default you can read against locks unless explicitly specified.
so my question: What scenarios would cause a select statement  to have to wait for a lock (and thereby be reported in the slow query log)? Assume both INNODB and MYISAM environments.
Could the disk interaction be listed as some sort of lock time? If yes, is there documentation around that says this?
thanks in advance.

A: MyISAM will give you concurrency problems, an entire table is completely locked when an insert is in progress.
InnoDB should have no problems with reads, even while a write/transaction is in progress due to it's MVCC.
However, just because a query is showing up in the slow-query log doesn't mean the query is slow - how many seconds, how many records are being examined?
Put "EXPLAIN" in front of the query to get a breakdown of the examinations going on for the query.
here's a good resource for learning about EXPLAIN (outside of the excellent MySQL documentation about it)

A: I'm not certain about MySql, but I know that in SQL Server select statements do NOT read against locks.  Doing so will allow you to read uncommitted data, and potentially see duplicate records or miss a record entirely.  The reason for this is because if another process is writing to the table, the database engine may decide it's time to reorganize some data and shifts it around on disk.  So it moves a record you already read to the end and you see it again, or it moves one from the end up higher where you've already past.
There's a guy on the net somewhere who actually wrote a couple of scripts to prove that this happens and I tried them once and it only took a few seconds before a duplicate showed up.  Of course, he designed the scripts in a fashion that would make it more likely to happen, but it proves that it definitely can happen.
This is okay behaviour if your data doesn't need to be accurate and can certainly help prevent deadlocks.  However, if you're working on an application dealing with something like people's money then that's very bad.
In SQL Server you can use the WITH NOLOCK hint to tell your select statement to ignore locks.  I'm not sure what the equivalent in MySql would be but maybe someone else here will say.


text:
Q: Is Couchbase able to replicate only a specific subset of data to a specific node? I have the following usecase:
I want to use Couchbase on a server to store data, and use Couchbase for Android on mobile devices. I would like to use the Couchbase synchronisation to be able to work online and offline with the data and have it synced up eventually. But I don't want the different clients to sync all the data onto the device, just a specific subset. What subset a client should sync, should be controlled by the client, and should be changed dynamically.
Is Couchbase able to handle such a scenario? And if, could you give me some hints to the matching documentations.

A: Couchbase can not do this. More importantly I can't think of any solution that would. Couchbase is a clustered nosql solution. Others are caching solutions or databases. They store data. The logic of syncing the data between different stores and the syncing of sub-sets of data would have to be done within your application.

A: Sync Gateway now handles the logic permitting users access to channels, which then contain subsets of data based on which channel(s) each document belongs to.
http://docs.couchbase.com/sync-gateway/#channels