text:
Q: cSlider: stop autoplay on mouseover How can I stop the autoplay function of cSlider with an onmouseover event?
HTML:

Text

More text

What I have tried so far with jQuery:
$(function() {
    $('#da-slider').cslider({
            autoplay    : true,
            bgincrement : 450
    });
});

$('#da-slider').hover(function() {

    if($('#daslider').autoplay('true')){
        autoplay: false
    }

}, function () {
    autoplay: true
});

This is the one I'm using:
http://tympanus.net/codrops/2012/03/15/parallax-content-slider-with-css3-and-jquery/

A: This feature not implemented by default but this shouldn't stop you from implementing it on your own. Look at modified plugin code below (draw attention on stop and 'start' methods)
(function ($, undefined) {

    /*
    * Slider object.
    */
    $.Slider = function (options, element) {

        this.$el = $(element);

        this._init(options);

    };

    $.Slider.defaults = {
        current: 0,     // index of current slide
        bgincrement: 50, // increment the bg position (parallax effect) when sliding
        autoplay: false, // slideshow on / off
        interval: 4000  // time between transitions
    };

    $.Slider.prototype = {
        _init: function (options) {

            this.options = $.extend(true, {}, $.Slider.defaults, options);

            this.$slides = this.$el.children('div.da-slide');
            this.slidesCount = this.$slides.length;

            this.current = this.options.current;

            if (this.current < 0 || this.current >= this.slidesCount) {

                this.current = 0;

            }

            this.$slides.eq(this.current).addClass('da-slide-current');

            var $navigation = $('');
            for (var i = 0; i < this.slidesCount; ++i) {

                $navigation.append('');

            }
            $navigation.appendTo(this.$el);

            this.$pages = this.$el.find('nav.da-dots > span');
            this.$navNext = this.$el.find('span.da-arrows-next');
            this.$navPrev = this.$el.find('span.da-arrows-prev');

            this.isAnimating = false;

            this.bgpositer = 0;

            this.cssAnimations = Modernizr.cssanimations;
            this.cssTransitions = Modernizr.csstransitions;

            if (!this.cssAnimations || !this.cssAnimations) {

                this.$el.addClass('da-slider-fb');

            }

            this._updatePage();

            // load the events
            this._loadEvents();

            // slideshow
            if (this.options.autoplay) {

                this._startSlideshow();

            }

        },
        _navigate: function (page, dir) {

            var $current = this.$slides.eq(this.current), $next, _self = this;

            if (this.current === page || this.isAnimating) return false;

            this.isAnimating = true;

            // check dir
            var classTo, classFrom, d;

            if (!dir) {

                (page > this.current) ? d = 'next' : d = 'prev';

            }
            else {

                d = dir;

            }

            if (this.cssAnimations && this.cssAnimations) {

                if (d === 'next') {

                    classTo = 'da-slide-toleft';
                    classFrom = 'da-slide-fromright';
                    ++this.bgpositer;

                }
                else {

                    classTo = 'da-slide-toright';
                    classFrom = 'da-slide-fromleft';
                    --this.bgpositer;

                }

                this.$el.css('background-position', this.bgpositer * this.options.bgincrement + '% 0%');

            }

            this.current = page;

            $next = this.$slides.eq(this.current);

            if (this.cssAnimations && this.cssAnimations) {

                var rmClasses = 'da-slide-toleft da-slide-toright da-slide-fromleft da-slide-fromright';
                $current.removeClass(rmClasses);
                $next.removeClass(rmClasses);

                $current.addClass(classTo);
                $next.addClass(classFrom);

                $current.removeClass('da-slide-current');
                $next.addClass('da-slide-current');

            }

            // fallback
            if (!this.cssAnimations || !this.cssAnimations) {

                $next.css('left', (d === 'next') ? '100%' : '-100%').stop().animate({
                    left: '0%'
                }, 1000, function () {
                    _self.isAnimating = false;
                });

                $current.stop().animate({
                    left: (d === 'next') ? '-100%' : '100%'
                }, 1000, function () {
                    $current.removeClass('da-slide-current');
                });

            }

            this._updatePage();

        },
        _updatePage: function () {

            this.$pages.removeClass('da-dots-current');
            this.$pages.eq(this.current).addClass('da-dots-current');

        },
        _startSlideshow: function () {

            var _self = this;

            this.slideshow = setTimeout(function () {

                var page = (_self.current < _self.slidesCount - 1) ? page = _self.current + 1 : page = 0;
                _self._navigate(page, 'next');

                if (_self.options.autoplay) {

                    _self._startSlideshow();

                }

            }, this.options.interval);

        },
        page: function (idx) {

            if (idx >= this.slidesCount || idx < 0) {

                return false;

            }

            if (this.options.autoplay) {

                clearTimeout(this.slideshow);
                this.options.autoplay = false;

            }

            this._navigate(idx);

        },
        stop: function () {
            if (this.options.autoplay) {

                clearTimeout(this.slideshow);
                this.options.autoplay = false;

            }
        },
        start: function () {
            this.options.autoplay = true;
            this._startSlideshow();
        },
        _loadEvents: function () {

            var _self = this;

            this.$pages.on('click.cslider', function (event) {

                _self.page($(this).index());
                return false;

            });

            this.$navNext.on('click.cslider', function (event) {

                if (_self.options.autoplay) {

                    clearTimeout(_self.slideshow);
                    _self.options.autoplay = false;

                }

                var page = (_self.current < _self.slidesCount - 1) ? page = _self.current + 1 : page = 0;
                _self._navigate(page, 'next');
                return false;

            });

            this.$navPrev.on('click.cslider', function (event) {

                if (_self.options.autoplay) {

                    clearTimeout(_self.slideshow);
                    _self.options.autoplay = false;

                }

                var page = (_self.current > 0) ? page = _self.current - 1 : page = _self.slidesCount - 1;
                _self._navigate(page, 'prev');
                return false;

            });

            if (this.cssTransitions) {

                if (!this.options.bgincrement) {

                    this.$el.on('webkitAnimationEnd.cslider animationend.cslider OAnimationEnd.cslider', function (event) {

                        if (event.originalEvent.animationName === 'toRightAnim4' || event.originalEvent.animationName === 'toLeftAnim4') {

                            _self.isAnimating = false;

                        }

                    });

                }
                else {

                    this.$el.on('webkitTransitionEnd.cslider transitionend.cslider OTransitionEnd.cslider', function (event) {

                        if (event.target.id === _self.$el.attr('id'))
                            _self.isAnimating = false;

                    });

                }

            }

        }
    };

    var logError = function (message) {
        if (this.console) {
            console.error(message);
        }
    };

    $.fn.cslider = function (options) {

        if (typeof options === 'string') {

            var args = Array.prototype.slice.call(arguments, 1);

            this.each(function () {

                var instance = $.data(this, 'cslider');

                if (!instance) {
                    logError("cannot call methods on cslider prior to initialization; " +
                    "attempted to call method '" + options + "'");
                    return;
                }

                if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
                    logError("no such method '" + options + "' for cslider instance");
                    return;
                }

                instance[options].apply(instance, args);

            });

        }
        else {

            this.each(function () {

                var instance = $.data(this, 'cslider');
                if (!instance) {
                    $.data(this, 'cslider', new $.Slider(options, this));
                }
            });

        }

        return this;

    };

})(jQuery);

With updated plugin you can pause and renew autiplaying with this code:
$('#da-slider').hover(
    function () {
        $(this).cslider("stop");
    },
    function () {
        $(this).cslider("start");
    }
);


text:
Q: How can I using uikit to fixed the navbar on the top? I'm using the uikit css framework, I want to fixed the navbar on the top?

A: You need to include 'components/sticky.js' file from UIKit package and add data-uk-sticky directive to your fixed bar div.
For example:

...

I suggest to use it with navbar component, for example:

    ...

...

...

...

A: Add this to your css file:
.uk-fixed-navigation {
    position: fixed;
    right: 0;
    left: 0;
    top: 0;
    z-index: 1030;
}

And add uk-fixed-navigtion class to your navbar.
EDIT
You also can use their sticky component

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lowercase delta in differential-like equation Preface: The following question comes from an expression seen in a biophysics paper published in Nature protocols.
I'm aware that in pure mathematical notation $\delta$ is never used in the context of differential equations, however, I have an expression with the following structure;
$$\frac{\delta x}{\delta y} = G(x)$$
Where G is a function which depends on $x$.
Rather than being a differential equation, I'm assuming this is a (somewhat misleading) way of looking at non-infinitesimal change. In the legend the following text appears
"$\delta x/ \delta y$ is the rate of change of ellipticity at any time t"
But in the original paper's context this $dt$ is likely to be value equal to or greater than 10 ms - i.e. this may not hold true as $\delta t \rightarrow 0$. This suggests that treating the expression as a differential equation would be inappropriate. Any thoughts/comments would be appreciated (even if it's just a 'yup - makes sense').

A: Infinitesimal rate of change is always a mathematical abstraction. Even for a simple physics problem, like the motion of a free falling stone, we encounter limitation of the model as $\delta t\to 0$. At small enough scale, the position and velocity of the stone are not well-defined: the stone is not a point, its molecules move around,  quantum effects become noticeable...
Any observed rate of change is not instantaneous; it is the mean rate of change over some period of time $\delta t>0$. One may still say "rate of change at time  $t_0$" instead of the longer "mean rate of change over some time interval of small length $\delta t$ containing $t_0$".  As long as the rate of change does not change much within the $\delta t$ interval, this is a reasonable thing to say. And we do use differential equations to model physical processes, and the models perform quite well in the setting of classical mechanics.
So,  I would not say that treating equation (7) as a differential equation is inappropriate just because the rate of change hasn't been measured at time intervals $\delta _t<0.01$. If one can somehow solve it as a differential equation, the result could be used to predict the behavior of $[\theta]_t$. And if the prediction diverges from reality too much, one will look  for reasons why.
After all, predictions based on models are not theorems. Nobody can prove a theorem about proteins;  theorems concern mathematical objects, which proteins are not.


text:
Q: Installing Ruby on Mac OS High Sierra error I've been trying to create a static website using Jekyll static website generator but for using it I have to install ruby using my terminal. But when I run brew install ruby I get this message error and I couldn't find a solution yet.
Warning: You are using macOS 10.13.
We (and Apple) do not provide support for this old version.
You will encounter build failures with some formulae.
Please create pull requests instead of asking for help on Homebrew's GitHub,
Twitter or any other official channels. You are responsible for resolving
any issues you experience while you are running this
old version.

Error: ruby: no bottle available!
You can try to install from source with:
 brew install --build-from-source ruby
Please note building from source is unsupported. You will encounter build
failures with some formulae. If you experience any issues please create pull
requests instead of asking for help on Homebrew's GitHub, Twitter or any other
official channels.

Should I install it from source as the error message says ?

A: You can try install a Ruby Manager with Homebrew. I prefer to use rbenv. There are other options, notably rvm. Choose one and stick to it.
If you choose to use rbenv
brew install ruby-build rbenv
Follow the brew caveats in your terminal to add any needed environmental variables.
To list available versions
rbenv install --list
Install the one you like
rbenv install <version number>
As mentioned in a comment you may run into more issues down the line so if possible upgrade macOS version.


text:
Q: Shared folder not connecting over Mac VirtualBox guest I am trying to connect with the Windows 7 host's shared folder from my VirtualBox Mac (Yosemite) guest. It is showing my PC's name in Finder's sidebar but when I double click it, it fails to connect to my PC/shared folder. Image below.

A: Virtual Guest Additions are required to be installed on your virtual machine in order to use Shared folders. These can be installed by selecting Insert Guest Additions CD Image from the Devices menu of your guest VM window.

A: I've found a "half-solution" for the same problem. I made ".iso" image and connect it to the guest OS as CD. The disadvantage is a one way direction from Host to Guest but for me it was ok because I needed to pass some files for testing.


text:
Q: Joins in Java 8 Collection API I have two List<Map<String, Object>> object.
[{Month=August-2013, Sales=282200}, {Month=July-2013, Sales=310400},
 {Month=June-2013, Sales=309600}, {Month=May-2013, Sales=318200},
 {Month=September-2013, Sales=257800}]

and
[{Month=April-2013, NoOfTranx=8600}, {Month=August-2013, NoOfTranx=6700},
 {Month=July-2013, NoOfTranx=14400}, {Month=June-2013, NoOfTranx=8500},
 {Month=May-2013, NoOfTranx=14400}]

I want to join(Merge) these two List on Month key. How can I perform several join operation (i.e. FULL OUTER JOIN, RIGHT OUTER JOIN etc.) on these List using new Collection API.

A: One way to perform a full outer join is to first construct a Map<String, Map<String, Object>> that links the month value to the maps themselves and get the values in a list:
//first concatenate the two lists
Map<String, Map<String, Object>> result = Stream.concat(list1.stream(),
                                                        list2.stream())
                //then collect in a map where the key is the value of the month
                .collect(toMap(m -> (String) m.get("Month"),
                //the value is the map itself
                               m -> m,
                //merging maps (i.e. adding the "Sales" and "NoOfTranx" infos)
                               (m1, m2) -> {m1.putAll(m2); return m1; }));

//finally put that in a list
List<Map<String, Object>> merge = new ArrayList<>(result.values());

Notes:

*

*the original maps are modified - if this is undesirable you can create a new HashMap<>() in the merging part.

*for left/right outer join, you can stream one list only and add the relevant entries in the stream

*for inner join you can start from one of the list, filter elements present in the other list and continue as above

Full example below which prints:
list1 = [{Month=August-13, Sales=282200}, {Month=July-13, Sales=310400}]
list2 = [{Month=August-13, NoOfTranx=6700}, {Month=July-13, NoOfTranx=14400}]
merge = [{Month=August-13, Sales=282200, NoOfTranx=6700}, {Month=July-13, Sales=310400, NoOfTranx=14400}]

Code:
public static void main(String[] args) {
    List<Map<String, Object>> list1 = new ArrayList<>();
    list1.add(map("Month", "August-13", "Sales", 282200));
    list1.add(map("Month", "July-13", "Sales", 310400));
    System.out.println("list1 = " + list1);

    List<Map<String, Object>> list2 = new ArrayList<>();
    list2.add(map("Month", "August-13", "NoOfTranx", 6700));
    list2.add(map("Month", "July-13", "NoOfTranx", 14400));
    System.out.println("list2 = " + list2);

    Map<String, Map<String, Object>> result = Stream.concat(list1.stream(),
                                                            list2.stream())
                .collect(toMap(m -> (String) m.get("Month"),
                               m -> m,
                               (m1, m2) -> {m1.putAll(m2); return m1; }));

    List<Map<String, Object>> merge = new ArrayList<>(result.values());
    System.out.println("merge = " + merge);
}

private static Map<String, Object> map(Object... kvs) {
    Map<String, Object> map = new HashMap<>();
    for (int i = 0; i < kvs.length; i += 2) {
        map.put((String) kvs[i], kvs[i+1]);
    }
    return map;
}


text:
Q: Fluent-ui React north start VS Material UI? I'm preparing to start developing a web solution based on ReactJS, I'm struggling to choose the framework that best matches my project goals. I know that the principal objective is that my solution should be perfectly adapted to Microsoft design.
Are there any Fluent-UI developers here ?
Best regards.


text:
Q: How to show the well-definedness of a lift of a continuous map via a covering map? Given a topological space $X$ is path-connected and locally path-connected. Say $p:Z \rightarrow Y$ is a covering map such that $p(z_0)=y_0$. A map $f:X \rightarrow Y$ is continuous and $x_0 \in X$ be such that $f(x_0)=y_0$. Also given that $f_*(\pi_1(X,x_0))\subset p_*(\pi_1(Z,z_0))$.
I am trying to show that $f$ can be lifted to a $Z$ via $p$ and the lift maps $x_0$ to $z_0$.
I have proceeded like this:
As $X$ is path connected so given $x \in X$, we have a path $\alpha$ from $x_0$ to $x$. Then I have a unique lifting of $f \circ \alpha$ to a path $\widetilde{f \circ \alpha}$ in $Z$ starting from $z_0$. I defined $\tilde{f}$ from $X$ to $Z$ as $\tilde{f}(x)= \widetilde{f \circ \alpha}(1)$.
I believe that $\tilde{f}$ will be the required lifting of $f$. And to show only the existence of such a lift local path-connectedness of $X$ is redundant. All it remains to finish the proof is that $\tilde{f}$ is well-defined i.e. independent of the path $\alpha$.
Am I proceeding correctly ? How do I show the well-definedness of $\tilde{f}$?

A: I have found the answer to this problem. This is proved as a theorem in Allen Hatcher's Algebraic Topology (Proposition 1.33)
Anyway, thanks.


text:
Q: Twisted FileSender unable to send binary file due to UnicodeDecodeError I have a rather annoying problem when trying to send a file via HTTP in Twisted. I'm reasonably new to Python (being that this is my first real attempt to do anything other than Hello World etc).
Now, I'm fairly sure that the problem occurs when the FileSender sends binary data that is not UTF-8 compatible. That seems like a fairly common thing to do when moving files like images, videos, executable binaries around over the network.
It would seem to me that when initialized, the Twisted buffer is initialized to "", which (I may be very mistaken here) is a UTF-8 (or whatever your Python's default character encoding is) character string?... Then, when new data is added to the buffer, the old buffer (UTF-8) is joined with the new buffer (er... some other binary encoding?) which results in:
Unhandled Error
Traceback (most recent call last):
Failure: exceptions.RuntimeError: Producer was not unregistered for /vfs/videos/thevid.avi
Unhandled Error
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 84, in callWithLogger
    return callWithContext({"system": lp}, func, *args, **kw)
  File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 69, in callWithContext
    return context.call({ILogContext: newCtx}, func, *args, **kw)
  File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 118, in callWithContext
    return self.currentContext().callWithContext(ctx, func, *args, **kw)
  File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 81, in callWithContext
    return func(*args,**kw)
--- <exception caught here> ---
  File "/usr/lib/python2.7/dist-packages/twisted/internet/selectreactor.py", line 146, in _doReadOrWrite
    why = getattr(selectable, method)()
  File "/usr/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 428, in doWrite
    result = abstract.FileDescriptor.doWrite(self)
  File "/usr/lib/python2.7/dist-packages/twisted/internet/abstract.py", line 199, in doWrite
    self.dataBuffer = buffer(self.dataBuffer, self.offset) + "".join(self._tempDataBuffer)
  File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
exceptions.UnicodeDecodeError: 'utf8' codec can't decode byte 0xd3 in position 6: invalid continuation byte
Unhandled Error
Traceback (most recent call last):
Failure: exceptions.RuntimeError: Producer was not unregistered for /vfs/videos/thevid.avi

Surely there has to be a way to reliably set the buffer for binary data transfer? My code for the file sending function is below. I'm using TxJSONRPC to create and manage the server (except the render method, which is overridden to handle more than just RPC). If more information is needed (eg about the Request object or the Reactor, I can go digging).
Note: I'm well aware that I have no error handler, but at the moment that is of little importance to me. Error handling will be added once I get files transferring reliably!
def writeFile(self, request, location):
    # Setup headers (mime type, filename)
    request.setHeader('Content-Type', mimetypes.guess_type("file://" + location))
    request.setHeader('Content-Disposition', "attachment; filename=" + path.basename(location))

    # Open file
    handle = open(location, "rb")

    # Setup transfer (then cleanup etc)
    d = FileSender().beginFileTransfer(handle, request)
    def fileFinished(ignored):
        handle.close()
        request.finish()
    d.addCallback(fileFinished).addErrback(fileFinished)


text:
Q: Remove JTextPane Lines and Keep Styling I'm using JTextPane and StyledDocument for styling message and I want to clear the messages or clear only the oldest message.
I can easily clear all by using:
textPane.setText("");

But if I want to clear all, except some lines, then not sure if/how it can be done.
I tried
textPane.setText(textPane.getText().substring(0, Math.min(200, textPane.getText().length())));

but the issue is that it remove the content styling.
Here is simple demo that shows the issue.
Is there an easy way to do it?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class TestJTextPane {

    private JTextPane infoTextPane = new JTextPane();
    private StyledDocument styledDocument;
    private SimpleAttributeSet attributeSet = new SimpleAttributeSet();

    private JButton addText;
    private JButton clearText;

    public static void main(String[] argv) {
        new TestJTextPane();
    }

    public TestJTextPane(){

        addText = new JButton("add");
        addText.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                try {
                    StyleConstants.setForeground(attributeSet, Color.GREEN);
                    StyleConstants.setBackground(attributeSet, Color.BLACK);
                    StyleConstants.setBold(attributeSet, true);
                    StyleConstants.setFontSize(attributeSet, 20);
                    styledDocument.insertString(styledDocument.getLength(), "sample text message to add\n", attributeSet);
                    infoTextPane.setCaretPosition(infoTextPane.getDocument().getLength());
                } catch (BadLocationException e1) {
                    e1.printStackTrace();
                }
            }
        });

        clearText = new JButton("clear");
        clearText.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                //infoTextPane.setText("");
                infoTextPane.setText(infoTextPane.getText().substring(0, Math.min(200, infoTextPane.getText().length())));
            }
        });

        styledDocument = infoTextPane.getStyledDocument();

        JPanel p = new JPanel();
        p.add(addText);
        p.add(clearText);
        p.add(infoTextPane);

        JFrame f = new JFrame("HyperlinkListener");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(p);
        f.setPreferredSize(new Dimension(400, 400));
        f.pack();
        f.setVisible(true);
    }
}

A: Figure how to do it with Element. For example, the below code will keep only the latest 2 messages.
Element root = infoTextPane.getDocument().getDefaultRootElement();
try {
    while(root.getElementCount() > 3){
        Element first = root.getElement(0);
        infoTextPane.getStyledDocument().remove(root.getStartOffset(), first.getEndOffset());
    }
} catch (BadLocationException e1) {
    // FIXME Auto-generated catch block
    e1.printStackTrace();
}


text:
Q: Recommended methods for replacing missing data? We conducted a pre-post attitudinal survey measuring "Attitudes toward STEM" (28-items; α > .90) and "Multi-Ethnic Identity" (12-items; α > .90) among 50 middle schoolers. Students skipped items resulting in incomplete scale scores. Given the small sample size and nature of the data, we plan to use case mean substitution to account for missing data before computing a "mean difference" variable between pre- and post-survey scores. The dependent variable will be mean attitude change and the predictor will be exposure to culturally-responsive STEM curriculum (regression).
The literature is inconclusive in identifying clear cutoffs for the maximum number of items that can be missing per scale/measure and will still allow case mean substitution (values ranged from 20-60%). We are hoping to keep as much data as possible but want to select an appropriate approach.

*

*Is there a better and/or more robust way to approach this problem?

*Are there recommendations for peer-reviewed citations which utilize this approach and/or suggest cutoffs?

A: I would consider case mean substitution inappropriate under any circumstances - unless you've tried everything else and it just makes no difference. Using something simplistic like that (or like taking the median of all respondents on that question or leading out non responders) with even 20% missing sounds highly problematic to me. I doubt you'll find a respectable publication that is based on some proper theoretical or simulation evaluation that would endorse that. Perhaps you'll find something where someone just claims that without having a clue, or based on having done it for one specific example dataset and liking the answer.
Some form of multiple imputation is often a good choice, but if the question responses are on very discrete ordinal scales or are categorical,  you may have to look beyond the very basic vanilla version for normally distributed data. There are probably other similarly performing options that might do something reasonable - e.g. k-nearest neighbour imputation.


text:
Q: Parse through text files and write into CSV I have about 100 different text files in the same format. Each file has observations about certain events at certain time periods for a particular person. I am trying to parse out the relevant information for a few individuals for each of the different text files. Ideally, I want to get parse through all this information and create a CSV file (eventually to be imported into Excel) with all the information I need from ALL the text files. Any help/ideas would be greatly appreciated. I would prefer to use java...but any simpler methods are appreciated.
The log files are structured as below: changed data to preserve private information
|||ID||NAME||TIME||FIRSTMEASURE^DATA||SECONDMEASURE^DATA|| etc...
TIME appears like 20110825111501 for 2011, 08/25 11:15:01 AM

A: Just to parse through the text file and use CSVParser from apache to write to a csv file. Additionally if you want to write in to excel, you can simply use Apache POI or JXL for that.

A: Here are the steps in Java:

*

*Open the file using FileReader

*You could also wrapped the FileReader with BufferedReader and use readLine() method to read the file line by line

*For each line you need to  parse it. You know best the data definition of each line, to help you might be able to use various String functions or Java Regex

*You could do the same thing for the Date. Check if you could utilize DateFormat

*Once you parse the data, you could start building your CSV File using CSVParser mentioned above or write it your own using FileOutputStream

*When you are ready to to convert to Excel, you could use Apache POI for Excel
Let me know if you need further clarification

A: You can use SuperCSV to parse the file into a bean and
also to create a csv-file.


text:
Q: How to prevent ipFlood Explanation
There is a website with limits on IP addresses,
but people have started using tools such as:
https://addons.mozilla.org/en-US/firefox/addon/ipflood/
I believe this tool overwrites headers to "Simulate the use of a series of proxy changing at each new connection."
Questions

*

*Is there any simple way to prevent such abuses with PHP or anything else on the server side? (we have root access to the server and can install packages)

*Will preventing proxy access to the website also prevent access of such users with such tools?

A:
I believe this tool overwrites headers to "Simulate the use of a series of proxy changing at each new connection."

More specifically, this extension sets fake X-FORWARDED-FOR, VIA, and CLIENT-IP headers on requests. It does not modify the actual source IP of the request.
The workaround is simple. Don't use the values of those headers unless your site is behind a load balancer that uses them. (Chances are that it isn't.)


text:
Q: multiple select box using v-for I have multiple select boxes which are rendered using a v-for loop, what I am trying to do is to store each option value for each select box in an array but when I select an option it only stores the chosen option, not multiple options
 <template v-for="(gettailor) in gettailors" :key="gettailor.id">

{{ gettailor.names }}

                            <select   class="form-select shadow-none" id="tailors"  v-model="tailors"   required>

                                <template v-for="(item) in gettailor.tailor" :key="item.id">

                                <option :value="item.id">{{ item.tailor }}</option>

                                </template>
                            </select>

                            Choose {{ gettailor.names }}

                    </template>

A: I think tailors should be an object, then you bind the select value to a value in the object:
<select
  class="form-select shadow-none"
  id="tailors[]"            <-------- generates several selects with same id
  v-model="tailors[gettailor.id]"  <--------- bind to object value
  required
>

Of course you can also use an array, but it does not work well with reactivity if you use loop index as key (if order changes, you don't know where the values came from), and if you use tailor id, you get a sparse array, which is probably hard to work with.


text:
Q: C++ contacts handler program with own dynamic template vector class I am working on a project what I have to do for the university. I want to do a simple contants program, my goal is, that I can add as many names, as I want, furthermore as many properties for each names as I want. Every proberty has a header, (e.g.:"Name") and a value (e.g.:"Jane").
I have already did it, with the included STL vector class, but I ought to do it without STL libraries, so I have written my own. Of course, it isn't working now, a program freezes, before it can begin. In connection with the error, I have found that the "a_row" class has been called twice during the program but I have no idea why.
I would like to apoligise for copying here a lot rows, but I have been searching the problem for 3 days it nobody could find the problem, around me. Here are the code, I have simplified it, for you :)
The vector class:
#include <iostream>
#include <string>

template <class T>
class vector{
    T* my_array;
    unsigned int vector_size;
public:
    vector():vector_size(0){}
    ~vector(){
        delete[] my_array;
    }
vector(const vector& rhs){
    vector_size = rhs.size();
    my_array = new T[vector_size];
    for(unsigned int i=0;i<vector_size;i++) my_array[i] = rhs[i];
}
T& operator[](unsigned int i) {return my_array[i];}
const T& operator[](unsigned int i) const {return my_array[i];}

vector& operator=(const vector& rhs){
    if (&rhs!=this){
        delete[] my_array;
        vector_size = rhs.size();
        my_array = new T[vector_size];
        for(unsigned int i=0;i<vector_size;i++) my_array[i] = rhs[i];
    }
    return *this;
}

void push_back(const T& rhs){
    T* tmp = new T[vector_size+1];
    for(unsigned int i=0;i<vector_size;i++)
        tmp[i] = my_array[i];
    tmp[vector_size] = rhs;
    delete[] my_array;
    my_array = tmp;
    vector_size++;
}

unsigned int size() const{return vector_size;}

void erase(unsigned int x){
    if (vector_size>0){
        T* tmp = new T[vector_size-1];
        unsigned int counter = 0;
        for (unsigned int i=0;i<vector_size;i++){
            if (i!=x) {
                tmp[counter++] = my_array[i];
            }
        }
        delete[] my_array;
        my_array = tmp;
        vector_size--;
    }
}
};

Here are the classes of the contacts program:
class a_row{
    std::string header;
    std::string value;
public:
    a_row(const std::string& h="No name",const std::string& v="No "):header(h),value(v){}

    std::string geth() const{return header;}
    std::string getv() const{return value;}

};

class a_name_card{
    vector<a_row> properties;
public:
    a_name_card(const std::string& f1="No name",const std::string& e1="No name"){
        properties.push_back(a_row(f1,e1));
    }

    unsigned int size()const{return properties.size();}

    a_row& get_a_row(int i){return properties[i];}

    void add(const std::string& f1="No name",const std::string& e1="No name"){
        properties.push_back(a_row(f1,e1));
    }

};

class list_of_name_cards{
    vector<a_name_card> array_of_names;
public:
    a_name_card& operator[](int i){return array_of_names[i];}

    void add(const std::string& f1="No name", const std::string& e1="No name"){
        array_of_names.push_back(a_name_card(f1,e1));
    }

    unsigned int size() const{return array_of_names.size();}
};

And here are the simple main program:
int main(){
    list_of_name_cards names;
    names.add("Name","Jane");
    return 0;
}

I would appreciate any kind of helps and thanks again if you've read it.
p.s.: Sorry for my english but English is not my mother tongue.

A: You need to initialize your variables:
vector():vector_size(0){}

What about my_array?
vector():my_array(nullptr), vector_size(0){}


text:
Q: How can i save the desired data on EditText by using onSaveInstanceState() and onRestoreInstanceState() methods I am trying to design an Android application, in that application i have sent the data from First Activity to Second Activity. In the Second Activity I am using this code

 @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

to save the data when application moves to landscape to portrait mode but in my application even i am using both of these but the data is not being saved. On rotation the data is getting destroyed which application is having in EditText View.
Please Check the below code, give the suggestions where i am doing the mistake to save the data
MainActivity.java

public class MainActivity extends AppCompatActivity {
    EditText name,age;
    TextView text_name,text_age;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name=(EditText) findViewById(R.id.name);
        age=(EditText) findViewById(R.id.age);
        text_name=(TextView) findViewById(R.id.name_edit);
        text_age=(TextView) findViewById(R.id.name_age);
        btn=(Button) findViewById(R.id.click);

        //Button Click to send data to another activity

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle=new Bundle();
                String user_name=name.getText().toString();
                String user_age=age.getText().toString();
                bundle.putString("UName",user_name);
                bundle.putString("UAge",user_age);
                Intent intent=new Intent(MainActivity.this,SecondClass.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

}

SecondClass.java

public class SecondClass extends Activity {
    EditText name,age;
    TextView text_name,text_age;
    String namer,ager;
    private String savedName,savedAge;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity_layout);
        name=(EditText) findViewById(R.id.name);
        age=(EditText) findViewById(R.id.age);
        text_name=(TextView) findViewById(R.id.name_edit);
        text_age=(TextView) findViewById(R.id.name_age);

        if (savedInstanceState!=null)
        {
            savedInstanceState.get(savedName);
            name.setText(savedName);
            savedInstanceState.get(savedAge);
            age.setText(savedAge);
        }
        if (savedInstanceState==null)
        {
            Intent i=getIntent();
            Bundle bundle=i.getExtras();
            namer=bundle.getString("UName");
            name.setText(namer);
            ager=bundle.getString("UAge");
            age.setText(ager);
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(savedName,namer);
        outState.putString(savedAge,ager);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState!=null)
        {
            savedInstanceState.get(savedName);
            name.setText(savedName);
            savedInstanceState.get(savedAge);
            age.setText(savedAge);
        }
        if (savedInstanceState==null)
        {
            Intent i=getIntent();
            Bundle bundle=i.getExtras();
            namer=bundle.getString("UName");
            name.setText(namer);
            ager=bundle.getString("UAge");
            age.setText(ager);
        }

    }
}

A: You put and get value in saved instance with a key, and first put your data in
'outState' then call '

super.onSaveInstanceState(outState);

try this:

public class SecondClass extends Activity {
    private static final String SAVED_NAME="savedName";
    private static final String SAVED_AGE="savedAge";
    EditText name,age;
    TextView text_name,text_age;
    String namer,ager;
    private String savedName,savedAge;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity_layout);
        name=(EditText) findViewById(R.id.name);
        age=(EditText) findViewById(R.id.age);
        text_name=(TextView) findViewById(R.id.name_edit);
        text_age=(TextView) findViewById(R.id.name_age);

        if (savedInstanceState!=null)
        {
            namer  = savedInstanceState.get(SAVED_NAME);
            name.setText(namer);
            ager = savedInstanceState.get(SAVED_AGE);
            age.setText(ager);
        }
        if (savedInstanceState==null)
        {
            Intent i=getIntent();
            Bundle bundle=i.getExtras();
            namer=bundle.getString("UName");
            name.setText(namer);
            ager=bundle.getString("UAge");
            age.setText(ager);
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString(savedName,namer);
        outState.putString(savedAge,ager);
        super.onSaveInstanceState(outState);

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState!=null)
        {
            namer  = savedInstanceState.get(SAVED_NAME);
            name.setText(namer);
            ager = savedInstanceState.get(SAVED_AGE);
            age.setText(ager);
        }
        if (savedInstanceState==null)
        {
            Intent i=getIntent();
            Bundle bundle=i.getExtras();
            namer=bundle.getString("UName");
            name.setText(namer);
            ager=bundle.getString("UAge");
            age.setText(ager);
        }

    }
}


text:
Q: Mule - unable to route message based on http.status I'm trying to create a choice router in my Mule application that will do something based on the response code received from an HTTP Outbound Endpoint. My config is as below - I followed the answers provided in this previous question:
<set-variable variableName="http.disable.status.code.exception.check" value="true" doc:name="Variable"/>
<http:outbound-endpoint exchange-pattern="request-response" host="localhost" port="8081" path="hello" contentType="text/xml" method="POST" doc:name="HTTP"/>

<logger level="INFO" doc:name="Logger"/>

<choice doc:name="Choice">
    <when expression="#[message.inboundProperties['http.status']] == 200">
        <logger level="DEBUG" message="HTTP SUCCESS" doc:name="Debug"/>
    </when>
    <otherwise>
        <logger level="DEBUG" message="HTTP FAILURE" doc:name="Debug"/>
    </otherwise>
</choice>

Yet, I get the following error:
********************************************************************************
Message               : Execution of the expression "message.inboundProperties['http.status']] == 20" failed. (org.mule.api.expression.ExpressionRuntimeException). Message payload is of type: ReleasingInputStream
Code                  : MULE_ERROR--2
--------------------------------------------------------------------------------
Exception stack is:
1. [Error: could not access: ]; in class: java.lang.String]
[Near : {... message.inboundProperties['htt ....}]
             ^
[Line: 1, Column: 1] (org.mvel2.PropertyAccessException)
  org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer:690 (null)
2. Execution of the expression "message.inboundProperties['http.status']] == 20" failed. (org.mule.api.expression.ExpressionRuntimeException)
  org.mule.el.mvel.MVELExpressionLanguage:218 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/expression/ExpressionRuntimeException.html)
3. Execution of the expression "message.inboundProperties['http.status']] == 20" failed. (org.mule.api.expression.ExpressionRuntimeException). Message payload is of type: ReleasingInputStream (org.mule.api.MessagingException)
  org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor:35 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/MessagingException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
[Error: could not access: ]; in class: java.lang.String]
[Near : {... message.inboundProperties['htt ....}]
             ^
[Line: 1, Column: 1]
    at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.getBeanProperty(ReflectiveAccessorOptimizer.java:690)
    at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.getBeanPropertyAO(ReflectiveAccessorOptimizer.java:472)
    at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.compileGetChain(ReflectiveAccessorOptimizer.java:374)
    + 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************

The http.status inbound property is clearly in the scope as the output from my logger immediately before the choice router is as below:
{
  id=dece5e82-db50-11e3-94e6-9552f33cb636
  payload=org.mule.transport.http.ReleasingInputStream
  correlationId=<not set>
  correlationGroup=-1
  correlationSeq=-1
  encoding=UTF-8
  exceptionPayload=<not set>

Message properties:
  INVOCATION scoped properties:
    http.disable.status.code.exception.check=true
    http.method=POST
  INBOUND scoped properties:
    Connection=true
    Content-Length=0
    Content-Type=text/plain
    Date=Wed, 14 May 2014 11:16:53 +0100
    Keep-Alive=true
    Server=Mule Core/3.4.0
    http.headers={Date=Wed, 14 May 2014 11:16:53 +0100, Content-Length=0, Keep-Alive=true, Connection=true, Content-Type=text/plain, Server=Mule Core/3.4.0}
    http.method=POST
    http.query.params={}
    http.query.string=
    http.request=http://localhost:8081/hello
    http.status=200
    http.version=HTTP/1.1
  OUTBOUND scoped properties:
    MULE_ENCODING=UTF-8
    MULE_SESSION=rO0ABXNyACNvcmcubXVsZS5zZXNzaW9uLkRlZmF1bHRNdWxlU2Vzc2lvbi7rdtEW7GGKAwAEWgAFdmFsaWRMAA1mbG93Q29uc3RydWN0dAAmTG9yZy9tdWxlL2FwaS9jb25zdHJ1Y3QvRmxvd0NvbnN0cnVjdDtMAAJpZHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wAD3NlY3VyaXR5Q29udGV4dHQAJ0xvcmcvbXVsZS9hcGkvc2VjdXJpdHkvU2VjdXJpdHlDb250ZXh0O3hwAXB0ACRkZWJiYzBjYi1kYjUwLTExZTMtOTRlNi05NTUyZjMzY2I2MzZwc3IAJWphdmEudXRpbC5Db2xsZWN0aW9ucyRTeW5jaHJvbml6ZWRNYXAbc/kJS0s5ewMAAkwAAW10AA9MamF2YS91dGlsL01hcDtMAAVtdXRleHQAEkxqYXZhL2xhbmcvT2JqZWN0O3hwc3IAJG9yZy5tdWxlLnV0aWwuQ2FzZUluc2Vuc2l0aXZlSGFzaE1hcJ3R2e9nRc4AAwAAeHB3DD9AAAAAAAAQAAAAAHhxAH4ACXh4
  SESSION scoped properties:
}

Can anyone identify why I'm having this issue? Thanks in advance.

A: You need to place your operator inside the mule expression brackets like so:
<when expression="#[message.inboundProperties['http.status'] == '200']">


text:
Q: AS3: Sandbox violation when trying to load an off-site swf I'm trying to load an swf placed on Amazon S3 (b.com) into an swf on a different domain (a.com), and it throws this error
SecurityError: Error #2121: Security sandbox violation: Loader.content:http://www.a.com/loader.swf cannot accesshttp://b.com/loadee.swf. This may be worked around by calling Security.allowDomain.
at flash.display::Loader/get content()

Both a.com and b.com have a crossdomain.xml on their root that looks like
<cross-domain-policy>
  <site-control permitted-cross-domain-policies="all"/>
  <allow-access-from domain="*"/>
  <allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>

The swf I'm trying to load (b.com/loadee.swf) has been generated by software, so I can't add Security.allowDomain("*") to it or anything like that.
Can I load this swf in some way, or am I stuck using a.com to host everything? I also want loader.swf and loadee.swf to be able to communicate (pass vars and make function calls)
if that's possible. This is what I have in loader.swf
Security.allowDomain("*");
Security.allowInsecureDomain("*");
Security.loadPolicyFile("http://b.com/crossdomain.xml");
var loaderContext:LoaderContext = new LoaderContext();
loaderContext.checkPolicyFile = true;
loaderContext.allowCodeImport = true;
var loader:Loader = new Loader();
loader.load(new URLRequest("http://b.com/loadee.swf"), loaderContext);

If anyone has any ideas I'd really appreciate it.

A: If the loadee.swf is not copyrighted material, you can add bytecodes to it using flasm or if you were an expert you can do it using any HEX editor.
P.S: Don't forget, Cross-Domain Policy is on port 843.


text:
Q: After H2-Upgrade i did an upgrade of h2-database in my project and now it fails with this exception:
Caused by: org.springframework.beans.PropertyBatchUpdateException: Failed properties: Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [org.h2.Driver]
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:121) ~[spring-beans-4.2.8.RELEASE.jar:4.2.8.RELEASE]
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:75) ~[spring-beans-4.2.8.RELEASE.jar:4.2.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1518) ~[spring-beans-4.2.8.RELEASE.jar:4.2.8.RELEASE]
    ... 66 common frames omitted

Here is my spring-context.xml:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${db.driver}" />
        <property name="url" value="${db.url}" />
        <property name="username" value="${db.username}" />
        <property name="password" value="${db.password}" />
    </bean>

And here my jdbc.properties where the spring-context loads the data to initialize my datasource:
db.driver=org.h2.Driver
db.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
db.username=sa
db.password=

db.memurl=jdbc:h2:mem:test

All works fine with h2-version 1.4.179 but fails with 1.4.196. Used Spring Version is 4.2.8.
I don't get it why it fails... something has change in H2, but i don't know what... anybody an idea?
--update--
Here all dependencies from pom.xml (spring-version is 4.2.8) and this is a common project for all my test dependencies (packaging is pom), it is used by several projects. I use h2-database as in memory database only for testing:
<dependencies>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.11</version>
            <exclusions>
                <exclusion>
                    <artifactId>junit</artifactId>
                    <groupId>junit</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.196</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-logging</artifactId>
                    <groupId>commons-logging</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.10.19</version>
        </dependency>
    </dependencies>
    <packaging>pom</packaging>

A: Try to add
<scope>runtime</scope>

or
<scope>test</scope>

if you are going to use h2 for test only
to the h2 dependency


text:
Q: How to pass File in electron contextBridge I could not find the docs on electron contextBridge and what is done to the API arguments but obviously something is done.
This is the gist of it:
// preload.js
contextBridge.exposeInMainWorld('fileCache', {
  put (file) {
    console.log(file) // ==> {}
  }
})

// web app
window.fileCache.put(new File([], 'foo.txt'))

How should I pass File or any Blob or Buffer argument ? (making a string is not an option for performance reasons: 20+ Mb files...)


text:
Q: PHP semaphore (in same browser) If I want prevent multiple execution of a code in same browser, why PHP semaphore not working in same browser or another browser tab?
https://www.php.net/manual/en/intro.sem.php
This code work only in different browsers, why not working in same browser, when i execute script simultaneously in same browser (php7.4-fpm + nginx)
$semaphore_key = 25;
$semaphore_max = 1;
$semaphore_permissions = 0666;
$semaphore_autorelease = 1;
$semaphore = sem_get($semaphore_key, $semaphore_max, $semaphore_permissions, $semaphore_autorelease);

if(sem_acquire($semaphore, true) === false) {
    echo "error";
    exit();
}else{
    echo "ok\n";
}

sleep(30);
sem_release($semaphore);

A: I don't understand why but it is caused by the Chrome browser cache, the response from the server does not contain any cache headers, when I disable browser cache, it works like expected


text:
Q: Are array elements identifiers in java? Java documentation says that an identifier is "The name of an item in a program written in the Java(TM) programming language," but this doesn't specify if something of the form myList[0] counts as a name for the first element in myList. So, does myList[0] count as an identifier?

A: myList[0] is not an identifier. It is an array access expression. The identifier in this case is myList.

A: No, myList is the identifier to the array, myList[0] refers to the element inside index 0 of that array, which a reference to a type of value.

A: The ultimate place to check these definitions is the JLS (Java Language Specification) rather than a tutorial, which is naturally less formal.
According to said specification, an identifier does not include brackets. Therefore myList[0] is not an identifier.


text:
Q: Agregar datos entre tablas relacionadas en Laravel Quiero saber si existe una manera mas optima de hacer lo que quiero hacer,
Tengo una tabla A que esta conformada de acuerdo al modelo que les voy a mostrar:
class M2m extends Model
{
protected $table = 'm2ms';
public $timestamps = true;

protected $casts = [
    'id_customer' => 'int',
    'dias_contrato' => 'int',
    'dias_pendiente_contrato' => 'int',
    'pausar_contrato' => 'int'
];

protected $dates = [
    'fecha_inicio_contrato',
    'fecha_fin_contrato',
    'fecha_pausa_contrato'
];

protected $fillable = [
    'id_customer',
    'nombre_cliente',
    'numero_serie',
    'numero_telefono_sim',
    'fecha_inicio_contrato',
    'fecha_fin_contrato',
    'dias_contrato',
    'dias_pendiente_contrato',
    'pausar_contrato'
];

public function estados()
{
    return $this->belongsToMany(Estado::class, 'estados_m2ms')
                ->withPivot('id')
                ->withTimestamps();
}

}
Perfecto...luego tengo una tabla B que tiene estos estado de acuerdo al modelo:
class EstadosM2m extends Model
{
protected $table = 'estados_m2ms';
public $incrementing = false;
public $timestamps = true;

protected $casts = [
    'id' => 'int',
    'm2m_id' => 'int',
    'estado_id' => 'int'
];

protected $fillable = [
    'm2m_id',
    'estado_id'
];

public function estado()
{
    return $this->belongsTo(Estado::class);
}

public function m2m()
{
    return $this->belongsTo(M2m::class);
}

}
Como ya se imaginaron, la tabla A es un articulo que una vez que se registra, se debe registrar el estado en la tabla B, ese articulo con el paso del tiempo sufrirá transiciones de estados, por ello se registra como lo ven.
Ahora bien mi pregunta:
Se puede hacer en eloquent que al momento de registrar el articulo, en este caso tabla A en el mismo proceso se pueda registrar el m2m_id de la tabla B que es el atributo que se relaciona con el ID de la tabla A?? a ver, yo he hecho esto de manera rudimentario es decir, primero registro los datos en A, después busco el ID y lo guardaría en la tabla B, pero quiero saber si existe un método (que desconozco completamente) para poder hacer ese registro de una manera diferente.
Espero me puedan entender y me puedan dar alguna idea. Gracias.
/EDITADO/
Lo que llevo hecho es esto
            $tarjetaM2M = new M2m();
            $tarjetaM2M->nombre_cliente = $nombrecliente;
            $tarjetaM2M->id_customer = $id_customer;
            $tarjetaM2M->numero_serie = $numero_serie;
            $tarjetaM2M->numero_telefono_sim = $numero_telefono_sim;
            $tarjetaM2M>fecha_inicio_contrato=
            M2m::ConvertirFormatoFechaCarbon($fecha_inicio_contrato);
            $tarjetaM2M->fecha_fin_contrato =
            M2m::ConvertirFormatoFechaCarbon($fecha_fin_contrato);
            $tarjetaM2M->dias_contrato = $diasdecontrato;
            $tarjetaM2M->save();

            $idTarjetaM2M = M2m::select('id')
                ->orderBy('id','desc')
                ->take(1)
                ->get();

                $idTarjeta='';
                foreach ($idTarjetaM2M as $id)
                {
                    $idTarjeta=$id->id;
                }

            if($idTarjetaM2M)
            {
                $estados = new EstadosM2m();
                $estados->m2m_id = $idTarjeta;
                $estados->estado_id = $estado_id;
                $estados->save();

            }

Pero se que esto se puede hacer mejor.

A: ya lo he resuelto, dejo la solucion si en el futuro alguien tiene un problema similar:
Despues de hacer el save(), en este caso el primer save era muy simple:
      /*Asi es como se agregan datos a tablas pivotes*/
            $estado = Estado::find($estado_id);
            $estado->m2m()->attach($tarjetaM2M);

Es decir que ya esto que les mostre, aunque funciona igual de bien, ya no seria necesario ademas de que es mas optimo:
$idTarjetaM2M = M2m::select('id')
            ->orderBy('id','desc')
            ->take(1)
            ->get();

            $idTarjeta='';
            foreach ($idTarjetaM2M as $id)
            {
                $idTarjeta=$id->id;
            }

        if($idTarjetaM2M)
        {
            $estados = new EstadosM2m();
            $estados->m2m_id = $idTarjeta;
            $estados->estado_id = $estado_id;
            $estados->save();

        }

Explicación:
Es importante tener bien definidas las relaciones a la tabla intersección o pivote desde las tablas principales, ya con eso simplemente se aplica la solución.


text:
Q: How can I load a stylesheet through ajax AND have a callback when the loading is done I need to load a bunch of CSS files through ajax and call an animation when the stylesheet has finished loading, otherwise the animation will fail.
What I have done so and used to work pretty well until I came accross doing this cross-domain is this:
$.get(resource.url, {cache:true}, function(css) {
    //Now that the stylesheet is in the browser cache, it will load instantly:

    $("head").append($("<link>",{
       rel: "stylesheet",
       type: "text/css",
       href: resource.url
    }));

}).then(function(){
   //Animation here that depends on the loaded css
});

This works fine as long as resource.url is on the same domain. Once I try to load the css from another domain $.get will fail like this:
XMLHttpRequest cannot load https://example.com/style.css. Origin https://example.com is not allowed by Access-Control-Allow-Origin.

So I have tried to add CORS into the header through .htaccess:
<IfModule mod_headers.c>
    #cross domain access is okay for resources (#107)
    <FilesMatch "\.(css|js)$">
        Header add Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>

This adds the CORS header to all CSS and JS resources.
For some reason CORS doesn't seem to have an effect on either chrome or firefox (newest versions).
I also came to notice that same domain policy is not enforced when doing $.getScript for js files, but it is for $.get:
$.get("https://example.com/script.js", {cache: false}, $.noop, "script");

//works regardless of CORS

but:
$.get("https://example.com/script.js", {cache: false}, $.noop);

//does not work (cross domain policy violation)

So since CORS is not widely supported and doesn't even seem solve the problem for a modern browser, I need something that behaves like $.getScript, but for CSS stylesheets.
It needs to be asynchronous and have a callback mechanism.
Any ideas? Thanks in advance...

A: $.get uses Ajax, which must obey the Same-Origin Policy.
$.getScript normally uses Ajax, but it also has a fallback option for cross-domain use only.  Scripts imported via <script> tag are not subject to Same-Origin rules, so jQuery just adds a <script> tag to the page and sets its src attribute to the requested script URL.
The same exemption is made for CSS resources loaded in through <link> tags.  In a perfect world, you should be able to 1) make a new <link> element, 2) set its href attribute to the right URL and 3) listen for a load event on that element.  I've added a callback to this solution from the jQuery forums:
// note: non-compatible example code, see below for better code
jQuery.getCSS = function( url, media, callback ) {
    jQuery( document.createElement('link') ).attr({
        href: url,
        media: media || 'screen',
        type: 'text/css',
        rel: 'stylesheet'
    }).appendTo('head')
    .on("load", callback);
};

One small problem here: it doesn't work cross-browser.  <link> tags do not fire load events in all browsers -- see the jQuery bug report  for the $.getCSS function that could have been.
So, the general-case workaround is a bit insane: add the CSS URL as the source of a new <img> tag and listen for its onerror handler:
// correct code!
jQuery.getCSS = function( url, media, callback ) {
    jQuery( document.createElement('link') ).attr({
        href: url,
        media: media || 'screen',
        type: 'text/css',
        rel: 'stylesheet'
    }).appendTo('head');

    jQuery( document.createElement('img') ).attr('src', url)
    .on("error", callback);
};

You could also add a bit of optimization and listen for load event on the <link> (for browsers that support it) and an error event on the <img> (for those that don't), and put some logic in place to ensure the callback is only ever called once, in case both events occur.
As for making $.getCSS return a deferred object, that's a bit out of my area of expertise, but there's no theoretical reason why it couldn't be done.

A: Put together my own implementation of apsillers' answer using a deferred rather than creating a jQuery plugin.
fetchStyleSheet(url, media = 'screen') {
    let $dfd = $.Deferred(),
        finish = () => $dfd.resolve(),
        $link = $(document.createElement('link'))
            .attr({
                media,
                type: 'text/css',
                rel: 'stylesheet'
            })
            .on('load', 'error', finish)
            .appendTo('head'),
        $img = $(document.createElement('img'))
            .on('error', finish); // Support browsers that don't fire events on link elements

    $link[0].href = $img[0].src = url;
    return $dfd.promise();
}

fetchStyleSheet('/url/to/my/stylesheet.css').done(() => {
    // Stuff after the sheet has loaded
});

This topic is several years old, and I dunno if the backup event on the img is still necessary, but it seemed fairly trivial to implement.
For my specific use-case, I don't actually care if the sheet failed to load so both cases are resolved. If you wanted to handle the cases separately, you could pass an argument to the finish handler to resolve/reject appropriately.


text:
Q: Tomcat shutdown due to flow control mechanism of active mq We have an application that is deployed on a tomcat server.
The application produces and consumes messages on an activemq server.
We had an issue recently that caused triggered flow control on active mq message producers due to 100% store percent used. (http://activemq.apache.org/producer-flow-control.html)
Somehow this cause our applciations on tomcat servers to shutdown.

INFO [main] org.apache.catalina.core.StandardServer.await A valid shutdown command was received via the shutdown port. Stopping the Server instance.

It seems something triggered a graceful shutdown, but I'm not sure how it's connected to the activemq issue. But the shutdown issue was resolved when we resolved the active mq issue.
How are these connected?
Could it be that the producer control flow caused jms connections to pile up causing the tomcat server to shutdown itself?


text:
Q: Tikz - draw bracket below a matrix of cell I have this array:
\documentclass[crop,tikz,convert={outext=.svg,command\unexpanded{pdf2svg \infile\space\outfile}},multi=false]{standalone}
\usepackage{xcolor}
\usepackage{tikz}
\usetikzlibrary{positioning, matrix, fit, arrows.meta, shapes.misc, backgrounds}

\definecolor{customBlue}{HTML}{0063A2}
\definecolor{customAzure}{HTML}{C4EDF9}
\definecolor{customGreen}{HTML}{009053}
\definecolor{customPurple}{HTML}{812C7C}
\definecolor{customBrown}{HTML}{943227}
\definecolor{customViolet}{HTML}{3F367B}
\definecolor{customPink}{HTML}{DA0F70}
\definecolor{bracket}{HTML}{00A3DA}

\begin{document}
  \begin{tikzpicture}[x=1cm,y=1.5cm,]
    \matrix (C) [
      matrix of nodes,
      nodes={draw, minimum size=6mm},
      inner sep=6pt, outer sep=0pt,
      column sep=-\pgflinewidth
    ] at (0, 3){
      $\textcolor{customBlue}{2}, sl^1_0, ic^1_0$ &
      $\textcolor{orange}{31}, sl^1_1, ic^1_1$ &
      $\textcolor{customBrown}{102}, sl^1_2, ic^1_2$ &
      $\textcolor{customPink}{187}, sl^1_3, ic^1_3 $
      \\
    };
    \node[above=3pt of C-1-1]{$levels[1]$};
    \node[below=3pt of C-1-1]{$0$};
    \scoped[on background layer] {
      \node[fill=customAzure, inner sep=0mm, fit=(C-1-2.north east)(C-1-2.south west) ] {};
    }
  \end{tikzpicture}
\end{document}

How can I draw a bracket between node 2 and node 102? The result is something like:

A: One possibility is the TikZ library decorations.pathreplacing which have such decoration. You need to add this library, an optional style for the brace (look at my tikzset) and then just draw the brace (last \draw).
Complete code (your code with the above additions):
\documentclass[crop,tikz]{standalone}
\usepackage{xcolor}
\usepackage{tikz}
\usetikzlibrary{positioning, matrix, fit, arrows.meta, shapes.misc, backgrounds,
                decorations.pathreplacing} % <-- we need this library for the underbrace

\definecolor{customBlue}  {HTML}{0063A2}
\definecolor{customAzure} {HTML}{C4EDF9}
\definecolor{customGreen} {HTML}{009053}
\definecolor{customPurple}{HTML}{812C7C}
\definecolor{customBrown} {HTML}{943227}
\definecolor{customViolet}{HTML}{3F367B}
\definecolor{customPink}  {HTML}{DA0F70}
\definecolor{bracket}     {HTML}{00A3DA}

\tikzset%
{% this sytle provides the underbrace
   myunderbrace/.style={bracket,decorate,decoration={brace,raise=4mm,amplitude=6pt,mirror}},
}

\begin{document}
  \begin{tikzpicture}[x=1cm,y=1.5cm,]
    \matrix (C) [
      matrix of nodes,
      nodes={draw, minimum size=6mm},
      inner sep=6pt, outer sep=0pt,
      column sep=-\pgflinewidth
    ] at (0, 3){
      $\textcolor{customBlue}{2}, sl^1_0, ic^1_0$ &
      $\textcolor{orange}{31}, sl^1_1, ic^1_1$ &
      $\textcolor{customBrown}{102}, sl^1_2, ic^1_2$ &
      $\textcolor{customPink}{187}, sl^1_3, ic^1_3 $
      \\
    };
    \node[above=3pt of C-1-1]{$levels[1]$};
    \node[below=3pt of C-1-1]{$0$};
    \scoped[on background layer] {
      \node[fill=customAzure, inner sep=0mm, fit=(C-1-2.north east)(C-1-2.south west) ] {};
    }
    \draw[myunderbrace] (C-1-1.south west) -- (C-1-3.south east);
  \end{tikzpicture}
\end{document}

And the picture:

Of course, the nicematrix that suggests projetmbc is another good possibility.

A: A wee bit more fancy (calligraphic) brace, used matrix of math nodes, local modifying cell style and use of labels enables to write simpler and shorter code:
\documentclass[border=3.141592]{standalone}
\usepackage{tikz} % it load also xcolor
\usetikzlibrary{decorations.pathreplacing,%
                    calligraphy,% had to be after decorations.pathreplacing
                matrix,
                positioning}

\definecolor{customBlue}  {HTML}{0063A2}
\definecolor{customAzure} {HTML}{C4EDF9}
\definecolor{customBrown} {HTML}{943227}
\definecolor{customPink}  {HTML}{DA0F70}

\tikzset%
{% this style provides the underbrace
BC/.style args = {#1/#2}{% Brace Calligraphic
        decorate,
        decoration={calligraphic brace, amplitude=6pt,
        raise=#1},% for mirroring of brace
        thick,
        pen colour={#2}  },
every label/.style = {draw=none, inner sep=0pt, font=\small}
}

\begin{document}
    \begin{tikzpicture}
\matrix (C) [matrix of math nodes,
             nodes={draw, minimum size=6mm},
             inner sep=6pt, outer sep=0pt,
             column sep=-\pgflinewidth,
             ]
{
|[label={\textit{levels}[1]}, label=below:0]|
                                \textcolor{customBlue}{2},      sl^1_0, ic^1_0  &
  |[fill=customAzure]|          \textcolor{orange}{31},  sl^1_1, ic^1_1    &
\textcolor{customBrown}{102},   sl^1_2, ic^1_2  &
                                \textcolor{customPink}{187},    sl^1_3, ic^1_3  \\
};
\draw[BC=3ex/red]  (C-1-3.south east) -- (C-1-1.south west);
  \end{tikzpicture}
\end{document}


text:
Q: Stm32f303 freertos I try to run freertos on stm32f303 discovery.
I include all header and source files from freertos archive downloaded from official web site. Also I include portable files from folder /GCC/ARM_CM4F.
I use codesourcery lite compiler. And when I try to compile project i get error:
In file included from freertos/inc/portable.h:321:0,
                 from freertos/inc/FreeRTOS.h:100,
                 from freertos/src/croutine.c:66:
freertos/inc/portmacro.h:167:7: error: missing binary operator before token "long"

portmacro.h's 167-172 strings:
    #if( configMAX_PRIORITIES > 32 )
        #error configUSE_PORT_OPTIMISED_TASK_SELECTION can only be set to 1 when configMAX_PRIORITIES is less than or equal to 32.  It is very rare that a system requires more than 10 to 15 difference priorities as tasks that share a priority will time slice.
    #endif

Searching in Google give that there is preprocessor error but it don't get me point what I should to do.
My Makefile settings:
# Set Libraries
LIBS        = -lm -lc

###################################################
# Set Board
MCU         = -mthumb -mcpu=cortex-m4
FPU         = -mfpu=fpv4-sp-d16 -mfloat-abi=softfp
DEFINES     = -DSTM32F3XX -DUSE_STDPERIPH_DRIVER
DEFINES     += -DUSE_DEFAULT_TIMEOUT_CALLBACK

# Set Compilation and Linking Flags
CFLAGS      = $(MCU) $(FPU) $(DEFINES) $(INCLUDES) \
            -g -Wall -std=gnu90 -O0 -ffunction-sections -fdata-sections
ASFLAGS     = $(MCU) $(FPU) -g -Wa,--warn -x assembler-with-cpp
LDFLAGS     = $(MCU) $(FPU) -g -gdwarf-2\
            -Tstm32f30_flash.ld \
            -Xlinker --gc-sections -Wl,-Map=$(PROJ_NAME).map \
            $(LIBS) \
            -o $(PROJ_NAME).elf

Where I am mistaken?

A: The compiler is telling you the C pre-processor does not understand the definition of configMAX_PRIORITIES.  Look at the definition in FreeRTOSConfig.h, I suspect it includes a cast that the pre-processor does not understand.  Remove the cast and it will probably be ok.


text:
Q: Cmake: pkg_check_modules error: Package '...', required by 'virtual:world', not found I am trying to build a c++ project with Netbeans in Windows but during the pre-built process an error relating to the CMakeLists I used comes out. Here is the error output:
cd 'E:\Yifan\Hiwi-FSD\FluCo1\Sourcecode\branch_HighLevelUmstrukturierung\High-Level\FCU-Interface\build-dev'
C:/msys64/mingw64/bin/cmake.exe -G Unix Makefiles -DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_COMPILER=E:/Yifan/Hiwi-FSD/FluCo1/Sourcecode/branch_HighLevelUmstrukturierung/High-Level/FCU-Interface/nbproject/private/tools/localhost/MinGW_1/gcc.exe -DCMAKE_CXX_COMPILER=E:/Yifan/Hiwi-FSD/FluCo1/Sourcecode/branch_HighLevelUmstrukturierung/High-Level/FCU-Interface/nbproject/private/tools/localhost/MinGW_1/g++.exe -DCMAKE_C_FLAGS_DEBUG=-g3 -gdwarf-2 -DCMAKE_CXX_FLAGS_DEBUG=-g3 -gdwarf-2 -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DPROJECT_SUFFIX=-dev -DPKG_CONFIG_USE_CMAKE_PREFIX_PATH=TRUE -DCMAKE_PREFIX_PATH=E:\Yifan\Hiwi-FSD\FluCo1\Libraries\fsd-libs\trunk\build-dev\install ..
-- SVN Revision Number is
-- FCU-Interface-dev PROJECT_SOURCE_DIR = E:/Yifan/Hiwi-FSD/FluCo1/Sourcecode/branch_HighLevelUmstrukturierung/High-Level/FCU-Interface
-- FCU-Interface-dev Build directory = E:/Yifan/Hiwi-FSD/FluCo1/Sourcecode/branch_HighLevelUmstrukturierung/High-Level/FCU-Interface/build-dev
-- Checking for module 'fsd-io-dev'
--   Package 'fsd-io-dev', required by 'virtual:world', not found
CMake Error at C:/msys64/mingw64/share/cmake-3.20/Modules/FindPkgConfig.cmake:561 (message):
  A required package was not found
Call Stack (most recent call first):
  C:/msys64/mingw64/share/cmake-3.20/Modules/FindPkgConfig.cmake:783 (_pkg_check_modules_internal)
  CMakeLists.txt:17 (pkg_check_modules)

-- Configuring incomplete, errors occurred!
See also "E:/Yifan/Hiwi-FSD/FluCo1/Sourcecode/branch_HighLevelUmstrukturierung/High-Level/FCU-Interface/build-dev/CMakeFiles/CMakeOutput.log".

PRE-BUILD FAILED (exit value 1, total time: 5s)

And the CMakelists file is shown below:
cmake_minimum_required(VERSION 3.12)

SET(FSD_LIB_DIR ${CMAKE_CURRENT_LIST_DIR}/../../../../Libraries)
include("${FSD_LIB_DIR}/CMakeSuffixBase.cmake")
project("FCU-Interface${PROJECT_SUFFIX}" VERSION 0.1)

SET(ENV{PKG_CONFIG_PATH} ${FSD_LIB_DIR}/fsd-libs/trunk/build${PROJECT_SUFFIX}/install/lib/pkgconfig)
include("${FSD_LIB_DIR}/CMakeBase.cmake")
include(FindPkgConfig)

Subversion_GET_REVISION(${CMAKE_SOURCE_DIR} SVN_REV)
message(STATUS "SVN Revision Number is ${SVN_REV}")
message(STATUS "${PROJECT_NAME} PROJECT_SOURCE_DIR = ${PROJECT_SOURCE_DIR}")
message(STATUS "${PROJECT_NAME} Build directory = ${CMAKE_BINARY_DIR}")

find_package(PkgConfig REQUIRED)
pkg_check_modules(FSD_IO REQUIRED IMPORTED_TARGET fsd-io${PROJECT_SUFFIX})

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)

file(GLOB_RECURSE SOURCE_FILES "src/*.cpp")
add_executable(${PROJECT_NAME} ${SOURCE_FILES})
set_target_properties(${PROJECT_NAME} PROPERTIES
    VERSION "${PROJECT_VERSION}+${SVN_REV}"
)
target_include_directories(${PROJECT_NAME} PRIVATE
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/>
)
target_include_directories(${PROJECT_NAME} PRIVATE
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/../Framework_Seitz>
)

target_link_libraries(${PROJECT_NAME} PRIVATE
    Threads::Threads
    PkgConfig::FSD_IO)

install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})

The PROJECT_SUFFIX is -dev. I reckon that the problem is, the file "fsd-io-dev.pc" cannot be found. But I already have it under the directory "E:\Yifan\Hiwi-FSD\FluCo1\Libraries\fsd-libs\trunk\build-dev\install\lib\pkgconfig". What should I do to let it be found? Thanks in advance!!!


text:
Q: "I thought she might have had a problem with alcohol" versus "I thought she might have a problem with alcohol" Here in the following sentences why are we using "I thought she might have had" with 'had', why not simply "I thought she might have"?

1)  Vincent remembered Eddie's wife, "I knew Naedine very well; she was very nice to me. I felt I had a great rapport with her".
Vincent said, "Eddie didn't talk much about it, but I thought she might have had a problem with alcohol.  One New Year's Eve I caught on right away. We were at the Inn at Jefferson Square. I was sitting at the table with my date, some friends and Naedine. She took a glass of wine and Eddie came over and told her she wasn't supposed to be drinking."
2)
  "I thought she had a good chance to get on the medal stand," Dunn said Monday. "And if she got a good jump, I thought she might have had a chance to win it. That one girl just got an amazing jump in. Tanae jumped better than she had ever jumped in her life. You can't do much better than that. When you jump the best you've ever jumped at the state meet, that's all you can ask for."

In both of the sentences above why can't we say "....might have..." like here:

The big woman's face was bright red. For a minute I thought she might have a stroke. It was 100 degrees in the shade. (Ref)

Although I know about tenses (past tense and past perfect), this seems to always confuse me. Also it is always very easy to understand without 'thought' but with 'thought' it looks confusing.
Please elaborate this point.

A: You ask: In both of the sentences above, why can't we say "....might have..."?
I'll answer: Who says you can't? Let's try it, and see what happens:

"I thought she had a good chance to get on the medal stand," Dunn said Monday. "Andif she got a good jump, I thought she might have a chance to win it".

That version seems grammatical, too.
Essentially, the speaker is saying:

If she had a good jump, she might have won.

There are many ways to say that, and you may not hear the most straightforward way of saying it the moment a microphone is thrust into a coach's face. So, the coach says,

If she got a good jump, I thought she might have had a chance to win [the race].

In this original, the words "if...", "I thought...",  "might have...", and "a chance...," we are pretty well-nested in conjecture and conditional language. The result is a sentence where the word had could be omitted or included, and the sentence pretty much means the same thing, especially if you change the punctuation around:

"With a good jump," I thought, "She might have a chance to win the race."

The same holds for your first example:

Eddie didn't talk much about it, but I thought she might have had a problem with alcohol.
Eddie didn't talk much about it, but I thought she might have a problem with alcohol.

The phrase "I thought she might" puts the sentence in the past tense, so the had can be removed. If I remove that phrase, though, the had needs to stay in place:

Eddie didn't talk much about it, but she had a problem with alcohol.

Remember, we are dealing with spoken words that were written down, not an author's polished work. A writer may have revised the sentence to read something more like this:

Eddie didn't talk much about it, but I thought she had a drinking problem.

Once again, after the conditional language has been removed, the had is required. Also, just like last time, I can remove the had, particularly with a change in punctuation:

Eddie didn't talk much about it, but I thought, "She might have a problem with alcohol."

A: When you say "I thought she might have had a chance to win it." it seems (at least to me) that she's not won! Indeed you've used the PP to stress the result. However, when you say "I thought she might have a chance", it's possible that you're still in the middle of the action, that is not possible or so idiomatic with the PP.

A: … she might have is present tense.  The verb is have.  Might is a modal auxiliary verb.
… she might have had is present perfect tense.  Had is a past participle.  Have is the auxiliary verb for forming the present perfect.  Might is a modal auxiliary verb, as before.


text:
Q: IE 11 Error: Issue with website's security certificate I am using a IE 11 to test an application on my local machine which has address:
https://10.10.10.20/app.html
IE show ups a message:
There is a problem with this website's security certificate.

I understand I can click:
"Continues to this website (not recommended)"

But I would need instead bypass this dialog, and see the content straight away.
Do you know if it is possible? How to do it?

A: At the moment I was able to solve this problem using:

*

*Open Internet Explorer.

*Select the options gear, then select

*"Internet Options". Select the "Advanced" tab. Scroll down to the
"Security" section, and uncheck the "Warn about certficate address
mismatch" option.

*Select "OK". Restart the computer.

If you know a better way, please post your answer.


text:
Q: Passing multiple parameters to WebAPI I have a simple Post method
[ResponseType(typeof(Conversation))]
[HttpPost]
[Route("foo/bar/Function/")]
public Conversation Function(string title, IEnumerable<Participants> participants)
{
}

I would like to pass some the title and the participants from my application to the service.
This is what I have tried:
var createNewConversation = function(title, participants) {
var deferred = $q.defer();
var data = {
    title: title,
    participants: participants
};

$http.post("/foo/bar/Function", data, { headers: { 'Content-Type': "application/json" }, withCredentials: true }).success(function(response) {
        deferred.resolve(response);
    }).error(function(err, status) {
        deferred.reject(err);
    });
    return deferred.promise;
};

But the request never gets to the service (aka not hitting the breakpoint).
Any idea what I am doing wrong?

A: you are sending the two param inside the body, and web api cannot manage this, you have two options:
1. Send the title in the URL and participans in body:
[ResponseType(typeof(Conversation))]
[HttpPost]
[Route("foo/bar/Function/{title}")]
public Conversation Function(string title, IEnumerable<Participants> participants)
{...}

//js
var data = {
    participants: participants
};
$http.post("/foo/bar/Function/title", data, ......

2. Send all in the body, change the action:
[ResponseType(typeof(Conversation))]
    [HttpPost]
    [Route("foo/bar/Function/{title}")]
    public Conversation Function([FromBody] MyClassThatHaveTitleAndParticipants data)
    {...}

The class MyClassThatHaveTitleAndParticipants must have the two properties, title and participants.
//js
var data = {
    title: title,
    participants: participants
};

$http.post("/foo/bar/Function", data, ...


text:
Q: How to pass one array elements as an index to another array in c I have two matrices path[max][2] and input_pair2[max][max] where max is 10 and path_count is dynamic and less than max (let's say 6). I want to use elements of path matrix as an index of input_pair2, i am doing this as in the following code. This works fine with c compiler but giving error in the framework i am using the code in. I am using framework for converting functions to circuits. The error indicates problem of assigning values 0 and 1 to the input_pair2 matrix.
typedef struct
{
   int input_pair1[max][max];
   int input_pair2[max][max];
}Pair;

typedef struct
{
  int array[max][2];
  int count;
}paths;

Pair augment_path(paths path, Pair pair )
{
     for (int p = 0; p < path.count; p++)
    {
       if (pair.input_pair2[path.array[p] [0]] [path.array[p][1]] == 1)

            pair.input_pair2[path.array[p][0]] [path.array[p][1]] = 0;

      else

            pair.input_pair2[path.array[p][0]] [path.array[p][1]] = 1;
   }
   return pair;
}

The error i get is,
terminate called after throwing an instance of 'std::runtime_error'
what(): Unknown literal: 14100. Did you forget to return a value or assign a value to a OUTPUT variable?
Makefile:8: recipe for target 'output.gate.txt' failed
make: *** [output.gate.txt] Aborted (core dumped)

When i comment the above given code, error vanishes and circuits are generated.


text:
Q: 16.10 Unable to locate package libqtwebkit I have been using Blink in Ubuntu 16.04 and upgraded to 16.10 today. Now Blink fails with the following error
root@mark-Inspiron-13-7359:~# blink
Traceback (most recent call last):
  File "/usr/bin/blink", line 30, in <module>
    from blink import Blink
  File "/usr/lib/python2.7/dist-packages/blink/__init__.py", line 41, in <module>
    from blink.chatwindow import ChatWindow
  File "/usr/lib/python2.7/dist-packages/blink/chatwindow.py", line 12, in <module>
    from PyQt4.QtWebKit import QWebPage, QWebSettings, QWebView
ImportError: No module named QtWebKit

and
libqt5webkit5 is already the newest version (5.6.1+dfsg-4ubuntu1~2).

A: Just pay attention that you have two different versions of Qt: Qt4 and Qt5.
You got error with python2.7 which uses Qt4, and unfortunately there is little to do anything about it as QtWebKit was removed from shipped Qt4 packages (As You noticed you have QtWebKit present with Qt5 on your system, but Qt4 program cant use it). It is up to software developers (in your case Blink) to port the code to Qt5 (or PyQt5 in your case). This is quite huge problem not only in Ubuntu 16.10 but also in Debian unstable, and a lot of Qt4 legacy programs fails do to this removal of QtWebKit from Qt4. Porting code base from Qt4 to Qt5 is not so hard. (It is quite simple in python Qt (pyqt) code base, but can be more complicated if parts of program is in C++).
update:
going to github page of blink, I can see that they allready addresed the problem and moved to Qt5. So either You will have to wait that blink will be repacked with upstream version in Ubuntu (You could try to fill the bug report to get the attention and faster up the process), or you could try to install the program manually from the source code.

A: This is an import error in python. One will get this error if python QtWebKit modules are not installed. Doesn't matter if libqtwebkit is installed or not. You may try running
sudo apt-get install python3-pyqt5.qtwebkit

to install corresponding python modules.
or for Qt4
sudo apt-get install python-pyside.qtwebkit


text:
Q: Use opencv to track potatoes on a belt, the best alternative? I want to use some kind of machine learning to measure (the diameter) and count potatoes passing on belt. I've started of with opencv and have started to train a cascade with positive and negative images, this is a print screen from a short video I've captured:

In this frame it only manage to identify some potatoes but I assume that I can add more positive and negative images to make a better identifier.
So to the questions,

*

*Do you think that I'm on right track?

*And any idea how I shall continue with measuring the diameter?

*How shall I keep track each potato so it is only counted once?
(This is the code I run to identify the potatoes)
import numpy as np
import cv2
pot_cascade = cv2.CascadeClassifier('cascade.xml')
cap = cv2.VideoCapture('potatoe_video.mp4')
while 1:
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    potatoes = pot_cascade.detectMultiScale(gray, 5, 5)
    for (x, y, w, h) in potatoes:
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)
    cv2.imshow('img', img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

A:
Do you think that I'm on right track?

Yes and no. Machine learning is definitely the right tool for the problem of tracking potatoes but the shown results so far are not very good at all. A long way still to go.

And any idea how I shall continue with measuring the diameter?

If you are only interested in measuring the average diameter of the potatoes then this might be much easier than really tracking the single potatoes.
First you need to estimate the perspective (position of the transport belt relative to the camera), so you know how the image space relates to the real space on the transport belt. What may help you in finding out the real-space to image-space transformation is putting a regular grid (a sheet with regular black dots for example) on the belt and observe its movement. Mounting the camera in top-view mode may make things much simpler there.
Measuring only the average diameter means you do not need to get every potato right, a standard edge detection algorithm might suffice to detect most of the potatoes and then fitting ellipses to them, making a histogram of the diameters and looking at the median value.
Alternatively calculate an auto-correlation of the luminosity of the potatoes (between the potatoes it's dark, potatoes itself are reflecting the light) and fit the width of peaks in the auto-correlation. Or calculate the Fourier transform of the images and normalize the average amplitude within a frequency band where you expect the size of the potatoes with the average amplitude of another frequency band. This works best if you can calibrate the method with potatoes of known size. That means you may be able to record potatoes of known different size and thereby calibrate auto-correlation or FFT based measures.
I would though go for the machine learning approach because it potentially gives you single potato measurements.

How shall I keep track each potato so it is only counted once?

Every potato is (potentially) visible for the time range in the video that is needed to transport the potato on the belt through the field of view. Once you have established the perspective, you can relate the position in the image and the recording time to a position on the transport belt and as long as a potato doesn't change position on the belt, you can easily identify it over the whole time range where it's visible.
You basically must know (estimate) the movement of the transport belt and then you can "undo" it (computationally) and average over all the incidences where you saw the same potato.
I recommend the following general workflow:

*

*Consider putting the camera in a more favorable position (top-view).

*Measure the real-space to image-space-time transformation by tracking easier to detect objects of known distances on the belt.

*Apply the inverse transformation and if you want, average over all images of the same object (can help if the single image are noisy, low contrast)

*Either use a simple edge detection and do some statistics to get the average diameter of a potato (possibly calibrate with potatoes of known size) or..

*.. use machine learning to identify (and track, if you did not average) the single potatoes

*If on the way you encounter problems break them down into nice little bits and ask for a solution to each of them in a separate question.


text:
Q: Replacing HTML ascii codes via a bash script? I need a way to replace HTML ASCII codes like ! with their correct character in bash.
Is there a utility I could run my output through to do this, or something along those lines?

A:
$ echo '!' | recode html/..
!
$ echo '<∞>' | recode html/..
<∞>

A: I don't know of an easy way, here is what I suppose I would do...
You might be able to script a browser into reading the file in and then saving it as text. If lynx supports html character entities then it might be worth looking in to. If that doesn't work out...
The general solution to something like this is done with sed. You need a "higher order" edit for this, as you would first start with an entity table and then you would edit that table into an edit script itself with a multiple-step procedure. Something like:
. . .
s/&Dagger;/‡/g

s/&#8221;/”/g

. . .

Then, encapsulate this as html, read it in to a browser, and save it as text in the character set you are targeting. If you get it to produce lines like:
s/</</g

then you win. A bash script that calls sed or ex can be driven by the substitute commands in the file.

A: Here is my solution with the standard Linux toolbox.
$ foo="This is a line feed
And e acute:é with a grinning face 😀."
$ echo "$foo"
This is a line feed
And e acute:é with a grinning face 😀.
$ eval "$(printf '%s' "$foo" | sed 's/^/printf "/;s/&#0*\([0-9]*\);/\$( [ \1 -lt 128 ] \&\& printf "\\\\$( printf \"%.3o\\201\" \1)" || \$(which printf) \\\\U\$( printf \"%.8x\" \1) )/g;s/$/\\n"/')" | sed "s/$(printf '\201')//g"
This is a line feed
And e acute:é with a grinning face .

You see that it works for all kinds of escapes, even Line Feed, e acute (é) which is a 2 byte UTF-8 and even the new emoticons which are in the extended plane (4 bytes unicode).
This command works ALSO with dash which is a trimmed down shell (default shell on Ubuntu) and is also compatible with bash and shells like ash used by the Synology.
If you don't mind sticking with bash and dropping the compatibility, you can make is much simpler.
Bits used should be in any decent Linux box (or OS X?)
- which
- printf (GNU and builtin)
- GNU sed
- eval (shell builtin)
The bash only version don't need which nor the GNU printf.


text:
Q: missing explicit frame definition for content or just static frames I am converting HTML to pdf in Django app and using xhtml2pdf. Given is my HTML template.
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Certificate</title>

        <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600" rel="stylesheet">
        <link rel="stylesheet" type="text/css" href="/static/css/main.css">

WINNER'S

CERTIFICATE

Paul

This is to acknowledge that you won the competition.

                  4 TIME

Congratulations on winning Challenge.

2018-09-20

Date

I am using pisa.CreatePDF to generate pdf and CSS is not loading properly. I tried default_css and got this error.
missing explicit frame definition for content or just static frames

Here is the snippet of my python code
        pisa.CreatePDF(io.BytesIO(html.encode('utf-8')),
                   dest=result, link_callback=fetch_resources,
                   default_css="/static/css/main.css")

A: I had a similar problem when used @page background-image by url.
After a few hours of testing different variants, I have fixed this warning by adding tag @frame in tag @page. But no need to use this frame in html(for me it is dummy tag only to exclude this warning).


text:
Q: Enjoying something more because I know it will end Suddenly enjoying something more because I know it's about to end/be taken away. Is there a word for this feeling?
Scenario: Getting to the bottom of a bag of M&Ms, and realizing a sudden greater joy of the last 2-3 candies- knowing they'll be entire gone soon.

A: As far as I know, it's not possible to enjoy something more just because it's about to end. If anything, there could be a tinge of sorrow to your enjoyment (if not outright sorrow) because you know it won't last.
People who enjoy something but know it won't last might actually call their feeling bittersweet.
On the other hand, you could be said to have a greater appreciation for something when you know it's about to end.

[Merriam-Webster]
1 a : a feeling or expression of admiration, approval, or gratitude
// I want to express my appreciation for all you've done.
// a small token of our appreciation
b : JUDGMENT, EVALUATION
especially : a favorable critical estimate
c : sensitive awareness
especially : recognition of aesthetic values
// a class in music appreciation

People who know that something is about to end don't enjoy it more because of that fact. Instead, increased enjoyment generally happens because they've deliberately chosen to pay more attention to it, forgetting about other things that would normally distract them.
In terms of enjoyment, it's a two-stage step of causation. The fact of something about to end causes you to concentrate on it more, and it's this increased concentration on it that can lead to increased enjoyment.
Meanwhile knowing that something is about to end can directly cause a greater appreciation of it.


text:
Q: storm with remote hbase cluster I have just started working on storm. One of my use case involves reading and writing data to/from a remote hbase table. I was wondering if it is possible to connect to a remote hbase cluster from local storm topology. If yes, how so?
TIA.

A: It is no different than connecting remotely from a stand-alone java application.  You may have to take care to set the parallelism hint - too high and you get too many connections and too low and you get a bottleneck - but that's really no different than connecting to any other kind of server from within storm.


text:
Q: Pre signed aws s3 url slowness I am trying to secure s3 resources and i have created temporary credential using sts service in the same region where bucket exist . I am using these credential to create a pre signed url which will expire after one hour. These url are images and will be shown on a mobile app . But after implementation, we are experiencing slowness in the response from s3 . Does anyone experienced same behaviour ?
This is how i am generating pre signed url
try {
    AmazonS3 s3Client = new AmazonS3Client(getTemporaryAwsCredentials());

    // Generate the pre signed URL.
    LOGGER.info("Generating pre-signed URL for " + unsignedUrl);
    GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, fileName).withMethod(HttpMethod.GET);

    URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);

    LOGGER.info("Pre-Signed URL: " + url.toString());
    return url.toString();

} catch (Exception e) {
    LOGGER.error("Error while generating pre signed url ", e);
}

private AWSCredentials getTemporaryAwsCredentials() {

    AWSSecurityTokenServiceClient sts_client = new AWSSecurityTokenServiceClient(getCredentials());
    sts_client.setEndpoint("sts.us-west-2.amazonaws.com");

    GetSessionTokenRequest session_token_request = new GetSessionTokenRequest();
    session_token_request.setDurationSeconds(43200);

    GetSessionTokenResult session_token_result = sts_client.getSessionToken(session_token_request);

    Credentials session_creds = session_token_result.getCredentials();

    BasicSessionCredentials sessionCredentials = new BasicSessionCredentials(
        session_creds.getAccessKeyId(),
        session_creds.getSecretAccessKey(),
        session_creds.getSessionToken());

    return sessionCredentials;
}