text:
Q: Is it possible to insert data into table using two select statements in one query? I am working with databases in which I have 3 tables one is skill table the other one is experience and the third one is Experience_skill table in this table I have foreign keys now the question is both foreign keys are primary keys as well. Let say I am storing data into skill table as well as in experience table how can I insert the the both keys data there in Experience_skill table. I have tried following queries.
insert into Experience_skill(eid, Skill_Id)
select eid
from Experience
where eid=2
union
select Skill_Id
from Skills
where Skill_Id=2

error I get:

The select list for the INSERT statement contains fewer items than the insert list. The number of SELECT values must match the number of INSERT columns.
  Than i tried this one.

insert into Experience_skill(eid)select eid from Experience where eid=2

it gives me this error:

Cannot insert the value NULL into column 'Skill_Id', table 'resume.dbo.Experience_skill'; column does not allow nulls. INSERT fails.
  Please help me out
  here are the snapshots of the table first snap shot is of skill table

the second one is experience table
And this one is EXperience_skill table where  i have my foreign keys

A: When using INSERT INTO, you need to supply ALL of the columns in the destination table (that do not allow NULLs) in each ROW of the SELECT.


text:
Q: Update XML file tag text in QT c++

<HmiRequest>
    <Type>AlertPopup</Type>
    <Id>123</Id>
    <Order>new</Order>
    <HmiContent>
        <ATBev_1000_Label_NatureOfCall>eCall</ATBev_1000_Label_NatureOfCall>
    </HmiContent>
</HmiRequest>

In the above xml file I wan to update Id value "123" with 111.
123 to 111.
I am able to update tag name but the value how can we change ?

A: Try this
QDomDocument doc;
doc.setContent(QString("<HmiRequest>    <Type>AlertPopup</Type>    <Id>123</Id>    <Order>new</Order>    <HmiContent>        <ATBev_1000_Label_NatureOfCall>eCall</ATBev_1000_Label_NatureOfCall>    </HmiContent></HmiRequest>"), false);
QDomNodeList lstNodes = doc.documentElement().childNodes();
int iCount = lstNodes. count();
for (int i = 0; i < iCount; ++i)
{
    if (lstNodes.at(i).nodeName() == "Id")
    {
        QDomElement newIdTag = doc.createElement(QString("Id"));
        QDomText idVal = doc.createTextNode(QString("111"));
        newIdTag.appendChild(idVal);
        doc.documentElement().replaceChild(newIdTag, lstNodes.at(i));
        break;
    }
}
qDebug() << doc.toString(4);

redpajama_set_name: RedPajamaStackExchange


text:
Q: API Gateway to allow requests from both a VPC Endpoint OR Source IP? I have a private API Gateway that can only be accessed via a VPC Endpoint.
I want the Resource Policy to only allow requests in if the request is either through the
A - VPC Endpoint (e.g. a Lambda that is within the same VPC)
OR
B - Not within the VPC, but from an external set of IP addresses/CIDR blocks.
I know A can be achieved with:
"Condition": {
      "StringEquals": {
             "aws:SourceVpce": "vpce-xyz"
       }
}

I know B can be achieved with:
"Condition": {
       "IpAddress": {
             "aws:SourceIp": [
                    "xx.xx.xx.xx/32"
             ]
       }
}

Is it possible however to apply them both, in an OR style manner?
The IP addresses/CIDR blocks are permitted on the VPC's inbound rules.
Lambda's within the same VPC can access the private API gateway.
Thanks
Edit - Full example of the policy:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": "arn:aws:execute-api:eu-west-1:x:y/*",
            "Condition": {
                "StringEquals": {
                    "aws:SourceVpce": "vpce-123"
                },
                "IpAddress": {
                    "aws:SourceIp": [
                        "1234",
                        "1234"
                    ]
                }
            }
        }
    ]
}

A: Yes, it should be possible. You need two IAM statements to obtain OR.
So basically the second statement is exactly same as first one, except the condition. For example:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": "arn:aws:execute-api:eu-west-1:x:y/*",
            "Condition": {
                "StringEquals": {
                    "aws:SourceVpce": "vpce-123"
                }
            }
        },
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": "arn:aws:execute-api:eu-west-1:x:y/*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": [
                        "1234",
                        "1234"
                    ]
                }
            }
        }
    ]
}


text:
Q: XSLT Transformation: Transform the message or sent an empty message depending on a condition I am trying to process a message and depending on a condition I want to apply a transformation, or to send an empty message (just ) depending on that condition, but I am not able to generate the empty message.
I was expecting to not send anything not putting content inside the when element, , however it sends all the message (without the transformation), how can I specify not to send a message if the condition inside the when clause is true?
This is the xml I need to transform:
<?xml version="1.0" encoding="utf-8"?>
<A1>
    <B1 d2p1:type="UntrackedItem"
          xmlns:d2p1="http://www.w3.org/2001/XMLSchema-instance">
        <C1>SI</C1>
    </B1>
</A1>

This is the xslt that I am using:
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml"
                indent="yes"
                encoding="UTF-8"/>
    <!--This will add the attribute Origin to the main element-->
    <xsl:template match="/">
        <xsl:choose>
            <xsl:when test="A1/B1/C1[text() = 'SI']">
                <!--Empty message-->
            </xsl:when>
            <xsl:otherwise>
                <!--Applies the transformation-->
                <xsl:apply-templates select="@*|node()"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
    <xsl:template match="A1">
        <xsl:element name="A1">
            <xsl:attribute name="Orig">
                <xsl:value-of select="22"/>
            </xsl:attribute>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:element>
    </xsl:template>
    <!-- This will copy all the nodes that do not match the above -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

And the expected outputs are the following:
1- If the condition is accomplished:
<?xml version="1.0" encoding="UTF-8"?>

2- If the condition is not accomplished:
<?xml version="1.0" encoding="UTF-8"?>
<A1 Orig="22">
      <B1 xmlns:d2p1="http://www.w3.org/2001/XMLSchema-instance"
       d2p1:type="UntrackedItem">
            <C1>SI</C1>
      </B1>
</A1>


text:
Q: I can't load the sp package in R I want to use RGDAL and Raster and the sp package is a dependency of Raster. When I try to load the sp Package I get an error message and the Raster package can't load
I have uninstalled the package, re-downloaded and re-installed and nothing changed. Updating R to 3.6.0 had no effect either.
Error Message reads:

"Error: package or namespace load failed "sp" in rbind(info, getNameSpace(env, "s3methods")) number of columns of matrices must match (see arg 2)


text:
Q: How to achieve thread-safety for my Java YAML-API? The example yaml file: example.yml is represented as a DreamYaml object.
That file is loaded and parsed, at initialization.
Now let's imagine multiple threads are loading, editing and saving that file at the same time. So that multiple DreamYaml objects get created for the same file. What is the best way of achieving thread safety in this scenario?
My idea was calling a static synchronized lockFile() method inside of the load() method and unlockFile() inside of the save() method. The problem with this is, that you would have to call save() at the end every time for the file to unlock and also this could block the file for other threads for a lot longer than actually needed.
I guess the best way would be calling the lockFile() method inside of save(), then inside of that locked section, load() the file again so that the current objects in-memory values get updated and match the actual/'real' current values. Then simply save() the file and release the lock. In this case, I would have to make sure, that the recent in-memory changes made to the values are not overwritten from the load() call. I don't think there are any more major drawbacks to this approach. *Edit: I just found out that the major drawback of this approach is that its not actually thread safe. thanks to https://stackoverflow.com/a/68313798/13600212
**Edit: This is what I came up with:
    /**
     * If you access the same yaml file from multiple threads, its recommended to lock the file before loading it.

     * Remember to {@link #unlockFile()} so that other threads can work with the file too.

     * If you don't do that, other threads will stay stuck at {@link #lockFile()} forever.

     * Example:

     *

     *     DreamYaml yaml = new DreamYaml("example.yml");
     *     yaml.lockFile();
     *     yaml.load();
     *     // Do changes to file here
     *     yaml.save();
     *     yaml.unlockFile();
     *

     */
    public synchronized void lockFile(){
        if (file!=null){
            ReentrantLock lock = null;
            synchronized (pathsAndLocks){
                if (pathsAndLocks.containsKey(file.getAbsolutePath()))
                    lock = pathsAndLocks.get(file.getAbsolutePath()); // If another thread has already the locked, the current thread will wait until it gets unlocked
                else{
                    lock = new ReentrantLock();
                    pathsAndLocks.put(file.getAbsolutePath(), lock);
                }
            }
            lock.lock();
        }
    }

    /**
     * If you access the same yaml file from multiple threads, its recommended to lock the file before loading it.

     * Remember to {@link #unlockFile()} so that other threads can work with the file too.

     * If you don't do that, other threads will stay stuck at {@link #lockFile()} forever.

     * Example:

     *

     *     DreamYaml yaml = new DreamYaml("example.yml");
     *     yaml.lockFile();
     *     yaml.load();
     *     // Do changes to file here
     *     yaml.save();
     *     yaml.unlockFile();
     *

     */
    public synchronized void unlockFile(){
        if (file!=null){
            ReentrantLock lock = null;
            synchronized (pathsAndLocks){
                if (pathsAndLocks.containsKey(file.getAbsolutePath())){
                    lock = pathsAndLocks.get(file.getAbsolutePath()); // If another thread has already the locked, the current thread will wait until it gets unlocked
                    lock.unlock();
                    if(!lock.hasQueuedThreads())
                        pathsAndLocks.remove(file.getAbsolutePath());
                }
            }
        }
    }

In the code above the pathsAndLocks variable is a hashmap containing the yaml files paths and their locks. That means that there is one ReentrantLock per file. Now the users can call lockFile() before loading the yaml file to achieve thread safety and unlockFile() when they are done.
But I am not entirely sure... so what do you think about this?
Further details about my Java-YAML API: https://github.com/Osiris-Team/Dream-Yaml

A: Locking the data only when saving is not thread-safe.
Assume some item in the data holds the value 0. Two threads concurrently want to increase the value by 1. The following classical race condition can occur:
Both threads read in 0 concurrently. Both calculate the new value to be 1. One thread acquires the lock, loads current data, sets the item to 1, saves. Other thread then acquires the lock, loads the updated data, replaces the item with 1 because the new value has already been calculated, then saves. Result is the the item in the file is 1 when it should be 2.
Regardless of whether you save a value to a file or keep it in memory, to achieve thread safety, you do need an exclusive lock (or an equivalent mechanism) in place from the time you read the value to the time you commit the updated value.
The question of what is the best way to achieve thread safety cannot be answered generally. It depends on your use-case and may need extensive analysis of the behavior of your system. As already mentioned, an exclusive lock from load to save will work (does not detect external modification of the file of course).
It is unclear why you want to save and load the data all the time, it seems far simpler to load the file once on startup and keep it in memory. When you make modifications, you save the file but keep it in memory. This would only be bad if the file is a) large and b) modifications happen only sparsely.


text:
Q: Algorithms - Network Flow Assuming G = (V, E) be a bipartite graph, M is maximum matching i.e, M is a matching with maximum number of edges.
Assuming A, B are two parts of bipartite graph and X is set of unmatched vertices in A,
and Y is set of matched vertices in B. If each edge has capacity 1, give with proof the
value of c((X ∪Y ), V (X ∪Y )) in terms of |V | and |M |.
How and where do I start to prove c((X ∪Y ), V (X ∪Y )) in terms of |V | and |M |.


text:
Q: Three.js - scaling background image to fit window, without stretching it When using scene.background the texture is stretched to fit the window size.
I'm trying to reproduce the CSS cover attribute behavior as described on the MDN page:

Scales the image as large as possible without stretching the image.
  If the proportions of the image differ from the element, it is cropped
  either vertically or horizontally so that no empty space remains.

I understand the repeat and offset texture attributes should be used, but I'm not sure how.

A: Same problem with you. After digging docs I resolved it. Below code should work for people struggle with this.
targetWidth is your surface or canvas width.
imageWidth is width of texture need fit to target.
const targetAspect = targetWidth / targetHeight;
const imageAspect = imageWidth / imageHeight;
const factor = imageAspect / targetAspect;
// When factor larger than 1, that means texture 'wilder' than target。
// we should scale texture height to target height and then 'map' the center  of texture to target, and vice versa.
scene.background.offset.x = factor > 1 ? (1 - 1 / factor) / 2 : 0;
scene.background.repeat.x = factor > 1 ? 1 / factor : 1;
scene.background.offset.y = factor > 1 ? 0 : (1 - factor) / 2;
scene.background.repeat.y = factor > 1 ? 1 : factor;


text:
Q: Inconsistency in Swift optional protocol behaviour Coming from .Net, I am trying to learn Swift3/iOS and got puzzled by the following apparent inconsistent behaviour of optional protocol members. I suspect its something got to do with the juggling between objc/swift words, but what am I missing here actually?
// In playground, given below:

@objc protocol SomePtotocol {
    @objc optional func someMethod()
}

class SomeDelegate: NSObject, SomePtotocol {
}

class SomeController: NSObject {
    var delegate: SomePtotocol = SomeDelegate()
}

// This works and compiles without error

let controller = SomeController()
controller.delegate.someMethod?()      // No error, typed as '(() -> ())?'

// But this fails to even compile ??

let delegate = SomeDelegate()
delegate.someMethod?()  // Error: 'SomeDelegate' has no member 'someMethod'

I would expect either both to fail or both pass, so if someone could please enlighten me on this anomaly.

A: The difference between the two blocks of code is the type of the variable involved.
In the first block, delegate is explicitly typed as SomePtotocol, and  this protocol defines the someMethod method, so your statement is valid.
In the second block, delegate is implicitly typed as SomeDelegate and although this class conforms to SomePtotocol, it doesn't implement the optional method someMethod, so you get an error.
If you change your second block to
let delegate: SomePtotocol = SomeDelegate()
delegate.someMethod?()

which is equivalent to the first block, then there is no error.


text: Q: Bridging two ethernet connections I have two network cards/interfaces: enp5s0 (which is connected to a 15m distant router connected to the internet) and enp4s0 (which is connected to another router not connected to the internet). I would like to use enp4s0 router wifi to extend enp5s0 internet connection. I tried to successfully create a bridged connection but when I connect to enp4s0's wifi I still can't connect to the Internet. Any hint?


text:
Q: hive orc writer.close() return null pointer exception when running on windos I am creating the orc file and adding row to the file. its working on linux. But its not working on the windows.writer.close() return NPE.
    please find the code below and stack trace below and give me help on the same.
    code:--
    package com.testing;
import java.io.IOException;
import java.util.Arrays;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.io.orc.OrcFile;
import org.apache.hadoop.hive.ql.io.orc.OrcFile.WriterOptions;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.apache.hadoop.hive.ql.io.orc.OrcFile;
import org.apache.hadoop.hive.ql.io.orc.OrcFile.WriterOptions;
import org.apache.hadoop.hive.ql.io.orc.Writer;

public class Typical  {

    public static void main(String args[]){
        String filePath ="C:/usr/tmp/EDMS_FILE_ARCHIVE_.orc";
        TypeInfo typeInfo=TypeInfoUtils.getTypeInfoFromTypeString("struct<a:string>");
          ObjectInspector inspector=TypeInfoUtils.getStandardJavaObjectInspectorFromTypeInfo(typeInfo);
          WriterOptions options=OrcFile.writerOptions(new Configuration()).inspector(inspector);
          //Path path=new Path(temporaryFolder.getRoot().getCanonicalPath(),"part-00000");
          Writer writer;
        try {
            writer = OrcFile.createWriter(new Path(filePath),options);
             writer.addRow(Arrays.asList("hello"));
              writer.close();

        } catch (IllegalArgumentException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

statcktrace:--

Exception in thread "main" java.lang.NullPointerException
    at java.lang.ProcessBuilder.start(Unknown Source)
    at org.apache.hadoop.util.Shell.runCommand(Shell.java:482)
    at org.apache.hadoop.util.Shell.run(Shell.java:455)
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:715)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:808)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:791)
    at org.apache.hadoop.fs.RawLocalFileSystem.setPermission(RawLocalFileSystem.java:656)
    at org.apache.hadoop.fs.FilterFileSystem.setPermission(FilterFileSystem.java:490)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:462)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:428)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:908)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:889)
    at org.apache.hadoop.hive.ql.io.orc.WriterImpl.getStream(WriterImpl.java:1967)
    at org.apache.hadoop.hive.ql.io.orc.WriterImpl.flushStripe(WriterImpl.java:1984)
    at org.apache.hadoop.hive.ql.io.orc.WriterImpl.close(WriterImpl.java:2289)
    at com.testing.Typical.main(Typical.java:30)

Advance Thanks
Hanuman

A: Its an issue with using orc library on windows and writing to local file:
java.lang.NullPointerException
at java.lang.ProcessBuilder.start(Unknown Source)

Program wants to execute chmod command but its not present on windows - here you get the NPE.
I found workaround which i don't like:

*

*dowload winutils.exe

*System.setProperty("hadoop.home.dir", "c:\path\to\winutils"); the real path to wintutils libs should be c:\path\to\winutils\bin


text:
Q: Solve the Diophantine equation $2xy + 3y^{2} = 24$
Solve the equation $$2xy + 3y^{2} = 24, \qquad x, y \in \mathbb{Z}$$

I tried by stating that $x$ and $y$ cannot both be odd and that y cannot be odd. So either $x$ and $y$ are both even or $x$ is even and $y$ is odd. Then I was trying take the residues modulo $3$ and modulo $8$ but could not arrive at a conclusion. Please help me solve this further.

A: Equation can be written as $y*(2x+3y)=24$. Thus $y$ must be an integer factor of $24$. This should get you to a manageable range of possibilities.

A: As you have rightly pointed out, y can never be even.
Now note that the equation can be written as $y∗(2x+3y)=24$. Thus $y$ must be an integer factor of $24$.
You will thus get the following results : -
$y=2,4,6,8,12$.
So this will give you $(x,y)=\{(3,2), (-3, -2),(−3,4),(3,-4),(−7,6),(7,-6),(−17,12),(17,-12)\}$
Only 8 does not give any solution.
So here is the solution you asked for.


text:
Q: Implement extensibility on callback? Currently, I am working on an API, and developers can subscribe to it to know the updates.
So right now I am implementing an interface IResult , so that I can send different parameters in the callback result. The problem right now is if in the future, I want to add a new callback, I have to add an argument in the method, and developers also need to change their method call. Is there a good solution for this?
public interface IResult
{
    int i { get; set; }
}

public class ConcreteResult : IResult
{
    public int i
    {
        get;set;
    }
}

public class MyAPI
{
    public delegate void MyAPIDelegate(IResult result);

    public void StartService(MyAPIDelegate callback, MyAPIDelegate callback2)
    {
        //step 1
        int i = 0;
        ConcreteResult result1 = new ConcreteResult();
        result1.i = i;
        callback(result1);
        //step 2
        i += 1;
        ConcreteResult result2 = new ConcreteResult();
        result2.i = i;
        callback2(result2);
        //potentially added in the future
        //i += 1;
        //callback3();
    }

    public void main()
    {
        //developers use my API
        StartService(developerCallback, developerCallback2);
    }
    private void developerCallback(IResult result)
    {
        Console.WriteLine(result.i);
    }
    private void developerCallback2(IResult result)
    {
        Console.WriteLine(result.i);
    }
}

A: Oddly everyone is recommending events, but nobody is showing an example.  I'll bite.
Judging by the naming conventions I'm guessing you come from Java land.  (C# methods are generally PascalCase).  C# has events, which make things like this much simpler.  I recommend you study them up, as they're quite common in C# code.
All you have to do is define a public event on your class, and have that class invoke the event where necessary.  (do ?. because an unsubscribed event is weirdly null).
Then from the consuming class, you subscribe handlers for it using +=.
This allows you to add new events in the future without your consumers having to worry about it.
public class MyAPI
{
    public event Action<IResult> Callback1;

    public event Action<IResult> Callback2;

    public void StartService()
    {
        //step 1
        int i = 0;
        ConcreteResult result1 = new ConcreteResult();
        result1.i = i;
        Callback1?.Invoke(result1);
        //step 2
        i += 1;
        ConcreteResult result2 = new ConcreteResult();
        result2.i = i;
        Callback2?.Invoke(result2);
        //potentially added in the future
        //i += 1;
        //callback3();
    }
}

public static class Program {
    public static void Main()
    {
        //developers use my API
        var api = new MyAPI();
        api.Callback1 += DeveloperCallback;
        api.Callback2 += DeveloperCallback2;

        api.StartService();
    }
    private static void DeveloperCallback(IResult result)
    {
        Console.WriteLine(result.i);
    }
    private static void DeveloperCallback2(IResult result)
    {
        Console.WriteLine(result.i);
    }
}

Also for simple event handlers, you can subscribe inline:
api.Callback1 += result =>
    {
        Console.WriteLine(result.i);
    };

Or even simpler for one-liners:
api.Callback1 += result => Console.WriteLine(result.i);

Since you asked, another option a bit more heavier than simple events, but eventually more powerful is Reactive Extensions.  If you want to use these, then you can write code like this:
using System.Reactive.Subjects;

public class MyAPI
{
    private readonly Subject<IResult> callback1 = new Subject<IResult>();

    private readonly Subject<IResult> callback2 = new Subject<IResult>();

    public void StartService()
    {
        //step 1
        int i = 0;
        ConcreteResult result1 = new ConcreteResult();
        result1.i = i;
        callback1.OnNext(result1);
        //step 2
        i += 1;
        ConcreteResult result2 = new ConcreteResult();
        result2.i = i;
        callback2.OnNext(result2);
    }

    public IObservable<IResult> Callback1 => this.callback1;

    public IObservable<IResult> Callback2 => this.callback2;
}

public static class Program
{
    public static void Main()
    {
        var api = new MyAPI();

        // Subscribing returns a disposable subscription, and disposing it unsubscribes.
        // That means you can use lambda syntax and still unsubscribe later
        IDisposable subscription =
            api.Callback1.Subscribe(result => Console.WriteLine(result.i));
        api.StartService(); // Writes result.

        // Once disposed, event is no longer called
        subscription.Dispose();
        api.StartService(); // Doesn't write result.

        // Since IDisposable is a special thing that can be scoped to using blocks in C#, you can do the following:
        using (api.Callback1.Subscribe(result => Console.WriteLine(result.i)))
        {
            api.StartService(); // Writes result
        }
        api.StartService(); // Doesn't write result

    }
}

A: I strongly recommend using events, like @Vikhram suggested, but here is your example, modified to use a class as you requested.
Notice that I did not specify a Callback3 when calling the function.  The API uses .? when calling them, instead of just ., so that it doesn't cause a NullReferenceException if the developer doesn't pass one in.
When you add more callbacks, just add additional properties to MyCallbackInfo, and invoke them the same as the existing ones.
public interface IResult {... }

public class ConcreteResult : IResult {...}

public class MyStartServiceCallbackInfo
{
    public MyAPI.MyAPIDelegate Callback1 { get; set; }
    public MyAPI.MyAPIDelegate Callback2 { get; set; }
    public MyAPI.MyAPIDelegate Callback3 { get; set; }
}

public class MyAPI
{
    public delegate void MyAPIDelegate(IResult result);

    public void StartService(MyStartServiceCallbackInfo callbacks)
    {
        ...
        callbacks?.Callback1(result1);
        ...
        callbacks?.Callback2(result2);
        ...
        callbacks?.Callback3(result3);
    }

    public void main()
    {
        StartService(new MyCallbackInfo()
        {
            Callback1 = developerCallback,
            Callback2 = developerCallback2,
        });
    }

    private void developerCallback(IResult result)
    {
        Console.WriteLine(result.i);
    }

    private void developerCallback2(IResult result)
    {
        Console.WriteLine(result.i);
    }
}


text:
Q: how does the neural netwok definition in pytorch use pyton classes in order to understand how this code works, I have written a small reproducer. How does the self.hidden variable use a variable x in the forward method?
enter code class Network(nn.Module):
def __init__(self):
    super().__init__()

    # Inputs to hidden layer linear transformation
    self.hidden = nn.Linear(784, 256)
    # Output layer, 10 units - one for each digit
    self.output = nn.Linear(256, 10)

    # Define sigmoid activation and softmax output
    self.sigmoid = nn.Sigmoid()
    self.softmax = nn.Softmax(dim=1)

def forward(self, x):
    # Pass the input tensor through each of our operations
    x = self.hidden(x)
    x = self.sigmoid(x)
    x = self.output(x)
    x = self.softmax(x)

    return x

A: You misunderstood what self.hidden = nn.Linear(784, 256) does. You wrote that:

hidden is defined as a function

but this is not true. self.hidden is an object of the class nn.Linear. And when you call self.hidden(...), you are not passing arguments to nn.Linear; you are passing arguments to __call__ (defined in the nn.Linear class).
If you want more details on that, I have expanded on how it works in PyTorch: see this answer.


text:
Q: In ionic 4, i got cordova not installed i have tried lot of things still cordova not installed.

What to do Next?

A: Ionic 4 introduced two method.one is cordova plugin another one is capacitor.ionic 4 not installing default plugin in cordova
if you  want cordova plungin.create ionic      project.Using following commands
ionic cordova build andriod
ionic cordova build ios


text:
Q: Django Making 1000 Duplicate Queries Model:
class Comment(MPTTModel):

    submitter = models.ForeignKey(User, blank=True, null=True)
    post = models.ForeignKey(Post, related_name="post_comments")
    parent = TreeForeignKey('self', blank=True, null=True, related_name="children")
    text = models.CharField("Text", max_length=1000)
    rank = models.FloatField(default=0.0)
    pub_date = models.DateTimeField(auto_now_add=True)

Iterating through nodes has the same effect (>1000 queries).

A: I had similar issue with MPTT models. It was solved with select_related
(also for parent's foreign keys).
So, depending on your needs, proper queryset can looks like:
Comment.objects.select_related('post', 'submitter', 'parent', 'parent__submitter', 'parent__post')

Also, if you need comment's children in your loop as well, it can be optimized like that:
queryset.prefetch_related('children')

Or even like that:
queryset.prefetch_related(
    Prefetch(
        'children',
        queryset=Comment.objects.select_related('post', 'etc.'),
        to_attr='children_with_posts'
    )
)

... and depending on tree depth, you can use that:
queryset.select_related('parent', 'parent__parent', 'parent__parent__parent')
# you got the idea:)

A: Duplicated queries happens because all objects from iteration hits the data base when you refer a related object.
Try using select_related in your view method.
Probably using django prefetch related or select related will resolve that, but if not work, sorry you will need a raw query.
Have you ever read about optimizing Django queries? Here is a simple tutorial that's explain a lot of things: https://docs.djangoproject.com/en/3.1/topics/db/optimization/


text:
Q: No verbose output when fork option is used for maven-compiler-plugin If I want to see the compiler output, usually I enable the verbose option for the maven-compiler-plugin.
However, this will not work when it is used together with the fork option.
The compilation is running in another process and it seems that maven does not redirect the output to console.
My code sample looks like this
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <fork>true</fork>
                <verbose>true</verbose>
            </configuration>
        </plugin>
    </plugins>
</build>

Does anyone know how can I see what is happening during compilation?
In this link I see that using the two options together (fork and verbose) is encouraged.
However, as I already mentioned, in practice the two options do not work well when used
together.

A: UPDATE (25/06/2016): This issue of the plexus-compiler was fixed and the given code in the question will work as of version 2.8.

After reading through the source code, this is a bug of the plexus-compiler 2.7, which is the library internally used by the maven-compiler-plugin 3.5.1 to compile the Java sources.
So it goes like this in the code: the maven-compiler-plugin populates an object called CompilerConfiguration and sets its fork and verbose according to the given configuration element in the POM. The verbose element is correctly read and added to the compiler arguments:

if ( config.isVerbose() )
{
    args.add( "-verbose" );
}

Then, there is a switch depending on whether we're forking or not.

If we are not, we eventually come down to the code invoking javac and its output is stored in the compilation result:

ok = (Integer) compile.invoke( null, new Object[]{ args, new PrintWriter( out ) } );

messages = parseModernStream( ok.intValue(), new BufferedReader( new StringReader( out.toString() ) ) );

finally returned with:

return new CompilerResult( success, messages );

So far so good, the maven-compiler-plugin will loop around those messages and output them into the console. Since the verbose parameter was set, we'll have all messages.

If we are, then an executable (which defaults to the javac in the PATH) is retrieved and the compiler arguments are correctly set:

for ( String key : config.getCustomCompilerArgumentsAsMap().keySet() )
{
    if ( StringUtils.isNotEmpty( key ) && key.startsWith( "-J" ) )
    {
        cli.addArguments( new String[]{ key } );
    }
}

We can confirm this by running Maven in debug mode with -X, we'll see the message:
[DEBUG] Excutable:
[DEBUG]  "C:\Program Files\Java\jdk1.8.0_74\bin\javac.exe"
[DEBUG] Command line options:
[DEBUG] -d ... -classpath ... -sourcepath ... -s ... -g -target 1.8 -source 1.8 -verbose

Notice the -verbose at the end.
And then, this is the bug. The standard output will be stored inside an out variable

CommandLineUtils.StringStreamConsumer out = new CommandLineUtils.StringStreamConsumer();

correctly used as parameter of the compile method, but completely ignored afterwards:

returnCode = CommandLineUtils.executeCommandLine( cli, out, err );

messages = parseModernStream( returnCode, new BufferedReader( new StringReader( err.getOutput() ) ) );

Notice how the messages, that will later form what is output by the plugin, is only populated with the errors and not the standard output. So put simply: the standard output is correctly set in verbose mode but it is ignored and not translated into the correct compilation result.

I do not see a workaround for that (except not forking). I created the issue 20 in their GitHub to track this.


text:
Q: Is it possible (or sane) to use an alternate dependency style for tomcat application deploys? We have an application that apparently has a lot of dependencies. It's a 150MB WAR file when packaged with all the dependencies. However, our application code only accounts for about 8MB of this.
In the idea of trimming the time it takes to do a redeploy I was thinking that potentially we could have a "dependencies" something or another (I'm not terribly familiar with Java) that is a 142 MB WAR, and then our application that's actually just the 8MB and then we only have to redeploy that.
Is this possible? If so, is it recommended? If not, why not?

A: You can deploy all the external generic jars in the lib folder of your tomcat so it will be available for all the applications deployed there, then deploy your war in the webapps folder as you're currently doing. Since looks that this war is the only application that will interact with these libraries, then there should be no problem.
<tomcat-home>
- lib
  + commonJar1.jar
  + commonJar2.jar
  + commonJar3.jar
  + ...
- webapps
  + yourApp.war


text:
Q: Problems with "Google Play App Signing" When I first published my app on google play,  I did not interact and enabled "Google Play App Signing".
Now I'm dealing with a serious problem and want to disable it, which unfortunately is not possible.
When I wanted to remove my app from Google Play and publish it again without "Google Play App Signing", I realized that Google would not allow the removal of the published program.
How can I solve this problem and publish my app with my signature?
Please help me

My problem is with Google signing
I want to disable it

A: Unpublish first and then remove.


text:
Q: Arrow function object iteration with condition This question is about improving working code. I have a function showLabels that takes a value, iterates over an object and defines which label to return by comparing the value to the object keys.
  showLabels = (value) => {
    Object.keys(this.state.labels).forEach( key => {
      if (value <= key) this.tooltip = this.state.labels[key];
    });
    return this.tooltip;
  }

The question: Is it possible to make this more succinct? Especially assigning the value of the function to this.tooltip and then returning it in the outer function seems unnecessarily verbose.
Example
Based on a comment here is an example:
this.state.labels = {0: "Smallest amount", 50: "In the middle", 100: "Top"}
value = 33
//showLabels(value=33) should return "In the middle"

A: You could use Array.prototype.find on Object.entries

 showLabels = value => Object.entries(this.state.labels)
                             // sort pairs by key
                             .sort(([keyA], [keyB]) => keyA > keyB)
                             .find(([key]) => key > value)[1]

BTW keep in mind that the order of iteration over keys is not guaranteed. So assuming you want to find the first label that is greater than value, you need to sort labels.

A:

showLabels = (value) => {
  let tooltip, { labels } = this.state
  Object.keys(labels).forEach( key => {
    if (value <= key) tooltip = labels[key];
  })
  return tooltip;
}

Something like this is more succinct. Is there a reason you need to use Object.keys() here? It's rather slow.
Anyway, I've added a variable declaration and a destructuring in the beginning.


text:
Q: How to get an union in a structure working in C I have an assignment where I need to represent the following data as output:

*

*average CO2 value

*amount of incorrect readings

*average CO2 value from 1958 till 1968

*average CO2 value from 2008 till 2018

*maximum CO2 value and the year and month it was measured

*minimum CO2 value and the year and month it was measured

I have coded the following program, where I declare a structure, initialize the structure and print the values of the structure:
#include <stdio.h>

// Represents statistics of a CO2 table.
struct Statistics {
    double co2_average_total;
    int amount_of_incorrect_data;
    double co2_average_1958_1968;
    double co2_average_2008_2018;

    union Co2_MIN {
      double co2_value;
      int month;
      int year;
    };

    union Co2_MAX {
      double co2_value;
      int month;
      int year;
    };
};

typedef struct Statistics Statistics;

// initializes statistics
Statistics make_statistics(void) {
    Statistics st;
    union Co2_MIN co2_MIN;
    union Co2_MAX co2_MAX;

    st.co2_average_total = 0.00;
    st.amount_of_incorrect_data = 0;
    st.co2_average_1958_1968 = 0.00;
    st.co2_average_2008_2018 = 0.00;

    st.co2_MIN.co2_value = 500.00;
    st.co2_MIN.month = 0;
    st.co2_MIN.year = 0;

    st.co2_MAX.co2_value = 0.00;
    st.co2_MAX.month = 0;
    st.co2_MAX.year = 0;

    return st;
}

// prints statistics
void print_statistics(Statistics s) {
    printf("\nmean CO2:\t\t\t%.2f", s.co2_average_total); // average co2
    printf("\nnumber errors:\t\t\t%d", s.amount_of_incorrect_data); // number of errors
    printf("\nmean CO2 in 1958 - 1968:\t\t\t%.2f", s.co2_average_1958_1968); // average co2 1958-1968
    printf("\nmean CO2 in 2008 - 2018:\t\t\t%.2f", s.co2_average_2008_2018);    // average co2 2008-2018
    printf("\nMinimum CO2 of %2.f was measured in %i.%i", s.co2_MIN.co2_value, s.co2_MIN.month, s.co2_MIN.year);    // minimum of Co2 value measured on month,year
    printf("\nMaximum CO2 of %2.f was measured in %i.%i", s.co2_MAX.co2_value, s.co2_MAX.month, s.co2_MAX.year); // maximum of co2 value measured on month,year
}

int main() {

    Statistics s = make_statistics();
    print_statistics(s);

    return 0;
}

However when I try to compile the program I get the message:
error: 'Statistics {aka struct Statistics}' has no member named 'co2_MIN'

So apparently I declared my unions wrong at the start of my code.
I have however no idea what exactly I did wrong.
Could you please help me debug my code?
Thanks in advance!

A: You declared the union tags inside the struct. Move them out and declare them at the top of the translation unit (file), then add them as fields of the Statistics struct.
union Co2_MAX {
  double co2_value;
  int month;
  int year;
};

union Co2_MIN {
  double co2_value;
  int month;
  int year;
};

struct Statistics {
    double co2_average_total;
    int amount_of_incorrect_data;
    double co2_average_1958_1968;
    double co2_average_2008_2018;

    union Co2_MAX co2_max;
    union Co2_MIN co2_min;
};

Though I am unsure whether an union is a correct data structure for the job, since in the original post you state that you need to store:

*

*maximum CO2 value and the year and month it was measured

*minimum CO2 value and the year and month it was measured

An union can only store at most one of its fields at a time (either the value, month, or year based on your example).


text:
Q: Training a neural network on chess data I have been writing a chess engine with a friend and the engine itself is really good already (2700+ CCRL). We had the idea to use a neural network to have a better evaluation of positions.
Input to the network
because the output of the network greatly depends on which side has to move, we use the first half of the inputs to parse the position of who has to move and the second half for the opponent. In fact, we have for each piece and for each square an input which would result in 12x64 inputs. We had the idea to also include the opponent king position. So each side had 6x64 inputs and this for each square the opponent king can be -> 6x64x64. In total, this results in 12x64x64 binary input values where at maximum 32 are set.
Layers
The next layer consists of 64neurons where the first 32 neurons only accept inputs from the first half of the input features and the last 32 only accept inputs from the second half of the input features.
It follows a layer with 32 neurons fully connected and the output layer has only a single output.
Activation function
We use LeakyReLU at both hidden layers and a linear activation function at the output.
Training
Initially, I wanted to train the network on about 1 million positions yet this is taking ages. The position itself has a target value in the range of -20 to 20. I am using stochastic gradient descent using ADAM with a learning rate of 0.0001 and MSE as the loss function.
The problem I have is that this is taking a very very long time to even train those 1 million positions. The target is to later train on 300M positions.
I am not sure where I could improve the training progress.
Below are the graphs which show the training progress over 1000 iterations

The change for each iteration looks like this:

I hope someone could give me one or two hints on what I could improve in order to train the network faster. I am very happy for any advice!
Greetings,
Finn
Edit 1
As suggested, I should convert my network to keras. I am having problems getting the sparse input to run.
import keras
from keras.layers import Input, Concatenate, Dense, LeakyReLU
from keras.models import Model
from keras import backend as K
import numpy as np

# trainX1 = tf.SparseTensor(indices=[[0,0], [0,1]], values=[1, 2], dense_shape=[1,24576])
# trainX2 = tf.SparseTensor(indices=[[0,0], [0,1]], values=[1, 2], dense_shape=[1,24576])
#
# trainY = np.random.rand(1)

trainX1 = np.random.random((10000,24576))
trainX2 = np.random.random((10000,24576))

trainY = np.zeros((10000,1))

#input for player to move
activeInput = Input((64*64*6,))
inactiveInput = Input((64*64*6,))

denseActive = Dense(64)(activeInput)
denseInactive = Dense(64)(inactiveInput)

act1 = LeakyReLU(alpha=0.1)(denseActive)
act2 = LeakyReLU(alpha=0.1)(denseInactive)

concat_layer= Concatenate()([act1, act2])
dense1 = Dense(32)(concat_layer)

act3 = LeakyReLU(alpha=0.1)(dense1)

output = Dense(1, activation="linear")(act3)

model = Model(inputs=[activeInput, inactiveInput], outputs=output)
model.compile(loss='mse', optimizer='adam', metrics=['accuracy'])

# print(model.summary())

print(model.fit([trainX1,trainX2], trainY, epochs=1))

If I use sparse=True for the Dense layer, it will throw some exceptions. I am happy if someone could help me creating sparse input vectors.

A: I think you need to consider running it on a GPU. Google Colab is free and Amazon AWS is very cheap. You seem to know what you are doing so you can probably get up and running with PyTorch very quickly. Once you compare the performance of the same network implemented on GPU vs your single processor setup, you will be in a better to position to know where to go next.

A: You could also try the CPU-friendly NNUE alternative. It is currently been developed for chess by the Stockfish team and seems to give good results. It is easy to use and train the networks, and it should be much easier than the hard-way. I've been working on the Stockfish team, and I think I could also help you with your engine if you wish (I'm also working on my own chess engine). Regards and good luck!


text:
Q: Rename a directory in installer I am working on a Windows application which needs to be able to update itself. When a button is pressed it starts the installer and then the parent application exits. At some point during the installer, the installer attempts to rename the directory that the parent application was running from and fails with "Access Denied" If you run the installer from the desktop it works.
I am using CreateProcess to start the installer, is there some way of using this or another API to create the installer completely independantly from the parent application so that it doesn't retain some attachment to the directory.

A: I'm not convinced that launching the installer separately will solve your issue.  It sounds more like a permissions problem that you might be able to solve using ACL manipulation.  If the app doesn't already have permissions to mess with that folder, you might be able to write a custom action to remedy the problem by adding the necessary permissions to your process.
Another way of doing this is to make sure that the directory deletion is happening within a custom action that you control (as in, you own/maintain the code that performs the deletion, rather than rely on MsiExec to do it for you).  Then, set that custom action to run in the System context so that it will have the same permissions as a service.  That should provide your installer with sufficient rights to remove the folder.

A: You should use the normal update system within the windows installer.
your access denied message appears because file/directory is in use.
renaming directories isn't also not a good idea.
what happened if the user clicks "repair" or "uninstall" ?
you can start the msi with shellexec. after that terminate you app immediately.
you should check that in the msi that your app is NOT running anymore.
do the update. if a file is in use the installer automatically wants to reboot to replace the stuff.

A: CreateProcess should work if you are passing it the right parameters. Don't reference the parent process in any way and set most things to NULL. If that doesn't work, then you can try WinExec().


text:
Q: Flutter - Trying to use a void Function to return a String I am trying to return a String using a function but i kept getting
'A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 269 pos 10: 'data != null''
This is my String function:
test<String>(String callsign) {
    Firestore.instance
        .collection('Manning')
        .getDocuments()
        .then((QuerySnapshot snapshot) {
      snapshot.documents.forEach((f) {
        if (f.data.containsKey('Paramedic') && f.documentID == callsign) {
          return f.data['Paramedic'];
        } else if (f.data.containsKey('Medic') && f.documentID == callsign) {
          return f.data['Medic'];
        } else if (f.data.containsKey('Driver') && f.documentID == callsign) {
          return f.data['Driver'];
        } else if (f.data.containsKey('Attachment') &&
            f.documentID == callsign) {
          return f.data['Attachment'];
        }
      });
    });
  }

I've tried returning a Future but that cant be placed inside a Text widget.

A: You are not actually returning anything.
You have 2 ways of doing it:
The best way is returnig a future and using it inside a FutureBuilder
OR
Passing a callback to the function and updating some state on callback call like:
test<String>(String callsign, void Function(String) callback) {
  Firestore.instance
    .collection('Manning')
    .getDocuments()
    .then((QuerySnapshot snapshot) {
    snapshot.documents.forEach((f) {
      if (f.data.containsKey('Paramedic') && f.documentID == callsign) {
        callback(f.data['Paramedic']);
      } else if (f.data.containsKey('Medic') && f.documentID == callsign) {
        callback(f.data['Medic']);
      } else if (f.data.containsKey('Driver') && f.documentID == callsign) {
        callback(f.data['Driver']);
      } else if (f.data.containsKey('Attachment') &&
        f.documentID == callsign) {
        callback(f.data['Attachment']);
      }
    }));
  });
}

and passing as callback something like
test("", (value) => setState(...))

inside a stateful widget


text:
Q: How to avoid scrolling when softkeyboard appears In my application, when soft keyboard appears, this pushes entire layout up. I am ok when it scrolls up. But there are 2 buttons at the top of the layout that should not be scrolled!
Any clue is helpful


text:
Q: .NET Core installation on Mac OS X I have a problem with .NET Core installation on Mac OS X (El Capitan 10.11). Generally, I did everything as MS documentation said but when I'm trying to test the installation (dotnet new) I get an error:

Unhandled Exception: System.TypeInitializationException: The type
  initializer for 'Crypto' threw an exception. --->
  System.TypeInitializationException: The type initializer for
  'CryptoInitializer' threw an exception. --->
  System.DllNotFoundException: Unable to load DLL
  'System.Security.Cryptography.Native': The specified module could not
  be found.

I was trying to deploy .NET core through manual process, i.e. downloaded all the packages from Git, install mandatory libraries (like openssl) via Homebrew and start compiling. Coreclr has compiled well, but corefx gives errors resembling to what I received with automatic installation:

In file included from
  /usr/local/git/corefx/src/Native/Unix/System.Security.Cryptography.Native/pal_ecdsa.cpp:5:
  /usr/local/git/corefx/src/Native/Unix/System.Security.Cryptography.Native/pal_ecdsa.h:7:10:
  fatal error: 'openssl/ecdsa.h' file not found
include
     ^ make[2]: *** [System.Security.Cryptography.Native/CMakeFiles/System.Security.Cryptography.Native.dir/pal_bignum.cpp.o]

Error 1

I looked through the interned for possible solution with no luck. I cannot get one thing... if openssl lib is deprecated, why in the world MS keeps using it, as it obviously causes a lot of pain in well known place.
Has anybody managed to run .NET core on Mac, having the issue I described above?

A: After a while, I decided to reinstall everything from scratch. I have deleted git repo with dotnetfx source, cleaned out 'lib' and 'opt' folders (from 'openssl'), deleted Cellar folder (where 'openssl' reside). Once I did all this, I've started a new installation and followed instructions published on the official resource This time it all been deployed and works like a charm.


text:
Q: Efficiently compute rows of matrix which are not positive combinations of other rows Constrained convex optimization is a key component of many workflows/research projects in industry and academia. These problems take the form:
$$ \min_\theta f(\theta) $$
$$ s.t. M \theta \leq b$$
Where $f$ is some convex function, $\theta \in \mathbb{R}^n$, $M$ is a $p \times n$ matrix, and $b \in \mathbb{R}^p$. Many generic solvers for convex optimization problems exist, but their theoretical and practical computational complexity scales in the number of constraints. Being able to reduce the number of constraints, that is being able to reduce the number of rows of $M$ and $b$ is therefore a central question.
The constraints defined by $M$ and $b$ can be reformulated into a single matrix $A$ which uniquely defines the constraints (we can leave the details of this reformulation aside).
The constraint matrix $A$ is called irreducible if no row of $A$ is a positive linear combination of other rows. More formally, let $A_i$ denote the $i$ row of $A$ and let $A_{-i}$ denote the matrix obtained by removing the $i$th row of $A$, then $A_i$ is a positive linear combination of the other rows of $A$ if there is some $\nu \ge 0$ such that
$$ A_i = A_{-i} \nu.$$
Given a matrix $A$, I would like to construct a matrix $R$ which removes the these reducible components of $A$, and a matrix $M$ which so that $$M R = A.$$
Essentially, $R$ is the irreducible version of the matrix constraint, and $M$ allows us to reconstruct $A$ from $R$.
There are reasonably fast algorithms for solving the nonnegative least squares problem, i.e,
$$\beta = \text{nnls}(y, M),$$
where $\beta$ is defined as:
$$ \inf_\beta||y-M\beta ||_2^2$$
$$ \text{s.t.} \beta \geq 0$$
I do not think that what follows this is the best solution, but given the nnls function, a simple algorithm for computing the irreducible set of rows might work like this:
reducible = []
for i in nrow(A):
    # compute the non-negative least squares
    coefs = nnls(A[i], A[-i])

    # if the non-negative least squares
    # recovers A[i] exactly it is reducible
    if A[-i] * coefs == A[i]:
        reducible.append(i)

M = A[-reducible] # get the irreducible rows

We can then run the nnls from M to the reducible set A[reducible] to compute R.
Is there a faster way to do this? Are there properties of (ir)reducible matrices that could lead to a faster algorithm?

A: $\newcommand{\R}{\mathrm{I\!R}}\newcommand{\cone}{\mathrm{cone}}$I will give an answer regarding the columns of $A$ (I find it more convenient). If you are interested in the rows of $A$ you can apply the following methodology to $A^\intercal$.
Let $A\in\R^{m\times n}$ and $A = [a_1~a_1~\cdots~a_{n}]$. We define $A_{\setminus i}\in\R^{m\times(n-1)}$ to be $A$ without the $i$-th column.
Then $a_i$ is a conic (positive) combination of the columns of $A_{\setminus i}$ iff there is a vector $x\geq 0$ (the inequality is meant in the element-wise sense) such that
$$
A_{\setminus i}x = a_i.
$$
Essentially, we are interested in solving the feasibility problem:
\begin{align}
\text{Find }& x\in\R^{n-1} \text{such that:}
\\
&x \geq 0,
\\
&A_{\setminus i}x = a_i.
\end{align}
Now for $I\subseteq \{1, \ldots, n\}$ let us define $A_{\setminus I}$ to be $A$ after we remove the vectors $a_i$ for $i\in I$. For a set of indices $I$ and $j\in\{1, \ldots, n\}$, $j \notin I$ we define the feasibility problem:
\begin{align}
\mathbb{P}_{I, j}: \text{Find }& x\in\R^{n-|I|} \text{such that:}
\\
&x \geq 0,
\\
&A_{\setminus I}x = a_j.
\end{align}
We can then apply the following algorithm:

*

*$I = \{\}$

*for $j = 1,\ldots, n$

*

*If $\mathbb{P}_{I,j}$ is feasible, $I \gets I \cup \{j\}$

*Return $A_{\setminus I}$
To solve the feasibility problem $\mathbb{P}_{I,j}$ we can use SCS or SuperSCS. SCS/SuperSCS can determine whether $\mathbb{P}_{I, j}$ are feasible. Both SCS and SuperSCS need (internally) to solve a linear system where the left-hand side is the matrix
$$
B_A = \begin{bmatrix}
I & A & -b
\\
-A^\intercal & I & 0
\\
-b^\intercal & 0 & I
\end{bmatrix}.
$$
In turn, as shown in [this paper, Section 4.1], this can be facilitated by computing the LDL factorisation of
$$
M_A = \begin{bmatrix}I & -A^\intercal\\-A & I\end{bmatrix}.
$$
This can be done once; every time we remove a column from $A$, we are essentially removing a column-row pair from $M$. We can reduce the overall complexity of the above algorithm, we can update the corresponding LDL factorisations so we don't have to compute them each time again from scratch.
This leads to the following algorithm:

*

*$I = \{\}$

*Compute the LDL factorisation of $M_{A_{\setminus 1}}$

*for $j = 1,\ldots, n$

*

*Check whether $\mathbb{P}_{I,j}$ is feasible using (Super)SCS and pass the pre-computed the LDL factorisation of $M_{A_{\setminus 1}}$ to (Super)SCS

*If $\mathbb{P}_{I,j}$ is feasible, $I \gets I \cup \{j\}$

*If $j > 1$ update the factorisation of $M_{A_{\setminus I}}$

*Return $A_{\setminus I}$
Note: The idea is that since we need to solve a sequence of optimisation problems (well... feasibility problems) perhaps there are quantities that are computed while solving each individual problem that can be used to facilitate/accelerate the solution of the next one.


text:
Q: Scala Streams: Self-Reference, Function Calls and Lazy Evaluation I'm trying to understand why the following code using Scala Streams doesn't work:
def main(args: Array[String]): Unit = {
  lazy val y : SimNumericStream = y.shift
  y.scalstream.take(10).print
}

class SimNumericStream( ss : Stream[Double] )  {
  lazy val scalstream = ss
  lazy val shift = new SimNumericStream( 0 #:: scalstream )
}

and yet replacing
lazy val y : SimNumericStream = y.shift

by
lazy val y : SimNumericStream = new SimNumericStream( 0 #:: y.scalstream )

works just fine.
I'm looking for a solution that allows to me wrap up operations on Streams inside functions without breaking the lazy evaluation when the streams are self-referential.

A: In your first version, your call to instantiate SimNumericStream is inside an instance of SimNumericStream, so you can never actually intantiate one unless you have one already.

A: I have achieved the effect I would like through the following:
  class SimNumericStream(str: =>Stream[Double]) {
    def ::(hd: Double) = Stream.cons(hd, str)
    def shift = 0.0 :: this
  }
  implicit def streamToSimNumericStream(str: =>Stream[Double]) = new SimNumericStream(str)

  lazy val y: Stream[Double] = y.shift


text:
Q: Charged conductor in an external electric field If we put a conductor in a place where there is a uniform electric field, then the field will change. Take for example the case of a conducting cylinder, then the field lines would curve to return something like this:

But what would happen if the cylinder was held to some potential $V_0>0$ before "turning on" the external electric field? Stated in other words, how would the resulting electric field change if the cylinder had a uniform surface charge density $\sigma$ before being placed inside the external electric field?

A: Because Maxwell's equations are linear, and we assume linear media, the principle of superposition holds. Thus, the field of a charged cylinder in an external field is simply the field without the added charge plus the field of the charged cylinder.


text:
Q: NoReverseMatch Issue (Tango With Django 1.7 [10.5]) I am in the process of teaching myself django, and have run into an error I haven't been able to troubleshoot myself. I have tried some of the recommendations found in similarly asked StackExchange answers, but haven't been successful.
Question:
I am attempting to use the url template tag as follows:
index.html
...
{% if categories %}

        {% for category in categories %}

{{ category.name }}

        {% endfor %}

{% else %}
    There are no categories present.
{% endif %}
...

urls.py
urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^about/$', views.about, name='about'),
    url(r'^add_category/$', views.add_category, name='add_category'),
    url(r'^category/(?P<category_name_slug>[\w]+)/$', views.category, name='category'),
    url(r'^category/(?P<category_name_slug>[\w]+)/add_page/$', views.add_page, name='add_page'),
    url(r'^register/$', views.register, name='register'),
    url(r'^login/$', views.user_login, name='login'),
    url(r'^restricted/$', views.restricted, name='restricted'),
    url(r'^logout/$', views.user_logout, name='logout'),
    )

views.py
def category(request, category_name_slug):

    context_dict = {}

    try:
        category = Category.objects.get(slug=category_name_slug)
        context_dict['category_name'] = category.name

        pages = Page.objects.filter(category=category)

        context_dict['pages'] = pages

        context_dict['category'] = category

        context_dict['slug'] = category_name_slug
    except Category.DoesNotExist:
        pass

    return render(request, 'rango/category.html', context_dict)
    #return HttpResponseRedirect(reverse('rango:category', args=context_dict))
    #^ not working

On accessing localhost:8000/rango, I receive the following error message:
NoReverseMatch at /rango/

Reverse for 'category' with arguments '(u'other-frameworks',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'rango/category/(?P<category_name_slug>[\\w]+)/$']

What have I done wrong??
Thanks in advance!

A: The part of your regexp that's supposed to match 'other-frameworks' is [\w]+. \w does not match -, so no pattern matches that slug. Add - to your patterns if you want them to match slugs, eg [-\w]+.


text:
Q: Flutter Form currentState on multiple tabbar NoSuchMethodError: The getter 'currentState' was called on null I have a page with 3 tabbar. On my app I have 2 modes, insert and edit mode. On insert mode currentState bypass through form validation but on the edit mode I got NoSuchMethodError: The getter 'currentState' was called on null. I understand the problem, as I am trying to call the following:
List<dynamic> _treatment = form.fields['treatment'].currentState.value;

which is in the second tab and I am on the first tab. Same occurs with the 3rd Tab. If I go to 2nd & 3rd tab and then tap the save button I am not getting any error as all the form's variable are created. So, my question is how can I bypass this situation? Help will be highly appreciated as I am a newbie on Flutter. The user of my app can tap the save button while he/she is on any tabbar. On Edit mode I can't prevent for form validation as it's already done on insert mode. Below is my save part code:
      Future _saveForm() async {
        final form = _formKey.currentState;
        if (form.validate()) {
          //_formKey.currentState.save();
          _validate = false;
          print('saved');

          form.save();
          List<dynamic> _treatment = form.fields['treatment'].currentState.value;//this make problem as this is in tab 2
          print(_treatment);

          String treatment;
          _treatment.forEach((dynamic treat) {
            if (!treat.contains('FormBuilderFieldOption')) {
              if (treatment == null) {
                treatment = treat.toString();
              } else {
                treatment = treatment + ',' + treat.toString();
              }
            }
          });

          final int prefs = await Preference.getInt('userid');
          final int _loginUser = prefs;
          String _visithealthfacility =
              form.fields['visithealthfacility'].currentState.value.toString();
          if (_visithealthfacility == 'null') {
            _visithealthfacility = null;
          }
          String _bloodinstool = form.fields['bloodinstool'].currentState.value;
          if (_bloodinstool == null) {
            _bloodinstool = 'No';
          }
          String _fever = form.fields['fever'].currentState.value;
          if (_fever == null) {
            _fever = 'No';
          }
          String _other = form.fields['other'].currentState.value;
          if (_other == null) {
            _other = 'Disoriented';
          }
          String _ocv = form.fields['ocv'].currentState.value;//this makes

problem as it's in tab 3
      if (_ocv == null) {
        _ocv = 'No';
      }
      final Country _country = form.fields['country'].currentState.value;
      final District _district = form.fields['district'].currentState.value;
      final Governorate _governorate =
          form.fields['governorate'].currentState.value;
      final HealthFacility _healthfacility =
          form.fields['healthfacility'].currentState.value;
      final ORT _ort = form.fields['ort'].currentState.value;
      final Village _village = form.fields['village'].currentState.value;
      final CTC _ctc = form.fields['ctc'].currentState.value;
      final CaseData _caseData = CaseData(
        id: widget.caseData.id,
        age: form.fields['age'].currentState.value,
        bloodinstool: _bloodinstool,
        comment: form.fields['comment'].currentState.value,
        countryId: _country.id,
        ctcId: _ctc != null ? _ctc.id : null,
        dehydration: form.fields['dehydration'].currentState.value,
        diarrhoea: form.fields['diarrhoea'].currentState.value,
        districtId: _district.id,
        fever: _fever,
        gender: form.fields['gender'].currentState.value,
        governorateId: _governorate.id,
        healthfacilityId: _healthfacility.id,
        hospitalization: form.fields['hospitalization'].currentState.value,
        month: form.fields['month'].currentState.value,
        ocv: _ocv,
        ortId: _ort != null ? _ort.id : null,
        other: _other,
        outcome: form.fields['outcome'].currentState.value,
        stoolsample: form.fields['stoolsample'].currentState.value,
        symptoms: form.fields['symptoms'].currentState.value.toString(),
        treatment: treatment,
        villageId: _village.id,
        visithealthfacility: _visithealthfacility,
        vomiting: form.fields['vomiting'].currentState.value,
        username: _loginUser,
        selected: 0,
      );
      print(_caseData.toString());
      _caseDataBloc.updatecaseData(_caseData);
      Navigator.pushNamed(context, '/caselist');
    } else {
      _validate = true;
      FlushbarHelper.createError(
        message: 'Mandatory fields are missing',
        title: 'Please fill the mandatory fields.',
      ).show(context);
      print('validation problem');
      setState(() {
        _autoValidate = true;
      });
    }
  }

Actually, this is not related to code but I think technique to handle form state in tabbar. Please see this gif file Video showing the problem


text:
Q: Problems running jQuery in Quickbase I'm trying to get jQuery to run on Quickbase.  I've run this code in jsfiddle and it works fine.  It's really simple code to test out the html pages in Quickbase.  I am currently using the built in html pages option and adding the code below but the scripting does not work.  What am I missing?

test

A: Even though QuickBase says that jQuery is on by default in the code pages that can be built you will still have to call it in each page should you need it.


text:
Q: List View text color is not changed Android I want to change the listview text color but its not changing. Also i have used different list style but the color of Text in the list is not changing. Help me to solve this problem
This is the code
 public class Line extends Activity
 {

List<Map<String, String>> data;

Map<String, String> Line1;
Map<String, String> Line2;

ListView Lines = null;

public void onCreate(final Bundle savedInstanceState)
{

    Lines = new ListView(Line.this);
    Lines = (ListView) findViewById(R.id.list);

    data = new ArrayList<Map<String, String>>();

    Line1 = new HashMap<String, String>();

    Line1.put("title", "Row | 1" );
    Line1.put("status", "");
    data.add(Line1);

   Line2 = new HashMap<String, String>();

    Line2.put("title", "Row | 2" );
    Line2.put("status", "");
    data.add(Line2);

    SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[] {"title", "status"}, new int[] {android.R.id.text1, android.R.id.text2});

    Lines.setAdapter(adapter);

void SetStatus(int nLineNo, String sStatusMsg)
{
    if(nLineNo == 0)
    {
        Line1 = new HashMap<String, String>();
        Line1.put("title", "Line | 1" );
        Line1.put("status", sStatusMsg);
        data.set(0, Line1);

        SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[] {"title", "status"}, new int[] {android.R.id.text1, android.R.id.text2});

        Lines.setAdapter(adapter);
    }

    if(nLineNo == 1)
    {
        Line2 = new HashMap<String, String>();
        Line2.put("title", "Line | 2" );
        Line2.put("status", sStatusMsg);
        data.set(1, Line2);
        SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[] {"title", "status"}, new int[] {android.R.id.text1, android.R.id.text2});

        Lines.setAdapter(adapter);
    }

    }

xml of listview
    <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
           >

        <ListView
            android:id="@+id/list"
            android:layout_width="wrap_content"
            android:layout_height="338dp"
            android:padding="10dip"
            android:listSelector="#372f89"
            style="@drawable/liststyle"
             android:textColor="@color/tabDark"
              android:background="#fcfbdf"
            android:scrollbars="none"
            android:cacheColorHint="#ffffff">

            <!-- Preview: listitem=@android:layout/simple_list_item_2 -->

        </ListView>

</TableRow>

list style xml
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

 <TextView
        android:id="@android:id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:minHeight="?android:attr/listPreferredItemHeight"
        android:paddingLeft="6dip"
        android:textColor="@color/circlebtn"
        android:paddingRight="10dip"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

A: Currently you are passing android.R.layout.simple_list_item_2 which uses default simple_list_item_2 for ListView row.
Pass list style xml(assuming created by you) to SimpleAdapter :
   SimpleAdapter adapter = new SimpleAdapter(this, data,
        R.layout.<list style xml>, new String[] {"title", "status"},
        new int[] {android.R.id.text1, android.R.id.text2});


text:
Q: Solr JVM is not getting updated Trying to increase the memory of Solr JVM in Linux

*

*Added the changes solr.in.sh and solr.in.cmd both files

*Restarted the solr service

*Restarted the Server also

*Tried to start solr with .\solr restart -p 8999 -m 1g , solr restart -m 1g

But no luck, please let me know if any other things needed.


text:
Q: Get other web pages html using php how can i get the price dynamically from another web page and store it in the server (php and SQL) if not in php it doesn't matter!
for example a web page that doesn't have json or xml but i want to get a specific value from it like the price
i tried a few things that are built in php but it didn't work the way i wanted to.
also this didn't work! :
Access-Control-Allow-Origin: *

i need this for my next project , i will really appreciate your help!

A: http://www.webmasterworld.com/forum88/10926.htm
How do I get the HTML code of a web page in PHP?
http://www.php.net/file_get_contents
You might start there. You will need to grab all of the HTML and then parse it based on the tags they are using.
From the first website (modified a bit):
$url = 'http://www.example.com';
$needle = '<b>find me</b>'; // Look for the tags on the other page and replace here
$contents = file_get_contents($url);
if(strpos($contents, $needle) !== false) {
    // Do your saving of the price here;
}

If you have more than one price on the page, you will need to form a loop that finds the next occurrence instead of only the first. Hopefully this helps!


text:
Q: Testing form inputs in PHPUnit What's the best way to test $_GET and $_POST inputs in PHPUnit?
I have a class that sanitises input and want to check that it works correctly when processing bogus data.  Is there an easy way to set up the form variables in PHPUnit or should I just pass off the validation to a secondary class/functions that are fed the form variables so test them indirectly?

A: Take a look at the idea of Dependency injection. In a nutshell you should feed your code what it needs as opposed to it getting the data it needs... Here's an example:
example without Dependency Injection
function sanitize1() {
  foreach($_POST as $k => $v) {
    // code to sanitize $v
  }
}

sanitize1();

example with Dependency Injection
function sanitize2(array &$formData) {
  foreach($formData as $k => $v) {
    // code to sanitize $v
  }
}

sanitize2($_POST);

See the difference? In your PHPUnit test you can pass sanitize2() an associative array of your choice; you've injected the dependency. Whereas sanitize1() is coupled with $_POST. $_POST and $_GET are assoc arrays anyways so in your production code you can pass $_GET or $_POST to your function but in your unit tests you'd hard code some expected data.
Unit test example:
function testSanitize() {
  $fakeFormData = array ('bio' => 'hi i\'m arin', 'location' => 'San Francisco');
  sanitize($fakeFormData);
  // assert something
}


text:
Q: How to get windows back? Lubuntu? I installed lubuntu and I don't like it. I did a clean install to lubuntu rather than making it dual. Now when I want to go back to Windows it won't work. I put the Windows Vista CD in and it won't load. It just loads lubuntu back. I know for a fact that the CD works just fine. I don't know what to do? I did a little research and it says I deleted the windows loader or the partition. Can someone help me?

A: From what I understand, you want to reinstall Windows Vista, boot your computer won't boot into the DvD.

*

*Power your computer on. When the BIOS screen appears (the first screen to appear during the boot process), press the "Delete" key. This is the most common way to enter the BIOS settings on a computer, though some systems differ. If the Delete key does not access the BIOS setting on your computer, look for different instructions on the screen itself. For example, it may say "Press F10 to enter setup."

*Using the arrows on your keyboard, scroll down to "Boot Device Select" and press "Enter."

*Change the boot order, moving DVD drive to the first boot device.

*Insert the DVD you wish to boot from.

*Save your changes and exit BIOS. Look for on-screen instructions on how to save and exit, as this option differs between systems. Exiting BIOS will force your computer to restart. When it does, it will boot from the Vista DVD.

A: i had similar problem.Windows just cant see hard drive after ubuntu changed it to ex4 format  type.. So i  booted from ubuntu live cd and use gparted to free space and create ntfc partition wich windows detected.Avoid to close gparted before its finished cause it can break your partition so even lubuntu will be gone.To see detailed progress info just press additional options under process bar.


text:
Q: Insert rows to fill sequence I am attempting to insert rows where I missing years in the Year column. The idea is to have a year and value populated for every year up until 2016, starting with the first year for a given id. Here is my current state:
id  year    value
a   2016    100
a   2015    90
a   2007    60
b   2016    120
b   2014    105
c   2015    110
c   2014    90
d   2016    150

Here is my desired state:
id  year    value
a   2016    100
a   2015    90
a   2014    60
a   2013    60
a   2012    60
a   2011    60
a   2010    60
a   2009    60
a   2008    60
a   2007    60
b   2016    120
b   2015    105
b   2014    105
c   2016    110
c   2015    110
c   2014    90
d   2016    150

So, populate missing years with the value from the previous year. How can this be achieved in Excel, SQL or VBA? I can throw this into an access database to get the job done. The only thing I can think of right now is joining my current table to a table in SQL with all the years I want and then go through a repopulate the NULL values. Any assistance is greatly appreciated. Thanks!
Edit: How do I do this specifically using SQL?

A: This can be done with VBA, brute force method shown below.
Please let me know if you have any questions.
Dim ws As Worksheet
' assuming data is always sorted by id
Dim Row As Integer
Dim curID, prevID As String
Dim curYr, prevYr As Integer
Dim prevVal As Integer

Set ws = ThisWorkbook.ActiveSheet

Row = ws.Cells.SpecialCells(xlCellTypeLastCell).Row
' This does 2 things gets the prevID and makes sure previous line selects the actual last row
prevID = ""
Do
   prevID = ws.Cells(Row, 1)
   prevYr = ws.Cells(Row, 2)
   prevVal = ws.Cells(Row, 3)
   Row = Row - 1
Loop Until prevID <> "" Or Row = 2

While Row > 2
   curID = ws.Cells(Row, 1)
   curYr = ws.Cells(Row, 2)

   ' next id
   If curID <> prevID Then
      Row = Row + 1
      For i = 2016 To (prevYr + 1) Step -1
         ws.Rows(Row).Insert shift:=xlShiftDown
         ws.Cells(Row, 1) = prevID
         ws.Cells(Row, 2) = i
         ws.Cells(Row, 3) = prevVal
      Next i
      Row = Row - 1
      prevID = curID
      prevYr = curYr
      prevVal = ws.Cells(Row, 3)
   ' next year
   ElseIf curYr - 1 = prevYr Then
      prevID = curID
      prevYr = curYr
      prevVal = ws.Cells(Row, 3)
   ' in between
   Else
      Row = Row + 1
      For i = (prevYr + 1) To (curYr - 1)
         ws.Rows(Row).Insert shift:=xlShiftDown
         ws.Cells(Row, 1) = prevID
         ws.Cells(Row, 2) = i
         ws.Cells(Row, 3) = prevVal
      Next i
      If prevYr = curYr Then
         Row = Row - 1
      End If
      prevYr = curYr
   End If

   Row = Row - 1
Wend


text:
Q: How to render and retrieve image data on Google Project Tango? I'd like to render the live image data on a GL surface (as shown in various Project Tango samples), and at the same time record (encode) it via a MediaCodec.
(On an Android Lollipop device, I've accomplished that using the camera2 interface and multiple surface targets, which works fine, but thus far Tango is pre-Lollipop...)
From other answers, it appears that you have to use the C API to access the image data.
The C API provides two camera frame functions -- TangoService_connectTextureId() and TangoService_connectOnFrameAvailable(). However, the documentation states "Use either TangoService_connectTextureId() or TangoService_connectOnFrameAvailable() but not both."
Why not both?
How do I best render and retrieve the image data?

A: The Pythagoras release now allows for simultaneous use of color and color texture callbacks now.  That said, you want to use the connectOnFrameAvailable if you want to process the image, you'd end up doing extra unnecessary work if you try and peel it out of the texture.


text:
Q: MySQL SUM With Grouped Date How to get data Price with grouped date ?
SELECT store.date, store.pic, owner.name,
SUM (CASE WHEN [>>GROUPED store.date<<] THEN store.price) AS total_price
FROM store
JOIN owner
ON store.pic = owner.name GROUP BY store.date

and i want to display like this :
+-------------+------+------------+
| date        | name |  price     |
+-------------+------+------------+
| 2016-09-30  | John | 100000.00  |
| 2016-09-29  | Rey  | 125000.00  |
+-------------+------+------------+

A: Try this will may help you,
 SELECT store.date, store.pic, owner.name,SUM(store.price) AS total_price
 FROM store
 JOIN OWNER ON store.pic = owner.name
 GROUP BY store.date

i can't understand why you used case statement in your query


text:
Q: How to troubleshoot 'NullInjectorError: StaticInjectorError' in Angular 8 resolver UPDATE: The problem is only present in development mode, and vanishes when running ng build or ng serve with the --prod flag.
I've noticed a regression in a web app I'm working on after upgrading to Angular 8. In one of my components, I've started recieving this error:
ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[function () { return []:
  StaticInjectorError(Platform: core)[function () { return []:
    NullInjectorError: No provider for function () { return [!
Error: NullInjectorError: No provider for function () { return [!
    at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (core.js:725) [angular]
    at resolveToken (core.js:11812) [angular]
    at tryResolveToken (core.js:11756) [angular]
    at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:11660) [angular]
    at resolveToken (core.js:11812) [angular]
    at tryResolveToken (core.js:11756) [angular]
    at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:11660) [angular]
    at resolveNgModuleDep (core.js:20006) [angular]
    at NgModuleRef_.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef_.get (core.js:20677) [angular]
    at getToken (router.js:2844) [angular]
    at getResolver (router.js:3492) [angular]
    at resolveNode (router.js:3475) [angular]
    at runResolve (router.js:3461) [angular]
    at MergeMapSubscriber.project (router.js:3455) [angular]
    at resolvePromise (zone.js:852) [angular]
    at resolvePromise (zone.js:809) [angular]
    at polyfills.js:3918:17 [angular]
    at Object.onInvokeTask (core.js:25977) [angular]
    at drainMicroTaskQueue (zone.js:601) [<root>]

I've narrowed the problem down to the resolver used in the route to the component. When I remove/comment out the injections from the constructor, the component loads fine. Any ideas what could be causing this? I'm stumped.
Here's the resolver:
IMPORTS REMOVED FOR BREVITY

@Injectable()
export class MemberListResolver implements Resolve<User[]> {
  constructor(
    private authService: AuthService,
    private router: Router,
    private alertify: AlertifyService,
    private distributorService: DistributorService
  ) {
  }

  resolve(route: ActivatedRouteSnapshot): Observable<User[]> {
    return this.authService.currentDistributor.pipe(
      flatMap((d: Distributor) => {
        return this.distributorService.getUsers(d.id).pipe(
          catchError(error => {
            this.alertify.message('Problem retrieving users');
            this.router.navigate(['/home']);
            return of(null);
          })
        );
      })
    );
  }
}

A: I had the same problem. It was a syntax error in the Routes array
First I wrote
const routes: Routes = [
  {
    path: '',
    component: GalleryComponent,
    resolve: PhotoListResolver
  }
];

But it should be
const routes: Routes = [
  {
    path: '',
    component: GalleryComponent,
    resolve: {
        photos: PhotoListResolver
    }
  }
];

A: My current app is running on Angular v8.1.2
Last week I had this error and I was able able to compile after adding forRoot() in a couple of files:

*

*The RouterModule in app-routing.module
import { Routes, RouterModule } from '@angular/router';
 @NgModule ({
    imports: [RouterModule.forRoot(routes)],  <!--edit here -->
    exports: [RouterModule],
  })
2     And if your are using NgRx, the StoreRouterConnectingModule in app.module.ts
`import { StoreRouterConnectingModule } from '@ngrx/router-store'

 @NgModule ({
   imports: Store.RouterConnectingModule.forRoot() <!--edit here -->
   })`

*Cancel and restart the terminal: $ ng serve


text:
Q: update google services from 9.0.0 to 10.0.1 Android studio 2.2 I get an error saying
Error:Execution failed for task ':app:processDebugGoogleServices'.

Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 9.0.0.

I tried looking at https://bintray.com/android/android-tools/com.google.gms.google-services/ and com.google.gms:google-services:3.0.0 seems to be the latest. This is my project gradle
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

And this is how my app gradle looks like
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    defaultConfig {
        applicationId "sk.tipos.paradox02.citaj"
        minSdkVersion 11
        targetSdkVersion 23
        versionCode 27
        versionName '2.003'
    }

    buildTypes {
        release {
            minifyEnabled false
            multiDexEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
          //  signingConfig signingConfigs.release
        }

        debug {
            debuggable true
            minifyEnabled false
            multiDexEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt')
//            signingConfig signingConfigs.release
        }
    }

    productFlavors {
    }

    lintOptions {

        checkReleaseBuilds false

    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.google.gms:google-services:3.0.0'
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:design:23.1.0'
    compile 'com.google.android.gms:play-services:10.2.0'
    compile 'com.google.android.gms:play-services-ads:10.2.0'
    compile 'com.google.android.gms:play-services-appindexing:9.8.0'
    compile 'com.google.android.gms:play-services-analytics:10.2.0'

    compile 'com.google.firebase:firebase-core:9.0.0'
    compile 'com.google.firebase:firebase-crash:10.0.1'
    compile 'com.google.firebase:firebase-ads:10.0.1'
    compile 'com.android.support:multidex:1.0.1'
}

apply plugin: 'com.google.gms.google-services'
If I change the play services to 9.0.0 everything compiles fine. What am I missing here?
Have you idea how resolve problem?
Thanks

A: You are having this issue because Firebase was built using Google Play Services , so you can't use a version of Google Play Services higher than the version of Firebase.
Can you try :

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    defaultConfig {
        applicationId "sk.tipos.paradox02.citaj"
        minSdkVersion 11
        targetSdkVersion 23
        versionCode 27
        versionName '2.003'
    }

    buildTypes {
        release {
            minifyEnabled false
            multiDexEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
          //  signingConfig signingConfigs.release
        }

        debug {
            debuggable true
            minifyEnabled false
            multiDexEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt')
//            signingConfig signingConfigs.release
        }
    }

    productFlavors {
    }

    lintOptions {

        checkReleaseBuilds false

    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.google.gms:google-services:3.0.0'
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:design:23.1.0'

    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-ads:10.2.0'
    compile 'com.android.support:multidex:1.0.1'

}
apply plugin: 'com.google.gms.google-services'

Sorry for my english, hope it's help.

A: You are using different versions of dependencies.Update their version to match version of latest google services version.
e.g.
compile 'com.google.android.gms:play-services:10.2.0'
compile 'com.google.android.gms:play-services-ads:10.2.0'
compile 'com.google.android.gms:play-services-appindexing:10.2.0'
compile 'com.google.android.gms:play-services-analytics:10.2.0'
compile 'com.google.firebase:firebase-core:10.2.0'
compile 'com.google.firebase:firebase-crash:10.2.0'
compile 'com.google.firebase:firebase-ads:10.2.0'

A: Have you tried the solution given in this post: https://stackoverflow.com/a/37565535/3108709 . I had the same issue as you had, this solved it for me.

That's because you should always put the "apply plugin" clause at the bottom for google-services, since it looks for the already-added dependencies. Do it like this in your app-level gradle:
dependencies {
      compile 'com.google.android.gms:play-services-ads:9.0.1'
  }
  // ADD THIS AT THE BOTTOM
  apply plugin: 'com.google.gms.google-services'
This is hidden in the Firebase documentation, but applies even if you don't use Firebase.
Note : Update Google Repository also.


text:
Q: Group web sessions with HAProxy I want to load balance web requests with HAProxy.  The catch is that I want particular groups of users to always go to the same server.  (This is a multiplayer system, and users in the same group need to be on the same server).  The users can go to any server, as long as the users with the same group id are on the same server.  The server can even change (for example if a server goes down) but then all users of that group must switch to a new server.  The app server will identify the user's grouping with a cookie.
As a specific example, suppose my application has a cookie GROUP_ID numbered 1..10000.  There might be 3 different users with GROUP_ID=1, a different 3 users with GROUP_ID=2, etc.  And let's assume I set up load balancing on servers: app1, app2, app3.
What I'd like to see is something similar to this:

*

*all GROUP_ID=1 users go to app1

*all GROUP_ID=2 users go to app2

*all GROUP_ID=3 users go to app3

*all GROUP_ID=4 users go to app1

*all GROUP_ID=5 users go to app2

etc.
If server app1 becomes unresponse, then I want to see the app1 users redistributed among app2 and app3.  (It'd be ok if all groups were reshuffled).  All users from a particular group should still be on a common server.
Obviously the initial request to the site will not have a cookie, but once the user authenticates they will be assigned the cookie.
Is this kind of custom load balancing supported by HAProxy?

A: 1) Setup a HAPROXY frontend, with:

*

*a dedicated backend for your authentication (login into the game). When you authenticate, you set a cookie called 'GROUPID'. (ie: GROUPID=GID3) for that http connection. (note: you can also pass that 'groupid' as an argument to an URL and/or set expiry time, etc..)

*a dedicated backend for your game servers, with the following directive:
cookie GROUPID insert indirect nocache
2) setup your servers (in the backend) as (note: check section can be removed):
server APP01 10.0.0.5:80 cookie GID3 check inter 5000 rise 2 fall 3 maxconn 2048

server APP02 10.0.0.6:80 cookie GID4 check inter 5000 rise 2 fall 3 maxconn 2048

(...)

For further reference, the documentation of HAPROXY is quite explicit (http://haproxy.1wt.eu/download/1.4/doc/configuration.txt)


text:
Q: Cannot update a component from inside the function body of a different component warning I wrote a component called component1 as below and it is inside the parent component. The component1 is at the bottom of the page and I don't want to render it unless the user scroll down to that area. Thus I use the InView from 'react-intersection-observer' to determine if this area is in view. If so then fetch data and render data. But I get the warning: Warning: Cannot update a component from inside the function body of a different component. What is the reason of getting this warning? Is it because I set the setInView in the component?
<parent>
    <component4 />
    <component3 />
    <component2 />
    <component1 />
</parent>

const component1 = () => {
    const [inView, setInView] = React.useState(false);
    const [loading, error, data] = fetchData(inView); // hook to fetch data
    // data is an array
    const content = data.map(d =>
{d}
);
    const showEmpty = true;
    if (data) {
        showEmpty = false;
    }
    return (<InView>
        {({ inView, ref }) => {
              setInView(inView);
              return (

{!showEmpty && content}

            )
    </InView>);
}

A: As I understood you want to fetch data when the component gets in view right?
here is my solution with useEffect:
const Componet1 = () => {

  const [inView, setInView] = useState(false)
  const [myData, setMyData] = useState(null)

  useEffect(() => {
    if (inView && !myData) {
      const [loading, error, data] = fetchData(inView); // hook to fetch data
      if (data) {
        setMyData(data)
      }
    }

    return () => {
      // cleanup
    }
  }, [inView,myData])

  return (
    <InView as="div" onChange={(inView) => setInView(inView)}>
      {myData ? myData.map((d, i) =>
{d}
) : 'Loading...'}
    </InView>
  );
}

Also, this fetches data just once.


text:
Q: Lost databinding of usercontrol in winforms when changing parent control I tryed for a lot of hours: I have a simple example with a microsoft textbox and a textbox on a usercontrol. Both with databinding to a datagrid, everythink works fine, the values change automaticly when you scroll through the datagrid.
After moving both controls on a groupbox (what changes their parent) the databindings are handled by microsofts sub BindingContext.UpdateBinding. The binding of the textbox is removed and added again, but the binding of the usercontrol gets removed, but never comes back, the databinding is dead.
Whats the matter about this?
Imports System.ComponentModel

Public Class Class1

    Public Shared Sub Main()

        Dim form1 As New Form With {.Width = 800, .Height = 600, .StartPosition = FormStartPosition.CenterScreen}

        Dim dataGrid1 As New DataGrid With {.Width = 780, .Height = 300}
        form1.Controls.Add(dataGrid1)

        Dim textbox1 As New TextBox With {.Left = 30, .Top = 400}
        form1.Controls.Add(textbox1)

        Dim userControl1 As New UserControl1 With {.Left = 150, .Top = 397, .BackColor = System.Drawing.Color.Aqua}
        form1.Controls.Add(userControl1)

        Dim groupBox1 As New GroupBox With {.Left = 410, .Top = 320, .Height = 200, .Width = 350, .Text = "GroupBox"}
        form1.Controls.Add(groupBox1)

        Dim button1 As New Button With {.Left = 290, .Top = 400, .Text = "--->"}
        form1.Controls.Add(button1)
        AddHandler button1.Click, Sub()
                                      groupBox1.Controls.AddRange({textbox1, userControl1}) : textbox1.Top = 70 : userControl1.Top = 67
                                  End Sub

        Dim snTBL = New System.Data.DataTable("serialnumbers")
        snTBL.Columns.Add(New DataColumn("serialnumber1", GetType(String)))
        snTBL.Columns.Add(New DataColumn("serialnumber2", GetType(String)))
        For i = 0 To 5
            Dim row As DataRow = snTBL.NewRow
            row.Item("serialnumber1") = CStr(i)
            row.Item("serialnumber2") = CStr(i * 10)
            snTBL.Rows.Add(row)
        Next

        dataGrid1.DataSource = snTBL

        textbox1.DataBindings.Add(NameOf(textbox1.Text), snTBL, "serialnumber1")
        userControl1.DataBindings.Add(NameOf(userControl1.BindingText), snTBL, "serialnumber2")

        Application.Run(form1)

    End Sub

    <System.ComponentModel.DefaultBindingProperty(NameOf(UserControl1.BindingText))>
    Public Class UserControl1
        Inherits System.Windows.Forms.UserControl
        Implements System.ComponentModel.INotifyPropertyChanged

        Friend WithEvents TextBox1 As TextBox

        Protected Overrides Sub oncreatecontrol()

            Me.TextBox1 = New System.Windows.Forms.TextBox()
            Me.SuspendLayout()
            '
            'TextBox1
            '
            Me.TextBox1.Location = New System.Drawing.Point(3, 3)
            Me.TextBox1.Name = "TextBox1"
            Me.TextBox1.Size = New System.Drawing.Size(103, 20)
            Me.TextBox1.TabIndex = 0
            '
            'UserControl1
            '
            Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
            Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
            Me.Controls.Add(Me.TextBox1)
            Me.Name = "UserControl1"
            Me.Size = New System.Drawing.Size(109, 26)
            Me.ResumeLayout(False)
            Me.PerformLayout()

        End Sub

        Public Property BindingText As String
            Get
                Return Me.TextBox1.Text
            End Get
            Set(value As String)
                Me.TextBox1.Text = value
                RaiseEvent PropertyChanged(Me, New System.ComponentModel.PropertyChangedEventArgs(NameOf(UserControl1.BindingText)))
            End Set
        End Property

        Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
    End Class

End Class

A: Thanks to @Jimi, the solution was to use BindingSource instead of binding directly to the DataTable.


text:
Q: Which system table holds the descriptions of system errors? Looking for the system table that holds the descriptions of errormsgs < 50000
Had no luck going through the contents of sys.objects with type_desc 'system_table'
Thanks in advance!

A: The answer actually depends on your version of SQL Server, which you didn't mention:
-- SQL 2000
select * from sysmessages where error < 50000
-- SQL 2005+
select * from sys.messages where message_id < 50000

See the documentation for more details: sysmessages and sys.messages

A: select  *
from    master.dbo.sysmessages

A: Looks like there is a brick wall here.
Internal function OpenRowset(TABLE SYSERRORS) is easy to use for reading system tables (using the DAC) but for updates it needs arguments that are totally undocumented outside Microsoft.