text:
Q: Mutual class instances in C++ What is the issue with this code?
Here we have two files: classA.h and classB.h
classA.h:
#ifndef _class_a_h_
#define _class_a_h_

#include "classB.h"

class B; //????

class A
{
public:
    A() {
        ptr_b = new B(); //????
    }

    virtual ~A() {
        if(ptr_b) delete ptr_b; //????
                    num_a = 0;
    }

    int num_a;
    B* ptr_b; //????
};

#endif //_class_a_h_

classB.h:
#ifndef _class_b_h_
#define _class_b_h_

#include "classA.h"

class A; //????

class B
{
public:
    B() {
        ptr_a = new A(); //????
                    num_b = 0;
    }

    virtual ~B() {
        if(ptr_a) delete ptr_a; //????
    }

    int num_b;
    A* ptr_a; //????
};

#endif //_class_b_h_

when I try to compile it, the compiler (g++) says:

classB.h: In constructor 'B::B()':
classB.h:12: error: invalid use of incomplete type 'struct A'
classB.h:6: error: forward declaration of 'struct A'
classB.h: In destructor 'virtual B::~B()':
classB.h:16: warning: possible problem detected in invocation of delete operator:
classB.h:16: warning: invalid use of incomplete type 'struct A'
classB.h:6: warning: forward declaration of 'struct A'
classB.h:16: note: neither the destructor nor the class-specific operator delete will be
called, even if they are declared when the class is defined.

A: You cannot create instances of an incomplete type (the compiler doesn't know anything about the class!)
You need to move the definitions of your functions (the constructor of A and B) into a C++ file that can include both headers (or into several C++ files, if you follow the convention that you have one class per file).
That having been said, your code as written has a serious problem:  every A creates an instance of B and every B creates and instance of A.  You will end up with an infinite recursion and you will eventually run out of memory.
Two minor nitpicks:  you do not need to test whether a pointer is null before calling delete on it (it is safe to delete a null pointer), and you need to change your include guards (names beginning with an underscore in the global namespace are reserved to the implementation).

A: EDIT: Read James McNellis's answer first -- this is a code example of what you'd have to do. But the recursion is the bigger point and he deserves any upvotes for that particular point -- not me :)
You can't use inline functions here as the full definition for classes A and B is not available when you're declaring them inline. Declare them as normal functions and you'll be fine with the forward declarations you have.
classA.h
#ifndef _class_a_h_
#define _class_a_h_

#include "classB.h"

class B; //????

class A
{
public:
    A();
    virtual ~A();
    int num_a;
    B* ptr_b;
};

#endif //_class_a_h_

classB.h
#ifndef _class_b_h_
#define _class_b_h_

#include "classA.h"

class B
{
public:
    B();
    virtual ~B();
    int num_b;
    A* ptr_a;
};

#endif //_class_b_h_

classes.cpp
#include "classA.h"
#include "classB.h"

A::A() {
    ptr_b = new B(); //????
}

A::~A() {
    if(ptr_b) delete ptr_b; //????
}

B::B() {
    ptr_a = new A; //????
}

B::~B() {
    if(ptr_a) delete ptr_a; //????
}

A:
classB.h: In constructor 'B::B()':
classB.h:12: error: invalid use of
  incomplete type 'struct A'

A is not fully defined. You've only given it a prototype (class A;).

classB.h:6: error: forward declaration
  of 'struct A'
classB.h: In destructor 'virtual
  B::~B()':

I think this is the same problem. It needs to know how A is defined so it knows how much memory to free up.
Refactor your code to remove the circular dependency. (A creates B, and B creates A... creates B, creates A, creates B...)

A: The simple solution is to pull your member function definitions out-of-line and into the files classA.cpp and classB.cpp.  Remove the mutual includes from the header files and instead insert those into the .cpp files.
Anywhere class A or B is used more than just in name (that is, other than just naming its pointer or reference types), a complete class declaration must already be present.  With your current include/inline design, one or the other will necessarily not be complete.  By splitting the class implementations out into .cpp files, you allow the declarations to complete gracefully before instantiating objects of type A or B.


text:
Q: how to implement alfresco custom login component I'm Following This Tutorial On Alfresco's Platforme and I'm Stuck at this point

You would typically connect to the remote authentication mechanism
  to verify username/pwd...
  this link to the tuto : Authentication

A: This means you will authenticate your user from external sources like external database or from any other external rest api call which will give you response and based on that response you need to decide whether user is authenticated or not, if authenticated pass true else false.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get Facebook post id when uploading? I have created a custom desktop app (Adobe AIR) that allows users to upload videos and pictures to their wall. As it turns out, I have to have control of these posts that get created by my app. I've read that everything you post using graph api has a post id:
http://developers.facebook.com/docs/reference/api/post/
I would like to know how can I retrieve this id so I can keep track of certain statistics later with FQL. Does anyone know how this is done?

A: While creating a post or uploading a photo to Facebook, the id of the newly created object is returned by Facebook. What you need to do is to fetch the response of the POST request you sent.
This should help https://developers.facebook.com/blog/post/498/
If you know C#.Net coding i shall provide you sample code for implementing it.
Get back if you need more help.

A: When you press on the timestamp in the head of the post you'll get a page with the post only with it's link in the adress bar, there you can also see the post ID.
That was what I've been looking for, and found out by myself...
Hope it helped you too.


text:
Q: CDF of $\frac{X_1}{X_2X_3a}$, where $X_1$, $X_2$, and $X_3$ have exp. distributions Problem:
Let $X_0$, $X_1$, $X_2$, and $X_3$ be four independent exponential random variables with the PDFs $f_{X_i}(x_i)={1\over \lambda_i} \exp(-\frac{x_i}{\lambda_i})$ where ($i=0,1,2,3$).
Let $X=\frac{X_0}{b}$ and $Y=\frac{X_1}{X_2X_3a}$ (where $a$, $b$ and $x$ are positive constants) and I want to find the:
$$\eqalign{\Pr\left(\min(X,Y)\le x\right) = \Pr(X\le x) + \Pr (Y\le x) - \Pr\left(\max(X,Y)\le x\right).\tag{1}}$$
The above result can be expressed in terms of the marginal distributions (only) when $X$ and $Y$ are independent, for then (1) becomes:
$$\eqalign{\Pr\left(\min(X,Y)\le x\right) &= F_X(x) + F_Y(x) - F_X(x)F_Y(x) \\&= 1 - (1-F_X(x))(1-F_Y(x)).\tag{2}}$$
My attempted Soloution:
$$\eqalign F_X(x)=X\leq x=1-exp(-xb)$$
and
$$\eqalign {F_Y(x) &=Y\leq x \\&=\frac{X_1}{X_2X_3a}\leq x}$$ after conditioning on $X_1$ and then on $X_3$
$$\eqalign {&=\int_0^\infty \frac{z_1}{X_2X_3a} \leq x \quad f_{X_1}(Z_1) \quad dz_1
\\&=\int_0^\infty\int_0^\infty X_2 \geq \frac{z_1}{z_3a} \quad f_{X_1}(Z_1) \quad f_{X_3}(Z_3) \quad dz_1 dz_3 \\
&= \int_0^\infty\int_0^\infty exp(-\frac{z_1}{z_3a\lambda_2x}) \quad f_{X_1}(Z_1) \quad f_{X_3}(Z_3) \quad dz_1 dz_3\\
&=\int_0^\infty \int_0^\infty exp(-\frac{z_1}{z_3a\lambda_2x}) {1\over \lambda_1} \exp( -\frac{z_1}{\lambda_1}) {1\over \lambda_3} \exp(-\frac{z_3}{\lambda_3}) dz_1 dz_3 \\}$$
Since ${1\over \lambda_1}\int_0^\infty exp(-\frac{z_1}{z_3a\lambda_2x}) \exp( -\frac{z_1}{\lambda_1}) dz_1 = \frac{z_3}{z_3+(a\lambda_1 x)}$,
let ${1\over \lambda_3}=k$ and $a\lambda_1 x=c$ then,
$$\eqalign {&={k}\int_0^\infty exp(-{z_3k}) \frac{z_3}{z_3+(c)} dz_3 \\
&=-kc \exp(ck)E_1(ck)+1}$$
where $E_1(ck)$ is the exponential integral function.
Therefore, the $min(X,Y)\leq x = 1 -\Big(exp(-xb) (kc \exp(ck)E_1(ck)\Big)$.
Any comments or pointing out mistakes will be very much appropriated.


text:
Q: Is there a way to link a label and date field when being dynamically added to a form vb.net I'm not sure if what I am doing is possible and if it is, what the best way to go about it is. I have a WinForm dynamically creating controls, depending on the type pre-selected by the user. This includes text boxes, date fields, dropdowns, and others. When a date field is created, I want to add a label that displays the age next to it. With what I have now, I can display the age when the form loads, but I need a solution on how to get the label to update if the date is changed?
I have tried creating a leave handler for the datepicker, but that does not work because it does not have control of each datepicker control, just the last one created.
EDIT:I'm going to share some code that I am using now. This function is calculating the age and creating the label that will go next to the datepicker.
Private Sub getAge()
    If ucDP.Text = "" OrElse ucDP.Text = "  /  /" Then
        Exit Sub
    End If
    Dim currentDate As DateTime = DateTime.Now
    Dim zeroTime As DateTime = New DateTime(1, 1, 1)
    Dim selectedDate As DateTime = New DateTime(Convert.ToDateTime(ucDP.Text).Year, Convert.ToDateTime(ucDP.Text).Month, Convert.ToDateTime(ucDP.Text).Day)
    Dim dateNow As DateTime = New DateTime(currentDate.Year, currentDate.Month, currentDate.Day)
    lblAge = New Label
    If (selectedDate > dateNow) Then
        Exit Sub
    End If
    Dim span As TimeSpan = dateNow - selectedDate
    Dim years As Integer = ((zeroTime + span).Year - 1)
    lblAge.Text = "Age: " & years
    lblAge.Location = New Drawing.Point(ucDP.Location.X + 122, ucDP.Location.Y + 2)
    lblAge.ForeColor = System.Drawing.Color.MidnightBlue
    lblAge.Font = New System.Drawing.Font("Segoe UI", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))

    gb.Controls.Add(lblAge)

End Sub

And I just have the sub executing in the ucDP event handler.
EDIT 2: Adding how I create the datepicker control
ElseIf datatype = "date" Then
            ucDP = New MSCtrlCore.ucDatePicker()
            ucDP.FutureDateEnabled = True
            ucDP.Name = "ucdp" & pkIOCI
            ucDP.Location = New Drawing.Point((gb.Width / 2) + 80, lbl.Location.Y + 3)
            ucDP.Format = "MM/DD/YYYY"
            ucDP.Size = New Drawing.Size(120, 26)
            ucDP.Anchor = AnchorStyles.Top Or AnchorStyles.Left Or AnchorStyles.Right

            sql = String.Format("SELECT Answer FROM OtherCoverageAnswers WHERE ISNULL(IsArchived, 0) = 0 AND fk_InsuredOtherCoverageInfo = {0} AND fk_Insured = {1}", pkIOCI, insuredKey)
            Try
                GetScalar(sql, strValue)
                If strValue = String.Empty OrElse strValue = "0" Then
                    ucDP.Text = ""
                Else
                    ucDP.Text = strValue
                End If
            Catch ex As System.Exception
            End Try
            AddHandler ucDP.Leave, AddressOf ucDP_Leave
            gb.Controls.Add(ucDP)

A: Listen well, because I'm putting waaay too much time in this answer. Ok I love this but still, please don't waste my time and learn at least one thing, even if this is not the answer you're looking for.
We'll do what jimi said and create a custom control, which will keep the operational logic all in one place.
First, right-click on your project and add a new user control:

Name it whatever you want. I'm naming mine AgeDateTimePickerControl:

Now design your new control. It's as easy as designing a form:

You can code properties, events, and this sort of thing into your custom control. I customed mine by copying your age calcul logic (I changed it to a simpler one because this is just an example) and writing it into the ValueChanged event of the DateTimePicker. I also coded 2 properties: Age (read only) and birth date (read and write). I made properties so that later, when I'll use the control inside a form, I'll be able to access them easily.
Here's how the code looks:
Public Class AgeDateTimePickerControl
    Private _age As Integer

    'You can create properties for your custom control to access them from your form later
    Public ReadOnly Property Age() As String
        Get
            Return _age
        End Get
    End Property

    Public Property BirthDate() As DateTime
        Get
            Return DateTimePicker1.Value
        End Get
        Set(value As DateTime)
            DateTimePicker1.Value = value
        End Set
    End Property

    'You can use events just like in a form
    Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
        If (DateTimePicker1.Value < Date.Today) Then
            _age = Date.Today.Year - DateTimePicker1.Value.Year
            Label1.Text = "Age: " & _age
        End If
    End Sub
End Class

Once you're finished with your new tool, save your project and rebuild it (if you don't build your own control, Visual Studio will not let you use it in the form designer).

Now you can drag and drop it from your toolbox. What? You want to add it programmatically? Sure, you can also do that. But look at the toolbox first! You just designed a new control!

Now, to test the business logic of your new control, drag and drop it into your form, compile and try it. The one I just coded was fun but maybe not exactly what you want, so tweak and code until you're satisfied.
Then add it programmatically to your form just as you used to do with the controls you were using before.
Isn't life beautiful?

A: You can keep track of the labels added in a list. Then when the DateTimePicker value changes, you can update each label's text. This allows for multiple labels.
Private ageLabels As New List(Of Label)()

Private Sub getAge()
    If ucDP.Text = "" OrElse ucDP.Text = "  /  /" Then
        Exit Sub
    End If
    Dim currentDate As DateTime = DateTime.Now
    Dim zeroTime As DateTime = New DateTime(1, 1, 1)
    Dim selectedDate As DateTime = New DateTime(Convert.ToDateTime(ucDP.Text).Year, Convert.ToDateTime(ucDP.Text).Month, Convert.ToDateTime(ucDP.Text).Day)
    Dim dateNow As DateTime = New DateTime(currentDate.Year, currentDate.Month, currentDate.Day)
    lblAge = New Label
    If (selectedDate > dateNow) Then
        Exit Sub
    End If
    Dim span As TimeSpan = dateNow - selectedDate
    Dim years As Integer = ((zeroTime + span).Year - 1)
    lblAge.Text = "Age: " & years
    lblAge.Location = New Drawing.Point(ucDP.Location.X + 122, ucDP.Location.Y + 2)
    lblAge.ForeColor = System.Drawing.Color.MidnightBlue
    lblAge.Font = New System.Drawing.Font("Segoe UI", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))

    gb.Controls.Add(lblAge)
    ageLabels.Add(l)

End Sub

Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
    ageLabels.ForEach(Sub(l) l.Text = $"{DateTimePicker1.Value}")
    ' fix logic to show age instead of date :)
End Sub


text:
Q: Registering for UIDeviceOrientation I want to detect the current orientation of the device.
So, I used the a line of code
Note: It gives me orientation even if I have not register it
-(IBAction) deviceOrientationChanged:(id) sender{
    NSLog(@"Device Orientation= %d",[[UIDevice currentDevice] orientation]);
}

When I change the orientation, on a button click event I get the device orientation.
But, the document says you need to register it first, then use the above code.
Note: In the below code I have registered device to receive device orientation notification
-(IBAction) deviceOrientationChanged:(id) sender{

    if(![[UIDevice currentDevice] isGeneratingDeviceOrientationNotifications]){
        //This statement is called very time when I click on the button. I expected to execute only once.
        [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    }
    NSLog(@"Device Orientation= %d",[[UIDevice currentDevice] orientation]);
}

So, I am not able get through the perfect way to get the Device Orientation.

A: I think Your if condition is wrong ;
U have it as
if([[UIDevice currentDevice] isGeneratingDeviceOrientationNotifications])
It should be
if(  !   [[UIDevice currentDevice] isGeneratingDeviceOrientationNotifications])

A: Registering for notifications is different from generating the notifications. Normally if you are planning to use device orientation notifications in the app delegate or in an appropriate place you will make the call beginGeneratingDeviceOrientationNotifications on the UIDevice and will make the endGeneratingDeviceOrientationNotifications in another appropriate place when U no longer need the notifications. This is only the initial setup for deviceOrientaion notification.
To get these notification is in you controllers or object U have to us the Notification Center. U register for the notification UIDeviceOrientationDidChangeNotification.
[[NSNotificationCenter defaultCenter] addObserver:myObject selector:@selector(deviceRotated:)name:UIDeviceOrientationDidChangeNotification object:nil]
and remove it from the notification center when U dont need it or in the dealloc of the object.

A: You can't stop the device from generating UIViewController rotation notifications. See the question here.
What the document you linked to is referring to, are NSNotificationCenter notifications.


text:
Q: Is this correct usage of super in python? class SessionWizardView(WizardView):
    @classonlymethod
    def as_view(cls, *args, **kwargs):
        #...snipped..
        pass

class ParentWizard(SessionWizardView):
    @classonlymethod
    def as_view(cls, *args, **kwargs):
        return super(SessionWizardView, cls).as_view( ... )

class ChildWizard(ParentWizard):
    @classonlymethod
    def as_view(cls, *args, **kwargs):
        return super(SessionWizardView, cls).as_view( ... )

In ChildWizard, is it legal to pass in a grandparent class (SessionWizardView) into the first parameter of super ? pylint is vomiting this error message:

Method should have "self" as first argument
Bad first argument 'SessionWizardView' given to super class

A: The usual usage of super for classmethods is to put cls first and the name of the current class as the second argument:
class SessionWizardView(WizardView):
    @classonlymethod
    def as_view(cls, *args, **kwargs):
        #...snipped..
        pass

class ParentWizard(SessionWizardView):
    @classonlymethod
    def as_view(cls, *args, **kwargs):
        return super(cls, ParentWizard).as_view( ... )

class ChildWizard(ParentWizard):
    @classonlymethod
    def as_view(cls, *args, **kwargs):
        return super(cls, ChildWizard).as_view( ... )

If you build working code that passes tests, I wouldn't worry to much about how pylint reports the naming of the first argument.  pylint knows that a standard Python classmethod will use cls as the first argument, but it doesn't know anything about classonlymethod which has the same pattern.
References:

*

*http://docs.python.org/library/functions.html#super

*http://blogs.gnome.org/jamesh/2005/06/23/overriding-class-methods-in-python/

*http://pylint-messages.wikidot.com/messages:c0202


text:
Q: Protect window.opener from change There is a JavaScript code that opens new page which tries to change the mother-page with the help of window.opener. I need to Protect mother-page from any change. Any advice on how to do it?
Code like this needs to be blocked
window.opener.location.href='http://google.com/';

A: No, you cannot stop executing "window.opener" but what you can do is assign the opener function to a different variable and mock the original one.
window.opener_old = window.opener;
window.opener = function(){};

If some other script tries to execute window.opener, the new empty function is going to be called and nothing will happen.


text:
Q: Button Color does not change back to normal color Im working on an image carrousell with some custom code:

<script>
const project1Btn = document.getElementById("project1Btn");

project1Btn.addEventListener("click", showProject1Info);

function showProject1Info() {
  document.getElementById("imageCarousell1").style.opacity = '50%';
  document.getElementById("imageCarousell1").style.filter = "grayscale(100%)";
  var elements = document.getElementsByClassName('projectBtn'),
    i, len;

  for (i = 0, len = elements.length; i < len; i++) {
    elements[i].style.color = '#F5FF00';
  }

}

document.addEventListener("click", (event) => {
  const isClickInside = project1Btn.contains(event.target);
  if (!isClickInside) {
    document.getElementById("imageCarousell1").style.opacity = '100%';
    document.getElementById("imageCarousell1").style.filter = "grayscale(0%)";

    var elements = document.getElementsByClassName('projectBtn'),
      i, len;

    for (i = 0, len = elements.length; i < len; i++) {
      elements[i].style.color = 'black';
    }

  }
});
</script>

The image opacity and also color changes on Btn Click but if i close the overlay the button color stays in the wrong color and i dont know how to fix that. :(
Live Preview:
https://mauricedill.ch/projects/


text:
Q: Characterizing compactness by properties of continuous functions defined on a space I want to find theorems of the form "all continuous functions defined on a topological space X satisfy some properties if and only if $X$ is compact."
Some restrictions on the space X may be acceptible, such as Hausdorff, metric space, etc. The codomain of the functions could be anything.

From the comments, I found that a metric space is compact if and only if every continuous real function on it is bounded. I would appreciate any other similar theorems.

A: There is no such characterisation that I know of, but there are some known things:
A space $X$ is called pseudocompact iff every continuous $f:X \rightarrow \mathbb{R}$ is bounded.
For normal spaces ($T_1$ plus being able to separate disjoint closed sets) this is equivalent to countable compactness (every countable open cover has a finite subcover) and limit point compactness (every infinite subset has a limit point).
For metric spaces all three are equivalent to compactness and sequential compactness as well (every sequence has a convergent subsequence).
But not in general, as $\omega_1$, the first uncountable ordinal in the order topology or $\Sigma$-Products of uncountably copies of $[0,1]$ show.
These are normal, pseudocompact (and so countably compact etc.) but not compact.
Using mappings of a special kind : $X$ is compact iff for every space $Y$, the projection $\pi_Y: X \times Y \rightarrow Y$ is a closed map.
If we already knwow that $X$ is $T_3$, $X$ is compact iff every embedding $e$ of $X$ into a Hausdorf space $Y$ has a closed image $e[X] \subset Y$. (in general such a space is called H-closed, and H-closed $T_3$ spaces are compact).


text:
Q: Is creating a new list object via multiplication by one with an existing list equivalent to making a deep copy? For example, say I want to make a deep copy of a list a, called b:
a = [1,2,3,4,5]

Is there any difference between:
import copy
b = copy.deepcopy(a)

and:
b = a*1

In both cases I've created a new object (i.e id(a) == id(b) is False), so are there any practical differences I should understand?  Thanks!

A: No, they aren't equivalent.  The multiplication operator makes only a shallow copy. A deep copy means that the references within the list are also copied (that is, new references are created), while a shallow copy only makes a new copy of the top-level reference but not the references within, as demonstrated below:
import copy
a = [[],[]]
b = copy.deepcopy(a)
c = a * 1
for i, v in enumerate(a):
    print(id(v), id(b[i]), id(c[i]))

This outputs:
31231832 31261480 31231832
31260800 31261400 31260800


text:
Q: How to guarantee get() of ConcurrentHashMap to always return the latest actual value? Introduction
Suppose I have a ConcurrentHashMap singleton:
public class RecordsMapSingleton {

    private static final ConcurrentHashMap<String,Record> payments = new ConcurrentHashMap<>();

    public static ConcurrentHashMap<String, Record> getInstance() {
        return payments;
    }

}

Then I have three subsequent requests (all processed by different threads) from different sources.
The first service makes a request, that gets the singleton, creates Record instance, generates unique ID and places it into Map, then sends this ID to another service.
Then the second service makes another request, with that ID. It gets the singleton, finds Record instance and modifies it.
Finally (probably after half an hour) the second service makes another request, in order to modify Record further.

Problem
In some really rare cases, I'm experiencing heisenbug. In logs I can see, that first request successfully placed Record into Map, second request found it by ID and modified it, and then third request tried to find Record by ID, but found nothing (get() returned null).
The single thing that I found about ConcurrentHashMap guarantees, is:

Actions in a thread prior to placing an object into any concurrent
  collection happen-before actions subsequent to the access or removal
  of that element from the collection in another thread.

from here. If I got it right, it literally means, that get() could return any value that actually was sometime into Map, as far as it doesn't ruin happens-before relationship between actions in different threads.
In my case it applies like this: if third request doesn't care about what happened during processing of first and second, then it could read null from Map.

It doesn't suit me, because I really need to get from Map the latest actual Record.
What have I tried
So I started to think, how to form happens-before relationship between subsequent Map modifications; and came with idea. JLS says (in 17.4.4) that:

A write to a volatile variable v (§8.3.1.4) synchronizes-with all
  subsequent reads of v by any thread (where "subsequent" is defined
  according to the synchronization order).

So, let's suppose, I'll modify my singleton like this:
public class RecordsMapSingleton {

    private static final ConcurrentHashMap<String,Record> payments = new ConcurrentHashMap<>();
    private static volatile long revision = 0;

    public static ConcurrentHashMap<String, Record> getInstance() {
        return payments;
    }

    public static void incrementRevision() {
        revision++;
    }
    public static long getRevision() {
        return revision;
    }

}

Then, after each modification of Map or Record inside, I'll call incrementRevision() and before any read from Map I'll call getRevision().
Question
Due to nature of heisenbugs no amount of tests is enough to tell that this solution is correct. And I'm not an expert in concurrency, so couldn't verify it formally.
Can someone approve, that following this approach guarantees that I'm always going to get the latest actual value from ConcurrentHashMap? If this approach is incorrect or appears to be inefficient, could you recommend me something else?

A: You approach will not work as you are actually repeating the same mistake again. As ConcurrentHashMap.put and ConcurrentHashMap.get will create a happens before relationship but no time ordering guaranty, exactly the same applies to your reads and writes to the volatile variable. They form a happens before relationship but no time ordering guaranty, if one thread happens to call get before the other performed put, the same applies to the volatile read that will happen before the volatile write then. Besides that, you are adding another error as applying the ++ operator to a volatile variable is not atomic.
The guarantees made for volatile variables are not stronger than these made for a ConcurrentHashMap. It's documentation explicitly states:

Retrievals reflect the results of the most recently completed update operations holding upon their onset.

The JLS states that external actions are inter-thread actions regarding the program order:

An inter-thread action is an action performed by one thread that can be detected or directly influenced by another thread. There are several kinds of inter-thread action that a program may perform:
…

*

*External Actions. An external action is an action that may be observable outside of an execution, and has a result based on an environment external to the execution.

Simply said, if one thread puts into a ConcurrentHashMap and sends a message to an external entity and a second thread gets from the same ConcurrentHashMap after receiving a message from an external entity depending on the previously sent message, there can't be a memory visibility issue.
It might be the case that these action aren't programmed that way or that the external entity doesn't have the assumed dependency, but it might be the case that the error lies in a completely different area but we can't tell as you didn't post the relevant code, e.g. the key doesn't match or the printing code is wrong. But whatever it is, it won't be fixed by the volatile variable.


text:
Q: Wordpress inline php does not work I have a little question why my inline php code doesn't work:
If I wrote my code like this: which is very ugly btw(IMO), it works great.
<?php
$cat = get_terms('logietype');
?>

        <?php

        foreach ($cat as $catVal) {
            echo "
";
            echo "
".$catVal->name."
";
            $postArg = array('post_type'=>'logie','posts_per_page'=>-1,'order'=>'desc',
                              'tax_query' => array(
                                                    array(
                                                        'taxonomy' => 'logietype',
                                                        'field' => 'term_id',
                                                        'terms' => $catVal->term_id
                                                    )
                            ));

            $getPost = new wp_query($postArg);
            global $post;

            if($getPost->have_posts()){

                    while ( $getPost->have_posts()):$getPost->the_post();
                        echo "
";
                        echo "
".$post->post_title."
";
                        echo "
".$post->post_content."
";
                        echo "
";
                    endwhile;

            }
            echo '
';
        }
    ?>

But when I try this: which is much cleaner(IMO), nothing works :(
<?php
$cat = get_terms('logietype');
?>

        <?php foreach ($cat as $catVal): ?>

<?php $catVal->name ?>

            <?php $postArg = array('post_type'=>'logie','posts_per_page'=>-1,'order'=>'desc',
                              'tax_query' => array(
                                                    array(
                                                        'taxonomy' => 'logietype',
                                                        'field' => 'term_id',
                                                        'terms' => $catVal->term_id
                                                    )
                            ));

            $getPost = new wp_query($postArg);
            global $post; ?>

            <?php if($getPost->have_posts()): ?>

                    <?php while ( $getPost->have_posts()):$getPost->the_post(): ?>

<?php $post->post_title ?>

<?php $post->post_content ?>

                    <?php endwhile; ?>

            <?php endif; ?>

        <?php endforeach; ?>

Anyone has any idea why the one works and the other doesn't?
Many thanks in advance!

A: The error is because of the following line:
 <?php while ( $getPost->have_posts()):$getPost->the_post(): ?>
                                                           ^ see this colon here

It should be,
 <?php while ( $getPost->have_posts()):$getPost->the_post(); ?>

A: I think you Should put semicolon after, like this:
<?php $catVal->name; ?>

<?php $post->post_title; ?>

<?php $post->post_content; ?>


text:
Q: hashCode implementation in Java String Just curious, in String's hashCode implementation what is the reason behind extra references creation in a hashCode implementation (v 1.8.0_65):
public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

Taking into consideration that value is final and created in constructor only (i.e. threadsafe) why do we need variable val[] reference here?
I.e. will this work:
public int hashCode() {
    if (hash == 0 && value.length > 0) {
        int h = 0;
        for (int i = 0; i < value.length; i++) {
            h = 31 * h + value[i];
        }
        hash = h;
    }
    return hash;
}

?
In addition to copying values from heap to stack to speed things up it is also about race conditions described in comments by @zapl. Which was not obvious to me before his comment.

A: It seems like the intent is to put hash and the value handle explicitly on the stack


text:
Q: select data which will start displaying in 48 hours from now Find all the articles which will start displaying in 48 hours from now
I need to get data which will display in next 48 hours only.
MySql Query
SELECT * from articles WHERE articles.start_date > CURDATE() + INTERVAL 48 HOUR

Today is 2015-04-15 and i am Getting result wrong. I have 2015-04-17 in database but not showing. I only need to get 2015-04-17 not all others.

A: You only need to get 2015-04-17, why don't you try to use equal.
Try This :
SELECT * from articles WHERE articles.start_date = CURDATE() + INTERVAL 48 HOUR

A: you need to use >= INTERVAL 2 day  and <= INTERVAL 2 day
try this
SELECT * FROM articles WHERE articles.start_date >= CURDATE() + INTERVAL 2 day AND articles.start_date <= CURDATE() + INTERVAL 2 day;

A: try this
SELECT * from articles WHERE articles.start_date >= CURDATE() + INTERVAL 48 HOUR and articles.start_date <= CURDATE() + INTERVAL 2 day;


text:
Q: Removing scanner selection from Windows' scan window I'm having an issue with scanner services showing up. I recently reinstalled Photoshop, but it seems that the old "scanner service" stayed.
Assistance in removing this will be appreciated.
Screenshot:


text:
Q: Streamreader doesn't find the file on some computers I have made a application in c# wpf .Net 4.5 that is using a c# library dll
assembled in .net 4.0. This dll uses a file that must be in the exe directory.
On all my computers my application works, but when I send this application to some other computers the application will throw my exceptions that is telling me that the dll I am using is not finding the file. I have decompiled the dll and checked out the code but it doesn't change the working directory at any point, However it uses it.
I suspect that this have something to do with the language of the computers but im not sure.
I have set the Directory.SetCurrentDirectory(...) to my exe path in alot of diffrent ways without success.
Does anyone have any clue how to solve this?
Edit: The full auctual error doesnt tell me the path Streamreader looked for the file.
I have used Clickonce deployment but for now I copy the binary folder and I guarantee that the file is in the correct spot.

A: As i suspected this had something to do with the language of the windows.
This line fixed the problems, but it would be nice if someone explained why.
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;


text:
Q: Why do some processors have unofficial codes and/or bugs? Lately I am writing (or trying) an emulator for the 6502 NES CPU.
I am learning many many things, some of them really surprise me and I was wondering what's the explanation for those, in particular, two things came to my mind

*

*The existence of bugs, in particular the 6502 seems to have a bug in the indirect addressing mode, at least for the first processors (it affects the one used in the NES)

*Unofficial operation codes: Again, really surprising that there are codes not official yet usable, some of them seem to be totally useless (like DOP and TOP which are variations of NOP), and some of them seem to be composition of other operation codes (such SAX or DCP).

The question is, how is it possible that when manufacturing millions of those CPUs, they ended up with bugs (such the indirect addressing mode) and also, why on earth would you as a manufacturer include unofficial operation codes that may be removed in following revisions? Does this happen also with newer CPUs?

A:
The question is, how is it possible that when manufacturing millions
  of those CPUs, they ended up with bugs (such the indirect addressing
  mode) and also, why on earth would you as a manufacturer include
  unofficial operation codes that may be removed in following revisions?

Why are CPUs any different than software? Companies spend millions of dollars on software development, manufacturing and marketing. Why then would a flawed product get loose?
I mean Apple is a major computer and data company right? How then can one explain how such a big company would—for example—release the iPhone 4 with bad antenna issues? Or heck, release a few seconds of white noise as a Taylor Swift song in Canada?
Your presumption is because a company is big and has checks & balances that those checks and balances should then be flawless. Which is simply not the case in any human endeavor no matter how many layers of quality assurance one has.
In the case of unofficial operation codes, it can easily be explained by rushed development or code being readied for future development. If a new CPU is made, the engineers will most likely have a massive list of desired features. Some will be made. Some will not. And some will be made yet would be impractical to officially stamp as "Yes this is working, uses this."
This is the reason—for example—why pretty much every CPU out there has revisions. And why in the multi-CPU systems—ones with multiple physical CPUs—it is often important that all CPUs match the same production batch.

A:
how is it possible that when manufacturing millions of those CPUs, they ended up with bugs

*

*It's really, really hard to design CPUs let alone CPUs that are totally bug-less.

*Often subtle bugs are only discovered in the real-world once a product is released, because there is no way you can test to the scale and breadth that millions of end-users can.

*Competition plays a huge part. Getting to the market first, or at least in a timely fashion, is important otherwise you loose business to competitors and eventually go out of business. That pressure versus the pressure to create quality is why you often get something that is only good enough.

*For some reason, in the IT world especially, the demand for new and improved massively outweighs the demand for updated and refined. It's your fault as much as mine. For example, if Intel continuously refined the 80486 CPU I suppose it would be exceptionally close to bug-free by now. But what could you do with an 80486 these days, really? I certainly wouldn't be buying one today, nor would you.

why on earth would you as a manufacturer include unofficial operation codes that may be removed in following revisions?

Unofficial op-codes exist for a variety of reasons:

*

*Some are found to have bugs or side-effects at a point during development where it would be too expensive and/or time-consuming to fix or remove.

*Some are the result of time constraints where they could not be tested thoroughly enough and there isn't enough certainly that they will work correctly.

*Some are put in place as a proof-of-concept or prototype for the future and might see adoption in later CPU revisions/generations.

*Some exist for internal testing purposes only.

*And no doubt some are put in there just for fun, aka Easter Eggs


text:
Q: Prevent to use systemctl poweroff and systemctl reboot for non-root users in CentOS I have CentOS 7 server and there is one non-root level user named user1. That user1 only has the permissions to start, stop, enable and disable for Zabbix Services (allow these service in sudoers file).
But that user1 can use 'systemctl poweroff' and 'systemctl reboot' without sudo. I would like to prevent it. How can I prevent usage of systemctl poweroff/reboot on user1?


text:
Q: Apply dynamic list of templates to an argument I need apply a variable sequence of templates to an argument. The template secuence is determined in runtime in the controller layer, and these templates are applied to only one argument like:
arg:tpl1():tpl2():...:tplN()

In resume, I need apply a serie of templates to an argument, but this sequence calculated in runtime and in the controller layer.
Thank you!!

A: You need to iterate over the template name and the parameter lists at the same time. From the documentation, http://www.antlr.org/wiki/display/ST4/Templates, you will find this example:
<names,phones:{ n,p | <n>: <p>}>

In your case, you need something like
<names,values:{ n,v | <(n)(v)>}>

Oh, per your comment, to apply a list of templates to another list requires a nested map-apply I think.
<values:{v | <names:{n | <(n)(v)>}}>

That applies each template named in names to each value in values.


text:
Q: Inconsistent results of wave objects in R I'm trying to test out how well R can handle audio analyses using tuneR, but I've been having some trouble.
When I try to get R to play back an mp3 I've stored on my computer using this code
holiday=readMP3("C:\\Users\\User1\\Downloads\\holiday_music.mp3")
play(holiday)

I received 3 different results depending on the mp3 I used.
1. R starts playing this cacaphonous sound that I can't decipher that cannot be stopped
2. R returns this error message
"Windows Media Player cannot play the file. The Player might not support the file type or a required codec might not be installed on your computer."
 3. R actually plays the mp3
 Any ideas for this discrepancy in playback between different mp3s?


text:
Q: Parsing data in json using java I have to parse the following data
{"ResultSet":{"Query":"microsec fin","Result":
[{"symbol":"MICROSE_a.NS","name": "MICROSEC FIN SERV LTD ","exch": "NSI","type": "S","exchDisp":"NSE","typeDisp":"Equity"},
   {"symbol":"MICROSEC.NS","name": "Microsec Fin Serv Ltd","exch": "NSI","type": "S","exchDisp":"NSE","typeDisp":"Equity"}]}}

The code i am using is
JSONObject json = (JSONObject) JSONSerializer.toJSON(inputLine);
symbol=json.getJSONObject("ResultSet").getJSONArray("Result").getJSONObject(0).getString("symbol");

which returns MICROSE_a.NS. What i want to do is if there is an undersore in symbol then i want the next symbol to be taken. That is now i want symbol to actually hold MICROSEC.NS. How do i do this.

A: Or which is much simpler with your library:
JSONArray Result= json.getJSONObject("ResultSet").getJSONArray("Result");
for(int i = 0; i<Result.length(); i++){
    String symbol = Result.getJSONObject(i).getString("Symbol");
    if(!symbol.contains("_"))
          return symbol;
}


text:
Q: Segmentation fault on insertion of more than one elements in the linked list in a sorted order I tried to do an insertion sort in a linked list. When only one element is inserted(i.e the first one),it executes well and fine but for multiple elements it gives segmentation fault. Can anyone tell me where the problem is?
#include <iostream>
using namespace std;

struct node
{
    int data;
    node* next;
} *head = NULL;

node* createNode(int x)
{
    node *temp = new node;
    temp->data = x;
    temp->next = NULL;
    return temp;
}

void insertSort(int x)
{
    if(head==NULL)
    {
        node  *temp = createNode(x);
        head = temp;
        return;
    }

    node *temp = createNode(x);
    node *prev = NULL;
    node *curr = head;
    bool inserted = false;

    while(curr != NULL || !inserted)
    {
        if(temp->data < head->data)
        {
            temp->next = head;
            head = temp;
            inserted = true;
        }

        else
        {
        if(temp->data < curr->data)
            {
                prev->next = temp;
                temp->next = curr;
                inserted = true;
             }
            else
            {
                prev = curr;
                curr = curr->next;
            }
        }

    }

    if(!inserted)
    {
    prev->next = temp;
    }

}

void display()
{
    node *p = head;
    while(p != NULL)
    {
        cout<<p->data<<" ";
        p = p->next;
    }

}

A: For starters the function insertSort has redundant code
if(head==NULL)
{
    node  *temp = createNode(x);
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    head = temp;
    return;
}
node *temp = createNode(x);
^^^^^^^^^^^^^^^^^^^^^^^^^^^

Secondly the condition in the while statement
while(curr != NULL || !inserted)

is incorrect. There must be
while(curr != NULL && !inserted)

In any case the function is too complicated. It can be written simpler.
Here is a demonstrative program that shows how the function can be implemented.
#include <iostream>
#include <cstdlib>
#include <ctime>

struct node
{
    int data;
    node* next;
} *head = nullptr;

node* createNode(int x)
{
    return new node { x, nullptr };
}

std::ostream &  display( std::ostream &os = std::cout )
{
    for ( node *current = head; current != nullptr; current = current->next )
    {
        os << current->data << " - > ";
    }

    return os << "NULL";
}

void insertSort( int x )
{
    node *new_node = createNode( x );

    node **current = &head;

    while ( *current != NULL && not ( x < ( *current )->data ) )
    {
        current = &( *current )->next;
    }

    new_node->next = *current;
    *current = new_node;
}

int main()
{
    const int N = 10;

    std::srand( ( unsigned int )std::time( nullptr ) );

    for ( int i = 0; i < N; i++ ) insertSort( std::rand() % N );

    display() << '\n';

    return 0;
}

The program output might look like
1 - > 2 - > 2 - > 3 - > 3 - > 3 - > 3 - > 8 - > 9 - > 9 - > NULL


text:
Q: What is causing a circular reference when plotting a map using ArcGIS API for Python? Following the documentation for the ArcGIS API for Python, I'm attempting to plot coordinates from a spatially enabled dataframe. Perhaps my understanding of a circular reference is off, but I can't see how the object would be referencing itself.
import pandas as pd
from arcgis.gis import GIS
## importing geocoded data from pickle
prop_sdf = pd.read_pickle("./recent_geocoded.pkl")
prop_sdf = pd.DataFrame.spatial.from_xy(prop_sdf, 'lat','long')
prop_sdf.head()

This is what my resulting dataframe looks like:
    unique_id        lat       long
0   43432884  41.701011 -70.019244
2   43400770  41.641784 -70.366659
3   43425636  41.701954 -70.146602
4   43427274  41.720506 -70.021849
5   43427818  41.649288 -70.490767

I'm able to render the interactive map
m1 = GIS().map("United States")
m1.zoom = 4
m1.center = [39,-98]

But hit an error when plotting:
prop_sdf.spatial.plot(map_widget=m1)
m1

Trace:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-30-d48a9f223ff4> in <module>
----> 1 prop_sdf.spatial.plot(map_widget=m1)
      2 m1

~\anaconda3\lib\site-packages\arcgis\features\geo\_accessor.py in plot(self, map_widget, **kwargs)
   2002             self._data.columns = [c.replace(" ", "_") for c in self._data.columns]
   2003             # plot and be merry
-> 2004             _plot_map_widget(map_widget)
   2005             self._data.columns = orig_col
   2006             return True

~\anaconda3\lib\site-packages\arcgis\features\geo\_accessor.py in _plot_map_widget(mp_wdgt)
   1984                  colors=kwargs.pop('cmap', None) or kwargs.pop('colors', None) or kwargs.pop('pallette', 'jet'),
   1985                  alpha=kwargs.pop('alpha', 1),
-> 1986                  **kwargs)
   1987
   1988         # small helper to address zoom level

~\anaconda3\lib\site-packages\arcgis\features\geo\_viz\mapping.py in plot(df, map_widget, name, renderer_type, symbol_type, symbol_style, col, colors, alpha, **kwargs)
    191         fc.layer['layerDefinition']['drawingInfo']['renderer'] = renderer
    192         if map_exists:
--> 193             map_widget.add_layer(fc, options={'title':name})
    194         else:
    195             map_widget.add_layer(fc, options={'title':name})

~\anaconda3\lib\site-packages\arcgis\widgets\_mapview\_mapview.py in add_layer(self, item, options)
   1051              _is_geoenabled(item):
   1052             item = item.spatial.to_feature_collection()
-> 1053         self._add_layer_to_widget(item, options)
   1054
   1055     def _add_layer_to_webmap(self, item, options):

~\anaconda3\lib\site-packages\arcgis\widgets\_mapview\_mapview.py in _add_layer_to_widget(self, item, options)
   1091             # (i.e., do what was done for ImageryLayer for all major Layers)
   1092             # 'No type' layer just means that we'll figure it out at JS time
-> 1093             _lyr = _make_jsonable_dict(item._lyr_json)
   1094             if ('type' in _lyr and \
   1095                 _lyr['type'] == 'MapImageLayer') and \

~\anaconda3\lib\site-packages\arcgis\widgets\_mapview\_mapview.py in _make_jsonable_dict(obj)
     60         will later be used to delete all values with this value"""
     61         return flag
---> 62     dict_ = json.loads(json.dumps(obj, default=default_func))
     63     return { k:v for k, v in dict_.items() if v != flag }
     64

~\anaconda3\lib\json\__init__.py in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys, **kw)
    236         check_circular=check_circular, allow_nan=allow_nan, indent=indent,
    237         separators=separators, default=default, sort_keys=sort_keys,
--> 238         **kw).encode(obj)
    239
    240

~\anaconda3\lib\json\encoder.py in encode(self, o)
    197         # exceptions aren't as detailed.  The list call should be roughly
    198         # equivalent to the PySequence_Fast that ''.join() would do.
--> 199         chunks = self.iterencode(o, _one_shot=True)
    200         if not isinstance(chunks, (list, tuple)):
    201             chunks = list(chunks)

~\anaconda3\lib\json\encoder.py in iterencode(self, o, _one_shot)
    255                 self.key_separator, self.item_separator, self.sort_keys,
    256                 self.skipkeys, _one_shot)
--> 257         return _iterencode(o, 0)
    258
    259 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,

ValueError: Circular reference detected


text:
Q: NextJS - Is there a use for getStaticProps in a CRUD app? Simple question. I've been playing around to try to understand well the implication use of NextJS's different ways of data fetching.
In production mode, Static Site Generation is run at build time, meaning, we would always get the same data cached... right?
In a CRUD app, where interacting with the DB comes quite often, is there any use then for using getStaticProps? I've tried playing around with their revalidate property, but it really doesn't make the data as updated and readily available as I would like.
I'm just curious to know the implication of getStaticProps instead of getserverSideProps then. Besides showing a blog with fixed data. Even then, after creating a new post, we will need to fetch the new data, for which we should probably use getserverSideProps again.
PS: For instance, I noticed accessing my main page with all the data listed takes way more time with getServerSideProps than with getStaticProps. I'd like to know if there could be a blend of both to have the pre-fetch done fast, then when heading back to the page, the data can be updated then.

A: It really depends on your use case. Blogs are a great candidate for SSR, as well as forums, social media posts, e-commerce sites, etc. You can set your revalidate timer as low as 1 second if you like. But you wont see the updated page until the next refresh. The first refresh will show the stale content.
If this is unacceptable for your use case then getServerSideProps() is your solution.
If you're planning on starting a new project, I highly recommend you check out NextJS 13's new /app directory, which replaces /pages. It's a completely new way of doing data fetching and puts server rendering first.
Also, NextJS automatically does pre-fetching when you use next/link to link to other pages.

A: getStaticProps is used for caching. all the pages are built at built time. if you run next build and check your .next folder you see that all the html files are already built and when the user sends a request, instead of fecthing and building html upon the request, your page will serve from pre-generated pages. Imagine in a blog app, every time users from different part of the world want to read a blog, your server will fetch data, parse the data and generate HTML for all of those requests. this does not make sense. when you set the revalidate option your page for specific blog will be newly generated and will be replaced with the old html file. do not think using getStaticProps for only blog pages. your about page, contact page can also be pre-generated with getStaticProps and this will be very helpful for big ecommerce websites.
getServerSideProps is used when you need to read the request object. maybe checking cookies or headers. or maybe you need to make an api request to an external api. you cannot regenerate those pages. this function runs for every incoming request


text:
Q: Show $\text{Gal}(K_\infty/\mathbb Q)\cong \mathbb Z_p^{\times}$ Let $\zeta_{p^n}$ be the primitive $p^n$-th root of unity where $p$ is a prime and $K_n=\mathbb Q(\zeta_{p^n})$ the $p^n$-th cyclotomic field. Let $K_\infty=\bigcup K_n$.
Could someone give a proof of the isomorphism $\text{Gal}(K_\infty/\mathbb Q)\cong \mathbb Z_p^{\times}$?
Many thanks in advance.


text:
Q: Doesn't Codeigniter have folders like assets and layout I am new to CI. I am using version 2. I noticed like other frameworks CI didn't have folders like assets and layout. Where do i place files like css and js and images. Also where is the layout folder.

A: You can place your assets directory wherever you desire, putting it under the root CodeIgniter directory is usually the norm.
CodeIgniter has no reason to include an assets directory as that's usually a front-end requirement, of which CI isn't made for (it's a back end MVC framework).

A: a simple answer is no. CI don't have that. You need to manually create.
And if you are coming from Yii, Ci doesn't implement that feature of Layout.
EDIT
by default, CI doesn't have. You can tweak it but easier implementation is
$this->load->view('header', $param1);
$this->load->view('content', $param2);
$this->load->view('footer', $param3);

where param1, param2, .... are variables you want to pass it to view.
CI will add the views in that order.
and remember, don't put .php while at the end of the filename in view().

A: No
Is the simple answer, you have to extend CIs functionality and use a library from a third party to provide these features for you. CI doesn't focus on the aesthetics of the "front-end". Its primary focus was "back-end".
Your Options:
look into Phil Sturgeons template library, and CI Sprinkles library first is for layout/theme/partials management, second is for asset management js/css minification and caching.
Phil's Template Library: http://philsturgeon.co.uk/demos/codeigniter-template/user_guide/
Sprinkles Library: https://github.com/edmundask/Sprinkle
Or build your own basic template library
This is a great intro video how to do such. I have used this in the past, before i got into using Sparks.
http://www.youtube.com/watch?v=gvGymDhY49E
you can use Sparks to make lib management a bit easier
In 2.1 sparks aren't included however it is in the dev builds of CI so im sure at a later date it will be merged in with the base code. FOr now you can use this site to install Sparks to help you manage third party libraries.
http://getsparks.org

A: You don't have to use a template library.
You don't have to programmatically serve the CSS and JS it can just be part of a view file.
But, you can if you want to!  CI is incredibly flexible.  We've written our own template library that works great for us (we'll release it soon, just checking that it works how we want it to...) but it might not suit the way you work.

A: Try using this PHP layout manager library, can be integrated with codeigniter easily:
https://github.com/mahadazad/php-layout-manager
its easy to setup and use.

A: look for assets helper to load css and js file anywhere..
Simple assets helper for codeigniter


text:
Q: Nlog: How to output Nested Diagnostics Context value to a log file? I can't find an example on how do I modify my config file so that I can output the string passed to Nested Diagnostics Context.
Here is the C# code:
using (NLog.NestedDiagnosticsContext.Push(DateTime.Now.Ticks.ToString()))
{
//some logging
}

and this is the nLog entry in web.config (not sure how to modify this):
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <!-- make sure to set 'Copy To Output Directory' option for this file -->
    <targets>
      <target name="logfile" xsi:type="File" fileName="somepath\\logfile.txt" />
    </targets>

    <rules>
      <logger name="*" minlevel="Debug" writeTo="logfile" />
    </rules>
  </nlog>

A: Just figured it out. Found an exmaple for MDC. Just  tweaked it a bit for NDC. Here's the updated config:
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

      <variable name="mycontext" value="${ndc:item=mycontext} -  ${longdate} -  ${message} "/>
      <targets>
        <target name="logfile" xsi:type="File" fileName="somepath\\logfile.txt" layout="${mycontext}"/>
    </targets>

    <rules>
      <logger name="*" minlevel="Debug" writeTo="logfile" />
    </rules>
  </nlog>


text:
Q: "Invalid memory access" when calling Delphi DLL from Java We have a DLL, written in Delphi, being called by a Java app. Initially we had issues when using PChar or ShortString but we changed these to PAnsiChar and all our issues seemed to have been solved.
However, when we started deploying the DLL to our clients, about 50% of the installations get the following error: Invalid memory access.
The very first line in the DLL is to write to our log file but that is not happening which indicated there is a problem between the Delphi and Java datatypes. Does anybody have any ideas as to what Delphi and Java data types work well together?
Delphi DLL code:
function HasCOMConnection(COMServerName: PAnsiChar): Boolean; stdcall;
begin
  WriteLog('HasCOMConnection: DLL entered');
  Result := HasConnection(COMServerName);
end;

exports
  HasCOMConnection;

Calling from Java:
    private interface IPMOProcessLabResult extends com.sun.jna.Library {
        boolean HasCOMConnection(String COMServerName);
    }

    private boolean canConnectToCOMServer() {
        try {
            IPMOProcessLabResult lib = (IPMOProcessLabResult) Native.loadLibrary(config.libraryName, IPMOProcessLabResult.class);
            return lib.HasCOMConnection(config.comServerName);
        }
        catch (Exception ex) {
            new AppendLog(new Date(), this.getClass() + "\t" + ex.getClass() + "\t" + "Exception while trying to connect to COMServer: " + ex.getMessage(), "debug");
            return false;
        }
    }

A: Per the Java JNA documentation, a Java String is converted to a const char* when passed to native code:

Java Strings perform the same function as the native types const char* and const wchar_t* (NUL-terminated arrays). In order to use the proper type when calling a native function, we have to introduce some sort of annotation to identify how the java Stringshould be converted. Java Strings are normally converted to char* since this is the most common usage of strings. Strings are automatically converted to a NUL-terminated array of characross the function call. Returned char* values are automatically copied into a String if the method signature returns String (strdup, for example).

So the use of PAnsiChar on the Delphi side is correct when passing a String as-is.
However, Delphi strings in Delphi 2009+ are natively encoded in UTF-16, same as Java strings.  So, it would be more efficient (or at least, no risk of data loss) to use WString on the Java side:

The WString class is used to identify wide character strings. Unicode values are copied directly from the Java char array to a native wchar_t array.

And use PWideChar on the Delphi side to match, eg:
function HasCOMConnection(COMServerName: PWideChar): Boolean; stdcall;

private interface IPMOProcessLabResult extends com.sun.jna.Library {
    boolean HasCOMConnection(WString COMServerName);
}

That being said, there are 2 other problems with your code.
Per the same JNA documentation, a Java boolean maps to a native int, not a bool, so your Delphi code needs to use Integer (or Int32) or better LongBool, eg:
function HasCOMConnection(COMServerName: PAnsiChar{or PWideChar}): LongBool; stdcall;

More importantly, if a native library uses the stdcall calling convention, you have to extend IPMOProcessLabResult from com.sun.jna.win32.StdCallLibrary, eg:
private interface IPMOProcessLabResult extends com.sun.jna.StdCallLibrary

Otherwise, if you extend from com.sun.jna.Library then you need to use cdecl on the native side:
function HasCOMConnection(COMServerName: PAnsiChar{or PWideChar}): LongBool; cdecl;


text:
Q: Validating textbox content on blur by calling server-side method without affecting page behaviour I have a textbox in one grid-view column where upon entering a particular value and losing focus of the textbox, should post to the server to get the text validated through a server-side method. If the entry is valid, a result set to fill rest of row cells would be returned, else the bgcolor of the textbox needs to be changed to Red.
I tried posting back through the obvious way, i.e. making the textbox's autopostback as true and wiring up a server-side OnTextChanged event handler to validate the entered value.
It is working with this setup, but is also affecting the remaining page controls behaviour. For example, if I click a button in some other grid after entering some text in the textbox, the OnTextChanged handler gets called thus preventing the button's click event, which I also wish to call to execute its functionality.
Kindly suggest what alternatives/corrections I should carry out to enable textbox content server-side validation plus making the other controls/updatepanels work as expected.

A: Me dumb. I tried everything from creating PageMethods, UpdatePanels to jQuery as hinted in lincolnk's reply. But the thing which finally worked was removing the Autopostback attribute from the textbox control.
After removing it the OnTextChanged event executed each time any server postback was initiated after changing the text. Thereby, executing both the OnTextChanged method and the other control's method. :)

A: I can think of a couple general approaches.

*

*Create a web service with your validation routine and manually make the call (jQuery or whatever) when the text changes. Manually update the client display when you get a result.

*Convert your gridview column to a templated field. Add a CustomValidator and wrap the textbox and validator in an UpdatePanel. Set the textbox to auto-postback and the UpdatePanel to conditional update so only the one you are using is refreshed.
Option 1 is kind of an end-around the typical asp.net process, and you would still want to validate everything on the server-side when the page is posted back.
Option 2 might have performance issues, since you're hitting the page again every time you do a validation.


text:
Q: C# Point in polygon I'm trying to determine if a point is inside a polygon. the Polygon is defined by an array of Point objects. I can easily figure out if the point is inside the bounded box of the polygon, but I'm not sure how to tell if it's inside the actual polygon or not. If possible, I'd like to only use C# and WinForms. I'd rather not call on OpenGL or something to do this simple task.
Here's the code I have so far:
private void CalculateOuterBounds()
{
    //m_aptVertices is a Point[] which holds the vertices of the polygon.
    // and X/Y min/max are just ints
    Xmin = Xmax = m_aptVertices[0].X;
    Ymin = Ymax = m_aptVertices[0].Y;

    foreach(Point pt in m_aptVertices)
    {
        if(Xmin > pt.X)
            Xmin = pt.X;

        if(Xmax < pt.X)
            Xmax = pt.X;

        if(Ymin > pt.Y)
            Ymin = pt.Y;

        if(Ymax < pt.Y)
            Ymax = pt.Y;
    }
}

public bool Contains(Point pt)
{
    bool bContains = true; //obviously wrong at the moment :)

    if(pt.X < Xmin || pt.X > Xmax || pt.Y < Ymin || pt.Y > Ymax)
        bContains = false;
    else
    {
        //figure out if the point is in the polygon
    }

    return bContains;
}

A: You can use the ray casting algorithm. It is well-described in the wikipedia page for the Point in polygon problem.
It's as simple as counting the number of times a ray from outside to that point touches the polygon boundaries. If it touches an even number of times, the point is outside the polygon. If it touches an odd number of times, the point is inside.
To count the number of times the ray touches, you check intersections between the ray and all of the polygon sides.

A: My answer is taken from here:Link
I took the C code and converted it to C# and made it work
static bool pnpoly(PointD[] poly, PointD pnt )
    {
        int i, j;
        int nvert = poly.Length;
        bool c = false;
        for (i = 0, j = nvert - 1; i < nvert; j = i++)
        {
            if (((poly[i].Y > pnt.Y) != (poly[j].Y > pnt.Y)) &&
             (pnt.X < (poly[j].X - poly[i].X) * (pnt.Y - poly[i].Y) / (poly[j].Y - poly[i].Y) + poly[i].X))
                c = !c;
        }
        return c;
    }

You can test it with this example:
PointD[] pts = new PointD[] { new PointD { X = 1, Y = 1 },
                                    new PointD { X = 1, Y = 2 },
                                    new PointD { X = 2, Y = 2 },
                                    new PointD { X = 2, Y = 3 },
                                    new PointD { X = 3, Y = 3 },
                                    new PointD { X = 3, Y = 1 }};

        List<bool> lst = new List<bool>();
        lst.Add(pnpoly(pts, new PointD { X = 2, Y = 2 }));
        lst.Add(pnpoly(pts, new PointD { X = 2, Y = 1.9 }));
        lst.Add(pnpoly(pts, new PointD { X = 2.5, Y = 2.5 }));
        lst.Add(pnpoly(pts, new PointD { X = 1.5, Y = 2.5 }));
        lst.Add(pnpoly(pts, new PointD { X = 5, Y = 5 }));

A: My business critical implementation of PointInPolygon function working on integers (as OP seems to be using) is unit tested for horizontal, vertical and diagonal lines, points on the line are included in the test (function returns true).
This seems to be an old question but all previous examples of tracing have some flaws: do not consider horizontal or vertical polygon lines, polygon boundary line or the order of edges (clockwise, counterclockwise).
The following function passes the tests I came up with (square, rhombus, diagonal cross, total 124 tests) with points on edges, vertices and just inside and outside edge and vertex.
The code does the following for every consecutive pair of polygon coordinates:

*

*Checks if polygon vertex equals the point

*Checks if the point is on a horizontal or vertical line

*Calculates (as double) and collects intersects with conversion to integer

*Sorts intersects so the order of edges is not affecting the algorithm

*Checks if the point is on the even intersect (equals - in polygon)

*Checks if the number of intersects before point x coordinate is odd - in polygon

Algorithm can be easily adapted for floats and doubles if necessary.
As a side note - I wonder how much software was created in the past nearly 10 years which check for a point in polygon and fail in some cases.
    public static bool IsPointInPolygon(Point point, IList<Point> polygon)
    {
        var intersects = new List<int>();
        var a = polygon.Last();
        foreach (var b in polygon)
        {
            if (b.X == point.X && b.Y == point.Y)
            {
                return true;
            }

            if (b.X == a.X && point.X == a.X && point.X >= Math.Min(a.Y, b.Y) && point.Y <= Math.Max(a.Y, b.Y))
            {
                return true;
            }

            if (b.Y == a.Y && point.Y == a.Y && point.X >= Math.Min(a.X, b.X) && point.X <= Math.Max(a.X, b.X))
            {
                return true;
            }

            if ((b.Y < point.Y && a.Y >= point.Y) || (a.Y < point.Y && b.Y >= point.Y))
            {
                var px = (int)(b.X + 1.0 * (point.Y - b.Y) / (a.Y - b.Y) * (a.X - b.X));
                intersects.Add(px);
            }

            a = b;
        }

        intersects.Sort();
        return intersects.IndexOf(point.X) % 2 == 0 || intersects.Count(x => x < point.X) % 2 == 1;
    }

A: Complete algorithm along with C code is available at http://alienryderflex.com/polygon/
Converting it to c# / winforms would be trivial.

A: The accepted answer did not work for me in my project. I ended up using the code found here.
public static bool IsInPolygon(Point[] poly, Point p)
{
    Point p1, p2;
    bool inside = false;

    if (poly.Length < 3)
    {
        return inside;
    }

    var oldPoint = new Point(
        poly[poly.Length - 1].X, poly[poly.Length - 1].Y);

    for (int i = 0; i < poly.Length; i++)
    {
        var newPoint = new Point(poly[i].X, poly[i].Y);

        if (newPoint.X > oldPoint.X)
        {
            p1 = oldPoint;
            p2 = newPoint;
        }
        else
        {
            p1 = newPoint;
            p2 = oldPoint;
        }

        if ((newPoint.X < p.X) == (p.X <= oldPoint.X)
            && (p.Y - (long) p1.Y)*(p2.X - p1.X)
            < (p2.Y - (long) p1.Y)*(p.X - p1.X))
        {
            inside = !inside;
        }

        oldPoint = newPoint;
    }

    return inside;
}

A: For those using NET Core, Region.IsVisible is available from NET Core 3.0. After adding package System.Drawing.Common,
using System;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace Example
{
    class Program
    {
        static bool IsPointInsidePolygon(Point[] polygon, Point point)
        {
            var path = new GraphicsPath();
            path.AddPolygon(polygon);

            var region = new Region(path);
            return region.IsVisible(point);
        }

        static void Main(string[] args)
        {
            Point vt1 = new Point(0, 0);
            Point vt2 = new Point(100, 0);
            Point vt3 = new Point(100, 100);
            Point vt4 = new Point(0, 100);
            Point[] polygon = { vt1, vt2, vt3, vt4 };

            Point pt = new Point(50, 50);

            bool isPointInsidePolygon = IsPointInsidePolygon(polygon, pt);
            Console.WriteLine(isPointInsidePolygon);
        }
    }
}

Of lesser importance is that, adding System.Drawing.Common package increased size of publish folder by 400 KB. Maybe compared to custom code, this implementation could also be slower (above function timed to be 18 ms on i7-8665u). But still, I prefer this, for one less thing to worry about.

A: All you really need are 4 lines to implement the winding number method.  But first, reference the System.Numerics to use complex library.  The code below assumes that you have translate a loop of points (stored in cpyArr) so that your candidate point stands at 0,0.

*

*For each point pair, create a complex number c1 using the first point and c2 using the 2nd point ( the first 2 lines within the loop)

*Now here is some complex number theory.  Think of c1 and c2 as complex number representation of vectors.  To get from vector c1 to vector c2, you can multiply c1 by a complex number Z (c1Z=c2).  Z rotates c1 so that it points at c2.  Then it also stretches or squishes c1 so that it matces c2.  To get such a magical number Z, you divide c2 by c1 (since c1Z=c2, Z=c2/c1).  You can look up your high school notes on dividing complex number or use that method provided by Microsoft.  After you get that number, all we really care is the phase angle.

*To use the winding method, we add up all the phases and we should +/- 2 pi if the point is within the area.  Otherwise, the sum should be 0

*I added edge cases, 'literally'.  If your phase angle is +/- pi, you're right on the edge between the points pair.  In that case, I'd say the point is a part of the area and break out of the loop
  /// <param name="cpyArr">An array of 2 coordinates (points)</param>
  public static bool IsOriginInPolygon(double[,] cpyArr)
  {
      var sum = 0.0;
      var tolerance = 1e-4;

      var length = cpyArr.GetLength(0);
      for (var i = 0; i < length-1; i++)
      {
          //convert vertex point pairs to complex numbers for simplified coding
          var c2 = new Complex(cpyArr[i+1, 0], cpyArr[i+1, 1]);
          var c1 = new Complex(cpyArr[i, 0], cpyArr[i, 1]);
          //find the rotation angle from c1 to c2 when viewed from the origin
          var phaseDiff = Complex.Divide(c2, c1).Phase;
          //add the rotation angle to the sum
          sum += phaseDiff;
          //immediately exit the loop if the origin is on the edge of polygon or it is one of the vertices of the polygon
          if (Math.Abs(Math.Abs(phaseDiff) - Math.PI) < tolerance || c1.Magnitude < tolerance || c2.Magnitude < tolerance)
          {
              sum = Math.PI * 2;
              break;
          }
      }
      return Math.Abs((Math.PI*2 ) - Math.Abs(sum)) < tolerance;
  }

A: See this it's in c++ and can be done in c# in a same way.
for convex polygon is too easy:

If the polygon is convex then one can
  consider the polygon as a "path" from
  the first vertex. A point is on the
  interior of this polygons if it is
  always on the same side of all the
  line segments making up the path.
Given a line segment between P0
  (x0,y0) and P1 (x1,y1), another point
  P (x,y) has the following relationship
  to the line segment. Compute (y - y0)
  (x1 - x0) - (x - x0) (y1 - y0)
if it is less than 0 then P is to the
  right of the line segment, if greater
  than 0 it is to the left, if equal to
  0 then it lies on the line segment.

Here is its code in c#, I didn't check edge cases.
        public static bool IsInPolygon(Point[] poly, Point point)
        {
           var coef = poly.Skip(1).Select((p, i) =>
                                           (point.Y - poly[i].Y)*(p.X - poly[i].X)
                                         - (point.X - poly[i].X) * (p.Y - poly[i].Y))
                                   .ToList();

            if (coef.Any(p => p == 0))
                return true;

            for (int i = 1; i < coef.Count(); i++)
            {
                if (coef[i] * coef[i - 1] < 0)
                    return false;
            }
            return true;
        }

I test it with simple rectangle works fine:
            Point[] pts = new Point[] { new Point { X = 1, Y = 1 },
                                        new Point { X = 1, Y = 3 },
                                        new Point { X = 3, Y = 3 },
                                        new Point { X = 3, Y = 1 } };
            IsInPolygon(pts, new Point { X = 2, Y = 2 }); ==> true
            IsInPolygon(pts, new Point { X = 1, Y = 2 }); ==> true
            IsInPolygon(pts, new Point { X = 0, Y = 2 }); ==> false

Explanation on the linq query:
poly.Skip(1) ==> creates a new list started from position 1 of the poly list and then by
(point.Y - poly[i].Y)*(p.X - poly[i].X) - (point.X - poly[i].X) * (p.Y - poly[i].Y) we'll going to calculate the direction (which mentioned in referenced paragraph).
similar example (with another operation):
lst = 2,4,8,12,7,19
lst.Skip(1) ==> 4,8,12,7,19
lst.Skip(1).Select((p,i)=>p-lst[i]) ==> 2,4,4,-5,12

A: meowNET anwser does not include Polygon vertices in the polygon and points exactly on horizontal edges. If you need an exact "inclusive" algorithm:

    public static bool IsInPolygon(this Point point, IEnumerable<Point> polygon)
    {
        bool result = false;
        var a = polygon.Last();
        foreach (var b in polygon)
        {
            if ((b.X == point.X) && (b.Y == point.Y))
                return true;

            if ((b.Y == a.Y) && (point.Y == a.Y))
            {
                if ((a.X <= point.X) && (point.X <= b.X))
                    return true;

                if ((b.X <= point.X) && (point.X <= a.X))
                    return true;
            }

            if ((b.Y < point.Y) && (a.Y >= point.Y) || (a.Y < point.Y) && (b.Y >= point.Y))
            {
                if (b.X + (point.Y - b.Y) / (a.Y - b.Y) * (a.X - b.X) <= point.X)
                    result = !result;
            }
            a = b;
        }
        return result;
    }

A: I've checked codes here and all have problems.
The best method is:
    /// <summary>
    /// Determines if the given point is inside the polygon
    /// </summary>
    /// <param name="polygon">the vertices of polygon</param>
    /// <param name="testPoint">the given point</param>
    /// <returns>true if the point is inside the polygon; otherwise, false</returns>
    public static bool IsPointInPolygon4(PointF[] polygon, PointF testPoint)
    {
        bool result = false;
        int j = polygon.Count() - 1;
        for (int i = 0; i < polygon.Count(); i++)
        {
            if (polygon[i].Y < testPoint.Y && polygon[j].Y >= testPoint.Y || polygon[j].Y < testPoint.Y && polygon[i].Y >= testPoint.Y)
            {
                if (polygon[i].X + (testPoint.Y - polygon[i].Y) / (polygon[j].Y - polygon[i].Y) * (polygon[j].X - polygon[i].X) < testPoint.X)
                {
                    result = !result;
                }
            }
            j = i;
        }
        return result;
    }

A: I recommend this wonderful 15-page paper by Kai Hormann (University of Erlangen) and Alexander Agathos (University of Athens). It consolidates all the best algorithms and will allow you to detect both winding and ray-casting solutions.
The Point in Polygon Problem for Arbitrary Polygons
The algorithm is interesting to implement, and well worth it. However, it is so complex that it is pointless for me to any portion of it directly. I'll instead stick with saying that if you want THE most efficient and versatile algorithm, I am certain this is it.
The algorithm gets complex because is is very highly optimized, so it will require a lot of reading to understand and implement. However, it combines the benefits of both the ray-cast and winding number algorithms and the result is a single number that provides both answers at once. If the result is greater than zero and odd, then the point is completely contained, but if the result is an even number, then the point is contained in a section of the polygon that folds back on itself.
Good luck.

A: This is an old question, but I optimized Saeed answer:
    public static bool IsInPolygon(this List<Point> poly, Point point)
    {
        var coef = poly.Skip(1).Select((p, i) =>
                                        (point.y - poly[i].y) * (p.x - poly[i].x)
                                      - (point.x - poly[i].x) * (p.y - poly[i].y));

        var coefNum = coef.GetEnumerator();

        if (coef.Any(p => p == 0))
            return true;

        int lastCoef = coefNum.Current,
            count = coef.Count();

        coefNum.MoveNext();

        do
        {
            if (coefNum.Current - lastCoef < 0)
                return false;

            lastCoef = coefNum.Current;
        }
        while (coefNum.MoveNext());

        return true;
    }

Using IEnumerators and IEnumerables.

A: If you are drawing Shapes on a Canvas this is a quick and easy Solution.
    private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
    if (e.OriginalSource is Polygon)
    {
        //do something
    }
}

"Polygon" can be any shape from System.Windows.Shapes.

A: Here's some modern C# code:
public record Point(double X, double Y);
public record Box(Point LowerLeft, Point UpperRight)
{
    public Box(Point[] points)
        : this(
                new Point(
                    points.Select(x => x.X).Min(),
                    points.Select(x => x.Y).Min()),
                new Point(
                    points.Select(x => x.X).Max(),
                    points.Select(x => x.Y).Max()))
    {
    }

    public bool ContainsPoint(Point point)
    {
        return point.X >= LowerLeft.X
            && point.X <= UpperRight.X
            && point.Y >= LowerLeft.Y
            && point.Y <= UpperRight.Y;
    }
}

public record Polygon(Point[] Points, Box Box)
{
    public Polygon(Point[] points)
        : this(points, new(points))
    {
    }

    public bool ContainsPoint(Point point)
    {
        do
        {
            if (Box.ContainsPoint(point) == false)
            {
                break;
            }

            bool result = false;
            int j = Points.Length - 1;
            for (int i = 0; i < Points.Length; i++)
            {
                if ((Points[i].Y < point.Y && Points[j].Y >= point.Y)
                    || (Points[j].Y < point.Y && Points[i].Y >= point.Y))
                {
                    if (Points[i].X +
                        ((point.Y - Points[i].Y) / (Points[j].Y - Points[i].Y) * (Points[j].X - Points[i].X))
                        < point.X)
                    {
                        result = !result;
                    }
                }

                j = i;
            }

            return result;
        }
        while (false);

        return false;
    }
}


text:
Q: Autocomplete textbox with two dropdowns I have one dropdown for country, another dropdown for cities and an autocomplete textbox for places.
When I select country in the first dropdown it shows cities list for that particular country in the second dropdown.
Next I want to show the places list under the selected city in the autocomplete textbox.
I have one local JSON file, html page and JavaScript file. The HTML code goes as follows:
<html ng-app="myApp">
    <head>
        <script data-require="angular.js@1.3.9" data-semver="1.3.9" src="https://code.angularjs.org/1.3.9/angular.js"></script>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" />
        <script src="//code.jquery.com/jquery-1.10.2.js"></script>
        <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
        <script src="//code.jquery.com/jquery-1.10.2.js"></script>
        <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
        <script type="text/javascript" src="js/json4update.js">
            < script type = "text/javascript"
            src = "js/textauto.js" >
        </script>
    </head>

    <body>
        <div ng-controller="MyController">
            <select ng-model="Countryselected" ng-options=" coun.country for coun in country" ng-change="getCity()">
                <option value="">Select</option>
            </select>
            <select ng-model="cityselect" ng-options=" c.name  for c in Citydetails " ng-disabled="!Countryselected">
                <option value="">Select</option>
            </select>
            <input id="tags" ng-model="placeselected" ng-keyup="complete()" placeholder="Type place name" ng-disabled="!cityselect" />
        </div>
    </body>
</html>

Here goes my .js file, here is the problem I guess. I am not able to use JS function on required place.
var app = angular.module('myApp', []);
app.controller('MyController', function ($scope, $http) {
    $http.get("file2update.json").success(function (data) {
        $scope.country = data.records;
        $scope.getCity = function () {
            $scope.Citydetails = $scope.Countryselected.cities;
            $scope.places = $scope.cityselect.place;
        }
    });
    $scope.complete = function ()
    {
        $("#tags").autocomplete({
            source: $scope.placeselected
        });
    }
});

Here is my JSON file .
 {
     "records": [{
         "cities": [{
             "name": "patna",
                 "place": [
                 "p1",
                 "p2",
                 "p3"]
         }, {
             "name": "delhi",
                 "place": [
                 "d1",
                 "d2"]
         }],
             "country": "india"
     }, {
         "cities": [{
             "name": "Australia1",
                 "place": [
                 "A1",
                 "A2",
                 "A3"]
         }, {
             "name": "Australia2",
                 "place": [
                 "a11",
                 "a22",
                 "a33"]
         }],
             "country": "Australia"

     }]
 }


text:
Q: concurrency writings into memcache Could you help me with my issue. I have some slow mysql queries, so I'm caching its results into memcache.
I do something like this:
$data = get_from_cache();
if (! $data) {
   $data = get_from_mysql();
   set_cache($data);
}

Problem.
Sometimes I have about 10 requests per second. So, when my cache is expiring, I have 5-10 get-requests which are initiating this slow mysql query at the same time.
Could you recommend a pattern for me to make a mutex in php, or something like this, to do only one slow request to mysql.

A: This is known as the dog pile problem. Strategy: Break Up The Memcache Dog Pile  describes two approaches:
Solution 1:

*

*Set the cache item expire time way out in the future.

*Embed the "real" timeout serialized with the value. For example, set the item to timeout in 24 hours, but the embedded timeout might be five minutes in the future.

*On a get from the cache determine if the stale timeout expired and on expiry immediately set a time in the future and re-store the data as is. This closes down the window of risk.

*Fetch data from the DB and update the cache with the latest value.

Solution 2:

*

*Create two keys in memcached: MAIN key with expiration time a bit higher than normal + a STALE key which expires earlier.

*On a get read STALE key too. If the stale has expired, re-calculate and set the stale key again.


text:
Q: Custom positions of author names, affiliations and emails in LaTeX article I'm looking for custom positions of  author names, affiliations and emails in LaTeX article. I want to have email immediately below the affiliations rather than in the footnote like this.
                       My title

   Author A 1,∗ , Author B 1,† , Author C 1,‡ , Author D 2,§ , and Author E 2,¶

         1 Department of Computer Science, L A TEX University
         2 Department of Mechanical Engineering, L A TEX University
         ∗ Corresponding Author: A.A@university.edu
         † B.B@university.edu
         ‡ C.C@university.edu
         § D.D@university.edu
         ¶ E.E@university.edu

Any help in this regard will be highly appreciated. Thanks
\documentclass{article}
\usepackage{authblk}
\usepackage{blindtext}

\begin{document}
\date{}

\title{My title}

\author[1]{Author A\thanks{Corresponding Author: A.A@university.edu}}
\author[1]{Author B\thanks{B.B@university.edu}}
\author[1]{Author C\thanks{C.C@university.edu}}
\author[2]{Author D\thanks{D.D@university.edu}}
\author[2]{Author E\thanks{E.E@university.edu}}
\affil[1]{Department of Computer Science, \LaTeX\ University}
\affil[2]{Department of Mechanical Engineering, \LaTeX\ University}

\maketitle

\begin{abstract}
\blindtext[2]
\end{abstract}

\section{Intro}
\blindtext[10]
\end{document}

A: You can use the below mentioned code. The screen shot of the output is attached below. You need to remove the \thanks part from the author affiliation area. This is because \thanks places the e-mail id in the footnote.
Hope this helps.

\documentclass{article}
\usepackage{authblk}
\usepackage{blindtext}

\begin{document}
\date{}

\title{My title}

\author[1]{Author A}
\author[1]{Author B}
\author[1]{Author C}
\author[2]{Author D}
\author[2]{Author E}
\affil[1]{Department of Computer Science, \LaTeX\ University}
\affil[2]{Department of Mechanical Engineering, \LaTeX\ University}
\affil[ ]{\textit {\{email1,email2,email3,email4,email5\}@xyz.edu}}
%\eid{123@gmail.com}

\maketitle

\begin{abstract}
\blindtext[2]
\end{abstract}

\section{Intro}
\blindtext[10]
\end{document}


text:
Q: add day name format on array in laravel i want to change the date to format ('l Y-m-d'), i mean to add the day name, for example Friday 2022-04-01 in the array, is it possible to add the day name in it? date in still in the form 2022-04-01, how to add the name of the day?
when i return result from $holiday like this

my code in index.blade.php
//to get date range from query start_date end_date
 @php
      $start_date = \Carbon\Carbon::parse(request()->query('start_date '))->format('Y-m-d');
      $end_date = \Carbon\Carbon::parse(request()->query('end_date'))->format('Y-m-d');

      $dateRangePeriod = \Carbon\CarbonPeriod::create($start_date , $end_date);
      $dateRange = [];
      foreach ($dateRangePeriod as $key => $date) {
            $dateRange[] = $date->format('Y-m-d');
      }
 @endphp

 @foreach ($dateRange as $key => $range)
      @php

         $holiday = array_filter(json_decode($company_holiday, true), function ($var) use ($range) {
               return $var['date'] == $range;
         });

         $holiday = reset($holiday);

         dd($holiday);

       @endphp
  @endforeach

my code in controller
$company_holiday = CompanyHoliday::where('company_holiday.company_id', $company_id)
            ->whereDateBetween('company_holiday.date', $date_start, $date_end)
            ->get();

A: You can use Accessor for this
https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor
// in CompanyHoliday Model
 //define accessor
public function getDayNameAttribute()
{
    return Carbon::parse($this->date)->format('l Y-m-d');
}

//get accessor in loop
 $company_holiday->dayName

if you want dayName always with Holiday then use appends property in CompanyHoliday Model
https://laravel.com/docs/8.x/eloquent-serialization#appending-values-to-json
protected $appends = ['day_name'];

A: make the changes in the blade file.
    @php

        use Carbon\Carbon;

        $range = '2022-04-01';
        $date = Carbon::parse($range)->format('l Y-m-d'); // "Friday 2022-04-01"

    @endphp

for more formating refere: Carbon Docs


text:
Q: Why are legitimate questions with no duplicates marked as duplicates? Questions that are not duplicates should not be marked as duplicates.  There should be some sort of peer review system.  See https://meta.stackexchange.com/a/12184/184301 for what is, it seems, a legitimate answer to what the hallmarks of a duplicate are.
Moderators should spend a couple of seconds, at least, thinking about their decisions.
Here is such an example.
EDIT:
Consider the differences.  A "difficulty menu" presumes the question of "Is this hard?".  A beginner menu presumes the question of whether the user knows he/she is a beginner.  Are those not entirely different questions?  In the linked question, I made that explicit-- halfway through, which would not have been obvious after a 5-second perusal.
The key question for me was, if I'm starting out and I can't get my bearings (e.g., I want to place a bunch of items at the bottom of the screen, and it's not working out, but I don't know the key words "autolayout" or "collection view"), how can we make that process easier for noobs.
This was completely misunderstood by the moderators, and evidently most of those who commented.

A: First, there is a peer review system. It takes 5 votes from ordinary users to mark a question as a duplicate. FIVE. (Alternatively, a diamond can cast a single binding vote, but this can be overturned just like ordinary 5-people votes can.) Any one person can vote to re-open, which puts the question into a review queue where more people can vote to re-open it - 5 votes and it is open again.
Second, if your question was closed as a duplicate and you think it is not, edit it to make this distinction more obvious. This does not mean to add a sentence simply stating it is not a duplicate. Add details that distinsguish the question from the duplicate. Reviewers can then easily vote to re-open the question.
Third, a closed question is not thrown away. When a question is closed as a duplicate it typically sticks around to help other people find their way to the "master" question. You might be interested in this answer of mine: Why are questions closed as duplicates if you could have never found them without knowing the answer? for more on my thoughts around closing as dupe. It's a gift to you, not a slap in the face. Truly it is. Asking moderators not to do it is, well, odd.

A: Questions that are not duplicates are not marked as duplicates.  There is a voting system and a review system in place to ensure this process isn't a Monarchy but a Democracy.  If you feel a question was wrongly marked, you can appeal the process and have it reviewed.
Also, you can go back to the question and make sure you have clarified your question as much as possible.  If you feel it's being wrongly compared to another question, feel free to put a "contrast clause" in your question and explain why it's different from other similar questions.  Links to those questions are also a good idea so they can be easily distinguished.


text:
Q: How can I prevent styles-l.css loading for mobile only? I'm trying to clean up some of our over stuffed css and js. Chrome inspector shows that styles-l.css is 100% unused for mobile and is used a little for desktop. I used 'remove' in the default_head_blocks.xml for the mobile theme and achieved the results I hoped for, no longer loaded for mobile and desktop unaffected.
It later crossed my mind that I hadn't tested at tablet resolution. It appears tablet resolution uses the mobile theme but also uses some styles from styles-l.css. It looked a mess on ipad. This was quite disappointing. Can anyone suggest a method of applying styles-l.css to desktop AND tablet but not to mobile please?
If anyone is kind enough to reply, please bear in mind that I'm not a programmer or developer, admin is the safe limit of my knowledge. I dabble in configuration and installation but continue to be baffled by Magento 2 styles pre processing and which files need to be changed to alter styles prior to deployment.
Thanks..