text:
Q: Limiting joined ForeignKey query using SQLAlchemy I'm getting inaccurate results when I call limit on my query and I'm not sure what's causing it.
models:
class Voter(db.Model):
    histories = db.relationship('VoterHistory', backref='voter', lazy='dynamic')
    ncid = db.Column(db.String(80),unique=True)

class VoterHistory(db.Model):
    voter_ncid = db.Column(db.String(80), db.ForeignKey('voter.ncid'))
    election_lbl = db.Column(db.String(280))

example
q1 = Voter.query.filter_by(birth_age='25')

q2  = db.and_(Voter.histories.any(VoterHistory.election_lbl == '11/03/2015'),
      Voter.histories.any(VoterHistory.election_lbl == '03/15/2016'))

res= q1.join(Voter.histories).filter(q2)

If I call .count on res I get a ~4000 results. If I do res.limit(3000).all() I get about 700 results.
What's going on here and how can I fix it? I'm trying to get 3000 Voter objects.

A: There are two things in play here, which together seem to produce inconsistent result:

*

*limit applies to the SQL query, indeed limiting number of rows which are returned by the query

*when you query for mapped instances, sqlalchemy will drop the duplicates.

In your case, setting a limit of 3000 will indeed limit the number of rows returned from the SQL to 3000 rows, but if within those 3000 rows there are only 700 distinct rows of the Voter class, only 700 such instances will be returned.
In your case the .join(Voter.histories) looks to be the one which introduces this non-correspondence between the number of rows returned from the database and the number of Voter instances.

I hope this is clear. If not, I am happy to provide an example.


text:
Q: Micro services: shared library vs code duplication Similar questions were asked a few times, but as every use-case can be different I thought it worth to ask it again with the specific case I'm facing with.
So, we are developing micro-services using .netCore.  Let's call these services ServiceA, ServiceB, ServiceC.
Common entities
If ServiceA calls  ServiceC, then ServiceC responds with a JSON content which can be serialized into ResponseC object.
This means, that both ServiceA and ServiceC should know ResponseC class.
At this point I see two possibilities. ResponseC class can be in a shared library and both ServiceA and ServiceC should have a reference to this shared library.
However I read statements like do not share libraries among micro-services. This leads to an other possible solution. Let's introduce ResponseC class in both micro-services, but then somehow I find this a bit against maintainability, because of code duplication.
Common logic
Both ServiceA and ServiceB communicates with ServiceC. When communicating with ServiceC we intend to have some policy regarding read and connection timeout and regarding the maximum number of retries. These values are configurable and there is also some common parts in the retry logic to be able to read the relevant values from the configuration file and to wrap the http calls.
The question is pretty much the same like in the previous case, because I either put these classes into a shared library or I basically introduce the same classes in both ServiceA and ServiceB. These classes are quite simple and generic, so at the moment I cannot imagine, that these classes will change frequently.
So the question is, that what is better in these cases, duplicate code and having independent micro-services or introduce a shared library which makes these services dependent?

A: When it comes to model classes, I say duplicate code. The entire idea of using JSON or some other language independent protocol instead of serialized native Java objects (for example) is to avoid side-effects of class changes in one microservice rippling throughout your entire ecosystem. A shared library of model classes locks multiple microservices into a polygamous marriage contract where divorce precipitated by even small disagreements between a pair of members can be very expensive. Service A may require changes to its model that not only are unneeded by Service B, but might be totally incompatible with it.
This doesn't mean that code cannot be shared across different microservices. There's nothing wrong with sharing libraries among different microservices as long as their functionality is limited to addressing cross-cutting concerns. Perhaps your common timeout and retry functionality you mentioned falls in the category. Model classes that do nothing but hold a data representation of a language independent protocol do not fall into this category in my opinion.

A: Of course there is DRY rule in programming. But, as Sam Newman said in his book "Building Microservice": Don't Repeat Yourself inside one microservice.
Common entities:
Let's look at your example with ResponseC. Imagine that something in ServiceB has changed so now one of the field from the response have changed - now you have to update each service that uses this shared library, even if the service don't need this changed field. If you had the ResponseA, ResponseB and ResponseC for each service, you didn't had to update each service with the new dependency.
Common logic:
Basically the same rules are applied here. However it's common to use some third party libraries for common microservices issues like time-outs and retries. What else I can suggest is to look at service mesh implementation like istio and linkerd. Service mesh will give the possibility to these issue to the infrastructure layer so you can focus on writing business logic.

A: I agree with the comments above in preferring duplicating the class code.  I went down the road of distributing shared classes via an internal NuGet server and it didn't work well.  The different microservice consumers of the JSON started out using the NuGet class, but soon were asking for changes that would break the others.  All consumers eventually ignored the NuGet class and created their own.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I run a command automatically upon connecting to a Bluetooth device? Background:
I'm using a Bluetooth mouse with my computer. I'm left-handed, and I need to run this command:
xinput set-button-map 'RAPOO BT3.0 Mouse' 3 2 1

every time it connects, because it resets to default buttons for some reason. I've aliased this command to left. Sometimes I have to connect to the mouse manually using bluetoothctl, like so:
alias mouse="bluetoothctl power on && bluetoothctl connect B4:EE:25:C2:0E:04"

In that case, it should be easy enough to add this to the alias:
alias mouse="bluetoothctl power on && bluetoothctl connect B4:EE:25:C2:0E:04 && sleep 3 && left"

However, sometimes the mouse connects automatically to my computer, and in that case I also want to run the left command.
The question:
Is it possible to run a command automatically every time a specific Bluetooth device connects to the computer?

A: Make a script with the commands.
Then use:
sudo tail -f /var/log/syslog

to get the idVendor and the idProduct, then write the udev rule to /etc/udev/rules.d/50-my_bluetooth_rule.rules as follows:
ACTION=="add" , SUBSYSTEM=="usb", ATTR{idVendor}=="xxx", ATTR{idProduct}=="yyy", RUN+="/home/myhome/my_script"

Run:
sudo service udev restart
sudo tail -f /var/log/syslog

Reconnect your bluetooth device. You can use logger in your bash script to write messages to syslog.

From here


text:
Q: No module named 'flask' despite package being isntalled? I was previously using Thonny as my IDE which was good. But I wanted GitHub integration so I decided to switch to PyCharm.
I created a virtual environment for the project inside of the project directory and installed all of the packages including Flask, Flask-WTF, Flask-Login, PyMongo, etc.
When I run the file I get 'No module named 'flask''
I am not sure what I am doing wrong!

A: Switch to virtualenv by your OS-specific command and then install flask and its modules.
For more info: Flask ImportError: No Module Named Flask


text:
Q: IE10's Flexbox : differences between March 2012 Draft and current frozen version I found differences in the flexbox implementation of IE10 and Chrome/Firefox. According to first answer here : Flexbox layout does not work in Internet Explorer 10 IE10 is based of an older, working version of the Flexbox standard.
In practice, for me, I have to treat as bugs the differences between the IE10 implementation and others browsers more compliant to the frozen standards (pardon my too vague vocabulary).
Does somebody know about list compiling those difference, or about way to find them out ? Ideally I am also looking for know solutions/workaround.
The specific bug I face is that a flex element set to 100% uses 100% of its parents width, instead of using 100% of the available width. But I am at first looking for an elegant way to treat those flexbox implementation differences.
Many thanks
Olivvv
EDIT: What I am looking for, is to learn about IE10 specific flexbox implementation, which is different form the flexbox in chrome and FF (latest flexbox draft).

A: Those ressources are helpful at finding out what is the IE10 specific syntax for flex box. IE10 flexbox version is based on the march 2012 draft (http://www.w3.org/TR/2012/WD-css3-flexbox-20120322/).
http://msdn.microsoft.com/en-us/library/ie/hh772069(v=vs.85).aspx
http://zomigi.com/blog/flexbox-syntax-for-ie-10/
My question has been downvoted, I am curious to know why. When coding flexbox with IE10 as requirement, then the specific syntax for IE10 is relevant to know.

A: If you're using Modernizr, then Modernizr 3 will have a new feature detection test called flexboxtweener that will detect this and allow you to include correct behavior when this condition is present, but as of right now you could do the test yourself, which is
Modernizr.addTest('flexboxtweener', testAllProps('flexAlign'));

See https://github.com/Modernizr/Modernizr/issues/812


text:
Q: How to Keep a Service Running in a Detached Container? Using docker to deploy a uvicorn server to serve some tensorflow model. The end of the dockerfile looks like this.
# Start ASGI server
CMD ['./runserver.sh']

The runserver.sh looks like this
#!/usr/bin/env bash
# encoding:utf-8
# This is a blocking call
uvicorn gateway:app --host=0.0.0.0 --workers 20 # Default port 8000

This is the command I am using to start the container
docker run --detach --publish 8000:8000 tensor_image

My expectation and goal:
The container will stay alive until killed with a docker stop command and a client can send request to the uvicorn server.
What is happening:
The docker run command just echoes a long id of the container on terminal and then the container dies.
How to keep it running? Also, how to view the server log itself if I make uvicorn log its content to a local file inside the container?
Using Linux mint ulyana as my operating system if that is important. Some additional clari

A: Your problem has to do with the way docker runs your containers.
The main process your container will run depends on the combination of two Dockerfile instructions, ENTRYPOINT and CMD.
In a nutshell - please, consider review for instance this related SO question for a deeper insight - ENTRYPOINT defines the command that will be run when your container starts. The default ENTRYPOINT command is /bin/sh -c and it cannot be overwritten by the docker command line.
On the other hand, CMD could be consider as a complement, arguments, that will be appended to the provided ENTRYPOINT. It will be overwritten in case you provide some arguments when running your container.
With this background, I think you could run your application in several ways.
For instance, by making your Dockerfile ENTRYPOINT the actual shell script you want to run:
ENTRYPOINT ["./runserver.sh"]

Other, by using CMD but modifying your runserver.sh script and run uvicorn with exec:
#!/usr/bin/env bash
# encoding:utf-8
# To run in production with multiple slaves
exec uvicorn gateway:app --host=0.0.0.0 --workers 20 # Default port 8000

exec triggers the process running the script to be replaced with the command given, instead of starting it as a new process, which is the default behavior when running a shell command.
You can use CMD and provide the uvicorn command directly as well - it should be visible for your PATH variable:
CMD ["uvicorn", "gateway:app", "--host", "0.0.0.0", "--workers", "20"]

Performing any of these changes will ensure that the container is not terminated early.

A: In order to detach a container you have to run for CMD statement in blocking mode.
In your case, which I cannot reproduce, you should run uvicorn not as a daemon, but as a blocking application.


text:
Q: Cargar traductor en pagina web Tengo una pagina web a la cual le cree la función de traducción, pero creé unas paginas alternativas las cuales se cargan por js, no traduce y no se por que.
Esas paginas son templates de cakephp, la verdad no creo que eso afecte.
Estos son los códigos:
(function ($) {
 $.traducir = function () {
        $('.lang').each(function (index, element) {

            if ($(this).attr('key').indexOf("txt") === 0) {
                $(this).attr("placeholder", arrLang[lang][$(this).attr('key')]);
            } else if ($(this).attr('key').indexOf("btn") === 0) {
                $(this).val(arrLang[lang][$(this).attr('key')]);
            } else if ($(this).attr('key').indexOf("img") === 0) {
                $(this).attr("alt", arrLang[lang][$(this).attr('key')]);
            } else {
                $(this).text(arrLang[lang][$(this).attr('key')]);
            }
            alert(arrLang[lang][$(this).attr('key')]);
        });
    }

})(jQuery);

Esa es la función para traducir:
(function ($) {
$.mostrar = function (id) {
        $.wizard(0, id);
        $(".xMenu").removeClass("cerrarMenu");
        $(".menuContenido").removeClass("verMenu");
        $(".xMenu").removeClass("mostrarElemento");
        $(".xMenu").addClass("ocultarElemento");
        $(".circle").css({"z-index": "100"});
        if ($("#div" + id).attr("id") !== $('div.principal').children('div').attr("id")) {
            $(".principal").css({'position': 'absolute'});
            $(".secundario").css({'position': 'absolute', "left": "1500px"});

            $(".principal").height($(window).height() - 100);
            $(".principal").width($(window).width() - 100);
            $(".secundario").height($(window).height() - 100);
            $(".secundario").width($(window).width() - 100);
            $(".principal").animate({
                left: "-=1500",
                width: "100%",
                opacity: "toggle"
            }, {
                duration: 2000,
                queue: false
            });
            $(".secundario").animate({
                left: "-=1480",
                width: "100%",
                opacity: "toggle"
            }, {
                duration: 2000,
                queue: false
            }).promise().done(function () {
                $(".principal").css({'position': '', 'left': '20px', 'display': ''});
                $(".principal").height("");
                $(".principal").width("");
                $(".principal").html($(".secundario").html());
                $(".secundario").height("");
                $(".secundario").width("");
                $(".secundario").css({'left': '1500px', 'position': '', 'display': ''});
                $(".secundario").hide();
                $(".secundario").html("");
            });
        }
        $.wizard(1, id);
        url = (id === "Home") ? "" : "Form/"+id;
        window.history.pushState("", "", '/Desarrollo/' + url);
    }
 })(jQuery);

Esta es la función con la que muestro un div que es un template y oculto otro:
$(document).ready(function () {
    $(".linkMenuHome").on('click', function (event) {
        event.preventDefault();
        $('.secundario').load(this.href);
        $.mostrar("Home");
    });
    $(".linkMenuNeeds").on('click', function (event) {
        event.preventDefault();
        $('.secundario').load(this.href);
$.traducir();
        $.mostrar("Needs");

    });
});

Ahí se supone que debe traducir pero no lo hace.

A: El problema es que la función .promise() es asíncrona, por lo tanto cuando cargas tu elemento la función $.traducir() ya se ejecutó en algún momento, para solucionarlo puedes ejecutar la función una vez terminada la promesa de jQuery
}).promise().done(function () {
    $(".principal").css({'position': '', 'left': '20px', 'display': ''});
    $(".principal").height("");
    $(".principal").width("");
    $(".principal").html($(".secundario").html());
    $(".secundario").height("");
    $(".secundario").width("");
    $(".secundario").css({'left': '1500px', 'position': '', 'display': ''});
    $(".secundario").hide();
    $(".secundario").html("");

    $.traducir() // Llamamos a la función de traducir una vez resuelta la promesa
});


text:
Q: how do i float these elements I am trying to float my four links so that it is lineal and one next to the other. I am fairly new to CSS, so please bear with me. I have endlessly tried different positions properties and yet can not achieve what I want. Thanks
<!DOCTYPE html>

HOME

ABOUT

LINKS

CONTACT

A: There are various methods to inline the elements.
1. using Flex Method
2. using table method
3. using float method
4. using display method.

Here you can check the Demo link. includes all possibility.

A: I don't know if you've noticed since posting your question, but each of your button DIVs is missing it's closing DIV tag. This means that any CSS applied will not have the expected effect. Once you've fixed the HTML, you can use the following CSS to have each navigation item on the same line, spaced out equally, with the menu occupying the full width:
.button {
    float: left;
    width: 25%;
}

If you don't want the menu to occupy the full width, use padding or margin instead of specifying 25% for the width attribute, e.g:
.button {
    float: left;
    padding: 0 20px;
}

A: You can use either use float: left; or display: inline to achieve what you want.
DEMO
Just add following style to your anchor tags:
.navbar a {
    float:left;
    margin-right: 15px;
}

A: Working Fiddle
.button{
display:inline-block;
}


text:
Q: Remove JSX elements in unordered list after removing items from an array I am new to React, JavaScript, and programming in general. Forgive me if this seems super elementary.
I am trying to create a simple to do list in React to get practice. I went through a course on freecodecamp.com, so I feel like I understand enough to do this. I didn't look at any tutorials on how to create one as I want to actually do as much as I can on my own.
Right now, I am attempting to remove an li from a ul list with a button next to each line item. I am able to get it to modify the array, but it won't re-render with the line item removed. I believe that modifying state should allow the change to happen automatically, but I must be missing something basic.
The only other component is the app component, which is obviously the parent.
import React, { useRef } from 'react';
import { useState } from 'react';

function ToDoList() {
  // initialize state
  const [list, modifyList] = useState([])

  // function to add elements to the list
  const nameForm = useRef(null)
  const updateList = () => {
    const form = nameForm.current
    modifyList([...list,`${form['addtodo'].value}`])
  }

// remove from list
const removeListItem = (listItem) => {
  modifyList(currentArr => {
    currentArr.splice(currentArr.indexOf(listItem), 1)
    return currentArr
  })
}

// render input, buttons, and list
  return (
    <form ref={nameForm}>
      <input type="text" name={'addtodo'} placeholder='input to do'></input>
      <button type="button" onClick={updateList}>Add to list</button>

        {
          list.map((elem) =>
            (

{elem} <button type='button' onClick={() => removeListItem(elem)}>X</button>

           )
       )
     }

    </form>
  );
}

export default ToDoList;

I realize my code is probably a hot mess and could be written better and maybe have the input and add button be a separate component from the to do list. I am open to other suggestions if they are needed.


text:
Q: ¿Cómo usar Toast en Xamarin.forms? Alguno puede decirme como puedo hacer que mi proyecto de Xamarin.forms muestre un mensaje tipo Toast (como tiene Android)?
Estuve buscando todo el día y no encontré nada por ahora, solo notificaciones y esto no me sirve.

A: La opción para crear algo parecido a un Toast de Android en  una aplicación Xamarin es la opción que comparte @alex chengalan
Al usar DependencyService, se puede obtener fácilmente el enfoque tipo "Toast" tanto para Android como en iOS.
Crea una interfaz en tu paquete common
public interface IMessage
{
    void LongAlert(string message);
    void ShortAlert(string message);
}

Sección Android
[assembly: Xamarin.Forms.Dependency(typeof(MessageAndroid))]
namespace Your.Namespace
{
    public class MessageAndroid : IMessage
    {
        public void LongAlert(string message)
        {
            Toast.MakeText(Application.Context, message, ToastLength.Long).Show();
        }

        public void ShortAlert(string message)
        {
            Toast.MakeText(Application.Context, message, ToastLength.Short).Show();
        }
    }
}

sección iOS
En iOs no hay una solución nativa como Toast, por lo que se necesita realizar una implementación propia.
[assembly: Xamarin.Forms.Dependency(typeof(MessageIOS))]
namespace Bahwan.iOS
{
    public class MessageIOS : IMessage
    {
        const double LONG_DELAY = 3.5;
        const double SHORT_DELAY = 2.0;

        NSTimer alertDelay;
        UIAlertController alert;

        public void LongAlert(string message)
        {
            ShowAlert(message, LONG_DELAY);
        }
        public void ShortAlert(string message)
        {
            ShowAlert(message, SHORT_DELAY);
        }

        void ShowAlert(string message, double seconds)
        {
            alertDelay = NSTimer.CreateScheduledTimer(seconds, (obj) =>
            {
                dismissMessage();
            });
            alert = UIAlertController.Create(null, message, UIAlertControllerStyle.Alert);
            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, true, null);
        }

        void dismissMessage()
        {
            if (alert != null)
            {
                alert.DismissViewController(true, null);
            }
            if (alertDelay != null)
            {
                alertDelay.Dispose();
            }
        }
    }
}

Debes tener en cuenta que en cada plataforma, tenemos que registrar nuestras clases con  DependencyService.
Ahora puede acceder al servicio de "Toast" en cualquier lugar de nuestro proyecto.
DependencyService.Get<IMessage>().ShortAlert(string message);
DependencyService.Get<IMessage>().LongAlert(string message);

Otras opciones serían:
https://github.com/EgorBo/Toasts.Forms.Plugin
https://www.nuget.org/packages/Toasts.Forms.Plugin
https://github.com/aritchie/userdialogs


text:
Q: precision voltage reference for multimeter First post, be easy on the newbie. I'm trying to throw together a simple precision voltage reference based on the 5v LT1236. Seems to me the chip effectively has 4 pins, input, output, GND, and trim. I assume I don't connect the other pins at all. Can I leave the trim pin disconnected if I want a straight 5v reference? Probably not that simple...do I need filtering capacitors? How to I decide what size? I like to think I'm familiar with a decent portion of electrical theory, but explaining to me like I'm an elementary schooler couldn't hurt..
Sorry for so many questions, I figure all those questions could be answered in a quickie by almost anyone haha.

Should have started with a more common chip. I looked at the LM4040 datasheet, which made me realize I didn't understand the regulator was basically a zener diode. (And I didn't know enough about zener diodes) Previously I had not questioned how the IC actually operates. (Which would have made this whole thing easier)

A: Since this is your first encounter with a voltage reference, Ill keep this simple.
Connect the IN terminal to a voltage source of 6 volts or greater, but no greater than 40 volts. A common 9 volt rectangular "transistor radio" battery would be fine. Connect IN (Pin 2) to the plus terminal of the battery and GND (pin 4) to the minus terminal. Leave the TRIM input (Pin5) unconnected. With this simple set-up you should measure 5.00 volts on the output. (Connect the black lead of your meter to the negative terminal of the battery or Pin 4 of the IC.
In general, it's a good idea to add capacitors to the input and output of voltage references. The size of the capacitor you would use varies from IC to IC. Most voltage reference data sheets will usually offer specific recommendations or at least guidance on this issue. In the case of the LT1236 you will find  this guidance on Page 7 of the data sheet under the heading "Capacitive Loading and Transient Response". Here we are told to connect a capacitor to the output of no more than 1,000 pf. Or, an RC filter consisting of a small value resistor ("several Ohms") and a 10 MFD capacitor. In your case I wouldn't bother with either.
The addition of a trim pot would be nice, but if you don't have a calibrated voltmeter with which to check the trimmed output of the LT1236, there's little point to include one. The part's specified 0.05% accuracy will produce a maximum error of 2.5 millivolts, so you won't be too far off as far as practical voltage references go.
Just keep an eye on the supply voltage to make sure it is above 6 volts (e.g. as the battery wears down). If it is, you can pretty much bet the output will be darn close to 5.000000000000000 volts.
As a newbie check your wiring and battery polarity carefully before powering up the circuit. There is no such thing as a circuit too simple to blow  up! The old carpenter's rule about "measure twice, cut once" applies analogously to electronics in terms of proper hook-up of parts. I like to say" "think thrice, measure twice, cut once".


text:
Q: Linearly independent functions Show that the set consisting of the functions
$$x, e^x, e^{-x}$$
on $\mathbb R$ is linearly independent.
So I have the equation $$ax + be^x + ce^{-x} = 0$$ and I want to show that this is only satisfied when $a = b = c = 0$
Letting x = 0, $b + c = 0$
Letting x = 1, $a + be + ce^{-1} = 0$
Letting x = -1, $-a + be^{-1} + ce = 0$
Using these equations as columns of a matrix I have
$\begin{bmatrix}
0 & 1 & 1 \\
1 & e & e^{-1} \\
-1 & e^{-1} & e
\end{bmatrix}$
$\begin{bmatrix}
1 & e & e^{-1} \\
0 & 1 & 1 \\
-1 & e^{-1} & e
\end{bmatrix}$
$\begin{bmatrix}
1 & e & e^{-1} \\
0 & 1 & 1 \\
0 & e^{-1}+e & e^{-1}+e
\end{bmatrix}$
But if I now subtract (e^{-1}+e) times row 2 from row 3 I will get all zeros in the last row meaning linear dependence. So what have I done wrong?

A: This is most naturally attacked using the Wronskian,
$$W(f_1,\ldots,f_n)(x) = \det\left(
\begin{array}{ccc}
f_1(x)  & \cdots & f_n(x) \\
f_1'(x) & \cdots & f'_n(x) \\
\vdots  & \vdots    & \vdots \\
f_1^{(n-1)}(x)   & \cdots & f_n^{(n-1)}(x)
\end{array}\right),$$
where $f_k^{(m)}(x)$ is the $m$th derivative of $f_k(x)$.
If the Wronskian does not vanish, the functions $f_k(x)$ are linearly independent.
We find
$$W(x,e^x,e^{-x}) = \det\left(
\begin{array}{ccc}
x   & e^x   & e^{-x} \\
1   & e^x   & -e^{-x} \\
0   & e^x   & e^{-x}
\end{array}\right) = 2x.$$
Therefore, the functions are linearly independent on $\mathbb{C}\setminus\{0\}$. (And therefore on $\mathbb{R}\setminus\{0\}$.)

A: Several people have posted rather general methods for attacking this problem.  Here is an alternative approach that is rather specific to this case.  Suppose that $a$, $b$, and $c$ are numbers and that
$$
ax + b e^x + c e^{-x} = 0, \qquad x \in \mathbb{R}.
$$
Divide both sides of this by $e^x$ and take the limit as $x \to \infty$ to deduce $b = 0$.  Once you know that, dividing both sides of the above by $x$ and taking the limit as $x \to \infty$, you deduce $a = 0$.  And $c=0$ clearly follows from there.
The same basic idea can be used slightly more generally, to prove linear independence of functions of different "growth rates" without solving systems of equations.

A: You have shown that the vectors of values of these three functions at these particular three points are linearly dependent. That does not show that the functions are linearly dependent. You will need a different choice of points.

A: You got that for those three values of x there are infinite solutions a,b,c, but it does not mean that those solutions verify the equation for all x.
If you had that  for  three values of x  only the trivial solution, it verifies for all x too then it is the unique solution for all x.

A: You just need to pick different values. For $x=0,1,2$ you get:
$$\begin{bmatrix}
0 & 1 & 1 \\
1 & e & e^{-1} \\
2 & e^2 & e^{-2}
\end{bmatrix}$$
This row reduces to:
$$\begin{bmatrix}
0 & 1 & 1 \\
1 & e & e^{-1} \\
0 & e(e-2) & e^{-2}(1-2e)
\end{bmatrix}$$
Now take the determinant: you get $e(e-2)-e^{-2}(1-2e)\neq0$ because $e$ is transcendental.


text:
Q: Html5 Canvas : Rotated text looks distorted on Google Chrome I have rotated a text in HTML5 canvas. It looks fine on all the browsers except google chrome. It looks distorted on chrome on Windows. Also, it looks fine on MAC. Why is it so?
I am using Chrome beta 20. Is it some HTML 5 issue or some Google Chrome or Windows bug? How can I resolve this distortion issue?
<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
      #myCanvas {
        border: 1px solid #9C9898;
      }
    </style>
    <script>
      window.onload = function() {
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");

        context.font = "12pt Calibri";
        context.rotate(Math.PI/2.5);
        context.fillText("Competitive Landcaping!", 450, 100);
      };

    </script>
  </head>
  <body>
    <canvas id="myCanvas" width="878" height="2000"></canvas>
  </body>
</html>

A: I went through the same head-banging myself recently. The short answer is that Chrome renders fonts quite poorly on Windows, and transformed fonts just get worse from there.
For a longer, more technical answer, check this post:
http://www.smashingmagazine.com/2012/04/24/a-closer-look-at-font-rendering/
There isn't a whole to be done about it, apart from trying to pick fonts that look the 'least worst' in Chrome.


text:
Q: What are the differences between Grunt, Gulp.js and Bower? Why & when to use them? What are the differences between Grunt, Gulp.js and Bower? Why & when and how to use them?
I've seen nowadays, most of the front-end project using the above tools, though I am using them like in my recent project I am using gulp to build HTML, CSS and JavaScript using a script like
$ gulp build

but don't have much understanding of all these front-end frameworks, please help me get an overall understanding of Grunt, Gulp.js and Bower.

A: to continue on the post of T.J. Crowder, Bower is quite similar to NPM, or Composer or Gem. The biggest difference between NPM and Bower, is that bower is for frontend packages, while NPM (used to be) for backend packages. NPM now does frontend packages as well as backend packages.
Also, you need NPM to install Bower.
Grunt was the first of these frontend task automaters that was available. It gave a better experience than what was available at the time. It still has a big following and active community.
Gulp came from grunt, in a way, and improves on it by using streams, not files.
Grunt writes changes to a file, and loads in that file to manipulate some more. Gulp reads a file, and does all transformations on the datastream, and only writes once all manipulations have been done.
It means it's async and faster than grunt. And I believe Gulp should be used for new projects in favor of grunt.
There are probably great use cases where grunt preforms better than gulp, but usually gulp is faster.

A: I just completed an analysis of Gulp vs Grunt (our prior standard) and although I think both are important to know for a front end developer to be current and both are good solutions I learn towards Gulp for future projects for the following reasons:

*

*Gulp is generally more concise (plugins doing one thing only and streams approach) and readable.  One Grunt script that I redid in Gulp resulted in only one quarter the lines of code to produce the same result.

*Gulp is faster in general.

*Although Gulp has fewer plugins and thinner documentation key plugins for minification, concatenation, listing, LESS transpilation, and so forth are currently available and work well.

A: In essence and with a lot of hand-waving away of details, Gulp and Grunt are both systems for automating serieses of inter-dependent tasks, commonly used for defining the "build" of your project, like a modern take on the make tool. Typically a project uses one of them or the other, but not both at the same time (for the same parts, anyway).
Bower is different, and frequently used with either Gulp or Grunt: It's a package manager for client-side libraries, making it easy to keep those libs up to date, specify them and their dependencies in a standardized way, and so forth.
The Gulp one-liner from their website:

Automate and enhance your workflow

The Grunt one-liner from theirs:

The JavaScript Task Runner

And Bower:

A package manager for the web

Why & when to use them?

I think the above covers that for Gulp and Grunt: If you have tasks you want to automate (like building the release version of a website with minification, concatenation, compression, etc.; or watching files for changes and re-running tasks when they change to support rapid development), you can use Gulp and Grunt for that.
But it's not just builds. You can use Gulp and Grunt for any series of tasks that you need to automate.
Bower is useful for managing the client-side libraries in your projects. You can use Bower to install, say, the latest version of Bootstrap, and it will put the relevant files in standard locations in your project. Bower can update those files if a newer Bootstrap comes out. If a library depends on other libraries (Bootstrap's JS relies on jQuery, for instance), Bower helps manage that tree. There are helpful tasks for Grunt (and I assume for Gulp) that can even automate adding the script and link tags to your HTML for those libraries, by having a placeholder in your source HTML that basically says "put the Bower libs here."

A: gulp and Grunt are task runners. They are different approaches to same problem. Grunt uses configuration based approach, while gulp uses streams from node to achieve result. You use them to define how and which tasks to execute (copying files, adding banners, replacing text, style checking, etc...). They are (usually) run from command line, manually.
For example, if copying and modifying files Grunt will create intermediate files and gulp will leverage node's streams and transform on the fly.
When to use Grunt or gulp is less specific answer because it takes into account personal preference, technology support (plugins for certain tasks), project specifics, and ease of configuration. Both are relatively easy to get up and running, but usually you will end up choosing one which has better plugins for technology stack used for your project (although both have good plugins support).
Bower is package manager. It's used to install javascript (mostly client side) packages (however npm - also packet manager - also contains almost all of those modules/packages. You use it to automatize dependency management and package installing.


text:
Q: Why dynamic created button not working? I have a search page, when click the button, then it display the search result.
however, in the result page, when I continue to search for something, it seems that the button is not responding:
here is script:

here is part render the page at back:
  if(route=='search'){

      var data = $.mobile.activePage.find("input[name=search]").val();
      /*

       code to filter the result

      */

      $('#mainpage').html(_.template($('#search').html())(
      {
            result: resultvalue }
      ));

  }

A: Your javascript is invalid is the first problem.
You're closing your _.template method call early.
Try replacing it with this:
if (route === 'search') {

    var data = $.mobile.activePage.find("input[name=search]").val();

    ...

    $('#mainpage').html(_.template($('#search').html(), {
        result: resultValue
    }));

}

EDIT
Try replacing the onclick event on your button with this:
onclick="app.navigate('#home/search',{trigger: true}); return false;"

Your onclick event was probably happening, but you weren't stopping the default behaviour of the submit button.


text:
Q: Inserting data into SQL Server Db An Invalid direction was specified I am using SQL Server DB (mssql), And trying to execute Insert Query through PHP.
public function registerCustomer($custId, $custData)
{

    $sqlString = "INSERT INTO CUSTMASTER ( CustId, CustData ) values ( ?, CONVERT(varbinary(max),? )) ; SELECT SCOPE_IDENTITY()";
    $params = array($custId, $custData);
    $stmt = sqlsrv_query($this->conn, $sqlString, $params);
    if ($stmt === false) {
        die(print_r(sqlsrv_errors(), true));
    }

    $rows = sqlsrv_has_rows($stmt);
    sqlsrv_next_result($stmt);
    sqlsrv_fetch($stmt);
    $lastId = sqlsrv_get_field($stmt, 0);

    if ($rows === true) {
       echo "Data Inserted."
    } else {
        return "Data Insert Failed.";
    }

}

I am getting the following error ,
Array
(
    [0] => Array
        (
            [0] => IMSSP
            [SQLSTATE] => IMSSP
            [1] => -15
            [code] => -15
            [2] => An invalid direction for parameter 2 was specified. SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT, and SQLSRV_PARAM_INOUT are valid values.
            [message] => An invalid direction for parameter 2 was specified. SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT, and SQLSRV_PARAM_INOUT are valid values.
        )
)

Note : CustData column in db is varbinary(max) type.
I am sending Base64 String from Android App and then converting the string into byte[] using following code.
 $a = base64_decode($FingerData);
 $custData = array();
 foreach (str_split($a) as $c) {
    $custData[] = sprintf("%08b", ord($c));
 }

How to resolve this issue?

A: I ran into the error An invalid direction for parameter # was specified and found this question. My issue, and assuming the OP issue, was that the variable at position # was an array. sqlsrv_query is trying to pars the parameter as a directional parameter.

A: If I understand you correctly, you have a base64 encrypted image. So try this:
<?php

# Only decode $FingerData.
...
$a = base64_decode($FingerData);
...

# Insert data
public function registerCustomer($custId, $custData)
{
    ...
    $sqlString = "INSERT INTO CUSTMASTER (CustId, CustData) VALUES (?, CONVERT(varbinary(max), ?)); SELECT SCOPE_IDENTITY();";
    $params = array(
        array($custId, SQLSRV_PARAM_IN),
        array($custData, SQLSRV_PARAM_IN)
    );
    $stmt = sqlsrv_query($this->conn, $sqlString, $params);
    ...
}
?>

I've made a small script, which is based on your example:
<?php
#------------------------------
# Connection info
#------------------------------
$server = 'server\instance,port';
$database = 'database';
$uid = 'user';
$pwd = 'password';

#------------------------------
# Connection
#------------------------------
$cinfo = array(
    "Database" => $database,
    "UID" => $uid,
    "PWD" => $pwd
);
$conn = sqlsrv_connect($server, $cinfo);
if( $conn === false )
{
    echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
    exit;
}

#------------------------------
# Function
#------------------------------
function registerCustomer($connection, $custId, $custData) {

    $sqlString = "INSERT INTO CUSTMASTER (CustId, CustData) VALUES (?, CONVERT(varbinary(max), ?)); SELECT SCOPE_IDENTITY();";
    $params = array(
        array($custId, SQLSRV_PARAM_IN),
        array($custData, SQLSRV_PARAM_IN)
    );
    $stmt = sqlsrv_query($connection, $sqlString, $params);
    if ($stmt === false) {
        die(print_r(sqlsrv_errors(), true));
    }

    $rows = sqlsrv_has_rows($stmt);
    while (sqlsrv_fetch($stmt)) {
        $lastId = sqlsrv_get_field($stmt, 0);
    }

    if ($rows === true) {
       echo "Data Inserted.";
    } else {
        return "Data Insert Failed.";
    }

    echo $lastId;
}

#------------------------------
# Load image file into database
#------------------------------
# With next two lines I load and encode an image.
# If I understand you correctly, this is already done and you have a base64 encrypted image.
$image = file_get_contents('image.jpg');
$encoded_image = base64_encode($image);

# Insert image
$decoded_image = base64_decode($encoded_image);
registerCustomer($conn, 1, $decoded_image);
?>


text:
Q: Google Tag Manager noscript tag appears as string, why? (using react-gtm-module) I use react-gtm-module to place the Google Tag Manager Tags in a react/next.js app hosted with netlify.
The gtm script tag in the head renders perfectly. But the noscript tag in the body is rendered falsely with the iframe as string:
<body>
  <noscript>
    "
          <iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX&gtm_auth=&gtm_preview=&gtm_cookies_win=x"
            height="0" width="0" style="display:none;visibility:hidden" id="tag-manager"></iframe>"
  </noscript>
  ...
</body>

react-gtm-module code:
import TagManager from 'react-gtm-module'
...
componentDidMount(){
const tagManagerArgs = { gtmId: 'GTM-NCGQVKQ' }
TagManager.initialize(tagManagerArgs);
}

Has anybody an idea what might be the cause?
Thanks a lot!

A: When scripting is enabled, the noscript element will only contain plain text. Try disabling JS in your browser, then the text in the noscript tag should be parsed as HTML
https://html.spec.whatwg.org/multipage/scripting.html#the-noscript-element

A: If your app is only on the client side (no server-side rendering involved), then the noscript part is useless and will never be triggered, since it is loaded using javascript and it is only meant in case javascript is disabled.
From the package's README:

Disabling javascript in the browser can prevent the correct operation of this library if React is only being rendered on the client side.


text:
Q: Error installing mysql-server-5.5 I am trying to run
sudo apt-get upgrade

But it gaves me below output. I tried to run
sudo apt-get -f install

but there isn't any difference.
(Reading database ... 621055 files and directories currently installed.)
Preparing to unpack .../mysql-client-5.5_5.5.46-0+deb8u1_amd64.deb ...
Unpacking mysql-client-5.5 (5.5.46-0+deb8u1) over (5.5.46-0ubuntu0.14.04.2) ...
dpkg: error processing archive /var/cache/apt/archives/mysql-client-5.5_5.5.46-0+deb8u1_amd64.deb (--unpack):
 trying to overwrite '/usr/share/man/man1/mysqlcheck.1.gz', which is also in package mysql-client-core-5.5 5.5.46-0ubuntu0.14.04.2
dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Processing triggers for man-db (2.7.0.2-5) ...
Errors were encountered while processing:
 /var/cache/apt/archives/mysql-client-5.5_5.5.46-0+deb8u1_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

Also i tried to run dpkg --configure -a, but its helpless too. The output is:
dpkg: dependency problems prevent configuration of mysql-server-5.5:
 mysql-server-5.5 depends on mysql-client-5.5 (>= 5.5.46-0+deb8u1); however:
  Version of mysql-client-5.5 on system is 5.5.46-0ubuntu0.14.04.2.

dpkg: error processing package mysql-server-5.5 (--configure):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 mysql-server-5.5

A: Assuming that you tried to install mysql-client-core-5.6 first.
Open your terminal and type:
sudo apt-get purge mysql-client-core-5.6
sudo apt-get autoremove
sudo apt-get autoclean
sudo apt-get install mysql-client-core-5.5
sudo apt-get install mysql-server


text:
Q: Adding chart control to WPF project I have made an app using WPF and coding in c# at VS 2017.
It contains many buttons and so on.
However, when I try to add charts in it I cant find the control in the toolbox.
I tried few things I have read as:
1) right click toolbox-> choose item -> chart... didnt work.
2) install blend SDK for .NET...didnt work
Any suggestion will be helpful.
Thank you.

A: So if you want to keep WPF , you have to use the drawing primitives
i have found a sample on my disk which draws sin and cos function:
Wpf sample:
<Window x:Class="DrawChart.SinCosChart"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Simple Chart" Height="300" Width="300">

    <Viewbox Stretch="Fill">
        <Border BorderBrush="Black" BorderThickness="1" Margin="5">
            <Canvas Name="chartCanvas" Width="250" Height="200" ClipToBounds="True"/>
        </Border>
    </Viewbox>
</Window>

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
namespace DrawChart
{
    public partial class SinCosChart : Window
    {
        private double xmin = 0;
        private double xmax = 6.5;
        private double ymin = -1.1;
        private double ymax = 1.1;
        private Polyline pl;
        public SimpleLineChart()
        {
            InitializeComponent();
            AddChart();
        }
        private void AddChart()
        {
            // Draw sine curve:
            pl = new Polyline();
            pl.Stroke = Brushes.Black;
            for (int i = 0; i < 70; i++)
            {
                double x = i / 5.0;
                double y = Math.Sin(x);
                pl.Points.Add(NormalizePoint(
                    new Point(x, y)));
            }
            chartCanvas.Children.Add(pl);
            // Draw cosine curve:
            pl = new Polyline();
            pl.Stroke = Brushes.Black;
            pl.StrokeDashArray = new DoubleCollection(
                new double[] { 4, 3 });
            for (int i = 0; i < 70; i++)
            {
                double x = i / 5.0;
                double y = Math.Cos(x);
                pl.Points.Add(NormalizePoint(
                    new Point(x, y)));
            }
            chartCanvas.Children.Add(pl);
        }
        private Point NormalizePoint(Point pt)
        {
            Point result = new Point();
            result.X = (pt.X - xmin) *
                       chartCanvas.Width / (xmax - xmin);
            result.Y = chartCanvas.Height – (pt.Y - ymin) *
                chartCanvas.Height / (ymax - ymin);
            return result;
        }
    }
}


text:
Q: Validate URL with IsWellFormedOriginalString fails I want to Validate an URL. I first used Uri.TryCreate. But this creates a valid URL object for links with invalid special characters like this one: https://www.z�rich.ch.
I therefore tried IsWellFormedOriginalString with the following result:
(new System.Uri("https://www.z�rich.ch")).IsWellFormedOriginalString().Display(); //false
(new System.Uri("https://www.google.ch?q=Schüler")).IsWellFormedOriginalString().Display(); //true
(new System.Uri("https://www.google.ch?q=Schuler%20Lehrer")).IsWellFormedOriginalString().Display(); //true
(new System.Uri("https://www.google.ch?q=Schüler%20Lehrer")).IsWellFormedOriginalString().Display(); //false

Why is an URL with ü or %20 correct and an URL with both (ü and %20) incorrect?
Is there a method to validate the URLs above and only first case is invalid? I know, i can check for the � explicitly but maybe there is something more generic.

A: The 1st URL contains a character that is not allowed in URLs. Of course it's clear it should be a u or ü but the string was probably converted from UTF-8 to an 8-bit encoding where the Unicode ü has no match in the target codepage.
In the case of the 4th URL, the %20 can be replaced with + to represent a space, which is the proper way to encode a space in the querystring. The ü is probably seen as indicating a different encoding than when such a character is absent.
Did you compose that 4th URL yourself? I'm wondering why there's a %20 instead of +, as when I follow the link and click Search, Google itself uses a + instead of %20 in the URL.


text:
Q: How to fetch JSON results from multiple APIs using redux I have three different APIs that I am fetching JSON results from and I want to dispatch all three of them using React Native Redux. I am trying to implement a server side search filter that gets the response from all three APIs. How can I do this?
actions.ts
// API 1
export const getCountries = () => {
  try {
    return async (dispatch) => {
      const response = await axios.get(`${BASE_URL}`);
      if (response.data) {
        dispatch({
          type: GET_COUNTRIES,
          payload: response.data,
        });
      } else {
        console.log("Unable to fetch data from the API BASE URL!");
      }
    };
  } catch (error) {
    console.log(error);
  }
};

// API 2
export const getStates = () => {
  try {
    return async (dispatch) => {
      const response = await axios.get(`${BASE_URL_STATES}`);
      if (response.data) {
        dispatch({
          type: GET_STATES,
          payload: response.data,
        });
      } else {
        console.log("Unable to fetch data from the API BASE URL!");
      }
    };
  } catch (error) {
    console.log(error);
  }
};

// API 3
export const getCounties = () => {
  try {
    return async (dispatch) => {
      const response = await axios.get(`${BASE_URL_COUNTIES}`);
      if (response.data) {
        dispatch({
          type: GET_COUNTIES,
          payload: response.data,
        });
      } else {
        console.log("Unable to fetch data from the API BASE URL!");
      }
    };
  } catch (error) {
    console.log(error);
  }
};


text:
Q: How is this familiar function implemented in C? Consider the following code segment written in S-expr notation:
(lambda (x) (lambda (y) (+ x y)))

or in Javascript:
function(x) { return function(y) { return x+y; }; }

How do I write this in C?

A: This is difficult to do in C, since it relies on closures. With C you have to pass an explicit context, so you might end up with something like this.
#include <stdio.h>

struct closure {
    int saved_x;
    int (*function)(struct closure, int);
};

int second_half_add(struct closure context, int y) {
    return context.saved_x + y;
}

struct closure curried_add(int x) {
    struct closure ret;
    ret.saved_x = x;
    ret.function = second_half_add;
    return ret;
}

int main() {
    struct closure context = curried_add(3);
    printf("%d\n", context.function(context, 4));
}

It's really ugly, and you lose almost all benefit of currying, but it is possible

A: C doesn't have first class functions, so the answer is: Nohow.

A: This depends on what you mean when you say "C."
Supposing that you really want to get something back which you can call by simple function application, ISO C makes such a thing pretty hard to do—probably impossible if you really want to stay within the confounds of the standard and not use some low-level assembly tricks.
Clang, however, implements non-standard support for closures that actually makes such things possible.  Using this feature, your example could be implemented in the following way:
#include <stdio.h>
#include <stdlib.h>
#include <Block.h>

int (^plus(int x))() {
  return Block_copy(^(int y) {
    return x + y;
  });
}

int main() {
  int (^plus2)(int) = plus(2);
  printf("2 + 3 = %d\n", plus2(3));
  Block_release(plus2);
  return EXIT_SUCCESS;
}

A: Well, you can do it. It's not pretty. It goes something like this:
typedef int (*intfuncint)(Env*, int);

// this is the "closure" block
typedef struct Env {
  int x;
  intfuncint f;
} env_t;

// this is the internal function
int sum(Env* me, int y){return me->x + y;}

// this is the external function
Env* foo(int x){
  Env* result = malloc(sizeof(*result));
  result->x = x;
  result->f = sum;
  return result;
}

Using it to get the sum of 3 and 5 would look something like this:
Env* p = foo(3); p->f(p, 5)

A: You can't write it in c, for several reasons, mostly that c just doesn't work like that.
If this is a homework question your teacher may say otherwise... something like:
struct functor {
  int x;
  functiontype* f;
}

int dofunctor(functor*, y) { ... }

But it generalises so poorly that it's not worth doing.
You can write it in some other c-like languages - such as perl.
You can do something like this in c++ - see the following answer:
C++ Functors - and their uses


text:
Q: Uncaught TypeError: $(...).sidebar is not a function I am building a layout to a laravel application and i'm having some errors i cannot understand.
The sidebar and other components are not being loaded. i get the error:
Uncaught TypeError: jQuery(...).sidebar is not a function. this happens to other components (dropdown / accordion), the dropdown and accordion error are showed in chrome dev tools as soon the page loads, the sidebar error only shows if i try to open the sidebar.
The reason i have included laravel in the tags is because i have tested exactly the same layout in another folder (outside the laravel structure) and it works. i am not sure if it is the way laravel processes the views.
The scripts i am loading are, in :

at the end of

Here is the code of the sidebar:

Tasks

                My Tasks
                Task Overview
                New task

Reports

                Reports

...

i have tried using different versions of jquery and changing the loading order of jquery and semantic.js.
There are other questions similar to this one in stackoverflow, i have tried them, but keep getting the same errors
thanks in advance.


text:
Q: Should a model be created to support a repository reading a database view intended for a UI pick list? I am looking for solution(s) to providing a pick list in an application based on a domain model. I Have a Product model with a Product Repository. I have a UI which needs to display a pick list of Products. The pick list would only need to display 2 properties from a Product Model which has 15 properties.
I am thinking of creating a database view named ProductSummaries where each row in this view would be represented by a new Model called ProductSummary.  This database view would be drawn from the Products table which is used for Product models.
Because this would be a database view, the creation of a repository for the ProductSummary model would only need one data access method which would be GetAll(). No modifications would be allowed on ProductSummaries because they are from a database view based on the Products table.
What other solutions are used to provide pick lists based on some properties of an existing domain model in an application? I don't know if what I am thinking of doing is something that will lead to problems.
Thanks in advance.

A:
I don't know if what I am thinking of doing is something that will lead to problems.

What you've come very close to discovering on your own is cqrs -- the pattern of having one object to support queries that is separate from the object used to support mutations.
You should be fine, so long as you make it clear in your code that the Product Summaries are read only.  (For example, if you use marker interfaces, then the summaries should be marked like values rather than like aggregates).


text:
Q: Rename all Java classes in a package (In Eclipse) Is it possible to rename all the classes in package with a single command.
Right now , My class names are like com.abc.Class1/com.abc.Class2.
Now I am copying all these classes under a new package com.xyx....In class definition I have changed the names using "File search" ...So now How can I change the names under my package (One command for all classes under package "xyz").

A: If I have understood correctly, you want to move our classes to another package. For this, click on the package in the project explorer and press Shift+Alt+R to rename it, effectively moving all included classes to the new package. This will not affect the names of the classes
EDIT A class name prefix? It's at least highly unusual. Eclipse can not help you with these. But if you are on a linux machine, you could do a mass move from command line.  I am not fluent with it myself, so here is a mmv tutorial.

A: Try some as this, move and then rename all files in a directory:
import java.io.File;

    public class Ls {
        public static void main(String args[])
        {
            String[] dir = new java.io.File("test").list();
            java.util.Arrays.sort(dir);
            File f[] = new File("test").listFiles();
            int len1 = dir.length;
            for (int i=0;i<len1; i++)
            {
                System.out.println(dir[i]);
                String name = f[i].getName();
                System.out.println(name);
                int j=name.indexOf('.');
                System.out.println(j);
                String newname = name.substring(0,j) + "_BS" + name.substring(j,name.length());
                System.out.println(newname);
                File newFileName=new File(f[i].getParentFile(), newname);
                System.out.println("newFileName="+newFileName);
                f[i].renameTo(newFileName);
            }
        }
    }


text:
Q: Asp.net MVC 2 JqueryGrid table row empty I need some help with asp.net mvc
Controller:
<HandleError()> _
Public Class HomeController
    Inherits System.Web.Mvc.Controller

    Function Index() As ActionResult
        ViewData("Message") = "Welcome to ASP.NET MVC!"

        Return View()
    End Function

    Public Function GetMovieData() As ActionResult
        Dim sortColumn As String = (Request.Params("sidx")).ToString()
        Dim sortOrder As String = (Request.Params("sord")).ToString()
        Dim pageIndex As Integer = Convert.ToInt32(Request.Params("page"))
        'Remember this is NOT 0 based
        Dim rowCount As Integer = Convert.ToInt32(Request.Params("rows"))
        Dim movies As New Movies()
        Dim movieList = movies.GetMovies()
        Dim totalRecords As Integer = movieList.Count()
        Dim totalPages As Integer = CInt(Math.Ceiling(CSng(totalRecords) / CSng(rowCount)))

        ' Dim allRecords As IQueryable(Of Movie)
        ' allRecords = movieList.OrderBy(Function(movie) movie.Id).Skip((pageIndex - 1) * rowCount).Take(rowCount)
        'movieList = movieList.AsQueryable().OrderBy(Function(movie) movie.Id).Skip((pageIndex - 1) * rowCount).Take(rowCount)
        Dim finalList = movies.Sort(movieList, sortColumn, sortOrder).Skip((pageIndex - 1) * rowCount).Take(rowCount)

        Dim jsonData = New With { _
                .total = totalPages, _
                .page = pageIndex, _
                .records = totalRecords, _
                .rows = (From m In finalList _
                    Select New With { _
                        .i = m.Id, _
                        .cell = New String() {m.Id.Value.ToString(), m.Name, m.Director, m.ReleaseDate.ToShortDateString(), m.IMDBUserRating, m.Plot, m.ImageURL} _
                    } _
                ).ToList()
                        }
        Return Json(jsonData)
    End Function

    Function About() As ActionResult
        Return View()
    End Function
End Class

View:
<%@ Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>
<asp:Content ID="PageHead" ContentPlaceHolderID="Head" runat="server" >
<link rel="stylesheet" type="text/css" media="screen" href="../../Scripts/grid/css/ui.jqgrid.css" />
<link rel="stylesheet" type="text/css" media="screen" href="../../Scripts/grid/redmond/jquery-ui-1.8.2.custom.css" />

</asp:Content>

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">

<%= Html.Encode(ViewData("Message")) %>

        To learn more about ASP.NET MVC visit http://asp.net/mvc.

</asp:Content>

When I run this code the table is always empty.

A: Just make sure to allow GET requests when returning JSON in the GetMovieData action because by default they are disabled:
Return Json(jsonData, JsonRequestBehavior.AllowGet)

I would recommend you using FireBug which allows you to see AJAX requests and possible error messages. It's much easier to debug problems like this.


text:
Q: DOMPDF Doesn't Work if HTML is Already Present I have a function that uses DOMPDF to generate a .pdf of whatever I set for the $html argument.
function generate_pdf($html){
    //DOMPDF stuff
}

This works, but the problem I'm running into is that when I call this function from a page that already has HTML content, it fails.
Fails...
<?php
  require_once '../header.php'; //This has HTML content in it.
  $html = '
stuff
';
  generate_pdf($html);
?>

This also fails...
<?php
  echo 'stuff';
  $html = '
stuff
';
  generate_pdf($html);
?>

Works...
<?php
  $html = '
stuff
';
  generate_pdf($html);
?>

Is there any way around this?

Contents of function generate_pdf($html)
function generate_pdf($html){
    //Get the necessary dompdf files
    include_once DOMPDF_PATH . '/autoload.inc.php';

    // instantiate and use the dompdf class
    $dompdf = new \Dompdf\Dompdf();
    $dompdf->loadHtml($html);

    // Render the HTML as PDF
    $dompdf->render();

    //Output the PDF
    $dompdf->stream();
}

Note that the file in which this function lives has a namespace, so that's why $dompdf = new \Dompdf\Dompdf(); might appear wrong, but that line is working fine.

A: CHANGED ANSWER after full code was added to question:
I have the complete  HTML content in an included file, no extra HTML before or after it (also no php echoing).
I made a mistake before - I mixed up the inclusion of the dompdf autoload and the content - but see below how it works in my case. This is the  content of a php file, there is no function:
<?php
require_once '../../dompdf/autoload.inc.php';
use Dompdf\Dompdf;
$dompdf = new Dompdf();
$dompdf->set_option('isPhpEnabled', true);
ob_start();

//Here I am getting a few variables (from the URL via GET) which I use in the included php file

include_once "your_content_in_one_file.php";
$html = ob_get_contents();
ob_end_clean();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream($pdf_name);
?>

A: It ended up being related to the fact that ob_start(); had already been called somewhere else in the system.  Using...
if (ob_get_level()){
    ob_end_clean();
}

fixed my issue.  Hope it helps someone else.


text:
Q: "in instantiation of function template specialization 'std::max' requested here" Error Message for max() function While trying to solve http://www.usaco.org/index.php?page=viewproblem2&cpid=891, I coded :
vector<int> abc(3) ;
vector<int> counter(3) ;
for (int i=0; i<3; i++) {
    abc[i] = i ;
}

for (int i=0; i<3; i++) {
    int a,b,g ;
    ifstr >> a >> b >> g ;
    a-- ;
    b-- ;
    g-- ;

    swap(abc[a], abc[b]) ;
    counter[abc[g]]++ ;
}
ofstr << std::max(counter[0], counter[1], counter[2]) ;
return 0 ;

I got +4 overloads on my max() function. How do I solve this problem?

A: The correct way to use std::max with anything else than 2 arguments is by using an initializer list:
ofstr << std::max( { counter[0], counter[1], counter[2] } );
//                 ^                                    ^

Alternatively, you could use std::max_element which doesn't require a copy of all the elements like the initializer list does. Instead you give it the begin and end iterators of your container:
ofstr << *std::max_element(std::begin(counter), std::end(counter));
//       ^

Note that it returns an iterator to the found element (or the end iterator) and it needs to be dereferenced to get the actual value, hence the * above.

A: Given your counter, you can do this
ofstr << *std::max_element(counter.begin(), counter.end());

(if you include the algorithm header).


text:
Q: Sqlalchemy "Packet sequence number wrong" despite using scoped_session I am using Flask with Sqlalchemy, and since switching from mysqldb to pymysql, I am getting this error:
InternalError('(pymysql.err.InternalError) Packet sequence number wrong - got 29 expected 1') (numbers vary depending on query)
This error is quite rare (around 1 in 100), and the reason I am switching to pymysql from mysqldb is because mysqldb kept creating utf8 decoding errors at a somewhat similar rate. Is it possible I am still getting errors because of this, and pymysql is interpreting the "invalid start byte" as an "invalid packet sequence" error, from the same problem further downstream?
As the title says, I already implemented scoped_session and it does not resolve the issue. Maybe I am doing something wrong?
engine_creation.py
def create_engine(db="")
    engine = sqlalchemy_package.create_engine(
        'mysql+pymysql://' + acc + ':' + pw + '@'
        + host + ':' + port + '/' + db + '?charset=utf8mb4',
        pool_recycle=3600, pool_size=25, max_overflow=5)

query_execution.py
from sqlalchemy.orm import scoped_session, sessionmaker
session_factory = sessionmaker(autocommit=True)
def execute_query(engine, query, parameters=None):
    session_factory.configure(bind=engine)
    my_session = scoped_session(session_factory)
    result = my_session.execute(query, parameters)  # noqa
    return result

some_resource.py
from engine_creation import create_engine
from query_execution import execute_query
engine = create_engine(db=some_db)
result_proxy = execute_query(engine, query, parameters)

Changing +pymysql to +mysqldb will work exactly the same, but the "packet sequence" error will change to UnicodeDecodeError('utf-8', b'\xf6', 8, 9, 'invalid start byte') . Has anyone heard of this before? I am still trying to debug why I am getting a UnicodeDecodeError, and if switching to a different dialect is producing a different error - or the same error, expressed differently.
Code worked fine without scoped_session and it seems superfluous if it doesnt fix the Packet sequence error. Sorry if this seems like multiple questions at once, but my gut feeling tells me these problems are related.

A: As expected, this error is not related to flask, sqlalchemy or unscoped sessions. As I see it, it is an error caused by MySQL 5.7 interacting with the pymysql dialect which throws the "Packet Sequence error", when its actually an UTF-8 issue.
In any case, upgrading to MariaDB 10.5 solved this issue. Implementing scoped_sessions was not necessary.


text:
Q: CSS animation for falling, vibrations, etc I'm looking to animate objects moving realistically using pure CSS. Specifically:

*

*something falling/bouncing

*a vibrating string (simple harmonic motion/sinusoidal)

*something falling through a fluid (from rest to terminal velocity)

As far as I'm aware, smooth animation in CSS can currently only be achieved through the use of cubic Bézier curves:
https://developer.mozilla.org/en-US/docs/Web/CSS/timing-function
I figured out that falling can be modelled exactly by cubic-bezier(0.33, 0, 0.66, 0.33), which together with cubic-bezier(0.33, 0.66, 0.66, 1) for the up-bounce can be seen here:
http://jsfiddle.net/BYossarian/Frg74/2/
Does anyone know of the best Bézier curves for (2) and/or (3)?
And if anyone has any input on any other types of physical motion, that would be great too.
If needs be, I can eye-ball it, but I was hoping someone might have this already.

A: Ok, so I've been playing with this, and have vibrations done. As I expected, I had to piece together a bunch of Bézier curves in order to make it work:
http://jsfiddle.net/BYossarian/wrK44/6/    (webkit prefixes only)
The red ball is animated through CSS, and the gray box is animated using JS for reference.
Click the container to start/stop.
The CSS (without prefixes) for the animation is:
.vibrate {
    animation: shm 2s infinite alternate;
}

@keyframes shm {
    from {
        margin-left:0px;
        animation-timing-function: cubic-bezier(0.25, 0.01, 0.55, 0.16);
    }
    25% {
        margin-left:29.3px;
        animation-timing-function: cubic-bezier(0.52, 0.44, 0.47, 0.44);
    }
    50% {
        margin-left:100px;
        animation-timing-function: cubic-bezier(0.53, 0.56, 0.48, 0.56);
    }
    75% {
        margin-left:170.7px;
        animation-timing-function: cubic-bezier(0.45, 0.84, 0.75, 0.99);
    }
    to {
        margin-left:200px;
    }
}

Couple of notes:

*

*This starts from one edge, rather than the middle of the vibration. If you need to start in the middle, you can offset it using animation-delay.

*You can scale the distances up/down by multiplying them all by some constant and it should work.

*The animation-duration given here is the time for the ball to move from one edge to the other (the return journey being covered by setting animation-direction: alternate;), so the time taken for the object to do a complete loop in the above is 4s.

UPDATE: Ok, so I finally found time to get fluid motion going on:
http://jsfiddle.net/S7WRp/  (again, webkit prefixes only)
Click to start. First ball is animated through JS. Second is the CSS animation. The third and fourth are both travelling at a constant speed (the terminal velocity of the other balls) and are used as reference so you can see the first two balls accelerating at the start, and then reaching terminal velocity at the end.
The CSS:
@keyframes fluidDrop {
    from {
        top: 0px;
        animation-timing-function: cubic-bezier(0.7, 0.22, 0.725, 0.61);
    }
    13.33% {
        top: 31.79px;
        animation-timing-function: cubic-bezier(0.16, 0.1875, 0.24, 0.094);
    }
    23.66% {
        top: 88.3px;
        animation-timing-function: cubic-bezier(0.234, 0.15, 0.88, 0.85);
    }
    65% {
        top: 441.5px;
        animation-timing-function: linear;
    }
    to {
        top: 800px;
    }
}

Even more notes:

*

*The shape of the object and the viscosity of the fluid will affect things here so I just went for an 'average' viscosity and a spherical object as a 'one size fits all'.

*To use this, just set the time of the animation to whatever you need, and then scale the top values proportionally to match the distance you want your object to fall. Right now, it falls a distance of 800px, so if, for example, you wanted it to fall a distance of 1600px you would multiple all the top values from all the keyframes by 2.


text:
Q: How to determine the orientation of a geometry surface in Scenekit I'm trying to write a shader to colorize a custom geometry in SceneKit. I want to set the colors so that horizontal surfaces that are facing up are white, horizontal surfaces that are facing downward are black, and all other surfaces in between are shades of gray based on their orientation. I used the material's surface entry point to call the following shader
vec4 normal = vec4(_surface.normal, 1.0);

// Assume value is [-1, 1], scale to [0, 1]
float color = normal.z * 0.5 + 0.5;

_surface.diffuse = vec4(color, color, color, 1.0);

It appears that the normal.z is relative to the camera (or view). I assume I need to transform the value, so that it's in another space. I tried multiple transforms (and combinations of transforms) such as u_inverseViewTransform, but the results all seem to be in view space. Does anyone know how to colorize a geometry based on the orientation of its surfaces?

A: Since _surface.normal is a vector in view space, you have to transform the vector to world space.
The transformation of a point form world space to view space is done by u_viewTransform, so the inverse operation (from view space to world space) can be done by u_inverseViewTransform.
_surface.normal is a direction vector, but not a point. A vector has to be transformed by the normal matrix, which is the transposed, inverse of the upper left 3*3 matrix of a 4*4 matrix:
transpose(inverse(mat3(u_viewTransform)))

See Why is the transposed inverse of the model view matrix used to transform the normal vectors?, Why transforming normals with the transpose of the inverse of the modelview matrix?
But since u_viewTransform and u_inverseViewTransform are Orthogonal matrices the transposed, inverse can be skipped, because the inverse matrix and the transposed matrix are equal. See In which cases is the inverse matrix equal to the transpose?.
This follows you have to transform by mat3(u_inverseViewTransform):
vec3 normal = mat3(u_inverseViewTransform) * _surface.normal;

float color = normal.z * 0.5 + 0.5;

_surface.diffuse = vec4(color, color, color, 1.0);


text:
Q: How to display special character in RichEdit control I am using following code.
  nsDialogs::CreateControl "RichEdit20A" ${WS_VISIBLE}|${WS_CHILD}|${WS_TABSTOP}|${WS_VSCROLL}|${ES_MULTILINE}|${ES_WANTRETURN} ${__NSD_Text_EXSTYLE} 30% 30% 65% 45% ``
  Pop $0

 ;load the license from file

nsRichEdit::Load $0 $PLUGINSDIR\license.txt

(Using NSIS RichEdit Plugin)
I have problem loading special characters. They should up as ® or – instead of copyright symbol or -
I am using unicode version of NSIS and compiling on 32 bit machine. Can someone please provide suggestions for this.

A: I think there were an update in Unicode NSIS which fixes this issue. Try to use latest version 3.0a2.
Set Unicode true and use
nsDialogs::CreateControl "RichEdit20W" ...

The W mean Unicode version of RichEdit (A is for Ansi).


text:
Q: mysql: update millions of records by applying a python function I have a python function (pyfunc):
def pyfunc(x):
    ...
    return someString

I want to apply this function to every item in a mysql table column,
something like:
UPDATE tbl SET mycol=pyfunc(mycol);

This update includes tens of millions of records.
Is there an efficient way to do this?
Note: I cannot rewrite this function in sql or any other programming language.

A: If your pyfunc does not depend on other data sources like apis or any cache, and just does some data processing like string or mathematical manipulations, or depends on the data stored in same database in mysql, you shall go for MySQL user defined functions.
Lets assume you create a MySQL function called colFunc , then your query would be
Update tbl set mycol=colFunc(mycol)

A: Just prepare update.sql file using python script.
After this you can check update on your local machine(with dump of db). Just connect to sql and run update.sql script which was prepared from python.
In this case you will use raw sql query without python for updating data.
I think it is not bad solution.


text:
Q: Input form for batch with HTA How can I make a simple input form in HTA and read it Batch in a simple variable,
and a button to proceed. I don't know any other way to make a decent GUI for a batch file.
Something like this

Any help is appreciated.

A: In short, all you need to do is

*

*Get a reference to the standard output stream inside the .hta file and write to this output the content of the field

*Execute the .hta from batch file using a for /f command to process the data sent to standard output.
The only "problem" is that you need to explicitly call the mshta.exe executable with the full path to the .hta file.
serialNumber.hta

        <HTA:APPLICATION
            ID              = "serialHTA"
            APPLICATIONNAME = "serialHTA"
            VERSION         = "0.1"
            NAVIGABLE       = "yes"
            SHOWINTASKBAR   = "yes"
            SINGLEINSTANCE  = "yes"
            WINDOWSTATE     = "normal"

            BORDER          = "normal"
            BORDERSTYLE     = "normal"
            INNERBORDER     = "no"

            CAPTION         = "yes"
            MINIMIZEBUTTON  = "yes"
            MAXIMIZEBUTTON  = "yes"
            SYSMENU         = "yes"
            SCROLL          = "yes"
            SCROLLFLAT      = "yes"

            CONTEXTMENU     = "yes"
            SELECTION       = "yes"
        />

        <TITLE>input serial number</TITLE>

        serial:
        <input type="text" id="serialNumber">

        <button onclick="closeHTA(true);">ok</button>
        <button onclick="closeHTA();">cancel</button>

serialNumber.cmd
@echo off
    setlocal enableextensions disabledelayedexpansion

    set "serialNumber="
    for /f "delims=" %%a in ('mshta.exe "%~dp0\serialnumber.hta"') do set "serialNumber=%%a"

    if defined serialNumber (
        echo Serial number: %serialNumber%
    ) else (
        echo No serial number provided
    )

A: alternatively you can run it from one file like so

        <HTA:APPLICATION
            ID              = "serialHTA"
            APPLICATIONNAME = "serialHTA"
            VERSION         = "0.1"
            NAVIGABLE       = "yes"
            SHOWINTASKBAR   = "yes"
            SINGLEINSTANCE  = "yes"
            WINDOWSTATE     = "normal"

            BORDER          = "normal"
            BORDERSTYLE     = "normal"
            INNERBORDER     = "no"

            CAPTION         = "yes"
            MINIMIZEBUTTON  = "yes"
            MAXIMIZEBUTTON  = "yes"
            SYSMENU         = "yes"
            SCROLL          = "yes"
            SCROLLFLAT      = "yes"

            CONTEXTMENU     = "yes"
            SELECTION       = "yes"
        />

        <TITLE>input serial number</TITLE>

        serial:
        <input type="text" id="serialNumber">

        <button onclick="closeHTA(true);">ok</button>
        <button onclick="closeHTA();">cancel</button>


text:
Q: The need of virtual memory on 64 bit processors What is the need of virtual memory on 64 bit microprocessor? As i know it can address around 16exabyte memory. So why do we still need paging.
Thanks in advance

A: In addition to providing virtual memory, paging is used to control memory protection, to provide separation between different applications and between applications and the operating system. Paging also allow different applications to use the same linear address to access different memory locations.

A: The memory pager is also capable of doing other very useful things, such as mapping a file to memory and paging only the blocks that are actually used from disk, mapping the same data into multiple processes with copy-on-write, giving each program only as much physical RAM as it actually uses, implementing shared memory, memory-mapped I/O and virtualization.
The main reason to have virtual memory is to be able to work with more data than the system has physical memory, but most of the underlying infrastructure (with the significant exception of the paging algorithm) would be needed anyway, and has hardware support.

A: In the future we may see paging go away. One other problem is that we have systems with 8GB of physical memory with 64 bit processors. As soon as you need more than 8GB of memory, you have to resort to paging. It should not be that long until we have computer systems that have terrabytes of memory and paging will not be necessary.
In that case we will need new operating systems and even new computer systems to take advantage of such large memory.


text:
Q: Missing or invalid url parameter (upload with media) API Twitter Help please... I can send tweets, but when try to upload with media says "missing or invalid url parameter"
I tryed with many ways of define "media", only url, getfilecontent("url"), "@"."url", and more...
I use Abrahams library (twitteroauth)
This is my code:
<?php

session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');

if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
    header('Location: ./clearsessions.php');
}
$access_token = $_SESSION['access_token'];

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $rowTwitter["twitter_token"], $rowTwitter["twitter_token_secret"]);

$msg = $_POST["texto2"];
$image = $_POST["URL"];

$parameters = array(
            'media[]'  => "{$image}",
            'status'   => "{$msg}"
        );

$code = $connection->post('statuses/update_with_media', $parameters);

var_dump($code);

?>

And this is the result:
object(stdClass)#5 (1) { ["errors"]=> array(1) { [0]=> object(stdClass)#6 (2) { ["code"]=> int(195) ["message"]=> string(33) "Missing or invalid url parameter." } } }
EDITED: Hi again! I added this code:
$filename = $image;
$handle = fopen($filename, "rb");
$image = fread($handle, filesize($filename));
fclose($handle);

And now this is the problem:
object(stdClass)#5 (1) { ["errors"]=> array(1) { [0]=> object(stdClass)#6 (2) { ["code"]=> int(189) ["message"]=> string(22) "Error creating status." } } }

A: i did it using modified library
---html---
<form action="" method="POST" enctype="multipart/form-data">

      Tweet Text
      <textarea type="text" name="status" rows="5" cols="60"></textarea>

      Photo
      <input type="file" name="image" />

      <input type="submit" value="Submit" />

  </form>

---php---
if (!empty($_FILES)) {
      // we set the type and filename are set here as well
      $params = array(
        'media[]' => "@{$_FILES['image']['tmp_name']};type={$_FILES['image']['type']};filename={$_FILES['image']['name']}",
        'status'  => $_POST['status']
      );

      $dd = $twitteroauth->post('statuses/update_with_media',$params,true);

      var_dump($dd);
}

download modified library here
https://github.com/tomi-heiskanen/twitteroauth/blob/77795ff40e4ec914bab4604e7063fa70a27077d4/twitteroauth/twitteroauth.php


text:
Q: remove the first characters of each string in a foreach How can I remove the first characters characters_to_eliminate of each string in a foreach loop?
EDIT: characters_to_eliminate are 3 random characters, they are not always the same.
In line 6 I try:
$val = substr($val, 3);

but only removes the first 3 characters of the first value in the array.
function multiexplode ($delimiters,$string) {
    $ary = explode($delimiters[0],$string);
    array_shift($delimiters);
    if($delimiters != NULL) {
        foreach($ary as $key => $val) {
            $ary[$key] = multiexplode($delimiters, $val);
        }
    }
    return  $ary;
}

// Example of use
$string = "characters_to_eliminate abc, characters_to_eliminate def: characters_to_eliminate ghi, characters_to_eliminate jkl";
$delimiters = Array(",",":");

$res = multiexplode($delimiters,$string);
echo '<pre>';
print_r($res);
echo '</pre>';

A: Try foreach($ary as $key => &$val)

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference. (via http://php.net/manual/en/control-structures.foreach.php )

A: str_replace()
$string = str_replace('characters_to_eliminate ', '', $string); // abc, def: ghi, jkl


text:
Q: sscanf variable length string parsing I have a problem that is probably fairly common and likely has a beautiful hack that I am not aware of. I would greatly appreciate it if someone would enlighten me!
I am using C's sscanf() function to parse input and the format is
    "%d %d %d %s %d %s %d ..."
    where the first two %d are random ID integers (insignificant) for the string and the third is a count of the number of %d %s combinations to follow.
For instance, "12 34 2 3 yes 2 no" could be a string, where 12 and 34 random are ID's (unimportant to the problem) and 2 specifies the two combinations following of '3 yes' and '2 no'. The 3 preceding 'yes' specifies the length of the string following, and the same is true for the 'no' with a 2 before it. Where we can have a variable number of these combinations following and we want to catch them all with the sscanf.
Does anyone know of any way to do this with sscanf?
Thanks a lot!

A: Just parse the string in two (or more) passes. This uses the %n format specifier to write the number of bytes processed, so we know where to pick up in subsequent passes:
int a, b, n, pos;
const char *buf = "12 34 2 3 yes 2 no";

assert(sscanf(buf, "%d %d %d %n", &a, &b, &n, &pos) == 3);
for(int i=0; i<n; i++) {
    int cur;

    int x;
    char y[20];

    assert(sscanf(buf+pos, "%d %19s %n", &x, y, &cur) == 2);
    printf("%d %s\n", x, y);
    pos += cur;
}

outputs
3 yes
2 no

A: There's no convenient way to do this with just sscanf.  You'd need to dynamically generate the format string itself, before passing it to sscanf.
You might want to consider writing a specialized parsing routine for this where you call sscanf in a loop, or more preferably (since you specify the C++ tag) using an std::istringstream in a loop.

A: First of all, ssprintf() is used to generate string, not parse it. You should use sscanf. I do not know hwo to finish it in one sscanf(). But you can do it in a loop as:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    int choice_id, count;
    char choice[20],id_1[20],id_2[20], count_str[20], choice_id_str[20];
    int index;
    char *input = "12 34 2 3 yes 2 no";

    sscanf(input, "%s %s %s", id_1, id_2, count_str);
    input += strlen(id_1)+strlen(id_2)+strlen(count_str)+2;
    count = atoi(count_str);
    for(index = 0; index< count; ++index){
        sscanf(input, " %s %s", choice_id_str, choice );
        choice_id = atoi(choice_id_str);
        // Process or store the record
        printf("%d: %s\n",choice_id, choice);
        input += strlen(choice_id_str) + strlen(choice) + 2;
    }
    return 0;
}

Compile with gcc (GCC) 4.1.2, and run with Linux. The output is:
-bash-3.2$ ./a.out
3: yes
2: no

A: Is there a maximum value for the number of %d %s pairs that follow the initial "%d %d %d" header?
There must be since you're putting the values somewhere, perhaps in a
struct { int i; char s[j]; } a[n];
with appropriate j and n sizes.
(BTW, your example uses "%d %d %d %s %d %s %d ..." when the description indicates it should be  "%d %d %d %d %s %d %s %d %s ...", 3 decimals, followed by decimal/string pairs)
If there is a maximum just create a maximized template and test that the return code from sscanf, which should indicate the number of input items successfully matched and assigned, is your 3rd value minus the 3 header items.
If the return code isn't correct when compared to the 3rd int, report a malformed line.
I once made something like this a function so the a[n] was automatic ion the stack and then the function allocated a linked list from the heap for the items sscanf-ed and returned a pointer to the first item.


text:
Q: Karma + Webpack Angular controller not found I've set up an Angular project using webpack with help from this blog post which has an associated boilerplate on Github.
The app itself is working fine, but when I run karma it says it can't find the controller it is trying to test.
// karma.config.js
module.exports = config => config.set({
  files: ['test.webpack.js'],
  preprocessors: {
    'test.webpack.js': ['webpack', 'sourcemap']
  },
  browsers: ['PhantomJS2'],
  webpack: require('./webpack.config'),
  webpackMiddleware: {
    noInfo: 'errors-only',
  },
});

// test.webpack.js
import 'angular';
import 'angular-mocks/angular-mocks';

const testContext = require.context('./', true, /\.spec\.js$/);
testContext.keys().forEach(testContext);

I only have one spec file right now for MainCtrl.spec.js. Karma will run it, but I get the error:

Argument 'MainCtrl' is not a function, got undefined

When I actually run the app, MainCtrl seems to load just fine, so I'm not sure why Karma can't get it.
I've also tried changing \.spec\.js to just \.js but this causes way more errors.

A: I was able to solve this by rethinking the workflow a bit. Two main issues are that module does not get globally exported from ngMocks (there is a conflict with the node import system). The other is that the tests also have to load all of the module files first which is pretty typical for Karma.
// karma.config.js
files: ['app/index.js', 'test.webpack.js']
preprocessors: {
  'app/index.js': ['webpack'],
  'test.webpack.js': ['webpack'],
}

// test.config.js
/* Angular is already imported by app/index.js */
import 'angular-mocks/angular-mocks';

/* MUST use `angular.mock.module`. `module` alone won't work */
beforeEach(angular.mock.module('ngculator'));
const testContext = require.context('.', true, /\.spec\.js$/);
testContext.keys().forEach(testContext);


text:
Q: Babel failes to compile plugin it should be ignoring Trying to compile my code with the webpack loader which i have set to ignore node_modules and have not been able to bypass the error below. I've tried clearing out my node_modules and reinstalling as well as adding and removing packages but have been unable to clear the block:
    /home/mgarf/Documents/testApp/node_modules/babel-plugin-     transform-react-jsx/lib/index.js:16
    var visitor = require("babel-helper-builder-react-jsx")({ /*istanbul ignore next*/
                                                         ^

    TypeError: require(...) is not a function
    at exports.default (index.js:14:17)
    at Function.memoisePluginContainer (/home/mgarf/Documents/testApp/node_modules/babel-core/lib/transformation/file/options/option-manager.js:134:13)
    at Function.normalisePlugin (/home/mgarf/Documents/testApp/node_modules/babel-core/lib/transformation/file/options/option-manager.js:168:32)
    at /home/mgarf/Documents/testApp/node_modules/babel-core/lib/transformation/file/options/option-manager.js:208:30
    at Array.map (native)
    at Function.normalisePlugins (/home/mgarf/Documents/testApp/node_modules/babel-core/lib/transformation/file/options/option-manager.js:180:20)
    at OptionManager.mergeOptions (/home/mgarf/Documents/testApp/node_modules/babel-core/lib/transformation/file/options/option-manager.js:300:36)
    at /home/mgarf/Documents/testApp/node_modules/babel-core/lib/transformation/file/options/option-manager.js:371:14
    at /home/mgarf/Documents/testApp/node_modules/babel-core/lib/transformation/file/options/option-manager.js:392:24
    at Array.map (native)

Here is my webpackconfig snippet.
var webpack = require('webpack');
require('style-loader');
require('css-loader');
require('babel-register')({
   ignore: /\.css$/,
});

...

module: {
      loaders: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: 'babel-loader',
          query: {
            plugins: [
              ['react-transform', {
                transforms: [
                  {
                    transform: 'react-transform-hmr',
                    imports: ['react'],
                    locals: ['module']
                  }, {
                    transform: 'react-transform-catch-errors',
                    imports: ['react', 'redbox-react']
                  }
                ]
              }]
            ]
          }
        },
        { test: /\.css$/, exclude: /node_modules/, loader: "style-loader!css-loader" }
      ]
    }

and package.json:
      "dependencies": {
        "async": "^1.5.2",
        "bcrypt-nodejs": "^0.0.3",
        "body-parser": "^1.15.1",
        "bookshelf": "^0.10.0",
        "compression": "^1.6.2",
        "cookie-parser": "^1.4.1",
        "dotenv": "^2.0.0",
        "express": "^4.13.4",
        "express-validator": "^2.20.4",
        "jsonwebtoken": "^5.7.0",
        "knex": "^0.11.7",
        "moment": "^2.12.0",
        "morgan": "^1.7.0",
        "mysql": "^2.10.2",
        "nodemailer": "^2.3.0",
        "nunjucks": "^2.4.1",
        "react": "^15.2.1",
        "react-cookie": "^0.4.5",
        "react-dom": "^15.2.1",
        "react-redux": "^4.4.5",
        "react-router": "^2.4.0",
        "react-transform-catch-errors": "^1.0.2",
        "react-transform-hmr": "^1.0.4",
        "redbox-react": "^1.2.4",
        "redux": "^3.3.1",
        "redux-thunk": "^2.0.1",
        "request": "^2.69.0",
        "webpack": "^1.12.14",
        "webpack-dev-middleware": "^1.6.1",
        "webpack-hot-middleware": "^2.10.0",
        "whatwg-fetch": "^0.11.0"
      },
      "devDependencies": {
        "babel-core": "^6.7.2",
        "babel-loader": "^6.2.4",
        "babel-plugin-react-transform": "^2.0.2",
        "babel-polyfill": "^6.7.2",
        "babel-preset-es2015": "^6.6.0",
        "babel-preset-react": "^6.5.0",
        "babel-plugin-react-transform": "^2.0.0-beta1",
        "babel-plugin-rewire": "^1.0.0-rc-3",
        "babel-plugin-transform-export-extensions": "^6.8.0",
        "babel-register": "^6.8.0",
        "chai": "^3.5.0",
        "css-loader": "^0.23.1",
        "enzyme": "^2.3.0",
        "fetch-mock": "3.0.2",
        "mocha": "^2.4.5",
        "react-addons-test-utils": "^15.0.2",
        "react-date-picker": "^5.3.21",
        "redux-mock-store": "^1.0.2",
        "sinon": "^1.17.3",
        "sinon-chai": "^2.8.0",
        "style-loader": "^0.13.1",
        "supertest": "^1.2.0"
      },
      "engines": {
        "node": "6.1.0"
      }
    }


text:
Q: how can javascript form submit fire angularjs event? I have a form submit by regular javascript outsite angular. The form is successfuly submit and update the database. I have a $http inside angularjs to query the data.
My question is once submit the form, how can I refresh data inside angularjs?
sample javascript submit:
$.getJSON('/Api/Cbs/setPost', inputPost, function(rsp){
  if(rsp.status > 0){alert('submited');
}

here is my code in angularjs
$http.get('echo U('Api/Cbs/getPostList')')
.then(function(rsp){
  console.log('angular-getPost', rsp);
  $scope.postList = rsp.data;
});

the $http.get() fire only once on page load, not keep watching the API data update.

A: You can get scope by DOM search:
angular.element(controllerId).scope().$apply("getHttp();");

Where controllerId - id attribute of you controller tag, e.g.:
<div ng-controller="myController" id="controllerId">

And getHttp() method is declared on scope:
  $scope.getHttp = function () {
    $http.get('echo U('Api/Cbs/getPostList')')
    .then(function(rsp){
      console.log('angular-getPost', rsp);
      $scope.postList = rsp.data;
    });
  };


text:
Q: How to make widget out of a GestureDetector with a Container child? I want to make a reusable button with a container in GestureDetector which will execute some function if I tap it and its color will become dark if I hold it. Any help, hint, tip would be very much appreciated.
I tried writing the GestureDetector in the custom widget file but it gives me errors.
When i try to extract widget on the GestureDetector it gives an Reference to an enclosing class method cannot be extracted error.
(the main page)
import 'package:flutter/material.dart';
import 'ReusableTwoLineList.dart';
import 'Text_Content.dart';

const mainTextColour = Color(0xFF212121);
const secondaryTextColour = Color(0xFF757575);
const inactiveBackgroundCardColor = Color(0xFFFFFFFF);
const activeBackgroundCardColor = Color(0xFFE5E5E5);

enum CardState {
  active,
  inactive,
}

class SettingsPage extends StatefulWidget {
  @override
  _SettingsPageState createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  CardState currentCardState = CardState.inactive;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Settings'),
      ),
      body: ListView(
        children: <Widget>[
          GestureDetector(
            onTapDown: (TapDownDetails details) {
              setState(() {
                currentCardState = CardState.active;
              });
            },
            onTapCancel: () {
              setState(() {
                currentCardState = CardState.inactive;
              });
            },
            onTap: () {
              setState(() {
                currentCardState = CardState.inactive;
                //some random function
              });
            },
            child: ReusableTwoLineList(
              mainTextColor: mainTextColour,
              secondaryTextColor: secondaryTextColour,
              backgroundCardColor: currentCardState == CardState.active
                  ? activeBackgroundCardColor
                  : inactiveBackgroundCardColor,
              cardChild: TextContent(
                mainLabel: 'First Day',
                secondaryLabel: 'This is the first day of the week',
              ),
            ),
          ),
          ReusableTwoLineList(
            mainTextColor: mainTextColour,
            secondaryTextColor: secondaryTextColour,
            cardChild: TextContent(
              mainLabel: '2nd day',
              secondaryLabel: 'This is the end day',
            ),
          ),
          ReusableTwoLineList(
            mainTextColor: mainTextColour,
            secondaryTextColor: secondaryTextColour,
          ),
        ],
      ),
    );
  }
}

ReusableTwoLineList.dart (the custom widget i am trying to make)
class ReusableTwoLineList extends StatelessWidget {
  ReusableTwoLineList({
    @required this.mainTextColor,
    @required this.secondaryTextColor,
    this.backgroundCardColor,
    this.cardChild,
    this.onPressed,
  });

  final Color mainTextColor, secondaryTextColor, backgroundCardColor;
  final Widget cardChild;
  final Function onPressed;

  @override
  Widget build(BuildContext context) {
    return Container(
      color: backgroundCardColor,
      padding: EdgeInsets.symmetric(horizontal: 16),
      height: 72,
      width: double.infinity,
      child: cardChild,
    );
  }
}

This is what i want but in a custom widget so i can use it over and over.
Normal-https://i.imgur.com/lVUkMFK.png
On Pressed-https://i.imgur.com/szuD4ZN.png

A: You can use extract method instead of extract widget. Flutter will add everything as it is, and instead of a class you will get a reusable function.