text:
Q: How to safely generate 200V from low voltage supply Unfortunately, this post requires quite a bit of background if it's going to be useful to anybody (including me).
I have been trying to build a relatively high voltage power converter for part of my grad project, and can't seem to get reality to match theory. I have a 12V supply and need to step it up to 200V so that I can drive some electrostatically driven MEMS devices. I have been trying to, as much as possible, make the topology compliant with relevant electrical safety standard (IEC60601-1 is the specific standard, but the concepts are essentially the same as in IEC60950).
From the safety standard, I determined I need to isolate the high voltage circuit from the low voltage circuit (power a computer and other simple LV electronics). The application calls for a high voltage rail (that runs some HV op-amps) and bi-polar low voltage rails (for low voltage op amps).
Conservative Power requirements:

*

*Isolated 200V rail, 4W

*Isolated ~10V rail, 2W (no tight voltage regulation required)

*Isolated ~-10V rail, 2W (no tight voltage regulation required)

So a conservative max of 8W total draw, which I would think isn't too hard to pull off.
I have designed the circuit around the LT3748 switching controller, which is designed to work in a flyback converter. It uses primary side sensing during the flyback period to sample the output voltage from the primary side and regulates that voltage, without needing to bridge the magnetic isolation of the transformer. This is helpful for safety because the fewer components bridging the isolation barrier, the better. This is the basic flyback circuit.

And I have modified this circuit to have 3 separate output windings. One for the high voltage, and two for the low voltages. Because I could not find a suitable transformer off-the-shelf, I ended up winding my own transformer on a toroidal core. I have read that, typically, flyback converter transformer cores are gapped, but all of my theory digging has lead me to believe that it only improves temperature stability and linearity (save that argument for another time :) ).
Transformer Design

*

*Primary inductance = 10uH (2 turns on the core I am using)

*Turns ratio to high voltage winding = 20:1

*Turns ratio to low voltage windings = 1:1

I have measured the inductances of the individual windings on an impedance analyzer and they are what they should be. I expect this circuit to operate at 100kHz when fully loaded with a duty cycle around 50%. I have appropriately designed in high breakdown voltage components for the FET and the output diode.
The problem
At least the apparent problem : This circuit behaves quite as expected when only the low voltage windings are installed. When the high voltage winding is added, things get funny. The expected behavior for a flyback is such that, when the primary FET turns on, the voltage on the high side of the diode is supposed to quickly shoot to a large negative voltage (-Vin*turns ratio). Then, when the FET turns off, the voltage at the low side of the primary is supposed to shoot up to the flyback voltage very quickly (Vin+Vout/turns ratio).
In reality, I am getting ~250ns delays between the switch action and the expected voltage changes. The circuit does produce a large positive voltage, but it majorly over-regulates, and basically every cycle is actually limited by the current trip voltage on the low side of the FET. So it's switching and generating voltage, so I believe it's all wired up correctly, it's just not behaving due to parasitics. I have suspicion that there is excessive capacitance on the high voltage secondary that reflects to the primary differently during different phases of the cycle. Additionally, this circuit is supposed to detect the end of the secondary current cycle by waiting for the flyback voltage to drop below Vin signaling it's time to turn the primary back on, but the rate of slew of the flyback voltage seems very slow and perhaps the cause of the trouble.
I could start posting oscilloscope traces, but perhaps I will save that for questions that hopefully arise.
The first Question
I suspect my issue here is too much capacitance, and possibly some exacerbation by the high turns ratio of the transformer. I can't even scope probe the secondary terminals without altering the behavior of the circuit, so I think it's super sensitive to capacitance on the secondary. What parasitics are likely to cause slow voltage slewing and delays of behavior in this type of circuit? I expect the circuit to operate at 100kHz with  50% duty, but the ferrite core is only permeable up to 2MHz. And once you wind on the windings, the stray capacitance make the transformer self-resonant at some frequency below 2MHz. For this circuit to work, how much capacitance do you suppose you can tolerate on/between windings?
The Second Question
If I needed to come up with an interim solution for this that was demonstrably safe, how might I got about doing it? I personally am driven to understand the problem, but practically I also need an alternate solution ASAP.
I would greatly appreciate any advice the community can offer!

A: OK, here's my take just to double-check things: -

*

*Your primary inductance is 11.76 uH formed from two turns on a core of \$A_L\$ = 2940 nH/turn\$^2\$.

*With 12 volts applied (charge cycle) current rises at V/L = 1.02 amps per microsecond

*Your operating frequency and duty are aiming to be 100 kHz at 50% hence the charge time is 5 microseconds

*In that time, the current reaches a peak of about 5.1 amps

*The stored energy is \$\frac{LI^2}{2}\$ = 153 micro joules

*At 100 kHz, this is an power throughput of 15 watts.

All seems OK because duty can be turned down a bit to accomodate lower powers. If 8 watts is the max power then you only need to transfer 8 uJ per cycle and this means a peak current of 3.7 amps and a therefore a duty of about 36%.
But, with an ungapped core, what is the H-field? H-field is ampere turns per metre where the "per metre" part is the mean circumference of the core (90 mm or thereabouts in the data sheet). The H-field level that liberates 8 watts is 3.7 amps x 2 turns divided by 0.09 metres = 82 At/m.
The core (N87) relative permeability is 2200 so multiplying this by 82 and the permeability of free space (\$4\pi\times 10^{-7}\$) means a flux density of 0.227 teslas and this is fine in my book but not a lot of clearance before saturation. You will be strongly saturating at a 50% duty cycle.
But, your load must consume that 8 watts or the core will, what is known as, walk into saturation. In other words, if you are using a fixed duty cycle you must dissipate that power in your load.
If your load doesn't dissipate the power, the output voltage will continue to rise until that power is consumed but, more than likely you will hit core saturation before that point: -

The circuit does produce a large positive voltage, but it majorly
  over-regulates, and basically every cycle is actually limited by the
  current trip voltage on the low side of the FET

Sounds to me like you need to control the duty cycle better. Maybe the chip you proposed isn't working as you thought it might. Try adding a load just in case.
I also note that you are not implementing a flyback catch circuit as per figure 18 in the data sheet: -

Given the application and the amount of leakage flux in a high step-up transformer you should use one. The design above is 5 watts and not a million miles different from your application. Please justify not using a flyback catch circuit to prevent damage to the MOSFET.
Also noteworthy is that the primary inductance in the design above (also for a 12 volt supply) is 100 uH and herein might lie another problem; the LT3748 relies on regulating the output voltage by using the back-enf during flyback and it seems to rely on a certain amount of leakage inductance for correct operation. I'm not an expert in this family of chips so I would recommend further reading to see if your primary inductance is suitable at 100 kHz. It might be necessary to wind more primary inductance and operate at a higher duty cycle.
Here's a link to a website that takes you through an example of designing a ferrite core and considerations for gapping. And here's another part of that site that discusses flyback operation and later on discusses the use of the ferrite core previously mentioned.


text:
Q: Change observable but don't notify subscribers in knockout.js Is there a way to ignore subscribers on a value change of the observable.  Id like to change a value of an observable, but not execute it for the subscribers with knockout.js

A: Normally this is not possible or advisable, as it potentially allows things to get out of sync in the dependency chains.  Using the throttle extender is generally a good way to limit the amount of notifications that dependencies are receiving.
However, if you really want to do this, then one option would be to overwrite the notifySubscribers function on an observable and have it check a flag.
Here is an extensions that adds this functionality to an observable:
ko.observable.fn.withPausing = function() {
    this.notifySubscribers = function() {
       if (!this.pauseNotifications) {
          ko.subscribable.fn.notifySubscribers.apply(this, arguments);
       }
    };

    this.sneakyUpdate = function(newValue) {
        this.pauseNotifications = true;
        this(newValue);
        this.pauseNotifications = false;
    };

    return this;
};

You would add this to an observable like:
this.name = ko.observable("Bob").withPausing();

Then you would update it without notifications by doing:
this.name.sneakyUpdate("Ted");

A: I like the solution provided by @RP Niemeyer when all subscribers need to be ignored.  However, for my case, I have an observable with 2-way bindings on a Select control.  When using @RP Niemeyer, the Select control isn't updated. So, I really needed a way to turn off specific observers, not all.  Here is a generalized solution for this case.
Add extensions methods for 'quiet' subscribe and 'quiet' writes.
ko.observable.fn.ignorePokeSubscribe = function (callback, thisValue, event){
    var self = this;
    this.subscribe(function(newValue) {
        if (!self.paused)
            callback(newValue);
    }, thisValue, event);
    return this;
};
ko.observable.fn.poke = function (newValue) {
    this.paused = true;
    var result = this(newValue);
    this.paused = undefined;
    return result;
};

You would subscribe to observable like:
this.name = ko.observable("Bob");
this.name.ignorePokeSubscribe(function(newValue) { /* handler */ }));

Then you would update it without specific notifications by doing:
this.name.poke("Ted");   // standard subscribers still get notified

A: An even simpler approach:
ko.observable.fn.silentUpdate = function(value) {
    this.notifySubscribers = function() {};
    this(value);
    this.notifySubscribers = function() {
        ko.subscribable.fn.notifySubscribers.apply(this, arguments);
    };
};

Use it as follows:
this.status = ko.observable("Happily Married");
this.walkIntoBar();
this.status.silentUpdate("Single");
this.walkOutOfBar(); // careful with exceptions
this.status.silentUpdate("Happily Married");

To be used with caution. We are dealing with an observable object so bad things can happen if you fail to notify your subscribers.

A: I came to this question because I was building a paged datagrid. Only 10 rows were shown and each row has a checkbox. The table header had a (de)select all checkbox.
During load tests we discovered that clicking the select all checkbox resulted in updating 1000 observables at once. This took way too long.
It seemed that KO updated the html 1000 times even though only 10 observables were bound to HTML.
If anyone finds this question for the same reason, I would suggest looking into deferred updates. Deferred updates queue notifying subscribers, it notifies your subscribers after your 'thread' is done. Deferred updates is configurable per observable or for your whole application.
http://knockoutjs.com/documentation/deferred-updates.html

A: This may help to someone:
const candiesCount = ko.observable(0);

const loadCandiesPriceByAjax = () => { /*...*/ };
let isPriceLoadingEnabled = true;

candiesCount.subscribe(() => {
    if (isPriceLoadingEnabled) {
        loadCandiesPriceByAjax();
    }
});

By changing isPriceLoadingEnabled I can pause the subscription effect without really disabling it. For example:
const setCandiesCountWithoutAjaxingPrice = (count) => {
    isPriceLoadingEnabled = false;
    candiesCount(count);
    isPriceLoadingEnabled = true;
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: Computing the power for binomial regression with indicator variables My question is kind of a sequel to this one. For an experiment I'm designing, I want to model the outcomes by a binomial regression, something like
bmodel <- glm(cbind(succ, (N - succ)) ~  x + x_ind, data = tb1, family = "binomial")

where x_ind is an indicator variable, indicating the experiment arm (placebo, therapy A, therapy B). I want to establish whether therapies have different effects, to which end I'd observe whether the indicator (dummy variables) significantly (say, at the $\alpha = 0.05$ level) differ(s) from zero.
I need to calculate the number of subjects required for achieving the desired power. The answer to the above linked question explains how to compute the power for binomial regression when the predictor is continuous:
$$ \gamma = 1 - {\bf{\Phi}}(1.96-\vert\beta\vert\sigma_x \sqrt{(np(1-p)} )$$
with $\gamma$ being the power, $\bf{\Phi}$ the normal CDF, $\beta$ the effect size, $\sigma_x$ the standard deviation of the predictor and $p(1-p$) the marginal variance of the outcome.
In my case I don't care about the continuous predictor, just the indicator. In that case, what is my $\sigma_x$? Simply the standard deviation of a discrete uniform distribution in the range $1 \ldots $ number_of_therapy_arms? But the therapy arms are actually on the nominal scale, so this approach doesn't seem quite right to me. Also, how would the approach change if I did care about the continuous predictor?

A:
In that case, what is my $\sigma_x$

The predictor here is categorical.  Most analyses will dummy encode these, which turns them into binary predictors (one for each exposure, save 1 category which is lumped into the intercept).  The standard deviation $\sigma_x$ will simply be $\sqrt{f(1-f)}$ where $0<f<1$ is the frequency of that exposure.
As an example, if you had 50% in control and 25% in the other arms, then $\sigma_x = \sqrt{0.25 \times 0.75}$ (since the frequency of the exposure arm is 25%).


text:
Q: Trouble calling public function of namespace (coffeescript) This should be a really simple question, but I'm still having difficulty.
I have a namespace and a single member function as follows:
fb =
    test1: ->
        console.log "test"

However, when I try to call the function in another file by using
fb.test1()

it doesn't recognize 'fb' as the namespace name. I have made sure that both files are sharing the same 'window' by making the proper inclusions.
EDIT:
this code worked with the function call:
    window.fb.test1()
and the namespace declaration:
    window.fb

A: Assuming you are doing this in the browser, try changing fb = to window.fb = and then see if you are able to find it in the "other file". You could also compile both files using --join or --bare, but be aware of the consequences.

A: When you want to define a global namespace do it like this:
fb = window.fb ?= {}

You can spread such declaration across multiple files safely.


text:
Q: Best way of Changing the background of JButtons Right now i change the background color of a button by using
button.setBackground(Color.WHITE);

That being an example.
But when i have a massive grid out of jbuttons (1000+), just running a for loop to change every buttons background is very, very slow. You can see the grid slowly turning white, box by box. I really don't want this
Is there a better way of changing every JButton on the grid to the same color at the same time?
This is how i am making the grid, the numbers used are only for example...
grid = new JPanel(new GridLayout(64, 64, 0, 0));

That's 4096 buttons, takes about 30+ seconds to change every button to the same color.
Edit 1: I need the buttons to be clickable, like when i click a button it turns blue for example. when all of the buttons are clicked, change the color of every button to white. Right now i have that working fine, but it is just slow to change the color of every button.
Edit 2: this is how i am changing the buttons:
    new javax.swing.Timer(300, new ActionListener() {
        int counter = 0;
        public void actionPerformed(ActionEvent e) {
            if (counter >= counterMax) {
                ((Timer) e.getSource()).stop();
            }
            Color bckgrndColor = (counter % 2 == 0) ? flashColor : Color.white;
            for (JButton button : gridButton) {
                button.setBackground(bckgrndColor);
            }
            counter++;
        }
    }).start();

A: The fact that you see the boxes being repainted individually indicates that either double buffering is turned off, or that the paint code in the button UI makes use of paintImmediately().
I tested your setup with 64x64 JButtons, an made sure that all UI operations were executed in the EDT (Event Dispatch Thread). I can confirm the effect you saw, changing the background of all buttons took about 1200 ms, with every box repainted immediately.
You can bypass the immediate repaints by setting the grid to non-visible before, and to visible after you changed the backgrounds:
grid.setVisible(false);
for (Component comp : grid.getComponents()) {
   comp.setBackground(color);
}
grid.setVisible(true);

This caused the grid to do only one repaint, and reduced the time to ~300ms (factor 4).
This is still too slow for frequent updates, so you're better off with a custom component which draws the grid, or a flyweight container (what trashgod suggested in the comment to your question) if you want allow the grid cells to be arbitrary components.

A: You can get a considerable benefit if only visible buttons need to be repainted. In the MVC approach shown below, each button listens to a model that defines it's current state. Updating the model is quite fast compared to repainting. Although startup takes a few seconds, I see updates taking < 10 ms. in the steady-state. It's not as scalable as the flyweight pattern used by JTable, illustrated here, but it may serve.
import java.awt.*;
import java.awt.event.*;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;
import javax.swing.*;

/** @see https://stackoverflow.com/questions/6117908 */
public class UpdateTest {

    private static final int ROW = 64;
    private static final int COL = 64;
    private static final int MAX = COL * ROW;
    private final DataModel model = new DataModel(MAX);

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new UpdateTest().create();
            }
        });
    }

    void create() {
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(ROW, COL));
        for (int i = 0; i < MAX; i++) {
            panel.add(new ViewPanel(model, i));
        }
        Timer timer = new Timer(1000, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                long start = System.nanoTime();
                model.update();
                System.out.println(
                    (System.nanoTime() - start) / (1000 * 1000));
            }
        });
        JFrame f = new JFrame("JTextTest");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new JScrollPane(panel), BorderLayout.CENTER);
        f.setPreferredSize(new Dimension(800, 600));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        timer.start();
    }

    private static class ViewPanel extends JPanel implements Observer {

        private final JButton item = new JButton();
        private DataModel model;
        private int index;

        public ViewPanel(DataModel model, int i) {
            this.model = model;
            this.index = i;
            this.add(item);
            item.setText(String.valueOf(i));
            item.setOpaque(true);
            item.setBackground(new Color(model.get(index)));
            model.addObserver(this);
        }

        @Override
        public void update(Observable o, Object arg) {
            int value = model.get(index);
            item.setBackground(new Color(value));
        }
    }

    private static class DataModel extends Observable {

        private final Random rnd = new Random();
        private final int[] data;

        public DataModel(int n) {
            data = new int[n];
            fillData();
        }

        public void update() {
            fillData();
            this.setChanged();
            this.notifyObservers();
        }

        public int get(int i) {
            return data[i];
        }

        private void fillData() {
            for (int i = 0; i < data.length; i++) {
                data[i] = rnd.nextInt();
            }
        }
    }
}


text:
Q: Delphi XE7 TdateTimePicker missing weekdays on Windows 10 when style other than Windows What can cause this weird behaviour? Calendar does not show Monday and Sunday when style is other than Windows.
Delphi XE7 + Windows 10 (polish version tested).


text:
Q: Trigger Discipline Perk - Good for Snipers without VATS? I started to play a sniper but I won't use Vats.
I heard, that a shot with a sniper rifle hits exactly where you aim. If that's true, the perk "Trigger Discipline" would be completely useless for me, right? Moreover a disadvantage, because of the lower fire rate.

A: High accuracy reduces bullet spread, but sniper rifles have very little spread when you fulfill its Strength/Guns requirements. They also have a good fire rate for a long range weapon, so you might prefer not to get this perk, which is better on weapons with high spread, like shotguns.
Just note that Fallout is not exactly a shooting game, and it might sometimes frustrate a player that chooses to avoid VATS. Think of VATS more like making the game be "turn-based" instead of a "cheat mode".


text:
Q: Perform action every time iframe re-navigates. (javascript) I'm making a bot for something, which is designed to move to the next 'page' of a file and search for a string, and to repeat this action until it's found that string. Everything works, in terms of searching for strings, however it only navigates to the next page once (so it only goes to online.php?page=2. I believe this is because the iframe.contentWindow.load is only triggering once, on the first run of the code. So when it moves to a new page, it's not continuing.
Any ideas?
document.body.innerHTML = '' //Out with the old
var iframe = document.createElement('iframe');
var increm = 1
iframe.src = 'online.php?page=' + parseInt(increm)
iframe.style.height= '3000px'
iframe.style.width = '100%'
document.body.appendChild(iframe); //In with the new

$( iframe.contentWindow ).load(function() { //Once EVERYTHING has loaded
    runcode()
});

function runcode(){
    whole = iframe.contentWindow.document.body.innerText
    var sub = "StringToSearchFor";
    if(whole.indexOf(sub) > -1){ //If the string is found on the page
        console.log('The string has been found on this page')
    }else{ //Otherwise
        increm = increm+1
        iframe.src = 'online.php?page=' + parseInt(increm); //Move to the next page
        $( iframe.contentWindow ).load(function() { //rinse
            runcode() //repeat
        });
    }
}

A: Your have 2 load handlers, one of which is inside your function, calling runcode() again.
You only need 1, but don't attach it to content that changes. Content removed means handler removed. So, do:
$( iframe ).load(function() { runcode() });

OR
$( iframe ).on("load", function() { runcode() });

OR
$( iframe ).on("load", ".newchilddiv", function() { runcode() });

EDIT: also innerText is causing an error
whole = iframe.contentWindow.document.body.innerText


text:
Q: org.openqa.selenium.WebDriverException: java.net.SocketException: Software caused connection abort: recv failed I was running one class in Selenium and suddenly receiving below error.
Error Details:
org.openqa.selenium.WebDriverException: java.net.SocketException: Software caused connection abort: recv failed
Build info: version: '3.13.0', revision: '2f0d292', time: '2018-06-25T15:24:21.231Z'
System info: host: 'LAPTOP-CT7IBV5D', ip: '9.236.152.55', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_181'
Driver info: driver.version: RemoteWebDriver
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:92)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:276)
    at org.openqa.selenium.remote.RemoteWebElement.getText(RemoteWebElement.java:160)
    at com.qa.PhpTravels.Pages.PhpTravelsSearchHotelPage.SearchHotelByLocation(PhpTravelsSearchHotelPage.java:67)
    at com.qa.PhpTravels.TestCases.PhpTravelsSearchHotelPageTest.SearchHotelByLocationTest(PhpTravelsSearchHotelPageTest.java:58)
I verified my code in SearchHotelByLocation and couldn't understand why it is failing.
List<WebElement> SearchLocationList=driver.findElements(By.xpath("//ul[@class='select2-results']/li/ul/li/div/span"));
        int NumberOfSearchLocation=SearchLocationList.size();
        System.out.println("Total Length of SearchLocation:"+NumberOfSearchLocation);
        if(NumberOfSearchLocation==0)
            {
                System.out.println("Please search some different location");
            }
        else
            {
                for(int i=0;i<NumberOfSearchLocation;i++)
                {
                    **System.out.println("Value in 1 index:"+SearchLocationList.get(i).getText());**
                    if(SearchLocationList.get(i).getText().contains(location))
                        {
                            SearchLocationList.get(i).click();
                            break;
                        }
                }
            }


text:
Q: Jersey: How to register MultiPartConfigProvider class I'm trying to load multiple files with jersey, but it demands me some configuration that i can't find.
This is the dependency, I had to add it because jersey couldn't resolver the type "multipart/related":
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-multipart</artifactId>
    <version>2.7</version>
 </dependency>

This is the API where I use the multipart:
    @PUT
    @Consumes("multipart/related")
    @Path("/{id}/user/{userId}")
    public Response loadFile(@PathParam("id") int id, @PathParam("userId") int userId, MultiPart files) throws Exception{
        int resultado = tool.loadFile(id, userId, files);
        switch (resultado){
        case 401:   return Response.status(401).entity("No existe el experimento con id: "+id).build();
        case 402:   return Response.status(402).entity("El tipo de uno de los archivos no se encuentra en los tipos de entregables del experimento").build();
        case 403:   return Response.status(403).entity("El usuario: "+userId+" no participa en el experimento").build();
        case 405:   return Response.status(405).entity("Debe ingresar un comentario").build();
        case 406:   return Response.status(406).entity("Hay entregables sin subir").build();
        case 200:   return Response.status(200).build();
        }
        return null;
    }

This is the web.xml, I think I am missing something here:
    <?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
     see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>org.mockapi</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

And this is the exception:
A MultiException has 3 exceptions.  They are:
1. java.lang.IllegalArgumentException: The MultiPartConfig instance we expected is not present.  Have you registered the MultiPartConfigProvider class?
2. java.lang.IllegalStateException: Unable to perform operation: create on com.sun.jersey.multipart.impl.MultiPartReaderClientSide
3. java.lang.IllegalStateException: Unable to perform operation: create on org.glassfish.jersey.message.internal.MessageBodyFactory

A: If we are using new version of dropwizard, then the dependency should be,

    <dependency>
         <groupId>org.glassfish.jersey.media</groupId>
         <artifactId>jersey-media-multipart</artifactId>
         <version>2.15</version>
     </dependency>

Because new version of dropwizard uses org.glassfish.jersey.core:jersey-server:jar.
And we have to register MultiPartFeature in our Application's run method as
   environment.jersey().register(MultiPartFeature.class);
For more information you can check here

A: Try to put this on your pom.xml
<dependency>
    <groupId>com.sun.jersey.contribs</groupId>
    <artifactId>jersey-multipart</artifactId>
    <version>1.8</version>
</dependency>

It fix my problem, and I hope it


text:
Q: Using one subject to propagate completly different event streams through I need to proxy all the different event streams through one subject.
I came up with this code:
var mySubject,
    getObservable;

getObservable = function (subject, eventName) {
    return subject
        .asObservable()
        .filter(function (x) {
            return x.EventName === eventName;
        })
        .flatMap(function (x) {
            if (x.Type === 'onNext') {
                return Rx.Observable.return(x.Data);
            }

            if (x.Type === 'onError') {
                return Rx.Observable.throw(x.Data);
            }

            return Rx.Observable.empty();
        });
};

mySubject = new Rx.Subject();

getObservable(mySubject, 'foo')
    .subscribe(function(x){
        console.log('foo onNext ' + x);
    }, function(x){
        console.log('foo onError ' + x);
    }, function(){
        console.log('foo onComplete');
    });

getObservable(mySubject, 'bar')
    .subscribe(function(x){
        console.log('bar onNext ' + x);
    }, function(x){
        console.log('bar onError ' + x);
    }, function(){
        console.log('bar onComplete');
    });

mySubject.onNext({Type: 'onNext', EventName: 'foo', Data: 5});
mySubject.onNext({Type: 'onCompleted', EventName: 'foo'});

mySubject.onNext({Type: 'onNext', EventName: 'bar', Data: 5});
mySubject.onNext({Type: 'onError', EventName: 'bar', Data: 'Error message'});

Got output:
foo onNext 5

bar onNext 5
bar onError Error message

Expected output:
foo onNext 5
foo onCompleted

bar onNext 5
bar onError Error message

For the bar event, that works like a charm: onNext will be propagated and as soon as the error raises the onError function gets called and the event stream finishes. However, I can't get it to work for the onComplete.
Whenever a complete notification raises I do see that Rx.Observable.empty() gets called but that doesn't cause the subscribers onComplete handler to be called. Instead, its calling its onNext handler.

A: The getObservable function returns an observable that subscribes to a eventName event sent through a subject.
let getObservable = function (subject, eventName) {
    return Rx.Observable.create(function (observer) {
        subject
            .asObservable()
            .filter(function(x) {
                return x.EventName === eventName;
            })
            .map(function(x) {
                if (x.Type === 'onNext') {
                    observer.onNext(x.Data);
                }

                if (x.Type === 'onError') {
                    observer.onError(x.Data);
                }

                if (x.Type === 'onCompleted') {
                    observer.onCompleted();
                }

                return x;
            })
            .subscribe();
    });
};

This is a working example using data from the original question:

var mySubject,
    getObservable;

getObservable = function (subject, eventName) {
    return Rx.Observable.create(function (observer) {
        subject
            .asObservable()
            .filter(function(x) {
                return x.EventName === eventName;
            })
            .map(function(x) {
                if (x.Type === 'onNext') {
                    observer.onNext(x.Data);
                }

                if (x.Type === 'onError') {
                    observer.onError(x.Data);
                }

                if (x.Type === 'onCompleted') {
                    observer.onCompleted();
                }

                return x;
            })
            .subscribe();
    });
};

mySubject = new Rx.Subject();

getObservable(mySubject, 'foo')
    .subscribe(function(x){
        console.log('SomethingHappened onNext ' + x);
    }, function(x){
        console.log('SomethingHappened onError ' + x);
    }, function(){
        console.log('SomethingHappened onComplete');
    });

getObservable(mySubject, 'bar')
    .subscribe(function(x){
        console.log('DataUpdated onNext ' + x);
    }, function(x){
        console.log('DataUpdated onError ' + x);
    }, function(){
        console.log('DataUpdated onComplete');
    });

mySubject.onNext({Type: 'onNext', EventName: 'foo', Data: 5});
mySubject.onNext({Type: 'onCompleted', EventName: 'foo'});

mySubject.onNext({Type: 'onNext', EventName: 'bar', Data: 5});
mySubject.onNext({Type: 'onError', EventName: 'bar', Data: 'Error message'});
<script src='https://rawgit.com/Reactive-Extensions/RxJS/master/dist/rx.all.js'></script>

A: in .NET Observable.SelectMany uses Observable.Merge to merge streams together to one composite observable. IMHO Observable.Merge completes only when any of the merged observables are completed.
e.g. http://theburningmonk.com/2010/02/rx-framework-iobservable-merge/
Thats could be the reason for issue.


text:
Q: CSS - linear-gradient - How to make the gradient part of border constant, not percentual? I have the following table:

and this css for the table border:
border-image: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, #b3b3b3 20%, #b3b3b3 calc(100% - 25px), rgba(0,0,0,0) calc(100% - 25px)) 0 0 0 1;

Currently the gradient part of the border is percentual. So when i have 1000 items in my list, the border of the first ~20 items will not be seen. How can i make the length of gradient part constant? So the beginning of the border seems always same regardless of the list item count?

A: Considering all your previous questions about the same issue (CSS - How to change border height in linear-gradient? / How to make a border left with custom bullet for my list, in a gradient style?) I would recomment another way to tackle this layout and avoid the different issues:

ul {
   background:
      /*top part always the same height (60px)*/
      linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, #b3b3b3 100%) 22.5px 0/3px 60px,
      /*bottom part*/
      linear-gradient(#b3b3b3,#b3b3b3) 22.5px 60px/3px calc(100% - 70px);
   background-repeat:no-repeat;
   overflow:hidden;
   margin:5px 0;
}

li {
  padding: 10px;
  background: #fff;
  border-radius: 10px;
  margin-bottom: 5px;
  list-style: none;
  position: relative;
}

li::before {
  content: "";
  position: absolute;
  left: -20px;
  top: 15px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: grey;
}
/*hide the non needed part of the gradient*/
li:last-child::after {
  content: "";
  position: absolute;
  left: -20px;
  top: 23px;
  width: 8px;
  height: 100vh;
  background: #ededed;

}

body {
  background: #ededed;
}

Some text

Some text

Some text
125 886

Some text

Some text

Some text

Some text

Some text
 5465 654

Some text
 5465 654

Some text
 5465 654

Some text
 5465 654

Some text
 5465 654


text:
Q: cefsharp winform load slowly Environment: Win7(x86)      net4.6.1     -Version 104.4.240
        browser = new ChromiumWebBrowser();
        //注册JS对象
        browser.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true;
        browser.KeyboardHandler = new CEFKeyBoardHander() { CanReload = WebAppContext.IsReload, CanShowDevTools = WebAppContext.IsShowDevTools };
        browser.DownloadHandler = new DownloadHandler();
        browser.MenuHandler = new ContextMenuHandler();
        browser.TitleChanged += OnBrowserTitleChanged;
        browser.LoadError += OnBrowserLoadError;
        browser.FrameLoadStart += Browser_FrameLoadStart;
        browser.FrameLoadEnd += Browser_FrameLoadEnd;
        browser.LoadingStateChanged += Browser_LoadingStateChanged;
        browser.IsBrowserInitializedChanged += Browser_IsBrowserInitializedChanged;
        browser.Dock = DockStyle.Fill;
        this.pnlWeb.Dock = DockStyle.Fill;
        this.pnlWeb.Visible = true;
        this.pnlWeb.Controls.Add(browser);
        browser.Load(WebAppContext.WebAppUrl)

debug.log
[0824/143124.770:VERBOSE1:pref_proxy_config_tracker_impl.cc(187)] 07884700: set chrome proxy config service to 07820000
[0824/143124.770:VERBOSE1:webrtc_internals.cc(120)] Could not get the download directory.
[0824/143124.770:VERBOSE1:media_stream_manager.cc(923)] MSM::InitializeMaybeAsync([this=078A8780])
[0824/143124.770:VERBOSE1:media_stream_manager.cc(923)] MDM::MediaDevicesManager()
[0824/143124.770:VERBOSE1:media_stream_manager.cc(923)] MSM::MediaStreamManager([this=078A8780]))
[0824/143124.786:VERBOSE1:first_party_sets_handler_impl.cc(181)] Empty path. Failed loading serialized First-Party Sets file.
[0824/143124.786:VERBOSE1:component_installer.cc(283)] StartRegistration for Widevine Content Decryption Module
[0824/143124.786:VERBOSE1:component_installer.cc(426)] FinishRegistration for Widevine Content Decryption Module
[0824/143124.786:VERBOSE1:component_updater_service.cc(131)] CrxUpdateService starting up. First update attempt will take place in 60 seconds. Next update attempt will take place in 18000 seconds.
[0824/143124.879:VERBOSE1:pref_proxy_config_tracker_impl.cc(187)] 07885A40: set chrome proxy config service to 0797E800
[0824/143146.226:VERBOSE1:network_delegate.cc(34)] NetworkDelegate::NotifyBeforeURLRequest: http://192.168.243.187:8090**
[0824/143146.242:INFO:cpu_info.cc(53)] Available number of cores: 4
[0824/143146.242:INFO:cpu_info.cc(53)] Available number of cores: 4
[0824/143146.273:VERBOSE1:media_stream_manager.cc(923)] RFAOSF::Core() [process_id=5, frame_id=1]
[0824/143146.273:VERBOSE1:network_delegate.cc(34)] NetworkDelegate::NotifyBeforeURLRequest: http://192.168.243.187:8090/css/chunk-vendors.5b38adc4.css
[0824/143146.273:VERBOSE1:network_delegate.cc(34)] NetworkDelegate::NotifyBeforeURLRequest:
Can anyone tell us what the LOAD (URL) has been doing for such a long time (about 22s  Bold Font)? how to optimize the loading speed,thank you.


text:
Q: Tabular view of data from normalized SQL database I've tried creating a normalized database, but I'm having trouble displaying the data in a tabular format.
In my example below, the database is used to track numbers (in various, arbitrarily-named categories) by date. As an example, a user may track how many fruits and vegetables are delivered to his grocery store each day. The user defines the names of the fruit and vegetable categories, and how many categories are present. Here are the tables corresponding to this example:
A tracker table:
 id |      name
----+---------------------
  1 | Grocery deliveries
  2 | Sports cars

An entries table:
 id |      datetime       | tracker_id
----+---------------------+------------
  1 | 2013-10-01 00:00:00 |          1
  2 | 2013-10-02 00:00:00 |          1
  3 | 2013-10-03 00:00:00 |          1

A values table:
 id | number | entry_id | category_id
----+--------+----------+-------------
  1 |   10.0 |        1 |          1
  3 |   20.0 |        1 |          2
  5 |   21.0 |        1 |          3
  7 |   18.0 |        2 |          2
  8 |    4.0 |        3 |          1
  9 |    9.0 |        3 |          2

And a category table:
 id |     name        | tracker_id
----+-----------------+------------
  1 | Tomatoes        |          1
  2 | Carrots         |          1
  3 | Brussel sprouts |          1
  4 | Ferraris        |          2

I'd like to print out a table for tracker 1, with each row corresponding to a date (no repeated dates). The columns would be: date, category 1 (Tomatoes), category 2 (Carrots), category 3 (Brussel sprouts). If there was no value for a given category on a given date, it would be empty or show as null. So, ideally, it would look something like this:
 datetime            | Tomatoes | Carrots | Brussel sprouts
---------------------+----------+---------+-----------------
 2013-10-01 00:00:00 | 10.0     | 20.0    | 21.0
 2013-10-02 00:00:00 | Null     | 18.0    | Null
 2013-10-03 00:00:00 | 4.0      | Null    | 9.0

I'm not sure how to do this, or if there's a better way to store this data. Any suggestions?
It was easy to display the data when the entries and values were represented by a single table (entries were rows, values were columns). But in that case, the maximum number of categories was limited by the number of columns in my table. I prefer how the normalized approach allows each "tracker" to represent an arbitrary number of categories.

A: I came up with an alternative using PostgreSQL's crosstab function, as suggested by @PM77-1.
Specifically, I'm using the crosstab(text source_sql, text category_sql) form of the function, as follows:
SELECT * FROM
  crosstab('SELECT e.datetime, v.category_id, v.number
            FROM entries e, values v
            WHERE v.entry_id = e.id AND e.tracker_id = 1 ORDER BY 1, 2',
           'SELECT id FROM categories WHERE tracker_id = 1 ORDER BY 1')
  AS (row_name timestamp without time zone,
      tomatoes numeric,
      carrots numeric,
      brussel_sprouts numeric);

With this approach, the AS (...) term must be unique for each tracker, since the number of categories and their names may be different for each tracker. In my case, I'm executing the query using Python and the psycopg2 module, so it's straightforward to generate the query dynamically. For instance,
# Retrieve the category names for the current tracker
cur.execute("SELECT name FROM categories WHERE tracker_id = " +
            str(tracker_id) + ";")
categories = cur.fetchall()
category_count = len(categories)

# Generate category string
cat_str = '';
for n in range(category_count):
    cat_str = cat_str + ", cat_" + str(n) + " numeric"

cur.execute("SELECT * FROM crosstab("
            "'SELECT e.datetime, v.category_id, v.number FROM entries e, values v"
            " WHERE v.entry_id = e.id"
            " AND e.tracker_id = " + str(tracker_id) +
            " ORDER BY 1, 2;',"
            " 'SELECT id FROM categories WHERE tracker_id =" +
            str(tracker_id) + "')"
            " AS (row_name timestamp without time zone" + cat_str + ");")

results = cur.fetchall()

The result has generic column names cat_0, cat_1, etc. instead of tomatoes, carrots, etc.. However, I pass both categories and results to an HTML template to render the table with the correct headings.

A: Here's how I would define your tables:
deliveries
    id          unsigned int(P)
    good_id     unsigned int(F goods.id)
    qwhen       datetime
    quantity    double

+----+---------+------------+----------+
| id | good_id | qwhen      | quantity |
+----+---------+------------+----------+
|  1 |       1 | 2013-10-01 |     10.0 |
|  2 |       2 | 2013-10-01 |     20.0 |
|  3 |       3 | 2013-10-01 |     21.0 |
|  4 |       2 | 2013-10-02 |     18.0 |
|  5 |       1 | 2013-10-03 |      4.0 |
|  6 |       2 | 2013-10-03 |      9.0 |
|  7 |       1 | 2013-10-01 |      3.0 |
| .. | ....... | ...........| ........ |
+----+---------+------------+----------+

good_types
    id                  unsigned int(P)
    name                varchar(50)

+----+-------------+
| id | name        |
+----+-------------+
|  1 | Groceries   |
|  2 | Sports cars |
+----+-------------+

goods
    id              unsigned int(P)
    good_type_id    unsigned int(F good_types.id)
    name            varchar(50)

+----+--------------+-----------------+
| id | good_type_id | name            |
+----+--------------+-----------------+
|  1 |            1 | Tomatoes        |
|  2 |            1 | Carrots         |
|  3 |            1 | Brussel Sprouts |
|  4 |            2 | Ferraris        |
| .. | ............ | ............... |
+----+--------------+-----------------+

And here's the SQL to get the column names:
SELECT id, name
FROM goods
WHERE good_type_id = 1

+----+-----------------+
| id | name            |
+----+-----------------+
|  1 | Tomatoes        |
|  2 | Carrots         |
|  3 | Brussel Sprouts |
+----+-----------------+

And here's the SQL to get the data to show in the table:
SELECT qwhen, good_id, sum(quantity) AS total
FROM deliveries d
LEFT JOIN goods g ON d.good_id = g.id
WHERE good_type_id = 1
GROUP BY qwhen, good_id

+------------+---------+-------+
| qwhen      | good_id | total |
+------------+---------+-------+
| 2013-10-01 |       1 |    13 |
| 2013-10-01 |       2 |    20 |
| 2013-10-01 |       3 |    21 |
| 2013-10-02 |       2 |    18 |
| 2013-10-03 |       1 |     4 |
| 2013-10-03 |       2 |     9 |
+------------+---------+-------+

So then you'll use PHP, Java or whatever your high-level language is to loop through the two query results to display the data. Below is PHP code to display the data and below the PHP code is an image showing you what is displayed.
// Get the column headers
$sql = 'SELECT id, name FROM goods WHERE good_type_id = 1';
$stmt = $pdo->prepare($sql);
$stmt->execute();

// Start our table.
echo '

';

// Print out the headers.
echo '
';
echo 'Date	';
while ($row = $stmt->fetch()){
    echo ''. $row['name'] .'	';
    $columns[$row['id']] = $row['name'];
}
echo '
';
echo '

';

// Get the data.
$sql = 'SELECT qwhen, good_id, sum(quantity) AS total FROM deliveries d LEFT JOIN goods g ON d.good_id = g.id WHERE good_type_id = 1 GROUP BY qwhen, good_id';
$stmt = $pdo->prepare($sql);
$stmt->execute();

// Manipulate the data into an array.
$save_date = NULL;
while ($row = $stmt->fetch()){
    if ($save_date !== $row['qwhen']){
        $save_date = $row['qwhen'];
        $data[$row['qwhen']] = array();
    }
    $data[$row['qwhen']][$row['good_id']] = $row['total'];
}

// Print out the table data.
foreach ($data AS $date => $cell){
    echo '
';
    echo ''. $date .'	';
    foreach ($columns AS $id => $name){
        echo '';
        if (isset($cell[$id])){
            echo $cell[$id];
        }else{
            echo ' ';
        }
        echo '	';
    }
    echo '
';
}

// End our table.
echo '

';


text:
Q: every gestures in touchpad is working except two fingers scrolling? (windows 10) My touchpad is working fine except for two fingers scrolling. Three and four fingers scrolling gesture are also fine.
The two fingers scrolling is only working in start menu, windows setting and every windows apps. other application like chrome, windows explorer, etc is not working
I've done updating touchpad driver, changing the pointer, and every guide in the internet but none of them worked.
My laptop is acer swift 3 SF314-54.
This scrolling gesture is very necessary to have for me so please help.
Note: The two fingers scrolling is working in windows 10 start menu, and every windows 10 application. But not working in other applications such as windows explorer, chrome, and every third-party applications.

A: You might try to install the Microsoft Precision Touchpad drivers.
These are made by Microsoft for Windows 10, with the intent by Microsoft
to create the "ideal" trackpad experience (just quoting).
Here are the steps to follow.
Check if you already have a Precision Touchpad
Navigate to Settings > Devices > Touchpad. If you see the text
"Your PC has a precision touchpad", you're already using a PC with a
Precision Touchpad, which means that these drivers are already installed,
so there is no point in continuing to the next section.
Have a physical mouse ready
Just In Case, ensure to have a physical mouse, in case you will lose
touchpad functionality after installing the Precision drivers.
You might also want to create a System Restore point, to be able to easily
revert to the old drivers if you need to.
Uninstall the current driver
If you have installed the Elan or Synaptics driver, uninstall it now.
In the Device Manager, right-click the touchpad, select Uninstall,
in the pop-up tick "Delete the driver software for this device" and press OK,
and finally reboot.
Download the drivers
Your driver is Elan, but I list here also Synaptics for other readers.

*

*Download Elan driver
from Softpedia

*Download Synaptics driver
from Lenovo
Install the Precision drivers

*

*Unzip to a temporary directory

*Start the Device Manager

*Under Mice and other pointing devices, right-click on the
Elan (Synaptics) device

*Choose Update driver

*Click Browse my computer for driver software

*Select Let me pick from a list of available drivers on my computer

*Pick Have Disk…

*Choose Browse… and navigate to the above folder

*Select Autorun.inf in the folder

*Select the Elan device (or Synaptics) and click Next

*On the message Update Driver Warning, choose Yes

*Let the driver install

*Restart the computer

For a more detailed description of the installation with screenshots see
How to enable a Precision Touchpad for more gestures on your laptop.


text:
Q: How to grant CreateRepository permission to create wikis in TFS Azure DevOps? I want to create Wiki using our TFS account (free account), we use Team Foundation Version Control not Git, but when I try to create wiki I get the error:

TF401027: You need the Git 'CreateRepository' permission to perform
  this action. Details: identity 'Windows Live ID\id@hotmail.com', scope
  'project'.

A: Internally, Wiki is stored as a Git repository in your Azure DevOps project. You can find more information describing the issue you're facing in the official documentation.
Here is the snippet:

On the Wiki landing page, choose Create Wiki to provision a new Git repository that will store all your wiki pages and related artifacts. (Even if you use TFVC for source control, you can create a wiki with a Git repository.)
...
You can contact your administrator to provision the Wiki Git repository or request that they elevate your permissions. Stakeholders can't be granted permissions to create a wiki as they have no permissions to work in Repos or Code.


text:
Q: asp.net mvc3 RouteLink I have just upgraded my mvc2 app to mvc3. And the routelink stopped working. any clue??
Global
routes.MapRoute(
            "Category",
            "category/{cat}/{subcat}/{page}/{viewall}",
            new
            {
                controller = "Category",
                action = "Index",
                cat = UrlParameter.Optional,
                subcat = UrlParameter.Optional,
                page = UrlParameter.Optional,
                viewall = UrlParameter.Optional
            }
        );

View
<%: Html.RouteLink("Women's", "Category", new { cat = "Women", subcat = "" })%>

This is how it renders
Women's

A: It's a regression bug, as explained by Phil Haack [ http://haacked.com/archive/2011/02/20/routing-regression-with-two-consecutive-optional-url-parameters.aspx ]

A: That's normal. You can have only one optional parameter and this parameter should be the last one in your route definition. So cat, subcat and page cannot be optional. You need to supply their values:
<%: Html.RouteLink("Women's", "Category", new {
    cat = "Women",
    subcat = "somesubcat",
    page = "123"
})%>

In ASP.NET MVC 3 this rule was enforced.
Consider the following urls:
category/1
category/1/2/
category/1/2/3
category/1/2/3/4

Only the last two urls are possible because it's the only case where the route parameters could be mapped to their corresponding values without ambiguity.


text:
Q: How can I make the redstone repeat a task x times and reset it self? So I'm trying to make a redstone circuit that can repeat a task x amount of times and then reset it self.
I was thinking of using a dropper and a hopper and use the hopper redstone signal (retrieved by a comparator) to check the amount, so lets say I need it to repeat a task 20 times, I place 20 items inside (along with the 3 items that are already inside the hopper, so it emits a 2 long signal once it has the 20 items from the dropper, I know how to do that part, but to the question, how can I make it reset to 3 on the hopper and 20 to the dropper?
The main question is the one described in the first paragraph and the title, the second one would be good to know, but idk if its possible.

A: As with most counting problems in Minecraft, the answer is eggs.
Take a look at my sample setup.

Redstone explanation

*

*To the right, we have a monostable circuit to shorten the input (the button) down to 1 tick. I use Sethbling's favored design, the repeater is set to 3.

*The Centerpiece is a Hopper-Dropper-Counter (a hopper and dropper pointing into each other), containing, in this case, 9 Eggs (or anything that stacks to 16) and 10 Cobblestone (or anything that stacks to 64), for a total of 19 items. You realize this is 1 short, but that's actually fine.

*The comparator turns to 3 when all items are in the hopper. In this case, the torch at the bottom of the picture turns off.

*The last component is a Repeater-Lock. On each button press, the hopper will update to whatever redstone signal is on the bottom torch before the button was pressed. So if it's at three bars after 19 clicks, it will unlock the hopper on the 20th click, causing all items to go back into the dropper.
To make something happen every 20th click, you should get the signal from the block next to the hopper (i.e. the state of the locked repeater), it is only ever off 1/20 of the time. You could put redstone dust underneath, or put a torch on top, for example (but watch out for signal inversion).

Design notice:  I used a variation of this for a three state enchanting room (lvl 1, lvl 18, lvl 30 enchants), using 2 wooden swords, and repeaters checking for a signal >0 and >3, respectively.

A: The circuit I ended up with when I came across similar task as question:

Posting just for further readers or something.


text:
Q: Example for Spring Cloud Consul with Ribbon for client side load balancing I see that spring-cloud-consul is live in spring.io [https://spring.io/blog/2015/05/27/spring-cloud-consul-1-0-0-m1-available-now] but I hardly see any reference examples.
I am mainly looking for Service Registration and Service Discovery with Consul and Ribbon as client side load balancer. Could someone give a sample application or an example to refer. I also checked in the git repository for spring-cloud-consul, didn't find any examples there[https://github.com/spring-cloud/spring-cloud-consul]

A: There is an example in the main repo, spring-cloud-consul-sample, that uses the LoadBalancerClient of which there is a ribbon implementation that will use consul to populate the server list.

A: I wasn't able to find much information about Consul and Ribbon, but I have found more information about Eueka (it's used by Netflix and it also does service registration/distcovery similiar to Consul). This Spring project seems to be a lot more active. Info about it can be found here: http://cloud.spring.io/spring-cloud-netflix/
This blog post demonstrates how to use spring cloud with Eueka and Ribbon: https://spring.io/blog/2015/07/14/microservices-with-spring
There is also a repo for the tutorial: https://github.com/paulc4/microservices-demo
If you still want to use Consul instead of Eueka, here is a sample project, you should be able to use this along with the blog post above to build a working example: https://github.com/spring-cloud/spring-cloud-consul/tree/master/spring-cloud-consul-sample

A: I wrote a demo project using Spring Cloud Consul and Spring Cloud Netflix.
I'm using Consul as a service registry, and Ribbon/Hystrix/Feign are used to simplify API service clients.
The project is hosted on GitHub: https://github.com/alexandreroman/number2words.


text:
Q: Function to represent the acceleration of a car I'm searching for a function that could represent the acceleration of a car.
The function has to rise fast from $(0,0)$ to a maximum and then fall slower. For $x\to \infty$ it should go to $0$.
Regards

A: you can take any $\frac{f(t)}{g(t)}$ where $g(t),f(t)$ polynomials and $deg(g(t) \geq deg(f(t))$ just make sure $f(0)=0$ and $g(0)\ne0$. For example look at $\frac{t}{t^2 + 1}$

A:
from here: $a(t)= t\cdot e^{-k(t-t_0)}$


text:
Q: Spring Boot Integration Test - BeanDefinitionOverrideException I have a Spring Boot Integration test with a class defined as follows.
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {TestApplication.class})
@Transactional
public class AuthorisationManagerControllerRequestIT
{
...

I get the below Exception:
Caused by: org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'org.springframework.transaction.config.internalTransactionAdvisor' defined in class path resource [org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.class]: Cannot register bean definition [Root bean: class [null]; scope=; abstract=false; lazyInit=null; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration; factoryMethodName=transactionAdvisor; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.class]] for bean 'org.springframework.transaction.config.internalTransactionAdvisor': There is already [Root bean: class [org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor]; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] bound.

My TestApplication class it is defined as follows:
@SpringBootApplication
@ComponentScan(excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Application.class)
})
@ImportResource({
        "classpath:properties-context.xml"
})
public class TestApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(TestApplication.class, args);
    }
}

It reads from properties-context.xml which is defined as follows:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/context
                            http://www.springframework.org/schema/context/spring-context.xsd
                            http://www.springframework.org/schema/util
                            http://www.springframework.org/schema/util/spring-util.xsd">

    <context:property-placeholder location="${CONFIG.ROOT}/external.properties"/>

</beans>

This reads from a file called external.properties. I have the property 'spring.main.allow-bean-definition-overriding=true' set in my external properties file.  I added this because when I was running the application before this same Exception was appearing, but no longer appears after adding this.
What is needed to stop this Exception appearing in my Integration Test?

A: Well, that seems logical given your error:
org.springframework.beans.factory.support.BeanDefinitionOverrideException is thrown when spring is creating a bean with the same name as one already created. And the properties spring.main.allow-bean-definition-overriding=true, which has been turned off by default for Spring-boot 2, is made to allow you bean override.
Which I don't understand is why you have 2 beans with the same regarding Transactions...


text:
Q: Delete multiple emty xml records? I'm trying to figure out how I delete multiple xml "records" if there is no attributes?
Here is what I have tried untill now:
$xml = new DOMDocument();
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;
$xml->loadXML('<friends>
  <friend id="779">
    <name>ML76</name>
    <games/>
    <wins/>
  </friend>
  <friend id="131">
    <name>Puttepigen67</name>
    <games/>
    <wins/>
  </friend>
  <friend id="17">
    <name>rikkelolk</name>
    <games>3</games>
    <wins>2</wins>
  </friend>
  <friend id="">
    <name/>
    <games/>
    <wins/>
  </friend>
  <friend id="">
    <name/>
    <games/>
    <wins/>
  </friend>
  <friend id="">
    <name/>
    <games/>
    <wins/>
  </friend>
</friends>');

echo "<xmp>OLD \n". $xml->saveXML() ."</xmp>";

$opNodes = $xml->getElementsByTagName('friend');
$remove = array();

foreach ($opNodes as $node) {
    if ($node->attributes() == ""){
        $remove[] = $node;
    }
}

foreach ($remove as $node) {
    $node->parentNode->removeChild($node);
}

echo "<xmp>NEW \n". $xml->saveXML() ."</xmp>";

I don't get anything in the last XML->saveXML().
What am I doing wrong?
Thanks in advance :-)

A: Use xpath.
$xml = new DOMDocument();
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;
$xml->loadXML('<friends>
  <friend id="779">
    <name>ML76</name>
    <games/>
    <wins/>
  </friend>
  <friend id="131">
    <name>Puttepigen67</name>
    <games/>
    <wins/>
  </friend>
  <friend id="17">
    <name>rikkelolk</name>
    <games>3</games>
    <wins>2</wins>
  </friend>
  <friend id="">
    <name/>
    <games/>
    <wins/>
  </friend>
  <friend id="">
    <name/>
    <games/>
    <wins/>
  </friend>
  <friend id="">
    <name/>
    <games/>
    <wins/>
  </friend>
</friends>');

$xpath = new DOMXPath($xml);

// prepare the xpath query to find the empty nodes
$node = $xpath->query("//friend[@id='']");

// if found, append the new "value" node
if( $node->length ) {
    foreach ($node as $n) {
        $n->parentNode->removeChild( $n );
    }
}
header('content-type: text/xml');
echo $xml->saveXML();

Hope it helps.


text:
Q: Most efficient way to combine two objects in C# I have two objects that can be represented as an int, float, bool, or string. I need to perform an addition on these two objects with the results being the same thing c# would produce as a result. For instance 1+"Foo" would equal the string "1Foo",  2+2.5 would equal the float 5.5, and 3+3 would equal the int 6 .  Currently I am using the code below but it seems like incredible overkill. Can anyone simplify or point me to some way to do this efficiently?
private object Combine(object o, object o1) {
    float left = 0;
    float right = 0;

    bool isInt = false;

    string l = null;
    string r = null;
    if (o is int) {
        left = (int)o;
        isInt = true;
    }
    else if (o is float) {
        left = (float)o;
    }
    else if (o is bool) {
        l = o.ToString();
    }
    else {
        l = (string)o;
    }

    if (o1 is int) {
        right = (int)o1;
    }
    else if (o is float) {
        right = (float)o1;
        isInt = false;
    }
    else if (o1 is bool) {
        r = o1.ToString();
        isInt = false;
    }
    else {
        r = (string)o1;
        isInt = false;
    }

    object rr;

    if (l == null) {
        if (r == null) {
            rr = left + right;
        }
        else {
            rr = left + r;
        }
    }
    else {
        if (r == null) {
            rr = l + right;
        }
        else {
            rr = l + r;
        }
    }

    if (isInt) {
        return Convert.ToInt32(rr);
    }

    return rr;
}

A: Can you use .NET 4.0? If so, it becomes very simple using dynamic typing:
private object Combine(dynamic o, dynamic o1)
{
    // Assumes an appropriate addition operator, found at execution time
    return o + o1;
}

Another alternative is to have a map of delegates for each pair of possible types. It's unfortunate that before .NET 4.0 there's no Tuple type, so you'll have to define your own TypePair type as the map key. Of course you then need to make sure you cover every possible pair... but at least the compiler can help when you've got a suitable "AddDelegate" method:
private void AddDelegate<T1, T2>(Func<T1, T2, object> sumFunction)
{
    // Put the function in the map
    ...
}

AddDelegate<int,int>((x, y) => x + y);
AddDelegate<int,float>((x, y) => x + y);
AddDelegate<int,string>((x, y) => x + y);
AddDelegate<float,int>((x, y) => x + y);
AddDelegate<float,float>((x, y) => x + y);
AddDelegate<float,string>((x, y) => x + y);
...

Btw, I've taken bool out of that as "addition" between a bool and a float (for example) doesn't make any sense. You can decide how you'd want to combine them though.
As Mitch says though, I'd revisit your design decisions - are you sure you really need this? It's a pretty odd requirement. Can you tell us anything about the bigger picture? We may be able to suggest alternative approaches.

A: You could just overload the method with the different types you want to use.  It's type-safe and simple.
    private string Combine(string o1, string o2) { return o1 + o2; }
    private string Combine(string o1, int o2) { return o1 + o2; }
    private string Combine(string o1, float o2) { return o1 + o2; }
    private string Combine(float o1, string o2) { return o1 + o2; }
    private float Combine(float o1, int o2) { return o1 + o2; }
    private float Combine(float o1, float o2) { return o1 + o2; }
    private string Combine(int o1, string o2) { return o1 + o2; }
    private float Combine(int o1, float o2) { return o1 + o2; }
    private int Combine(int o1, int o2) { return o1 + o2; }


text:
Q: Handle filter exception in control advice in spring boot Hi I have a global exception handler and I do something if exceptions occurs.But I have spring filters and spring filters cannot catch in my globalexceptionhandler.I read similar post in stackoverflow but still confused.Is there a way to catch filter exception in control advice
  @RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
public ResponseEntity handleAllException(Exception ex, WebRequest request){
 //To something in exception case
//Except filter exception All exceptions catched here
}


text:
Q: Split numbers and letters in a string Python How would I split numbers and letters in a string? So if given:
string = "12really happy15blob"

splitString = []
splitString = mySplitter(string)
print splitString

would return ["12","really happy","15","blob"]

A: You could use re.split here:
>>> import re
>>> re.split(r'(\d+)', "12really happy15blob")
['', '12', 'really happy', '15', 'blob']

Note that you actually get an empty string from splitting between the start of the string and the initial 12.  You'd have to filter that out if you didn't want it.


text:
Q: Compare two lists for similarity in Elixir I have two lists of skills that I'd like to compare to provide a percentage score for how much of one list appears in the other:
user_skills = [
  %{name: "Elixir"},
  %{name: "Python"}
]

project_skills = [
  %{name: "Elixir"},
  %{name: "Erlang"},
  %{name: "Ruby"}
]

What percentage of user_skills appear in project_skills? What we'd want here is a result of 50%.

A: You can be very simple and use Kernel.--/2 to calculate the difference first:
iex(5)> user_skills -- project_skills
# [%{name: "Python"}]

You can then use the length of the original list user_skills and the length of the above operation to get a percentage like figure:
iex(6)> 1 - (length(user_skills -- project_skills) / length(user_skills))
0.5

If you'd like to do more sophisticated comparisons and diffs, take a look at the myers_difference as well.


text:
Q: Convert Scala Any to Java Object I've a problem using Java Reflection from Scala. My Code:
case class MyClass(id: String, value: Double)

def create(values: Map[String, Any]): MyClass = {
   val constructor = classOf[MyClass].getConstructors.head
   val arguments = classOf[MyClass].getDeclaredFields().map( f => values(f.getName) )
   constructor.newInstance(arguments: _*).asInstanceOf[MyClass]
}

create(Map("id" -> "CE0D23A", "value" -> 828.32))

My problem is, that I need to pass a Map[String, Any], because one of the values is a Double, but newInstance needs Object, not Any.
I tried the same with scalas universe:
case class MyClass(id: String, value: Double)

def create(values: Map[String, Any]): MyClass = {
   val m = universe.runtimeMirror(getClass.getClassLoader)
   val myClass = universe.typeOf[MyClass].typeSymbol.asClass
   val cm = m.reflectClass(myClass)
   val ctro = universe.typeOf[MyClass].declaration(universe.nme.CONSTRUCTOR).asMethod
   val ctorm = cm.reflectConstructor(ctro)
   ctorm(values: _*).asInstanceOf[MyClass]
}

create(Map("id" -> "CE0D23A", "value" -> 828.32))

Problem here is, that I only introduced MyClass for the example. Later it should be a generic function like def create(values: Map[String, Any]): T. But then I got the following exception: "No TypeTag available for T"
Is there any way to transform these values?
Thank you

A: java.lang.Object is equivalent to AnyRef in Scala, not Any. The idea is, Scala Double (roughly equivalent to Java double) is an Any, but not an AnyRef. java.lang.Double is an AnyRef, thus also an Any.
You can simply cast an Any to AnyRef, which will perform the needed conversion to turn a Scala Double into a java.lang.Double:
scala> val x = 3.5
x: Double = 3.5

scala> x.getClass
res0: Class[Double] = double

scala> val y = x.asInstanceOf[AnyRef]
y: AnyRef = 3.5

scala> y.getClass
res1: Class[_ <: AnyRef] = class java.lang.Double

A: Ok, I was a bit late but here goes:
The following works:
constructor.newInstance(arguments.asInstanceOf[Array[AnyRef]]: _*).asInstanceOf[MyClass]

See also: Transforming Scala varargs into Java Object... varargs
Advice: I'd be very cautious using reflection. In Scala that is bad style. One way to limit/encapsulate it could be:
case class MyClass(id: String, value: Double)

object MyClass {

    import scala.util.Try
    def apply(map: Map[String, Any] /* this is asking for trouble */) : Option[MyClass]  =  for {
            id <- maybeT[String](map.get("id"))
            value <- maybeT[Double](map.get("value"))
        } yield MyClass(id, value)

    // a truly global utility?
    @inline def maybeT[T] ( a: Any /*Option[T]*/ ) : Option[T]= Try(a.asInstanceOf[Option[T]]).toOption.flatten //yep ugly as hell

}

MyClass(Map("id" -> "CE0D23A", "value" -> 828.32))


text:
Q: How to prevent the content in mobile devices to stop overflowing? I am experiencing a weird issue with my making my website responsive.
I basically have this output of my website on mobile devices:

Even though my body is set to overflow-x: hidden;, there is still white space and I can scroll on the x axis. I do not know why this is happening even though I have set it to hidden.
One thing, however, that might be making this happen is this right here:

When I scroll to the end of the website and then scroll on the x-axis to the farthest right, I see these things. Both the banner and the New icon should appear at the start of my website but somehow I see them at the bottom.
Basically, I am looking for this output:

I even added <meta name="viewport" content="width=device-width, initial-scale=1.0"> but I don't know why my website is not the same width as the device. Any suggestions?

A: Make sure your html element also has overflow-x: hidden:
html, body{
  overflow-x: hidden;
}


text:
Q: Send scheduled SMSs via Skype I would like to send programmed SMSs via Skype. I mean, I write a list with SMSs to different people that says; a) send a 04:30 a SMS to Joe "Wake up please, we meet at 05.30!", and so. The first idea that comes to my mind is somehow to call skype via linux shell using cron (although I do not know the right commands now), are there other alternatives?

A: You can use Perl to do this:
  CPAN - Net::DBus::Skype
  http://search.cpan.org/~ecarroll/Net-DBus-Skype-0.02/lib/Net/DBus/Skype.pm
  Perl SMS Sender via Skype API – kSMS
  http://intunsigned.co.uk/?p=77


text:
Q: Facebook Graph Request is returning name but not email I'm using the graph api to return my name and email from a Facebook login. This is the code I use - name comes back fine, but email is nil:
func getUserInfo() {
    let params = ["fields" : "email, name"]
    let graphRequest = GraphRequest(graphPath: "me", parameters: params)
    graphRequest.start {
        (urlResponse, requestResult) in

        switch requestResult {
        case .failed(let error):
            print("error in graph request:", error)
            break
        case .success(let graphResponse):
            if let responseDictionary = graphResponse.dictionaryValue {
                print(responseDictionary)

                if let name = responseDictionary["name"] {
                    self.nameLabel.text = "Logged in as: \n\(name)"
                }

                if let email = responseDictionary["email"] {
                    self.emailLabel.text = "Your email is: \n\(email)"
                } else {
                    self.emailLabel.text = "Your email is: "
                }
                print(responseDictionary["name"])
                print(responseDictionary["email"])
            }
        }
    }
}

This is what prints to my console:
["id": 1653899307960705, "name": *my name removed for privacy*]
Optional(*my name removed for privacy*)
nil

I'm not sure if my code is wrong or it's just a bug - I specify both email and name as my parameters, but as you can see only the name comes back. Anyone know why this is happening?

A: Your code is absolutely correct, there few possibilities that facebook graph API not providing email:

*

*Registered user has submitted its email but not validated

*User has set email (visibility) as private/limited access to friends only (not public)

Check account setting of an/your account (email is valid & validated as well as it is public)

A: I thing you forgot to take email permission, so here I am sharing you code to take permission.
func fbLoginInitiate()
    {
        let loginManager = FBSDKLoginManager()
        loginManager.logInWithReadPermissions(["public_profile", "email","user_friends"], handler: {(result:FBSDKLoginManagerLoginResult!, error:NSError!) -> Void in
            if (error != nil) {
                // Process error
                self.removeFbData()
            } else if result.isCancelled {
                // User Cancellation
                self.removeFbData()
            } else {
                //Success
                if result.grantedPermissions.contains("email") && result.grantedPermissions.contains("public_profile") && result.grantedPermissions.contains("user_friends"){
                    //Here you need to call your function for graphRequest
                    self.getUserInfo()
                } else {
                    //Handle error
                }
            }
        })
    }
func removeFbData()
    {
        //Remove FB Data
        let fbManager = FBSDKLoginManager()
        fbManager.logOut()
        FBSDKAccessToken.setCurrentAccessToken(nil)
    }


text:
Q: Best way to organize user inputs in a Python class with multiple functions I have a large class with multiple methods. The first function in the class asks for multiple user inputs and those values are used by multiple other functions in the class.
What would be the best way to 'centralize' these inputs and make them available to all functions within the class? Someone suggested to me that I should put those inputs as Class parameters so the user could see how many inputs are needed, as currently the user would not know if they will need to input two parameters or two hundred.
class Simulation:

    def pull_data(self):

        input1 = input()
        input2 = input()
        input3 = input()

    def simulate(self, input1, input2, input3)

Also what happens if my user inputs aren't always fixed, so for example imagine that the user first inputs a selection and then the subsequent inputs will depend on that. If they chose option a, then one set of inputs will be asked for, otherwise another set of inputs will be asked for. Could I still 'centralize' these all of the inputs even though half of them will never be used? For example
class Simulation:

    def pull_data(self):

        input1 = input()
        if input1 == 'bla':
            input2 = input()
            input3 = input()

        else:
            input2 = input() # these inputs are different questions to the above
            input3 = input()

    def simulate(self, input1, input2, input3)

A: Make the inputs as attributes to self.
class Simulation:

    def pull_data(self):

        self.input1 = input()
        self.input2 = input()
        self.input3 = input()

Now, you can refer to the inputs in any function in the class using self.input1, self.input2, and self.input3.
Check the docs for self


text:
Q: Multiple vulnerabilities in new CRA app , but the suggested "npm fix" is questionable I ran npx create-react-app project-a for my project and right away i found 27 vulnerabilities (16 moderate, 9 high, 2 critical) in my console.
As new developer this looks very scary, so i ran npm audit fix and noticed that many of them are related to Regular Expression stuff in browserslist , the npm audit fix didnt do anything, i still have 27 vulnerabilities.
After a bit of googling i found this closed github issue where the solution is apparently to move react-scripts to devDependencies ( that didnt remove the warnings ).

These warnings are false positives. There are no actual vulnerabilities affecting your app here.
To remove npm audit warnings, move react-scripts from dependencies to devDependencies in your package.json.

I found another github issue and someone said to add this to my package.json to change the version of the sub-dependency because react-dev-utils package uses a vulnerable version (7.0.9) of immer as a dependency ( it didnt fix it ).
 "resolutions": {
    "immer": "9.0.7",
    "ansi-html": "https://registry.yarnpkg.com/ansi-html-community/-/ansi-html-community-0.0.8.tgz",
    "ansi-regex": "5.0.1",
    "nth-check": "2.0.1",
    "glob-parent": "6.0.1",
    "browserslist": "4.18.1"
 }

At the very end of the audit it was suggested to run npm audit fix --force and that it includes breaking changes ! very-scary.
The breaking changes were this pretty much :
PS G:\Workspaces\React\project-a> npm audit fix --force
npm WARN using --force Recommended protections disabled.
npm WARN audit Updating react-scripts to 0.9.5,which is a SemVer major change.

Big jump right there from version 4.0.3 down to 0.9.5 and of course it resulted in 43 vulnerabilities , and it suggested running npm audit fix --force yet again to go back to 4.0.3, so i did :
npm WARN audit Updating react-scripts to 4.0.3,which is a SemVer major change.

It's an infinite loop , going back and fourth between react-scripts 0.9.5 and 4.0.3 .

My Node version is : 16.13.1
My NPM version is : 8.1.2
I dont have CRA installed globally.
My Package.json :
{
  "name": "project-a",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/css": "^11.5.0",
    "@emotion/react": "^11.7.0",
    "@emotion/styled": "^11.6.0",
    "@mui/icons-material": "^5.2.1",
    "@mui/material": "^5.1.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "styled-components": "^5.3.3"
  },
  "devDependencies": {
    "react-scripts": "^4.0.3"
  },
  "resolutions": {
    "immer": "9.0.7",
    "ansi-html": "https://registry.yarnpkg.com/ansi-html-community/-/ansi-html-community-0.0.8.tgz",
    "ansi-regex": "5.0.1",
    "nth-check": "2.0.1",
    "glob-parent": "6.0.1",
    "browserslist": "4.18.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

A: You can use npm >8.3.0 with the overrides feature.
Just add to package.json:
...
"overrides": {
    "immer": "9.0.7",
    "ansi-html": "https://registry.yarnpkg.com/ansi-html-community/-/ansi-html-community-0.0.8.tgz",
    "ansi-regex": "5.0.1",
    "nth-check": "2.0.1",
    "glob-parent": "6.0.1",
    "browserslist": "4.18.1"
  },
...


text:
Q: Can I use one layout with diffrent strings? I am trying to make a book app with a list view of say 10 chapters but I don't want to make 10 activities and 10 layouts for these chapters isn't there a way for me to change the text view string based on with list item I chose that will use one layout but change strings depending on with list view item I chose. Recently began with java still at noob level I would really appreciate detailed explanations.
I am still a beginner so I don't really understand much about strings

A: You need to get a reference to the TextView by setting this attribute within your textView in XML
android:id="@+id/textViewName
Once you have this you can tap into the android:text property programmatically and change it based on what chapter you're on.

A: Of course you can! The method depends on the element you'll use
Or just replace bellow "Book.CurrentChatpter.title" by your title
If you want to change the ActionBar's text :
ActionBar ab = getActionBar();
ab.setTitle(Book.currentChatpter.title);

for a TextView's text:
TextView tv = (TextView)findViewById(R.id.yourTextView);
tv.setText(Book.currentChatpter.title);

Thanks Mike ! Edited the TextView's id

A: Couple of ways you can achieve this :
1. Page array list  -> keep next and previous button an keep the current index reference to navigate back forth on click event.

*Show horizontal recycler view list contain book pages list items


text:
Q: What mail program offers spam filtering and a unified way to check multiple mailboxes? I have been using Mail and I really don't like it. I have tried Thunderbird, Entourage and Postbox and do not like any of them either.
I need a clear and unified way to check all my mails and also a very non-intrusive spam filter.
Edit: The thing, that I hate about Mail is:

*

*Its hard to get a collated view of all my mails. I have multiple classifications, that does not make much sense, some mails end up in Important and Junk at the same time. What is the point of having both Junk and Spam.

*Sent Items are not maintained properly. I would expect the items sent from other mail client to be visible.

*The Junk mail algorithm is faulty and I have missed a whole lot of important mails recently.

*Maintaining multiple account is difficult. I have found myself sending same email thread using different email accounts. ( I think mail has memory on what is the last used email account)

*Mail threads are difficult to read. It creates multiple copy of the mail thread.
What I would like in the optimal email client:

*

*Simple, single unified view.

*Seamless handing of multiple email accounts.

*Ability to handle Hotmail and Microsoft exchange accounts.

*Better Junk mail classification algorithm.

*Maintain better record of past conversations, including sent mails.

*Good interoperability with Calendar and possibly other related services (like chat client).
Edit 2: I had further analyzed my problem with Mail and I have found out, that the problem has been with Gmail's interaction with Mail. I was quick to judge, Mail as a faulty piece of software. I have found an very useful link, that has addressed, almost all of my problems, http://www.macworld.com/article/1157846/mailgmail.html. Sorry again, for a very nebulous question and being very judgmental. (I am a programmer, judging things is in my genes ;) )
Also I have been  trying SpamSieve and the faulty behavior of spam filter is mostly user error. In this case, me providing faulty training data to the software, by clicking on all junk emails and not marking enough mails as junk.

A: Its hard to pick a best it really is up to what works best for you! I would recommend searching around for more mac e-mail clients using your favorite search engine and try as man as you can.  This Wikipedia list will get you started Comparison of email clients for some more e-mail clients to research.


text:
Q: Взаимная передача информации между активностями: непонятен принцип работы Здравстуйте, нужна помощь. Есть 2 активности Java. В одной есть лист, который нужно передать во вторую активность. Во второй происходит изменение одного из элементов листа и обратная передача листа в первую активность. Вопрос: как реализовать передачу этого листа в обе стороны?

A: https://startandroid.ru/ru/uroki/vse-uroki-spiskom/68-urok-29-vyzyvaem-activity-i-poluchaem-rezultat-metod-startactivityforresult.html
по такому принципу передаём ваш объект:
//при нажатии на элемент списка вынимаем его и передаём в новое активити
intent.putExtra("itemObject", itemObject)
startActivityForResult(intent, 1);

Потом возвращаете его и обновляете в списке.
Для того что бы передать объект через Intent нужно его сериализовать: Serializable или Parcelable, в Android правильнее использовать Parcelable он производительнее.


text:
Q: Cannot change VIDEO tag size via InvokeScript of WPF WebBrowser control I do very simple thing: I need to change VIDEO tag size via InvokeScript of WPF WebBrowser control.
So it shows "Hello" but size doesn't changes at all.
Note: If i open this page directly it changes size fine for any browser.
private void btSize_Click(object sender, RoutedEventArgs e)
{
   wb.InvokeScript("SetVideoSize");
}

function SetVideoSize() {

            try {
                document.getElementById("player1").style.height = '400px';
                document.getElementById("player1").style.width = '400px';
                alert('Hello2');
  } catch (e) {
               // alert(e.Message);
            }
        }

 <video width="10" height="10" style="margin: 0 !important; padding: 0 !important;
        overflow: hidden;" id="player1" name="mplayer1"  src="http://mysite.com/files/werweB"  type="video/mp4">
    </video>
     <script type="text/javascript">
        MediaElement('player1',
        {
            success: function (me) {
                me.play();
            }
        });
    </script>

I even tried to do:
mshtml.HTMLDocument doc = (mshtml.HTMLDocument)wb.Document;
var player = doc.getElementById("player1");
player.setAttribute("width", "400");
player.setAttribute("height", "400");

But there is no any visual changes at all...

A: I spent two days searching and this is what I found:
All you have to do is add the following meta tag to your HTML:
<meta http-equiv="X-UA-Compatible" content="IE=9" >


text:
Q: Change background button color on click I'm developing Windows Phone 8 app and I have two buttons. Once I click on the first one it's color is changed, but when I click on the second one and its color is changed as well the color of the first button is not set to default. I can't access first button from the click event of the second one. How can I highlight one button and set color of another one to default on click?
EDIT: Here I can't access second button within the first event handler.
private void firstButton_Click(object sender, RoutedEventArgs e)
{
    (sender as Button).Background = new SolidColorBrush(Colors.Green);
}

private void secondButton_Click(object sender, RoutedEventArgs e)
{
    (sender as Button).Background = new SolidColorBrush(Colors.Green);
}

A: Why can't you access the first button from the second one? Normally you could do something similar like this:
private void firstButton_Click(object sender, RoutedEventArgs e)
{
    (sender as Button).Background = new SolidColorBrush(Colors.Green);
    secondButton.Background = new SolidColorBrush(Colors.LightGray);
}

private void secondButton_Click(object sender, RoutedEventArgs e)
{
    (sender as Button).Background = new SolidColorBrush(Colors.Green);
    firstButton.Background = new SolidColorBrush(Colors.LightGray);
}

And for reusability perhaps throw it in a method:
private void SetButtonColor(Button toDefaultColor, Button toGreenColor)
{
    toGreenColor.Background = new SolidColorBrush(Colors.Green);
    toDefaultColor.Background = new SolidColorBrush(Colors.LightGray);
}

private void secondButton_Click(object sender, RoutedEventArgs e)
{
    SetButtonColor(firstButton, (sender as Button));
}


text:
Q: How to have version and audit information inside a nested object in springboot-MongoDB? I have a version and auditing info in the @document class and it works fine.
Note:using this org.springframework.data.annotation.Version;
EmployeeModelDTO.java
@Getter
@Setter
@Builder
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "unt-employee")
public class EmployeeModelDTO implements Serializable {
    private static final long serialVersionUID = 1L;
    private String type;
    @Field("group")
    private GroupDTO groupDTO;

    @Id
    @JsonAlias("id")
    String id;

    @Version
    Integer schema_version;

    @LastModifiedDate
    LocalDateTime updatedDateTime;

    @CreatedDate
    LocalDateTime createdDateTime;
}

But if i try to put it inside a nested objects it is not getting inserted into mongo db
I need to have it inside GroupDTO.java
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
@NoArgsConstructor
@AllArgsConstructor
public class GroupDTO{

    @Id
    @JsonAlias("id")
    String id;

    @Version
    Integer schema_version;

    @LastModifiedDate
    LocalDateTime updatedDateTime;

    @CreatedDate
    LocalDateTime createdDateTime;

}

So if I put the version and other info inside this class, it is not getting populated. Can any one let me know if having the version and other info inside the nested class is possible ?


text:
Q: ImageMapster - jquery/html issue I am having a few issues with the jquery plugin (ImageMapster). ImageMapster has provided a demo jsfiddle to test out their demo, they use one resource and the rest is right in front of you: http://jsfiddle.net/nYkAG/396/
If you hover over the image, you will be able to several small boxes and when you hover over them, you will see a description under the image. (if it doesnt work then try clicking on the image itself). It uses the area tag.
I tried to use the same method and implement it on a normal HTML site. However, its not working and i cannot understand what i have done wrong to the jsfiddle that is not working.
Example SIte: http://www.nina-naustdal.com/index1.html
Its Exactly the same site, which is annoying. Can someone shed some light onto this issue.
Thanks again for your assistance.

A: Just wrap your code in
$(function(){
   // Your code
});

or
$(window).load(function(){
   //Your code
});

You are accessing #beatles before loading it in DOM.
Its running under jsfiddle because it is wrapping in $(window).load(function(){


text:
Q: PostgreSQL update a jsonb column multiple times Consider the following:
create table query(id integer, query_definition jsonb);
create table query_item(path text[], id integer);
insert into query (id, query_definition)
values
    (100, '{"columns":[{"type":"integer","field":"id"},{"type":"str","field":"firstname"},{"type":"str","field":"lastname"}]}'::jsonb),
    (101, '{"columns":[{"type":"integer","field":"id"},{"type":"str","field":"firstname"}]}'::jsonb);
insert into query_item(path, id) values
    ('{columns,0,type}'::text[], 100),
    ('{columns,1,type}'::text[], 100),
    ('{columns,2,type}'::text[], 100),
    ('{columns,0,type}'::text[], 101),
    ('{columns,1,type}'::text[], 101);

I have a query table which has a jsonb column named query_definition.
The jsonb value looks like the following:
{
  "columns": [
    {
      "type": "integer",
      "field": "id"
    },
    {
      "type": "str",
      "field": "firstname"
    },
    {
      "type": "str",
      "field": "lastname"
    }
  ]
}

In order to replace all "type": "..." with "type": "string", I've built the query_item table which contains the following data:
path            |id |
----------------+---+
{columns,0,type}|100|
{columns,1,type}|100|
{columns,2,type}|100|
{columns,0,type}|101|
{columns,1,type}|101|

path matches each path from the json root to the "type" entry, id is the corresponding query's id.
I made up the following sql statement to do what I want:
update query q
set query_definition = jsonb_set(q.query_definition, query_item.path, ('"string"')::jsonb, false)
from query_item
where q.id = query_item.id

But it partially works, as it takes the 1st matching id and skips the others (the 1st and 4th line of query_item table).
I know I could build a for statement, but it requires a plpgsql context and I'd rather avoid its use.
Is there a way to do it with a single update statement?
I've read in this topic it's possible to make it with strings, but I didn't find out how to adapt this mechanism with jsonb treatment.


text:
Q: Linux assembly; argument list going haywire I'm new to programming in any sort of assembly, and since I've heard that NASM-type assembly for Linux is comparatively simple to DOS based assembly, I decided to give it a try.
This is my program thus far:
section .data
    opening:    db  'Opening file...',10
    openingLen: equ $-opening
    opened:     db  'File opened.',10
    openedLen:  equ $-opened
    bad_params: db  'Usage: writeFile filename.ext',10
    bad_paramsLen:  equ $-bad_params
    not_opened: db  'Unable to open file.  Halted.',10
    not_openedLen:  equ $-not_opened
    hello:      db  'Hello, this is written to a file'
    helloLen:   equ $-hello
    success:    db  'Successfully wrote to file.',10
    successLen: equ $-success

section .bss
    file:       resd    1

section .text
    global _start:

_start:
    pop ebx             ; pop number of params
    test ebx,2          ; make sure there are only 2
    jne bad_param_list
    pop ebx

    mov eax,4           ; write out opening file msg
    mov ebx,1
    mov ecx,opening
    mov edx,openingLen
    int 80h

    mov eax,5           ; open file
    pop ebx
    mov ecx,64
    mov edx,777o            ; permissions of file
    int 80h
    mov dword [file],eax

    test dword [file],0
    jle bad_open

    mov eax,4           ; write successful open message
    mov ebx,1
    mov ecx,opened
    mov edx,openedLen
    int 80h

    mov ebx,file            ; write to file (4 already in eax)
    mov ecx,hello
    mov edx,helloLen
    int 80h

    mov eax,6           ; close file
    mov ebx,file
    int 80h

    mov eax,4           ; write successfully written msg
    mov ebx,1
    mov ecx,success
    mov edx,successLen
    int 80h

    mov eax,1           ; exit
    mov ebx,0
    int 80h

bad_param_list:
    mov eax,4           ; write that params are bad
    mov ebx,1
    mov ecx,bad_params
    mov edx,bad_paramsLen
    int 80h

    mov eax,1           ; exit with code 1
    mov ebx,1
    int 80h

bad_open:
    mov eax,4           ; write that we couldn't open the file
    mov ebx,1
    mov ecx,not_opened
    mov edx,not_openedLen
    int 80h

    mov eax,1           ; exit with code 2
    mov ebx,2
    int 80h

The goal is to write a string of text to a file without library functions; I'm only using the Linux kernel.  I had a few problems with missing brackets here and there, and all the rest of mistakes that you'd expect from a noob to assembly, but I think this is mostly under control now.
Here's my issue:  From what I know, the first four lines of this program should pop the number of arguments off the stack, jump to bad_param_list if there is not only one parameter (aside from the program name), and pop the program name off the stack.
But this is not what happens.  Here's some sample I/O, reformatted for clarity:
$./writeFile
Opening file...
Unable to open file.  Halted.

$./writeFile x
Usage:  writeFile filename.ext

$./writeFile x x
Usage:  writeFile filename.ext

$./writeFile x x x
Opening file...
Unable to open file.  Halted.

$./writeFile x x x x
Opening file...
Unable to open file.  Halted.

$./writeFile x x x x x
Usage:  writeFile filename.ext

$./writeFile x x x x x x
Usage:  writeFile filename.ext

What I've noticed is that if you take the number of arguments including the name of the program, divide by 2, and discard the decimal, if the answer is odd, you'll get my usage error, but if the answer is even, you'll get the unable to open error.  This is true up until at least 10 arguments!
How the heck did I manage to do this?  And how do I get it to have the expected result?

A: Instead of
test ebx,2

you want
cmp ebx,2

test performs a bitwise AND between the arguments and throws the result away, except for setting the flags. So, in particular ZF will be set if the two arguments have no 1-bits in positions that match. (In your particular case, this works out as setting ZF to the complement of the second-to-lowest bit of ebx).
Conversely cmp subtracts its arguments and throws away the result after setting flags. In that case, ZF will be set if the two arguments are equal.