text:
Q: How can I prevent jquery from breaking on an overlay after a validator returns Invalid? I am using Plone 4.3 and I have a form that has a validator (z3c.form.validator.SimpleValidator) that raises Invalid when a condition for a field is not met.  However, under the circumstances that a user clicks 'Submit' with invalid data and the form is opened as an overlay, the Invalid message displays, but any changes I made using jQuery revert.
I have a function that when called replaces the minutes in the start and end field (implemented from IEventBasic behavior) with 00 and 30:
jquery(function($){
    $.fn.extend({
        modifyTEWidgets: function(){
            $('#form-widgets-IEventBasic-start-minute').replaceWith(
                '<select class="minute datetime-widget required datetime-field" id="form-widgets-IEventBasic-start-minute" name="form.widgets.IEventBasic.start-minute">\
                     <option value="00">00</option>\
                     <option value="30">30</option>\
                </select>'
            );

            $('#form-widgets-IEventBasic-end-minute').replaceWith(
                '<select class="minute datetime-widget required datetime-field" id="form-widgets-IEventBasic-end-minute" name="form.widgets.IEventBasic.end-minute">\
                     <option value="00">00</option>\
                     <option value="30">30</option>\
                 </select>'
             );
        },
    });

});

In the prep overlay's config parameter, I set the onLoad option to call modifyTEWidgets()
$('a#my-object-myobject, .openMyObject').prepOverlay({
        subtype: 'ajax',
        filter: '#content>*',
        formselector: '#content-core > form',
        noform: 'redirect',
        config:{
                onLoad: function(e){
                        $().modifyTEWidgets();
                },

        }
});

I also make the same changes when the form is not accessed as a popup:
jQuery(document).ready(function(){
    if($('body').hasClass('portaltype-my-object-myobject') || $('body').hasClass('template-my-object-myobject')){
        $().modifyTEWidgets();
    }
    ...
});

The problem is that when the form is accessed as an overlay, the jQuery breaks when the user clicks the submit button with invalid dates.  The minutes revert back to 0-59 and another change for hiding time components of the start and end fields if whole day is selected stops working.
What is odd is that if the user clicks on another field after leaving an invalid date, as opposed to clicking submit, it doesn't break and the Invalid message shows up as it should.  Also, the jQuery doesn't break at all if the user is accessing the form normally.
I did try using other options in the config parameter to call the modifyTEWidgets from, but I'm not sure if that's going to help as nothing changed.  Part of the problem could be the fact the start and end fields are from IEventBasic.
Is there any way to prevent the changes made in the fields from being undone when the user clicks submit with invalid data?
UPDATE
I came up with a work around finally.
$('#form-buttons-save').click(function(e){

    if(typeof clicked !== 'undefined'){
        //prevent submitting again
        e.preventDefault();
    }
    else{
        $('.fieldErrorBox').each(function(i,obj){
            if(obj.innerHTML.length > 0){
                //prevent submitting and break loop
                e.preventDefault();
                clicked = undefined;
                return false;
            }
            //Set clicked to true since there could be a potential submission
            clicked = true;
        });
    }
    //Upon reaching this line, the submission will occur
});

The other thing I needed to do was to make my own check in my validator for seeing if the end date was set before the start date.  Theirs by default took place after the submit was clicked and in my case would break the jQuery change.


text:
Q: ODE waring messages in simple ODE problem I am working on a complicated model to study the population dynamics. I am getting some warning messages and not sure why? I am not sure does it have any effect on the solution.
I am reproducing the same error in a sample Lotka-Volterra Model. Please consider this as an example, it may not correspond to actual dynamics of the model.
(1) Could you pleases explain, how to eliminate these warnings?
(2) Does it have any effect on the output?
Thanks for reading. Here is the code:

library(deSolve)

predpreyLV<-function(t,y,p){
  N<-y[1]
  P<-y[2]

  with(as.list(p),{
    dNdt<- r*N*(1-(N/1000))-a*P*N
    dPdt<- -b*P+f*P*N
    return(list(c(dNdt,dPdt)))
  })
}

rootfun <- function (t,y,parms){
  if (t>=200 && y[2]>130)
    return (0)
  else
    return (1)
}

eventfun <- function (t,y,parms){
   y[2] = y[2]*0.99
   return (y)
}

r<-0.5; a<-0.01; f<-0.01; b<-0.2;

p<-c(r=r,a=a, b=b, f=f)
y0<-c(N=25, P=5)
times<-seq(0,500,0.01)

LV.out<-ode(y=y0,times,predpreyLV, p,method="lsodar",
            rootfunc = rootfun, events = list(func=eventfun, time = seq(198,200,0.01)))

I am getting following warnings and need to why it is happening:
*Warning messages:
1: In checkevents(events, times, Ynames, dllname, TRUE) :
  Not all event times 'events$time' are in output 'times' so they are automatically included.
2: In checkevents(events, times, Ynames, dllname, TRUE) :
  Some time steps were very close to events - only the event times are used in these cases.*

A: One method is to round both time vectors to the required precision:
times  <- round(seq(0,500,0.01), 2)
evtime <- round(seq(198,200,0.01), 2)

evtime %in% times ## check if all events are in 'times'

LV.out<-ode(y=y0,times,predpreyLV, p,method="lsodar",
            rootfunc = rootfun, events = list(func=eventfun, time = evtime))
plot(LV.out)

Hope it helps!

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS: Google Chrome shows reverse :target transition if CSS is loaded eternally I have the following fairly basic CSS for showing a menu using CSS :target
nav {
  position: absolute;
  height: 100vh;
  display: block;
  width: 20vw;
  margin-left: -30vw;
  transition: margin-left 0.5s ease-in;
  background-color: lightgrey;
}

nav:target {
  margin-left: 0vw;
}

and some sample HTML:

            Close

        Show menu

While this works, in Google Chrome, when the page loads, the menu slides out.
I've worked out that this only happens if it's an eternal stylesheet. If I use


text:
Q: Synchronizing thread communication? Just for the heck of it I'm trying to emulate how JRuby generators work using threads in C#.
Also, I'm fully aware that C# has built in support for yield return, I'm just toying around a bit.
I guess it's some sort of poor mans coroutines by keeping multiple callstacks alive using threads. (even though none of the callstacks should execute at the same time)
The idea is like this:

*

*The consumer thread requests a value

*The worker thread provides a value and yields back to the consumer thread

*Repeat untill worker thread is done

So, what would be the correct way of doing the following?
//example
class Program
{
    static void Main(string[] args)
    {
        ThreadedEnumerator<string> enumerator = new ThreadedEnumerator<string>();

        enumerator.Init(() =>
            {
                for (int i = 1; i < 100; i++)
                {
                    enumerator.Yield(i.ToString());
                }
            });

        foreach (var item in enumerator)
        {
            Console.WriteLine(item);
        };

        Console.ReadLine();
    }
}

//naive threaded enumerator
public class ThreadedEnumerator<T> : IEnumerator<T>, IEnumerable<T>
{
    private Thread enumeratorThread;
    private T current;
    private bool hasMore = true;
    private bool isStarted = false;
    AutoResetEvent enumeratorEvent = new AutoResetEvent(false);
    AutoResetEvent consumerEvent = new AutoResetEvent(false);
    public void Yield(T item)
    {
        //wait for consumer to request a value
        consumerEvent.WaitOne();

        //assign the value
        current = item;

        //signal that we have yielded the requested
        enumeratorEvent.Set();
    }

    public void Init(Action userAction)
    {
        Action WrappedAction = () =>
        {
            userAction();
            consumerEvent.WaitOne();
            enumeratorEvent.Set();
            hasMore = false;
        };
        ThreadStart ts = new ThreadStart(WrappedAction);
        enumeratorThread = new Thread(ts);
        enumeratorThread.IsBackground = true;
        isStarted = false;
    }

    public T Current
    {
        get { return current; }
    }

    public void Dispose()
    {
        enumeratorThread.Abort();
    }

    object System.Collections.IEnumerator.Current
    {
        get { return Current; }
    }

    public bool MoveNext()
    {
        if (!isStarted)
        {
            isStarted = true;
            enumeratorThread.Start();
        }
        //signal that we are ready to receive a value
        consumerEvent.Set();

        //wait for the enumerator to yield
        enumeratorEvent.WaitOne();

        return hasMore;
    }

    public void Reset()
    {
        throw new NotImplementedException();
    }

    public IEnumerator<T> GetEnumerator()
    {
        return this;
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this;
    }
}

Ideas?

A: There are many ways to implement the producer/consumer pattern in C#.
The best way, I guess, is using TPL (Task, BlockingCollection). See an example here.


text:
Q: Reset drag and drop filelist every time bootstrap-modal hides or closes Background
I'm creating a from where the user can upload information and add an image file. The form information and file name is stored in a mysql db. I'm using Bootstrap to do the styling of the site.
On this page I use the bootstrap modal to bring up the form for the user to complete. The form has a drag and drop file upload area. The file is uploaded once the form is submitted.
Once the file is dropped the info about the file is displayed in the modal inside a <div> place holder.
Problem
The problem is that when a record with a file is submitted the modal containing the form is then closed (hidden) from the user. The form should rest. When the form is then opened again to add another record and a file is added, the image holder is loaded twice. The number of times that the image holder is replicated depends on the number of times that the modal was shown before.
Question
How do change my script so that the array that olds the file information is reset with every from or modal('show')
My script is here https://jsfiddle.net/mielie007/9vz5m7da/3/

A: If I'm understanding correctly, you want to reset the entire form when the modal is being shown. Your issue is the image uploader right?
Have you tried to reset the input value to blank as follow:
$('#file').val("");

Let me know if that's what you are looking for.
Best


text:
Q: Steps Of Control Creation Process WPF I have been searching for such an explaination for a while and I couldn't have found any yet. The thing is that I would like to know the steps of initialization/creation process of a Wpf Control.
Lets take a simple Button and I would like to know what is happening when constructor gets called, when is the control added to visualTree/logicalTree, when does invocation of dependencyproperty values happen, when is ApplyTemplate() called?
I need this information to be able to write proper custom control and I think it will help others too in case they wonder why this.Template.FindName("test") always returns "null" when being called inside a constructor of a control.
Can anyone answer this or provide me with links of tutorials where the concept of initizaling a control is poperly explained?
Thanks :)

A: Per this SO answer here

Sequence of events when a Window is created and shown
As requested, here is the sequence of major events in WPF when a
  window is created and shown:

*

*Constructors and getters/setters are called as objects are created, including PropertyChangedCallback, ValidationCallback, etc on the
  objects being updated and any objects that inherit from them

*As each element gets added to a visual or logical tree its Intialized event is fired, which causes Styles and Triggers to be
  found applied in addition to any element-specific initialization you
  may define  [note: Initialized event not fired for leaves in a logical
  tree if there is no PresentationSource (eg Window) at its root]

*The window and all non-collapsed Visuals on it are Measured, which causes an ApplyTemplate at each Control, which causes additional
  object tree construction including more constructors and
  getters/setters

*The window and all non-collapsed Visuals on it are Arranged

*The window and its descendants (both logical and visual) receive a Loaded event

*Any data bindings that failed when they were first set are retried

*The window and its descendants are given an opportunity to render their content visually
Steps 1-2 are done when the Window is created, whether or not it is
  shown.  The other steps generally don't happen until a Window is
  shown, but they can happen earlier if triggered manually.

Also, I personally found the DispatcherPriority Enum useful in determining the event order in some cases

*

*Invalid

*Inactive

*SystemIdle

*ApplicationIdle

*ContextIdle

*Background

*Input

*Loaded

*Render

*DataBind

*Normal - Constructors run here

*Send


text:
Q: Potential Memory Leak in my wxPython App I am pretty sure I am suffering from memory leakage, but I havent 100% nailed down how its happening.
The application Iv'e written downloads 2 images from a url and queues each set of images, called a transaction, into a queue to be popped off by the user interface and displayed.  The images are pretty big, averaging about 2.5MB.  So as a way of speeding up the user interface and making it more responsive, I pre-load each transaction images into wxImage objects and store them.
When the user pops off another transaction, I feed the preloaded image into a window object that then converts the wxImage into a bitmap and DC blits to the window.  The window object is then displayed on a panel.
When the transaction is finished by the user, I destroy the window object (presumably the window goes away, as does the bitmap) and the transaction data structure is overwritten with 'None'.
However, depending on how many images ive preloaded, whether the queue size is set large and its done all at once, or whether I let a small queue size sit over time, it eventually crashes.  I really cant let this happen .. :)
Anyone see any obvious logical errors in what im doing?  Does python garbage collect?  I dont have much experience with having to deal with memory issues.
[edit] here is the code ;)  This is the code related to the thread that downloads the images - it is instanced in the main thread the runs the GUI - the download thread's main function is the 'fill_queue' function:
def fill_queue(self):
    while True:
        if (self.len() < self.maxqueuesize):

            try:

                trx_data = self.download_transaction_data(self.get_url)

                for trx in trx_data:
                    self.download_transaction_images(trx)
                    if self.valid_images([trx['image_name_1'], trx['image_name_2']]):
                        trx = self.pre_load_images(trx)
                        self.append(trx)

            except IOError, error:
                print "Received IOError while trying to download transactions or images"
                print "Error Received: ", error
            except Exception, ex:
                print "Caught general exception while trying to download transactions or images"
                print "Error Received: ", ex

        else:
            time.sleep(1)

def download_transaction_images(self, data):
    """ Method will download all the available images for the provided transaction """

    for(a, b) in data.items():
        if (b) and (a == "image_name_1" or a == "image_name_2"):
            modified_url   = self.images_url + self.path_from_filename(b)
            download_url   = modified_url + b
            local_filepath = self.cache_dir + b

            urllib.urlretrieve(download_url, local_filepath)
            urllib.urlcleanup()

def download_transaction_data(self, trx_location):
    """ Method will download transaction data and return a parsed list of hash structures """

    page = urllib.urlopen(trx_location)
    data = page.readlines()
    page.close()

    trx_list = []
    trx_data = {}
    for line in data:

        line = line.rstrip('|!\n')
        if re.search('id=', line):
            fields = re.split('\|', line)

            for jnd in fields:
                pairs = jnd.split('=')
                trx_data[pairs[0]] = pairs[1]

            trx_list.append(trx_data)

    return trx_list

def pre_load_images(self, trx):
    """ Method will create a wxImage and load it into memory to speed the image display """
    path1  = self.cache_dir + trx['image_name_1']
    path2  = self.cache_dir + trx['image_name_2']
    image1 = wx.Image(path1)
    image2 = wx.Image(path2)
    trx['loaded_image_1'] = image1
    trx['loaded_image_2'] = image2
    return trx

def valid_images(self, images):
    """ Method verifies that the image path is valid and image is readable """
    retval = True
    for i in images:
        if re.search('jpg', i) or re.search('jpeg', i):
            imagepath = self.cache_dir + i
            if not os.path.exists(imagepath) or not wx.Image.CanRead(imagepath):
                retval = False
        else:
            retval = False

    return retval

Also, I'd like to add that sometimes, just before the crash I get peculiar errors in my console, they look like corrupt image errors but the images are not corrupted, the error has  happened at all stages on all images.

Application transferred too few
  scanlines [2009-09-08 11:12:03] Error:
  JPEG: Couldn't load - file is probably
  corrupted. [2009-09-08 11:12:11]
  Debug: ....\src\msw\dib.cpp(134):
  'CreateDIBSection' fail ed with error
  0x00000000 (the operation completed
  successfully.).

These errors can happen a la carte, or all together.  What I think is happening is that at some point the memory becomes corrupted and anything that happens next, if I load a new transaction, or image, or do a cropping operation - it takes a dive.

So unfortunately after trying out the suggestion of moving the pre-loading function call to wxImage into the main gui thread I am still getting the error - again it will occur after too many images have been loaded into memory or if they sit in memory for too long.  Then when I attempt to crop an image the i get a memory error - something is corrupting, whether in the former case I am using too much or dont have enough (which makes no sense because I've increased my paging file size to astronomical proportions) or in the latter case where the length of time is causing a leak or corruption
The only way I think I can go at this point is to use a debugger - are there any easy ways to debug a wxPython application?  I would like to see the memory usage in particular.
The main reason why I think I need to preload the images is because if I call wxImage on each image ( I show two at a time) each time i load a 'transaction' the interface from one transaction to the next is very slow and clunky - If I load them in memory its very fast - but then I get my memory error.

A: Two thoughts:

*

*You do not mention if the downloading is running a separate thread (actually now I see that this is running in a separate thread, I should read more closely).  I'm pretty sure that wx.Image is not thread-safe, so if you are instantiating wx.Images in a non-GUI thread, that could lead to trouble like this.  (This is almost certainly the issue, most wx classes/objects/functions are not thread-safe).

*I've been bitten by nasty IncRef/DecRef bugs in wxPython (due to the underlying C++ bindings) before (mostly associated with wx.Grid and associated classes).  While I don't know of any with wx.Image, it wouldn't surprise me to find out you may be required to manually manage memory like you have to in wx.Grid sometimes.

Edit
You need to instantiate the wx.Image in the GUI thread, not the downloading thread (which your above code looks like you are currently instantiating in the non-GUI thread).  In general this is almost always going to cause lots of problems in any GUI toolkit.  You can search the wxPython mailing list for lots of emails where this is the case.  Personally I would do this:

*

*Queue for download urls.

*Thread to download images.

*Have the downloading thread places a disk location (watch out for race conditions!) in a separate queue and post custom wx.Event(threadsafe) (threadsafe with wx.PostEvent function) to the App thread.

*Have the GUI thread pop the file locations and instantiate wx.Image  ----> wx.Bitmap (maybe with wx.CallAfter to process when App is idle)

*Display (Blit) as needed.


text:
Q: Reading array into textfield on ui stack My problem is I'm reading the entire array into the textField. I need to separate them.
The goal is to show the ui of stack in motion. How do I separate them into individual text fields.
heres a the problem
Heres the panel:
public class StackPanel extends javax.swing.JPanel {

Random rnd = new Random();
MyStack stack = new MyStack();
private int top;

public StackPanel() {
    initComponents();
    clearLabels();

}

private void clearLabels() {
    label1.setText("");
    label2.setText("");
    label3.setText("");
    label4.setText("");
    label5.setText("");
}

private void setTopTextField(String topValue) {
    topValue = stack.toString();
    if (top == 0) {
        label1.setText(topValue);
    } else if (top == 1) {
        label2.setText(topValue);
    } else if (top == 2) {
        label3.setText(topValue);
    } else if (top == 3) {
        label4.setText(topValue);
    } else if (top == 4) {
        label5.setText(topValue);
    }
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
                    private void initComponents() {

    jTextField6 = new javax.swing.JTextField();
    pushButton = new javax.swing.JButton();
    popButton = new javax.swing.JButton();
    label5 = new javax.swing.JTextField();
    label4 = new javax.swing.JTextField();
    label3 = new javax.swing.JTextField();
    label2 = new javax.swing.JTextField();
    label1 = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    jLabel5 = new javax.swing.JLabel();

    jTextField6.setText("jTextField6");

    pushButton.setText("Push");
    pushButton.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            pushButtonMouseClicked(evt);
        }
    });

    popButton.setText("Pop");
    popButton.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            popButtonMouseClicked(evt);
        }
    });

    jLabel1.setText(" top");

    jLabel2.setText("top");

    jLabel3.setText("top");

    jLabel4.setText("top");

    jLabel5.setText("top");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(87, 87, 87)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel3)
                        .addComponent(jLabel4)
                        .addComponent(jLabel5))
                    .addGap(10, 10, 10)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(label1, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE)
                        .addComponent(label2)
                        .addComponent(label3))
                    .addGap(66, 66, 66)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(popButton)
                        .addComponent(pushButton))
                    .addGap(53, 53, 53))
                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabel1))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(label5, javax.swing.GroupLayout.DEFAULT_SIZE, 103, Short.MAX_VALUE)
                        .addComponent(label4))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(93, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(label5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel2))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(29, 29, 29)
                    .addComponent(pushButton)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(popButton)
                    .addContainerGap())
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel5))
                    .addGap(43, 43, 43))))
    );
}// </editor-fold>

private void pushButtonMouseClicked(java.awt.event.MouseEvent evt) {
    stack.push(rnd.nextInt(99) + 1);
    String topValue = String.valueOf(rnd.nextInt());
    setTopTextField(topValue);
    top++;

    System.out.println(stack);

}

private void popButtonMouseClicked(java.awt.event.MouseEvent evt) {
    stack.pop();
    String topValue = String.valueOf(rnd.nextInt());
    setTopTextField(topValue);
    top--;
    System.out.println(stack);
    }

// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JTextField jTextField6;
private javax.swing.JTextField label1;
private javax.swing.JTextField label2;
private javax.swing.JTextField label3;
private javax.swing.JTextField label4;
private javax.swing.JTextField label5;
private javax.swing.JButton popButton;
private javax.swing.JButton pushButton;
// End of variables declaration
}

heres the stack class:
public class MyStack {
private int[] values;
private int numberOfValues;

 public MyStack(){
  values= new int[5];
  numberOfValues = 0;
 }
public boolean isEmpty() {
    return numberOfValues == 0;
 }

public int peek(){
return values[values.length - numberOfValues];
 }
public void push(int value){
     if (numberOfValues <= 5) {
        values[numberOfValues] = value;
        numberOfValues++;
    }
   }
   public void pop(){
    for (int i = 1; i <= numberOfValues - 1; i++) {
        values[i - 1] = values[i];
    }
    numberOfValues--;
   }
  @Override
  public String toString() {
    String str = "";
    for (int i = 0; i <= numberOfValues - 1; i++) {
        str += String.valueOf(values[i]) + " ";
    }
   // str += "]";

    return str;
}

}

A: Not very nice but actually working:
StackPanel:
import java.util.Random;

public class StackPanel extends javax.swing.JPanel {

    Random rnd = new Random();
    MyStack stack = new MyStack();
    private int top;

    public StackPanel() {
        initComponents();
        clearLabels();

    }

    private void clearLabels() {
        label1.setText("");
        label2.setText("");
        label3.setText("");
        label4.setText("");
        label5.setText("");
    }

    private void setTopTextField(String topValue) {
        if (top == 0) {
            label1.setText(topValue);
        } else if (top == 1) {
            label2.setText(topValue);
        } else if (top == 2) {
            label3.setText(topValue);
        } else if (top == 3) {
            label4.setText(topValue);
        } else if (top == 4) {
            label5.setText(topValue);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jTextField6 = new javax.swing.JTextField();
        pushButton = new javax.swing.JButton();
        popButton = new javax.swing.JButton();
        label5 = new javax.swing.JTextField();
        label4 = new javax.swing.JTextField();
        label3 = new javax.swing.JTextField();
        label2 = new javax.swing.JTextField();
        label1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();

        jTextField6.setText("jTextField6");

        pushButton.setText("Push");
        pushButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                pushButtonMouseClicked(evt);
            }
        });

        popButton.setText("Pop");
        popButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                popButtonMouseClicked(evt);
            }
        });

        jLabel1.setText(" top");

        jLabel2.setText("top");

        jLabel3.setText("top");

        jLabel4.setText("top");

        jLabel5.setText("top");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        layout.createSequentialGroup()
                                .addGap(87, 87, 87)
                                .addGroup(
                                        layout.createParallelGroup(
                                                javax.swing.GroupLayout.Alignment.TRAILING)
                                                .addGroup(
                                                        layout.createSequentialGroup()
                                                                .addGroup(
                                                                        layout.createParallelGroup(
                                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                                                .addComponent(
                                                                                jLabel3)
                                                                                .addComponent(
                                                                                jLabel4)
                                                                                .addComponent(
                                                                                jLabel5))
                                                                .addGap(10, 10,
                                                                        10)
                                                                .addGroup(
                                                                        layout.createParallelGroup(
                                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                                                .addComponent(
                                                                                label1,
                                                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                                88,
                                                                                Short.MAX_VALUE)
                                                                                .addComponent(
                                                                                label2)
                                                                                .addComponent(
                                                                                label3))
                                                                .addGap(66, 66,
                                                                        66)
                                                                .addGroup(
                                                                        layout.createParallelGroup(
                                                                                javax.swing.GroupLayout.Alignment.TRAILING)
                                                                                .addComponent(
                                                                                popButton)
                                                                                .addComponent(
                                                                                pushButton))
                                                                .addGap(53, 53,
                                                                        53))
                                                .addGroup(
                                                        javax.swing.GroupLayout.Alignment.LEADING,
                                                        layout.createSequentialGroup()
                                                                .addGroup(
                                                                        layout.createParallelGroup(
                                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                                                .addComponent(
                                                                                jLabel2,
                                                                                javax.swing.GroupLayout.Alignment.TRAILING)
                                                                                .addComponent(
                                                                                jLabel1))
                                                                .addPreferredGap(
                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addGroup(
                                                                        layout.createParallelGroup(
                                                                                javax.swing.GroupLayout.Alignment.LEADING,
                                                                                false)
                                                                                .addComponent(
                                                                                label5,
                                                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                                103,
                                                                                Short.MAX_VALUE)
                                                                                .addComponent(
                                                                                label4))
                                                                .addContainerGap(
                                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                        Short.MAX_VALUE)))));
        layout.setVerticalGroup(layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        javax.swing.GroupLayout.Alignment.TRAILING,
                        layout.createSequentialGroup()
                                .addContainerGap(93, Short.MAX_VALUE)
                                .addGroup(
                                        layout.createParallelGroup(
                                                javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(jLabel1)
                                                .addComponent(
                                                        label5,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(
                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(
                                        layout.createParallelGroup(
                                                javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(
                                                        label4,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(jLabel2))
                                .addGroup(
                                        layout.createParallelGroup(
                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                .addGroup(
                                                        layout.createSequentialGroup()
                                                                .addGap(29, 29,
                                                                        29)
                                                                .addComponent(
                                                                        pushButton)
                                                                .addPreferredGap(
                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addComponent(
                                                                        popButton)
                                                                .addContainerGap())
                                                .addGroup(
                                                        javax.swing.GroupLayout.Alignment.TRAILING,
                                                        layout.createSequentialGroup()
                                                                .addPreferredGap(
                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addGroup(
                                                                        layout.createParallelGroup(
                                                                                javax.swing.GroupLayout.Alignment.BASELINE)
                                                                                .addComponent(
                                                                                label3,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                                .addComponent(
                                                                                jLabel3))
                                                                .addPreferredGap(
                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addGroup(
                                                                        layout.createParallelGroup(
                                                                                javax.swing.GroupLayout.Alignment.BASELINE)
                                                                                .addComponent(
                                                                                label2,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                                .addComponent(
                                                                                jLabel4))
                                                                .addPreferredGap(
                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addGroup(
                                                                        layout.createParallelGroup(
                                                                                javax.swing.GroupLayout.Alignment.BASELINE)
                                                                                .addComponent(
                                                                                label1,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                                .addComponent(
                                                                                jLabel5))
                                                                .addGap(43, 43,
                                                                        43)))));
    }// </editor-fold>

    private void pushButtonMouseClicked(java.awt.event.MouseEvent evt) {
        stack.push(rnd.nextInt(99));
        setTopTextField(new Integer(stack.peek()).toString());
        top++;

        System.out.println(stack);

    }

    private void popButtonMouseClicked(java.awt.event.MouseEvent evt) {
        stack.pop();
        top--;
        setTopTextField("");
        System.out.println(stack);
    }

    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField jTextField6;
    private javax.swing.JTextField label1;
    private javax.swing.JTextField label2;
    private javax.swing.JTextField label3;
    private javax.swing.JTextField label4;
    private javax.swing.JTextField label5;
    private javax.swing.JButton popButton;
    private javax.swing.JButton pushButton;
    // End of variables declaration
}

MyStack:
public class MyStack {
    private int[] values;
    private int numberOfValues;

    public MyStack() {
        values = new int[5];
        numberOfValues = 0;
    }

    public boolean isEmpty() {
        return numberOfValues == 0;
    }

    public int peek() {
        return values[numberOfValues - 1];
    }

    public void push(int value) {
        if (numberOfValues <= 5) {
            values[numberOfValues] = value;
            numberOfValues++;
        }
    }

    public void pop() {
        numberOfValues--;
    }

    @Override
    public String toString() {
        String str = "";
        for (int i = 0; i <= numberOfValues - 1; i++) {
            str += String.valueOf(values[i]) + " ";
        }
        // str += "]";

        return str;
    }

}


text:
Q: folder structure for a plugin oriented site like wordpress i just want to know about the files and folder structure for a site which is a plugin oriented like wordpress or joomla.
my requirement is to develop a site and want to add more functions via plugin or something like features.
what i need is to just add and additional information or functional sessions like in wordpress
we can use All in one SEO packages it will bypass the title and some other information.
or some other features like Related articles are shown at the bottom of a particular article body.
aam talking about a structure of wordpress.
does any one have an Idea please share with me.
hope every one understood my qustion as well.
thank you.

A: I think there are many possible solutions.
It might depend on:

*

*scalablity (how large do you want it to support plugins and do the reuse parts of each other?)

*vibility (how should the plugin address become visible in the url?)

*deployment (who can add new plugins? is it open for everyone or just certified developers)

You could go for:
www.domain.xyz/plugins/some_module/
But what if the plugins arent plugins but becomes default part of the system afterwards?
Then it would be more logical to call them what they are like:
www.domain.xyz/some_module/
But then you might get into problems with plugins name like exisiting system folders. Therefore you would need some "reserved" list of foldernames to prevent that.
You could also go for:
some_module.domain.xyz/
But that would requiere your webadmin or webserver to support multiple aliases for one website on the other hand, this arhictecture would bring scalability, because you could move the modules to other webhosts later on. But its also more expensive work in the development + its hard to make it "user/developer controlled" as this could grow.
You could have a look at how FaceBook is handling Applications too. Thats a plugin interface too. Slow, but implemented.


text:
Q: Friedman test to report on occurrence of categories in multiple articles To investigate reasons for certain behavior, we have defined three categories for these reasons, and have determined how often these were mentioned across 15 (very different) scientific articles. These articles were selected by systematic review of titles and abstracts. They span the whole (broad) medical field and are very heterogeneous in methodology and setting.
I want to report on which category of reasons is the most 'important' category for the investigated behavior. I.e. if one category is mentioned significantly more often than the others.
Our data is as follows, we have a table with the 15 articles for rows, and the categories as columns. Each cell shows how often an article has mentioned a category in absolute numbers. Like so:
Art C1  C2  C3
1   10  3   2
2    7  18  1
3    5  2   7
etc...

After much consideration my idea would be to use the Friedman test to determine if one category is mentioned significantly more often than the others, or to show the mean rank of one category is significantly higher than the others. First question, assuming the data, would this be the right test?
Second question, should I use the actual occurrences in the articles as data in the table? EG:
Art C1  C2  C3
1   10  3   2
2    7  18  1
3    5  2   7
etc...

Or ranked?
Art C1 C2  C3
1    3  2   1
2    2  3   1
3    2  1   3

And then I would report the mean rank and the result of the Friedman test e.g. the probability that the difference in mean rank is based on chance"
So two questions:

*

*Friedman, good idea?

*List the data with the absolute numbers,
or ranked?


text:
Q: Need a secure way to bypass License check condition in a public method I have two products A and B. A is a paid tool while B is a free tool. B uses the some dll of A. Now i have a method say
 public void licenseCheck(bool test){....}

this method contains a condition which gives alert "get license" if you dont have one. Now from one of the class of Product B i have to call licenseCheck method for some reason and since B is free and you dont need a license for it, it still gives "get license" Error.
I tried i changed the signature of the method
licenseCheck( bool test, bool byPasslicense = false)

and use the byPasslicense variable to bypass the condition of license checking. I gave default value to it because this method is used at many places.
This approach has some security issues as these dlls are used for many other paid products where licensing is required. some one can just call this method and pass "true" value to byPasslicense argument of  licenseCheck method. I dont want that. I just want it to bypass for  product B
Note:
this is a completed project and I cant just change the whole method, i just have to bypass the condition responsible for license checking in the licenseCheck method.

A: It seems to me that you have broken the S in the SOLID principles, in that the method getLicense does more than just checking the license, otherwise there would be no need to call it if you want it to not check the license.
So here is how you should solve this.

*

*Split the getLicense method into two (at least) by extracting a portion of it into a new method. Leave the part that actually checks the license in the original method, and split the rest out to a new method. Make this new method internal.

*Add this attribute to your A project: [assembly: InternalsVisibleTo("B")]

*From B, call the new method instead of getLicense, thereby bypassing the license check.

Note that an internal method can only be accessed from within the same assembly, A in this instance, of from assemblies that A specifically says that internals are visible to, like B in this instance. 3rd party developers will not have direct access to that method.

Example
Original class:
public class Dohickey
{
    public void getLicense(bool hasLicense)
    {
        if (!hasLicense) throw new Exception("Ewups");
        SetSomethingThatOtherCodeDependsOn();
        SetSomethingElseAsWell();
    }
}

after fix:
[assembly: InternalsVisibleTo("B")]
// ...
public class Dohickey
{
    public void getLicense(bool hasLicense)
    {
        if (!hasLicense) throw new Exception("Ewups");
        SetThings();
    }

    internal void SetThings()
    {
        SetSomethingThatOtherCodeDependsOn();
        SetSomethingElseAsWell();
    }
}


text:
Q: How to use PooledConnectionFactoryBean with ActiveMQ First of all, I am new to JSM.
I am trying to create a pool of connection for JMS ActiveMQ
Using the connection factory ActiveMQConnectionFactory I succeed to send/receive messages, but using the PooledConnectionFactoryBean it failed with this error:
Exception in thread "Thread-0" java.lang.NoClassDefFoundError: org/springframework/beans/factory/FactoryBean
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    at jmxproducer.JMXProducerTest.run(JMXProducerTest.java:28)
    at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.ClassNotFoundException: org.springframework.beans.factory.FactoryBean
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    ... 14 more
Exception in thread "Thread-1" java.lang.NoClassDefFoundError: org/apache/activemq/pool/PooledConnectionFactoryBean
    at jmxproducer.JMXProducerTest.run(JMXProducerTest.java:28)
    at java.lang.Thread.run(Thread.java:722)
Exception in thread "Thread-2" java.lang.NoClassDefFoundError: org/apache/activemq/pool/PooledConnectionFactoryBean
    at jmxproducer.JMXProducerTest.run(JMXProducerTest.java:28)
    at java.lang.Thread.run(Thread.java:722)
Exception in thread "Thread-3" java.lang.NoClassDefFoundError: org/apache/activemq/pool/PooledConnectionFactoryBean
    at jmxproducer.JMXProducerTest.run(JMXProducerTest.java:28)
    at java

.lang.Thread.run(Thread.java:722)

Here is the source code:
package jmxproducer;

import javax.jms.*;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.pool.PooledConnectionFactoryBean;

public class JMXProducerTest implements Runnable {

    private String message;

    public JMXProducerTest(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public void run() {
        try {
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");

            PooledConnectionFactoryBean pool = new PooledConnectionFactoryBean();
            pool.setConnectionFactory(connectionFactory);

            // Create a Connection
            Connection connection = connectionFactory.createConnection();
            connection.start();

            // Create a Session
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            // Create the destination (Topic or Queue)
            Destination destination = session.createQueue("MY.QUEUE");

            // Create a MessageProducer from the Session to the Topic or Queue
            MessageProducer producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            // Create a messages
            TextMessage msg = session.createTextMessage(message);
            producer.send(msg);
            session.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

What did I miss? I added to the classpath this jar: activemq-all-5.8.0.jar
Thanks,
kdureidy

A: Did you add the Spring libraries to your project?
The error
java.lang.ClassNotFoundException: org.springframework.beans.factory.FactoryBean

seems to indicate that spring-beans-X.jar is missing from your project (where X is the version of Spring that you're missing).


text:
Q: Dimension of Quot scheme of zero dimensional quotients of a locally free sheaf Given a locally free sheaf $E$ of rank $r$ on a (smooth, projective, algebraic) surface, I want to know the dimension of the scheme parametrizing the zero-dimensional (meaning they have zero dimensional support) quotients of $E$ of length $k$.
I believe the answer should be $(r+1)k$. Indeed, the generic thing seems to be a quotient of the form $\bigoplus_{i=1}^k \mathbb C_{p_i}$, with an $r-1$ choice of dimensions for a map $E_{p_i} \rightarrow \mathbb C_{p_i}$ for each $i$, and $2k$ dimensions of choices for the $p_i$.
Question
Is this the correct dimension? If so, does anyone have a reference with a rigorous argument?

A: Your dimension is correct, this and more can be found in this article.


text:
Q: How to create custom function on OData RESTier I'm referring to http://odata.github.io/RESTier/#03-01-Operations on how to create a custom method that takes in input and return a list of object.
Here's my custom method
[HttpGet]
[ODataRoute("Locations/PointLoc.Data.GetLocationsByMarketId()")]
public IHttpActionResult GetLocationsByMarketId()
{
    var database = new Database();
    var locations = database.Locations.GetAllLocationsByMarket(1);
    return Ok(locations);
}

And here's how I set it in my DbDomain
protected EdmModel OnModelExtending(EdmModel model)
{
    var ns = model.DeclaredNamespaces.First();

    var location = model.FindDeclaredType(ns + "." + "Location");
    var locations = EdmCoreModel.GetCollection(location.GetEdmTypeReference(isNullable: false));

    var getLocationsWithMarketId = new EdmFunction(ns, "GetLocationsWithMarketId", locations, true, null, false);
    getLocationsWithMarketId.AddParameter("bindingParameter", locations);
    model.AddElement(getLocationsWithMarketId);

    return model;
}

Can't get it to work. Keep getting OData Uri error like
'Locations/PointLoc.Data.GetLocationsByMarketId()' on the action 'GetLocationsByMarketId' in controller 'PointLoc' is not a valid OData path template. The request URI is not valid. Since the segment 'Locations' refers to a collection, this must be the last segment in the request URI or it must be followed by an function or action that can be bound to it otherwise all intermediate segments must refer to a single resource.
Wanted to access the Odata via "/Locations/GetLocationsByMarketId". How to do it?


text:
Q: Animation in fragment I want to use animation on an Image Button in my fragment what argument
 should I use instead of activity ("this)?
pause.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));

A: You should use getActivity().

Return the Activity this fragment is currently associated with.

startAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));


text:
Q: direct and redirect iframe from relatedlist to detail and back I have this visualforce page with 2 iframes in which i want to place a 2 different contact related list and be able to add new contacts on the detail page and be redirected to the related list in the iframe see my example below, is this possible?
<apex:page>
 <apex:form >
        <apex:iframe src="/apex/AccountDetailOld?id=0010Y00000WxAd6" scrolling="false" id="Iframe1" width="50%"/>
    <apex:iframe src="/apex/AccountDetailNew?id=0010Y00000WxAd67" scrolling="false" id="Iframe2" width="50%"/>
</apex:form>

<apex:page standardController="Account" sidebar="false" showHeader="false">
<apex:relatedList list="Contacts"/>


text:
Q: How to start Apache nifi 1.17.0? I've downloaded Apache nifi 1.17.0 and tried to start it by bin/run0nifi.bat, but it didn't work. When I click on it window open and disappear in the same time.
I'm working on windows 11 pro
What should i do?
I tried to start it by console and tried to start 1.19.1 and unfortunately it didn't help
I'm a beginner so I might not have done some obvious things
Thx for help)

A: You need to do two things first of all:

*

*you need to make sure that you have installed JAVA on your machine and set the PATH for the JDK in the Environment Variables (JAVA_HOME).

*If JAVA is configured correctly you need to open CMD and go within the NiFi Folder. From there, you should execute the run-nifi.bat manually and see if anythings gets written in the CMD window.

Besides that, you can go within the logs folder and see if any logs are being generated. Most likely you will find something in the nifi-app.log.


text:
Q: Populating month and day I'm populating a combobox with month name as follows:`
        var engCulture = new CultureInfo("en-US");
        cmbAmCul.Items.AddRange(engCulture.DateTimeFormat.MonthNames);

what is the right way to:

*

*eliminate the blank entry after the
12 month names.

*populate another
    combobox with day (1-31 || 1-28 ||
    1-30) according to the month
    selected?

A: For the first part, you could use a linq query...
var engCulture = new CultureInfo("en-US");
cmbAmCul.Items.AddRange(from m in engCulture.DateTimeFormat.MonthNames
                        where !String.IsNullOrEmpty(m)
                        select m);

The DateTimeInfo class supports calendars with 13 months, which is why this occurs.
For the second part, I would go for something like...
for (int i = 1; i <= DateTime.DaysInMonth(year, month); i++) {
    cmbDay.Items.Add(i.ToString());
}

Obviously populating the year/month vars from your selected values.

A: *

*Use String.Trim() to remove blanks from beginning & end of strings

*Use return value from DateTime.DaysInMonth(int year, int month) to populate your day combo box

You could also use a DateTime picker from the standard controls or is it not an option for you?

A: You don't specify what you are trying to build (ASP.NET or Winforms etc) but you could possibly use a Calendar control instead of dropdowns to improve the User experience.  Less clicks and less code tho go wrong perhaps.


text:
Q: how to find keywords in a pdf document and highlight them using JavaScript in Adobe Acrobat How do I find keywords in a pdf document and highlight them using JavaScript in Adobe Acrobat?
I've tried using arrays, where list of arrays contains the keywords that needs to be filtered in the document I opened in adobe acrobat, but unable to find and highlight them using JavaScript.
The below code is finding for one keyword which has to enter every time with new keywords in the if condition and run.
var keywords = ["ex1", "ex2", "ex3", "ex4", "ex5"];

if (keywords.indexOf("ex1") !== -1) {
  alert("Yes, the value exists!");
} else {
  alert("No, the value is absent.");
}

But what I need is to run code single time, picking keywords in that runtime and highlight all the keywords exists in the document.


text:
Q: Non-conformable arguments stop function that uses matices as inputs from working Im trying to replicate the code here for "R code for replicating kings". Below I attach the code up to the point it works fine.AFter this point I get Error in istate %*% Pmat : non-conformable arguments. Why does this happen? Do I miss something. Maybe someone can figure it out. That all I have no other dataset or something. I tried to run the example that is int doc as well but get the same error.
MMod<-function (Pmat, cycle, n, Init, halfcycle=F, measure, discount=.03)
{cumul<-0
i<-1
istate<-Init
m<-measure*cycle
if (halfcycle) {cumul<-0.5*(Init%*%m)}
while (i <= n)
{ istate<-istate%*%Pmat
imeasure<-istate%*%m
cumul<-cumul+imeasure
#print(paste(c(i,round(istate,2),cumul)))   i<-i+1
m<-m*(1-discount*cycle)
}
if (halfcycle) {cumul<-cumul - 0.5*imeasure}
return(cumul)}

MToll<-function (Pmat, cycle, n, Init, toll, discount=.03)
{cumul<-0
i<-1
m<-1
istate<-Init
nstates<-length(Init)
LTM<-matrix(0, nrow=nstates, ncol=nstates)
LTM[lower.tri(LTM)]<-1
while (i <= n)
{
  istate2<-istate%*%Pmat
  netshifts<-LTM%*%t(istate-istate2)
  tolli<-netshifts[-1]%*%toll*m
  cumul<-cumul+tolli
  istate<-istate2
  m<-m*(1-discount*cycle)
  i<-i+1 }
return(cumul)
}

MST<-function (Pmat, n, Init)
{i<-1
istate<-Init
States<-Init
while (i <= n)
{
  istate<-c(istate%*%Pmat)
  States<-cbind(States, istate)
  i<-i+1 }
return(States)}

New.calc<-function(P1, P2, HSU, cost.Treat, cost.Care, Toll, Fixed.Treat, halfcycle=T,...) {
  QY1<-MMod(Pmat=P1,measure=HSU,halfcycle=halfcycle,...)
  QY2<-MMod(Pmat=P2,measure=HSU,halfcycle=halfcycle,...)
  Treat1<-MMod(Pmat=P1,measure=cost.Treat[,1],halfcycle=halfcycle,...)
  Treat2<-MMod(Pmat=P2,measure=cost.Treat[,2],halfcycle=halfcycle,...)
  Care1<-MMod(Pmat=P1,measure=cost.Care,halfcycle=halfcycle,...)
  Care2<-MMod(Pmat=P2,measure=cost.Care,halfcycle=halfcycle,...)
  Toll1<-MToll(Pmat=P1,toll=Toll,...)
  Toll2<-MToll(Pmat=P2,toll=Toll,...)
  ansDF<-data.frame( Utility=c(QY1, QY2),
                                                                                Treatment=c(Treat1+Fixed.Treat[1], Treat2+Fixed.Treat[2]),
                                                                                RC=c(Care1, Care2),                    TC=c(Toll1, Toll2))
  ansDF<-data.frame(ansDF, Total_Cost=apply(ansDF[,2:4], 1, sum))
  ansDF2<-rbind(ansDF, ansDF[2,]-ansDF[1,])   rownames(ansDF2)<-c("Tr1", "Tr2", "Diff")
  ans1<-(Care2-Care1+Treat2-Treat1+Toll2-Toll1+Fixed.Treat[2]-Fixed.Treat[1])   ans2<-(QY2-QY1)
  return(list(Cost_Utility=ansDF2, ICUR=ans1/ans2))
}

P.RILUneg<-read.table(text="
6.8604466e-01 0.27237339416 0.0392288844 0.0020896625 0.00011414761 0.00014925021 2.6080360e-02 0.74183221490 0.2130311396 0.0167613306 0.00121619371 0.00107876162 7.9577302e-04 0.04513125922 0.8115775903 0.1232709064 0.01337414561 0.00585032537 2.7391412e-05 0.00229455178 0.0796554694 0.7391659905 0.16375225528 0.01510434163
8.9680288e-07 0.00009978931 0.0051797995 0.0981474867 0.79583386882 0.10073815882
0.0000000e+00 0.00000000000 0.0000000000 0.0000000000 0.00000000000 1.00000000000",fill = TRUE , header = FALSE )
P.RILUpos<-read.table(text="
6.9449942e-01 0.27189897910 0.0314651341 0.0019380647 8.9161464e-05 0.00010923903 2.6903100e-02 0.77862279416 0.1766404706 0.0160845681 9.8349868e-04 0.00076556815 8.0656346e-04 0.04576193898 0.7942333863 0.1423245490 1.3101929e-02 0.00377163306 2.7854076e-05 0.00233633511 0.0797978780 0.7588375567 1.4166520e-01 0.01733517825
9.1518056e-07 0.00010202547 0.0052463334 0.1011747832 8.2156998e-01 0.07190595839
0.0000000e+00 0.00000000000 0.0000000000 0.0000000000 0.0000000e+00 1.00000000000",fill = TRUE , header = FALSE )
P.RILUneg<-as.matrix(P.RILUneg)
P.RILUpos<-as.matrix(P.RILUpos)

Q.stages<-c(0.7886603, 0.7425028, 0.6293351, 0.5407166, 0.4644944, 0)

RC.med<-c(0, 14784, 21696, 29568, 40200, 0)
RC.informal<-c(0, 15588, 30336, 39876, 49428, 36372)
RC.soc<-c(0, 30372, 52032, 69444, 89628, 36372)

TC.med<-c(245.5 ,5036.5,11082.5,17203.0,10911.5)
TC.soc<-c(245.5 ,5036.5,13633.5,22305.0,20462.5)
COST.RILU<-matrix(c(rep(0, 7), rep(158*12, 4), 0), nrow=6)
COST.RILU.fixed<-c(0, 184)

New.calc(P.RILUneg, P.RILUpos, HSU=Q.stages, cost.Treat=COST.RILU, cost.Care=RC.med,
         Toll=TC.med, Fixed.Treat = COST.RILU.fixed, Init=c(0,1,0,0,0,0), cycle=1/12, n=60)


text:
Q: TSQL - Changing databases dynamically I'm in a new company, and trying to write a proc that loops through the databases and looks up a keyword in all the tables, procs, etc.
It works great in theory, however I've noticed that the database never changes.
I've outputted the SQL, and ran it, no problem. But if I run the piece of code, it doesn't change.
I've also played around with the code and hard-coded the table name and gotten it to work, so could it be a security feature?
Here's the TSQL:
Declare @Dbname varchar(250);   --Stores Database Name

Declare @SearchTerm varchar(250); --What we're searching the DB for

Declare @vSQL varchar(550)=''; --Variable that will hold our dynamic queries

set @SearchTerm='LoadID';

select name
from   sys.databases
where  owner_sid != 0x01;

print @Dbname;
set @vSQL = 'use [' + @dbname + ']';
exec (@vSQL);

--exec @vSQL;
--execute (@vSQL);
--execute @vSQL);

A: EXEC runs in its own context. Put entire script into @vSql kind of
set @vSQL = 'use [' + @dbname + '];' +'--do what you need ' ;

A: Something I have that does this, and a bit more is the following proc. Should loop through all DB's on a given instance, look for a keyword in the definition of objects in those dbs, as well as if any jobs make use of those objects and their last execute duration.
USE [master]
GO

Create Proc dbo.DependencyCheck @SearchKey Varchar(150) As

Begin

--DB Refs

Drop Table If Exists #Databases

Create Table #Databases

(
    DatabaseName Varchar(50) Primary Key
    ,Checked Int Default 0 Not Null
    ,SearchKey Varchar(150)
    ,DependencyText As 'Insert Into #Dependencies
                                            Select Distinct '

                                            + '''' + DatabaseName + '''' +
                                            ',
                                            D.id As ObjectID,
                                            O.name As ObjectName,
                                            xtype As ObjectType,
                                            S.name As SchemaName

                                            From '

                                            + DatabaseName + '.dbo.syscomments D

                                            Inner Join ' + DatabaseName + '.dbo.sysobjects O
                                                On O.ID = D.id

                                            Inner Join ' + DatabaseName + '.sys.schemas As S
                                                On s.schema_id = O.uid

                                            Where D.text Like ''%' + SearchKey + '%'''
)

Insert Into #Databases (DatabaseName, SearchKey)

    Select

    Name, @SearchKey

    From sys.sysdatabases As S

    Where S.filename Not Like '%.SS' --Not DB Snapshots

Declare @TargetDatabase Varchar(25) = (Select Top 1 DatabaseName From #Databases As D Where D.Checked = 0)

--Dependency Table

Drop Table If Exists #Dependencies

Create Table #Dependencies

(
    DatabaseName Varchar(50) Not Null,
    ObjectID Int Not Null,
    ObjectName Varchar(150) Not Null,
    ObjectType Varchar(15) Not Null,
    SchamaName Varchar(150) Not null
)

--Dynamic SQL for Insert
Declare @DynamicDependency Varchar(8000) = (Select D.DependencyText From #Databases As D Where D.DatabaseName = @TargetDatabase)

While @TargetDatabase Is Not Null

    Begin

        Exec(@DynamicDependency)

        Update D Set Checked = 1 From #Databases D Where DatabaseName = @TargetDatabase

        Set @TargetDatabase = (Select Top 1 DatabaseName From #Databases As D Where D.Checked = 0)
        Set @DynamicDependency = (Select D.DependencyText From #Databases As D Where D.DatabaseName = @TargetDatabase)

    End

;With JobStats As
(
Select Distinct

J.name,
JH.step_id,
First_Value(JH.run_duration) Over (Partition By J.name, JH.step_id Order By CA.StartTime Desc) As Last_Duration,
Avg(JH.run_duration) Over (Partition By J.name, JH.step_id) As Avg_Duration

From msdb.dbo.sysjobhistory As JH

Cross Apply (Select Convert(Datetime, Convert(varchar(8),run_date))
 + Convert(datetime, Stuff(STUFF(RIGHT(REPLICATE('0', 6) +  CAST(run_time as varchar(6)), 6), 3, 0, ':'), 6, 0, ':')) As StartTime) CA

 Inner Join msdb.dbo.sysjobs As J
    On J.job_id = JH.job_id

Where JH.step_id <> 0
And JH.run_status = 1 -- Success
)

Select

D.ObjectID
,D.DatabaseName
,D.SchamaName
,D.ObjectName
,D.ObjectType
,J.name As JobName
,JS.step_id As JoBStepID
,JS.step_name As JobStepName
,JStat.Last_Duration
,JStat.Avg_Duration

From #Dependencies As D

Left Join msdb.dbo.sysjobsteps JS
    On JS.command Like '%' + D.ObjectName + '%'
    And JS.subsystem = 'TSQL'
Left Join msdb.dbo.sysjobs J
    On J.job_id = JS.job_id

Left Join JobStats JStat
    On JStat.name = J.name
    And JStat.step_id = JS.step_id

Order By 1, 3

End


text:
Q: htaccess RewriteRule for /category/page In .htaccess defined such rewrite rule
RewriteRule ^([a-zA-Z0-9_-]+)$ ___show-content.php?$1

Created file ___show-content.php which includes code
echo (ltrim($_SERVER['QUERY_STRING'],'/')). '<br/>';

If i type www.mydomain.com/some-page then $_SERVER['QUERY_STRING' is /some-page. This works as expected.
But if I type www.mydomain.com/some-page/another-page, then get see Not Found The requested URL /some-page/another-page was not found on this server. I see nothing with $_SERVER['QUERY_STRING'. If one trailing slash (after domain name), then works ok, but if more than one, does not works.
What need to modify for RewriteRule to work with more than one trailing slash in url?

A: That is because your regex to capture URI is only allowing one and more of [a-zA-Z0-9_-] characters in it.
Make your rule as:
RewriteRule ^([\w/-]+)$ ___show-content.php?$1 [L,QSA]


text:
Q: PWI - Picasa Webalbum Integrator and jQuery.noConflict()? I have a Problem with the following script: http://code.google.com/p/pwi/
This is a very nice Picasa jQuery Gallery!
Can someone please tell me how i run this script in jQuery.noConflict() mode? I have already added the line...
<script>jQuery.noConflict()</script>

...in the HTML file and replace all $ with jQuery. But then the script doesn't work anymore.

Nobody can help me? I have the Demo 1 from this ZIP file
with fancybox.
Normally i need only replace $ with jQuery in the .html and .js files, and then add the jQuery.noConflict() to the head. But here doesn't work...
The error console in Firefox says:

Error: TypeError: n.gphotojQuerytimestamp is undefined
Source file: file:///C:/Users/pc/Desktop/jquery.pwi/js/jquery.pwi.js
Line: 361

A: Looking at the page from jQuery (http://api.jquery.com/jQuery.noConflict/) you can use two methods.
I did a quick test, and it looks like you can use the second method. If you modify Demo1 like this:
In the script section where PWI is initialized add these lines before var $viewerSelected = "fancybox";:
  $.noConflict();
  jQuery(document).ready(function($) {
  // Code that uses other library's $ can follow here.

Just before the closing end-script tag add the lines
  });
  // Code that uses other library's $ can follow here.

This at least makes sure that the code is still running without errors


text:
Q: How to find the minimum and maximum value of a 10x12 matrix I have a program that calculate the amount of sales for a sales company using a 10x12 matrix.
The sales company has branches in 10 cities, and the program has to print the number of sales for each branch in the last 12 months. Then print the total number of the sales in the year, then the last thing is to print the minimum and maximum value of the sales
But the program does not print the correct minimum and maximum value
Here is the code
using namespace std;
int main() {
    double F[10][12];
    double sum[10] = { 0 };
    double Msum[12] = { 0 };

    int i = 0;
    int j;
    double x = 0;
    double max = 0;
    double Minimum = 100000000;

    for (i = 0; i < 10; i++) {
        cout << "please enter the " << i + 1 << " branch sale for the " << endl;
        for (j = 0; j < 12; j++) {
            cout << "month " << j + 1 << ": " << endl;
            cin >> F[i][j];
        }
    }

    for (i = 0; i < 10; i++)
        for (j = 0; j < 12; j++)
            sum[i] += F[i][j];
    for (i = 0; i < 10; i++) {
        cout << "the total sales for branch " << i + 1 << " is " << sum[i] << endl;
    }

    for (i = 0; i < 10; i++)
        for (j = 0; j < 12; j++) {
            x += F[i][j];
        }
    cout << "the total sales for all branches in the year is " << x << endl;

    int min = INT_MAX;
    int max = INT_MIN;

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j <= 3 / 2; j++)
        {
            if (F[i][j] > F[i][3 - j - 1])
            {
                if (min > F[i][3 - j - 1])
                    min = F[i][3 - j - 1];
                if (max < F[i][j])
                    max = F[i][j];
            }
            else
            {
                if (min > F[i][j])
                    min = F[i][j];
                if (max < F[i][3 - j - 1])
                    max = F[i][3 - j - 1];
            }
        }
    }

    cout << "the branch that has the maximum sale in the year is " << max << endl;
    cout << "the month that has the least sales in the year is " << min << endl;
    return 0;
}```


text:
Q: is $T:C[0,1]\rightarrow C[0,1]$: $x(t)\mapsto x(t^2)$ compact? Is $T$ a compact operator?
$T:C[0,1]\rightarrow C[0,1]$: $x(t)\mapsto x(t^2)$ where $t\in[0,1]$
with supremum norm.

A: Same approach as previous answers, using limited operators:
If $T\colon X \to X$ is a compact operator and $S \colon X \to X$ is a bounded operator, then both $TS$ and $ST$ are compact.
Let $S: C^1[0,1] \to C^1[0,1]$ such that $u(t) \mapsto u(\sqrt{t})$. Readily we see that $\|S\| = 1$, so $S$ is bounded. But $TS = Id$. If $T$ is compact so is $Id$, but as $C^1[0,1]$ is infinite dimensional, $Id$ cannot be compact and therefore $T$ is not compact.

A: Here is a much less intuitive answer.
Note: Unfortunately this was not as simple as I had originally thought (thanks to Davide for catching my oversight). The result depends on the fact that $C[0,1]$ has the 'approximation property', that is, any compact operator is the limit (in the operator norm) of a sequence of finite rank operators.
(See Remark 1.1.15 in "An Introduction to Nonlinear Analysis: Applications", Vol. 2, Z. Denkowski, S. Migórski, N. S. Papageorgiou.)
Note that $\|Tx\|= \|x\|$ for all $x$.
Suppose $A$ is a finite rank operator, then $\ker A  $ is non-trivial (consider the effect of $A$ on $t \mapsto t^n$, for example).
Choose $x \in \ker A$ of unit norm, then $\|(T-A)x\| = \|Tx\| = \|x\| = 1$, and so
$\|T-A\| \ge 1$, hence $T$ cannot be approximated by finite rank operators. It follows that $T$ is not compact.

A: Here's Daniel Fischer's comment in more explicit terms: any compact operator on an infinite dimensional Banach space (e.g. $C([0,1])$) cannot be invertible. However the map $x(t)\mapsto x(\sqrt{t})$ is the inverse map for $T$ so $T$ cannot be compact.

A: Slightly different approach:
Assume to the contrary that $T$ is compact. Clearly $\|T\|=1$, in fact $\|T^n\|=1,$ so spectral radius is equal to 1.
 Since the ambient space in infinite dimensional then there exists a sequence of eigenvalues that converges to zero . in particular we can find eigenvalue $\lambda$ with $|\lambda|<1$ and  $g\in C[0,1]$ such that
$Tg=\lambda g\Rightarrow g(x^2)=\lambda g(x)\,\forall x\in[0,1]\Rightarrow $ $\|g\|=|\lambda|.\|g\|<\|g\|$ which is a contradiction.

A: First, a  general remark. A common way to prove that some operator $T$ is not compact is to exhibit an infinite-dimensional subspace $M$ on which $T$ has a lower bound: that is, there exists $c>0$ such that
$$\|Tx\|\ge c\|x\|,\quad \forall\ x\in M \tag{1}$$
If (1) holds, then the image of unit ball under $T$ contains a ball of radius $c$ in the infinite-dimensional subspace $TM$, and therefore is not compact.
In view of the above, you should be asking yourself: for which functions $x$ can I prove an inequality of the form $\|Tx\|\ge c\|x\|$? Looking at what $T$ does, and recalling the definition of the norm, you will realize that $\|Tx\| = \|x\|$ holds for all $x\in C[0,1]$. Therefore, $T$ is not compact.


text:
Q: AddThis Wordpress plugin not working with AJAX theme I'm using the AddThis Wordpress plugin to include share buttons underneath each post in an AJAX theme, and am having trouble getting the code right.
I inserted the following code in the custom button field on the settings page:

Then in the post loop in the main page PHP file I have this:

The buttons will only load sporadically, and disappear after a refresh. I'm also getting the error Uncaught ReferenceError: ReinitializeAddThis is not defined which is confusing... I'd really appreciate any insight and I apologize if anything is unclear. Thanks!

A: I have arrived at a solution, so I'll post it here in case anyone ever runs into the same problem.
On the AddThis settings page, I pasted this code into the "custom button" field:

Then in the post loop within the main page PHP file:

This calls the window.addthis.toolbox() function for each individual post and creates a sharing toolbox after AJAX has rendered as specified on this page.


text:
Q: Need an average grand total but have a sum The issue that I am dealing with is that I have a sum as the grand total for the value of a ratio of two measures and I need the grand total to be an average. After some research, I am fairly certain that I know the issue is that I am using sum() as part of one of the measures in this ratio, which means DAX is just going to use a sum by default for any subtotal or grand total, but I'm at my wits end trying to figure out how to adjust my formulas to calculate the average instead. To start, I'll show the matrix I am working with:
matrix
My formula for status counts per day is
Status Count per Day = [Statuses]/[Days worked]

Statuses (which I think is the source of my problem), unfortunately has the following obnoxiously long code:
Statuses = if(values(TMD[Specialty])="Hunt PS",calculate(SUM('Status Counts'[Count]),
'Status Counts'[TI-Status Combo]="1538 Attempted" ||
'Status Counts'[TI-Status Combo]="1538 Confirmed - All Docs" ||
'Status Counts'[TI-Status Combo]="1538 Confirmed - No Docs" ||
'Status Counts'[TI-Status Combo]="1538 Confirmed - On Hold" ||
'Status Counts'[TI-Status Combo]="1538 Confirmed - Some Docs"),
calculate(sum('Status Counts'[Count]),
'Status Counts'[TI-Status Combo]="1538 Attempted" ||
'Status Counts'[TI-Status Combo]="1538 Confirmed - All Docs" ||
'Status Counts'[TI-Status Combo]="1538 Confirmed - No Docs" ||
'Status Counts'[TI-Status Combo]="1538 Confirmed - On Hold" ||
'Status Counts'[TI-Status Combo]="1538 Confirmed - Some Docs"))

I don't know how to get around using sum for this formula because it is adding together the count column for the desired statuses, which is always 1, so every time I produce a formula that doesn't error out just gets me to an output of 1 (the average in the count column for these statuses). Obviously not the desired output.
Status table
Days worked:
Days Worked = [Hours Worked]/8

Hours Worked:
Hours Worked = calculate(sum('Hours Worked'[Regular Hours]),TMD[CommonID])

CommonID is just the unique ID for each person. I do have a date table in my data set that has days, month number, calendar month, calendar year, quarter, etc.
As you could see in the picture I have months in the column of the matrix. What I need the average broken down to is the monthly level but I can't seem to filter the formulas in the right way. I've tried tinkering with the formulas for [Status count per day] and [statuses] but have made no progress. Any help is appreciated.

A: Maybe something like:
AVERAGEX(VALUES('Date'[Month]),[Status Count per Day])


text:
Q: Consume Azure Authenticated .net core API with PowerShell I'm trying to invoke an azure ad authenticated .net core api with powershell script. Can someone help me with the powershell script? I have already created an app registration for the api in azure active directory.

A: I exposed the api protected by Azure, created an application registration for the api, and then used the client credential flow to obtain the token:

script:
$clientID = 'a13b414b-93b3-4aae-bb68-6a40ffxxxxxx'
$secretKey = '4.Yi4qwn_rqe7BK3F6Nfz.c0A7pTxxxxxx'
$tenantID = 'e4c9ab4e-bd27-40d5-8459-230ba2xxxxxx'

$password = ConvertTo-SecureString -String $secretKey -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($ClientID,$password)
Connect-AzureRmAccount -ServicePrincipal -Credential $credential -Tenant $tenantID

$authUrl = "https://login.microsoftonline.com/" + $tenantID + "/oauth2/v2.0/token/"
$body = @{
   "scope" = "api://a13b414b-93b3-4aae-bb68-6a40ffxxxxxx/.default";
   "grant_type" = "client_credentials";
   "client_id" = $ClientID
   "client_secret" = $secretKey
}

Write-Output "Getting Authentication-Token"
$adlsToken = Invoke-RestMethod -Uri $authUrl –Method POST -Body $body
Write-Output $adlsToken


text:
Q: Typescript decorator for function, not method. Possible? I'm trying to add a custom TypeScript decorator in a function which is not included in a class and it seems that the compiler is complaining no matter what I do.
Any thoughts? Is it possible?

A:
add a custom TypeScript decorator in a function

Not to a raw function. The main issue is dealing with hoisting of functions. Any attempt to wrap a function in another function breaks the hoist.
Support Targets

A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators use the form @expression, where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.

Docs: https://www.typescriptlang.org/docs/handbook/decorators.html#decorators

A: Isn't possible because the method decorator use the PropertyDescriptor and this one is only possible to use in classes.
But, there is a lib that you can use the method decorators in functions, but without the syntax @myDecorator. The decorator has the same syntax, you can use exist method decorators in functions
https://www.npmjs.com/package/pure-function-decorator
But, instead this:
class Somethind {
  @log
  myMethod() { //....

You can use in this way
const myFunction = fnDecorator([log], () => { /*....*/});

And has the same result


text:
Q: Bind to all interfaces for IPv4 and IPv6 in haproxy I want to configure haproxy to bind to a tcp as well as tcp6 socket on all interfaces (i.e., 0.0.0.0:80 and :::80).
I was able to reach this goal with the following settings:
listen web
  bind :80 v4v6
  bind :::80 v6only

Is there any shorter way than this?
While I expect it to behave different, the v4v6 keyword makes haproxy bind to a v4 socket only.

A: To listen on the same port for IPv6 and IPv4, use this:
bind :::80 v4v6

Admittedly, this was an intuitive guess that appears to have been correct... but rather than just post a "lucky" guess as the answer, even though it works, it seems like I should justify it.

the v4v6 keyword makes haproxy bind to a v4 socket only.

My first intuition was that it's not v4v6 but rather the use of :80 (or, more precisely, the use of no IP address at all, just a port number) that causes this socket to listen on IPv4 only.
This seems to be confirmed in the docs for bind:

address is optional and can be a host name, an IPv4 address, an IPv6 address, or '*'. It designates the address the frontend will listen on. If unset, all IPv4 addresses of the system will be-listened on. The same will apply for '*' or the system's special address "0.0.0.0". The IPv6 equivalent is '::'.
http://cbonte.github.io/haproxy-dconv/configuration-1.6.html#4.2-bind (emphasis added)

So the following three forms are all equivalent, and are all interpreted as being IPv4 by HAProxy:
bind :80
bind *:80
bind 0.0.0.0:80

Next, there is one sentence in the docs for v4v6 could be read in isolation to indicate that v4v6 might be usable to extend one of the above bind statements to listen on IPv6...

v4v6
It is used to bind a socket to both IPv4 and IPv6 when it uses the default address.

...hmmm, but I suspect that this actually means "the v6 default address" (::)...

Doing so is sometimes necessary
  on systems which bind to IPv6 only by default.

...and now, I suspect it even more...

It has no effect on non-IPv6
  sockets, and is overridden by the v6only option.
http://cbonte.github.io/haproxy-dconv/configuration-1.6.html#5.1

So, it appears that v4v6 only modifies bind directives that specify the IPv6 default listen address, which is :: (the 3rd : is the separator between the address and the port), and is ignored for others.

A: I know im late to the party. Im not allowed to comment so i had to add this answer.
I just wanted to add if you dont like the way the triple colons ::: look
bind :::80

You can always enclose IPv6 address in brackets.
bind [::]:80

A: The accepted answer does not work for me, at least with haproxy-1.6.11p0 on OpenBSD. Also, TL;DR. Just do:
bind 0.0.0.0:80
bind :::80

and it will work:
# netstat -an|grep "*.80"
tcp          0      0  *.80                   *.*                    LISTEN
tcp6         0      0  *.80                   *.*                    LISTEN

A: I configure it like this:
    bind *:80,[::]:80 v6only
    bind *:443,[::]:443 v6only ssl crt ...


text:
Q: Enabling caching for GWT RPC asynchronous calls I'm thinking of introducing some kind of caching mechanism (like HTML5 local storage) to avoid frequent RPC calls whenever possible. I would like to get feedback on how caching can be introduced in the below piece of code without changing much of the architecture (like using gwt-dispatch).
void getData() {

    /* Loading indicator code skipped */

    /* Below is a gwt-maven plugin generated singleton for SomeServiceAsync */
    SomeServiceAsync.Util.getInstance().getDataBySearchCriteria(searchCriteria, new AsyncCallback<List<MyData>>() {

        public void onFailure(Throwable caught) {
            /* Loading indicator code skipped */
            Window.alert("Problem : " + caught.getMessage());
        }

        public void onSuccess(List<MyData> dataList) {
            /* Loading indicator code skipped */
        }
    });
}

One way I can think of to deal with this is to have a custom MyAsyncCallback class defining onSuccess/onFailure methods and then do something like this -
void getData() {

    AsyncCallback<List<MyData>> callback = new MyAsyncCallback<List<MyData>>;

    // Check if data is present in cache
    if(cacheIsPresent)
        callback.onSuccess(dataRetrievedFromCache);
    else
    //  Call RPC and same as above and of course, update cache wherever appropriate
}

Apart from this, I had one more question. What is the maximum size of storage available for LocalStorage for popular browsers and how do the browsers manage the LocalStorage for different applications / URLs? Any pointers will be appreciated.

A: I suggest to add a delegate class which handles the caching. The delegate class could look like this:
public class Delegate {

  private static SomeServiceAsync service = SomeServiceAsync.Util.getInstance();

  private List<MyData> data;

  public static void getData(Callback callback) {
    if (date != null) {
      callback.onSuccess(data);
    } else {
      service.getData(new Callback() {
        public onSuccess(List<MyData> result) {
          data = result;
          callback.onSuccess(result);
      });
    }
  }

}

Of course this is a crude sample, you have to refine the code to make it reliable.

A: I did take too long to decide on using hash maps to cache results.
My strategy was not to use a singleton hashmap, but a singleton common objects class storing static instances of cache. I did not see the reason to load a single hashmap with excessive levels of hashtree branching.
Reduce the amount of hash resolution
If I know that the objects I am dealing with is Employee, Address, Project, I would create three static hashes
final static private Map<Long, Employee> employeeCache =
  new HashMap<Long, Employee>();
final static private Map<Long, Address> addressCache =
 new HashMap<Long, Address>();
final static private Map<String name, Project> projectCache =
 new HashMap<String name, Project>();

public static void putEmployee(Long id, Employee emp){
  employeeCache.put(id, emp);
}
public static Employee getEmployee(Long id){
  return employeeCache.get(id);
}

public static void putEmployee(Long id, Address addr){
  addressCache.put(id, addr);
}
public static Address getEmployee(Long id){
  return addressCache.get(id);
}

public static void putProject(String name, Address addr){
  projectCache.put(name, addr);
}
public static Address getProject(String name){
  return projectCache.get(name);
}

Putting it all in a single map would be hairy. The principle of efficient access and storage of data is - the more information you have determined about the data, the more you should exploit segregating that data using that information you have. It would reduce the levels of hash resolution required to access the data. Not to mention all the risky and indefinite type casting that would need to be done.
Avoid hashing if you can
If you know that you always have a single value of CurrentEmployee and NextEmployee,
avoid storing them in the hash of Employee. Just create static instances
Employee CurrentEmployee, NextEmployee;

That would avoid needing any hash resolution at all.
Avoid contaminating the global namespace
And if possible, keep them as class instances rather than static instances, to avoid contaminating the global namespace.
Why avoid contaminating the global namespace? Because, more than one class would inadvertently use the same name causing untold number of bugs due to global namespace confusion.
Keep the cache nearest to where it is expected or used
If possible, if the cache is mainly for a certain class, keep the cache as a class instance within that class. And provide an eventbus event for any rare instance that another class would need to get data from that cache.
So that you would have an expectable pattern
ZZZManager.getZZZ(id);

Finalise the cache if possible,
otherwise/and privatise it by providing putters and getters. Do not allow another class to inadvertently re-instantiate the cache, especially if one day your class becomes a general utility library. Also putters and getters have the opportunity to validate the request to avoid a request from wiping out the cache or pushing the app into an Exception by directly presenting the cache with keys or values the cache is unable to handle.
Translating these principles into Javascript local storage
The GWT page says

Judicious use of naming conventions can help with processing storage data. For example, in a web app named MyWebApp, key-value data associated with rows in a UI table named Stock could have key names prefixed with MyWebApp.Stock.

Therefore, supplementing the HashMap in your class, with rather crude code,
public class EmployeePresenter {
  Storage empStore = Storage.getLocalStorageIfSupported();
  HashMap<Long, Employee> employeeCache;

  public EmployeePresenter(){
    if (empStore==null) {
      employeeCache = new HashMap<Employee>();
    }
  }

  private String getPrefix(){
    return this.getClass()+".Employee";
    //return this.getClass().getCanonicalName()+".Employee";
  }

  public Employee putEmployee(Long id, Employee employee)
    if (empStore==null) {
      stockStore.setItem(getPrefix()+id, jsonEncode(employee));
      return;
    }
    employeeCache.put(id, employee);
  }

  public Employee getEmployee(Long id)
    if (empStore==null) {
      return (Employee) jsonDecode(Employee.class, stockStore.getItem(getPrefix()+id));
    }
    return employeeCache(id);
  }
}

Since, the localstore is string based only, I am presuming that you will be writing your own json encoder decoder. On the other hand, why not write the json directly into the store the moment you receive it from the callback?
Memory constraints?
I cannot profess expertise in this question but I predict the answer for hashmaps to be the maximum memory constrained by the OS on the browser. Minus all the memory that is already consumed by the browser, plugins and javascript, etc, etc overhead.
For HTML5 local storage the GWT page says
"LocalStorage: 5MB per app per browser. According to the HTML5 spec, this limit can be increased by the user when needed; however, only a few browsers support this."
"SessionStorage: Limited only by system memory"

A: Since you are using gwt-dispath an easy solution here is to cache the gwt-dispatch Response objects agains the Request objects as a key in a Map. Its easy to implement and type agnostic. You will need to override Request - equals() method to see if the Request is already in the cache. If yes return Response from cache otherwise hit the server with a call.
IMO - LocalStorage is not a necessity here if all you need is in session cache for performance. Local Storage only a must for offline apps.
You may look into this - http://turbomanage.wordpress.com/2010/07/12/caching-batching-dispatcher-for-gwt-dispatch/