Definition of flatness for a connection on a vector bundle

Question: Let $M$ be a Riemannian manifold, $E \to M$ a vector bundle and $\nabla : \Gamma(E) \to \Gamma(T^*M \otimes E)$ a connection on $E$.
I'm a bit confused on the definition of flatness. The word is used a bit vaguely here and there.
Lee calls a Riemannian manifold flat if and only if the curvature tensor $R $ vanishes identically.
Some authors call the connection flat if $R$ vanishes identically.
Is this just a poor choice of words or am I misunderstanding something here? To be clear, I'm trying to understand the definition of a flat connection, but I can't find a good resource anywhere. Someone also defined flat connection by $\nabla^2 = 0$, but this is different than $R = 0$ right? If $F$ is a $(k,l)$-tensor field, then $\nabla^2F$ is a $(k,l+2)$-tensor field and I don't see how $\nabla^2_{X,Y}F= \nabla_X(\nabla_YF) - \nabla_{\nabla_XY}F$ is related to the curvature.
Any clarification for this would be appreciated.
Comment: The [exterior covariant derivative](https://en.wikipedia.org/wiki/Connection_(vector_bundle)#Exterior_covariant_derivative_and_vector-valued_forms) $d_\nabla$ (or your author prefers calling it just $\nabla$) is the operator satisfying $d(\omega \otimes s) = d\omega\otimes s + (-1)^{\text{deg}(\omega)}\omega\wedge \nabla s$. It leaves the "direction" slot of the directional derivative empty, raising the degree of the form. If you do it twice, you get the curvature. If the curvature is zero, you call the connection flat.
Comment: I think the form you have written, $\nabla^2_{X,Y}F=\nabla_X(\nabla_Y F)-\nabla_{\nabla_X Y}F,$ is equivalent for a torsion free connection on the tangent bundle. That is, one for which $\nabla_X Y-\nabla_Y X = [X,Y].$ The form I gave is for a general connection on a vector bundle which does not have a notion of torsion.
Comment: The definition of curvature is $R(X,Y)=\nabla_X\nabla_Y-\nabla_Y\nabla_X-\nabla_{[X,Y]}$. If that is zero, then the connection $\nabla$ is flat. When you view it as an exterior covariant derivative, $R(X,Y)=\nabla_X\nabla_Y-\nabla_Y\nabla_X-\nabla_{[X,Y]}$ is in fact the same thing as $d_\nabla^2(X,Y)$
Comment: Read your quotes more closely and you will see the difference in the context: What bundle and what connection are used in the context of Riemannian metrics?
Comment: @MoisheKohan It's the tangent bundle often times.
Comment: And what connection? (Replace "often times" by "always".)
Comment: Right, okay so the definition that Lee uses for a flat Riemannian manifold is that it's flat if the Levi-Civita connection has zero curvature. The case with an arbitary vector bundle $E \to M$ is different. There is no notion of flatness for the underlying manifold, but the connection is called flat if $R^\nabla = 0$? The notation $\nabla^2 = 0$ is still mysterious. @MoisheKohan
Comment: Right. There is a way to interpret $\nabla^2$ as curvature (even for Ehresmann connections).
Comment: I have a feeling that this $d_\nabla$ is different from $\nabla^2_{X,Y}F= \nabla_X(\nabla_YF) - \nabla_{\nabla_XY}F$ which I found from the book. @ziggurism
Comment: No, those are two notations for the same thing. I think calling it just $\nabla$ is more common in Riemannian geometry
Comment: Notice how your definition of $\nabla\colon \Gamma(E) \to \Gamma(T^{*}M\otimes E)$ includes a factor of the cotangent bundle. From leaving the direction slot empty of the directional derivative.
Answer: Curvature is a property of a connection. When talking about connections on tangent bundles, we abuse language slightly and speak of curvature of the underlying manifold. See here for some more remarks about why we omit the distinction in language about objects 'living on $M$' vs 'living on $TM$'.
Next, given any linear connection $\nabla$ in a vector bundle $(E,\pi,M)$, one can construct a whole bunch of operators $d_{\nabla}$, called the exterior covariant derivative (relative to $\nabla$) which take $E$-valued $k$-forms on $M$ to $E$-valued $(k+1)$-forms on $M$, i.e $d_{\nabla}:\Omega^k(M;E)\to \Omega^{k+1}(M;E)$. This is 95% analogous to how given our usual definition of $df$ for smooth functions, we get a unique extension (after imposing some conditions) of $d$ to higher order forms.
Now, with this technology, for any section $\psi$ of $E$, we can show that $d_{\nabla}^2\psi$ is not the zero section, but rather $R\cdot_{\text{ev}}\psi$, where the $\cdot_{\text{ev}}$ denotes the evaluation pairing $\text{End}(E)\oplus E\to E$. Or more explicitly, for each $x\in M$, and each $h_x,k_x\in T_xM$, we have that
\begin{align}
(d_{\nabla}^2\psi)_x(h_x,k_x)&=R_x(h_x,k_x)[\psi(x)].
\end{align}
Or if you don't like to go to the pointwise level, we can stay at the field level and say that for all vector fields $X,Y$ on $M$,
\begin{align}
(d_{\nabla}^2\psi)(X,Y)&=R(X,Y)[\psi]=\nabla_X\nabla_Y\psi-\nabla_Y\nabla_X\psi-\nabla_{[X,Y]}\psi.
\end{align}
Therefore, vanishing of $R$ is equivalent to $d_{\nabla}^2=0$ (i.e every section $\psi$ of $E$ gets sent to the zero $E$-valued $2$-form on $M$).

You should note that on a general vector bundle $(E,\pi,M)$ with a linear connection $\nabla$, it doesn't even make sense to speak of iterated covariant derivatives $\nabla\nabla$. Why? Because if $\psi$ is a section of $E$, then $\nabla\psi$ is an $E$-valued $1$-form on $M$, or equivalently, a section of $T^*M\otimes E$. So, if I want to take a covariant derivative of $\nabla\psi$, then I would need a connection $\nabla^{T^*M\otimes E}$ on the larger bundle $T^*M\otimes E$… and in general just having a connection on $E$ does not give me a connection on $T^*M\otimes E$. You would have to either arbitrarily fix a connection on $TM$, then consider the associated connection on $T^*M\otimes E$. Or, if your vector bundle was $E=TM$ to begin with, then of course $T^*M\otimes E=T^*M\otimes TM$ is again a tensor bundle of $M$, so we have a naturally induced connection.
In any case, the iterated $\nabla\nabla\psi$ is not necessarily the same as $d_{\nabla}^2\psi$ (which is always defined). Indeed, let's just stick to the tangent bundle $TM$. Then for any torsion-free and flat connection $\nabla$ (e.g think of $\Bbb{R}^n$ with the usual flat connection) and any smooth function $f$, we have that $\nabla\nabla f=\nabla(df)$ is called the Hessian of $f$, and it is a symmetric $(0,2)$ tensor field on $M$, and not necessarily $0$. On the other hand, $d_{\nabla}^2f=d^2f=0$.
Having said this, there are some authors who use the notation $\nabla^2$ to mean not the iterated $\nabla\nabla$, but rather $d_{\nabla}^2$. Notationally, I find this confusing, but it is what it is.
Comment: Thank you @peek-a-boo. Been reading your answers on this site and I have to say, they are solid gold.
Comment: @Tepes thank you for the kind comment.


Converse of Bounded Inverse Theorem

Question: Are there examples of a bijective bounded linear operator $T\colon X\longrightarrow Y$ where $X$ is a Banach space but not $Y$, yet $T$ has a bounded inverse?
Answer: Since the condition of boundedness of $T$ was added to the question, this makes my old answer irrelevant. It can still be found below.
It is not possible to find such a $T$ because it would be an isomorphism of normed spaces which preserves properties like completeness:
If $(y_n)_n$ is a Cauchy sequence in $Y$, then $(T^{-1}y_n)_n$ is a Cauchy sequence in $X$ because $T^{-1}$ is bounded, thus the sequence $(T^{-1}y_n)_n$ converges in $X$. But then, by boundedness of $T$, the sequence $(y_n)_n = (TT^{-1}y_n)_n$ converges in $Y$, hence $Y$ is complete.

Let $(X, \|\cdot\|_1)$ be an arbitrary infinite dimensional Banach space. Then choose an arbitrary discontinuous functional $\varphi$ on $X$.1
Define $\|x\|_2 := \|x\|_1 + |\varphi(x)|$. Then $\|\cdot\|_2$ is a norm on $X$ with the property $\|\cdot\|_1\leq \|\cdot\|_2$, hence for $T:(X,\|\cdot\|_1)\to (X,\|\cdot\|_2),x\mapsto x$, the inverse $T^{-1}$ is bounded.
$(X,\|\cdot\|_2)$ is not a Banach space because this would imply $|\varphi(x)|+\|x\|\leq C\|x\|$ for some $C>0$ and all $x\in X$ by the bounded inverse theorem. This implies $|\varphi(x)|\leq (C-1)\|x\|$ however, making $\varphi$ bounded which contradicts the choice of $\varphi$.
1If $(b_i)_{i\in I}$ is a base of $X$ with $\|b_i\|_1 = 1$ for all $i$ and w.l.o.g. $\mathbb N\subset I$. Then set $\varphi(b_i) = i$ if $i\in\mathbb N$ and $\varphi(b_i)=0$ otherwise.
Comment: I just realised I am missing one key property on $T$: boundedness. My apologies.
Comment: @CheeHan I altered my answer accordingly.
Comment: Ahhhhhhh now I felt like a dumb kid asking dumb question....... Thanks! ((:

Converse of Bounded Inverse Theorem


Creating your own Node Entity Normalizer

Question: I am trying to create my own Node Entity Normalizer in Drupal 10 to get rid of the unnecessary JSON structure that comes out of the box. For example, instead of my API's returning
{
  "nid": [
    {
      "value": 7
    }
  ]
}

I want to make it return
{
  "nid": 7
}

So I've tried the following options in my custom module:

Typed Data Interface

example_normalizer.services.yml
services:
  example_normalizer.typed_data:
    class: Drupal\example_normalizer\Normalizer\CustomTypedDataNormalizer
    tags:
    - { name: normalizer, priority: 2 }

src/Normalizer/CustomTypedDataNormalizer.php
<?php
namespace Drupal\example_normalizer\Normalizer;
use Drupal\serialization\Normalizer\NormalizerBase;
/**
 * Converts typed data objects to arrays.
 */
class CustomTypedDataNormalizer extends NormalizerBase {
  /**
 * The interface or class that this Normalizer supports.
 *
 * @var string
 */
  protected $supportedInterfaceOrClass = 'Drupal\Core\TypedData\TypedDataInterface';
  /**
 * {@inheritdoc}
 */
  public function normalize($object, $format = NULL, array $context = array()) {
    $value = $object->getValue();
    if (isset($value[0]) && isset($value[0]['value'])) {
      $value = $value[0]['value'];
    }
    return $value;
  }
}

and

Custom Node Entity Normalizer

example_normalizer.services.yml
services:
  example_normalizer.node_entity:
    class: Drupal\example_normalizer\Normalizer\NodeEntityNormalizer
    arguments: ['@entity.manager']
    tags:
    - { name: normalizer, priority: 8 }

src/Normalizer/NodeEntityNormalizer.php
<?php
namespace Drupal\example_normalizer\Normalizer;
use Drupal\serialization\Normalizer\ContentEntityNormalizer;
use Drupal\Core\Datetime\DrupalDateTime;
/**
 * Converts the Drupal entity object structures to a normalized array.
 */
class NodeEntityNormalizer extends ContentEntityNormalizer {
  /**
 * The interface or class that this Normalizer supports.
 *
 * @var string
 */
  protected $supportedInterfaceOrClass = 'Drupal\node\NodeInterface';
  /**
 * {@inheritdoc}
 */
  public function normalize($entity, $format = NULL, array $context = array()) {
    // Similar logic as above
  }
}

However, in both cases, when I clear the cache I am getting the error
PHP Fatal error:  Uncaught Error: Class "Drupal\example_normalizer\Normalizer\NodeEntityNormalizer" not found in /var/www/html/web/core/lib/Drupal/Component/DependencyInjection/Container.php:262

What am I missing in my module that this is not getting picked up?
I'd like to be able to make a call like
$serializer = \Drupal::service('serializer')
$custom_json = $serializer->serialize($entity, 'json', ['plugin_id' => 'my_custom_normalizer']

Comment: You've cleared the cache? Are these pastes correct? The second example YAML does not validate.
Comment: The *example_normalizer.services.yml* file is not correctly formatted, in both the cases. The indentation must be two spaces, not a single space. Patrick Kenny's answer does not explain why you get that error, but it explains how to change the normalizer used by Drupal core.
Comment: @Kevin No, I can't clear the cache, that is when I am getting the DependencyInjection error. And the pastes were not correct, I just updated them though.
Comment: @apaderno I just updated them, they are correct in my actual module (I have an auto formatter). My ultimate goal is to be able to point to my own plugin_id when I call Drupal's serialize function.
Comment: Looks like your module is either not named "example_normalizer" or not put in the right folder. For the second example, please note, that in Drupal 10 there are 3 arguments required: `arguments: ['@entity_type.manager', '@entity_type.repository', '@entity_field.manager']`.
Answer: JSON normalization is not declared in services.yml. Instead, you want to use MyModuleServiceProvider.php to override the core class.
This is an example from my site overriding FieldItemNormalizer:
<?php

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Drupal\Core\DependencyInjection\ServiceProviderInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class MyModuleServiceProvider extends ServiceProviderBase implements ServiceProviderInterface {

  /**
   * {@inheritDoc}
   */
  public function alter(ContainerBuilder $container): void {
    $jsonapi_definition = $container->getDefinition('serializer.normalizer.field_item.jsonapi');
    $jsonapi_definition->setClass('Drupal\my_module\Normalizer\MyModuleFieldItemNormalizer');
}

Here's a general guide to overriding core services.
Comment: I don't think that is what I want to actually do. I'm not looking to override the core class completely, I just want to create a new normalizer so that I can serialize with a call like: \Drupal::service('serializer')->serialize($entity, 'json', ['plugin_id' => 'my_custom_normalizer']


Poisson versus Binomial and estimation of variance

Question: Let X denotes the number of successes in n trials and p is the probability of success.
Then, X ~ B(n, p) and EX = np, VarX = npq.
If n is really large (e.g. n > 20000) then it seems also reasonable to calculate the expected number of successes to be λ = np and model X as Poisson(λ).
Doing so we find EX = VarX = λ.
The two models provide the same expected value but different variances. I understand that the Binomial approach is the correct one.
The question is:
Is the Poisson model a false approach for this problem?
or:
What is the reason that the Poisson approach give "inflated" estimation for the variance?
Answer: The important part isn't whether $n$ is large, it's whether $p$ is small.
The Binomial approach is correct, but the Poisson is a good approximation when $p$ is small. Thinking about the variances, if $p$ is small, $q=1-p\approx 1$, and $\lambda=np\approx npq$.  The approximation gets better as $p$ gets smaller.  For example, if $p=0.001$ then $q=0.999$ and the Poisson and Binomial variances are equal to three significant digits.
The same general result is true for a lot of other properties apart from the variance, but the proof is more complicated.
Comment: The summary at the outset is incorrect.  It doesn't really matter whether $p$ is small: it matters, as your subsequent analysis shows, whether $np$ is small.
Comment: No, if $p$ is small and $n=1$, the approximation of Bernoulli(p) by Poisson(p) is excellent. The total variation difference is bounded by $\min\{p,np^2\}$
Comment: That's because in that case $np \approx p.$ The point is not whether it works, but the reasoning behind why it works.  (The key concept is that the Poisson approximates Binomial distributions asymptotically as $n$ grows large and $np$ remains bounded.) Informing readers about such basic principles enables them to correctly identify and apply a solution in future problems.


How to specialize a widget according to a file type?

Question: I'm looking for a way to specialize a widget at runtime. I have a form created with Qt Designer. In this form there is a widget that displays user data, like name, age and so on. Then the user chooses a file and according to the type the widget shall display additional information (like to OO example person -> student, teacher).
I tried to put an empty QWidget on my form, assigned a person widget to it and if the user clicks a button I call deleteLater() on person and assign a new Student(). This works but the new widget then doesn't follow the layout.
I also found QStackedWidget. This seems to work but because all possible widgets are created when the form is shown, even if they are never used, this way doesn't feel right.
What would be the way to accomplish this?
Edit: I feel that my question is a bit unclear. What Qt mechanism should be utilized if one wants to replace a QWidget with a specialized (inherited) version of the original widget? I'm looking for the Qt way to do this.
Answer: You need to add a widget dynamically to the widget you have drawn in the designer.
// in UI file
QWidget *wdgFromForm;

// in cpp file
QHBoxLayout *const layout(new QHBoxLayout(wdgFromForm));
SpecializedWidget * specializedWidget( new SpecializedWidget(wdgFromForm));
layout->addWidget(specializedWidget);

Comment: Thanks, this works. Is this the way it is done in Qt? I find it a bit odd that instead of replacing an already existing widget that is float in an existing layout, I have to add a layout to this widget and put the new widget in this new layout.
Comment: You could setup the entire form dynamically, but I find it easier to setup the form with the designer an use a placeholder for the context dependent widgets.
Comment: Exactly this was my intention. As I said, I just find it odd that I have to add a layout and then add a new widget instead of just replacing the placeholder. But anyway, I like it more than the QStackedWidget approach. Thanks.
Answer: Maybe the problem is not that the widget is not suitable, but simply that you're not giving time for the widget to update.
You could take a look at processEvents:
http://web.mit.edu/qt-dynamic/www/qapplication.html#details
Comment: I'm sorry, I don't understand what you mean. At the moment there are no event in place (I didn't put any in), just a click of a button in an example app. The new widget is shown after a call of myWidget->show(), but it's not display where the original widget used to be. Instead it's in the left upper corner. Did I get something wrong?
Comment: A click in a button is an event. Any operation the user does is translated to an event. If you are inside a loop in one of your application event handlers, the Qt library will not be able to update the status of the GUI. That's when processEvents() is useful.
Answer: This looks like a use case for the factory pattern.
#include <map>
#include <string>
struct Whatever;
struct QWidget;
typedef QWidget*(*WidgetCtor)(Whatever*);
typedef std::map<std::string, WidgetCtor> FileFactory;

QWidget* createFoo(Whatever*);
QWidget* createBar(Whatever*);
QWidget* createDefault(Whatever*);

void factory_init(FileFactory& ff)
{
    ff["foo"] = createFoo;
    ff["bar"] = createBar;
}

QWidget* create_by_factory(const FileFactory& ff, const std::string t, Whatever* w)
{
    FileFactory::const_iterator it(ff.find(t));
    if(it != ff.end())
    {
        return it->second(w);
    }
    else
    {
        return createDefault(w);
    }
}

Comment: Thanks for your reply. A factory would be helpful if I have to generate those objects more often. But in this case a factory seems a bit of an overkill.
Answer: Adding widgets dynamically to a layout is not a problem.
You might need to call updateGeometry on the containing widget though.
Comment: UpdateGeometry didn't work. It's not quiet adding a widget, it's more replacing an existing widget in a layout with another widget.
Comment: replacing should be the same as adding a new widget. did you call updateGeometry() on the correct widget, i.e. the one with the layout where you inserted the new widget?


Transfer files from flash,iphone,android device to LAMP server

Question: I have a LAMP server that needs to accept files from flash applications that run locally on client's computer (ie, they open the swf file from their windows explorer), iphone apps and android apps.
My understanding is that I need to set up a webservice on my LAMP server to allow for this.  Basically I create a PHP file that's accessible via http://mysite.com/upload.php, and it accepts _POST data.  The POST data will contain the file the client application sends me.
Is this the correct approach?
Answer: I successfully implemented the approach above.  I posted a queston about Curl equivalent for Android here.
What is android's equivalent for this curl operation?
So now other client devices can do the same.


Get 1st number between every 10 numbers

Question: I have 120 groups, each group has 10 numbers.
Suppose if 24 is in the loop I want to get in which group it is? Means if 24 is there then I want to get 21 because 24 comes between 21-30.
Give me logic using if or for loop whatever.
Here is my code:
for (int i = 0; i < 120; i++)
{
    if (i % 10 == 0)
    {
        Response.Write(i.ToString());
    }
}

Comment: Your question is pretty unclear. Are *all* the groups 1-10, 11-20, 21-30 etc? It would really help if you'd give a short but complete example program.
Comment: @DipaliWagh:- Please edit your question and update your code over there. Dont paste code in comments
Comment: And is your input guaranteed to be in one of the groups? If so, it's just `(((input - 1) / 10) * 10) + 1`
Comment: @JonSkeet whatever you explained is correct. Yes all the groups are 1-10,11-20,21-30 like this.
Comment: Have you tried to make it?
Comment: I tried this one: for(int i=0; i<120;i++){if(i%10==0){reponse.write(i.tostring();)}}.   But it is not helping
Answer: Something like that?
static int starter(int n)
{
    var x = n % 10;
    return n - x + 1;
}
static void Main(string[] args)
{
    Console.WriteLine(starter(24));
    Console.ReadLine();
}

Answer: I do not know how in pack the numbers in groups, so I'm giving you a solution and you have to change it for your own needs.
Suppose the number are packed in an ArrayList and the groups are then packed together in another ArrayList. This way you would have an ArrayList of several ArrayList with number. So my solution would be:
private int FindNumber(int number)
{
    int count = 0;
    int gindex = -1;
    foreach(group g in groups)
    {
        if(g.contains(number))
        gindex = count;
        count++;
    }
    ArrayList aux = groups[gindex];
    return aux[0];
 }

Edit after reading Jester response. I guess you would like the first number of the 10 groups so
private int FindNumber(int number)
{
    int ret
    foreach(group g in groups)
    {
        if(g.contains(number))
        {
            var x = number % 10;
            ret = number - x + 1;
        }
    }

    return ret;
 }

Jester response is right in the main idea but that doesn't work if you don't have the number in the group.

Get 1st number between every 10 numbers


How can I format text to Title Case from within a transformation in Kentico?

Question: Within a transformation in Kentico, I am trying to format text to title case. I have discovered CMS.Helpers.TextHelper.ToTitleCase() in some Kentico documentation but, I don't believe that is available from within a transformation. I was also hoping I could get access to a TextInfo.ToTitleCase() via one of the CultureInfo objects in Kentico (like CMS.Localization.LocalizationContext.CurrentCulture.TextInfo.ToTitleCase()) but that doesn't seem to be available within the transformation either.
Any advice would really be appreciated.
[This is in a Kentico 11 website]
Answer: This depends on what type of transformation you are using.  If you're using an ASCX transformation type, you can use the following:
<code>CMS.Helpers.TextHelper.ToTitleCase(Eval<string>("ColumnName"))
</code>
If you're using a Text/HTML transformation type you would have to create a custom macro method to call that TextHelper method and return the title case value you're expecting.
Comment: this was a tremendous help. Thank you. It has been a while since I have worked with transformations.


Best breathing strategy for long distance butterfly

Question: I swim butterfly pretty often & in optimal conditions I can swim 11 strokes without breathing or 44 strokes breathing every stroke before I get so tired I can't swim anymore. Specifically when breathing every stroke for 44 strokes I almost feel like I'm breathing too much. However, if I switch to breathing every 2 strokes after 44 strokes I am usually too tired to continue swimming.
I'm curious if anyone has advice for optimizing long distance butterfly breathing strategies.
Comment: Not sure I'd say 44 strokes is 'long distance'. Anyway, if Michael Phelps decided to breathe every stroke whether doing the 100 or 200 fly, I'd say go for every stroke.
Answer: Swimmer here.
I'd say go for what you're comfortable with if you're not competing. There isn't really any optimal breathing strategy if you're just swimming leisurely.
If you want to not breathe for XXX number of strokes, the only way is to train holding your breath while swimming butterfly. Most pro swimmers in the 200 fly probably breathe every alternate stroke or every stroke. It's pretty hard to hold your breath and do butterfly.
Answer: Michael Phelps was a world record setting butterfly swimmer and he would breathe every stroke.  He breathed shallowly but frequently (more instructions in the link or just watch him on YouTube or similar).
Another option would be to simply skip a breath every time you feel you don't need one.  I.e. rather than breathe every stroke or every two strokes consistently, breathe intermittently.  If you feel short of breath, then breathe.  If you don't, skip that stroke (and definitely breathe on the next stroke).  This might end up with breathing two strokes and then skipping one.  But what I'm saying is that rather than breathe every stroke whether you need it or not, breathe when you feel you need it.  If you feel out of breath at the end of your forty-four strokes, then breathe more next time.  If you feel like you have too much breath, breathe less often.
Phelps' insight was that breathing shallowly every stroke gave him plenty of breath without slowing him down too much.  I would encourage you to try it.  Lift your head less and take shorter breaths.  If that doesn't work for you, try being more intermittent.  Don't breathe every stroke but don't skip every other stroke either.  There's no score for consistent breathing in swimming.  Work out something that feels right to you, not that matches some arbitrary metric.


Set name in state along with its index in an iteration

Question: I have an iteration code. I'm using react along with antd select.
<code>      {this.state.count.map((d, i) => (
          <Select
            placeholder={`Question #${i + 1}`}
            style={{ width: '100%' }}
             onChange={(e) => this.setState({securityQuestions{i}:e})} // here I have issue.. need to set name with index
             showSearch
             optionFilterProp="children"
             filterOption={(input, option) =>
    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
         filterSort={(optionA, optionB) =>
    optionA.children.toLowerCase().localeCompare(optionB.children.toLowerCase())
                                                                    }>
{this.state.securityQuestions && this.state.securityQuestions.map((d) => <Select.Option value={d.id}>{d.securityQuestion}</Select.Option>)}
                 </Select>
         ))}
</code>
My code is like this. As i mentioned in code I have issue in 'onchange'. I want to set name along with its index. Can anyone help me?
Answer: If I understand correctly, your goal is to end up with something like this?:
<code>{securityQuestions1:e}
</code>
In that case you can use bracket notation to reference the property with a value, and then your value is just an interpolated string (template literal):
<code>{[`securityQuestions${i}`]:e}
</code>
Or if you prefer a concatenated string:
<code>{['securityQuestions' + i]:e}
</code>


Evitar registros em duplicidade em uma determinada coluna MySQL

Question: Tenho um sistema de leilão onde vários usuários podem dar lances, mas estou com um problema quando ocorrem lances ao mesmo tempo, pois são inseridos no banco de dados com o mesmo valor na coluna bidding_price, ex:

0.02
  0.02
  0.02

Eu montei um select que retorna todos os lances com valores iguais (duplicidade) para um determinado leilão:
SELECT bidding_price, count(*)
    FROM bid_account
    WHERE auction_id = 1335
    GROUP BY bidding_price
    Having Count(*) > 1

Nesse caso ele vai retornar as duplicidades para o leilão com ID 1335.
A estrutura da tabela bid_account esta dessa forma:
id | int(255) - índice - primária - AUTO INCREMENT
auction_id | int(11) - id do leilão
bidding_price | float(20,2) - valor do lance, ex. 0.02

Eu cheguei a criar um DELETE que consegue apagar as duplicidades, porém seria injusto com algum usuário, ter o lance apagado por um erro do sistema. Segue:
DELETE ba
    FROM bid_account ba JOIN
         (SELECT ba2.auction_id, ba2.bidding_price, MAX(ba2.id) as max_id
          FROM bid_account ba2
          WHERE ba2.auction_id = ?
          GROUP BY ba2.auction_id, ba2.bidding_price
         ) ba2
         ON ba2.auction_id = ba.auction_id AND
            ba2.bidding_price = ba.bidding_price AND
            ba2.max_id > ba.id
WHERE ba.auction_id = ?;

Esta com ? ali por que ele recebe o valor por um parâmetro.
Alguém tem alguma ideia de como posso resolver este problema, evitando que seja inserido o valor igual na tabela bidding_price, porém para um determinado leilão identificado pela coluna auction_id?
Na tabela existem vários valores iguais em bidding_price, porém o que não pode ocorrer é valores iguais para o mesmo leilão, ou seja, para o mesmo valor em auction_id.
Eu pensei em criar um update, que verifica antes se existem duplicidades, se houver ele atualiza os valores inserindo 1 centavo a mais em cada duplicidade. Mas acho que iria da problema quando houve 3 lances ao mesmo tempo.
Esse comando SQL será executado em node, e irá rodar em um cron a cada segundo, ou seja, a todo momento ele estará realizando essa verificação. Se houver um lance duplicado agora, no próximo segundo ele vai identificar e corrigir.
O sistema de lances funciona em conjunto com um cronômetro regressivo de 15 segundos, sempre que alguém realiza um lance o cronômetro volta a sua contagem inicial de 15s.
Comment: Basta criar um índice UNIQUE e ver se deu falha no insert, e essa idéia de cron a cada segundo é furada. Melhor trabalhar com um código que suporte paralelismo e eventos/sinais.
Comment: Índice único e "transactions" rápidas , tratando o erro de duplicidade.
Comment: Infelizmente surgiu um problema, ele até iria funcionar mas o que ocorre é o seguinte: cada lance realizado ele cria uma nova linha que contém o valor e a ID do leilão. Se eu colocar UNIQUE para as duas colunas, como que ele vai inserir a próxima linha com a mesma ID do leilão? E tem casos onde haverá leilões diferentes com o mesmo valor. Ai o UNIQUE não iria funcionar para nenhuma das colunas. Ou existe algo que pode ser feito para contornar essa situação?
Answer: Basta que você use o UNIQUE, tal forma que:
ALTER TABLE tabela ADD UNIQUE INDEX(`bidding_price`, `auction_id`);

Dessa forma o par de bidding_price e auction_id são únicos, então se for {0, 0} não poderá existir outro igual, mas ainda poderá existir {0, 1} ou {1, 0}. Então para cada auction_id apenas irá existir um único bidding_price.
Você pode testar isso no SQLFiddle.
Comment: @Inkeliz...E como faço para ele retornar algum alert para o cliente se já houver algum lance com o mesmo valor? E se acontecer do lance ser realizado exatamente no mesmo instante o que ocorre, ele não registra nenhum?
Comment: Consegui aqui, valew, não achei que algo tão simples fosse resolver o problema, parabéns!
Comment: Infelizmente surgiu um problema, ele até iria funcionar mas o que ocorre é o seguinte: cada lance realizado ele cria uma nova linha que contém o valor e a ID do leilão. Se eu colocar `UNIQUE` para as duas colunas, como que ele vai inserir a próxima linha com a mesma ID do leilão? E tem casos onde haverá leilões diferentes com o mesmo valor. Ai o `UNIQUE` não iria funcionar para nenhuma das colunas. Ou existe algo que pode ser feito para contornar essa situação?
Comment: O `UNIQUE` é aplicado ao par, não para cada um separado, como expliquei na resposta. O `UNIQUE` irá prevenir uma inserção onde os dois valores `bidding_price` e `auction_id` são iguais. Então, se eu posso *dar um lance* de 1 para A e 1 para B e também 2 para A, mas eu não posso dar *um novo lance* de 1 para A, porque duplica. Isso está explicado em https://dev.mysql.com/doc/refman/5.7/en/create-table.html, você pode fazer um teste simplesmente dando dois `INSERT teste VALUES (1,1), (1,0), (0,1)`, todos vão funcionar, mas se incluir um novo (1,1) irá falhar...
Comment: Você pode testar isso em http://www.sqlfiddle.com/#!9/96ea19/1.
Comment: Nossa, show de bola heim, funcionou mesmo! Me tira mais uma dúvida, como seria para deixar essas tabelas configuradas dessa forma no `CREATE`? Seria dessa forma? `PRIMARY KEY `id` (`id`), UNIQUE KEY `bidding_price` (`bidding_price`,`auction_id`)`
Answer: Você pode verificar no SQL se existe algum lance com o mesmo valor usando CASE:
CASE
    WHEN ? IN (SELECT bidding_price FROM bid_account WHERE auction_id = ?)
    THEN INSERT ...

Comment: O problema é que o lance é inserido tudo ao mesmo tempo, não tem como verificar antes se já existe algum registro.
Comment: O problema então é a linguagem escolhida, talvez o node não seja a linguagem ideal para o que deseja fazer. Da uma olhada [nesse vídeo](https://www.youtube.com/watch?v=KtDwdoxQL4A), é possível mudar o tamanho do pool de thread para 1, mas a idéia do node é justamente fazer mais de uma coisa ao mesmo tempo
Answer: O que interessa é quem dá o commit primeiro. E isso nunca se dá ao mesmo tempo, diferença de milissegundos. O que acontece é que precisas aumenta o cache de armazenamento de insert do mysql para criar uma fila. Depois disso, cada nova requisição deveria fazer reload na página do cliente ou ao menos jogar os dados atualizados com o timestamp num arquivo json e ir modificando a div (ou outra tag qualquer) dinamicamente e só a parte do preço. Podes fazer isso com uma api rest ou ajax.


Reescrever números de no máximo 2 dígitos do input para o output

Question: Preciso reescrever números de no máximo 2 dígitos do input para o output, parando de processar o input depois de ler o número 42.
Input:

1
2
88
42
99

Output:

1
2
88

Meu código está assim, não consigo entender o que está errado:
#include <stdio.h>
#include <stdlib.h>

int main(){
    int a=100;
    int *n=(int*)malloc(100*sizeof(int));

    for(int i=0;i<100;i++){
        scanf("%d", &n[i]);
        if(n[i]==42){
            a=i++;
            break;
        }
    }

    for(int i=0;i<a;i++){
        printf("%d\n", n[i]);
    }

    return 0;
}

Comment: qual o erro? qual a saída quando você executa?
Comment: Também não vejo nada de errado, a única coisa que reparei é que ele permite a impressão de números com mais de 2 dígitos, exemplo 999
Answer: parando de ler depois de ler o número 42, entao a sua repeticao nao deve ter um limite for(int i=0;i<100;i++){ e sim um laço infinito,
deveria ser algo como : for(int i=0;i>-1;i++){
e o seu codigo iria ficar assim
#include <stdio.h>
#include <stdlib.h>

int main(){
    int a=0;
    int *n=(int*)malloc(100*sizeof(int));

    for(int i=0;i>-1;i++){
        scanf("%d", &n[i]);
        if(n[i]==42){
            a=i++;
            break;
        }
    }

    for(int i=0;i<a;i++){
        printf("%d\n", n[i]);
    }

    return 0;
}

se esse for o erro.
Comment: agora deu certo!!! muito obrigado


Jordan form of matrices

Question: So my professor gave me this question:
$A=\begin{pmatrix}
  0 & 2 & 5\\
  -5 & 5 & 10\\
   2 & -2 & -4 \\
  \end{pmatrix}$
I had to calculate $\forall 0 < i$ $kerA^{i}$ and $ImA^{i}$
So after calculating I reached those results:
$kerA$={$\begin{pmatrix}
  1 \\
  5 \\
   -2  \\
  \end{pmatrix}$}
and $\forall 1<i$
$kerA^{i}$={$\begin{pmatrix}
  1 \\
  -1 \\
  0  \\
  \end{pmatrix}$,$\begin{pmatrix}
  -3 \\
  0 \\
  1  \\
  \end{pmatrix}$}
regarding the image it is just the span of the columns of $A^{i}$
Then he asked us to calculate $\forall 0 < i$ $ker(A-I)^{i}$ and $Im(A-I)^{i}$
So after calculating I reached those results:
$\forall 0<i$
$kerA^{i}=$ {$\begin{pmatrix}
  0 \\
  -5/2 \\
   1  \\
  \end{pmatrix}$}
regarding the image it is just the span of the columns of $(A-I)^{i}$
Then he asked us to show the Jordan form of $A$
How can I conclude that from what I proved. As far as I know the diagonal of jordan form contains the eigenvalues of $A$ (each eigenvalue repeat in the diagonal as the number of Algebraic multiplicities of the eigenvale ) and nothing more but how can I conclude from what I proved the eigenvalues of $A$.
Any help would be appreciated
Thanks in advanced !!
Comment: There seems to be a typo. Judging from your computed kernel it should be $-4$ in the matrix.
Comment: @JulianKuelshammer fixed, you were right !!
Answer: For a general method to compute the normal form in such case:
For each eigenvector, start with the power such that the kernel of $A-\lambda I$ does not change anymore (call that $m_\lambda$. Take a basis of a complement of $\operatorname{ker}(A-\lambda I)^{m_\lambda-1}$ in $\operatorname{ker}(A-\lambda I)^{m_\lambda}$. Now apply $(A-\lambda I)$ to that basis. The elements will lie in $\operatorname{ker}(A-\lambda I)^{m_\lambda -1}$. Now take a basis of the complement of the span of these vectors and $\operatorname{ker}(A-\lambda I)^{m_\lambda-2}$ in that space. Continue inductively. You will then get a basis for your whole space. If you change your matrix to that basis, you will get a matrix in Jordan normal form.
In your example (assuming your calculations are correct) take for example $b_0=(1,-1,0)^T$ and $Ab_0$ (for the eigenvalue $0$ and $b_1=(0,-5/2,1)^T$ for the eigenvalue $1$. Then your matrix represented in Jordan normal form will look like
$$\begin{pmatrix}0&1&0\\0&0&0\\0&0&1\end{pmatrix},$$
the first column corresponding to $Ab_0$, the second to $b_0$ and the third to $b_1$

Jordan form of matrices


Boost mutexes and semaphores on disk or in memory?

Question: I would like to know if Boost mutexes and semaphores store any information on the disk, or if there is an option to avoid that (e.g. storing the data in a memory block).
I care about this detail both for performance reasons, and also to avoid throwing my SSD away too soon...
Thank you.
Comment: Why on earth would an OS synchronization object hit the disk?
Comment: T.E.D.: I just wanted to be sure it does not.
Answer: They're purely in memory. The only way anything would end up on disk would be if that particular memory got written out to the paging file. If that does happen, however, it's not going to do any more to your SSD than anything else being written to the paging file.
Answer: Nope. Boost mutexes that require file storage use memory-mapped files.  But anything in main memory might possibly paged out to disk, unless you do some operating-system dependent action to prevent it.
http://www.boost.org/doc/libs/1_37_0/doc/html/interprocess/synchronization_mechanisms.html


Is there a way to add a title or a caption to the drawing using graph_tool

Question: At least some workaround would be appreciated. I am trying to save the figures as pdfs and then use it with latex as an animation. If there is a way to automatically add captions that will be really helpful as I am going to have about 50-60 figures.
Answer: I don't know if it is possible natively, but you can put the graph drawn by graph-tool in a matplotlib Figure() using the mplfig option in graph_draw(). With that you have access to all the flexibility of matplotlib around your graph.


Scoring metric for regression that does not weight outliers heavily

Question: I'm using the root mean squared error (RMSE) as a metric for tuning the parameters of my model in a regression problem through cross-validation. However, I'm not so much interested that all predictions are good, I want that about 20% or 40% percent of my predictions to be "spot-on" and don't care if the other 80% or 60% are garbage.
What metric would be best for this?
Comment: Look at the entire distribution of residuals. This should be directly available in any decent software after regression. No omnibus statistic can be anything more than a particular summary. Unfortunately, you should care if 60% or 80% of your predictions are garbage; that may mean that you are fitting an inappropriate model and that may mean that the model is not to be trusted any way.
Comment: why would you care only about 20% of your predictions?
Comment: I don't think it's fair to criticize OP for asking this question. We don't know the specific problem they're working on. We can assume they've done their due diligence and offer solutions based on the question they asked, not the question we wished they asked.
Answer: You could try the Huber loss function. It penalizes close predictions more than predictions that are very wrong.
Using the usual notation for Huber Less, define $a_i$ as your residual, $Y_i - \hat{Y}_{i}$. Huber loss is defined as
$$ L_\delta(a) = \begin{cases}
\frac{1}{2} a^2,  & \text{for $|a| < \delta$} \\
\delta * (|a| - \frac{1}{2}\delta), & \text{for $|a| \geq \delta$}
\end{cases}$$
You define a threshold of "closeness", $\delta$. If your prediction is within this threshold, your loss is quadratic. If your prediction is outside of this threshold, your loss is linear. This let's the model prioritize fitting points that your model is close to getting correct and de-prioritize outliers. If you want to de-emphasize outliers even further, you could increase the polynomial degree in the case when $|a| < \delta$ and/or decrease the polynomial degree when $|a| \geq \delta$.
In R, you can calculate Huber Loss with the yardstick package. I'm not aware of any out-of-the-box implementations of Huber loss as a standalone metric in Python. Sklearn let's you fit linear regression with  Huber Loss. but Huber Loss isn't one of sklearn's scoring metric.
Answer: Answering my own question here, it seems that the root mean squared log error (RMSLE) is a suitable metric, see this CV post
Comment: This can't be a general answer without a rationale.


Webform send multiple email

Question: I have created a webform. There is one field "Send invitation to your friends" . In this field user can enter their friends email ids (Comma seperated) For example email@example.com,firstname.lastname@example.com,firstname.lastname@example.com etc. I want to send a common email "Welcome and join us" to all these people. Can anyone help me, how can I proceed?
Comment: I am not fully sure how to achieve this. It might be possible with the use of tokens and/or rules, but I am sure someone else can chime in. I don't want to assume the full scope of what the webform is for, but if it's just inviting people to the site, have you considered just using http://drupal.org/project/invite ?
Answer: You can send custom emails to addresses submitted in the form. When creating the form, you have to select 'email' for the field type. Once you've done that, go to the 'Emails' tab in the webform, and add a new email using the 'Component value' menu; you should see your Email field in there (you can add as many of these as you want). This sets it up to send an email to the email address entered in the form, in your case the friends' email addresses.
From there you can customise the email options.
Edit: Whoops, this answer is for Drupal 7 specifically, but (if I remember correctly) the option exists in Drupal 6 as well.
Comment: thanks, i didn't even noticed this component type and i was about to create a function to implement this fonctionnality :)

Webform send multiple email


PROJETO SCRIPT SQL

Question: Boa tarde, tenho esse projeto como um trabalho da faculdade, gostaria que alguém pudesse me dar uma luz, dizendo se tem algo errado, ou algo que eu possa melhorar.
Segue o print do que é pedido, e o meu script feito.
Comment: Wííl TR, O SQLite tem uma particularidade por aceitar campos sem definições de tipo. Tome cuidado com isso. Como a resposta do adrianosmateus abaixo, mostra esse caso. O que pode fazer, é executar seu script em outros bancos (pode-se usar o [sqlfiddle](http://www.sqlfiddle.com/), ou outro), assim te ajudará a captar possíveis inconsistências.
Answer: Vamos a algumas coisas que observei.
O id da sua tabela situacao está sem tipo, então mude a declaração desse id para id_situacao INTEGER NOT NULL.
A coluna id_socio na tabela carro é de um tipo diferente do id_socio na tabela socio, e isso causará erros. A solução é manter id_socio na tabela carro também como INTEGER
Na sua FK da tabela CARRO, há um pequeno problema de lógica, onde a sua chave estrangeira está sendo montada como CONSTRAINT  carro_FK FOREIGN KEY (id_socio, id_marca) REFERENCES socio (id_socio, id_marca) sendo que, dessa forma, o sistema tentará vincular o id_marca da sua tabela carro com id_marca na tabela socio, mas como socio(id_marca) não existe, não vai funcionar. O certo, para funcionar de acordo com seu modelo, essa fk deveria ser montada assim:
CONSTRAINT  carro_socio_FK FOREIGN KEY (id_socio) REFERENCES socio (id_socio),
CONSTRAINT  carro_marca_FK FOREIGN KEY (id_marca) REFERENCES marca (id_marca)

Dessa forma, sua tabela fica até mais organizada, com uma constraint representando cada chave separadamente.
No fim das contas, com as alterações que eu citei, seu script ficaria assim:
CREATE TABLE situacao (
id_situacao INTEGER NOT NULL,
situacao VARCHAR(10) NOT NULL,
CONSTRAINT situacao_id_situacao_PK PRIMARY KEY (id_situacao)
);

CREATE TABLE socio (
id_socio  INTEGER PRIMARY KEY AUTOINCREMENT,
nome         VARCHAR(256) NOT NULL,
cpf          CHAR(11) NOT NULL,
email        VARCHAR(256),
id_situacao  INTEGER,
CONSTRAINT socio_cpf_UN UNIQUE(cpf),
CONSTRAINT socio_id_situacao_FK FOREIGN KEY (id_situacao) REFERENCES situacao (id_situacao)
);

CREATE TABLE marca (
id_marca     INTEGER  PRIMARY KEY AUTOINCREMENT,
marca        VARCHAR (128) NOT NULL
);

CREATE TABLE carro (
id_carro    INTEGER PRIMARY KEY AUTOINCREMENT,
modelo      VARCHAR(128) NOT NULL,
cor         VARCHAR(64),
placa       VARCHAR(10) NOT NULL,
id_socio    INTEGER,
id_marca    INTEGER,
CONSTRAINT  carro_placa_UN UNIQUE (placa),
CONSTRAINT  carro_socio_FK FOREIGN KEY (id_socio) REFERENCES socio
(id_socio),
CONSTRAINT  carro_marca_FK FOREIGN KEY (id_marca) REFERENCES marca
(id_marca)
);

Comment: Obrigado, provavelmente seria reprovado por causa desses erros, acho que sua correção ficou perfeitamente funcional ao que pede o enunciado
Comment: Que bom que ajudei. Por favor, marque minha resposta como correta se ela realmente te serviu e boa sorte.
Comment: sempre o mesmo tipo da chave referenciada, no caso, INTEGER
Comment: uma chave estrangeira tem que referenciar a um campo do mesmo tipo
Comment: teria que ser INTEGER então né, desculpa kk estou no começo do aprendizado
Comment: sim, teria. Se tiver mais dúvidas, por favor abra um novo tópico pra não prolongarmos muito a sessão de comentário.

PROJETO SCRIPT SQL


Convenient Way to Create Offline/Disconnected data from QtSQL?

Question: I'm trying to figure out how to grab 2D data from a database and stuff it into widgets. This data is quasistatic -- once I grab it there is no need to stay connected to the database. Further, if I leave the connection open, but it times out, it can crash my app. I'd like to know if there is a some kind of offline data container or functionality in QtSql that I am not aware of.
As near as I can figure, Qt only offers QsqlTableModel and QAbstractTableModel as containers for data. I have not found any methods for keeping data in QsqlTableModel if the connection is dropped. And QAbstractTableModel is not even usable by itself; you have to subclass it. It is likely that I will end up going the subclassing route if I cannot find a more simple or elegant solution. There is a subclassing example here.
By way of code samples, the code below fills two combo boxes from a SQL Server database. When the second button is clicked and the second combobox is filled, the first combobox breaks and the application breaks. I'm hoping there is a simple way to grab the data and keep it in a local container that is disconnected from the database.
from PyQt5.QtWidgets import (QApplication, QMainWindow, QComboBox, QPushButton,
                             QTableView, QTableView)
from PyQt5.QtSql import (QSqlQuery, QSqlQueryModel, QSqlDatabase)
import sys

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__()

        self.setGeometry(300, 300, 600, 350)

        self.db = QSqlDatabase.addDatabase("QODBC", 'MyDB')
        self.db.setDatabaseName('Driver={SQL Server};Server=MyServer;Database=MyDB;Trusted_Connection=Yes;')

        self.cb1 = QComboBox(parent=self)
        self.cb1.setGeometry(25,25, 250, 50)

        self.cb2 = QComboBox(parent=self)
        self.cb2.setGeometry(300,25, 250, 50)

        self.button1 = QPushButton('^^^ Fill Table 1 ^^^', parent=self)
        self.button1.setGeometry(55,290, 200, 30)
        self.button1.clicked.connect(self.fillTable1)

        self.button2 = QPushButton('^^^ Fill Table 2 ^^^', parent=self)
        self.button2.setGeometry(320, 290, 200, 30)
        self.button2.clicked.connect(self.fillTable2)

    def fillTable1(self):
        print('self.db.open() ', self.db.open())
        sql = 'select * from aaa.car limit 10'
        query = QSqlQuery(self.db)
        print("query.exec_(sql) ", query.exec_(sql))

        self.t1model = QSqlQueryModel(parent = self)
        self.t1model.setQuery(query)
        self.cb1.setModel(self.t1model)
        self.cb1.setModelColumn(0)
        self.cb1.setView(QTableView(self.cb1))

    def fillTable2(self):
        print('self.db.open() ', self.db.open())
        sql = 'select * from aaa.car limit 10'
        query = QSqlQuery(self.db)
        print("query.exec_(sql) ", query.exec_(sql))
        self.t2model = QSqlQueryModel(parent = self)
        self.t2model.setQuery(query)
        self.cb2.setModel(self.t2model)
        self.cb2.setModelColumn(0)
        self.cb2.setView(QTableView(self.cb2))

app = QApplication(sys.argv)
main = MainWindow(None)
main.show()
sys.exit(app.exec_())

Comment: Why don't you create a copy of the SQL server table in a sqlite, and so you use the sqlite?
Comment: Ugh. That's one solution, but it has a lot of overhead. I would have to CREATE new tables for every query I want to run. It might be that subclassing QAbstractTableModel is the least amount of work/overhead.
Comment: My logic is: create a mirror copy of the tables and update it whenever necessary (for example if the original table changes)
Answer: Here is a barebones subclassed QAbstractTableModel. You feed it a QSqlQuery in the fillFromQuery method, and it extracts the data from the query result. As written, it does not play nice with QCompleter. Edited. Now works with QCompleter
from PyQt5.QtCore import Qt, QAbstractTableModel
from PyQt5.QtSql import QSqlQueryModel

class OfflineTableModel(QAbstractTableModel):
def __init__(self, parent, inputQuery=None):
    QAbstractTableModel.__init__(self, parent)
    self.mylist = []
    self.header = []

    if inputQuery is not None:
        self.fillFromQuery(inputQuery)

def fillFromQuery(self, inputQuery):
    # don't know how to get row/column count except from a QSqlQueryModel
    bogusModel = QSqlQueryModel()
    bogusModel.setQuery(inputQuery)
    rowCount = bogusModel.rowCount()
    colCount = bogusModel.columnCount()

    inputQuery.first()

    self.header = []
    for col in range(colCount):
        self.header.append(inputQuery.record().fieldName(col))

    self.mylist = []
    for row in range(rowCount):
        innerList = []
        for col in range(colCount):
            innerList.append(inputQuery.value(col))
        self.mylist.append(tuple(innerList))
        inputQuery.next()

def rowCount(self, parent=None):
    return len(self.mylist)
def columnCount(self, parent=None):
    return len(self.mylist[0])
def data(self, index, role):
    if not index.isValid():
        return None
    elif role not in (Qt.EditRole, Qt.DisplayRole):
        return None
    return self.mylist[index.row()][index.column()]
def dataRowCol(self, row, col):
    return self.mylist[row][col]
def headerData(self, col, orientation, role):
    if orientation == Qt.Horizontal and role not in (Qt.EditRole, Qt.DisplayRole):
        return self.header[col]
    return None

The advantage of this technique over making a local Sqlite database is that this OfflineTableModel will provide offline data to a view widget from any SQL SELECT query.
When this OfflineTable model is applied to the OP, the original QSqlDatabase (db) can be open and closed multiple times without breaking the widgets that are already loaded with offline data. 41 lines of code. Seems like there should be an easier way to accomplish the same thing. . .


Detecting consecutive integers and collapse to string

Question: Disclaimer: A very similar question was already asked in a Python context here. This is about C#.
I have an enumeration containing integers such as:
[1, 2, 3, 4, 7, 8, 10, 11, 12, 13, 14]

I'd like to obtain a string putting out the ranges of consecutive integers:
1-4, 7-8, 10-14

I came up with:
public static void Main()
{
    System.Diagnostics.Debug.WriteLine(FindConsecutiveNumbers(new int[] { 1,2, 7,8,9, 12, 15, 20,21 }));
}

private static string FindConsecutiveNumbers(IEnumerable<int> numbers)
{
    var sb = new StringBuilder();
    int? start = null;
    int? lastNumber = null;
    const string s = ", ";
    const string c = "-";

    var numbersPlusIntMax = numbers.ToList();
    numbersPlusIntMax.Add(int.MaxValue);
    foreach (var number in numbersPlusIntMax)
    {
        var isConsecutive = lastNumber != null && lastNumber + 1 == number;
        if (!isConsecutive)
        {
            if (start != null)
            {
                if (sb.Length > 0) { sb.Append(s); }
                if (start == lastNumber)
                {
                    sb.Append(start); ;
                }
                else
                {
                    sb.Append(start + c + lastNumber); ;
                }
            }

            start = number;
        }

        lastNumber = number;
    }

    return sb.ToString();
}

This algorithm works for ordered input. Is there a built-in/LINQ/shorter C# way of doing this?
Answer: int[] numbers = { 1, 2, 3, 4, 7, 8, 10, 11, 12, 13, 14 };

return string.Join(", ",
    numbers
        .Select((n, i) => new { value = n, group = n - i })
        .GroupBy(o => o.group)
        .Select(g => g.First().value + "-" + g.Last().value)
);

Comment: `.Select(g => g.First().value == g.Last().value ? $"{g.First().value}" : $"{g.First().value}-{g.Last().value}")` in order to stick to required format
Answer: I suggest decomposition: Let's split initial routine into logics:
private static IEnumerable<(int left, int right)> Consecutive(IEnumerable<int> numbers) {
  int start = -1;
  int stop = -2;

  foreach (var item in numbers) // numbers.OrderBy(x => x) to sort numbers
    if (item == stop + 1)
      stop = item;
    else {
      if (stop >= start)
        yield return (start, stop);

      start = item;
      stop = item;
    }

  if (stop >= start)
    yield return (start, stop);
}

and representation
private static string FindConsecutiveNumbers(IEnumerable<int> numbers) =>
  string.Join(", ", Consecutive(numbers)
    .Select(item => item.left == item.right
       ? $"{item.left}"
       : $"{item.left}-{item.right}"));

Then business as usual:
public static void Main()
{
    // 1-2, 7-9, 12, 15, 20-21
    System.Diagnostics.Debug.WriteLine(FindConsecutiveNumbers(new int[] {
      1, 2,
      7, 8, 9,
      12,
      15,
      20, 21 }
    ));
}

Comment: Nice usage of [Tuple types](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples)!
Answer: If we could get the numbers in a List instead of an enumeration then we do not need to access all the numbers. The previous answers are have a time complexity of O(n) where n is the size of the array. Whereas if we have a list, this problem could be solved in O(klogn) where k is the number of groups.
Basically you could use a slightly modified binary search to find the end point of a group which could be done in O(logn) And then from end+1, you could do the same for the next group.
Comment: A binary search. Also a nice idea. But if I understood the approach correctly, this will only prove advantages if there are few groups.
Comment: That's right. If it is expected that every group will have very few elements (which means there are lots of groups) than there is no point using this approach.
Comment: @JackMiller, we could also modify the binary search in a way that at the worst case it will be O(n) instead of O(nlogn) in the case of k = n. Therefore the complexity will be the better of O(klogn) and O(n).


Caliburn.Micro: How to bind a function to a context menu item in the RowDetailsTemplate of a DataGrid?

Question: I have a datagrid of Items that includes a datagrid of SubItems for the row details. There is a context menu for the main "Items" datagrid with functions to add or remove items, this is working fine. There is also a context menu for the row details datagrid "SubItems" with similar functions that I cannot get to bind properly. If executed i get the following exception "System.Exception: 'No target found for method AddSubItem.'"
I have desperately tried many other solutions that were suggested on other posts but nothing has worked so far. I appreciate any insight. Below is my test code.
ShellViewModel:
using System;
using Caliburn.Micro;
using ContextMenuTest.Models;

namespace ContextMenuTest.ViewModels
{
    public class ShellViewModel : Screen
    {
        public static Random rnd = new Random();
        private BindableCollection<ItemModel> items = new BindableCollection<ItemModel>();
        public BindableCollection<ItemModel> Items
        {
            get { return items; }
            set
            {
                items = value;
                NotifyOfPropertyChange(() => Items);
            }
        }

        private ItemModel selectedItem = new ItemModel(rnd);
        public ItemModel SelectedItem
        {
            get { return selectedItem; }
            set
            {
                selectedItem = value;
                NotifyOfPropertyChange(() => SelectedItem);
            }
        }

        private SubItemModel selectedSubItem = new SubItemModel(rnd);
        public SubItemModel SelectedSubItem
        {
            get { return selectedSubItem; }
            set
            {
                selectedSubItem = value;
                NotifyOfPropertyChange(() => SelectedSubItem);
            }
        }

        public ShellViewModel()
        {
            for(int i = 0; i < 10; i++)
            {
                Items.Add(new ItemModel(rnd));
            }
        }

        public void AddItem()
        {
            Items.Add(new ItemModel(rnd));
        }

        public void RemoveItem()
        {
            Items.Remove(SelectedItem);
        }

        public void AddSubItem(object e)
        {
            var _item = e as ItemModel;
            _item.SubItems.Add(new SubItemModel(rnd));
        }

        public void RemoveSubItem(object e)
        {
            var _item = e as ItemModel;
            _item.SubItems.Remove(SelectedSubItem);
        }
    }
}

ShellView:
<Window x:Class="ContextMenuTest.Views.ShellView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ContextMenuTest.Views"
        xmlns:cal="http://www.caliburnproject.org"
        mc:Ignorable="d"
        Title="ShellView" Height="450" Width="800"
        >

    <Grid Grid.Row="1">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <DataGrid x:Name="Items" Grid.Row="0" AutoGenerateColumns="False" CanUserResizeColumns="True" CanUserAddRows="false"
                        VerticalAlignment="Stretch" VerticalScrollBarVisibility="Auto" MinHeight="100" SelectedItem="{Binding SelectedItem}">
            <DataGrid.ContextMenu>
                <ContextMenu cal:Action.TargetWithoutContext="{Binding Path=PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
                    <MenuItem Header="Add Item" cal:Message.Attach="AddItem()"/>
                    <MenuItem Header="Remove Item" cal:Message.Attach="RemoveItem()"/>
                </ContextMenu>
            </DataGrid.ContextMenu>

            <DataGrid.Columns >
                <DataGridTextColumn Header="ID" Binding="{Binding Path=ID, UpdateSourceTrigger=PropertyChanged}" Width="*" IsReadOnly="True"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}" Width="*"/>
            </DataGrid.Columns>

            <DataGrid.RowDetailsTemplate>
                <DataTemplate>
                    <DataGrid ItemsSource="{Binding Path=SubItems}"  AutoGenerateColumns="False" CanUserResizeColumns="True" CanUserAddRows="false"
                                VerticalAlignment="Stretch" VerticalScrollBarVisibility="Auto" MinHeight="100"
                                  SelectedItem="{Binding Path=SelectedSubItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}}">
                        <DataGrid.ContextMenu>
                            <ContextMenu cal:Action.TargetWithoutContext="{Binding Path=PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
                                <MenuItem Header="Add Sub Item" cal:Message.Attach="AddSubItem($dataContext)"/>
                                <MenuItem Header="Remove Sub Item" cal:Message.Attach="RemoveSubItem($dataContext)"/>
                            </ContextMenu>
                        </DataGrid.ContextMenu>
                        <DataGrid.Columns>
                            <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}" Width="auto" IsReadOnly="True"/>
                            <DataGridTextColumn Header="Name" Binding="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}" Width="auto"/>
                            <DataGridTextColumn Header="Value" Binding="{Binding Path=Value, UpdateSourceTrigger=PropertyChanged}" Width="auto"/>
                        </DataGrid.Columns>
                    </DataGrid>
                </DataTemplate>
            </DataGrid.RowDetailsTemplate>
        </DataGrid>
    </Grid>
</Window>

ItemModel:
using Caliburn.Micro;
using System;

namespace ContextMenuTest.Models
{
    public class ItemModel
    {
        public Guid ID { get; set; }
        public string Name { get; set; }
        public BindableCollection<SubItemModel> SubItems { get; set; } = new BindableCollection<SubItemModel>();

        public ItemModel(Random rnd)
        {
            ID = Guid.NewGuid();
            Name = "Item " + ID.ToString().Substring(3, 5);

            for (int i = 0; i < 5; i++)
            {
                SubItems.Add(new SubItemModel(rnd));
            }
        }
    }
}

SubItemModel:
using System;

namespace ContextMenuTest.Models
{
    public class SubItemModel
    {
        public Guid ID { get; set; }
        public string Name { get; set; }
        public int Value { get; set; }

        public SubItemModel(Random rnd)
        {
            ID = Guid.NewGuid();
            Name = "SubItem " + ID.ToString().Substring(3,5);
            Value = rnd.Next();
        }
    }
}

Answer: Try using TagHelper. It works for your requirement.sample code is as below.
<Grid Background="White" HorizontalAlignment="Stretch" Height="200" Name="GridLayout">
    <ListBox x:Name="ListBoxItems">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Tag="{Binding DataContext, ElementName=GridLayout}">
                    <Grid.ContextMenu>
                        <ContextMenu Name="cm" cal:Action.TargetWithoutContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
                            <MenuItem Header="Open"
                                      cal:Message.Attach="Open($dataContext)">
                            </MenuItem>
                        </ContextMenu>
                    </Grid.ContextMenu>

                    <TextBlock VerticalAlignment="Center">
                        .. text..
                    </TextBlock>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>


How do I limit the values returned by ctools_export_load_object()?

Question: Imagine I have the following code.
$result = ctools_export_load_object('mytable', 'conditions', array('date' => '1337020900'));

How can I limit the values returned by ctools_export_load_object()?
What is the difference between ctools_export_load_object() and db_query()?
Answer: You are right; that is how you should call ctools_export_load_object() to filter the returned objects. Keep in mind that:

For each condition you can just enter a value a database field must have
If you enter more than one condition, the function will return the objects for which all the conditions are verified

The code used from the function for handling the conditions is the following one.
  else if ($type == 'conditions') {
    foreach ($args as $key => $value) {
      if (isset($schema['fields'][$key])) {
        $query->condition($key, $value);
      }
    }
  }

Because that code, you cannot get (for example) the objects for which the date is 1337020900, or 1337020910, or 1337020940, or 1337020906. You cannot choose the operator to apply for the conditions, which means (for example) that you cannot get all the objects for which the date is greater than 1337020900, or lower than 1337020900.
The difference between ctools_export_load_object() and db_query() are the following.

ctools_export_load_object() doesn't just return the objects obtained from a database table; it returns also objects returned from a specific hook. This is done from the following code in _ctools_export_get_defaults().
if ($export['default hook']) {
  if (!empty($export['api'])) {
    ctools_include('plugins');
    $info = ctools_plugin_api_include($export['api']['owner'], $export['api']['api'], $export['api']['minimum_version'], $export['api']['current_version']);
    $modules = array_keys($info);
  }
  else {
    $modules = module_implements($export['default hook']);
  }

  foreach ($modules as $module) {
    $function = $module . '_' . $export['default hook'];
    if (function_exists($function)) {
      foreach ((array) $function($export) as $name => $object) {
        // Record the module that provides this exportable.
        $object->export_module = $module;

        if (empty($export['api'])) {
          $cache[$table][$name] = $object;
        }
        else {
          // If version checking is enabled, ensure that the object can be used.
          if (isset($object->api_version) && version_compare($object->api_version, $export['api']['minimum_version']) >= 0 && version_compare($object->api_version, $export['api']['current_version']) <= 0) {
            $cache[$table][$name] = $object;
          }
        }
      }
    }
  }

  drupal_alter($export['default hook'], $cache[$table]);
  ```

ctools_export_load_object() can automatically join tables, if it finds the right information in the database schema defined in hook_schema().
// Build the query
$query = db_select($table, 't__0')->fields('t__0');
$alias_count = 1;
if (!empty($schema['join'])) {
  foreach ($schema['join'] as $join_key => $join) {
    if ($join_schema = drupal_get_schema($join['table'])) {
      $query->join($join['table'], 't__' . $alias_count, 't__0.' . $join['left_key'] . ' = ' . 't__' . $alias_count . '.' . $join['right_key']);
      $query->fields('t__' . $alias_count);
      $alias_count++;

      // Allow joining tables to alter the query through a callback.
      if (isset($join['callback']) && function_exists($join['callback'])) {
        $join['callback']($query, $schema, $join_schema);
      }
    }
  }
}

ctools_export_load_object() caches the result obtained, which means it could not execute any query at all.

ctools_export_load_object() uses many functions that are defined in the database schema. You can look at the code comments in ctools_export_get_schema() to see which functions are used.

As side note, a comment contained in ctools_export_get_schema() says (emphasis is mine):

Please do not call these directly, always use the ctools_export_crud_ wrappers* to ensure that default implementations are honored.
Answer: as i see it, you have to limit the $result array yourself, if the conditions are not limiting enough.
the difference, taken from the documentation:

This function will cache the objects, load subsidiary objects if
  necessary, check default objects in code and properly set them up. It
  will cache the results so that multiple calls to load the same objects
  will not cause problems.
It attempts to reduce, as much as possible, the number of queries
  involved.


OpenCart 2.3 - Controller default and custom template

Question: I am following the book OpenCart Theme and Module development
In chapter 3 it states:
For example, you can refer to catalog/controller/account/account.php. You
will find the following code in it:
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/account/account.tpl')) {
    $this->template = $this->config->get('config_template') . '/template/account/account.tpl';
} else {
    $this->template = 'default/template/account/account.tpl';
}

However, it is not possible to find this code excerpt while checking catalog/controller/account/account.php.
Where is this check in OpenCart 2.3?
Comment: What is your actual requirement? Can you explain further.
Comment: Understand where is that code in OpenCart 2.3 that checks if file is present or not. According to the book it shall be there so I guess it has been moved from previous OpenCart 2.x versions
Answer: Loading view in OpeCart 2.3:
$this->response->setOutput($this->load->view('account/account', $data));

You may want to ckeck these files:
system\library\response.php
system\engine\loader.php
system\library\template.php


Android TableLayout in a ListView, mysterious column shrinking

Question: I am using TableLayout within a ListView. The data I'm presenting is tabular in nature and the TableLayout seems like a good way to ensure that the columns line up as desired. This approach worked well most of the time - see below.
Desired view:

But occasionally the Views representing the columns wrapped their text content as shown below.

After searching around for a while, I came across the following discussion on the Android Google Group. In response, I set android:stretchColumns="*" in the TableLayout and voila, the contained TextViews stopped mysteriously wrapping their text.
Here's a partial content of the layout's XML, with the change highlighted with a comment:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:stretchColumns="*">

While I'm now getting the desired result, I'm a bit confused as to why this "fixed" my problem. The TableLayout documentation states that "The width of a column is defined by the row with the widest cell in that column." But if that's true, why did the columns apparently shrink in size in the first place causing the text to wrap?
Does anyone have a good explanation?
Answer: Containers query their children for how much space they want, and this process continues recursively.  Any dynamically sized layout framework is going to work this way.  From the inside out, children report up to their parents their desired size, and then on a second pass the parents report back to their children how much space is available to them.  When they're not included in the stretchColumns list (either explicitly by position, or implicitly by wildcard as in the example), they ask for the bare minimum which in the case of TextView is the minimum space required to display the text wrapped.  When they're included in the stretchColumns list, they report the width required to display the entire contents, and if it fits they don't get wrapped.  Anyone who requests more space than is available to them gets wrapped text.  I imagine the priority is given in order from least space required up to the most so if you have stretchColumns="*" the largest blocks of text are getting wrapped first (if necessary) and everyone else gets to be displayed normally.


You have already activated rack 1.6.0, but your Gemfile requires rack 1.6.4

Question: Similar to problem with rack 1.3.2. You have already activated rack 1.3.2, but your Gemfile requires rack 1.2.3 -- I'm experiencing You have already activated rack 1.6.0, but your Gemfile requires rack 1.6.4 when attempting to run Rails (4.2) in production with Puma and Nginx.
bundle update rake nor rm Gemfile.lock && bundle install seem to help, the only solution I have so far is manually changing rack (1.6.4) to rack (1.6.0) in Gemfile.lock.
Comment: this is similar to your case. http://stackoverflow.com/questions/9241912/how-to-force-rack-to-work-around-the-usual-you-have-already-activated-rack. you have to remove rack version 1.6.0 like this  `gem uninstall rack -v 1.6.0`
Comment: That did indeed to the trick @Athar - tyvm!
Comment: Have you tried binstub? Check the answer below
Answer: you need to uninstall one version of rack which is not required.
Do this please
gem uninstall rack -v 1.6.0

Reference: How to force rack to work around the usual "You have already activated rack..." bug?
Answer: One experienced Rails developer highly recommends using binstubs. Have it installed by:
bundle install --binstubs

and run it via relative path:
./bin/rails server

or what is most recommended update PATH and forget about bundler issues:
export PATH="./bin:$PATH"
rails server

Comment: It will happen again if not fixed properly
Comment: Nope, this is in production using Puma. Athar's comment above fixed it though. Thanks!
Answer: Run it like this: bundle exec rails s. This will use settings from your Gemfile.lock
Comment: No matter how carefully you install or uninstall gems you will end up with multiple versions. Running it is bundle exec is the right way to do it and removes version ambiguity from your deployment
Comment: Thanks, but see Athar's comment above.
Comment: @Zepplock right, "binstubs" is a way to avoid prepend *bundle exec* all the time
Answer: These issues might arise if you are using local or global gemset for more than one project. Why not create seprate gemset for each project.
You can do this using rvm
Create new gemset
rvm gemset create new_test

rvm gemset use new_test

bundle install

Comment: Indeed. Multiple projects was my issue and this is a clean solution. Also, adding #ruby-gemset=new_test to the Gemfile sets the gemset for the project
Answer: You can simply run below cmd to get the latest rack installed in server to fix the issue:
gem install rack

Answer: I experienced this issue:
Here's my solution:
Solution 1:
This solution works a lot of the time, simply update the gem causing the issue.
bundle update rack

Solution 2:
In some cases Solution 1 may not work, and you will need to edit your Gemfile.lock file.
Simply, open your Gemfile.lock file and then change the version to the update requested.
In my case, I had rack 2.0.7 defined in my Gemfile.lock file, but my application required rack 2.1.2, I simply had to modify it to rack 2.1.2 in the Gemfile.lock file.
I then had to uninstall the previous version of rack which is rack 2.0.7
 gem uninstall rack -v 2.0.7

And finally installed the new gem in production
bundle install --without development test

Solution 3:
In very rare cases Solution 1 and Solution 2 may not work, and you will need to edit your Gemfile before updating the gem.
In my case, the gem was puma, I had puma ~> 3.11 defined in my Gemfile, but my application required puma ~> 4.3.1. At this point running bundle update puma and editing my Gemfile.lock file didn't work, since puma ~> 3.11 version specified in the Gemfile would not allow an update to puma ~> 4.3.1.
I simply had to change the version of puma in the Gemfile to puma ~> 4.3.1 and then ran the command.
bundle update puma

That's all.
I hope this helps


For very basic markdown, will these regular expressions work?

Question: just a quick question about Regular expressions: Will this code work for any grooming I will need to do? (i.e. Can this be inputted into a database and be safe?)
function markdown2html($text) {
        $text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
    // Strong Emphasis
    $text = preg_replace('/__(.+?)__/s', '$1', $text);
    $text = preg_replace('/\*\*(.+?)\*\*/s', '$1', $text);

    // Underline
    $text = preg_replace('/_([^_]+)_/', '
$1
', $text);
    //Italic
    $text = preg_replace('/\*([^\*]+)\*/', '$1', $text);

    // Windows to Unix
    $text = str_replace('\r\n', '\n', $text);
    // Macintosh to Unix
    $text = str_replace('\r', '\n', $text);

    //Paragraphs
    $text = '
' . str_replace("\n\n", '

', $text) . '
';
    $text = str_replace("\n", '
', $text);

    // [Linked Text](Url)
   $text = preg_replace('/\[([^\]]+)]\(([a-z0-9._~:\/?#@!$&\'()*+,;=%]+)\)/i', '$1', $text);

   return $text;

}

Comment: Why don't you just... try it
Comment: @James this will have no impact on SQL injections. Be sure to use PDO if you want better protection.
Comment: Why do you think about injection? Did you use old and deprecated mysql lib?
Comment: I strongly recommend you put Markdown into your database and parse it on the way out. Then you can change your Markdown implementation. Besides — what if a user wants to edit their post?
Comment: Works on test, just wondering if it would stop SQL injection.
Comment: How does anything your Markdown-to-HTML conversion have anything to do with SQL injection?  There is nothing related to SQL in your code.
Answer: No, absolutely not.
Your code has nothing to do with SQL -- it does not modify ' or \ characters at all. Commingling the formatting functionality of this function with SQL escaping is silly.
Your code may also introduce HTML injection in some situations -- I'm particularly suspicious of the URL linking regex. Without a proper parser involved, I would not trust it an inch.
Answer: No, the data can not assured to be safe after passing through that function.
You need to either escape sql-sensitive characters or use PDO/Mysqli. Preapared statements are much more handy anyway.
Don't use the old way of hacking together a query, ie:
$query = 'select * from table where col = '.$value;

You're just asking for trouble there.
Answer: A couple of things jumped out at me:
I believe that the first two regexs ('/__(.+?)__/s' and the corresponding one for *) handle ___word___ and ***word*** incorrectly –– they will treat the third character as part of the word, so you will get *word* (where the first * is bold and the trailing one is not) instead of word.
On the third one ('/_([^_]+)_/'), is it really appropriate for

do _not_ do that

to turn into

do
not
 do that

?
Of course I'm not saying that it's OK to use if you fix these issues.


Do accidentals earlier in the measure affect a trill?

Question: I was attempting to help someone understand all the markings in a piece with which they are unfamiliar. One, however, has given me pause:

Now, I know the rule for a trill is that it ordinarily remains diatonic. If a chromatic trill is needed, an accidental will be placed near the tr marking (or occasionally with grace notes).
What I am not sure about is whether an accidental earlier in the measure also affects the auxiliary or upper note of the trill.
In this specific case, should one trill D-E or D-E♭?
(I would like an authoritative answer, as I plan to also use this to tell the people at MuseScore how the trill should work. Currently, they do an E♭ for the first quarter note, but then switch to an E♮ across the bar. I know that's wrong, but I want to have a definitive answer before reporting a bug.)
Comment: In Elaine Gould's *Behind bars*, this remains somewhat open for clarification. She only mentions "this pitch is modified by a key signature" (p. 138). Here, I'd like a clarification like: [and not by accidentals earlier in the bar], but there's none of that.
Although I agree on User23017's answer, I also agree Trlkly's inquiry for a better source material than "common knowledge".
Answer: You retain the accidental.  In this case, it is pretty unambiguous since the lead note is immediately preceding the note (baroque trills would even start with the upper note).  If there is more of a distance to the preceding use of a changed pitch, one would lean towards adding a reminder accidental to the trill.
Comment: Can you give a little more context to your answer? What I mean is, how are you so sure? Do you have a source? Or are you a professional in notation or some sort of music teacher? Were you taught this in music theory class? Have you written this sort of thing before? I mean, I lean towards it being an E-flat, too, but I'd like to have an authoritative reason.
Comment: If it was supposed to be an E nat, the trill notation needs to reflect that.  Currently, the notation indications that you should trill to Eb.  As far as playback goes, typically, un-altered trill indications in contemporary music signify a whole-step trill, which is why you're hearing the E nat. come back to you. It would be better to clarify your trill notation by providing a small notehead in parenthesis that indicates which note you're trilling to.
Comment: One could argue this is common knowledge. I don't know how I know this but I do. I know I've played pieces where the accidental is cancelled for a trill with a natural sign, which would only make sense if the accidental were assumed to apply when a natural is not present.
Comment: @ToddWilcox or the natural could be some type of cautionary accidental to remind you that it is a natural ;)
Comment: As MuseScore has since changed this, and they are now using an official source, I decided I't better accept and upvote this Answer.


Length from tangent circles

Question: A circle $Γ_1$ of radius $25$ is externally tangent to a circle $Γ_2$ of radius $16$ at $C$. Let $AB$ be a common direct tangent, so that $A$ lies on $Γ_1$ and $B$ lies on $Γ_2$. Draw the tangent to $Γ_1$ that is parallel to $AB$; let this tangent intersect $Γ_1$ at $T$, and the common transverse tangent through C at $U$. Then find the  length of $TU $. From where do I start the problem. I tried drawing some perpendiculars, but I don't think it helps.

Comment: Does this help?
Comment: I think that you have not understood the problem. Please try to make the figure. I have the figure and the question is correct.
Comment: How? Should I take the pic from my notebook and attach it?
Answer: Assume that $CU$ and $AB$ meet at $V\in AB$. And $O_i$ is a center
of $\Gamma_i$.
(1) Note that $$O_1TUC\ {\rm is\ similar\ to}\ O_2BVC$$ And note that the
ratio is $16/25$. That is if we know $BV=CV=x$, then we are done.
(2) In $O_1O_2BA$, $$\angle AO_1O_2+ \angle BO_2O_1=\pi$$ so that $$
 \triangle CO_2V,\ \triangle CO_1V\ (,\
 \triangle O_1VO_2 )$$ are similar.
Hence $$ \triangle CO_2V :  \triangle CO_1V
 = 16:x=x: 25 \Rightarrow x=20 $$
Hence we have $125/4$
Answer: Direct trig calculations after a sketch is drawn. The circle radii are $ (R,r)= (25,16)$.
The half -angle between direct tangents $= \theta~ $ is given by
$$ \sin \theta =\frac{R+r}{R-r}\to \theta=12.680383^{\circ}$$
$\angle FHA $  is half the complement of $\theta$
$$ TU= FH= R \cot (45^{\circ}- \theta/2)= 25/ \tan 38.66^{\circ}\approx 31.25$$
which tallies with Geogebra construction:

Length from tangent circles


process.env.proxy no longer populated in React.js in Node 8.8.1

Question: I set the proxy in the package.json file like that:
<code> "proxy": "http://localhost:8000/"
</code>
and I used to be able to read the value using
process.env.proxy
Unfortunately since I updated to the latest node v8.8.1 the proxy is no longer part of the process.env properties.
Where did it go and how can I get it?
PS: I need the value because I'm creating links in my UI that point to the API backend.
Cheers.
Answer: Just require('package.json') and extract it from there.
Comment: Also, if you're using something like Webpack to build your client bundle you can easily include package.json.
Comment: Thanks for the suggestion but unfortunately the file lives outside the "src" folder and thus cannot be require'd.


Como posso contar campos que são NULL?

Question: Estou utilizando essa query:
Gostaria de saber como posso contar esses campos que nao possuem registros. Aqui retorna 0. Mas tenho alguns registros nulos. O que faço?
SELECT DataFim, COUNT(DataFim) AS QTD FROM AtivacaoGuincho
GROUP BY DataFim
HAVING DataFim is  null

Comment: Se puder, experimente `SELECT COUNT(*) - COUNT(DataFim) AS qtd` e me comente se funciona.
Answer: Assim:
SELECT COUNT(*) AS QTD FROM AtivacaoGuincho
WHERE DataFim is  null

Já que o Marlon tocou no assunto da contabilização das linhas posso melhorar um
pouco mais essa resposta e entrar num assunto que é quase uma curiosidade.
O count é basicamente usado dessa maneira acima. Solicito que contabilize todas linhas ONDE a DATAFIM é nula.
Mas poderia fazer assim:
SELECT COUNT(*) AS TOTAL, COUNT(DATAFIM) AS DTFIM FROM AtivacaoGuincho

E teria algo assim: tenho 1884 linhas na tabela e 50 linhas onde DATAFIM é nula.
E claro, poderia ter tantos counts quantos quisesse no meu select.
Comment: esse me retorna 2. É o correto
Answer: Faltou a cláusula where corretamente..
SELECT COUNT(DataFim) AS QTD
FROM AtivacaoGuincho
WHERE DataFim is  null

EDIT:
Desculpe pelo erro de Ctrl+c/Ctrl+v, o correto é:
SELECT COUNT(*) AS QTD
FROM AtivacaoGuincho
WHERE DataFim is null

E pra quem não sabe a diferença entre Count(*) e Count(coluna) é que:

Count(*) contabiliza todas as linhas sem exceções.
Count(coluna) contabiliza valores da coluna que não são nulos
(null)
Comment: esse me retona 0
Comment: @Aline, editei a resposta com uma informação que pode ser valiosa pra você :)
Comment: Opa, obrigada moço.
Comment: Awwwwwwwwwwwwwwwwwwwww entendi
Comment: Agora sei pq estava me retornando 0...

Como posso contar campos que são NULL?


How to click on the checkbox when another element receives the click action?

Question: I have a problem with click action in Selenium Python.
I try to click on the checkbox, but  element receive this click.
I tried to resolve this problem by correctly choice of this element, I checked CSS SELECTOR, XPATHs and iteration by elements which I found by CLASS NAME but even if I have an absolute path to the element, the  element where my  is nested catches the click action.
I don't know how I can resolve this issue, many you have some ideas?
It's my HTML code with  element which I need to click:

And Selenium Exception:
Message: unknown error: Element  is not clickable at point (40, 178). Other element would receive the click: ...\n
And my selectors:
Answer: Could you please use the xpath as below to select the checkbox.
//input[@id='vf-pp-accept-terms2']

Comment: Anytime my friend :)


How to display a form filled by a VBO-submission?

Question: I'd like to use Privatemsg module to send messages to group of users. For this purpose I plan to use a view with Views Bulk Operations (VBO) and plenty of exposed filters.
I was able to create a custom VBO-action that puts the selected users into the recipient field of the message form:
function mymodule_my_custom_action(&$user, $context=array()) {

module_load_include('pages.inc','privatemsg');

$recipients = array();
foreach ($user as $recipient) {
$recipients[] = user_load($recipient->uid);
}

$subject = 'Some subject'

$message_form = drupal_get_form('privatemsg_new', $recipients, $subject);
$message_html = drupal_render($message_form);
}

I'm not very experienced in development so I don't know how to display this form together with the view that helps choosing the recipients. A simple print $message_html; won't be enough of course. For example would it be possible to use a panel page containing two panes: one for the view of users with VBO and one for the privatemsg form?
Any help would be greatly appreciated!
Answer: As per the "I'm not very experienced in development", you may want to use an alternative approach which only requires site building skills, as further explained below ...
Use the integration of the Privatemsg module with Rules instead (make sure to checkout this community docu, and its child pages ...), together with the Views Bulk Operations module.
For more details, refer to the video about Using Rules components with VBO. Possibly you also want to look at the 2 prior videos and/or the 2 subsequent videos (all about Views Bulk Operations), i.e.:

Introducing Views Bulk Operations.
More details about VBO settings.
Using Rules componens with more than one parameter.
Using VBO to load list of objects into Rules.

In this specific case;

use Views bulk operations to create the list of your users to be targeted (so this is just a minor variation of the VBO based view you seem to already have in place).
create a Rules Component which uses Rules action "Send a message" (provided by the Privatemsg module). If you'd add 2 "variables" to this Rules Component, named something like "MsgSubject" and "MsgBody", you might want to use those variables as "tokens" for constructing the actual Subject and Body of your message.
Within your VBO settings, just execute this Rules Component. If you then use this VBO-view, you can specify the desired values for the variables used to create your Rules Component (like "MsgSubject" and "MsgBody"). So you avoid hardcoding the "Subject" and "Body" for the "Send a message" action (without those variables it would only allow you to send predefined messages). And this simply by using these variables of your Rules Component (to implement that "Subject" and "Body" of the message). That way, each time you use your VBO to send such messages, you can enter the desired "Subject" and "Body" for each of those messages.

Done, no (custom coding) involved ...
For some other illustrations about using VBO in combination with Rules Components, refer to the answers to these questions:

How to bulk update select list fields?
How to bulk delete selected content/nodes?
Comment: Thanks for the detailed answer. But - unless I'm mistaken - the "Send a message" action needs to specify subject and body, so I can send predefined messages only. Or is it possible to use this method in sending any messages in privatemsg message form?
Comment: @StG: Good (extra) question! Refer to my **Bonus tip** I just added to also  address that (and some related questions to get a better idea of how it is like to use Rules with VBO). The possibilities you get by the combination of both amazing modules is only limited to your own imagination ...
Comment: That seems to be a good solution but I don't really know how to implement it. To have subject and body values as variables, users needs fields to fill. How can I add these two extra fields to the VBO-page and hhow can I submit them?
Comment: @StG : refer to my updated answer (the numbered list items 2. and 3.) And make sure to watch the videos (especially the one about Rules components with more than one parm). Let me know (via extra comment) if you can get it to work, ok?
Comment: Ah okay, I see now. Thanks a lot, I 've created the rule component with 3 parameters (list of users, text for subject and formated text for body) and it's working! Thanks again!
However, I still have a minor issue with it: Since I send the messages looping through the list of users, privatemsg module sends individual messages and doesn't create a thread. Is it possible to use the whole array of users in a single Send message action?
Comment: Absolutely :)  (btw. please check my previous comment. Should it be discussed here or shall I open a new question for it?)
Comment: Hm, that sounds like worth a different question (I'd have to think about it a bit to find out if it is doable though) ...


Does Apple mandate authorization via SSL?

Question: A friend of mine claims that Apple rejects applications that use vanilla HTTP for authentication.
I am unable to verify this information and Google doesn't say anything on the topic.
Are there any known cases of an app being rejected on the grounds that it doesn't use SSL?
Comment: I don't know if they would reject on those grounds, but it seems fairly pointless to perform authorisation to a back end over an insecure connection. One thing I can say is that if you do want to connect to a SSL service, the certificate must be from a trusted vendor, self-generated certificates and those from dubious providers will fail connection without very helpful reasoning.
Answer: Apple doesn't care about how you handle data transfer security. I am the author of an app which is available for over a year. The app got a couple of updates which all went through the approval process and the app never used HTTPS for sign up.
Even apps like Twitter or Facebook didn't use HTTPS in the first years of iOS.


How to get id of just-executed sql query (in php)

Question: In php I have an INSERT query to database. This query add some issue to database. I want to check if issue was added fine (there are some cases when issue doesn't added - without any mistake reporting). How to check this?
I have an idea, that after i make INSERT query i should make a query, for example: SELECT ..... WHERE id=last_id. But how to get the last_id - how to get id of last INSERT query? (id is autoincrementing sql field)
Thank you
Comment: Which database (MySQL / SQL / PostgreSQL / SQLite / etc.)? And what functions are you using?
Comment: What do use you for executing the query? `mysql`, `pdo`?
Comment: possible duplicate of [SQL - INSERT and catch the id auto-increment value](http://stackoverflow.com/questions/621369/sql-insert-and-catch-the-id-auto-increment-value)
Comment: Postgresql, connecting via PEAR MDB2
Comment: Thanks to everybody. I've found and answer in that topic. Sorry for duplicate
Answer: mysql_insert_id();
Answer: mysql_insert_id()

More info at http://php.net/manual/en/function.mysql-insert-id.php and http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
Answer: You may find the answer to this StackOverflow question useful:
SQL - INSERT and catch the id auto-increment value
Comment: Thank you.
Sorry for duplicate question. I've used search but it was uneffective.
I found answer there
Answer: mysql_insert_id function returns id of previously inserted record.
I assume you're working with MySQL


Strange integrand: $\int \sqrt{x} e^{x}dx$

Question: Is it possible, and if yes, how,  to evaluate an integral like $\int \sqrt{x} e^{x}dx$? I have heard of the Gaussian function which integrates to $\sqrt{\pi}$ but what about this? Thank you.
Answer: That indefinite integral is not an elementary one: in fact using the substitution $y=\sqrt{x}$ and integrating by parts you obtain:
$$\begin{split}
\int \sqrt{x}\ e^x\ \text{d}x &\stackrel{x=y^2}{=} \int 2y^2\ e^{y^2}\ \text{d} y \\
&= \int y\ \text{d} \left( e^{y^2}\right)\\
&= y\ e^{y^2} -\int e^{y^2}\ \text{d} y
\end{split}$$
where the latter integral is not elementary.
Comment: You could continue to $$\sqrt {x}{{e}^{x}}-{\frac {\sqrt {\pi}}{2}{\rm erfi} \left( \sqrt {x} \right) } + C$$
Answer: To get $\sqrt{\pi}$ you need to integrate from $0$ to $\infty$, and you need to replace $e^x$ by $e^{-x}$.  Specifically, we have $$\int_0^\infty \sqrt{x}e^{-x}dx =\frac{1}{2}\Gamma\left(\frac{1}{2}\right)=\frac{\sqrt{\pi}}{2}.$$
See the following answer for a variety of different proofs: $\int_{-\infty}^{+\infty} e^{-x^2} dx$ with complex analysis


Mining cycles from graphs

Question: Suppose $T$ is a set of transactions containing some paths taken from a set of undirected graphs $G$ whose nodes are all taken from the same finite alphabet $A$. I would now like to extract all frequent cycles (strongly connected components) from $T$ by using the Apriori algorithm.
The idea is that since the Apriori is anti-monotone in the support parameter (for the item $(abc)$ to be frequent, all subsets $(ab)$, $(ac)$, $(bc)$ etc must also be frequent), it is sufficient to just extract all rules of length $2$, ie. $a\to b$, $b\to c$ etc. Returning to the graph representation, we do not need to extract paths like $a\to b \to c \to d$, because they can all be described as a set of paths of length $2$.
Am I correct in saying that by combining all such rules/paths of length $2$ from $T$ into a new directed graph $G'$, the strongly connected components can be extracted?
Answer:
Am I correct in saying that by combining all such rules/paths of length 2 from T into a new directed graph G′, the strongly connected components can be extracted?

I don't have a citation for you, but I think you've essentially just restated the Apriori algorithm in graph notation (I'm accustomed to a set notation description), so I believe your reasoning is correct.

Mining cycles from graphs