Cant cast custom control

Question: I am attempting to use a Custom Ribbon panel, http://www.codeproject.com/Articles/25907/A-Professional-Ribbon-You-Will-Use-Now-with-orb, as well as working out a way to make a application that will take "Plugin" .dll's.
This is the code that I am trying at the moment.
        Assembly assembly = Assembly.LoadFrom(@"dir");
        Type type = assembly.GetType("WindowsFormsControlLibrary2.UserControl1");
        object o = Activator.CreateInstance(type);
        string s = "GiveControl";
        UserControl uc = (UserControl)type.GetMethod(s).Invoke(o, null);
        ((Panel)uc.Controls.Find("panel1", true)[0]).Parent = panel2;

        RibbonTab rt = (RibbonTab)uc.Controls.Find("ribbonTab1", true)[0];

The last line is giving me an error that states "Cannot convert type 'System.Windows.Forms.Control' to 'System.Windows.Forms.RibbonTab'"
Its obvious what this message means, but I don't understand why it is happening. Is there a reason that custom controls can't be found this way?
This code/application is just a proof of concept/trying to find a way to do this (My first attempt).
Any known ways to do this would be appreciated.
------UPDATE------
Appologies, I should have said, this error is happening at compile time, not at runtime.
Comment: I would debug and see what kinda control that find is getting make sure it is the RibbonTab control
Comment: See comment on "Reed Copsey" answer
Comment: I realized this is happening at runtime, Reed Copsey and I have come to the same conclusion, the control you are trying to cast might not be a ribbontab
Comment: This is happening at Compile time. Not runtime. Visual Studio doesnt see it as a control.
Comment: my bad I miss read what you said sorry! See my answer
Answer: Your code should work, provided the returned control is actually a System.Windows.Forms.RibbonTab.
However, at runtime, it's not.  You can rework your code to make it easier to diagnose.  Instead of writing:
RibbonTab rt = (RibbonTab)uc.Controls.Find("ribbonTab1", true)[0];

I would break it up and do some error checking:
Control controls[] = uc.Controls.Find("ribbonTab1", true);
if (controls.Length == 0)
{
   // No "ribbonTab1" control was found -
}

Control rtControl = controls[0];
RibbonTab rt = rtControl as RibbonTab;
if (rt == null)
{
    // The first control named "ribbonTab1" wasn't actually a ribbon tab...
    // Check rtControl.GetType() to see what type it is actually defined to be
}

Comment: See update.
Just put your code in. The uc.Controls.Find("ribbonTab1") is bringing back nothing. For some reason, the Application is seeing the not seeing the RibbonTab as a control. There is also now a link to the controls that I using in the question.
Comment: @Seige Are you finding the panels? etc?  Why not just create a new control directly?
Comment: Yes, i made it just to see if it got the controls (No casting), and the panel is still displaying on the form. The control list is just empty. What i am trying to achieve, is a application that when a "plugin" dll is placed next to it, it is incorperated into the app. Including design and code. Sorry having internet problems.
Comment: @Seige Why not use MEF to dynamically load your "plugin" and just expose a `Control` to add directly?  Far simpler...
Comment: Because i dont know about other ways of doing things like this. Thats why i tagged that little bit at the end of my question :) I am open to ideas. I will look into MEF, thanks.
Comment: It seems that RibbonTab doesnt like being called a Control. However, its parent, the Ribbon, does. So to get to the Tab, I have pulled out the Ribbon, and through that have access to the RibbonTab..
Answer: This is because RibbonTab is not a control
public class RibbonTab : Component, IRibbonElement, IContainsRibbonComponents

Comment: Technically correct, so i will check this as the answer. Thanks to Reed Copsey aswell

Cant cast custom control


Google Maps API v3 jQuery Mobile

Question: I am trying to figure out how to limit the number of markers that can be created to one. Using the example code from the "other-example.html" file, the user can create multiple markers and I would like the user to be limited to one marker. I tried an "if" statement such as "int i; if (i<1){... i++;}" around the addMarker function and didn't have any luck. I am guessing it is something really simple to fix.
http://jquery-ui-map.googlecode.com/svn/trunk/demos/other-examples.html
Also I am trying to find a good tutorial on using gmaps to record lat/long location data via PHP/MYSQL to a database I have already created. Specifically, how can I pass the newly created marker's lat/long info to the database and then later retrieve the coordinates to be displayed on a non-editable gmap?
I will appreciate any help I can get with these questions, I don't expect them all to be answered!
Answer: If you're allowing users to add markers, I'd say you then make an ajax call to your PHP page, passing user ID, latitude and longitude (and anything else your DB will require).
To prevent users adding more than 1 marker, I think you must have been on the right tracks.  I'd maybe do it like this.
var intMarkers = 0;  // make it global

$('#map_canvas').gmap().bind('init', function(event, map) {
            $(map).click( function(event) {
                intMarkers++;
                if (intMarkers === 0) {
                            $('#map_canvas').gmap('addMarker', {'position': event.latLng, 'draggable': true, 'bounds': false}, function(map, marker) {
                                $('#dialog').append('<form id="dialog'+marker.__gm_id+'" method="get" action="/" style="display:none;">
Country<input id="country'+marker.__gm_id+'" class="txt" name="country" value=""/>

State<input id="state'+marker.__gm_id+'" class="txt" name="state" value=""/>

Address<input id="address'+marker.__gm_id+'" class="txt" name="address" value=""/>

Comment<textarea id="comment" class="txt" name="comment" cols="40" rows="5"></textarea>
</form>');
                                findLocation(marker.getPosition(), marker);
                            }).dragend( function(event) {
                                var self = this;
                                findLocation(event.latLng, this);
                            }).click( function() {
                                openDialog(this);
                            });

                            // stick in an Ajax call here too
                }
            });
        });

Also the example code is using the deprecated Google Maps API 2, I'd suggest you use API 3 instead.

Google Maps API v3 jQuery Mobile


Camel CDI runtime InstanceAlreadyExistsException on JBoss EAP 6.1

Question: When multiple wars are deployed, and each war file contains one instance of a class StandardContext that extends DefaultCamelContext and context name is set to "StandardContext" using @ContextName, this exception gets thrown. Is this due to class loader setup on JBoss?
Camel version: 2.17.4
JBoss version: EAP 6.1
Comment: How do you deploy your Camel application. Do you use a WAR or do you use wildfly-camel or something? And a good idea is to use unique camel id names, so eg @ContextName should use unique name in all your applications
Comment: The camel application is deployed as a war file on JBoss EAP 6.1. Unfortunately the ContextName cannot be changed, as it is a common base class used by every war file, but the workaround is to use the module name as the name pattern:
Answer: Earlier I had used
<code>    getManagementNameStrategy().setNamePattern("#name#");
</code>
But that did not work, so I modified my code to the following:
<code>    @ApplicationScoped
    @ContextName("StandardContext")
    public class StandardContext extends DefaultCamelContext {

    @Resource(lookup = "java:module/ModuleName")
    private String moduleName;

    @PostConstruct
    public void init() {

    getManagementNameStrategy().setNamePattern(moduleName);
</code>
Posting this code to clarify my solution for other readers
Answer: You can configure your Camel application to use a naming pattern (such as managementNamePattern) for JMX. See more details in the JMX documentation: http://camel.apache.org/camel-jmx.html
You can then let the pattern use a counter or something to avoid the clash. Or you can override the name and set it to something you know is unique such as the module name.


So what really is a random variable?

Question: I've been confused about the definition of a stochastic (random) variable for an embarrassingly long amount of time.
From the Wikipedia entry on Stochastic Processes, I could gather that a random variable is a map from a probability space $(\Omega,F,P)$ to a space $S$. And if there is one such map $X(t)$ for each $t\in T$ (where $T$ is some indexing set), then we have a stochastic process.
Is this definition correct? So if $(\Omega,F,P)$ is the probability space {Heads,Tails} with $P(Heads)=\frac{1}{2}$ and $P(Tails)=\frac{1}{2}$, and the space $S$ is $\{1,0\}$, then $X(heads)=1$ and $X(tails)=0$ is one such random variable, and $X(heads)=0$ and $X(tails)=1$ is another random variable.
Both of these random variables are possible with a probability of $\frac{1}{2}$ each.
Am I understanding random variables correctly? That they're maps, out of many possible maps?
Comment: It is not structurally correct to say a "map from a probability space $(\Omega, F, P)$ to a space $S$," as if the objects being mapped are three-tuples $(\omega, f, p)$,  and as if you have $X(\omega, f, p) \in S$.   You are dealing with maps from $\Omega$ to $S$, that is, $X:\Omega\rightarrow S$. The objects being mapped are $\omega$, and you have $X(\omega) \in S$.  And it makes sense to assume the conventional thing that $S=\mathbb{R}$.
Comment: If you have multiple random variables $X_t:\Omega\rightarrow\mathbb{R}$ indexed by $t$, say, $t \in \{1, 2, 3\}$, then you can write $X_t(\omega)$.  Then the single outcome $\omega \in \Omega$ determines the value of all random variables $X_1(\omega), X_2(\omega), X_3(\omega)$.  Or you can write it as $X(t, \omega)$.  Or you can suppress the $\omega$ by just writing $X(t)$ but it is implicitly assumed this means $X(t,\omega)$, so it is understood that $t$ is the index and is different from the outcome $\omega$.
Comment: https://math.stackexchange.com/questions/3777027/what-is-the-difference-between-stochastic-process-and-random-variable/3777109#3777109
Answer: I'm going to answer this question from a slightly different perspective.  Or, rather, from two different perspectives, since they're both relevant:
From one historical and practical perspective, what random variables are supposed to represent is simply unknown variables whose value is uncertain in some way that we can quantify — the prototypical example being the result of a dice roll that hasn't been rolled yet.
We can then algebraically manipulate these unknown variables to obtain expressions for other variables whose value may also be uncertain (like, say, the winner of the game being played with these dice that haven't been rolled yet), and ask questions about how uncertain we are about the values of these dependent random variables and how likely they are to take a particular value or values, given what we know / believe / assume about the likelihoods of the original unknown variables (such as the dice rolls) taking specific values.
The other perspective arises from trying to rigorously formalize the intuitive and pragmatic concept described above.
For this, we need not only rigorous rules for how to manipulate algebraic expressions involving unknown variables (which we already historically had, long before rigorous probability theory became a thing) but also a rigorous way to specify how likely these "quantifiably unknown" variables are to take particular values and a way to take these quantified distributions of the random variables over their possible values and use them to calculate the corresponding distributions for new variables obtained by logically and algebraically manipulating the original ones.
Historically, this formalization has evolved over time.  The earliest formalizations of probability theory simply assigned probabilities to discrete independent events, which works fine as long as we're dealing with things like a series of independent dice rolls that can each only take one of a finite set of discrete possible values.  But for formalizing things like the random location of a dart thrown at a dartboard, we need to allow our random variables to range over a continuous range of possible values, which introduces apparent paradoxes (like the probability of the dart hitting any given point being zero, yet it still always hitting some point) that our formalization needs to handle.  And for dealing with "random variables" like the trajectory of a diffusing microscopic particle over time or the temperature at every point on the Earth's surface two days from now, we need an even more advanced formalization.  And, at some point along the way, we also need to figure out how to really rigorously deal with dependencies between random variables, which historically wasn't a trivial thing at all.
The current formalization that we've settled on is the one that's already been described in other answers: we define random variables as measurable functions from a probability space to a measurable space and then define rules for algebraically manipulating these functions as if they were just elements of their codomain, plus some useful extra rules for things like conditioning a random variable on an event or taking the (conditional) expected value of a random variable and so on.
But the important thing to realize is that all this formalism involving sigma-algebras and measures and functions exists just to create a rigorous foundation for the intuitive concept of a "variable with an uncertain value", while avoiding all the various paradoxes that may arise in various edge cases if one attempts to do so in a more naïve manner.
In particular, after having learned (and, hopefully, on some level understood) these definitions in an undergraduate probability theory class, most mathematicians or statisticians will never again deal directly with low-level stuff like sample spaces and sigma-algebras.  In practice, they are nearly always simply assumed to exist and to be sufficiently fine-grained to allow defining all the actual random variables and their possible interdependencies that one happens to need for a particular calculation.

Ps. Anyway, to answer your literal question, yes, both "the number of heads obtained on a coin toss" and "the number of tails obtained on a coin toss" are valid random variables, and the correspond to your two $X$ functions.  For a fair coin, as in your example, both of these random variables have an expected value of $\frac12$.  (Not "a probability of $\frac12$" — events have probabilities, random variables have values.)
Note that, as defined, your two $X$'s are dependent random variables, since they describe the same coin toss (which is the only thing your probability space contains).  In particular, as defined, their sum is always exactly $1$ in any event.  For two independent fair coin tosses, the sum would instead be a binomially distributed random variable $S$ with $P(S = 0) = P(S = 2) = \frac14$ and $P(S = 1) = \frac12$.  But to define that, you'd need a bigger probability space.
Comment: If I may presume to say so, this is beautiful, honest pedagogy, that respects the obvious intelligence of the OP.
Answer: A real-valued random variable is just a measurable function from $\Omega$ to $\mathbb{R}$
For practical purposes you can forget the word measurable and think of it as just a function.
It's as simple as that. It's just a fancy/confusing name "random variable"
which I guess is there mainly for historical reasons.
One could argue that a random variable (r.v.) is neither a variable, nor is random.
It's just a function from $\Omega$ to the reals.
Of course if it's not a real-valued r.v. but if it takes values in some other set $S$ then well... you just replace $\mathbb{R}$ with $S$ in that definition.
Comment: @ε-δ OK... But by the time the OP gets to that depth (of measurable functions), the OP might just  want to think of random vars as just functions.
Comment: @RobertIsrael- I watched a youtube video which had the notation $E_n(X_{n+1})$. So for some reason I thought the expectation of a random variable had to be a random variable (and not a number, as mentioned here). Does such a construction exist? The video was on martingales, and they said $E_n(X_{n+1})=X_n$.
Comment: I disagree with your comment that random variables are not variables. Sure, not in the strict sense, but they can be used like variables in probabilistic algorithms. For example, in cryptography you often see `k←GenerateKey, c←Enc(key, "abc")` where `key` and `c` are used as *random* variables. Perhaps one should distinguish the actual variable from the (probabilistic) algorithm generating it. In crypto, you would write `coin ←$ {head,tail}, X ← f(coin)` where `←$` stands for uniform sampling, and `f` is the mapping from head/tail as desired. In math, X and f are denoted by the same thing X.
Comment: @ComFreek I said "one could argue", I didn't say it's definitely so. Of course in some sense it is a variable. But in strict math sense, it's just a function. The term variable has a very different meaning in math normally than the one it has in "random variable". I guess you would agree with that.
Comment: Right. So if $f$ is this random variable, then $f(heads)=1$ and $f(tails)=0$ is a random variable?
Comment: I was just thinking that for this definition of random variable to make sense, all random variables would have to be characteristic functions. Is this intuition correct? And where does probability come in?
Comment: Go through the first few lectures here and it will become crystal clear. https://www.youtube.com/watch?v=j9WZyLZCBzs&list=PLUl4u3cNGP61MdtwGTqZA0MreSaDybji8
Comment: In particular look at the lecture "Discrete random variables I"
Comment: Yes, $\Omega = \{heads, tails\}$ in your example and $f$ just assigns real values to elements of $\Omega$. It's as simple as that, it's just a fancy name "random variable". It's neither a variable, nor is random :). It's just a function from $\Omega$ to the reals. In this case the function values are 0 and 1 i.e. the function range is $\{0,1\}$. Probability is assigned to events. E.g. you may ask the question - what is $P(f < 0.5)$ which is basically the same as asking: what is the probability that $f(u) = 0$
Comment: Thank you for the references. Also, how does one compute the expectation value of a random variable? Do I take a weighted sum of all possible random variables, the weights being probabilities?
Comment: Expectation is also covered in these lectures, both for discrete and continuous random variables. It's also in Wikipedia. For discrete ones it's a weighted sum. For continuous ones it's a definite integral.
Comment: A random variable is a MEASURABLE function.
Comment: The expected value of the random variable $f$ is $\int_\Omega f \; dP$.  In the discrete case it's a weighted sum over **outcomes**.  You never consider "all possible random variables".
Comment: @RobertIsrael OK, thank you for the note.
Answer: The definition is correct, but your "with a probability of $1/2$ each" is nonsense.  Probabilities are assigned to events, which are measurable subsets of the sample space, not to random variables.
Your first $X$ ($1$ for heads, $0$ for tails) is a random variable.
Your second is another random variable.
A third would be $0$ for both heads and tails, and a fourth would be $1$ for both heads and tails.
But we generally don't restrict the values of the random variables to $0$ and $1$.  If we did, they'd just be the indicator functions of events.  Usually we allow real values.
EDIT: Perhaps I should mention that working probabilists usually don't think this way: the focus is on the random variables and their distributions, while the probability space is hardly mentioned.  See my answer here (and read the other answers too while you're at it).
Comment: **heads** is an elementary outcome, it is a member of $\Omega$
Comment: @fierydemon Strictly speaking **heads** is a member of $\Omega$, while the set $\{heads\}$ is a sub-set of $\Omega$ But yeah, OK... most people abuse the notation a bit in order to simplify things. In that sense, sure, what you say is OK.
Comment: @Robert : What may give rise to this "nonsense" is the structurally misleading statement that a random variable is a map from $(\Omega, F, P)$ to $\mathbb{R}$. This incorrectly suggests the objects being mapped are 3-tuples $(\omega, f, p) \in (\Omega, F, P)$.    This may be confusing fierydemon because you see that fierydemon is trying to put the probability mass into the thing being mapped, as if $(\omega, f, [1/2; 1/2])$ maps to something different from $(\omega, f, [1/4; 3/4])$.   I suspect it is better to emphasize a random variable is a map from $\Omega$ to $\mathbb{R}$.
Comment: Isn't $heads\subset \{heads,tails\}$ possibly a measurable subset of the space, and hence we can assign a probability to it?
Comment: Sure I mean we could declare **heads** to be a measurable subset of $\Omega$. Sorry that's the construction I had in mind for this particular example
Answer: I would strongly urge you not to consider the set
$\{ \mathrm{heads}, \mathrm{tails} \}$ to be your $\Omega.$
You just can't do much with an $\Omega$ that has only two elements in it.
When I flip a coin I expect the result to be either "heads" or "tails",
which would be signified by the value of a random variable.
Either I say the space $S = \{ \mathrm{heads}, \mathrm{tails} \}$
so that the value of the random variable is literally heads or tails,
or I might say that $S = \{ 0, 1 \}$, that $X(1) = 1$ means that flip number $1$ is heads, and that $X(1) = 0$ means that flip number $1$ is tails.
If I want to model a sequence of three tosses of a fair coin, then I want something like the variables $X(1),$ $X(2),$ $X(3),$ where each $X(t)$ has equal chance of being heads or tails and each $X(t)$ is independent from the other two.
In particular, there are eight different possible sequences of outcomes:
$$ HHH, HHT, HTH, HTT, THH, THT, TTH, TTT. $$
In order for this to be possible, I need $\Omega$ to have at least eight elements,
because each element of $\Omega$ determines the values of all three variables $X(1),$ $X(2),$ and $X(3).$ No one element of $\Omega$ can produce more than one of the sequences of outcomes listed above.
Answer: My 2 cents: random variable $X$ is measurable map from $(\Omega,\mathfrak{F},P)$ to $\mathbb{R}$ and this means, that for given value $a$ of $X$ the preimage $X^{-1}(a) \in \mathfrak{F}$. So we have defined $P(X^{-1}(a))$ and measurability cannot be omitted or forgotten, because only this gives warranty to have probability defined for it.
For your example you can say, that random variable obtain value $1$ with probability $\frac{1}{2}$ if/when $P(X^{-1}(1)) = \frac{1}{2}$
Stochastic or random process is family of random variables $X:\Omega \times T \to \mathbb{R}$ and so can describe more dynamic situations. Imagine, that random variable's probability is depending on time so we have $P(X^{-1}(a,t)) $ different probabilities for different time values: for different toss coin it is different probabilities to obtain "head".
Comment: Constructive critique is welcome, especially as answer is correct.

So what really is a random variable?


Optimization closed formsolution

Question: Hi I've tried this question, but doesn't have a clue about how to approach this. Here is the question, and thank you in advance for your help.

Suppose A ∈ $R^{m×n}$ is full column rank, and b ∈ $R^m$. Derive a closed-form solution (meaning a solution expressed involving the parameters A and b) to the optimization problem$$
(P) min ||Ax − b||_2 $$such that x ∈ $R^n$.
Be clear why your proposed solution is indeed the solution. [ Hint: $(A^T A)^{-1}$
  exists since A is full column rank. Another hint: it doesn't matter if the objective function is instead $||Ax − b||^2_2$]

I think we are trying to minimize an Euclidean norm, and to do that, I did:
$$|Ax−b|^2=(Ax−b)^t(Ax−b)=x^tA^tAx−2x^tA^tb+b^2$$ Am I on the right track?
Comment: What have you tried so far?  What tools do you have that might help you find the minimum of a function?
Comment: @BrianBorchers I just updated the question, could you take a look?
Comment: $b$ is a vector, so you should try to rewrite the expression correctly $(b^2$ does not make sense$)$. But yes, you are on the right track!
Comment: That's a start.  How do you find the stationary points (minima, maxima, or saddle points) of a function of a vector?  How would you do it if the function was just a function of a scalar?
Answer: $\newcommand\nsq[1]{{\left\lVert #1\right\rVert}^2}$I would suggest a different route.
Notice that, as a map between vector spaces, we have $A:\mathbb{R}^n\longrightarrow\mathbb{R}^m$.
We can decompose $\mathbb{R}^m$ as
$$\text{Im}(A)\oplus{\big(\text{Im}(A)\big)}^{\perp}.$$
Any $u\in\mathbb{R}^m$ can thus be uniquely written as
$u_A+u_A^\perp$,
where $u_A\in\text{Im}(A)$ and $u_A^\perp\in{\big(\text{Im}(A)\big)}^{\perp}$.
Moreover, this decomposition satisfies
$\nsq{u}=\nsq{u_A}+\nsq{u_A^\perp}$.
Write then $b=b_A+b_A^{\perp}$.
Since $Ax\in\text{Im}(A)$ for all $x$, it follows that
$$\nsq{Ax-b}=\nsq{Ax-b_A-b_A^\perp}=\nsq{Ax-b_A}+\nsq{b_A^\perp}.$$
Notice that $\nsq{b_A^\perp}$ is independent of $x$, so that indeed the best we can do is minimize $\nsq{Ax-b_A}$.
On the other hand, $b_A\in\text{Im}(A)$, so surely there is $x_0$ such that $Ax_0=b_A$.
This guarantees a minimum, because the norm is non-negative.
Okay, but what about the closed form?
Here is a general result of interest:

Let $\{u_1,\dots,u_n\}\subset\mathbb{R}^m$ be linearly independent and  $M\in\mathbb{R}^{m\times n}$ be the matrix whose columns are given by the $u_i$.
  Then the orthogonal projection $P_M$ onto $\text{span}(u_1,\dots,u_n)=\text{Im}(M)$ is
$$P_M=M{\left(M^tM\right)}^{-1}M^t.$$

Do you think you can show this?

Using this, we find that $b_A=A{\left(A^tA\right)}^{-1}A^tb$, and at this point it's easy to check that
$$x_0={\left(A^tA\right)}^{-1}A^tb.$$
Comment: Yeah, this really makes sense to me!  thank you

Optimization closed formsolution


Problemas com paginação no SLIM com Pager

Question: Como fazer a mudança de página usando o Pear-Pager no SLIM Framework?
O código da router é:
    $app->get('/imoveis(/:pg)', function($pg = '') use($app) {
    $imoveis = array('casa 1', 'casa 2', 'casa 3', 'casa 4', 'casa 5', 'casa 6', 'casa 7', 'casa 8', 'casa 9', 'casa 10');
    $params = array(
        'mode' => 'Jumping',
        'perPage' => 3,
        'delta' => 4,
        'itemData' => $imoveis,
        'append' => false,
        'path' => site_url().'imoveis/' ,
        'fileName' => '%d',
        'altNext' => 'Próximo',
        'nextImg' => '>>Próximo',
    );
    $pager = Pager::factory($params);
    $data = $pager->getPageData();
    $links = $pager->getLinks();

    $dados = array(
        'titulo' => 'Nossos imóveis',
        'pagina' => 'imoveis',
        'menu_hover' => 3,
        'dados' => $data,
        'links' => $links,
    );

    $app->render('layout.php', $dados);
});

e o da view é:
<?php
foreach ($dados as $item):
    echo $item->codigo.'
';
endforeach;
echo $links['all'];
?>

Quando eu clico no número da página ele simplesmente muda na URL mas o resultado continua o mesmo.
Comment: Veja se isso pode ajudar tmb -> http://draft.studiokoalla.com/2015/03/paginacao-com-slim-framework/
Answer: Tente definir o "currentPage" no params:
'currentPage' => $pg,

Ele deve está dando conflito com a forma que o slim pega os dados.
Na dúvida veja a lista completa dos parâmetros que voce pode definir.


PowerShell: Check if Variable is smaller than 126.96.36.199

Question: How can I test which version number is bigger?
<code>$Variable1:188.8.131.52
$Variable2:126.96.36.199
</code>
If want to write a simple if question like <code>($Variable1 -gt $Variable2)</code>
Answer: Probably not the best solution, but you could try this:
<code>[int]($Variable1.Split('.') -Join '') -gt [int]($Variable2.Split('.') -Join '')
</code>
UPDATE! This is what you want:
<code>[System.Version]$Version = "126.96.36.199"
[System.Version]$Version2 = "22.214.171.124"
$Version -gt $Version2
</code>
Comment: Thanks for your Reply, but it doesn't work as expected.    $variable1="220.127.116.11"
$Variable2="18.104.22.168"
[int]($Variable1.Split('.') -Join '') -gt [int]($Variable2.Split('.') -Join '')
True
Comment: Yes, that's why this way is not really any good. As it just "converts" the version number into an integer and compares them. In this example that would be 150015 and 15015. So the comparison returning true is actually correct, but not what you want.
Comment: Updated my answer with a better way.
Comment: Great! Sometimes it can be so easy!! :)

PowerShell: Check if Variable is smaller than 15.0.0.152


Cast struct c/c++

Question: Galera estou vendo um codigo de um network sniffer e nao estou entendendo as seguintes linhas :
ethernet = (struct sniff_ethernet*)(packet);
ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);

como funcionam esses cast com struct?
//////////////////////////função
got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{

 static int count = 1;

 /* declare pointers to packet headers */
 const struct sniff_ethernet *ethernet;
 const struct sniff_ip *ip;
 const struct sniff_tcp *tcp;
 const char *payload;

 int size_ip;
 int size_tcp;
 int size_payload;

 printf("\nPacket number %d:\n", count);
 count++;

 ethernet = (struct sniff_ethernet*)(packet); ////////

 ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);//////////
 size_ip = IP_HL(ip)*4;
 if (size_ip < 20) {
  printf("   * Invalid IP header length: %u bytes\n", size_ip);
  return;
 }

 printf("       From: %s\n", inet_ntoa(ip->ip_src));
 printf("         To: %s\n", inet_ntoa(ip->ip_dst));

 switch(ip->ip_p) {
  case IPPROTO_TCP:
   printf("   Protocol: TCP\n");
   break;
  case IPPROTO_UDP:
   printf("   Protocol: UDP\n");
   return;
  case IPPROTO_ICMP:
   printf("   Protocol: ICMP\n");
   return;
  case IPPROTO_IP:
   printf("   Protocol: IP\n");
   return;
  default:
   printf("   Protocol: unknown\n");
   return;
 }

Comment: Os *casts* nao tem razao de ser no codigo apresentado. Ao fazer uma atribuicao a uma variavel de um valor de tipo diferente mas compativel o compilador faz uma conversao automatica. A presenca do cast nem ajuda nem desajuda antes pelo contrario.
Answer: A função got_packet recebe o argumento cont u_char* packet, que é um array de caracteres que contêm os bytes do pacote recebido.
A struct sniff_ethernet representa o cabeçalho Ethernet que possui 6 bytes para o endereço de destino, 6 bytes para o endereço origem e 2 bytes para EtherType. Então os primeiros 16 bytes do array de caracteres packet são destinados a essa struct.
A struct sniff_ip representa o cabeçalho IP por sua vez, está pegando as informações que estão no array packet e inserindo na struct para melhor manipulação.
ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);

packet + SIZE_ETHERNET, significa que tu estás a pegar o endereço de packet, e somando com o tamanho do cabeçalho Ethernet, ou seja vai estar atribuindo a essa struct somente as informações do cabeçalho IP.
Dessa forma, os primeiros bytes do array packet estão na struct sniff_ethernet e os próximos na struct sniff_ip, e assim por diante.

Cast struct c/c++


Passar CSV para Classe C++

Question: Tenho uma classe que que encho com um csv e quando tento adicionar um nova linha no ficheiro dá-me erro de alocação de memoria em seguida o codigo:
#pragma once
#include "Produto.h"

class GerirProduto {
    public:
        GerirProduto();
        void adicionarProduto(int id,string nome, int stock, double precoCusto, double iva);
        void removerProduto(string nome);
        void modificarProduto(string nome,int novoStock, double novoPrecoCusto, double novoIva);
        void mostrarProdutos();

    private:
        bool verificaNoCsv(int id,string nome);
        void guardarInformacoes();
        Produto* item;
        int numItem;
};

Gerirproduto.cpp
#include "GerirProduto.h"
#include <fstream>
#include <sstream>

bool GerirProduto::verificaNoCsv(int id, string nome){
    ifstream arquivo("produtos.csv");
    string linha;
    while (getline(arquivo, linha)) {
        stringstream ss(linha);
        string idCSV, nomeCSV, stock, precoCusto, iva;
        getline(ss, idCSV, ',');
        getline(ss, nomeCSV, ',');
        getline(ss, stock, ',');
        getline(ss, precoCusto, ',');
        getline(ss, iva, ',');
        if (nomeCSV == nome|| idCSV == to_string(id)) {
            return true;
        }
    }
    return false;
}

void GerirProduto::guardarInformacoes() {
    fstream arquivo("produtos.csv", ios::out | ios::app);  // Abra o arquivo no modo ios::app
    if (!arquivo.is_open()) {
        arquivo.open("produtos.csv", ios::out);  // Abra o arquivo no modo ios::out se ele não existir
    }
    for (int i = 0; i <numItem; i++) {
        arquivo << item[i].getId() << "," << item[i].getNome() << "," << item[i].getStock() << "," << item[i].getPrecoCusto() << "," << item[i].getIva() << endl;
    }
    arquivo.close();
}

GerirProduto::GerirProduto() {

    ifstream arquivo("produtos.csv");
    if (!arquivo.is_open()) {
        cout << "Arquivo de produtos não encontrado." << endl;
        return;
    }
    string linha;
    numItem = 0;

    //Ler quantas linhas tem o csv
    while (getline(arquivo, linha)) {
        numItem++;
    }
    numItem++;

    arquivo.close();

    item = new Produto[numItem];

    arquivo.open("produtos.csv");
    numItem = 0;

    while (getline(arquivo, linha)) {
        stringstream ss(linha);
        string idCSV, nomeCSV, stock, precoCusto, iva;
        getline(ss, idCSV, ',');
        getline(ss, nomeCSV, ',');
        getline(ss, stock, ',');
        getline(ss, precoCusto, ',');
        getline(ss, iva, ',');

        int id = stoi(idCSV);
        int stockValue = stoi(stock);
        double precoCustoValue = stod(precoCusto);
        double ivaValue = stod(iva);
        item[numItem] = Produto(id, nomeCSV, stockValue, precoCustoValue, ivaValue);
        numItem++;
    }
    arquivo.close();
}

void GerirProduto::adicionarProduto( int id, string nome, int stock, double precoCusto, double iva){
    if (!verificaNoCsv(id, nome)) {

        numItem++;
        Produto* newItem = new Produto[numItem];

        for (int i = 0; i < numItem; i++) {
            newItem[i] = item[i];
        }

        newItem[numItem] = Produto(id, nome, stock, precoCusto, iva);
        numItem++;

        if (item != nullptr) {
            delete[] item;
        }

        item = newItem;

        guardarInformacoes();
    }
    else {
        cout << "ID ou Nome ja existem!!\n";
    }
}

Answer: Seu programa cancela porque está errado. E é normal até aí. Mas a razão dele cancelar envolve um grande número de erros conceituais. As coisas simplesmente não são assim nessas linguagens. Você tem um professor? Um bom livro? Um plano? Procure ter os 3.
Em C++ --- como em java, javascript, Python e um grande número de linguagens --- existe o conceito de classe e o conceito de instância. Não deve escrever programas nessas linguagens enquanto não tiver esse conceito claro.
Vou deixar uma explicação passo a passo aqui porque pode ajudar num primeiro momento a ver  essa relação classe x instância, em especial se está ao mesmo tempo escrevendo programas simples em C ou Assembler ou outra que não tenha essas coisas.
Essa é sua classe, direto de sua questão como apresentada:
class GerirProduto {
    public:
        GerirProduto();
        void adicionarProduto(int id,string nome, int stock, double precoCusto, double iva);
        void removerProduto(string nome);
        void modificarProduto(string nome,int novoStock, double novoPrecoCusto, double novoIva);
        void mostrarProdutos();

    private:
        bool verificaNoCsv(int id,string nome);
        void guardarInformacoes();
        Produto* item;
        int numItem;
};

Isso sugere que você queria ter uma classe Produto e que tal coisa teria id, nome, stock, precoCusto e iva.
E onde está isso? Não existem.
E onde iriam parar esses produtos? A julgar pelo código iriam parar num array private chamado item, e a quantia num dado momento seria representada por numItem:
        Produto* item;
        int numItem;

No código item é Produto* e pode apontar para um Produto. Só um.
Se você escrever
    item = new Produto[numItem];

Como está em seu programa, vai funcionar uma única vez, se numItem for 0. Isso porque em C++ como em C o endereço do primeiro elemento de um vetor pode ser acessado assim --- array to pointer decay.
Alem desse único vai ter que alocar memória para o ponteiro para cada novo elemento. new Produto() apenas aloca um novo Produto, uma instancia da classe, com seus valores e funções (métodos).
A classe Produto

class Produto
{
   public:
   private:
    int    id;
    string nome;
    int    stock;
    double preco_custo;
    double iva;
};

Se um produto é assim, cada novo produto deve ter esses campos. Podem vir de qualquer lugar ou de nenhum. Sempre vão estar lá. Podem ter valores indefinidos, mas estarão em cada instância da classe.
criando um Produto
Isso é feito explicitamente ou implicitamente por um construtor. Isso seria a idéia de
void GerirProduto::adicionarProduto(
    int id, string nome, int stock, double precoCusto,
    double iva)

em seu programa original. Só que não é bem assim em C++.
Você pode ter vários construtores, e todos tem o mesmo nome: o da Classe. Isso é polimorfismo e é um dos pilares dessas linguagems orientadas a objetos.
Esse seria um trivial construtor:
Produto::Produto(
    int id, string nome, int stock, double precoCusto,
    double iva)
{
    id         = id;
    nome       = nome;
    stock      = stock;
    precoCusto = precoCusto;
    iva        = iva;
}

E um programa assim
#include "Produto.h"

int main(void)
{
    Produto um = Produto(2, "Produto X", 1, 42., 4.2);
    return 0;
}

Já rodaria e ajudaria a entender melhor as coisas: um é um instância de Produto.
Como era de se esperar, há uma notação mais simples para isso:
Produto::Produto(
    int um, string nm, int stock, double preco,
    double iva)
    : id(um), stock(stock), preco_custo(preco), iva(iva){};

Usando : precedendo uma lista de campos que vão ser apenas copiados dos argumentos.
o construtor padrão
O construtor padrão é um que não tem argumentos, e podia ser algo assim para esse exemplo:
Produto::Produto()
{
    id         = -1;
    nome       = "";
    stock      = 0;
    precoCusto = 0.;
    iva        = 0.;
}

Exemplo:
#include <iostream>
#include "Produto.h"

int main(void)
{
    Produto um = Produto(2, "Produto X", 1, 42., 4.2);
    Produto outro = Produto();
    std::cout << "id de 'um' = " << um.id << endl;
    std::cout << "id de 'outro' = " << outro.id << "\n";
    return 0;
}

mostraria
id de 'um' = 2
id de 'outro' = -1

E se vê que foi usado o construtor padrão para criar o segundo. E ele será usado para inicializar qualquer instância de container, implicitamente.
Exemplo:
    Produto prd[30];

O construtor padrão vai ser chamado para TODOS esses 30 elementos do array. Todos os campos vão ter os valores como definidos no construtor padrão.
a noção de container
métodos como
        void adicionarProduto(int id,string nome, int stock, double precoCusto, double iva);
        void removerProduto(string nome);
        void modificarProduto(string nome,int novoStock, double novoPrecoCusto, double novoIva);
        void mostrarProdutos();

    private:
        bool verificaNoCsv(int id,string nome);
        void guardarInformacoes();

Envolvem outra entidade que não é o Produto: é uma coleção de produtos. Em java são chamadas assim, collections. Em C++ são chamados containers como visto em português na documentação.
C++ oferece vetor, array, lista, fila, pilha. mapa, conjunto e outros containers, e todos tem claro o mesmo paradigma. Tem tamanho ajustável e o tamanho faz parte do container. E tem tamanho variável.
Pode ter um container de qualquer coisa, de qualquer classe. Um vetor de Produto seria algo simples para seu caso e pode ter um exemplo do uso aqui. O programa abaixo pega os produtos do último exemplo, coloca em um vetor e mostra as id na tela:
#include <iostream>
#include <vector>
#include "Produto.h"

int main(void)
{
    Produto um = Produto(2, "Produto X", 1, 42., 4.2);
    Produto outro = Produto();
    std::cout << "id de 'um' = " << um.id << endl;
    std::cout << "id de 'outro' = " << outro.id << "\n";

    auto catalogo = std::vector<Produto>{um, outro};
    for (auto p : catalogo)
        std::cout << "id " << p.id << "\n";

    return 0;
}

E mostra
id de 'um' = 2
id de 'outro' = -1
id 2
id -1

Claro que seu objetivo pode ser justamente escrever tal container e assim usaria uma Classe`. Algo assim seria o comum:
// catalogo.h
#pragma once
#include <vector>

#include "Produto.h"
class Catalogo
{
   private:
    unsigned size;

   public:
    Catalogo();
    int    Adicionar(Produto);
    int    Remover(int id);
    int    Remover(string nome);
    int    Listar();
    size_t get_size();

   private:
    vector<Produto> Prd;
};

Eis a implementação simples usada, que já pode compilar
#include "Catalogo.h"

Catalogo::Catalogo() : size(0){}

int Catalogo::Adicionar(Produto novo)
{
    Prd.push_back(novo);
    size++;
    return 0;
}
int Catalogo::Remover(int id) { return -1; }
int Catalogo::Remover(string nome) { return -1; }

int Catalogo::Listar()
{
    std::cout << "    Catalogo tem " << size
              << " produtos:\n\n";
    for (auto p: Prd ) std::cout << "id " << p.id << "\n";
    return 0;
}

size_t Catalogo::get_size() { return size_t(size); }

E main para um exemplo
#include <iostream>
#include <vector>
#include "Produto.h"
#include "Catalogo.h"

int main(void)
{
    Produto um = Produto(2, "Produto X", 1, 42., 4.2);
    Produto outro = Produto();
    std::cout << "id de 'um' = " << um.id << endl;
    std::cout << "id de 'outro' = " << outro.id << "\n";

    auto catalogo = std::vector<Produto>{um, outro};
    for (auto p : catalogo)
        std::cout << "id " << p.id << "\n";

    Catalogo cat;
    cat.Adicionar(um);
    cat.Adicionar(outro);
    std::cout << "    main: Catalogo tem " << cat.get_size()
              << " produtos\n";
    cat.Listar();

    return 0;
}

Esse programa mostra algumas coisas que precisa entender:

classe e instância em C++
composição
polimorfismo
algo da sintaxe
um container simples

Mas é um exemplo mínimo. C++ é uma linguagem enorme e complexa. mas talvez a melhor que existe para compor modelos e abstrair coisas.

Passar CSV para Classe C++


wxPython GUI crashing due to uncaught exception 'NSRangeException'

Question: I have read that pub/sub mechanism is a thread-safe mean of communicating from a thread to a GUI ( https://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/ )
The program below, which has been reduce from a bigger one to the essence of the problem, crashes after a number of writings from the thread to the wx.TextCtrl area of the GUI through the pub/sub mechanism. For experimenting several writing rates, it can be changed in the time.sleep(x) statement. Whatever x is, it crashes (tested by myself from 0.1 to 100 seconds), it is not a matter of how frequently the thread writes to the GUI.
Basically, the GUI creates the text control and subscribes to a pub/sub mechanism. The thread writes periodically into the publisher. It works fine until crashing with exception:
2017-10-21 13:50:26.221 Python[20665:d07] An uncaught exception was raised
2017-10-21 13:50:26.222 Python[20665:d07] NSMutableRLEArray insertObject:range:: Out of bounds
2017-10-21 13:50:26.222 Python[20665:d07] ([…])
2017-10-21 13:50:26.223 Python[20665:d07] *** Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray
insertObject:range:: Out of bounds'
*** First throw call stack:
([…]
)
libc++abi.dylib: terminating with uncaught exception of type NSException

The 'out of bounds' probably relates to an index on which I have no access from the Python code…  I am unable to go further. Could anybody help ?
Using Python 2.7.12 | wxPython 188.8.131.52
Running Mac OS X 10.9.5 | on platform x86_64
The code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

__version__ = '04'

import sys
import threading
import time
import platform

try:
    import wx
except ImportError:
    raise ImportError ("The wxPython module is required to run this program")

try:
    from pubsub import pub
except ImportError:
    from wx.lib.pubsub import pub

class CrashFrame(wx.Frame):
    def __init__(self,parent,id,title):
        wx.Frame.__init__(self,parent,id,title)

        self.hor_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.textlogger = wx.TextCtrl(self, size=(520,110), style=wx.TE_MULTILINE | wx.VSCROLL, value="" )
        self.hor_sizer.Add(self.textlogger)
        self.SetSizerAndFit(self.hor_sizer)
        self.Show(True)

        self.crashthread = SocketClientThread()

        self.run()

    def run(self):
        self.logthistext('Using Python {} | wxPython {}'.format(sys.version.split()[0], wx.VERSION_STRING))
        self.logthistext('Is thread running ? - %s' % self.crashthread.isAlive())

        # Create a listener in the GUI form
        pub.subscribe(self.logthistext, 'fromSocketListener')

    def logthistext(self, msg):
        self.textlogger.AppendText('{}\n'.format(msg)) # a good way to write on the text area

class SocketClientThread(threading.Thread):
    def __init__(self):
        super(SocketClientThread, self).__init__()
        self.alive = threading.Event()
        self.alive.set()
        self.start() # thread will start at creation of the class instance

    def run(self):
        while self.alive.isSet():
            data = 'A bunch of bytes'
            pub.sendMessage('fromSocketListener', msg=data)
            time.sleep(10) # or 0.1 or 100, whatever, it crashes
            continue

if __name__ == '__main__':
    app = wx.App()
    frame = CrashFrame(None,-1,'Crash Program - v{}'.format(__version__))
    app.MainLoop()

Answer: wxPython's Threadsafe Methods
wx.PostEvent
wx.CallAfter
wx.CallLater
def run(self):
    x=0
    while self.alive.isSet():
        data = 'A bunch of bytes-'+str(x)
        wx.CallAfter(pub.sendMessage,'fromSocketListener', msg=data)
        time.sleep(0.2) # or 0.1 or 100, whatever, it crashes
        x +=1

Comment: Thank you Rolf. It works fine. Great ! What I understand is that pub/sub mechanism is not thread-safe by itself. CallAfter or CallLater are the actual thread-safe mean.


Show a field in table if current user is node author

Question: I want to create a view block that shows all published nodes of a certain content type. I've included an image below.

However the trick here is to only show the link Print Report if the logged in user is the author of that node. So if you look at my image above, the user Dennis Bonilla should be able to see his Print Report link but not see one for the row below for Test McTest.
Is there a module that can help me do this or some administrative trickery in the views ui? Or maybe even programmatically?
Answer: Two modules can help you do that. Note that you'll likely choose one of these two modules. they aren't dependent on each other. They can both help you get what you want in different ways.

Views PHP
Computed Field
Answer: This is possible via views UI itself.

Create a view with content types you need as a filter criteria
Then add a "relationship" for "Content: Author". Now add a "contextual filter" for the field "user: uid" with a default argument for "user-id of logged in user" to filter the view.

Now you will get the list of nodes authored by current logged in user.
To get the Print Report Link you could make use of Views PHP module and by adding content:nid field

To List all nodes and Add print report link to only contents of the current user

Add a Content: Author UID and a Global: PHP field
In global:PHP field, add conditions like below:
global $user;
if ($user->uid ==  $row->uid) {
  echo 'print reports';
}

Comment: This will filtered out the logged in user's content But QA want to display all the contents but the print report link with only his contents.
Comment: Oh sry I missed it. I will update my answer
Answer: The answer of @Pravin Ajaaz is correct but I'd have to disagree of using PHP Views don't use this module .. its bad!
alternatively write you PHP code in the server side ,, and that's possible by writing the result of that field which is well documented here:
Theming a single field in a Views 3 template


When piano pedalling seems to conflict with the original score

Question:
This is from Burgmüller's "Harmony of the Angels", Op. 100 No. 21, edited by Ingrid Jacobson Clarfield.
I'm wondering about the difference between the green and red blocks. Doesn't the sustain pedal make the green parts sound exactly as the red ones?
I understand that sheets often use non strict notation for pedal-sustained notes, but here we have different sections of the same piece...
Considering (guessing) that the notation is different notation comes from the author (but not the pedal indications), would that imply that the author originally didn't intend to use pedalling in the green parts ? Or what?
Answer: There are two issues that would matter to a sufficiently experienced pianist.

They can sound different. Unless one is extremely careful, there is a difference in how one plays a held note versus a non-held note, and this can be heard even in the presence of the pedal.
Although the pedal is indicated for the entire measure, one may choose either to half-pedal or to lightly change the pedal during the measure so that the sound doesn't become to thick. In that case, notes would be lost when using the non-held notation, but would be retained with the sustained notation.

It's important to understand that pedal markings in piano music generally do not mean "sustain the note" — that would be indicated by the note duration. The pedal marking most often means "warm up the sound". Thus, the notes give the specific musical intention, and the pedal serves as a modifier to the sound (similar to a dynamic marking or articulation marking).


Bulk operations: Taxonomy: Save

Question: I am just looking to do a bulk save on a bunch of taxonomy terms - need to trigger an update on a geofield - but there is no Save option in the bulk operations for Taxonomy Terms (as there is for Nodes).
When I try to update a field on the terms with Modify Entity Value, I get an AJAX error...
Ditto when I try to do a taxonomy_term_save($object) with Execute Arbitrary PHP Script.
Any ideas?
Thanks!
Simon.
Answer: taxonomy_term_save($entity); inside "Execute Arbitrary PHP Script" will do the trick.
In D7, the variable is $entity, for D6 it is $object.
Comment: Thanks Bojan - appreciate the tip! Unfortunately this just saves, but doesn't update the taxonomy term - any suggestion of how I can trigger update to force the geofield to generate?
Comment: I'm not familiar with geofield triggers generation, you will probably have to ask in their issue queue.
Comment: Okay - thanks Bojan - I know that they have a drush backfill command, but it only works on Nodes...
Comment: I needed to do this again in a different context and the code snippet worked fine on a computed field - must be something specific to the geofield which failed in the first instance...

Bulk operations: Taxonomy: Save


C# foreach statement not adding models to model list correctly

Question: I have two foreach loops, which are building a timeline of events in my application.  I have a timeline list object, which is a list of timeline details objects.  The code looks like this:
var viewModel = new TimeLineListViewModel();
var timelineDetailsViewModel = new TimelineDetailsViewModel();

var referralDiaryEvents = _referralService.GetReferralDiaryEventsByReferralId((int)referralId).ToList();

var referral = _referralService.GetReferral((int)referralId);

foreach (var referralDiaryEvent in referralDiaryEvents)
{
1    timelineDetailsViewModel.EventDate = referralDiaryEvent.App_DiaryEvent.EventDateTimeScheduled;
2    timelineDetailsViewModel.EventType = referralDiaryEvent.App_DiaryEvent.Ref_EventType.Description;
3    timelineDetailsViewModel.EventDescription = referralDiaryEvent.App_DiaryEvent.EventName;

4    viewModel.TimeLineList.Add(timelineDetailsViewModel);
}

foreach (var referralStatusHistory in referral.App_ReferralStatusHistory)
{
    timelineDetailsViewModel.EventDate = referralStatusHistory.DateChanged;
    timelineDetailsViewModel.EventType = "Referral Status Changed: " + referralStatusHistory.Ref_ReferralStatus.Description;
    timelineDetailsViewModel.EventDescription = referralStatusHistory.Ref_ReferralStatusReason.Description;

    viewModel.TimeLineList.Add(timelineDetailsViewModel);
 }

This all should be straightforward, and should be adding each item in each of the loops to build up a list of objects.  The problem is that it's not doing that.  I actually have no idea what it's doing - when I debug and run through the loop, it's doing some really weird stuff.  I've numbered the lines of code in the loop for reference.  It'll run through line 1, then run through line 2, then back to line 1, then onto line 3, then back to line 2, then onto line 4, and so on, it jumps back and forth through the loop for no apparent reason instead of running straight through the loop, line after line.
Then eventually it will add the timelineDetailsViewModel to the TimeLineList.  Then it'll start the loop again for the next item, but when it gets to adding the timelineDetailsViewModel to the TimeLineList again, the TimeLineList count becomes 0, then jumps back to line 2, then back to 4 again, then adds the item to the list, but overwrites every item that was previously added to the list to that all of the timelineDetailsViewModel items in the list are the same as the latest added item.  So by the time it gets to the bottom of the 2nd foreach loop, in my code there should be seven unique timelineDetailsViewModel items in the list, all with different details - there does end up being seven items, but they are all the same as the last timelineDetailsViewModel that was added during the last loop of the 2nd foreach loop.
Does anybody have any idea what's happening here?  Is my visual studio broken?  I've tried a restart on my machine but to no avail.  I'm using visual studio 2012.
Comment: Are you running this on more that one thread at a time?
Comment: Look in the output log and see if you're getting any instances of "First chance exception" in it, my guess is that you're getting some sort of minor exception in line 3 such as a casting exception that doesn't actually cause the debugger to break.  I've learned when I see weird things like what you describe, it's normally because of those stupid "First Chance Exceptions"
Comment: I don't know, how would I find that out?  I've never touched any settings to do with threads, I'm just running the application like normal and it's doing this.  Is it possible that I've accidentally done something to have it running on multiple threads?
Comment: You are trying to debug in release mode.
Answer: It does not explain the weird debugger behaviour, but you actually have another bug in your code:
You are creating the instance of TimeLineListViewModel and TimelineDetailsViewModel only once. Then, iterating through the foreach loops, you always change the properties of exactly the same instance.
In each run through the loops you are changing the properties of the only instance you ever created and try to add this very instance x times to your lists.
You need to create the instances inside your foreach loops:
foreach (var referralDiaryEvent in referralDiaryEvents)
{
    // create a NEW instance for every event!
    var timelineDetailsViewModel = new TimelineDetailsViewModel();

    timelineDetailsViewModel.EventDate = referralDiaryEvent.App_DiaryEvent.EventDateTimeScheduled;
    timelineDetailsViewModel.EventType = referralDiaryEvent.App_DiaryEvent.Ref_EventType.Description;
    timelineDetailsViewModel.EventDescription = referralDiaryEvent.App_DiaryEvent.EventName;

    viewModel.TimeLineList.Add(timelineDetailsViewModel);
}

Comment: Thanks, this actually fixed the problem, it's debugging fine now, using the same instance of object must've been making VS freak out!


DTOs in a WCF Web Api project

Question: Ive been reading on some best practices for exposing Data over WCF Web Api and in many places it seems to be recommended not to use Domain Entities to expose your data but to use DTO for this.
What I cant find is a sample on the web on how to approach doing this.
Where can I find some documentation/samples on this?
whats your take on this approach?
Please help.
Answer: I like Samuel Meachan's approach.

DTOs in a WCF Web Api project


Merge DataFrame using `contains` (not a full match !)

Question: I have been struggling with this problem all week. I have two DataFrames as follows:
df1:
Account| ID              | Name
--------------------------------------
B36363 | 2019001         | John
G47281 | 2019002;2018101 | Alice;Emma
H46291 | 2019001         | John

df2:
Account   | Col_B   | Col_C
-----------------------------
B36363-0  | text_b1 | text_c1
01_G47281 | text_b2 | text_c2
X_H46291  | text_b3 | text_c3
II_G47281 | text_b4 | text_C4

I want to merge these DataFrames on Account when df2.Account contains df1.Account (not the full match with a normal merge/join!)
Desired output:
df3:
Account   | Col_B   | Col_C   | ID              | Name
--------------------------------------------------------------
B36363-0  | text_b1 | text_c1 | 2019001         | John
01_G47281 | text_b2 | text_c3 | 2019002;2018101 | Alice;Emma
X_H46291  | text_b3 | text_c3 | 2019001         | John
II_G47281 | text_b4 | text_C4 | 2019002;2018101 | Alice;Emma

I have no sample code because I have no idea how to handle this. A normal merge/join goes well, but not if I want to use contains. Thank you very much in advance
Answer: You can try str.extract with join():
d=df1.set_index('Account').agg(list,axis=1).to_dict()
p='({})'.format('|'.join(df1.Account))
#'(B36363|G47281|H46291)'
m=pd.DataFrame(df2.Account.str.extract(p,expand=False).map(d).fillna('').tolist()
               ,columns=['ID','Name'],index=df2.index)
df2.join(m)

     Account    Col_B    Col_C               ID        Name
1   B36363-0  text_b1  text_c1          2019001        John
2  01_G47281  text_b2  text_c2  2019002;2018101  Alice;Emma
3   X_H46291  text_b3  text_c3          2019001        John
4  II_G47281  text_b4  text_C4  2019002;2018101  Alice;Emma

Answer: Try str.extract on df2.Account and set the result to index of df2 and join
pat1 = '('+'|'.join(df1.Account)+')'
s = df2.Account.str.extract(pat1, expand=False)
df2.set_index(s).join(df1.set_index('Account')).reset_index(drop=True)

Out[644]:
     Account    Col_B    Col_C               ID        Name
0   B36363-0  text_b1  text_c1          2019001        John
1  01_G47281  text_b2  text_c2  2019002;2018101  Alice;Emma
2  II_G47281  text_b4  text_C4  2019002;2018101  Alice;Emma
3   X_H46291  text_b3  text_c3          2019001        John

Another way is using merge
df2.assign(Account2=df2.Account.str.extract(pat1, expand=False)) \
   .merge(df1, left_on='Account2', right_on='Account', suffixes=('', 'y')) \
   .drop(['Account2', 'Accounty'], 1)

Out[645]:
     Account    Col_B    Col_C               ID        Name
0   B36363-0  text_b1  text_c1          2019001        John
1  01_G47281  text_b2  text_c2  2019002;2018101  Alice;Emma
2  II_G47281  text_b4  text_C4  2019002;2018101  Alice;Emma
3   X_H46291  text_b3  text_c3          2019001        John

Answer: Using my fuzzy_merge function:
from fuzzywuzzy import fuzz
from fuzzywuzzy import process

df3 = fuzzy_merge(df2, df1, 'Account', 'Account', threshold=80)\
     .merge(df1, left_on='matches', right_on='Account', suffixes=['', '_2'])\
     .drop(columns=['matches', 'Account_2'])

Output
     Account    Col_B    Col_C               ID        Name
0   B36363-0  text_b1  text_c1          2019001        John
1  01_G47281  text_b2  text_c2  2019002;2018101  Alice;Emma
2  II_G47281  text_b4  text_C4  2019002;2018101  Alice;Emma
3   X_H46291  text_b3  text_c3          2019001        John

Fuzzy_merge function from linked answer:
def fuzzy_merge(df_1, df_2, key1, key2, threshold=90, limit=2):
    """
    df_1 is the left table to join
    df_2 is the right table to join
    key1 is the key column of the left table
    key2 is the key column of the right table
    threshold is how close the matches should be to return a match
    limit is the amount of matches will get returned, these are sorted high to low
    """
    s = df_2[key2].tolist()

    m = df_1[key1].apply(lambda x: process.extract(x, s, limit=limit))
    df_1['matches'] = m

    m2 = df_1['matches'].apply(lambda x: ', '.join([i[0] for i in x if i[1] >= threshold]))
    df_1['matches'] = m2

    return df_1


How do I give access to SQL Server 2005 Reports for users outside domain without using FBA

Question: How do I give access to SQL Server 2005 Reports for users outside domain without using FBA.
I've built report using SSRS 2005 and published it on the report server.
The account is able to access the ASP.NET page which has the report control on it.
However the report area is inaccessible and gives 401 error for unauthenticated user.
Answer: We used NTLM proxy for this.
http://ntlmaps.sourceforge.net/
The developers did the most of it so I'm at a loss for details however.
Answer: Thanks Mo for the answer.
However, we got it fixed by giving access rights to sql server, report manager, report server and report directory to the asp.net application account.
Comment: Be really, really careful how much access rights you give.  If someone drops an aspx page in your web server that drops databases, and if you gave the asp.net account enough permissions, it'll happen.  This is hacker gold.
Comment: thanks for the tip.  in this case, the asp.net application by itself is an intranet application which requires password/usb smart card to log into.  but i would definitely want to look into the other options.


State for not empty EditText in Android

Question: I use this selector for my EditText:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:drawable="@drawable/mostatil" />
    <item android:state_focused="false" android:drawable="@drawable/mostatil50" />

</selector>

Is there any state for EditText that shows EditText is not empty (user wrote something in it)?
Answer: /Just use the below code Snippet/

<selector xmlns:android="http://schemas.android.com/apk/res/android">

   <item android:drawable="@drawable/mostatil50" android:state_pressed="true" />
   <item android:drawable="@drawable/mostatil" android:state_focused="true" />
   <item android:drawable="@drawable/mostatil" />

</selector>

Answer: You could check if EditText is empty by using the following code:
EditText edittext = (EditText)findViewById(R.id.edittext);
edittext = edittext.getText().toString();
if (edittext.matches("")) {
    //do something here
}
else {
    //do something else
}

Comment: thanks,by the code, I should add a listener for all other items in the layout to detect any change. if there is a state for this situation ...
Comment: Sure, for other text related elements, you can use a similar listener. However for state changes related to focus, press, activation etc. you can use XML code directly.
Comment: If this or any other answer solved the question, please consider accepting it.

State for not empty EditText in Android


Can´t bind mongodb service on Appfog

Question: Hi i´m trying to bind mongodb service on my expressjs app with Appfog.
I have a config file like this:
config.js
var config = {}

config.dev = {};
config.prod = {};

//DEV
config.dev.host = "localhost";
config.dev.port = 3000;
config.dev.mdbhost = "localhost";
config.dev.mdbport = 27017;
config.dev.db   = "detysi";

//PROD
config.prod.service_type = "mongo-1.8";
config.prod.json         = process.env.VCAP_SERVICES ? JSON.parse(process.env.VCAP_SERVICES) : '';
config.prod.credentials  = process.env.VCAP_SERVICES ? config.prod.json[config.prod.service_type][0]["credentials"] : null;
config.prod.mdbhost      = config.prod.credentials["host"];
config.prod.mdbport      = config.prod.credentials["port"];
config.prod.db           = config.prod.credentials["db"];
config.prod.port         = process.env.VCAP_APP_PORT || process.env.PORT;

module.exports = config;

And this is my mongodb conf depending of the environment
app.js
if ( process.env.VCAP_SERVICES ) {
    server = new Server(config.prod.mdbhost, config.prod.mdbport, { auto_reconnect: true });
    db = new Db(config.prod.db, server);
} else {
    server = new Server(config.dev.mdbhost, config.dev.mdbport, { auto_reconnect: true });
    db = new Db(config.dev.db, server);
}

I bind the service manually from https://console.appfog.com, my app is using the infra AWS Virginia. I also use MongoHQ addon to create one collection with two documents.
When i go to Windows console and write af update myapp it throws me next error:

Cannot read property '0' of undefined

This is cause process.env.VCAP_SERVICES is undefined.
I was investigating that and it can be that my mongodb service is incorrectly binded.
After that i tried to bind mongodb service from the windows console like below:
af bind-service mongodb myapp

But it throws me next error:

Service mongodb and App myapp are not on the same infra

At this point i don´t know what can i do.
Answer: I had the same problem.
What fixed it for me:
Go to: console>services>(re)start mongodb service
Run the same command again.
Push again.
It should work.

Can´t bind mongodb service on Appfog


chamar um .exe em javaScript ou html

Question: Estou migrando um sistema desktop para web , com já temos grande parte pronta, gostaria de subir ela e chamar o que ainda não ta pronto da aplicação pelo browser , gostaria de uma ajuda, na seguinte questão qual a melhor maneira de fazer isso, usando angular, javascript puro, html?
Comment: Procure por URI Handler na linguagem utilizada no seu sistema desktop para saber como registrar URLs do tipo `suaAplicacao:\\dados`.
Comment: Javascript não tem acesso direto ao disco ou propriedades do sistema, a não ser pelo node.js.
Comment: tem alguma maneira de fazer  um aplicação web service abrir uma aplicação em desktop?
Comment: O que você poderia fazer é uma aplicação back-end (node.js, java, spring, etc) com um end-point que quando consumido executa o seu .exe, e consumir esse end-point da sua aplicação web.
Answer: Você pode implementar um URI Handler.
Crie um arquivo .REG a ser executado, com as devidas permissões, nas máquinas Windows, com um conteúdo similar a este:
REGEDIT4

[HKEY_CLASSES_ROOT\SuaAplicacao]
@="URL:Protocolo SuaAplicacao"
"SuaAplicacaoHandler"=""

[HKEY_CLASSES_ROOT\SuaAplicacao\DefaultIcon]
@="\"C:\\Program Files\\SuaAplicacao\\SuaAplicacao.exe\""

[HKEY_CLASSES_ROOT\SuaAplicacao\shell]

[HKEY_CLASSES_ROOT\SuaAplicacao\shell\open]

[HKEY_CLASSES_ROOT\SuaAplicacao\shell\open\command]
@="\"C:\\Program Files\\SuaAplicacao\\SuaAplicacao.exe\" \"%1\" \"%2\" \"%3\" \"%4\" \"%5\" \"%6\" \"%7\" \"%8\" \"%9\""

Após isso, utilize URLs no seguinte formato:
SuaAplicacaoHandler://qualquerDadoQueDesejarPassar
para que sua aplicação Windows seja invocada, e o parâmetro qualquerDadoQueDesejarPassar recebido pela aplicação.
Comment: valeu OnoSendai
Comment: @Aderbal não por isso, é sempre um prazer ajudar. =)
Answer: Não é possível executar arquivos executáveis pelo browser. Por questão de segurança. Já que grande parte do trabalho já foi realizado em sua aplicação desktop. É aconselhado implementar o conceitos de flags na aplicação desktop (passagem de parâmetros) e então consumir este com algumas funções script para disponibilizar os recursos e processamentos através de uma REST API. Assim você poderá utilizar em sua aplicação Web.

chamar um .exe em javaScript ou html


what is procedure to become a cricket umpire in state level?

Question: I want to know what's the procedure to become a state level Cricket Umpire?
please explain starting from the grass root Steps.
Comment: Voted to reopen to close it as a duplicate of the question I have mentioned above.
Comment: Look at [this question](http://sports.stackexchange.com/q/2611/540) this may help you.
Answer: You need to contact your local cricket authority - I think you can find them at http://www.orissacricket.org/
The normal procedure is to do a preliminary training course, and pass an exam, all on the laws of the game and practices of umpiring. Then you start umpiring in matches (lower-league adult games or childrens' games). If you're good enough, and prepared to put in the time and effort, you will progress through the ranks.
Good luck with it - umpiring is very enjoyable and a great way to be involved in the game at any level.


Exception generated from destination of a call

Question: I wrote this code:
    AssemblyName assemblyName = new AssemblyName("SamAsm");
    AssemblyBuilder assemblyBuilder =      Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
    TypeBuilder typeBuilder = assemblyBuilder.DefineDynamicModule("SamAsm.exe").DefineType("SamAsmType", TypeAttributes.Public);
    MethodBuilder methodBuilder1 = typeBuilder.DefineMethod("Main", MethodAttributes.Static | MethodAttributes.Public, typeof(void), new Type[] { typeof(string) });
    ILGenerator gen = methodBuilder1.GetILGenerator();
    FieldInfo field1 = typeof(Form1).GetField("TextBox1", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

    MethodInfo method2 = typeof(Control).GetProperty("Text", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetGetMethod();
    MethodInfo method3 = typeof(String).GetMethod(
        "op_Equality",
        BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic,
        null,
        new Type[]
        {
            typeof(String),
            typeof(String)
        },
        null
    );
    MethodInfo method4 = typeof(MessageBox).GetMethod(
        "Show",
        BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic,
        null,
        new Type[]
        {
            typeof(String)
        },
        null
    );

    LocalBuilder a = gen.DeclareLocal(typeof(Boolean));

    System.Reflection.Emit.Label label42 = gen.DefineLabel();

    gen.Emit(OpCodes.Nop);
    gen.Emit(OpCodes.Ldarg_0);
    gen.Emit(OpCodes.Ldfld, field1);
    gen.Emit(OpCodes.Callvirt, method2);
    gen.Emit(OpCodes.Ldstr, "HI");
    gen.Emit(OpCodes.Call, method3);
    gen.Emit(OpCodes.Ldc_I4_0);
    gen.Emit(OpCodes.Ceq);
    gen.Emit(OpCodes.Stloc_0);
    gen.Emit(OpCodes.Ldloc_0);
    gen.Emit(OpCodes.Brtrue_S, label42);
    gen.Emit(OpCodes.Nop);
    gen.Emit(OpCodes.Ldstr, "You cracked me");
    gen.Emit(OpCodes.Call, method4);
    gen.Emit(OpCodes.Pop);
    gen.Emit(OpCodes.Nop);
    gen.MarkLabel(label42);
    gen.Emit(OpCodes.Ret);

    typeBuilder.CreateType().GetMethod("Main").Invoke(null, new string[] { null });
    assemblyBuilder.SetEntryPoint(methodBuilder1, PEFileKinds.WindowApplication);}

When I run it stops on
typeBuilder.CreateType().GetMethod("Main").Invoke(null, new string[] { null });

With this error:

Exception generated from destination of a call.

I checked the IL code emitted, I think it is ok. What should I do to resolve this?
Comment: I just tested in in LINQPad and it works if I remove all the emitted code except the first Nop and the last Ret. So there must be a problem with the rest.
Comment: I really can't find the problem in the il code.. maybe can you help me?
Comment: I am sorry, I don't have much experience with IL code. Try comparing it with IL generated by the compiler if you write equivalent C# code.
Answer: For one thing it looks like you're declaring your method to take a string argument when it should take a Form1 (based on your use of ldfld).


Vue devtools in Chrome: Vue.js not detected

Question: I am new to Vue and I experiment with Vue 3 Composition API, which I created demo app and it works fine.
I installed Vue.js Devtools in Chrome, but when I open my site I can do nothing with it;
it has a gray/disabled look and when I click on it, I get tooltip "Vue.js not detected", and in my Developer Tools I don't see any tab regarding Vue or whatsoever.
EDIT: I run some localhost app like "http://localhost:8998/#/home"
EDIT2: Which one? IDK, I just googled it and chose the one at the top with the best user rating, I add a capture
Comment: For Vue 3 you need to install the version 6 beta of the Devtools. Links: https://v3.vuejs.org/guide/installation.html#vue-devtools
Comment: You need version 6 of the Vue Devtools, not Chrome Devtools. The link I provided should guide you to the relevant download. From the picture in your question it seems you have the wrong one. You need the one at the top, with the orange `beta` logo. You may also need to disable the other copy of the Devtools (this is explained on the download page).
Comment: Thank you. I tried installed that beta, but the result is the same. I disabled other 2 extensions I use (all others were disabled before in the past) "Clear cache" and "Moesif Origin & CORS Changer" however, the results are same. I open the page running Vue solution, and open developer tools, icon is gray and says "Vue.js not detected". I tried closing devtools, closing tab, closing browser, etc.
Comment: Can you add some more details? How you created/initialise the app etc.
Comment: Also, did you install the [latest Vue Devtools](https://chrome.google.com/webstore/detail/vuejs-devtools/ljjemllljcmogpfapbkkighbhhppjdbg)? There's a new version for Vue 3
Comment: https://stackoverflow.com/questions/62059776/vue-js-devtools-not-showing What helps for me is closing all devtools, closing localhost tab with Vue app, disabling the Vue devtools addon, enabling it again, then opening localhost and F12 to see if vue devtools tab is there. This happens both on Vue2 and the Vue3 beta devtools
Comment: @ArturTagisow I just tried step by step what you wrote. Nope, still gray icon, still nothing in my developer tools regarding vue.
Comment: Hmm can you see the fixes in https://github.com/vuejs/vue-devtools/issues/620 ? This is a very common problem.
Comment: @skirtle IDK what you mean (I just googled Chrome devtools 6 and nothing), I have the latest version of Chrome.
Answer: credit: skirtle
Vue 2 and Vue 3 have separate versions of the devtools. Make sure you're using the version that's compatible with Vue 3. Currently that'd be 6.0.0 beta 3.
You'll also need to use a dev build of Vue for the devtools to be able to interact with it. It won't work with a production build of Vue.
Answer: I also had problems with the plugin for Vue3. Recently a new version came out and now everything is working. Below is the link to the working version:
https://devtools.vuejs.org/guide/installation.html
Answer: Have you tried npm run dev? Your Vue application needs to be in development mode in order for the Vue dev tools tab to display.


Detectar a mudança de resolução da janela

Question: Preciso que quando o usuario redimensionar a janela, eu consiga detectar para poder mandar a pagina dar um refresh.
Comment: se queres a questão como resolvida, marca uma resposta como correta, não alteres o titulo da pergunta.
Comment: Pegasus, parece que você ainda não sabe [*Como e por que aceitar uma resposta?*](http://meta.pt.stackoverflow.com/q/1078/201)
Answer: Em JavaScript temos um manipulador de eventos para o evento de redimensionamento da window, o window.onresize (Inglês).
window.onresize = function(){
   location.reload();
};

Mas atenção:
Despoletar uma atualização da página no decorrer da alteração do tamanho da tela é complicado, porque enquanto estamos a alterar o tamanho, a página recarrega, volta a detetar a mudança, volta a recarregar...
A solução passa por garantir que a alteração de tamanho terminou e após isso chamar a atualização:
function recarregarPagina(){
    // Sem redimencionamento à 100ms!
    location.reload();
}

var boraLa;
window.onresize = function(){
  clearTimeout(boraLa);
  boraLa = setTimeout(recarregarPagina, 100);
};

Aqui, fazendo uso do setTimeout() (Inglês) e do clearTimeout() (Inglês) estamos a verificar a cada 100 milissegundos se a página ainda está a ser redimensionada. Se já acabou, chamamos a nossa função recarregarPagina().
Enquanto o utilizador estiver a redimensionar a tela, o temporizador está sempre a ser colocado a 0 (zero). Quando o utilizador parar de redimensionar a tela, ao fim de 100 milissegundos a nossa função recarregarPagina() é chamada. Dentro da mesma temos o código a executar, no teu caso: location.reload();.
Comment: Ótima resposta. Perfeito!
Answer: Se você pode usar JQuery:
$(window).resize(function() {
  // código que será executado quando o browser for redimensionado.
});

Veja: JQuery - método .resize
Answer: //recarrega a pagina se mudar a resolução.
$( window ).resize(function() {
  document.location.reload();
});//

Comment: Não creio que vai ficar legal dessa maneira. A função pode ser invocada várias vezes enquanto a janela está sendo redimensionada (usuário arranstando a borda do navegador).


Editar linhas em vbscript

Question: Estou tentando aprender VBS para resolver um problema que aconteceu quando tentei importar um arquivo no meu sistema. O arquivo possui mais de 4000 linhas e todas as linhas devem ter 240 caracteres. (Não tenho backup)
Atualmente, o documento está desconfigurado assim:
A primeira linha está ok, com 240.
A segunda linha está apenas com CRLF.(0).
240 + 0 = 240

A terceira linha está com 238 caracteres + CRLF (238 caracteres).
A quarta linha está com 2 caracteres + CRLF (2 caracteres).
238 + 2 = 240

A quinta linha está com 236 caracteres + CRLF (236 caracteres).
A sexta linha está com 4 caracteres + CRLF (4).
236 + 4 = 240

A sétima linha está com 234 caracteres + CRLF (234 caracteres).
A oitava linha está com 6 caracteres + CRLF (6 caracteres).
234 + 6 = 240

Notei que esse padrão continua por todo o arquivo, portanto creio que consigo corrigir isso por VBS.
Alguém poderia me auxiliar a criar um script para resolver esse problema?
Creio que devo ler cada linha, usar Len() para verificar a quantidade de caracteres e dar um DELETE onde seria o CRLF caso a linha tenha menos de 240 posições.
Ou talvez fazer Split e concatenar a linha k com a linha k+1, num loop onde k começa com 0(linha 1 do arquivo) e receberá K = K+2 a cada iteração.
Vou tentar primeiro fazer a opção do Split. Caso alguém queira colaborar com algum tipo de código ou apenas dizer uma forma mais inteligente de solucionar o caso, agradeço!
Answer: Script vbs:
Dim arq
Dim obj

Set obj = CreateObject("Scripting.FileSystemObject")
Set arq = obj.OpenTextFile(WScript.Arguments(0), 1)

Dim texto
Dim conteudo
Dim tamanho

texto = arq.ReadAll
arq.Close
Set obj = Nothing

conteudo = Split(texto, vbCrLf)
tamanho = UBound(conteudo) - LBound(conteudo) + 1

Dim i
Dim numlinha

numlinha = 0
Do While numlinha < tamanho
    Dim novo
    novo = conteudo(numlinha)

    If Len(novo) < 240 Then
        Dim primeiralinha
        primeiralinha = numlinha
        Do While numlinha < tamanho And Len(novo) < 240
            numlinha = numlinha + 1
            novo = novo & conteudo(numlinha)
        Loop
        If Len(novo) <> 240 Then
            Err.Raise vbObjectError + 514, _
                "Erro concatenando linhas entre " & (primeiralinha + 1) & _
                " e " & (numlinha + 1) & " (inclusive)"
        Else
            WScript.Echo novo
        End If
    ElseIf Len(novo) > 240 Then
        Err.Raise vbObjectError + 515, _
            "Linha " & (numlinha + 1) & " tem mais de 240 caracteres"
    Else
        WScript.Echo novo
    End If

    numlinha = numlinha + 1
Loop

Para usar:
cscript script.vbs c:\dados\meuarquivo.txt > c:\dados\meunovoarquivo.txt

Editar linhas em vbscript


If $S\leq G$, prove that $S\unlhd G \iff \gamma (S) \leq S$ for every conjugation $\gamma$

Question: If $S\leq G$, prove that $S\unlhd G \iff \gamma (S) \leq S$ for every conjugation $\gamma$
I have proven the forward direction but I am not sure that the way I prove the converse is true.
Let $g\in G,s\in S$.
$$gsg^{-1}=s_1,s_1\in S$$
$$\implies gs=s_1g$$
$$\implies gS \subset Sg$$
Also,
$$sg^{-1}=g^{-1}s_1$$
$$\implies Sg^{-1}\subset g^{-1}S$$
Hence, $Sg=gS$ and $S$ is normal in $G$.
Comment: Just check that all the implications are reversible.
Comment: How does $gs=s_1g$ imply $gS\subset Sg$? Perhaps you are missing sume quantification.
Comment: @anon This equation holds for every s right?
Comment: Right. Like I said, missing some quantification. If for every $s\in S$ there is a $s'\in S$ for which $gs=s'g$ (hence $gs\in Sg$), then in particular we have $gs\in Sg$ for every $s\in S$, hence $gS\subseteq Sg$.
Comment: @anon Ok noted. Then does $Sg^{-1}\subset g^{-1}S$ implies $Sg\subset gS$? I am not pretty sure with this.
Answer: You have the right idea, but I think the proof would be clearer if you used the same $g$ for the cosets.
For the backwards inclusion, you could write:
Let $sg \in Sg$. Since $g^{-1}sg \in S$ (because $S$ is normal), we have $g^{-1}sg=s'$ for some $s'\in S$.
Hence, $sg = gs' \in gS$, so $Sg \subseteq gS$.


evaluating $\int_0^{k!}e^{i\frac{t^k}{k!}} dt$

Question: How to evaluate the following integral?$$
\int_0^{k!}e^{i\frac{x^k}{k!}} dx
$$ Here $k$ can be any positive integer. When $k=2$, I can square it and use polar coordinates. But I've no idea about the general $k$.
Comment: You can evaluate the integral in terms of the incomplete Gamma function.
Comment: I've provided the answer in terms of the Lower Incomplete Gamma function.  It isn't pretty.
Comment: I hope that my answer was of use to you.  I really do want to help, so, please let me know if there is any way that I can improve my answer.  I just want it to be the best possible answer for you.
Comment: @Dr.MV Sorry for my late reply and thank you for your answer. I got this question from an exercise in a textbook and it seems to me the integral should depend linearly on $k$.
Comment: Why do you believe that the dependence should be linear on $k$?
Comment: @Dr.MV The exercise says so. You see that the upper limit of the integral and the coefficient of $x^k$ match. I suspect that there should be some nice cancellation going on.
Comment: $\frac{(k!)^k}{k!} = (k!)^{k-1}$.  I'm not sure it is obvious.
Answer: Let $t=-i\frac{x^k}{k!}\Rightarrow x=(ik!)^{\frac{1}{k}} t^{\frac{1}{k}}$.  Then, we have
$$dt=-i\frac{x^{k-1}}{(k-1)!}dx$$
$$x=(ik!t)^{\frac{1}{k}}$$
$$I=\int_0^{k!} e^{i\frac{x^k}{k!}}dx=C_k\int_0^{-i(k!)^{k-1}} t^{\frac1k-1}e^{-t}dt$$
where $C_k=-(i)^{\frac{1}{k}}\frac{(k!)^{\frac1k}}{k}$.  Now, noting that the lower Incomplete Gamma function $\gamma (s,x)$is given by
$$\gamma (s,x)=\int_0^x t^{s-1}e^{-t}dt$$then $I$ is given by
$$I=C_k \gamma \left(\frac{1}{k},-i(k!)^{k-1}\right)$$


Change responsive and unresponsive site with button click

Question: I have a responsive site with bootstrap 3.1.1. I want to show the desktop view when the user click a button "Desktop view".
I have used this question right here as the support but this does not help.
It does not help for 2 reasons:-

The CSS I have added in my Layout file is as shown:

<link rel='stylesheet' media='screen and (max-device-width: 480px)' href='styles/mobile.css' type='text/css' />

I have used hidden-xs, hidden-sm, hidden-md and hidden-lg classes throught out my application.

How can I make the site desktop view and mobile view with the button click?
EDIT
I am simultaneously using both the style sheets at the same time. The style sheet for "mobile.css" and "desktop.css" (for the items which doesnot need to be styled specially for mobiles).
SO swapping both the style sheet would not work.
Answer: A way: is to use Jquery to change the meta tag for the viewport when the button is clicked:
$('#buttonId').click(function (){
        $('meta[name=viewport]').attr('content', "width=1024");
});

I just thought of something simple. To all you divs that have hidden-xs classes: add a special class (had-hidden-xs), for hidden-lg add had-hidden-lg and so on for every single one of them.
//when the button is clicked, every class is removed
$('#buttonId').click(function (){
   //removes all the classes
   $('.hidden-xs, .hidden-sm, .hidden-md, .hidden-mg').removeClass('hidden-xs hidden-sm hidden-md  hidden-mg');
});

//when the button to go to mobile view is clicked:
$('#backToMobile').click(function (){
   //add back your classes using the classes you created in the previous 2 steps
   $('.had-hidden-xs').addClass('hidden-xs');
   $('.had-hidden-sm').addClass('hidden-sm');
   $('.had-hidden-md').addClass('hidden-md');
   $('.had-hidden-lg').addClass('hidden-lg');
});

Before Question Edit: Looking at your style sheet, you probably have a style for desktop too since you have a mobile.css. You can easily swap the stylesheets using jquery
$('#buttonId').click(function (){
   $('link[href="styles/mobile.css"]').attr('href','desktop.css');
});

$('#buttonId').click(function (){
   $('link[href="style/desktop.css"]').attr('href','mobile.css');
});

Comment: Please check the edit. Swapping would not work in these cases. Even if swapping would have worked I would not have been able to come around with the second issue of (hidden classes).
Comment: check my edit @user3328402 . I think the second option deals with both. It will behave just like the question you checked to help solve your problem.
Comment: I tried the method with the question but that didn't help me with the second issue of hidden classes and that is why I posted the question.
Comment: @user3328402 I added how to remove all those classes. you can combine solution and everything will work fine.


Let $f:\mathbb R \longrightarrow \mathbb R$ be continuous which is also an additive homomorphism

Question: Let  $f:\mathbb R \longrightarrow \mathbb R$  be continuous which is also an additive homomorphism, that is, $f( x+ y)= f( x )+f(y) $ for all $x,y\in \mathbb R$ then $f( x)= \lambda x$ where $\lambda= f(1)$
I tried like this let $x\in N$
$f(x)=f(\underbrace{1+\cdots+1}_{x \text{ times }})= \underbrace{ f(1)+\cdots+f(1)}_{x \text{ times}} =xf(1)=\lambda x $
Say $\lambda =f(1)$. But it is the case where $x$ is natural number what to do for $x$ real.
Comment: You can kinda go on like this, showing the statement für $x\in\mathbb{Z}, x\in\mathbb{Q}$ and finally $x\in\mathbb{R}$. The case $x\in\mathbb{Z}$ is done, when you sperate the cases $x\geq 0$ and $x<0$, which is the same as for $x\in\mathbb{N}$. Now take $x\in\mathbb{Q}$. Hence $x=\frac{a}{b}$ with a\in\mathbb{Z}, and $b\in\mathbb{N}\setminus\{0\}$. Then bf(q)=f(bq)=f(a)=a\lambda, hence $f(q)=\frac{a}{b}\lambda$ after division by b. Use that f is continuous and take rational cauchy-sequences with irrational limit and you are done.
Comment: You can use `\mathbb R` to obtain $\mathbb R$ and `\longrightarrow` or `\to` for $\longrightarrow$ or $\to$.
Comment: What is q in that? Oh is it $\frac ab$ ? Yes yes I got it :) thanks
Comment: Oh, excuse me, with $q$ i meant $x$. So $bf(x)=f(bx)=f(a)=a\lambda$ and then $f(x)=\frac{a}{b}\lambda$ after division of $b$.
Comment: In your last equal sign, you can say that, since $\mathbb{R}$ is a field, every non-zero element has an inverse, assuming $x \not = 0$, you can multiply both sides with $x^{-1}$, and you get $f(1) = \lambda$.
Comment: @onurcanbektas I wrote $f(1)= \lambda $ why would I cancel out x (or apply inverse) both sides.
Comment: Apparently I just misunderstood your proof.
Comment: By the way, it might be helpful to consider the derivative of $f$ with its formal definition, i.e $\lim_{h\to 0}\frac{f(x+h) - f(x)}{h} = \lim_{h \to 0} \frac{f(h)}{h}$, and the fact that the map preserves the distance between any two real number.
Answer: Standard proof:

Let $n$ be a positive integer. Then by additivity, $$f(n) = \underbrace{f(1) + \cdots +f(1)}_{n\text{ times}} = n\cdot f(1)$$, which establishes the proof for positive integers.
Let $q$ be a positive integer. Then $f(1/q) = \frac{1}{q}f(1).$ To see this, note that $f(1) = f(q\cdot 1/q) = q f(1/q)$ by our previous result with positive integers.
Combining these two results, we have that $f(p/q) = \frac{p}{q}f(1)$ whenever $p$ and $q$ are positive integers so that $p/q$ is a positive rational number.
We can extend this result to all rational numbers by proving that $f$ is odd: $f(x) = -f(-x)$. To see that $f$ is odd, note that $f(0)$ must be zero because $f(0) = f(0+0) = f(0)+f(0) = 2f(0)$. Then, using additivity, it follows that for any $x$, $0 = f(0) = f(x + (-x)) = f(x) + f(-x)$.
Now we know that $f(r) = r\cdot f(1)$ whenever $r$ is any rational number.
Finally, we extend this result to all real numbers. Let $x$ be any real number. Then there is a sequence $r_n$ of rational numbers that converges to $x$. Because $f$ is continuous, $f(r_n)$ must converge to $f(x)$. But $f(r_n) = r_n f(1)$ as we have shown, and this sequence evidently converges to $x \cdot f(1)$. Q.E.D.

Here's an alternative proof that shows how this condition affects the derivative of $f$. In particular, we can prove that the derivative of $f$ must be constant—namely, equal to $f(1)$.

Let $n$ be any positive integer. Then $f(1/n) = \frac{1}{n}f(1)$. To see this, note that $f(1) = f(n/n) = \underbrace{f(1/n)+f(1/n)+\cdots + f(1/n)}_{n\text{ times}} = nf(1/n)$. Then divide the first and last terms by $n$.
Suppose the limit $L \equiv \lim_{\epsilon\rightarrow 0}\frac{f(\epsilon)}{\epsilon}$ exists. (We'll prove that it does later.)
The derivative of $f$ exists and is constantly equal to $L$. Indeed, for any $x$,
$$\begin{align*}f^\prime(x) &= \lim_{\epsilon\rightarrow 0}\frac{f(x+\epsilon)-f(x)}{\epsilon}\\&= \lim_{\epsilon\rightarrow 0} \frac{f(x) + f(\epsilon) - f(x)}{\epsilon}&\{\text{additivity}\}\\&= \lim_{\epsilon\rightarrow 0} \frac{f(\epsilon)}{\epsilon}\\&= L.\end{align*}$$
Because the derivative of $f$ is constant, we must have by integration that $f(x) = Lx + C$ for some constant $C$. Because $f$ is additive, $C$ must be zero. (Because, for example, $f(2) = 2L+C$ whereas $f(1)+f(1) = 2(L+C)=2L+2C$.) Hence $f(x) = L\cdot x$.
Now we show that the limit $L$ exists. Let $r_n\rightarrow 0$ be a vanishing sequence of rational numbers.  We can write the limit $\lim_{\epsilon\rightarrow 0} \frac{f(\epsilon)}{\epsilon}$ as the limit of a sequence $\lim_{n\rightarrow \infty}\frac{f(r_n)}{r_n} = \lim_{n\rightarrow \infty}\frac{f(p_n/q_n)}{p_n/q_n}$. We know from additivity and our first observation above that we can rewrite $f(p_n/q_n) = \frac{p_n}{q_n} f(1)$, yielding   $L = \lim_{n\rightarrow \infty}\frac{\frac{p_n}{q_n}f(1)}{p_n/q_n} = \lim_{n\rightarrow\infty}f(1)$. Hence it's the limit of a constant, whose value is $L=f(1)$. Because $f$ is continuous, this result holds for all sequences, not just sequences of rationals, so the limit holds. Q.E.D.
Comment: But where did you prove the limit $L$ exists?
Comment: @PedroTamaroff Step 5. I've rephrased slightly to clarify.
Comment: You still don't prove the limit exists in that step, only that if it exists, it must be $f(1)$. It is not true that the limit $\lim_{t\to 0}f(t)/t$ exists if it exists for a sequence $t_n\to 0$.
Comment: I like the standard proof ..the one without actually finding the function ...since it is easy for me...but the other one is interesting...
Answer: I wrote this one up last night but then fell asleep before I posted; when I awoke, I found the answer of user 326210 and the engaging dialog 'twixt himself and Pedro Tamaroff, but decided to throw my US \$0.02 into the hat anyway.  You can think of it as sharing my lecture notes . . .
Well, first off,
$f(0) = f(0 + 0) = f(0) + f(0), \tag{1}$
so
$f(0) = 0; \tag{2}$
also,
$f(a) + f(-a) = f(a + (-a)) = f(0) = 0, \tag{3}$
so
$f(-a) = -f(a); \tag{4}$
(4) holds for all $a \in \Bbb R$; now for $n \in \Bbb N$,
$f(n) = nf(1), \tag{5}$
as a simple induction proves:  if
$f(k) = kf(1), \tag{6}$
then
$f(k + 1) = f(k) + f(1) = kf(1) + f(1) = (k + 1)f(1); \tag{7}$
thus (5) binds.  Using (2), (4), and (5), we conclude
$f(m) = mf(1) \tag{8}$
for all $m \in \Bbb Z$.  So we have (8) for all integers.  We move outward in scope and extend the relation
$f(r) = rf(1) \tag{9}$
to all $r \in \Bbb Q$, the rationals.  Writing
$r = \dfrac{p}{q}, \tag{10}$
where $p, q \in \Bbb Z$, we have
$p = q \dfrac{p}{q} = qr; \tag{11}$
thus,
$f(qr) = f(p) = pf(1); \tag{12}$
we now observe that essentially the same inductive argument which proves (5), (8) may easily be extended to show that
$f(nx) = nf(x) \tag{13}$
where $n \in \Bbb Z$, $x \in \Bbb R$, viz.
$f(x) = f(x), \tag{14}$
$f(2x) = f(x + x) = f(x) + f(x) = 2f(x); \tag{15}$
and assuming
$f(kx) = kf(x), \tag{16}$
we have
$f((k + 1)x) = f(kx + x) = f(kx) + f(x) = kf(x) + f(x) = (k + 1)f(x); \tag{17}$
we now apply (13) to (12):
$qf(r) = f(qr) = pf(1), \tag{18}$
whence
$f(r) = \dfrac{p}{q}f(1) = rf(1) \tag{19}$
holds for all rationals $r \in \Bbb Q$.
Now for real $t \in \Bbb R \setminus \Bbb Q$, we take a sequence $t_i \in \Bbb Q$ with
$\lim_{i \to \infty} t_i = t; \tag{20}$
then since $f$ is continuous by hypothesis,
$f(t) = \lim_{i \to \infty} f(t_i) = \lim_{i \to \infty} (t_i f(1)) = (\lim_{i \to \infty} t_i)f(1) = tf(1), \tag{21}$
and we are done!


How do I call an Excel macro from Python using xlwings?

Question: I've read the API docs for xlwings, and played around with Workbook and Sheet objects in the interpreter, but I can't figure out how to call a macro from Python.
How do I use xlwings to call an Excel macro from Python?
Answer: This is not implemented yet, but there's an open issue for it, see here. In the meantime, you can work around it like so (this is for Windows, but the Mac version works accordingly, see again in the issue):
from xlwings import Workbook
wb = Workbook(...)
wb.application.xl_app.Run("your_macro")

update: for more recent versions, you have to do:
from xlwings import Workbook, Application
wb = Workbook(...)
Application(wb).xl_app.Run("your_macro")

update 2: This functionality is now natively supported from >=v0.7.1. Let's assume, there is a VBA function YourMacro that sums up two numbers:
>>> import xlwings as xw
>>> wb = xw.Book(r'C:\path\to\mybook.xlsm')
>>> your_macro = wb.macro('YourMacro')
>>> your_macro(1, 2)
3.0

Answer: I got issues when I updated xlwings to 0.9+ version.
To run vba macro with xlwings, I used the code written below for running macros inside the personal workbook (PERSONAL.XLSB).
The updated code no2 of Felix didn't work for me, for macro inside the personal workbook.
import xlwings as xw

wb = xw.Book(excel_file_path)
app = wb.app
# into brackets, the path of the macro
macro_vba = app.macro("'PERSONAL.XLSB'!my_macro")
macro_vba()

Hope it will help.
Comment: Thanks for this! And for completeness' sake: import xlwings as xw ;)
Answer: I know it is a late answer, but all the ways posted above didn't work for me.
But I have found another way, by using the awesome api-interface provided by xlwings.
Here is my code I used to run a macro:
xlApp = xw.App(visible=False)
wb= xw.books.open('.\\Path\\To\\File.xlsm')
a = xlApp.api.Application.Run("macroTest")

My macro opened a MsgBox and returned the value 1 just for test and it worked very well.
Although one should avoid using MsgBox, since it was opened in background.
Btw. the api-interface is available in many (when not all) objects and it is really powerfull if you are used to VBA programming.
Answer: Another simple way if you already open a excel.
xw.apps.active.macro('yourMacro')(1, 2)

Answer: Extending @Felix Zumstein's answer and all other answers here, please ensure you have disabled Macro settings as you may face COM issues later.
You can change that under,
File > Options > Trust Center > Trust Center Settings > Macro Settings > Enable all macros (not recommended...)


Advice for Debugging Apache with PHP Segmentation Faults

Question: Every hour or so an Apache child process seg. faults on our web server. We are running a non-threaded PHP 5.2.17 Apache module with Apache prefork MPM. I have run httpd with a few core dumps, gdb and this .gdbinit file from php's github repo, typing this command into gdb for each:
dump_bt executor_globals.current_execute_data

With no experience with gdb or the inner-workings of the php interpreter, I can't make anything from the results.
core.22762
[0x53896ef0] () :-2118682552
[0x538977a0] () /Statement/Interface.php:113
[0x538978a0] /Zend/Db/Statement/Interface.php()

core.22791
[0x538977a0] () @:0
[0x538978a0] ()

core.5568
[0x53896ef0] () :2061035360
[0x538977a0] () :1767992432
[0x538978a0] ()

core.30384
[0x538977a0] () :0
[0x538978a0] ()

core.3091
[0x53896ef0] mysql_query():992424253
[0x538977a0] () ~:17
[0x538978a0] ()

(core.3091 also shows this after Program terminated with signal 11, Segmentation fault.)
#0  0x00002b6e7ad8d67d in zend_do_fcall_common_helper_SPEC (execute_data=0x7fff53896ef0) at /usr/src/debug/php-5.2.17/Zend/zend_vm_execute.h:217
217                             EX_T(opline->result.u.var).var.fcall_returned_reference = return_reference;

Is there something else that I can type in gdb to get a better stack trace? Is there anything else that you do when debugging Apache segmentation faults?
Any help would be greatly appreciated, thanks.
Comment: Running `bt full` from `(gdb)` prompt, it may helpful. But if you're not familiar with PHP, all you can do is file a bug to PHP developers.
Comment: Thanks for the tip. bt full definitely gives more information. I'll probably end up filing a bug on the PHP site.
Answer: I've seen this before.. apart from getting your PHP app developers to check their code, and making sure you have up-to-date versions (from your distribution) of PHP and apache, there isn't much you can do.
If you're running an Op-Code cacher (eaccelerator, APC or XCache), you could try turning them off, they're known to cause the odd segfault.
In the past, we've had to deploy some impressively hackish solutions to a segfaulting system, for short-term fixes, of course. For example, this cronjob worked well:
# Restart apache when a segfault is found in the most recent line of errorlog
#*/5 * * * * tail -n1 /var/log/apache2/error.log | grep 'Segmentation fault' && /etc/init.d/apache2 restart
Or you could try something a bit more clever:
#*/5 * * * * /usr/bin/wget http://www.my-site.com/ -T10 -O 2> /dev/null - | grep "Hosted by" > /dev/null || /usr/local/bin/brutally_restart_apache.sh
Where brutally_restart is:
    #!/bin/sh
    /usr/sbin/apache2ctl stop
    sleep 6
    killall -9 apache2
    sleep 4
    /usr/sbin/apache2ctl start

Comment: "brutally_restart_apache.sh" - nice name ;)

Unfortunately, disabling APC didn't help. We have something similar in place for restarting Apache.

We're still on PHP 5.2.17, so hopefully upgrading to 5.3 will help.