text:
Q: Docker build not using layer cache Given: I want to build a Dockerfile to compile a Scala application. To speedup the build I want the dependency download to be cached.
Problem: The command ./sbt -sbt-dir ./sbt-dir -ivy ./ivy update is not cached for some reason.
FROM openjdk:8 as workspace

ARG BUILD_VERSION

WORKDIR /build

COPY ./sbt ./sbt
COPY ./sbt-dist ./sbt-dist
COPY ./build.sbt ./build.sbt
COPY ./project/build.properties ./project/build.properties
COPY ./project/plugins.sbt ./project/plugins.sbt

RUN ./sbt -sbt-dir ./sbt-dir -ivy ./ivy update

COPY ./ ./

# Embedded postgres need to be run as non-root user
RUN useradd -ms /bin/bash runner
RUN chown -R runner /build
USER runner

RUN ./sbt -sbt-dir ./sbt-dir -ivy ./ivy clean test
RUN ./sbt -sbt-dir ./sbt-dir -ivy ./ivy docker:stage -Ddocker.image.version="${BUILD_VERSION}"

Because this build runs in a new VM all the time I push the workspace image and pull it on the next run to build the cache from it
docker build --rm=false --cache-from=workspace --build-arg BUILD_VERSION=1 -t workspace .

Here is a piece of the output
Step 2/22 : ARG BUILD_VERSION
 ---> Using cache
 ---> de98ffcfad8e
Step 3/22 : WORKDIR /build
 ---> Using cache
 ---> 253b71142240
Step 4/22 : COPY ./sbt ./sbt
 ---> Using cache
 ---> 3091fa1e1821
Step 5/22 : COPY ./sbt-dist ./sbt-dist
 ---> Using cache
 ---> f9c68659cd91
Step 6/22 : COPY ./build.sbt ./build.sbt
 ---> Using cache
 ---> d30058c451fc
Step 7/22 : COPY ./project/build.properties ./project/build.properties
 ---> Using cache
 ---> 7451eb63303f
Step 8/22 : COPY ./project/plugins.sbt ./project/plugins.sbt
 ---> Using cache
 ---> 79ac2d1e5ff5
Step 9/22 : RUN ./sbt -sbt-dir ./sbt-dir -ivy ./ivy update
 ---> Running in 609104e7045e
Getting org.scala-sbt sbt 1.0.3 ...

Can anyone explain me why Docker is not using the cache here?
A link to a explanation how the cache really decides when to use the cache would be ok as well. As far as I know here Docker should use the cache until the signature of the RUN command changes.
Thanks in Advance

A: I found the answer by the way :) The Dockerfile itself was ok except one problem I could then find via docker history Which shows the real shell command which are executed by docker.
The Problem was that ARG BUILD_VERSION lead to docker adds to every run command the environment variable like /bin/sh -c "ARG=123 ./sbt ...". This leads to a different call signature and a different hash every time the arg changes and therefore the run command is not applied from cache. To fix this issue just move the ARG down to the first RUN command which needs it.
FROM openjdk:8 as workspace

WORKDIR /build

COPY ./sbt ./sbt
COPY ./sbt-dist ./sbt-dist
COPY ./build.sbt ./build.sbt
COPY ./project/build.properties ./project/build.properties
COPY ./project/plugins.sbt ./project/plugins.sbt

RUN ./sbt -sbt-dir ./sbt-dir -ivy ./ivy update

COPY ./ ./

# Embedded postgres need to be run as non-root user
RUN useradd -ms /bin/bash runner
RUN chown -R runner /build
USER runner

RUN ./sbt -sbt-dir ./sbt-dir -ivy ./ivy clean test

ARG BUILD_VERSION
RUN ./sbt -sbt-dir ./sbt-dir -ivy ./ivy docker:stage -Ddocker.image.version="${BUILD_VERSION}"

A: As the docker build output shows, the building stopped using the cache at the stage:
4:32:35 PMStep 4/22 : ADD ./sbt ./sbt
4:32:36 PM---> 7a9e21819cea

This is happening because there have been changes in the ./sbt folder on the host and thus docker will rerun the ADD instruction. From there on, docker will not use the cache anymore as a base layer was invalidated causing the layers after it to also be invalidated.
The change might be in the contents of the directories, but rather something trivial such as a timestamp.
As a best practice, to get advantage of the build caching mechanism, you should delay instructions that change often to the bottom of the Dockerfile. In general, adding source to a docker image is one of these steps that changes the very frequently between builds.


text:
Q: got UICC carrier priviliges but failed to open channel in android 5.1 I am trying to develop some functions with newly added UICC features in  TelephonyManager in android 5.1,
using these configuration in my UICC and got UICC carrier privileges already.
( refer to https://source.android.com/devices/tech/config/uicc.html )
my UICC configuration in TLV format :
FF40
81 A8
E2 3E
E1 30 //UICC rule
   C1 14 CD AE 0D 74 62 B8 ED 7D 58 68 59 23 16 45 E9 7C A5 DA 1F 90
   CA 18 63 6f 6d 2e 74 61 69 73 79 73 2e 73 6d 61 72 74 63 61 72 64 74 65 73 74
E3 0A DB 08 FF FF FF FF FF FF FF FF
E2 32 //SEEK smartcard api AID and hash
E1 28
   4F 10 01 A4 04 00 0B A0 00 00 00 18 47 50 41 43 2D 31  //AID
   C1 14 EA 76 BC 02 00 00 3B 6E 0C 58 12 72 37 F4 1F F9 78 FC 10 6B //sha-1 hash
E3 06 //SEEK smartcard api rule
   D0 01 01
   D1 01 01
E2 32
   E1 28 //uicc privilege AID and hash
   4F 10 01 A4 04 00 0B A0 00 00 00 18 47 50 41 43 2D 32
   C1 14 CD AE 0D 74 62 B8 ED 7D 58 68 59 23 16 45 E9 7C A5 DA 1F 90
E3  06
   D0 01 01
   D1 01 01

but after getting UICC privileges and trying to open iccOpenLogicalChannel, This is the stack trace I get when calling one of the above functions:
    "java.lang.SecurityException: Only Smartcard API may access UICC"
How to modify the UICC configuration and open channel successfully in Telephonymanager ?
Thanks in advance !

redpajama_set_name: RedPajamaStackExchange


text:
Q: creating a maven pom file in intellij plugin new project wizard I am writing an Intellij-idea plugin. In the plugin I want to define a new project type using new project wizard. My project should contain a specific pom file to build the project.
Any idea how I can do that? Shall I try to create the pom-file pro grammatically or shall I save a pom file as a template?

A: I resolved this by adding
<depends>org.jetbrains.idea.maven</depends> to my plugin.
Then I added a new ModuleBuilder based on jetbrains example.
I extended MavenModuel Builder (Some methods are neccessary to override e.g. getBuilderId(), getPresentableName()).
By this you are getting a pom file very easy. By cutomizing the ModuleType and ModuleBuilder you can add things that you want to POM file.

A: I generally create my IntelliJ projects using mvn archetype:generate then import it into IntelliJ.


text:
Q: Upgrade to ruby 1.9.3 with rvm or brightbox gems I currently use rvm on my dev box (osx) but I use the system ruby on my server (1.8.7 on Ubuntu 10.04)
I want to upgrade the server to 1.9.3 and have been researching the best way to do it.
The server is running about four Rails applications all on version 3.2.11.
My options appear to be using rvm or alternatively using the 1.9.3 deb package and the ruby-switch gem provided by BrightBox (who also provide passenger packages)
The Brightbox packages appear to be a clean way to go but I thought I would ask a question here to see if there are any advantages or disadvantages of either approach that I have not thought about.

A: Rvm is useful when you need to have two or more versions of Ruby on the same machine. Development machines tend to have this. There is no need to use a version manager if your production box only requires one version of Ruby.
To this effect, I'd suggest you're correct in doing a single installation from the deb package. I can see the ruby-switch gem gives similar functionality to rvm - up to you as to whether that's important. But if you're using three apps on the same version of ruby, it may not be!


text:
Q: Creating QList of multiple object types I need to make multiple instances of various class types (classA, classB, classC), and store then in a single list.  Is is possible to create these objects dynamically and then add them to a single QList?  Something like:
QList<QObject> mylist;
mylist.append(classA());
mylist.append(classB());
mylist.append(classC());

This won't compile because the objects are not of type QObject.  I could static_cast them to QObject, but will I be able to typeid.name() to determine their origical types?  (To cast them back later)?
I found an example here of using a QList< QVariant >, but the compiler complains that:

error: no matching function for call to 'QVariant::QVariant(classA&)'

for this code:
QList<QVariant> mylist;
mylist.append(QVariant(tempObj));

Update:
I got it compiling by creating the object during the append operation, AND using ::fromValue.
mylist.append(QVariant::fromValue(ClassA(1,2,3)));

Not sure this is right.  1 - will this cause a memory leak/problem creating the object in the append statement?  2 - why would I need ::fromValue to make this work?  (Does this just make a second copy of the object?)
I put a qDebug in my constructors, and I see that my constructor with parameters is called twice, then the copy constructor is called once, and the default (no parameters) constructor is never called.  I don't understand that...

A: You can use QVariant which can hold any number of different types: QVariant API
To use QVariant with a custom type you need to register it with the metatype system: QMetaType This means using Q_DECLARE_METATYPE(MyClass) Q_DECLARE_METATYPE()
QVariant is designed for holding objects of different types, and is used in all sorts of Qt conventions when the programmer wants to pass around user-defined types through Qt's interfaces when Qt itself has no way of knowing which type the programmer wants to use.
To convert back to the original type use a combination of QVariant::canConvert() and QVariant::value():
QVariant v;

MyCustomStruct c;
if (v.canConvert<MyCustomStruct>())
    c = v.value<MyCustomStruct>();

v = 7;
int i = v.value<int>();                        // same as v.toInt()
QString s = v.value<QString>();                // same as v.toString(), s is now "7"
MyCustomStruct c2 = v.value<MyCustomStruct>(); // conversion failed, c2 is empty

Your custom type must provide:

*

*a public default constructor,

*a public copy constructor, and

*a public destructor.

The following Message class is an example of an acceptable custom type for use in QVariant
class Message
{
 public:
   Message();
   Message(const Message &other);
   ~Message();

   Message(const QString &body, const QStringList &headers);

   QString body() const;
   QStringList headers() const;

 private:
   QString m_body;
   QStringList m_headers;
};

You could also declare your own "meta-type wrapper" that holds a type and a description of a type. The simplest example:
template <typename T>
class AnyType
{
public:
  enum THE_TYPE { MT_INT, MT_STRING };

  AnyType(T value, THE_TYPE type) : value(value), type(type) { }
  THE_TYPE getType() { return type; }
  T getValue() { return value; }

private:
  T value;
  THE_TYPE type;
}

A:
I could static_cast them to QObject

No, you couldn't!  And this is illegal:
QList<QObject> mylist;

QObjects have a notion of identity, and are non-copyable types.  You have to manipulate them by pointer, and that would be a list of QObject values.
But speaking more generally (about seeking to get around this kind of thing with casting)...a QList and other templated containers specifically allocate an amount of memory for the object type they are parameterized with.  So a QList<A> at the implementation level has only enough storage per item to store sizeof(A), while a QList<B> can only hold items that are sizeof(B).
So first of all: if you cast an object vs. casting a pointer then you really do lose information you can't get back...if you can even get the compiler to let you do it.  And secondly: you need to be careful even if you have a slot that holds pointers to cast to them to a "punned type" and back again due to various pitfalls which come from doing so.  Despite pointers to different types being the same size as pointers, you've got to reckon with things like the Strict Aliasing Requirement.
You can work around this with something like the QVariant as suggested by @snowandotherjoys.  If you wanted to be more "standard" you might look at boost::variant.
But it's often said that a case requiring some kind of run-time-typing like this may mean you need to take a second look at the design.  If classA and classB and classC are so different that they have no interface in common, what is it that makes putting them in a single collection that is compelling?  What can you usefully do with a collection of things that have nothing in common?  While these cases do come up (and motivate the existence of variants) it's valuable to step back and ask if you really do have one of those cases.


text:
Q: Can every basic concept of fundamental group be generalized to homotopy group? I'm taking (undergraduate) algebraic topology this year and I have learned some basic concepts in this subject. I found this subject interesting, but it seems like the usefulness of fundamental groups is restricted to low-dimensional.
Pedagogically, it's quite common that the notion of "topological space" is introduced as a metric space at the first time, then introduced later as a general topological space. I hate this approach
Just like general topology, I feel like "fundamental group" is introduced first, then "homotopy group" is introduced later even though the general "homotopy group" have almost all basic properties of fundamental group. Am I correct?
So my question is: can I just jump to homotopy group chapter and then back to first chapters of algebraic topology texts?

A: The fundamental group and higher homotopy groups are defined only for a space with a chosen base point, a structure which looks like a space, but is a bit more. I explain in this presentation,  given in Paris last June,   how the problem with the van Kampen theorem and the fundamental group of the circle led me to the use of groupoids and then higher groupoids in algebraic topology.
One has algebraic models of weak homotopy types, and higher van Kampen type theorems for filtered spaces,  and for $n$-cubes of spaces, and these allow for some calculations of $n$-types not available by other means. The catch is that calculation of a homotopy group, or a $k$-invariant,  from the determination of the model may be tricky!
Whereas group objects in groups are just abelian groups, the situation is quite different for groupoids: $n$-fold groupoids get "more nonabelian" an $n$ increases, and in fact model weak homotopy $n$-types. Since $n$-fold groupoids are strict algebraic structures, one can discuss, for example, limits and colimits.  Also the fact that these structures exist, and generalise groups,  raises the question of how generally useful they can be.
The work on filtered spaces is covered in this book Nonabelian Algebraic Topology. "The aim is for the major parts of this book to be readable by a
graduate student acquainted with general topology, the fundamental
group, notions of homotopy, and some basic methods of category
theory."
A survey on the $n$-cube case is in this paper.
The $2$-dimensional case, involving pushouts of crossed modules, the latter seen  as models of homotopy $2$-types, is  given in detail in the above book; this area seems not to have been looked at much by geometric group theorists.
To go back to one part of the question, the work on fundamental groupoids of orbit spaces as "orbit groupoids"  given in Chapter 11 of the book Topology and Groupoids has not to my knowledge been lifted to higher dimensions.


text:
Q: How to pass ASP.NET Repeater items to JavaScript array? On my, aspx page I have a repeater control that displays the lat long of the locations in the database.i want to pass the values returned from repeater into java script that display locations markers on google maps from sql server database.
 <form id="form1" runat="server">

    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

    <script type="text/javascript">
        var markers = [
        <asp:Repeater ID="rptMarkers" runat="server">
        <ItemTemplate>
                 {
                "title": '<%# Eval("City") %>',
                 "lat": '<%# Eval("Latitude") %>',
                 "lng": '<%# Eval("Longitude") %>',

             }
    </ItemTemplate>
    <SeparatorTemplate>
        ,
    </SeparatorTemplate>
    </asp:Repeater>
    ];
    </script>
   </form>

and this my code behind ,
 void GetData(string strRsult)
{
    XmlDataDocument xmlDataDoc = new XmlDataDocument();
    xmlDataDoc.LoadXml(strRsult);
    foreach (XmlNode n in xmlDataDoc.DocumentElement.GetElementsByTagName("Property"))
    {
        if (n.HasChildNodes)
        {
          List<Markers> markers = new List<Markers>();
            foreach (XmlNode childNode in n)
            {
                if (childNode.Name=="GEOData")
                {
                    markers.Add(new Markers
                    {
                        City = childNode.Attributes["City"].Value,
                        Longitude = childNode.Attributes["Longitude"].Value,
                        Latitude = childNode.Attributes["Latitude"].Value
                    });
                }

            }
            rptMarkers.DataSource = markers;
            rptMarkers.DataBind();
        }

    }

A: Code Behind
//Retrieves markers from somewhere and converts them to a JSON string
public string GetMarkersJson()
{
    List<Marker> markers = GetData("string");
    return JsonConvert.SerializeObject(markers); //using JSON.NET for serialization
}

//Parses an XML string and retrieves a list of Marker objects. Should probably go in a utility class somewhere, not in code behind
List<Marker> GetData(string strRsult)
{
    List<Marker> markers = new List<Marker>();
    XmlDataDocument xmlDataDoc = new XmlDataDocument();
    xmlDataDoc.LoadXml(strRsult);
    foreach (XmlNode n in xmlDataDoc.DocumentElement.GetElementsByTagName("Property"))
    {
        if (n.HasChildNodes)
        {
            foreach (XmlNode childNode in n)
                {
                    if (childNode.Name=="GEOData")
                    {
                        markers.Add(new Marker
                        {
                            City = childNode.Attributes["City"].Value,
                            Longitude = childNode.Attributes["Longitude"].Value,
                            Latitude = childNode.Attributes["Latitude"].Value
                        });
                    }
                }
            }
    return markers;
}

Model
//Represents the data needed for each marker, with JSON.NET attributes to account for different property names we want to use in the JSON
public class Marker
{
    [JsonProperty(PropertyName = "title")]
    public string City {get; set;}

    [JsonProperty(PropertyName = "lat")]
    public string Latitude {get; set;}

    [JsonProperty(PropertyName = "lng")]
    public string Longitude {get; set;}
}

Page
//Embed the JSON into the page and have JavaScript parse it
var markers = JSON.parse('<%= GetMarkersJson() %>');

A: your aspx code
<form id="form1" runat="server">
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

<asp:literal runat="server" id="Literal1"></asp:literal>
</form>

your aspx.cs code
    //Parses an XML string and retrieves a list of Marker objects. Should probably go in a utility class somewhere, not in code behind
    protected void GetData(string strRsult)
    {
        List<Marker> markers = new List<Marker>();
        XmlDataDocument xmlDataDoc = new XmlDataDocument();
        xmlDataDoc.LoadXml(strRsult);
        //This line write script init in your html page
        Literal1.text = "<script type=\"text/javascript\">var markers = [";

        foreach (XmlNode n in xmlDataDoc.DocumentElement.GetElementsByTagName("Property"))
        {
            if (n.HasChildNodes)
            {
//for any item you write directly the element{ tile:'yourTile', lat:'yourLat', lng:'yourLng' }
                foreach (XmlNode childNode in n)
                    {
                        if (childNode.Name=="GEOData")
                        {
                            literal1.text += "{title: '"+childNode.Attributes["City"].Value+"', lat: '"+childNode.Attributes["Longitude"].Value+"', lng: '"+childNode.Attributes["Latitude"].Valu+"'}";
                        }
                    }
            }
        }
        //Write the scripts end
        Literal1.text += "];</script>";
    }


text:
Q: react old state is showing data in new url page? I have List page where list of posts are displaying by calling the action in componentDidMount method. Links are also displayed so that when user click it will show that particular post. But when new page/url is rendered it shows the list of all posts without fetching, but when we refresh the page it does not show the list. What it means that the state data is visible to new page.
How it occurs because in react state clears when url is changed ?
enter image description here

A:
How it occurs because in react state clears when URL is changed?
  This is true and not true, actually depends on what context you are looking at. In here react state(the component state will clear) when the component is unmounted or when you deliberately.
  So possible places you should look at it are:

*

*check whether you are checking somewhere that data is fetched and you don't need to make the call. some flag in your reducer that is not being reset.

*Are you using any kind of data persistence, while reloading? like saving in session storage or local storage.

*Try to add debugger in componentDidMount and this.props.fetchPost function and see if those are being called


text:
Q: Wordpress calendar password protection I am new to Wordpress and i am trying to build a site for a customer on it.
Everything is almost finished. But now i need to password protect the calendar page of wordpress.
I am using The Events Calendar.
This site is for a small claub and only clubmember should be able to view the calendar.
Any idea how i can do it?


text:
Q: Call a method only after jobs on other threads have terminated? in my app I have two methods that load data from csv. These methods are loadData() and loadOtherData(). I want to run them in parallel so I have two threads to run them.
The loadData() method also populate one datagridview, while the data loaded by the loadOtherData() method are stored in a dictionary myDictionary.
After data loading is completed (so the methods running in the two threads have finished) I want to call another method updateGrids() that takes myDictionary as argument.
For updateGrids() to run properly, both loadData() and loadOtherData() must have run successfully cause otherwise the method doesn't have the data to work on.
How can I call method updateGrids() only when the other methods have terminated in other threads?
The structure is as follow:
    private void loadData_Click_1(object sender, EventArgs e)
    {
        ThreadStart thread1Start = new ThreadStart(loadData); // load data and fill the first datagridview
        ThreadStart thread2Start = new ThreadStart(loadOtherData); // load data and fill myDictionary
        Thread t1 = new Thread(thread1Start);
        Thread t2 = new Thread(thread2Start);
        t1.Start();
        t2.Start();

        updateGrids(myDictionary); // call this method to update remaining datagridviews
    }

    private void updateGrids(Dictionary<string, double> myDictionary)
    {
        // update the remaining datagridviews by using
        // information in the first datagridview and in myDictionary
    }

But if I run this, I get the error when updateGrids() since it doesn't have the data to work with. How can I easily change the code to make it work?

A: You could stop using ThreadStart objects directly and use Tasks instead - have them returned from your loadData and loadOtherData methods.
You have either two options here:
Either Use Task.WaitAll if you're using .NET 4.0
or (more preferable)....
Make loadData and loadOtherData async in .NET 4.5 and above (or use the async BCL package in .NET 4.0). The when you call the methods, you can cache the Task objects they return and await a call to Task.WhenAll
public async Task LoadData(){

}

public async Task LoadOtherData() {

}

private async void loadData_Click_1(object sender, EventArgs e)
{
    var loadDataTask = LoadData();
    var loadOtherDataTask = LoadOtherData();
    await Task.WhenAll(loadDataTask, loadOtherDataTask);

    updateGrids(myDictionary);
}

A: You can use async/await to wait both tasks without blocking the UI
async private void loadData_Click_1(object sender, EventArgs e)
{
    await Task.WhenAll(Task.Run(() => loadData()),
                       Task.Run(() => loadOtherData()));

    updateGrids(myDictionary);
}

A: After you start your threads, you want to wait until they are done.  So add these lines of code:
t1.Join();
t2.Join();

Join will cause the current thread to sleep until the thread being joined is complete.
Based on comments, I'm assuming this is WinForms.  In this case Join will block the UI thread.  You could create a third thread that will join the other two threads and then call Invoke to call your update method.
Since you're using .Net 4.5., you could use Async / Await; add the async modifier to your click method event handler and uses Tasks instead of Threads directly and await them.  Other answers cover that, and you can see this blog for other details too.


text:
Q: jnetpcap: can't create PcapPacket using byte array on ubuntu I'm trying to run this code which just take a HexString of bytes transform it to a byte array and try to create a PcapPacket from this array:
import org.jnetpcap.packet.PcapPacket;

public class PcapTest {

    public static void main(String[] args) {
        PcapPacket packet= new PcapPacket(hexStringToByteArray("08002760f9b952540012350208004500008f6ee600004006ab16d5f87e650a00020f15b3d192006546b55996b53d5018fffffe0c00000dcd6405003156656e6420efbfbc206d7020766f73206f66667265206a65207661697320646f646f2064616e732032206d696e7574657354cf1d3400087a376b706d7338700059006500084968656273657468050cf0a100013fcc07000100467c3c99e2ac5401"));//tcp Packet from wireshark
    }

    //this function is jute for completeness of the example
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                 + Character.digit(s.charAt(i+1), 16));
            //System.out.println(Integer.toHexString(data[i / 2]));
        }
        return data;
    }
}

I get the following error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Invalid [16,3696,3680) range.
    at org.jnetpcap.nio.JMemory.peer(Unknown Source)
    at org.jnetpcap.packet.JPacket$State.peerTo(Unknown Source)
    at org.jnetpcap.packet.PcapPacket.peerStateAndData(Unknown Source)
    at org.jnetpcap.packet.PcapPacket.transferStateAndDataFrom(Unknown Source)
    at org.jnetpcap.packet.PcapPacket.<init>(Unknown Source)
    at jNetPcapTest.JNetPcapTest.main(JNetPcapTest.java:12)

I checked the function it seems to be working well, also I'm using eclipse with root privilege (on ubuntu).
to add the library in eclipse, I've created a new User Library on eclipse added the jar and the native library location (folder where is located the .so/.dll)
I have the same problem on both linux(ubuntu) and windows.
Thank you for your help
cheers

A: I found the answer here should have read the javadoc:
http://jnetpcap.com/docs/javadocs/jnetpcap-1.3/org/jnetpcap/packet/PcapPacket.html
A pcap packet. Fully decoded packet that provides access to protocol headers as determined during the decoding process. A PcapPacket class is designed to work with pcap library. It can not be used to create a new packet from an external memory buffer that only contains packet data, such as preparing a packet to be sent from a network interface. You can use JMemoryPacket to create an in memory packet from scratch. ....

A: Example and fragment of code:
JPacket packet =
 new JMemoryPacket(JProtocol.ETHERNET_ID,
      " 001801bf 6adc0025 4bb7afec 08004500 "
    + " 0041a983 40004006 d69ac0a8 00342f8c "
    + " ca30c3ef 008f2e80 11f52ea8 4b578018 "
    + " ffffa6ea 00000101 080a152e ef03002a "
    + " 2c943538 322e3430 204e4f4f 500d0a");

tested on Windows.


text:
Q: What is the name of rank $n$ where these primes occurs Let $(p_{n})$ be the sequences of primes. We know that the quantity $g_{n}=p_{n+1}-p_{n}$ is called gap.
Consider the case of twin primes $p_{n+1}-p_{n}=2$.
My question is:
What is the name of rank $n$ where these primes occurs. For example, $n=2,3,...$.

A: The general term, for the numerical subscript when used in mathematics related to sets, is an index. Its used as reference to the ordering of the elements of the ordered set (or a sequence more likely). For example if my set were $\{2x:x\in\mathbb{N}\}$ (aka the even numbers) then then $x$ acts as an index and arguably could be referred to for the $x$th even number by using notation as $2_x$, however dangerous (definition might be required at that point though).
Another way subscripts are used in mathematics,and computing, is for bases. A numerical string, could be $123_3$ for $1\cdot 3^2 +2\cdot 3+3$ for example.
You can index in two dimensions as well, like binomial coefficients in pascal's triangle, or rows and columns of a matrix. It just takes two reference points though, usually using a hanging subscript or a comma in a subscript $_nC_r$ (sometimes written $^nC_r$) and $H_{n,m}$ for example.
EDIT we could call them the set of numbers that aren't of form $2ab+a+b$, because $2(2ab+a+b)+1 = (2a+1)(2b+1)$ which makes it composite if $a,b>0$ via Sieve of Sundaram., okay thinking wrong way, it's just an index on the primes which are a set of numbers set out as above.


text:
Q: Corresponding dependency and target lists in Makefile In a makefile, suppose I have two corresponding dependency and target lists, like this:
SRC = x.c y.c z.c
OBJS = x.o y.o z.o

Of course, my example is more complicated than this, but I want to know if it is possible to automatically create targets x.o, y.o, z.o depending on x.c, y.c, z.c respectively, like this:
x.o: x.c
y.o: y.c
z.o: z.c

A: You can use substitution references:
OBJS = $(SRC:.c=.o)

or patsubst:
OBJS = $(patsubst %.c,%.o,$(SRC))

A: I think the question was how to create rules for each of these targets, not how to create OBJS from SRC (although it's good to do that!).
The simplest way is to use the already-built-in rule in make that knows how to do it; you don't need to write your own.  Just use:
all: $(OBJS)

and they'll all be created.  You can control the compiler by setting the CC variable, the preprocessor flags by setting the CPPFLAGS variable, and the other compiler flags by setting the CFLAGS variable.
If you DO really want to write your own rule, then pattern rules will do that for you easily:
%.o : %.c
        $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<


text:
Q: Creating a domain model without circular references in Entity Framework I have found a solution that works (using DTOs and AutoMapper), which is reproduced below, but I would prefer an answer that lists the different approaches to the problem with examples and this will be marked as the answer if received.
In my entity model I have a navigation property that goes from a child entity to the parent entity. My project was working swimmingly.  Then I began to use AutoFixture for unit testing, and testing failed, AutoFixture saying I had a circular reference.
Now, I realise that circular reference navigation properties like this are OK within Entity Framework, but I found this post (Use value of a parent property when creating a complex child in AutoFixture), where Mark Seemann, the creator of AutoFixture states:
"For the record, I haven't written an API with a circular reference for years, so it's quite possible to avoid those Parent/Child relations."
So, I want to understand HOW a domain model can be refactored to avoid child/parent relations.
Below are the entity classes in question, the repository method, and how I use the property causing the circular reference in my View.  The perfect answer would explain the different options I could choose from with examples, and the basic pros/cons of each approach.
Note: The property causing the circular reference is User, in the UserTeam model.
Models:
public class UserProfile
{
    public UserProfile()
    {
        UserTeams = new HashSet<UserTeam>();
        Games = new HashSet<Game>();
    }

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }

    public virtual ICollection<UserTeam> UserTeams { get; set; }
    public virtual ICollection<Game> Games { get; set; }
}

public class Game
{
    public Game()
    {
        UserTeams = new HashSet<UserTeam>();
    }

    public int Id { get; set; }
    public int CreatorId { get; set; }

    public virtual ICollection<UserTeam> UserTeams { get; set; }
}

public class UserTeam
{
    public UserTeam()
    {
        UserTeam_Players = new HashSet<UserTeam_Player>();
    }

    public int Id { get; set; }
    public int UserId { get; set; }
    public int GameId { get; set; }

    public virtual UserProfile User { get; set; }
    public virtual ICollection<UserTeam_Player> UserTeam_Players { get; set; }
}

Repository Method
public IEnumerable<Game> GetAllGames()
    {
        using (DataContext)
        {
            var _games = DataContext.Games
                 .Include(x => x.UserTeams)
                 .Include(x => x.UserTeams.Select(y => y.User))
                 .ToList();
            if (_games == null)
            {
                // log error
                return null;
            }
            return _games;
        }
    }

View
@model IEnumerable<Game>
@foreach (var item in Model){
    foreach (var userteam in item.UserTeams){
        <p>@userteam.User.UserName</p>
    }
}

Now, if I remove the 'User' navigation property, I wouldn't be able to do '@userteam.User.UserName'
So, how do I refactor the domain model to remove the circular reference, whilst being able to easily loop through Games, and do something like
UserTeam.User.Username?

A: I had a similar problem with AutoFixture and EntityFramework a while ago. My solution was to add an extension to AutoFixture, that allows you to build a SUT with a few recursions. That extension has recently been adopted in AutoFixture.
But I understand that your question was not about how to make AutoFixture construct recursive data structures, which is indeed possible, but how to create domain models without recursion.
First, you have tree or graph structures. Here anything but recursion would mean indirection through loose coupled node ids. Instead of defining an association, you would have to traverse the tree query-by-query or cache the whole thing and traverse by node-key lookup, which may be impractical depending on the tree-size. Here it is very convenient to make EF do the work for you.
The other common structure is a two-way navigational structure similar to your user / game scenario. Here it is often not that inconvenient to prune the navigation flow to a single direction. If you omit one direction, say from game to team, you can still easily query all teams for a given game. So: User has a list of games and a list of teams. Team has a list of games. Games have no navigational reference to either. To get all users for a specific game you could write something like:
var users = (from user in DataContext.Users
            from game in user.Games
            where game.Name == 'Chess'
            select user).Distinct()

A: I have found a solution that works (using DTOs and AutoMapper), which is reproduced below, but I would still prefer an answer that lists the different approaches to the problem with examples, in particular whether this is a desirable solution, or whether I should stick with the navigation properties as they were, get rid of AutoFixture, and when it comes to serializing for json just utilise other work arounds (attributes etc)...
So, in my View Model, I added a couple of classes:
public class GameDTO
{
    public int Id { get; set; }
    public int CreatorId { get; set; }

    public ICollection<UserTeamDTO> UserTeamsDTO { get; set; }
}

public class UserTeamDTO : UserTeam
{
    public UserProfile User { get; set; }
}

And in my controller, I use AutoMapper to map the Game / UserTeam objects from the repository to my DTO objects, and return the IList _gamesDto to the View.
var _games = _gameRepository.GetAllGames();

IList<GameDTO> _gamesDto = new List<GameDTO>();
IList<UserTeamDTO> _userteamsDto = new List<UserTeamDTO>();
GameDTO _gameDto = new GameDTO();
UserTeamDTO _userteamDto = new UserTeamDTO();
Mapper.CreateMap<Game, GameDTO>();
Mapper.CreateMap<UserTeam, UserTeamDTO>();

foreach (Game _game in _games)
{
    foreach (UserTeam _userteam in _game.UserTeams)
    {
        _userteamDto = Mapper.Map<UserTeamDTO>(_userteam);
        _userteamDto.User = _userRepository.GetUser(_userteam.UserId);
        _userteamsDto.Add(_userteamDto);
    }

    _gameDto = Mapper.Map<GameDTO>(_game);
    _gameDto.UserTeamsDTO = _userteamsDto;
    _gamesDto.Add(_gameDto);
}

A: I had a similar problem recently which also impacted serializing JSON objects. I decided to remove the circular references from my data model.
I first removed the redundant navigation properties which were creating the circular references. I made sure that my resulting tree of data made sense. This allowed me to make it clear which objects own which relationships.
This also made EF unable to automatically reason about my relationships. I had to specify the One-to-Many and Many-to-Many relationships using the FluentAPI. I found a solution here: https://stackoverflow.com/a/16719203/1887885
Hope this is helpful.


text:
Q: Memcpy matrix to another matrix I would like to copy the 2 matrices. With a copy element by element through 2 for loops (row and column), after several mathematical operations and copies the final result is correct while using "memcpy" the final result is wrong in the decimal places. The code is as follows.
double **L_original;
double **L;
int nF,nU;

 L = new double*[nU]();
 L_original = new double*[nU]();
  for(int i=0; i<nU; i++){
      L_original[i] = new double[nF]();
      L[i] = new double[nF]();
  }

// copy element to element
/*for(int i=0; i<nU; i++)
        for(int j=0; j<nF; j++)
            L[i][j] = L_original[i][j];*/

memcpy(L, L_original, sizeof(L_original));

This is the correct result:Matrix Correct
This is the output: output when using memcpy

A: your L and L_original are 2D matrices, made of an array of pointers to separately allocated 1D vectors. These memory addresses may not be in a contiguous memory space. So you can't use a single memcpy to copy all subvectors.
you will have to use a for loop to apply memcpy between each L[i] and L_original[i].
also, your sizeof() operator is used incorrectly. what you need to copy is the byte length of the data (of the 1D subvector), not the length of the pointer. You need something like
  for(int i=0; i<nU; i++)
     memcpy(L[i],L_original[i], sizeof(double)*nF);


text:
Q: C++: File conflicting with itself I have created custom random number generators and placed their global functions in a file I called SamRandom.h. The file looks as follows:
#ifndef _SAM_RANDOM_H
#define _SAM_RANDOM_H

#include <cstdlib>
#include <ctime>

void InitialiseRandomSeed()
{
    //...
}

//...

#endif

I'm working in a very complex object-oriented program that has many different components from here and there. Everytime I add a file that is anyhow related to this file, I get the following conflict message:
LaserBase.obj:-1: error: LNK2005: "void __cdecl InitialiseRandomSeed(void)" (?InitialiseRandomSeed@@YAXXZ) already defined in main.obj
error: LNK1169: one or more multiply defined symbols found

On MSVC, and on MinGW I get:
In function `Z20InitialiseRandomSeedv':
SamRandom.h:8: multiple definition of `InitialiseRandomSeed()'
error: first defined here
:-1: error: collect2: ld returned 1 exit status

Why is this happening? I thought that preprocessor directive is supposed to prevent this problem from happening... this is really driving me crazy!!!
P.S.: The problem is independent of the function name.
Thanks for any efforts

A: When you include your file in a .cpp file the preprossesor directly copys it into that file. So when you compile that .cpp file the object file (a step the compiler always does even if you don't recognize) will contain that function. If you include it in more than one .cpp file each object file will contain the function. When the linker trys to link all object files to an executable it finds the function x-times and gives that error.
"one or more multiply defined symbols found" says it found one of your functions (or variables) more than once and doesnt know how to deal with it.
To avaoid this you should only put the signature of you function e.g.
//whatever.h
#ifndef _SAM_RANDOM_H
#define _SAM_RANDOM_H

void InitialiseRandomSeed();

#endif

in ther header file and put the implementation into a seperate .cpp file:
//whatever.cpp
#include "whatever.h"
#include <cstdlib>
#include <ctime>

void InitialiseRandomSeed()
{
    //...
}

A: The header guards ensure that the function is not being defined multiple times in a single compilation unit (.cpp file). However, they don't prevent the function from being defined a single time in multiple compilation units. This is because the header contains the definition of the function, so every .cpp that includes the header has its own definition of the function.
You could move the definition to SamRandom.cpp and instead declare the function in the header like so:
void InitialiseRandomSeed();

Alternatively you could specify that the function is inline which would make multiple definitions acceptable:
inline void InitialiseRandomSeed()
{
    //...
}

Assuming that the function is not performance-critical and does not get called frequently, I would go with the former approach. This keeps headers more readable and (in general) decreases compile times.

A: You could separate the definition into a .cpp file and just declare the function in the header.


text:
Q: How can I call a function of a helper class in a view - Laravel 5.8? I have a helper class DateHelper

I have one fn in there
public static function getAgo($date) {

    if ($date) {

        $ts = time() - strtotime(str_replace("-","/",$date));

        if($ts>31536000) $val = round($ts/31536000,0).' year';
        else if($ts>2419200) $val = round($ts/2419200,0).' month';
        else if($ts>604800) $val = round($ts/604800,0).' week';
        else if($ts>86400) $val = round($ts/86400,0).' day';
        else if($ts>3600) $val = round($ts/3600,0).' hour';
        else if($ts>60) $val = round($ts/60,0).' minute';
        else $val = $ts.' second';

        if($val>1) $val .= 's';

        return $val;

    }

}

I want to use it in my view like this
{{ DateHelper::getAgo($log->createdAt) }}

I kept getting

Class 'DateHelper' not found (View: ...

I tried to include it on top of my index.blade.php like this
<?php use App\DateHelper; ?>

Can someone please help me ?

A: If a use statement doesn't work in the view, you can always use inline namespacing:
{{ \App\DateHelper::getAgo($log->created_at) }}

Ensure the class is in the correct namespace and has the correct class/filename and you should be good to go.

A: You can add an alias in your config/app.php:
'aliases' => [
    // ...
    'DateHelper' => App\DateHelper::class,
],

Then in your view you can simply do:
{{ DateHelper::getAgo($log->created_at); }}


text:
Q: Querying MySQL database using PHP (if statement) I need your help.
I have a PHP code that I use to query a MySQL database after selecting a certain operator. The operators that I have from the dropdown list are "LESS THAN, GREATER THAN, and EQUALS". The problem I have is; whichever operator I select, the result that I get from the database is always for the "LESS THAN" operator. That is, it give me the same result whether I select "LESS THAN", "GREATER THAN" or "EQUALS". I tried to locate the problem but failed. Here is the code that I use:
            if ($op='LESS THAN') {
        $query = "SELECT * FROM tbl_reservoir WHERE res_vol < '$vol'";
    } elseif ($op='GREATER THAN') {
            $query = "SELECT * FROM tbl_reservoir WHERE res_vol > '$vol'";
    } elseif ($op='EQUAL') {
         $query = "SELECT * FROM tbl_reservoir WHERE res_vol = '$vol'";
    }

$op is a variable that holds the operator, and "res_vol" is a field that I compare with from the database table.

A: You have to use == or === in your if condition
if ($op == 'LESS THAN')
{
  // code here
}
elseif ($op == 'GREATER THAN')
{
  // code here
}
// .......

A: You're using an assignment operator (=) where you want the equality operator (==), so your code should read:
        if ($op=='LESS THAN') {
    $query = "SELECT * FROM tbl_reservoir WHERE res_vol < '$vol'";
} elseif ($op=='GREATER THAN') {
        $query = "SELECT * FROM tbl_reservoir WHERE res_vol > '$vol'";
} elseif ($op=='EQUAL') {
     $query = "SELECT * FROM tbl_reservoir WHERE res_vol = '$vol'";
}

but, you could simplify this to:
static $map = array('LESS THAN' => '<', 'GREATER THAN' => '>', 'EQUAL' => '=');
if (!isset($map[$op])) {
    throw new Exception(sprintf("Unexpected operator '%s', $op));
}
$query = sprintf("SELECT * FROM tbl_reservoir WHERE res_vol %s '$vol'", $map[$op]);


text:
Q: Set correct order of bibliography using latex+bibtex So, I have an .tex and .bib files and I need my bibliography list to be on right order - appearance in text (now it is like in .bib file).
How to do it?
.tex file:
\bibliography{texfile}{}
Honestly, I've tried to use search, but didn't succeed. Thanks in advance.

A: Try using
\bibliographystyle{unsrt}
\bibliography{your_bib_file_without_extension}

The unsrt option orders the references as they appear in text.


text:
Q: How do I use .htaccess RewriteRule to change underscores to hyphens When I try that this I redirect to my site root only.
For example:
https://example.com/video_cat/a-respiratory/

I want all underscores to be replaced with - (hyphen) but when I try this I'm redirected to https://example.com
Here is my .htaccess configuration
 RewriteEngine On

 RewriteRule ^([^_]*)_(.*)$ /$1-$2 [R=301,L]
 RewriteRule ^([^_]*)_([^_]*)$ /$1-$2 [L,R=301]

Complete .htaccess file:
#BEGIN CORS access to staging environments

   #start start's here
   Options +FollowSymLinks
   RewriteEngine on
  #RewriteRule ^([^_]*)_+(.*)$ /$1-$2-$3 [L,NC,R=302]

  RewriteBase /
  RewriteRule ^([^_]*)_(.*)$ /$1-$2 [R=301,L]
  RewriteRule


text:
Q: CRFSuite vs CRF++ Parameters & Results How do I mimic the results of a basic CRF++ model in CRFSuite?
I have been using CRF++ for some time and the results have been very promising, however I have recently switched to CRFSuite with Python implementation to get the model into production. That said, I have been unable to replicate to results I've obtained with CRF++ in CRFSuite using simple parameters.
The model I have created is as simple as possible with only one feature (current word):
**CRF++ Model:**
#Unigrams
U00:%x[0,0]
#Bigrams
#B

**CRFSuite Model**
def word2features(sent, i):
    word = sent[i][0]
    features = [
        'word=' + word,
    ]
    return features

The CRFSuite model is based off of this example - https://github.com/scrapinghub/python-crfsuite/blob/master/examples/CoNLL%202002.ipynb
I am using the default parameters for CRF++, but even modifying the parameters for CRFSuite to match those has been unable to get the same results.
The parameters I am using for CRFSuite are (from the manual):
algorithm = lbfgs
c1 = 0
c2 = 1

Which is supposedly the same as the default parameters in CRF++ (I'd post the manual but dont have enough rep - searched for CRF++ documentation).
Am I missing something? Thanks!


text:
Q: Enable touchpad acceleration (21.04, Wayland) Moving my finger 3 cm over the touchpad moves the cursor across approximately half the screen, regardless how quickly/slowly I do it.
That means I either can't easily hit a click target (current settings) or can't quickly move across the screen. Normally, I'm used to touchpads moving "faster" on fast movements (i.e. moving your finger quickly by 3 cm moves the cursor across the entire screen, moving the finger slowly for 3 cm only moves the cursor a little bit).
Is there some way to enable/adjust this?
$ sudo libinput list-devices
Device:           SynPS/2 Synaptics TouchPad
Kernel:           /dev/input/event6
Group:            8
Seat:             seat0, default
Size:             70x50mm
Capabilities:     pointer gesture
Tap-to-click:     disabled
Tap-and-drag:     enabled
Tap drag lock:    disabled
Left-handed:      disabled
Nat.scrolling:    disabled
Middle emulation: disabled
Calibration:      n/a
Scroll methods:   *two-finger edge
Click methods:    *button-areas clickfinger
Disable-w-typing: enabled
Accel profiles:   flat *adaptive
Rotation:         n/a


text:
Q: Upgrading to Durandal 2.0 from 1.2 - shell.html not found i'm getting a 404 error when trying to activate my shell. it seems to find shell.js but then indicates that it can't find shell.html because it's looking in the wrong place!
i tried forcing the convention to expressly tell it where to look, but it's still not working. like so: viewLocator.useConvention('viewmodels', 'views', '');
but i still get:
App/viewmodels/shell.html 404 (Not Found)
Obviously it shouldn't be looking in app/viewmodels/, it should look in app/views/
the difference in my project is that i'm not using the '/scripts/' folder for 3rd party stuff, i am using my own folder called '/content/'. i'm also putting almost everything that has to do with durandal in the '/app/' folder.
here's the structure of some key files in my project:
+app (folder)
  main.js
  > durandal (folder)
     app.js
     r.js
     require.js
     text.js
     viewEngine.js
     viewLocator.js
 > plugins (folder)
     router.js
 > viewmodels (folder)
     shell.js
 > views (folder)
     shell.html

in main.js >
  here's where i set the shell to be called:
app.setRoot('viewmodels/shell');
and here's the paths also in main.js:
paths: {
        'text': 'durandal/text',
        'durandal': 'durandal',
        'plugins': 'durandal/plugins',
        'transitions': 'durandal/transitions'
}

in shell.js >
  well, it doesn't really matter because it's already thrown the 404 by this point.
any ideas?

A: i see now. i had the wrong path to the defined modules in main.js. not sure why they weren't throwing an error, but anyhow, here's what i changed:
from:
    define(['../app/durandal/system', '../app/durandal/app', '../app/durandal/viewLocator'], function (system, app, viewLocator) {
to:
    define(['durandal/system', 'durandal/app', 'durandal/viewLocator'], function (system, app, viewLocator) {
seems to work now.


text:
Q: Plotting scatterplot with non-dominated front in R I have a dataset with two objectives (runtime and solution quality). Is there some way to draw a scatterplot in R that also draws a non-dominated front of the two objectives?

A: Presumably "runtime" is better when it is low and "solution quality" is better when it is high.  To make these variables more consistent in how they represent the attributes, first re-express them so that high numbers always correspond to better values.  For this question, the reciprocal of runtime (which could be interpreted as number of runs per second) would be a good choice, but the negative of runtime would work fine too.
With this convention established, we may plot each record in the dataset by associating the re-expressed "runtime" value with the x coordinate and the "solution quality" value with the y coordinate, creating a scatterplot.  One record $(x,y)$ dominates another $(x',y')$ when simultaneously $x\ge x'$, $y\ge y'$, and $(x,y) \ne (x',y')$.  No rational actor (using solely information about "runtime" and "solution quality") would choose the dominated option $(x',y')$ when $(x,y)$--which is at least as good on both attributes and better on at least one--is available. Therefore such an actor would focus their interest on the non-dominated options and would be free to neglect all others.

All points dominated by the solid red point are shown in gray.  All possible points that it can dominate constitute the (closed) rectangle shown in pink. Because evidently no points in the scatterplot dominate the solid point, it must lie on the non-dominated frontier.
The set of non-dominated options forms the vertices of part of the "quasi-convex hull" or "non-dominated frontier" of the scatterplot.  This is an analog of the better-known convex hull.  Indeed, the quasi-convex hull will be invariant under all increasing monotonic re-expressions of the variables, $f(x)$ and $g(y)$, and one can always find such re-expressions for which the quasi-convex hull actually becomes the convex hull.  This connection, and the fact that optimal construction of the convex hull of $n$ points requires $O(n\log(n))$ computation, suggests that we seek an algorithm for the quasi-convex hull that performs at least as well.  Such algorithms exist.  Here is one, given in R as requested, which is written to port easily to other computing platforms:
hull.qc <- function(xy) {
  i <- order(xy[, 1], xy[, 2], decreasing=TRUE)
  frontier <- rep(0, length(i))
  k <- 0; y <- -Inf
  for (j in i) {
    if (xy[j, 2] > y) {
      frontier[k <- k+1] <- j
      y <- xy[j, 2]
    }
  }
  return(frontier[1:k])
}

It performs a decreasing lexicographic sort of the coordinates (time: $O(n\log(n))$) and then scans through the first coordinate (time: $O(n)$), putting into effect a line scan algorithm. The points where a new larger value of the second coordinate is found are recorded.  Their indexes within the input array xy are returned.
We can prove this algorithm is correct by induction.  The initial point, chosen to have a maximal first coordinate and (among such points) a maximal second coordinate, obviously is not dominated.  Using it we can eliminate all other points that it does dominate, including itself.  The first non-eliminated point next encountered in the algorithm necessarily has a larger value of its second coordinate. It obviously is not dominated by any point because if it were, that other point would already have been encountered.  Therefore the algorithm indeed selects non-dominated points and (by induction on the number of points) it finds them all, QED.
To illustrate these concepts and this algorithm, here is plot of a dataset of $16$K records (all with integral values, shown jittered) along with its quasi-convex hull (a dark line at the upper right), its vertices marked as requested in the question, and the "dominance rectangles" of those vertices colored in.

The code to do the calculations, make a scatterplot, and mark the vertices of its quasi-convex hull appears below.  It includes a slightly faster R-centric version of hull.qc.  It processes a million points in approximately two seconds on this machine.
#
# A faster solution (for R).
#
hull.qc <- function(xy) {
  i <- order(xy[, 1], xy[, 2], decreasing=TRUE)
  y <- xy[i, 2]
  frontier <- which(cummax(y) <= y)
  #
  # Eliminate interior points along edges of the hull.
  #
  y.0 <- y[frontier]
  frontier <- frontier[c(TRUE, y.0[-1] != y.0[-length(y.0)])]
  return(i[frontier])
}
#
# Generate data.
#
library(MASS)
set.seed(17)
n <- 2^14
xy <- floor(mvrnorm(n, c(1,1), matrix(c(1, -1/2, -1/2, 1), 2))^2)
#
# Do the work.
#
system.time(frontier <- hull.qc(xy))
xy.f <- xy[frontier, , drop=FALSE]
#
# Visualization.
#
plot(xy, xlab="X", ylab="Y", main="Quasiconvex Hull")
points(xy.f, pch=19, col="Red")


text:
Q: How to change the content with click of an image in Javascript? I have a fiddle in which I want to apply some logic in it.
On clicking of Franchise Hub image, I want the desktop screen and the text next to it should appear with the phone screen below and the content next to it getting hidden.
Whereas on clicking of Cloud Based and Mobile, I want the mobile screen and the text next to it should appear with the tv screen and the content next to it getting hidden.

Javascript:
The Javascript code which I have tried in order to achieve the above logic is:
const cbBtn = document.querySelector('img#franchise-hub');

const cloudbasedtextipad = document.querySelector('div.cloudbasedtextipad');

cbBtn.addEventListener('click', event => {
cloudbasedtextipad.style.display = 'block';
cbBtn.className = 'active';
});

Problem Statement:
I am wondering what changes I should make in the Javascript code above so that on clicking different images, different contents should appear.

const cbBtn = document.querySelector('img#franchise-hub');

const cloudbasedtextipad = document.querySelector('div.cloudbasedtextipad');

cbBtn.addEventListener('click', event => {
  cloudbasedtextipad.style.display = 'block';

  cbBtn.className = 'active';
});
.product-contents {
  margin-left: 15%;
  margin-right: 15%;
  display: flex;
  justify-content: space-between;
  background-color: #f0f0f0;
  align-items: center;
  padding: 1rem;
  margin-bottom: 5%;
}

.product-contents .product {
  width: 10%;
  text-align: center;
  height: 150px;
  padding-top: 1%;
  padding-left: 1%;
  padding-right: 1%;
  border-style: solid;
  border-width: 3px;
  border-color: rgb(145, 147, 150);
  background-color: white;
  border-radius: 10px
}

.product-contents .product #franchise-hub {
  margin-bottom: 22%;
}

.product-contents .product #cloud-based-mobile {
  margin-bottom: 30%;
}

.product-contents .product #business-analytics {
  margin-bottom: 28%;
}

.product-contents .product #tech-support {
  margin-bottom: 27%;
}

.product-contents .product #order-management {
  margin-bottom: 27%;
}

.product-contents .product #employee-management {
  margin-bottom: 18%;
}

.product-contents .product #white-label {
  margin-bottom: 15%;
}

.product-contents .product #brand-control {
  margin-bottom: 20%;
}

.product-contents .product #lead-tracking {
  margin-bottom: 28%;
}

.product-contents .product #custom-invoicing {
  margin-bottom: 27%;
}

.product-contents .product #goal-setting {
  margin-bottom: 26%;
}

.product-contents .product #customization-tools {
  margin-bottom: 27%;
}

.product-contents .product #royalty-calculator {
  margin-bottom: 27%;
}

.product-contents .product #email-marketing {
  margin-bottom: 24%;
}

.ipads {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
}

.tvs {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
}

.cloud-based-text {
  width: 50%;
}

.franchise-hub-text {
  width: 50%;
}

div.cloudbasedtextipad {
  display: flex;
  margin-left: 15%;
  margin-right: 15%;
  align-items: center;
  background-color: #f0f0f0;
  padding: 2%;
  margin-bottom: 5%;
}

div.franchisehubtv {
  display: flex;
  margin-left: 15%;
  margin-right: 15%;
  align-items: center;
  background-color: #f0f0f0;
  padding: 2%;
}

Franchise Hub

Cloud Based & Mobile

Software that works the way you do

We're cloud-based and mobile-first, which means you can access everything you need, no matter where you are. The app lets you run your business without compromising any features or power, so employees are able to check in from worksites and stay up
      to date.

Software that works the way you do

We're cloud-based and mobile-first, which means you can access everything you need, no matter where you are. The app lets you run your business without compromising any features or power, so employees are able to check in from worksites and stay up
      to date.

A: Selection Colour Toggle Implemented as well.

$("#mobile").click(function() {
  if ($('.cloudbasedtextipad').css('display') == "flex") {
    $('.cloudbasedtextipad').css('display', 'none');
    $('#mobile').css('background-color', 'lightgray');
    $('#desktop').css('background-color', 'lightgray');
  } else {
    $('.cloudbasedtextipad').css('display', 'flex');
    $('#mobile').css('background-color', 'green');
    $('#desktop').css('background-color', 'lightgray');
    $('.franchisehubtv').css('display', 'none');

  }

});

$("#desktop").click(function() {

  if ($('.franchisehubtv').css('display') == "flex") {
    $('.franchisehubtv').css('display', 'none');
    $('#desktop').css('background-color', 'lightgray');
    $('#mobile').css('background-color', 'lightgray');
  } else {
    $('.franchisehubtv').css('display', 'flex');
    $('.cloudbasedtextipad').css('display', 'none');
    $('#desktop').css('background-color', 'green');
    $('#mobile').css('background-color', 'lightgray');
  }
});
.product-contents {
  margin-left: 15%;
  margin-right: 15%;
  display: flex;
  justify-content: space-between;
  background-color: #f0f0f0;
  align-items: center;
  padding: 1rem;
  margin-bottom: 5%;
}

.product-contents .product {
  width: 10%;
  text-align: center;
  height: 150px;
  padding-top: 1%;
  padding-left: 1%;
  padding-right: 1%;
  border-style: solid;
  border-width: 3px;
  border-color: rgb(145, 147, 150);
  background-color: white;
  border-radius: 10px
}

.product-contents .product #franchise-hub {
  margin-bottom: 22%;
}

.product-contents .product #cloud-based-mobile {
  margin-bottom: 30%;
}

.product-contents .product #business-analytics {
  margin-bottom: 28%;
}

.product-contents .product #tech-support {
  margin-bottom: 27%;
}

.product-contents .product #order-management {
  margin-bottom: 27%;
}

.product-contents .product #employee-management {
  margin-bottom: 18%;
}

.product-contents .product #white-label {
  margin-bottom: 15%;
}

.product-contents .product #brand-control {
  margin-bottom: 20%;
}

.product-contents .product #lead-tracking {
  margin-bottom: 28%;
}

.product-contents .product #custom-invoicing {
  margin-bottom: 27%;
}

.product-contents .product #goal-setting {
  margin-bottom: 26%;
}

.product-contents .product #customization-tools {
  margin-bottom: 27%;
}

.product-contents .product #royalty-calculator {
  margin-bottom: 27%;
}

.product-contents .product #email-marketing {
  margin-bottom: 24%;
}

.ipads {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
}

.tvs {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
}

.cloud-based-text {
  width: 50%;
}

.franchise-hub-text {
  width: 50%;
}

div.cloudbasedtextipad {
  display: flex;
  margin-left: 15%;
  margin-right: 15%;
  align-items: center;
  background-color: #f0f0f0;
  padding: 2%;
  margin-bottom: 5%;
}

div.franchisehubtv {
  display: flex;
  margin-left: 15%;
  margin-right: 15%;
  align-items: center;
  background-color: #f0f0f0;
  padding: 2%;
}

Franchise Hub

Cloud Based & Mobile

Software that works the way you do

We're cloud-based and mobile-first, which means you can access everything you need, no matter where you are. The app lets you run your business without compromising any features or power, so employees are able to check in from worksites and stay up
      to date.

Software that works the way you do

We're cloud-based and mobile-first, which means you can access everything you need, no matter where you are. The app lets you run your business without compromising any features or power, so employees are able to check in from worksites and stay up
      to date.

A: I implement the first case only.
You have to learn how to implement the second one.
First, the CSS for div.cloudbasedtextipad changed to
div.cloudbasedtextipad
{
display: none;
margin-left: 15%;
margin-right: 15%;
align-items: center;
background-color: #f0f0f0;
padding: 2%;
margin-bottom: 5%;
}

And the javascript changed as the following:
    const cbBtn = document.querySelector('img#franchise-hub');

    const cloudbasedtextipad = document.querySelector('div.cloudbasedtextipad');

    cbBtn.addEventListener('click', event => {
        cloudbasedtextipad.style.display = 'flex';
    });


text:
Q: Potential CSS Scroll Snap bug in Chrome (Windows). Two examples, only one work. Why? Here are two CSS scroll-snaps examples from csstricks.com

*

*Example #0 works on Chrome on Windows

*Example #3 does not work

Why does one of them work, and not the other; what is the difference between the two?
Example 1:
.container {
    flex-basis: 50%;
    max-height: 100vh;
    overflow-y: scroll;
    border: 1px solid gray;
    scroll-snap-type: y mandatory;
    &.proximity {
            scroll-snap-type: y proximity;
    }
}

li {
    border-bottom: 1px solid white;
    padding: 3rem;
    font-size: 1.4rem;
    color: rgba(white, .5);
    background: lightgray;
    text-align: center;
    scroll-snap-align: start;
    display: flex;
    flex-flow: column;
    justify-content: center;
}

Example 2:
body {
    font-family: sans-serif;
    scroll-snap-type: mandatory;
    scroll-snap-points-y: repeat(100vh);
    scroll-snap-type: y mandatory;
}
section {
    border-bottom: 1px solid white;
    padding: 1rem;
    height: 100vh;
    scroll-snap-align: start;
    text-align: center;
    position: relative;
}

A: Because by default the <body> doesn't scroll, <html> does.
 Change the selector to :root and it will work in Chrome.
Though to be safe you'd be better defining your own scrolling area since older browsers were indeed using <body> as scrollingElement.


text:
Q: NextAuth / Auth.js + Keycloak OAuthCallbackError: failed to validate JWT signature (T3 Stack) I am attempting to integrate a remote Keycloak provider into my containerized Next application. Currently, I am able to make it all the way through the authentication flow, including reaching the correct Keycloak instance and signing in on that page, up until I should be signed into my app... At that point, I receive this error:
[next-auth][error][OAUTH_CALLBACK_ERROR]
https://next-auth.js.org/errors#oauth_callback_error failed to validate JWT signature {
  error: RPError: failed to validate JWT signature
    at Client.validateJWT (/app/node_modules/openid-client/lib/client.js:1055:11)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Client.validateIdToken (/app/node_modules/openid-client/lib/client.js:745:49)
    at async Client.callback (/app/node_modules/openid-client/lib/client.js:488:7)
    at async oAuthCallback (/app/node_modules/next-auth/core/lib/oauth/callback.js:127:16)
    at async Object.callback (/app/node_modules/next-auth/core/routes/callback.js:52:11)
    at async AuthHandler (/app/node_modules/next-auth/core/index.js:201:28)
    at async NextAuthHandler (/app/node_modules/next-auth/next/index.js:23:19)
    at async /app/node_modules/next-auth/next/index.js:59:32
    at async Object.apiResolver (/app/node_modules/next/dist/server/api-utils/node.js:366:9) {
  name: 'OAuthCallbackError',
  code: undefined
 },
 providerId: 'keycloak',
 message: 'failed to validate JWT signature'
}

I also have a Github app integrated with the application, and it works perfectly. the code for my [...nextauth].ts can be found below.
export const authOptions: NextAuthOptions = {
  providers: [
    KeycloakProvider({
      clientId: env.KEYCLOAK_CLIENT_ID,
      clientSecret: env.KEYCLOAK_CLIENT_SECRET,
      issuer: env.KEYCLOAK_ISSUER,
    }),
    GithubProvider({
      clientId: env.GITHUB_ID || "",
      clientSecret: env.GITHUB_SECRET || "",
    }),
  ],
  debug: true,
  secret: env.NEXTAUTH_SECRET,
};

export default NextAuth(authOptions);

This is what my _app.tsx looks like:

const MyApp: AppType<{ session: Session | null }> = ({
  Component,
  pageProps: { session, ...pageProps },
}) => {
  return (
    <SessionProvider session={session}>
      <Component {...pageProps} />
    </SessionProvider>
  );
};

export default trpc.withTRPC(MyApp);

And finally, my Login Button component:

export default function LoginButton() {
  const { data: session } = useSession();
  if (session) {
    return (
      <>
        Signed in as {session.user?.name}

        <button onClick={() => signOut()}>Sign out</button>
      </>
    );
  }
  return (
    <>
      Not signed in

      <button onClick={() => signIn()}>Sign in</button>
    </>
  );
}

I have gotten this integration to work before on a local containerized version of Keycloak using the quay.io/keycloak/keycloak:20.x.x version of Keycloak, but have yet to get it to work with a remote/production version. The production version of Keycloak I am attempting to connect to is behind an NGINX reverse proxy, the configuration for which is fairly standard but can be provided upon request. I have even gone as far as to put the Next app and Keycloak into the same docker-compose file, to no avail.
I have attempted to change the location of the Next app, change the location of Keycloak, create a new app, create a new KC Realm, and integrate with other OAuth providers. I have never gotten further in the flow than the OAuthCallbackError, except when both versions were local, which is not acceptable for a production environment.
Has anyone else had this issue or found a possible fix?


text:
Q: Create the configuration file at maven install and without or before feature install for Karaf In my project, in the bundle module, at resource directory, I have my sample startup.cfg file. This file contains properties I want to use at the startup. In the bundle pom.xml I have the following.
<build>
  <plugins>
    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>build-helper-maven-plugin</artifactId>
      <executions>
        <execution>
          <id>attach-artifacts</id>
          <phase>package</phase>
          <goals>
            <goal>attach-artifact</goal>
          </goals>
          <configuration>
            <artifacts>
              <artifact>
                <file>${project.build.directory}/classes/startup.cfg</file>
                <type>cfg</type>
                <classifier>config</classifier>
              </artifact>
            </artifacts>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

And in my feature xml, I have,
<feature name="my-sample-feature" description="Sample service" version='${project.version}'>
    <bundle>mvn:org.sample.app/service.implementation/{{VERSION}}</bundle>
    <configfile finalname="/etc/org.sample.app.startup.cfg">mvn:mvn:org.sample.app/service.implementation/{{VERSION}}/cfg/config</configfile>
</feature>

In feature xml, I have added,
<dependency>
  <groupId>${project.groupId}</groupId>
  <artifactId>service.implementation</artifactId>
  <version>${project.version}</version>
  <classifier>config</classifier>
  <type>cfg</type>
</dependency>

This feature is a startup feature too. Now, when I install the feature in a karaf container or in this case when I spin up the karaf, only then the etc/org.sample.app.startup.cfg is created. My target is simple, to have this conf file always at etc/ independent of the feature is installed or not.

A: The cfg file are deployed into etc folder when installing the feature . If you want it to be present independent of the feature is installed or not, this means that you have to deploy it manually to etc and this is more simple after attaching the cfg to your artifact as you did in your pom.
Remember that if you want to follow best pratices (especially in a production environnement), don't separate cfg deployment from it's origin feature.


text:
Q: Is it possible for a particular thread in a process to create multiple jobs? Is it possible to create multiple jobs with in a single thread? I am really wondered by looking into one of the product logs. Same thread called a function with different parameter approximately at the same time.
Please correct me if understanding is wrong. or is there any other method which actually does this in a single thread.

A: If you mean by "multiple jobs" the concept of "multiple threads", then yes ... it is possible to create multiple threads from a single thread ... you simply call pthread_create() in your thread, and it will spawn more threads.
From your description of some reading of a "log file" though, it sounds to me like you're asking whether a single thread can do multiple things simultaneously.  The answer to that is "no".  A single thread of execution has the appearance of sequential consistency to the end-user, meaning that it will appear to perform one operation after another.  When you are stating from a log-file that a single thread appeared to call one function at the same time as another function, but with different parameters, the most likely cause for this scenario is that the precision of time measurement for the log file was not precise enough to account for how fast the function calls took place.  Therefore it appears as though two function calls were made simultaneously by a single thread.  That does not mean that a single-thread is performing "multiple jobs" simultaneously ... that would be impossible.


text:
Q: Is it possible to run IIS7 on Windows Server 2003? Is it possible to run IIS 7 or IIS 7.5 on Windows Server 2003?

A: No, since IIS4, the IIS version has been tied to the OS version.
IIS7, specifically, has many hooks into Server 2008 features that don't exist in Server 2003.  So even if you were able to force the installer to complete on 2003, IIS would not work.  Upgrade to a newer OS, or live with IIS 6.

A: Nope. It's not possible. You'll need to upgrade your OS.


text:
Q: Удалить первые два символа в каждом слове длиннее заданной величины есть у меня строка на входе, и в ней нужно удалить первые два символа у слов, длина которых больше 4
public static void main(String[] args) throws FileNotFoundException {
String content = getInput("part1.txt");

}
public static String getInput(String fileName) {
    StringBuilder sb = new StringBuilder();
    try {
        Scanner scanner = new Scanner(new File(fileName), "cp1251");
        while(scanner.hasNextLine()) {
            sb.append(scanner.nextLine()).append(System.lineSeparator());
        }
        scanner.close();
        return sb.toString();
    }catch(IOException ex) {
        ex.printStackTrace();
    }
    return sb.toString();
}

как это можно сделать?
на входе
When I was younger,
So much younger
than today

на выходе
en I was unger,
So ch unger
an day

A: Находит слова длины 4+, удаляете в них найденную группу:
([\w'-][\w'-])[\w'-][\w'-]+

Использованы именно такие определения символов, а не просто \w, исходя из комментариев. Нужны ещё какие-то символы — добавляйте.
Тест https://regexr.com/593a5

When I was younger,
So much younger
than today
wbtb wtombotb wrb omwb wtbombr wtomo

A: Предполагаю, что это какая-то практическая задачка, и особого внимания ко входным данным не требует. Чуток видоизменил ваш метод, при необходимости можно внести дополнения в переменную regex
public static String getInput(String fileName) {
    StringBuilder sb = new StringBuilder();
    String regex = "([A-Za-z]+)[^A-Za-z]+";
    Pattern pattern = Pattern.compile(regex);

    try (Scanner scanner = new Scanner(new File(fileName), "cp1251")) {
        while(scanner.hasNextLine()) {
            String line = scanner.nextLine() + System.lineSeparator();

            Matcher matcher = pattern.matcher(line);
            while (matcher.find()) {
                String block = matcher.group();
                String word = block.replaceAll(regex, "$1");
                sb.append((word.length() >= 4 ? block.substring(2) : block));
            }
        }
    }catch(IOException ex) {
        ex.printStackTrace();
    }

    return sb.toString();
}


text:
Q: VS2010 Build Exception caused by ReSharper; SetEnvironmentVariable task not found I've had a problem with my Windows 7 after an update, neither Safe Mode nor Recovery Mode could resolve the problem. I was forced to reinstall Windows completely. To develop on my projects I need Visual Studio 2010.
I always had ReSharper installed and got used to its features, so I installed it aswell.
Everything setup I tried building my solution but encountered a problem ...

(The underlined file can be found here: https://up.zone/aj)
After hours of trying to resolve the problems, I figgured out that ReSharper was the problem. I can build the solution perfectly fine without ReSharper installed. Having it installed, even if all features are turned off and the services are suspended, causes these errors in the picture above to show on build.
I managed to resolve two out of three errors by following the instructions of this Reddit user on his post: https://up.zone/ag
Now I am left with one more exception I cannot figgure out how to resolve. I couldn't really find anything helpful googling, which means you guys are my last hope. I really do not want to go back to developing without ReSharper.
This is the one:

Any idea?
Thank you!

Update 1
I figgured out that the problem must be in the NuGet.targets file, located in the .nuget folder in our solution.
I managed to find a workaround following the suggestion of this post, I am now able to build the solution without any errors.
To summarize, remove this line out of your *.csproj file

<Import Project="$(SolutionDir)\.nuget\nuget.targets" />

Although this works, I don't think this can be the solution. This line is there for a reason I assume. Anybody with a deep understanding of NuGet who might know how to properly resolve this problem?

Update 2
I found out that as soon as you reload your solution/project, the line gets added once again. Also, if you have certain dependencies nuget should download for you - it won't, because the line which makes that call and handles this got removed.
I'm now at a point where I know where the problem is but not why it is caused.
Does ReSharper change anything in the way NuGet behaves? As far as I can tell, nothing gets added or removed to or from the NuGet.targets file due to ReSharper.

A: There were one more report on this topic, at https://youtrack.jetbrains.com/issue/RSRP-462271 .
The best guess so far is that this is caused by two things happening at once: (a) using MSBuild tasks in C# source code form inside MSBuild XML files rather than DLLs and (b) having some of the MSBuild opensource DLLs shipped with the latest version of ReSharper for its own project file handling needs.
The source code gets compiled into a task DLL during an MSBuild run (not a much common thing to have; Roslyn would do this rather than ship a DLL? seriously?). When building from within Visual Studio (rather than with msbuild.exe), the in-process MSBuild instance is used, and it would run in the same appdomain as ReSharper, so it uses the common assembly reference resoluiton. If it's not too accurate, then it might accidentally pick the wrong DLL version by the short name, which would break the task compilation (that's a separate error, maybe cached away) and then result in the task-not-found error later at runtime (SetEnvironmentVariable task not found in here case).
I've tested on sample solutions with source code based tasks and could not get it broken. So trivial cases are OK. Never heard back from the original issue reporter, so there was no further progress.
Now I've got a hint that this is Visual Studio 10 (any other VS versions installed on that machine?) and maaaaybe it's Roslyn tasks. We might know for sure if you run MSBuild with more detailed logs (by setting the logging options at Tools | Options | Projects and Solutions | Build and Run | MSBuild project build output verbosity to at least Detailed) and building just the faulty project.
I'll also try this out with VS10 and update this reply with new data.


text:
Q: Button click event works only once asp.net This is my .aspx code:
<asp:Panel ID="passengerBox" CssClass="transparentBox" runat="server">
    <asp:Table ID="passengerDetailsTable" runat="server">
        <asp:TableRow>
            <asp:TableCell><asp:Label runat="server" Text="1." /></asp:TableCell>
            <asp:TableCell><asp:TextBox ID="name1" CssClass="nameTextbox form-control" runat="server" /></asp:TableCell>
            <asp:TableCell><asp:TextBox ID="age1" CssClass="ageTextbox form-control" runat="server" /></asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
            <asp:TableCell><asp:Label runat="server" Text="2." /></asp:TableCell>
            <asp:TableCell><asp:TextBox ID="name2" CssClass="nameTextbox form-control" runat="server" /></asp:TableCell>
            <asp:TableCell><asp:TextBox ID="age2" CssClass="ageTextbox form-control" runat="server" /></asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
            <asp:TableCell><asp:Label runat="server" Text="3." /></asp:TableCell>
            <asp:TableCell><asp:TextBox ID="name3" CssClass="nameTextbox form-control" runat="server" /></asp:TableCell>
            <asp:TableCell><asp:TextBox ID="age3" CssClass="ageTextbox form-control" runat="server" /></asp:TableCell>
        </asp:TableRow>
    </asp:Table>
    <asp:Button ID="addPerson" runat="server" Text="Add Person" OnClick="addPerson_Click" />
</asp:Panel>

This is my .aspx.cs page:
public partial class Pages_Passengers : System.Web.UI.Page
{
    int count = 3;
    protected void addPerson_Click(object sender, EventArgs e)
    {
        TextBox nameTxtBox = new TextBox();
        TextBox ageTxtBox = new TextBox();

        TableRow tRow = new TableRow();
        for (int i = 1; i <= 3; i++)
        {
            TableCell tCell = new TableCell();
            if (i == 1)
                tCell.Text = count.ToString() + ".";
            if (i == 2)
                tCell.Controls.Add(nameTxtBox);
            if (i == 3)
                tCell.Controls.Add(ageTxtBox);
            tRow.Cells.Add(tCell);
        }
        passengerDetailsTable.Rows.Add(tRow);
    }
}

I want to add a new row to the table every time I click the button "addPerson". But this button only works once. What do I do?

A: Ok! I'm assuming the code has no real purpose but it's just for training.
If you're not using databases the easy way to get data persistency is using session variable (so .. it works but let me remind you it's not always a good idea)
Web form :
<body>
<form id="form1" runat="server">
<div>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>

Your webform now is cleaner because the table will be managed by code behind.
The code:
public partial class WebForm1 : System.Web.UI.Page
{
    private Table _passengerDetailsTable;
    private int _rowCounter = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        // a recomandation ... make strong use of comments

        this.InitTable(); // initializing the table from code behind

        this._rowCounter = this._passengerDetailsTable.Rows.Count;
    }

    private void InitTable()
    {
        this._passengerDetailsTable = new Table();

        if (Page.IsPostBack) // ok! if page is loaded for the first time we can create table, if we are back by a summit button code will be skipped
        {
            this._passengerDetailsTable = (Table)Session["tblPassengers"]; // get back the Table we stored in a session variable
        }
        else
        {
            TableRow dr = CreatePassengerDataRow(); // remember DRY Don't Repeat Yourself you are expected to create many rows. Bundle all the needed stuff inside a method

            // perhaps you should create an header for the table to enhance readibility

            this._passengerDetailsTable.Rows.Add(dr); // add the datarow

            Session["tblPassengers"] = this._passengerDetailsTable; // store the table state in a session variable
        }

        this.form1.Controls.Add(_passengerDetailsTable); // add the control to the form
    }

    /// <summary>
    /// create a new datarow
    /// </summary>
    /// <param name="counter"></param>
    /// <returns></returns>
    private TableRow CreatePassengerDataRow()
    {

        var dr = new TableRow(); // keeping things easy I'll create a single TableRow

        // avoid the loop, it make code less readable and has no clear purpose

        var tc0 = new TableCell();  // counter cell
        tc0.Text = String.Format("#{0}", (this._rowCounter));
        dr.Cells.Add(tc0);

        var tc1 = new TableCell(); // name cell
        tc1.Controls.Add(this.CreateInputTb("name", this._rowCounter)); // DRY again
        dr.Cells.Add(tc1);

        var tc2 = new TableCell(); // age cell
        tc2.Controls.Add(this.CreateInputTb("age", this._rowCounter));
        dr.Cells.Add(tc2);
        return dr;
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="name"></param>
    /// <param name="counter"></param>
    /// <returns></returns>
    private TextBox CreateInputTb(string name, int counter)
    {
        var textBox = new TextBox();
        textBox.ID = String.Format("{0}_{1}", name, counter); // create a tb unique identifier (makes your life easier if you plan to use is data)
        return textBox;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        TableRow dataRow = this.CreatePassengerDataRow(); // create a brand new role
        this._passengerDetailsTable.Rows.Add(dataRow); // append the role
    }
}

Enjoy.


text:
Q: Create Grafana Alert for k8s cluster pods CPU usage I have already tried finding resources and articles online for how to create alerts using Grafana 8 UI about the CPU and/or memory usage of my kubernetes cluster pods, but I couldn't find anything, neither on youtube, google, discord, stackoverflow nor reddit.
Does anyone know any guide on how to do that?
The goal is to literally create an alert rule that will send a slack message when the CPU or Memory usage of my kubernetes cluster pods pass over X%. The slack app to receive the grafana message is working, but I have no idea how would be the grafana query.
PS.: I am using Prometheus and node-exporter.

A: You can try this query for creating an alert if the CPU or Memory usage is above threshold (let say 85%).
sum(rate(container_cpu_usage_seconds_total{namespace="$namespace", pod="$pod", container!="POD", container!="", pod!=""}[1m])) by (pod) / sum(kube_pod_container_resource_limits{namespace="$namespace", pod="$pod", resource="cpu"}) by (pod) * 100
You can check CPU utilization of all pods in the cluster by running:
sum(rate(container_cpu_usage_seconds_total{container_name!="POD",pod_name!=""}[5m]))
If you want to check CPU usage of each running pod you can use using:
sum(rate(container_cpu_usage_seconds_total{container_name!="POD",pod_name!=""}[5m])) by (pod_name).
To see actual CPU usage, look at metrics like container_cpu_usage_seconds_total (per container CPU usage) or maybe even process_cpu_seconds_total (per process CPU usage).
You can create alert rule in grafana by following the steps provided in the document and refer to the link for more information.


text:
Q: call model from laravel 8 on view i want to call my model function from my view.
I tried like this but it didn't work
<ul class="sidebar-nav" data-coreui="navigation" data-simplebar="">
    @php
        $role = App\Models\Web\Systems\Role;
        //     $r = $role->getApi(1);
        var_dump($role);
    @endphp </ul>

A: Make the function static inside of the model. After that in the view use:
\App\Models\Web\Systems\Role::getApi(1);


text:
Q: Using baposter: position logos I am preparing a poster, and the problem I have is that the logo stays center to the line of title, while i wanna it to respect the top margin. any idea how to do that?
{\includegraphics[scale=0.5]{LOGO1}}  %%%Added left logo
{\sf\bf \smaller What I talk about} % Poster title
{\vspace{0.2em} I am the speaker} % Author names
{\includegraphics[scale=0.5]{LOGO2}}

beside, how can I add a box the title part?

A: You may try something like this:
{\parbox[top][6em][t]{10em}{\includegraphics[scale=0.5]{LOGO1}}}
{\sf\bf\smaller\fbox{What I talk about}}
{\vspace{0.2em} I am the speaker}
{\parbox[top][6em][t]{10em}{\hfill \includegraphics[scale=0.5]{LOGO2}}}

Also make sure that eyecatcher=yes.


text:
Q: How to add a seperate column instead of a row group in a matrix SSRS Report I am trying to create a matrix report in SSRS using Visual Studuio 2008 .
My reports are .rdlc reports
This is how I want the report look like
Product Name |Year | Question1| Question 2| so on........
Test 1       |2012 | Response1| Response 2| so on........
Test 1       |2013 | Response1| Response 2| so on........

But my report comes as like this
Product Name       | Question1| Question 2| so on........
Test 1       |2012 | Response1| Response 2| so on........
             |2013 | Response1| Response 2| so on........

I am not able to achieve this the year column is adding a sub group
but not as a seperate column
When I right click on the Product Name row these are the options i get though

Here is the screen shot of the report

Let me know if any other option i have .
Thanks ,
Sravanthi

A: It would be easier to troubleshoot if you post your report design.
Method 1 Split Cells
Step 1. Right click on the detail row for product (where it says Fields!Product.Value or Test) and insert a row. Insert Row > Inside Group - Below
Step2. Right click on the data/detail row for product and you will see an option for split cells. Click on that. It will split the cells.
Step 3. Delete the row added in step 1 without deleting any row groupings.
Step 4. Run your report, you should see the changes.
Method 2 Delete the columns and re-add them
Step 1. Delete Product and Year columns without deleting the associated groups.
Step 2. Right Click on your Question column and click on Insert Column > Outside Group - Left. Do that twice.
Step 3. In those newly generated columns add the Product and Year header and data.
Step 4. Run your report, you should see the changes.


text:
Q: Analogue to Fixed Point Theorem for Compact metric spaces If $\omega:H \rightarrow H$ (into) is continuous and $H$ is compact, does  $\omega$ fix any of its subsets other than the empty set?

A: the proof I learned from Henno Brandsma's answer: Let $X$ be compact Hausdorff (no metric is needed), and define $A_0 = X$, $A_{n+1} = f[A_n]$; then all $A_n$ are compact non-empty, and the $A_n$ are decreasing. Try to show that $A = \cap_n A_n$, which is also compact and non-empty, satisfies $f[A] = A$.
Another non-constructive way to show this is to consider the poset $\mathcal{P} = \{ A \subset X \mid A, \mbox{closed, non-empty and } f[A] \subset A \}$, ordered under reverse inclusion. Then an upper bound for a chain from $\mathcal{P}$ is the (non-empty) intersection, and a maximal element (by Zorn one exists) is a set $A$ with $f[A] = A$.

A: *

*Here is an example showing that the assumption that $H$ is Hausdorff is needed.

Let $H$ be the set of natural numbers $1,2,3,\ldots$ in the cofinite topology (the topology in which a subset is closed iff it is finite or the whole space).
And consider $f(n)=n+1$.
Here are some facts:
a) The space is $T_1$ (in fact, the minimal $T_1$-space on this set) but not Hausdorff.
b) Every subset, including the whole space, is compact (since the space is not Hausdorff, a compact subset does not have to be closed).
c) $f$ is continuous (the preimage of every closed set, which is either the whole space or a finite subset, is either the whole space or a finite, hence closed, subset).
d) Obviously, there is no subset $A$ such that $f(A)=A$ (the only sets $A$ such that $f(A)\subseteq A$ are inductive sets $H_n=\{n,n+1,n+2,\ldots\}$, but $f(H_n)=H_{n+1}\subsetneq H_n$).

*However, as was mentioned by Une Femme Douce, if $H$ is compact Hausdorff, then for every continuous $f$ there is some $A$ such that $f(A)=A$. This is much easier to prove for a metric space, which seems to be the case after your comments.

Consider $A_0=H$, $A_n=f(A_{n-1})$. This is a monotonically decreasing sequence of compact (as images of compact sets under a continuous function), and hence, closed subsets. Their intersection $A=\cap_n A_n$ is non-empty.
Now, $f(A)=f(\cap_n A_n)\subseteq\cap_n f(A_n)=A$. Vice versa, suppose $z\in A$. Then for every $n$, there is $x_n\in A_n$ such that $f(x_n)=z\in A_{n+1}$. Since the space is compact and metric, it is sequentially compact, and there is a subsequence converging to some point $x$, and $x\in A$ (otherewise it is in some open set $H-A_j$ and no subsequence converges to it). Moreover, since $f$ is continuous and the space is Hausdorff, $f^{-1}(z)$ is closed and every $x_n\in f^{-1}(z)$, hence, $x\in f^{-1}(z)$, i.e. $f(x)=z$ and $z\in f(A)$. Overall, $A\subseteq f(A)$ and $A=f(A)$.

*In the general case, we don't even need the assumption that $f$ is continuous, all we need that $f$ maps compact subsets to compact subsets. But the proof is different.

A: In general, the answer is no. For example, let $H$ be a two-point space and $\omega$ be the function that swaps the two points.


text:
Q: MTLModels within MTLModels? I have a web service that returns a JSON of an object, and within that object there is a list of other objects. How can I get Mantle to create an object for each one of these nested objects, rather than giving me a dictionary for each one of them?

A: This can be done using mtl_JSONDictionaryTransformerWithModelClass: tranformer introduced by Mantle some time ago.
Let's look at the example taken from Mantle project readme itself:
@interface GHIssue : MTLModel <MTLJSONSerializing>

@property (nonatomic, strong, readonly) GHUser *assignee;

@end

@implementation GHIssue

+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    return @{
        @"assignee": @"assignee",
    };
}

+ (NSValueTransformer *)assigneeJSONTransformer {
    return [NSValueTransformer mtl_JSONDictionaryTransformerWithModelClass:[GHUser class]];
}

@end

Assuming GHUser is a subclass of MTLModel conforming to MTLJSONSerializing protocol, everything should work perfectly.
UPDATE: The above solution is now deprecated. The correct method to use now would be
return [MTLJSONAdapter dictionaryTransformerWithModelClass:GHUser.class];

inside the 'assigneeJSONTransformer' method.


text:
Q: Problem After registering a url protocol handler in Node.js I was successfully able to register a custom protocol using npm i protocol-registry. Here is the code for the same :
ProtocolRegistry.register({
            protocol: "mydemoprotocol",
            command: `node ${path.join(__dirname, './app_code.js')} $_URL_`,
            override: true,
            terminal: true,
            script: false,
        }).then(async () => {
            console.log("Registered Successully...");
        });

But when I enter mydemoprotocol:// in the browser, I get the following error :

I am trying to load faceapi models in app_code.js. Here is the code for the same :
await faceapi.nets.ssdMobilenetv1.loadFromDisk('/models')
await faceapi.nets.faceLandmark68Net.loadFromDisk("./models"),
await faceapi.nets.faceRecognitionNet.loadFromDisk("./models"))

All the files required to load the model are present in the same directory as app_code.js. Why am I getting error for the path 'C:\WINDOWS\system32\' when I am trying to run the file from D: Drive.
Any help will be grateful. Thanks.


text:
Q: Add uipickerview stored in object to viewcontroller's view Many people on SO suggest using a uipickerview and a uitextfield to make a dropdown-like interface. I having a pickerview stored in an object. How can I then add this to a viewcontroller's view when the textfield is tapped?

A: Instead of storing the pickerview, store only the datasource in the dropdown class. Make the ViewController the delegate of the dropdown class. When the textfield begins editing, call a delegate method to set the datasource of the pickerview the the viewcontroller to the dropdown
Dropdown Delegate protocol:
protocol DropdownDelegate : class {
    func activateDropdown(dropdown: Dropdown)
}

Dropdown class:
class Dropdown: UITextField, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
    var dataSouce : String = []

    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == self {
            if(dropdownDelegate != nil) {
                dropdownDelegate?.activateDropdown(dropdown: self)
                textField.endEditing(true)
            }
        }
    }
    //rest of delegate methods
 }

ViewController class
class ViewController: UIViewController, DropdownDelegate {
    @IBOutlet weak var pickerView: UIPickerView!

    func activateDropdown(dropdown: Dropdown) {
        self.pickerView.delegate = dropdown
        self.pickerView.dataSource = dropdown
    }

    func deactivateDropdown() {
        changeDropdownStatus(status: true)
        self.pickerView.isHidden = true
    }
}


text:
Q: Where are the downloaded data when an issue happens before installing? I installed some Python packages through the terminal, however after downloading it, I got an error and had to do it again.
It means I downloaded each package twice and now wonder: where are they ? Can I delete the useless downloaded but not installed packages ?
It's an example of a general problem I have with Ubuntu since I started using it.


text:
Q: Entity Framework only saves some fields I have a GridView that pulls data using Entity Framework. The RowUpdating event is giving me a weird problem. Pulling desired data, Inserting, and Deleting works just fine, it's just Updating.
In the method I get the item given the datakey from the GridView:
int dataKey = Convert.ToInt32(gridView.DataKeys[e.RowIndex].Value);
MyEntity ent = context.MyEntities.First(x => x.Key == dataKey;

Then I update the necessary fields and save:
ent.Field1 = "some data";
ent.Field2 = "other data";
ent.ModifiedDate = DateTime.Now;
context.SaveChanges();

While debugging, after context.SaveChanges() I see Field1 and Field2 saved their new values whereas ModifiedDate changed back to what it had before.
The only thing I could think that would cause this is when I look at the table in the .edmx file the ModifiedDate field has "Computed" in StoreGeneratedPattern. However, this is supposed to be just computed initially. For example, a user inserts an item without a ModifiedDate and SQL Server puts getdate() in the field on creation.
USE [MyDB]
GO

ALTER TABLE [dbo].[MyEntities] ADD  CONSTRAINT
DF_MyEntities_ModifiedDate]  DEFAULT (getdate()) FOR [ModifiedDate]
GO

A: the problem was indeed in the StoreGeneratedPattern being computed. If it is set to Computed it overrides whatever the user sets the value as and tries to find the constraint in the DB that will give it it's computed value. The problem lies with a default constraint only fires if nothing is supplied, but the query EF generates for the UPDATE command sends something like ModifiedDate = NULL. So EF says i'll send ModifiedDate = NULL, but it will be overridden once the DB runs this update query. Then the DB says ok I will supply a calculated value for ModifiedDate if the user did not supply one. Oh wait, I see they supplied a ModifiedDate I don't need to run my constraint.