Minimum of the absolute value of two unitary matrices elements

Question: Given two unitary matrices $A \in\mathcal{M}_{n\times n}=\{a_{ij}\}_{i,j \in {1..n}}$  and $B \in\mathcal{M}_{p\times p}=\{b_{ij}\}_{i,j \in {1..p}}$ where n>p.
Can I say that $\min(|\{a_{ij}\}_{i,j \in {1..n}}|)\leq \min(|\{b_{ij}\}_{i,j \in {1..p}}|)$?
Answer: Counter-example using real matrices : Let $A=Id\in \mathcal{M}_{3\times3}$. Then $A$ is trivially unitary. Now let $$B=\begin{pmatrix}
cos(\theta) && -sin(\theta)\\
sin(\theta) && cos(\theta)
\end{pmatrix}$$
Be the rotation matrix (thus orthogonal, which is a special case of unitary) of angle $\theta$ in the plane. For $\theta\in (0,\frac{\pi}{2})$, both $|cos(\theta)|$ and $|sin(\theta)|$ are smaller than one, so your inequality wont hold.
Comment: Thank you very much. Yeah I see.


Get user's avatar with their ID in discord.py

Question: Code
<code>@bot.command()
async def avatar(ctx, *,  avamember : discord.Member=None):
   userAvatarUrl = avamember.avatar_url
   await ctx.send(userAvatarUrl)
</code>
error:
Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
Comment: Maybe try to update to the newest version
Comment: what version of `discord.py` are you using?
Comment: The newest version (2.0) doesn't have that attribute @FlexGames
Comment: My python version 3.9.7
Answer: <code>@bot.command()
async def avatar(ctx, *, member: discord.Member = None):
    if not member:
        member = ctx.message.author
    em = discord.Embed(title=str(member), color=0xAE0808)
    em.set_image(url=member.avatar_url)
    await ctx.reply(embed=em, mention_author=False)
</code>
On responds on your comment: "AttributeError: 'Member' object has no attribute 'avatar_url'"

In my IDE you will see I used "client" rather than "bot", but that does not have anything to do with your code. Besides that, I am using the prefix ">" which can be obviously different for you.
Results:

Code in IDE:
Comment: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
Comment: While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: https://stackoverflow.com/help/how-to-answer . Good luck
Comment: CINEMA Plus, are you sure you used to code correctly because I am on the latest discord.py version, and this code works perfectly fine for me.
Comment: Bram, yes i use python 3.9.7.
Comment: Updated the code a bit, and uploaded screenshots.
Comment: Are you btw sure you are pinging the user with "@"?


Contextual Action Bar unable to delete selected item from SQLite

Question:
CAB unable to delete the data from cursor adapter

public class History extends ListActivity{

private ReminderDB mDbHelper;
List selections = new ArrayList();
int count = 0;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.history);

    mDbHelper = new ReminderDB(this);
    mDbHelper.open();
    fillData();
    registerForContextMenu(getListView());
}

private void fillData() {
    final Cursor remindersCursor = mDbHelper.fetchAllHistoryEvents();
    startManagingCursor(remindersCursor);
    // an array for the fields to show in the list row (now only the TITLE)
    String[] from = new String[]{ReminderDB.KEY_TITLE};
    // and an array of the fields for each list row
    int[] to = new int[]{R.id.row1};
    // a simple cursor adapter and set it to display
    final HistoryCustomCursorAdapter history = new HistoryCustomCursorAdapter(this, R.layout.history_list_row, remindersCursor, from, to);
    setListAdapter(history);
    getListView().setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
    getListView().setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            if(checked){
                selections.add(history.getItem(position));
                count++;
                mode.setTitle(count+ " Selected");
            }else{
                selections.remove(history.getItem(position));
                count--;
                mode.setTitle(count+ " Selected");
            }
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            MenuInflater menuInflater = getMenuInflater();
            menuInflater.inflate(R.menu.contextual_menu, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            if (item.getItemId()==R.id.item_delete){
                AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
                mDbHelper.deleteHistory(info.id);
                history.notifyDataSetChanged();
                mode.finish();
            }
            fillData();
            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            count = 0;
            selections.clear();
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    fillData();
}
}

This is the error message i getting:

11-08 14:24:03.475    6934-6934/com.example.windchin.digitalbrain
  E/AndroidRuntime﹕ FATAL EXCEPTION: main
      java.lang.NullPointerException
              at com.example.windchin.digitalbrain.History$1.onActionItemClicked(History.java:83)
              at android.widget.AbsListView$MultiChoiceModeWrapper.onActionItemClicked(AbsListView.java:7680)
              at com.android.internal.policy.impl.PhoneWindow$DecorView$ActionModeCallbackWrapper.onActionItemClicked(PhoneWindow.java:3299)
              at com.android.internal.app.ActionBarImpl$ActionModeImpl.onMenuItemSelected(ActionBarImpl.java:1009)
              at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
              at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
              at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
              at com.android.internal.view.menu.ActionMenuView.invokeItem(ActionMenuView.java:630)
              at com.android.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:200)
              at android.view.View.performClick(View.java:4475)
              at android.view.View$PerformClick.run(View.java:18786)
              at android.os.Handler.handleCallback(Handler.java:730)
              at android.os.Handler.dispatchMessage(Handler.java:92)
              at android.os.Looper.loop(Looper.java:176)
              at android.app.ActivityThread.main(ActivityThread.java:5419)
              at java.lang.reflect.Method.invokeNative(Native Method)
              at java.lang.reflect.Method.invoke(Method.java:525)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
              at dalvik.system.NativeStart.main(Native Method)

This is cursor adapter class
public class HistoryCustomCursorAdapter extends SimpleCursorAdapter {
    private Context context;
    private ReminderDB mDbHelper;
    private int layout;

    public HistoryCustomCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to) {
        super(context, layout, c, from, to);
        this.context = context;
        this.layout = layout;
        mDbHelper = new ReminderDB(context);
        mDbHelper.open();
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {

        final LayoutInflater inflater = LayoutInflater.from(context);
        View rowView = inflater.inflate(layout, parent, false);

        int titleCol = cursor.getColumnIndex(ReminderDB.KEY_TITLE);
        String title = cursor.getString(titleCol);
        TextView textView1 = (TextView) rowView.findViewById(R.id.row1);
        TextView textView2 = (TextView) rowView.findViewById(R.id.row2);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);

        textView1.setText(title);

        String Hdate = cursor.getString(cursor.getColumnIndex(ReminderDB.KEY_DATE_TIME));
        String latitude = cursor.getString(cursor.getColumnIndex(ReminderDB.KEY_LATITUDE));
        String longitude = cursor.getString(cursor.getColumnIndex(ReminderDB.KEY_LONGITUDE));

        if(Hdate != null)
            imageView.setImageResource(R.drawable.cclock);
        else
            imageView.setImageResource(R.drawable.maps);

        if(Hdate != null)
        {
            textView2.setText(Hdate);
        }
        else
        {
            Cursor c = mDbHelper.fetchLocation(latitude, longitude);
            String location = c.getString(c.getColumnIndex(ReminderDB.KEY_LOCATION));
            int option = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ReminderDB.KEY_LOCATIONOPTION)));
            String locationOption;
            if (option == 0){
                locationOption = "When I Arrive";
            } else {
                locationOption = "When I Leave";
            }
            textView2.setText(locationOption + ": " + location);
        }
        return rowView;
    }
}

Comment: which line is Line 83 in your History object??
Comment: @Jim mDbHelper.deleteHistory(info.id);
Answer: Based on your comment, then you have a problem at these lines:
            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
            mDbHelper.deleteHistory(info.id);

This means that your info object is null and your call to item.getMenuInfo() is not working.
That means your HistoryCustomCursorAdapter is not setting this value correctly. You have not posted the code for that object, but I think this should be sufficient to allow you to find the error.


An embedding of $\Bbb C^2/\Bbb Z_{p^2}$ into $\Bbb C^3/\Bbb Z_p$ onto the subvariety $\{xy=z^p\}$

Question: Let $p,q$ be coprime integers with $1\leq q<p$. Let $\Gamma_{p,q}$ be the action of the cyclic group $\Bbb Z_{p^2}$ on $\Bbb C^2$ generated by $(z_1,z_2)\mapsto (\zeta z_1, \zeta^{pq-1} z_2)$ where $\zeta=e^{2\pi i / p^2}$. Simiarly let $G_{p,q}$ be the action of $\Bbb Z_p$ on $\Bbb C^3$ generated by $(x,y,z)\mapsto (ax,a^{-1}y,a^qz)=(\zeta^px,\zeta^{-p}y,\zeta^{pq}z)$ where $a=e^{2\pi i /p}=\zeta^p$. According to Example 2.5 (p.5) of this paper (https://arxiv.org/pdf/1606.08656.pdf), there is an embedding of $\Bbb C^2/\Gamma_{p,q}$ into $\Bbb C^3/G_{p,q}$ onto the subvariety $\{xy=z^p\}$, but I can't see why. Can we explicitly construct such an embedding?
Answer: First of all, note that the variety $V=\{xy=z^p\} \subset \mathbb C^3$ is invariant under $G_{p,q}$. Draw the following diagram:
$$\require{AMScd}
\begin{CD}
\mathbb C^2 @>{g}>> V\\
@V{\sigma}VV @VV{\pi}V \\
\mathbb C^2/\Gamma_{p,q} @>{f}>> V/G_{p,q}
\end{CD}$$
Because the actions of the groups are free outside the coordinate axis, $\pi , \sigma$ are ramified coverings  of $p$ and $p^2$ sheets, respectively. With that in mind my first thought was to find a $p$-valued map $g$ (I realized later that this makes no sense at all) from $\mathbb C^2$ to $V$ that would respect the group action.
In this situations the best is going for the simplest maps first, so I try $g(z_1, z_2)=(z_1, z_2, (z_1z_2)^{1/p})$ but then that does not behave well with the group actions: the equivalent element $(\zeta z_1,\zeta^{pq-1}z_2)$ is sent to $(\zeta z_1, \zeta^{pq}(\zeta^{-1} z_2), \zeta^q(z_1z_2)^{1/p})$. If you look more closely, if we had $\zeta^p$ instead of $\zeta$ everything would work, so the next try is $g(z_1, z_2) =(z_1^p, z_2^p, z_1z_2)$. This clearly respects the group actions, and also, going back to counting ramifications, it makes sense because it is a $p$-ramified covering of $V$, so if $f$ were an embedding, then $\pi g=f \sigma$ should be a $p^2$-ramified covering.
It is clear that $g$ is surjective and therefore so is $f$. On the other hand, if $g(z_1, z_2)$ is $G_{p,q}$-related to $g(w_1, w_2)$ then there is some $k$ such that
$$
z_1^p \zeta ^kp = w_1^p \quad , \quad z_2^p\zeta^{-kp}=w_2^p \quad , \quad z_1z_2 \zeta ^{kpq} = w_1w_2.
$$
Taking $p$-th roots, we get $l,m$ such that $w_1 = z_1 \zeta^{k+lp}$, $w_2 = z_1 \zeta^{-k+mp}$ and by the third equation (i assume $z_1z_2\neq 0$), $\zeta^{kpq} = \zeta^{lp+mp}$. After some manipulation it is easy to see that $(z_1, z_2)$ and $(w_1, w_2)$ are $\Gamma_{p,q}$-related, so $f$ is bijective.
Now, I am not familiar with which theorems you can use to prove that some bijective holomorphic map between complex varieties (not manifolds, I know that a bijective holomorphic map between complex manifolds is a biholomorphism) has an inverse. Maybe you can construct the inverse locally, with $p$-th roots (note that the maps we are looking for should come from $p$-valued maps from $V$ to $\mathbb C^2$) but I hope this is sufficient to convince you that $g(z_1, z_2) =(z_1^p, z_2^p, z_1z_2)$ is the desired map.
I have tried to explain my thought process because I am by no means an expert in this area and I'm just extrapolating my knowledge from Riemann Surfaces; I hope everything is clear, and if I said anything wrong, feel free to correct me


Grocery CRUD Callback

Question: Estou precisando setar uma mensagem para o usuário, após a validação de uma função callback, porém, não entro nada referente. Tem uma mensagem genérica que serve para o formulário inteiro, eu quero por campos.
Tentei com form_validation->set_message, porém não funcionou.
Agradeço se alguém souber como fazer pra exibir uma mensagem personalizada, vinda de uma função de callback.
Comment: Robson, mostre o código que você esta usando e como esta usando o Grocery Crud para que possamos te ajudar.
Comment: Olá, @RafaelAcioly! Então, por fim eu desisti do Grocery Crud. Estava me dando mais trabalho do que se eu fosse fazer na mão. Obrigado.
Answer: Um exemplo:
 /** CHAMADA REGRA**/
   $this->form_validation->set_rules('campo', 'Label Campo', 'required', ['nome_regra', [$Objeto, 'nome_funcao_valida']]],
            ['required' => 'Campo obrigatorio.']);

/** FUNCAO QUE VALIDA **/
function nome_funcao_valida($valor)
    {
     if(CONDICAO)
          return true;
    else
    {
       $this->form_validation->set_message('nome_regra', 'A {field} não confere');
                return false;
    }
}

Comment: Olá, yathal! Então, tentei dessa forma, mas não deu certo também. Por fim, desisti e fiz tudo na mão. Valeu!

Grocery CRUD Callback


Visual Studio 2019 menustrip item click event

Question: I've been working for a while on a school project which involves menustrip items in a C# windows forms application. I'm currently working in Visual Studio 2019. I've tried over and over again to find a way to conveniently add "click" event methods for each items of the menustrip and I have only found one solution via contextmenustrips from a youtube video (https://www.youtube.com/watch?v=UE5FuSjm3d0). The problem is that I have some menus with multiple items and the solution above doesn't work for such a case.
What am I missing? How can I add proper on_click or click events for the menustrip items?
Answer: That is the proper way to do it from GUI. If you want to add the click events within the code, you can write the menu name, '.' and select Click, then type '+=':
mnuMyMenuItem.Click +=

VS will prompt you for an event handler, type TAB once to write the handler to the right side of the assignment, type TAB twice to automatically generate the method.
Answer: I personally recommend you to add the event handlers for menu strip items in your code manually.
Actually, there's no difference between adding it manually and using the IDE.
If you are familiar enough with the code, you can implement the handler in SomeForm.cs and register the handler to the event in SomeForm.Designer.cs then it will be EXACTLY the same with the code your IDE generate.
You can navigate to SomeForm.Designer.cs simply by pressing F12 when your cursor is on InitializeComponent() in the constructor of your form, or you can find it by expanding the form entry in the Solution Explorer.
If you insists on achieving what you want visually, you can find your menu strip item controls in a drop down list in a sub window called Properties, then you can add the event handlers in your preferred visual way.
Answer: You cannot add a click handler from the Items Collection Editor as only the properties are available in this window.
Instead select your ToolStripMenuItem directly by name in the main (dockable) Properties window (View -> Properties Window or Alt+Enter)
If you look carefully there is a drop down box for the current item on the first line, in there you should be able to select your ToopStripMenuItems and add event handlers
Thanks to: https://www.telerik.com/forums/where-in-designer-is-the-click-event-hiding


Rotating 3D coordinates to 2D plane

Question: I'm trying to solve this problem but I'm stuck;
I have 2 coordinates, in 3D, say $C_1 = (x_1,y_1,z_1)$ and $C_2 = (x_2,y_2,z_2)$.
Now I'd like to transpose these to a 2-dimensional plane, but instead of just saying $z_1=z_2=0$. I'd like to keep the distance and relation between these two coordinates.
So, I figured for that I should transpose the coordinates, such that $C_1$ is at $(0,0,0)$, and $C_2 = (x_2-x_1, y_2-y_1, z_2-z_2-z_1)$, and then rotate with a rotation matrix $R$.
But can someone help me with how to find the right rotation matrix if I want the lenght on the x-axis?
Comment: When you say "distance and relation" can you clarify what that means?  A simple approach is to take the line the two points are on and translate it onto your plane...
Comment: Yes that is what i like to do, translate the line between the two points and translate it onto my plane. I want to find the translation matrix that translates the two coordinates such that $z_1$ and $z_2$ are 0, but i dont know how.
Answer: Let the vectors be denoted by $v_1$ and $v_2$ (my preference :)).

Get the cross product of the two: $c = v_1 \times v_2$
$c$ is orthogonal to both $v_1$ and $v_2$.

Get the angle between $c$ and $k=(0,0,1)$:
$$
\cos\theta = \frac{c\cdot k}{|c|}
$$

Rotate both vectors about $a = c \times k$ by $\theta$ using Rodrigues' rotation formula
You have to normalize $a$ to get a unit vector before applying it to the formula: $a' = a/|a|$.

The pair of resulting vectors is one instance of possible rotations and both are perpendicular to $k$ ($z$-axis).
The rotation matrix can be obtained from Rotation matrix from axis and angle
Comment: Thanks! I found the correct solution to my problem! Didn't knew about the Rodrigues rotation, but it's a very handy formula! Unfortunately i cant upvote you yet..
Comment: @Pickels I've got curious about your approach :) You can update the post to show your solution if you have time.
Comment: I used your answer! Going through your steps gave me the correct solution! :)
Comment: @Pickels Oh, I see. I thought you found your own approach.

Rotating 3D coordinates to 2D plane


Ler uma linha específica em JavaScript

Question: Olá.
Tenho um código em HTML que recebe uma informação lida de um QR Code, que contém informações como Cliente, Danfe, Código e Quantidade e as exibe dentro de uma textarea. Essa leitura é feita por meio de um aplicativo separadamente do código.
Segue o código HTML:

    <textarea type="text" id="dadosLidos" style="height: 250px; width: 700px;"></textarea>

O conteúdo dessa textarea é salvo em uma var no arquivo JavaScript e impressa no console logo após.
$scope.saveInfo = function() {
    var dados = document.getElementById("dadosLidos").value;
    console.log(dados);
};

Um exemplo de informação que a textarea recebe é:
CLIENTE: FULANO DE TAL
DANFE: 123456
CÓDIGO: 1234
QNT.: 2

O que eu preciso é ler apenas o conteúdo da terceira linha, ou seja, CÓDIGO: 1234. Vou fazer uma verificação com o código contido em cada QR Code. Como eu posso fazer para ler ou salvar em uma variável apenas o conteúdo da terceira linha, ou da linha CÓDIGO ?
Answer: Simplesmente faça um split por quebras de linha \n.
Você irá obter um vetor com todas as linhas do texto. O conteúdo da 3ª linha estará na posição 2:
const textoLido = `CLIENTE: FULANO DE TAL
DANFE: 123456
CÓDIGO: 1234
QNT.: 2`;

vTexto = textoLido.split('\n');

linha3 = vTexto[2]
console.log(linha3);

Vai retornar:
CÓDIGO: 1234

Ler uma linha específica em JavaScript


Powershell Remoting Handover Variables

Question: I've opened a Remote Session s1, and like to run a function with Parameters i handover in my scriptblock:
Simplified example with Write-Host:
$a = "aaa"
$b = "bbb"
$c = "ccc"
$d = "ddd"
Write-Host "AAAAA: $a $b $c $d"  #This works fine as it's locally

Invoke-Command -Session $s1 -scriptblock {Write-Host "BBBBB: $a $b $c $d"}  #These variables are empty

What is the cleanest way to handover Variables (I normally receive from a local csv file) to the scriptblock?
Answer: You need to "pass" the parameters into your script block using the ArgumentList parameter on Invoke-Command. This should do it for you:
Invoke-Command -Session $s1 -scriptblock {param($a, $b, $c, $d) Write-Host "BBBBB: $a $b $c $d"} -ArgumentList $a, $b, $c, $d

Comment: Thanks, Already played with param but i was missing the
 -ArgumentList

Powershell Remoting Handover Variables


Add link field in custom form

Question: I want add link field (label + url internal/external) in custom form
This not work:
$form['test_ink'] = array(
  '#type' => 'link',
  '#title' => $this->t('Link title'),
  '#url' => '',
);

Answer: The link (Link) render element type is used to render an anchor element on a page, and not used to provide an input element in a form that is constrained for URLs.
As an example you may look at LinkWidget::formElement, which shows how that field widget creates form elements for a Link field. And the way it does this is to use the url (Url) form element, which will provide an input element that validates URLs. Make sure that the #url property is a valid (Url) object.
use Drupal\Core\Url;

$form['test_link'] = [
  '#type' => 'url',
  '#title' => $this->t('Link title'),
  // Example of a Url object from a route. See the documentation
  // for more methods that may help generate a Url object.
  '#url' => Url::fromRoute('entity.node.canonical', ['node' => 1]),
];

Edit:

Added @imclean's suggestion to the answer for readability
Comment: Note that for internal links the `url` type is *not* used, rather the `entity_autocomplete`.
Comment: Note that you can also use the linkit element if you have the linkit module (see https://www.drupal.org/project/linkit):
$form['test_ink'] = [
        '#type' => 'linkit',
        '#autocomplete_route_name' => 'linkit.autocomplete',
        '#autocomplete_route_parameters' => [
          'linkit_profile_id' => 'default',
        ],
      ]
Comment: Make sure the URL is a URL object or it simply won't work.  For example:

`use Drupal\Core\Url;

$element['test_link'] = [
  '#type' => 'link',
  '#title' => t('Link title'),
  '#url' => Url::fromRoute('entity.node_type.collection'),
];`
Answer: I liked @mpp's answer on how to create a linkit field if you have Linkit module enabled.
His example was not code formatted, so this is just a repost using formatted code for better readability and to make it easier to copy paste this to use in your own projects. Create a linkit field with Drupal's form api:
$form['block_link'] = [
  '#type' => 'linkit',
  '#title' => $this->t('Select link target'),
  '#description' => $this->t('Start typing to see a list of results. Click to select.'),
  '#autocomplete_route_name' => 'linkit.autocomplete',
  '#autocomplete_route_parameters' => [
    'linkit_profile_id' => 'default',
  ],
  '#default_value' => isset($config['block_link']) ? $config['block_link'] : '',
];

Note that you can change 'default' to any linkit profile you might have in your project.
Also note: my default value in this case comes from a block config form because I added this linkit field to a block's settings page. Remove #default_value if it is not applicable to your case or change it depending on where you get your value from.
Answer: For anyone stumbling across this post looking at adding Linkit to a config form (thanks @mpp and @Flyke), there's been a slight change in the API: 'linkit_profile_id' => 'default', should now be 'linkit_profile' => 'default',
 $form['block_link'] = [
  '#type' => 'linkit',
  '#title' => $this->t('Select link target'),
  '#description' => $this->t('Start typing to see a list of results. Click to select.'),
  '#autocomplete_route_name' => 'linkit.autocomplete',
  '#autocomplete_route_parameters' => [
    'linkit_profile' => 'default',
  ],
  '#default_value' => isset($config['block_link']) ? $config['block_link'] : '',
];

Small point but worth knowing.
Answer: I was facing this problem when I needed to add a link (url+label) to the theme settings form. I didn't use the url field cause it has a bug if the user wants to add an internal link.
This is how it looked on the CMS:

This is the code:
/**
 * Implements hook_form_system_theme_settings_alter().
 **/
function francisco_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id = NULL) {
  // Work-around for a core bug affecting admin themes. See issue #943212.
  if (isset($form_id)) {
    return;
  }

  $form['francisco_theme_option_sidebar'] = array(
    '#type' => 'details',
    '#title' => t('Sidebar'),
    '#description' => t('Lorem ipsum.'),
    '#open' => TRUE,
  );

  $form['francisco_theme_option_sidebar']['francisco_theme_option_sidebar_footer_cta_title'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Link Title'),
    '#default_value' => theme_get_setting('francisco_theme_option_sidebar_footer_cta_title'),
    '#description'   => t("Lorem ipsum."),
    '#maxlength' => 255
  );

  $form['francisco_theme_option_sidebar']['francisco_theme_option_sidebar_footer_cta_url'] = array(
    '#type'          => 'textfield',
    '#title'         => t('URL'),
    '#default_value' => theme_get_setting('francisco_theme_option_sidebar_footer_cta_url'),
    '#description'   => t("Lorem ipsum."),
    '#maxlength' => 2048,
  );

}

Answer: To add link field (label + url internal/external) & core link widget's url field validation in custom form:
$form['resource_fieldset']['design_tool_link'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'node',
  '#title' => $this->t('Design Tool Link'),
  '#description' => $this->t('Select Design Tool Link'),
  '#required' => TRUE,
  '#element_validate' => [
    [
      'Drupal\link\Plugin\Field\FieldWidget\LinkWidget',
      'validateUriElement',
    ],
  ],
  '#attributes' => [
    'data-autocomplete-first-character-blacklist' => '/#?',
  ],
  '#process_default_value' => FALSE,
  '#default_value' => $design_tool_link ?? : '',
];

 $form['resource_fieldset']['title'] = [
  '#type' => 'textfield',
  '#title' => $this->t('Title'),
];

Note: by adding #element_validate attribute :

Custom Url field 'll accept external & internal links as default core
link widget's URL field do
Also validation of core link 'll applied instead of writing same
validation again

Add link field in custom form


Reset PHP cache via command line

Question: When I try to reset cache from command line with:
php -r "opcache_reset();"

I get the following error message:

Call to undefined function opcache_reset() in Command line code on
  line 1

Is there a way to add the opcache_reset function to PHP via php.ini or something like this?
Thanks for help.
Answer: You need to check your php.ini config files.
Option 1)
Enable the following flag in your opcache config, likely under mods-available
opcache.enable_cli

Option 2)
If you have different config for CLI and apache2/fpm then check the CLI version has enabled opcache

Reset PHP cache via command line


Probability of being inside $p$-dimensional ball

Question: A point $x$ is chosen inside the $p$-dimensional unit ball $B(0,1)$ (centered at the origin) with uniform probability.
What is the probability $P\big(||x||_2<r\big)=P\big(x\in B(0,r)\big)$ where $0\leq r\leq 1$?
I can't figure out how to solve this without first having to come up with a way to write out a general expression for the volume of a $p$-dimensional sphere.
Comment: https://en.wikipedia.org/wiki/Volume_of_an_n-ball
Comment: In general, scaling a $p$-dimensional shape by a factor of $r$ means the volume scales by a factor of $r^p$, so the probability is $r^p$ (and this generalizes to a lot of situations besides hyperspheres and Euclidean metrics).
Answer: Just notice that
$$P(||x||_2 < r) = P(x \in B_r(0))$$
so we just have to find the ratio
$$\frac{|B_r(0)|}{|B_1(0)|}$$
but we know that $|B_r(0)| = r^p|B_1(0)|$ so the answer is $r^p$.
(Is it clear why $|B_r(0)| = r^p|B_1(0)|$?)
Comment: I understand the intuition. But I can also easily write the volume of a hypercube with side length $r$ as $V(r)=r^p$ and see this. It does seem intuitive that for more complicated shapes a proportional scaling by $r$ in all directions will result in a volume scaling of $r^p$. Is the formalization of this intuition all that is needed to show this in general?
Comment: It makes intuitive sense that you are correct about $|B(0,r)| = r^p |B(0,1)|$. However, I don't see mathematically why that is necessarily true for volumes without first having an explicit expression for the volume as a function of $r^p$
Comment: @Dan this is the similarity rule to which you are used to: take a cube. if the length of the sides are doubled, the area of each side becomes $4\times$ larger and the volume becomes $8\times$ larger. This holds true as you move up the dimensions. Is this convincing enough?
Comment: @Dan I would say so, yes. If you are familiar with integrals, you could also do it by first considering that the volume of the ball of radius $r$ is given by $\int_{B_r(0)} 1dx$ and then use a change of coordinates to change that integral into an integral over $B_1(0)$. That will also make the $r^p$ appear.
Comment: Haha the integral was what I was trying to avoid. Cheers
Comment: @Dan Of course, but I am not telling you to solve the integral. I was just asking you to relate $\int_{B_r} 1dx$ and $\int_{B_1}1 dx$, which is easier.


Long form links in an "overview page"

Question: I have a drupal project with a hierarchical page structure. On each category page (top level), I'd like to have a blurb about the category, and then a series of links to subpages, where each link has a title, an image, and a sentence or two, laid out in a box.
I've looked into modules such as "Menu Node Views" and "Node Hierarchy" but I'm not certain that those are the best way to go about doing this. (Right now, as a temporary solution, I've just defined a bunch of blocks each containing an individual link/image/blurb and attached them to the overview pages using contexts).
Can someone suggest a good way to do this? Ideally it could be attached to the menu system in some way so that changes to the menu would be reflected in the appropriate overview page.
(See http://www.freethechildren.com/aboutus/index.php for an idea of the kind of navigation structure I want to display in the page content, although there will be actual content above the link blocks).
Answer: I would simply use content types (cck if you're in d6), views in blocks, taxonomy and some theming. I'm sure there are other ways to do it, but this would maybe be one.
Create a taxonomy 'category' and add all the 'categories' to it.
Create the content types category_page and category_sub_page (or something along those lines).
Create the fields you need for each content type:
For the category_page add a taxonomy tag field (to add the category from your 'category' taxonomy vocab) and if you wish to have images as headers different on each cat page add an image field etc ..
For the sub_page you need 2 or 3 image fields (depending on how many different images you wish to show (1 on the teaser, 1 or 2 on the main page?) and another taxonomy field.
Create your category overview page - tag it.
Create your subpages pages for that cat - tag them too.
Create a .tpl file for your node type:
In d7, copy the node.tpl.php file in your theme/template/ directory twice and name them node--category_page.tpl.php and node--category_sub_page.tpl.php (that's if you used naming conventions like above).
Create a node view that displays node type = category_sub_page and filter them by category, so only display category = 'SOMETHING' - or go even further and use arguments to get tax term of page and show only subpages with the same term (this way you could only use 1 view for multiple category pages). Create a block view from that showing teasers, add it to the content reagion using the blocks page. It should be displayed below the actual page content - if you don't have a region there you will need to add a block region. You'll have to add it to your theme in the page.tpl.php and the theme.info file. Read up about it.
Now edit your theme files for sub_pages .. node--category_sub_page.tpl.php - start it with
<?php if (!$page): ?>

anything in  between here will be shown as the teaser - that's you're menu block with text image - then
<?php endif; ?>
<?php if ($page): ?>

now anything in between is your sub_page full view.
To help you add items use to display the different items called.
 <?php dsm($node); ?>

then add them with php, defining your layout and style classes. Now theme it using css to get your desired look
Now you've create a node that displays sub-nodes in a block below the content.

Long form links in an "overview page"


How to create a modeless dialog from a worker thread when main GUI thread is blocked?

Question: My goal is to write a class (let's call it CProgressDlg) that can be used to display a dialog window with a progress bar when some operation in the main UI thread takes longer than, say 1 second, to finish. So a previously written method:
if(do_work)
{
    for(int i = 0; i < a_lot; i++)
    {
        //Do work...
        ::Sleep(100);     //Use sleep to simulate work
    }
}

can be easily adjusted as something like this (pseudo-code):
if(do_work)
{
    CProgressDlg m_progDlg;

    for(int i = 0; i < a_lot; i++)
    {
        //Do work...
        ::Sleep(100);     //Use sleep to simulate work

        if(m_progDlg.UpdateWithProgress(i))
        {
            //User canceled it
            break;
        }
    }
}

So to implement it I would start a worker thread from the CProgressDlg constructor:
::CreateThread(0, 0, ThreadProcProgressDlg, (LPVOID)0, 0, 0);

And then from a worker thread I would create a modeless dialog that will display the progress bar and a cancel button for the user:
DWORD WINAPI ThreadProcProgressDlg(
  _In_ LPVOID lpParameter
)
{
    //Wait a little
    ::Sleep(1000);

    HMODULE hModule = AfxGetResourceHandle();
    ASSERT(hModule);

    //Get parent window
    //(Can't use main window, as its UI thread is blocked)
    HWND hParentWnd = NULL;

    const static BYTE dlgTemplate[224] = {
        0x1, 0x0, 0xff, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xc8, 0x0, 0xc8, 0x90, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0xdb, 0x0, 0x4b, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x90, 0x1, 0x0, 0x1, 0x4d, 0x0, 0x53, 0x0, 0x20, 0x0, 0x53, 0x0, 0x68, 0x0, 0x65, 0x0, 0x6c, 0x0, 0x6c, 0x0, 0x20, 0x0, 0x44, 0x0, 0x6c, 0x0, 0x67, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x1, 0x50, 0x92, 0x0, 0x36, 0x0, 0x42, 0x0, 0xe, 0x0, 0x2, 0x0, 0x0, 0x0, 0xff, 0xff, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x81, 0x0, 0x2, 0x50, 0x7, 0x0, 0x7, 0x0, 0xcd, 0x0, 0x19, 0x0, 0xed, 0x3, 0x0, 0x0, 0xff, 0xff, 0x82, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0x50, 0x7, 0x0, 0x21, 0x0, 0xcd, 0x0, 0x7, 0x0, 0xec, 0x3, 0x0, 0x0, 0x6d, 0x0, 0x73, 0x0, 0x63, 0x0, 0x74, 0x0, 0x6c, 0x0, 0x73, 0x0, 0x5f, 0x0, 0x70, 0x0, 0x72, 0x0, 0x6f, 0x0, 0x67, 0x0, 0x72, 0x0, 0x65, 0x0, 0x73, 0x0, 0x73, 0x0, 0x33, 0x0, 0x32, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x81, 0x0, 0x2, 0x50, 0x7, 0x0, 0x29, 0x0, 0xcd, 0x0, 0x8, 0x0, 0xee, 0x3, 0x0, 0x0, 0xff, 0xff, 0x82, 0x0, 0x0, 0x0, 0x0, 0x0, };

    //Show dialog
    HWND hDlgWnd = ::CreateDialogIndirectParam(hModule, (LPCDLGTEMPLATE)dlgTemplate, hParentWnd, DlgWndProc, (LPARAM)0);
    ASSERT(hDlgWnd);
    if(hDlgWnd)
    {
        ::ShowWindow(hDlgWnd, SW_SHOW);
    }

    return 0;
}

Where the minimal dialog procedure (just to display it) will be something like this:
INT_PTR CALLBACK DlgWndProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    UNREFERENCED_PARAMETER(wParam);
    UNREFERENCED_PARAMETER(lParam);

    switch (uMsg)
    {
        case WM_INITDIALOG:
        {
        }
        return TRUE;

        case WM_COMMAND:
        {
            UINT uCmd = LOWORD(wParam);

            if (uCmd == IDOK ||
                uCmd == IDCANCEL)
            {
                ::DestroyWindow(hDlg);

                return (INT_PTR)TRUE;
            }
        }
        break;
    }

    return (INT_PTR)FALSE;
}

But when I run this code, my modeless dialog is shown for a split second and then disappears. I understand that I probably haven't done something to display it properly from a worker thread.
Any idea what am I missing?
Comment: Why do you give the heavy work to the GUI thread and the progress bar to the worker thread? Shouldn't it be the other way round?
Comment: Since you're doing the heavy work in the main thread, then it doesn't make sense to create a worker thread for the sole purpose of updating the GUI. It will surely create more problems than solve. That said, if you need to update parts of the `GUI` from a worker thread, you're typically going to post a message using `PostMessage` and have the main thread process this message inside the heavy work loop. Again, this is no better than having the main thread do all the work (in fact, it's worse).
Comment: @Alex: I understand that. Like I said, this a patch for the code that was already written.
Comment: Example: a user clicks on the list column to sort it (a list with a lot of items). In the current code it may block the main thread for about 5 seconds with a spinning mouse cursor. I was thinking to write this class to address situations like that. (It's just one example that comes to mind.)
Comment: Maybe there's a bug that causes the destroy function to be called unintentionally? Does stepping through the code via debug breakpoints leave any clues?
Comment: @Alex: yes, `WM_INITDIALOG` is called once but `WM_COMMAND` is never called. It's something about creating that dialog from a worker thread. If I call it from the main UI thread, everything works fine.
Comment: "So to implement it I would start a worker thread from the CProgressDlg constructor" Starting threads from a constructor is something that caused me problems in the past, because those threads tend to want to access functions from unfinished objects, but not sure if it's a problem in your case.
Comment: Is there a message loop running in that thread?
Comment: @Michael: No. I was thinking that that might be the reason. The code above is all I'm testing with. So how do I create it?
Answer: For a thread to display a window, there must be a message loop so the window receives messages. Worker threads typically do not have message loops, so no window can be displayed. Otherwise, you need to call GetMessage() periodically, a bad practise but it will anyway work. After you get a message, Use TranslateMessage() and DispatchMessage().
Also see Worker thread doesn't have message loop (MFC, windows). Can we make it to receive messages?
Comment: That is the point of GUI threads: to block until you have a message. And that is why it's bad to call it from a thread that is supposed to do other work.
Comment: Well, I can't call `GetMessage` or `PeekMessage` because I don't have a window for that worker thread. Plus `GetMessage` will block execution.
Answer: As others pointed out you cannot simply create windows from non GUI thread. Even if you were able to, you would still have a problem of main thread 'hanging' as you said.
Your have 2 solutions here:
1) Use message pumping technique
2) Move the work into a thread and wait on GUI while showing progress window
Unfortunately both solutions require you to deal with this on case by case basis. You need to manually identify all potentially long operations on GUI and then modify their code.
In both cases I like to use modal dialog for progress bar control because modal dialog blocks access to main UI. This prevents user from interacting with other features until current one is completed.

The most basic way to prevent hanging is to add a function that peeks at message queue and pumps it:

bool CMyGUIWnd::PumpAppMessages()
{
    MSG msg;
    while (::PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)) {
        if (!AfxGetApp ()->PumpMessage ()) {
            ::PostQuitMessage (0);
            return false;
        }
    }

    return true;
}

In any lengthy code (like your column sort) you would need to find places where to sprinkle this PumpAppMessages to keep program responsive.
Of course you don't want to call this all the time and you might want to make sure you only call it after certain number of milliseconds (250 in my example below):
bool CMyGUIWnd::PumpMessages()
{
    //
    // Retrieve and dispatch any waiting messages.
    //
    bool do_update = false;
    DWORD cur_time = ::GetTickCount ();

    if (cur_time < m_last_pump_message_time){
        do_update = true; // wrap around occurred
    }else{
        DWORD dt = cur_time - m_last_pump_message_time;
        if (dt > 250){
            do_update = true;
        }
    }

    if (do_update)
    {
        m_last_pump_message_time = cur_time;
        return PumpAppMessages();
    }

    return true;
}

where m_last_pump_message_time is initialized with ::GetTickCount().
To show progress bar and block UI, you would need to write a progress dialog class which calls your lengthy function once it's created. You would instantiate this dialog before the function and block UI with DoModal call.
void CMyGUIWnd::LengthyCallWrapper()
{
    CProgressDlg dlg (&LengthyCall);
    dlg.DoModal();
}

void CMyGUIWnd::LengthyCall()
{
    // Long process with lots of PumpMessages calls to keep UI alive
}

The second approach is a bit more work, but makes the UI more responsive because it doesn't depend on how often message pumping is done.

You would again use the progress dialog class which takes the lengthy function pointer and executes it in worker thread. Once the thread is finished it should post a message to dialog. In response to this message the dialog would close itself unblocking UI.
For actual progress reporting in both cases your LengthyCall should take a pointer to the progress dialog so that it could update proper controls. In the second approach you would need to add sync objects like CCriticalSection when setting any progress variables but you would not modify any controls directly. Instead, you would setup a timer and check and update progress controls in regular intervals based on provided variables.
Hope this helps.
Comment: Hey, I appreciate your input.
Comment: But have you tried it? I've used both approaches in commercial software for at least 15 years now. As I said, there's no magic bullet when it comes to GUI thread on Windows. If you want to show progress for long task on GUI, you need to interrupt it, otherwise you move it to worker thread and and talk back to UI.
Comment: No, I haven't. I implemented it myself some time ago. I think I posted my solution somewhere in comments. Basically I create a message loop in my worker thread that allows to create its own popup window that lets a user see progress and cancel if needed. The main thread periodically calls an update function that notifies the worker thread of its progress, checks the `stopNow` event if it needs to quit and also  does this: `PeekMessage(&msg, hMainThreadWnd, 0, 0, PM_NOREMOVE);` to prevent GUI thread from showing "Not responding" in the title bar for the locked GUI thread.
Comment: I understand that this is not an ideal solution, as it doesn't allow GUI thread to process its drawing messages, which has a side effect of the main window becoming grayed out if the user starts heavily interacting with it. But, on a plus side, such approach can be included into already working code with just 2 or 3 lines of code without doing anything else. Thus I'm going with it.
Answer:
CreateDialogIndirectParam(...)
ShowWindow(...)

CreateDialog returns immediately, the thread exits after ShowWindow, and so the mode-less dialog closes because the thread is finished.
This is different than DialogBox, DialogBoxIndirect which have their own message loop, and do not return until the dialog is closed by the user or another message.
The usage for CreateDialog, CreateDialogIndirectParam... is as follows:
CreateDialogIndirectParam(...)
ShowWindow(...)

MSG msg;
while(GetMessage(&msg, NULL, 0, 0))
{
    if(hDlgWnd == 0 || !IsDialogMessage(hDlgWnd, &msg))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

In this case you can just borrow a window from GUI thread. Example:
class CProgressDlg : public CDialog
{
public:
    bool stop;
    CProgressDlg() { stop = false; }
    void OnCancel()
    {
        stop = true;
        CDialog::OnCancel();
    }
};

UINT WorkerThread(LPVOID ptr)
{
    CProgressDlg* dlg = (CProgressDlg*)ptr;
    for(int i = 0; i < 10; i++)
    {
        Sleep(1000);
        if(dlg->stop)
        {
            dlg->MessageBox(L"stopped");
            break;
        }
    }

    dlg->SendMessage(WM_COMMAND, IDCANCEL);
    return 0;
}

void CMyWindow::foo()
{
    m_progress.Create(IDD_PROGRESS, this);
    m_progress.ShowWindow(SW_SHOW);
    AfxBeginThread(WorkerThread, (LPVOID)&m_progress);
}

Comment: Thanks, but that's not that easy. What seemed to have happened is this. A modeless dialog uses the message loop of its parent window. Another stipulation seems to be that the parent window's `WndProc` must be in the same thread. So in my case when `CreateDialogIndirectParam` was called, it didn't find any message loop associated with the thread and thus some internal check made it self-destruct. The workaround was to create a message loop. Unfortunately it's easier said than done.
Comment: I basically ended up registering a custom class from a worker thread, then created a message-only window of that class and thus had it have its own message loop in that worker thread. Then, I could communicate with that thread using `SendMessage`/`PostMessage` mechanism from the main thread (prior to it going into a long processing.) Then using one of the custom `WM_APP+n` messages I was able to notify my thread to call `CreateDialogIndirectParam` as I showed above. But that still had some surprises in store associated with the fact that my main GUI thread's message loop was hanging ....
Comment: i.e. if I specified `HWND` of the "hanging" main thread as a parent window for either `CreateDialogIndirectParam` or `ShowWindow`, both functions would hang when trying to display my window until the main thread became responsive. (Thus defeating the purpose of my exercise here.) I guess both APIs communicate with the parent window using `SendMessage` of sorts. So the only way to display my modeless window was to use `NULL` as a parent, which unfortunately had its own negative consequence of dis-joining it from its parent window. Which I haven't overcome yet ...
Comment: The thread has finished and so the window associated with that thread is destroyed. You can't have a window that's associated with a thread which no longer exists; or a process which no longer exists.


Bootstrap Modal alteração e Ajax ASP.NET?

Question: Desenvolvi uma funcionalidade básica no controller asp.net MVC onde eu tenho uma lista de produto e é alterada no Back-End e no front-End utilizo o Bootstrap-Modal pra carregar o produto e alterar, o modal carrega o produto perfeitamente, o problema é que na hora de salvar, eu não estou conseguindo deixar a página AJAX quando o usuário da um salvar no modal, no back-end tudo funciona perfeito e devolvo um Json no intuito de deixar a página Ajax, porém não estou conseguindo pegar esse Json no Front-End e deixar Ajax.
Lista de Produtos:
@model IEnumerable<CaelumEstoque.Models.Prod>

        @Html.DisplayNameFor(model => model.Codigo)

        @Html.DisplayNameFor(model => model.Descricao)

        @Html.DisplayNameFor(model => model.Preco)

@foreach (var item in Model)
{

            @Html.DisplayFor(modelItem => item.Codigo)

            @Html.DisplayFor(modelItem => item.Descricao)

            @Html.DisplayFor(modelItem => item.Preco)

                Detalhe

                @*<button class="btn btn-default details" data-id="@item.Codigo"></button>
                <button class="btn btn-danger delete" data-id="@item.Codigo"></button>
                <button class="btn btn-primary edit" data-id="@item.Codigo"></button>*@

        }

Modal para editar o produto.
@model CaelumEstoque.Models.Prod
@{
    Layout = null;
}

         @using (Html.BeginForm("ParcialEdit","Prod"))

         {

                <button type="button" class="close" data-dismiss="modal">×Close</button>

Editar produto

                    @Html.ValidationSummary(true)

                        @Html.LabelFor(model => model.Codigo, new { @class = "control-label col-md-3" })

                            @Html.TextBoxFor(model => model.Codigo, new { @class = "form-control", @readonly = "readonly" })
                            @Html.ValidationMessageFor(model => model.Codigo)

                        @Html.LabelFor(model => model.Descricao, new { @class = "control-label col-md-3" })

                            @Html.TextBoxFor(model => model.Descricao, new { @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.Descricao)

                        @Html.LabelFor(model => model.Preco, new { @class = "control-label col-md-3" })

                            @Html.TextBoxFor(model => model.Preco, new { @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.Preco)

                <input type="submit" value="Salvar" class="btn btn-primary salvar" />
                @*<input type="button" value="Salvar" class="btn btn-primary salvar" data-url="@Url.Action("ParcialEdit", "Prod", new {p =  Model })" /> *@
                    <input type="button" value="Cancelar" class="btn btn-default" data-dismiss="modal" />

            }

Controller
using CaelumEstoque.DAO;
using CaelumEstoque.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CaelumEstoque.Controllers
{
    public class ProdController : Controller
    {

        public static List<Prod> _listaProdutos = new List<Prod>()
        {
            new Prod { Codigo=01, Descricao="Produto 1", Preco=10 },
            new Prod { Codigo=02, Descricao="Produto 2", Preco=15 },
            new Prod { Codigo=03, Descricao="Produto 3", Preco=20 }
        };
        // GET: Prod
        public ActionResult Index()
        {

            IList<Prod> lista = _listaProdutos;

            return View(lista);
        }

        public ActionResult Details(int id) {

            var existe = _listaProdutos.Find(x => x.Codigo == id );

            ViewBag.Detalhes = existe;
            return View("parcial",existe);
        }

        public ActionResult Edit( int id) {
            var existe = _listaProdutos.Find(x => x.Codigo == id);

            //return Json( registro);
            return View(existe);
        }

        public ActionResult ParcialEdit(Prod p)
        {
            var registro = _listaProdutos.Find(x => x.Codigo == p.Codigo);
            registro.Descricao = p.Descricao;
            registro.Preco = p.Preco;

            //return Json(registro);
            //return RedirectToAction("Index");
            //return Json(new {"/Prod/Index" });
            //return Json(new { Title = "abc", Summary = "Summary", Magazine = "This is magazine", Url = "Index" }, JsonRequestBehavior.AllowGet);
            return Json( registro );
        }

        public ActionResult parcial() {
            return View();
        }

    }
}

Answer: Você deve fechar o modal ao final de todo o processo, no click do botão.
Modal de edição do produto

Comment: Obrigado pela resposta Cassio, só não entendi qual é o id $('#myForm') que eu tenho que pegar, visto que neste momento estou na página do Modal e no caso abaixo quando peço pra esconder meu modal $('#myModal').modal('hide') o '#myModal' está na página principal como iria chamar esse Id estando na página Modal.
Comment: Desculpe, este é o nome do seu modal, que no seu caso é "modal", que esta na sua lista de produtos.
Comment: Certo, ele retorna 'Registro salvo com sucesso.' mas continua retornando o Json no browser, sabe se eu preciso mudar o retono no controller? http://prntscr.com/fv9utv
Comment: Muda seu método que retorna um JsonResult para um Void()


Which of the following staements are true (NBHM-$2014$)

Question: Let $A \in \mathrm{GL}\,_n(\mathbb R)$ have integer entries. Let  $b \in \mathbb R^n $ be a column vector also with integer entries. Then

If $Ax = b$ , then entries of $x$ are also integers.
if $Ax = b$ , then the entries of $x$ are rational.
The matrix $A^{-1}$  has integer entries  iff  $\det(A) = \pm 1$.

For (1)  is false  by Cramer's Rule.
For (2)  is true by Cramer Rule.
For (3), I think it is also true.
Thank you for sparing your valuable time in checking my solutions
Comment: What is NBHM-2014?
Comment: $NBHM$ means national board of higher mathematics which is conducted an exam for phd programme in INDIA
Comment: They all seem correct.
Answer: I think you are right. Since ${A^{ - 1}}$ has integer entries, $det({A^{-1}})=det(A)^{-1}$ is an integer. It's true only for neither $det(A)$ is 1 or -1. By the formula ${A^{ - 1}} = \frac{{{A^ * }}}{{\det \left( A \right)}}$, the other hand holds.


How to print sid value in webform?

Question: I have created a form using webform module, and alter form In D7
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  global $user;

  if('webform_client_form_1' == $form_id) {

    $form['#validate'][] = 'mymodule_check_email';

  }

}

function mymodule_check_email($form, &$form_state, $form_id) {

.............

.............

}

I write print_r($form_state); in mymodule_check_email function.
Get all variables but sid value is empty but in database sid insert proper.
My question how to get sid value.
Comment: Which version of webform are you using ??
Comment: webform 7.x-3.19
Answer: The sid won't be available from a validation handler; validation handlers are called before form submission, thus a valid sid for your submission doesn't exist at time of execution.
If you need to call a post-submit webform hander, the webform module provides hook_webform_submission_insert():
function mymodule_webform_submission_insert($node, $submission) {
  // The submission object contains $submission->sid, the submission id.
  print_r($submission);
}

Comment: yes, this is right answer vote up.

How to print sid value in webform?


Dynamic Audio Generation Actionscript 3

Question: I'm looking into making a music theory lab application, where you can see the graphical relation between music theory concepts. I would like this to be available online, so Flash and Silverlight come to mind.
But I would like to dynamically generate tones and chords etc from user input. This is something I know is a very underdeveloped area in the Flash Player. So my question is what is the current state of features for dynamic audio generation on both the Flash and Silverlight players?
Answer: From Flash Player 10 and onwards you don't need to do any hacky type stuff. There is an API to generate sound dynamically.
This blog post has a quick introduction. His code reads samples from an mp3 but you can write samples any way you want to.
As always the docs have lots of info too, along with this code sample which should get you going pretty quickly.
<code>var mySound:Sound = new Sound();
function sineWaveGenerator(event:SampleDataEvent):void {
    for ( var c:int=0; c<8192; c++ ) {
        event.data.writeFloat(Math.sin((Number(c+event.position)/Math.PI/2))*0.25);
        event.data.writeFloat(Math.sin((Number(c+event.position)/Math.PI/2))*0.25);
    }
}

mySound.addEventListener(SampleDataEvent.SAMPLE_DATA,sineWaveGenerator);
mySound.play();
</code>
Comment: You can also find a lot of interesting source codes and samples at http://lab.andre-michelle.com/
Answer: You may try out The Synthesis ToolKit in AS3 which is ported from C++ by me :)
It's different from standingwave and popforge, STK in AS3 provides real-life instruments like flute and clarinet for you to use which the first two don't.
Answer: There are ways to do it which involves a fair bit of hacking. I don't remember the exact mechanics, but you could have a look at (or use) existing streaming libraries like StandingWave:
http://code.google.com/p/standingwave/
or the stuff at Popforge:
http://code.google.com/p/popforge/
It can hopefully give more information than I can right here. :)
Comment: @Dentoid Thanks for the links I'll give them a look and see what they can do for me
Answer: So it seems that out of Silverlight and Flash, that Flash beats Silverlight on dynamic audio generation features, (which surprised me considering how basic audio support is in Flash). It seems Silverlight cannot generate dynamic audio at all, and Flash can only do so officially since version 10 of the player.
I can find very little information on the future of dynamic audio on both platforms, but Flash has the most active discussions at the moment.

Dynamic Audio Generation Actionscript 3


Why does the conductor also play harpsichord when there is already a harpsichordist in the orchestra?

Question: When listening to Baroque chamber music, it is not uncommon to see the harpsichordist or the soloist being also the conductor.
However, there were two harpsichords in this concert, one dual manual for the harpsichordist and one single manual harpsichord for the conductor.
It is my first time to see setting like this. Why are there two harpsichords? Isn't it redundant (Since there is already a harpsichordist to play the basso continuo part, what is the point that the conductor also plays the same thing again)?
Answer: If you look at the scores for Corelli's concerti grossi, for example, you can see that the concertino (soloists) and the tutti (full orchestra) each have their own basso continuo parts. These continuo parts mostly coincide, but sometimes differ. The reason for this arrangement is not known for certain, but it could have something to do with fullness of sound (a single harpsichord doesn't carry far in a church or similar environment), or with the convenience for the soloists of having their own continuo section within earshot, so to say, especially if there is some distance between soloist and orchestra. (A popular arrangement in a church, for example, was to put the orchestra near the altar (perhaps with a harpsichord continuo), and the soloists in the organ loft, or vice versa.)
Another consideration could be this: since in most baroque compositions the continuo plays more or less constantly, it must be pretty tiring for one harpsichordist to play all of it. Hence the need to alternate between two instruments. This was often done in operas; one harpsichord for the orchestral bits and another for the recitatives.
Comment: "Must be pretty tiring" tell that to the violinists. Otherwise I agree.
Comment: "since in most baroque compositions the continuo plays more or less constantly": indeed, that is why it's called "continuo."  In early baroque choral works, the continuo doubles whatever part is lowest and therefore plays continuously.  A nice example is the *Christe eleison* from Monteverdi's *Messa da capella" for 4 voices published in the *Selva morale e spirituale* of 1641.
Comment: @11684  Ha Ha :-) .  Try marching with a tuba
Comment: @CarlWitthoft I shudder just thinking about it! Unfortunately it wasn't invented yet in Baroque times.


Como colorir coluna tipo data de acordo com a data atual

Question: Tenho uma tabela Excel de agendamentos, o que preciso que a cor vá mudando de acordo com a data,a data atual ficara com o tom de vermelho.
 Se a data for maior que a data atual ficara vermelho também (Agendamento vencido).
 Eu tentei a formatação condicional, mais não encontrei onde trabalhar com data nela.
 Segue imagem de como seria:
Comment: Você já tentou esse link: https://www.ablebits.com/office-addins-blog/2014/06/17/excel-conditional-formatting-dates/
Answer: Você pode utilizar a formatação condicional, só que você invés de utilizar uma célula, você pode comparar à formula HOJE()

E se desejar ver outras formatações, tem esse link: https://www.ablebits.com/office-addins-blog/2014/06/17/excel-conditional-formatting-dates/
Comment: Perfeito,Obrigado !


What are the techniques to deal with classifying sparse categorical features?

Question: Suppose I have a group of features each one is sparse with a few number of values (1-10) what are the required preprocessing steps required to avoid degradation of the performance of the classifier especially if the number of features is moderate and the data is not very large?
Comment: in general it would be recommended to recategorise into meaningful categories (which will not be sparse) - eg rather than having a list of 100 jobs recategorise into manual/office worker... and use hierarchies etc. basically you probably know a lot about the categories that is not available to the learning algorithm.
Answer: As far as I know you can use penalized methods like, Lasso (for variable selection) and Elastic Net (for grouping). Look at this http://en.wikipedia.org/wiki/Elastic_net_regularization and references within.


Customizing/theming a created view

Question: I searched a lot on net, but did not find proper answer for the customizing / theming  a view that is created. I have created a view like one in screenshot . I wanted to change the way the pagination appears and some cosmetic changes for it. So whats the best way to do it.
Answer: Use the unformatted style, instead of the table style. Then use CSS in your theme and you can style it any way you want. Should you want to change the html (I hardly ever need it), try rearranging the view or using the suggested templates.

Customizing/theming a created view


React.js Flux add, make Client's Browser automatic update to latest code

Question: Right now when we deploy new versions of our server and client code to production we have to tell every single user to do a hard refresh in their browser to get the latest code.
This is really annoying to our users, having to constantly tell them or ask them "Did you refresh?" or "Did you hard refresh?"
It should be automatic. With other web technologies this wouldn't be a problem, but with React.js Cache stores etc it is very difficult.
Answer: This sounds like an issue not with React, but with your caching mechanism. If you need users to do a hard refresh then something is going wrong with how you cache your site.
If you can't make any changes to caching then why don't you store a hash of your bundle on the client and when they enter the site, compare that with the latest hash, if they're the different then request a few set of code down from the site.
Comment: Thanks for your post. We do nothing to make the browser cache, not cache. This is 1000% a React.js thing. I have made many Java Enterprise web sites in my life and this is the 1st to ever not automatically update the UI side of things when we deployed.

I don't understand what you mean about hash of your bundle?
Comment: The browser will not automatically download a new bundle.js when you deploy the new code.


One nginx rules for lots of subdomain

Question: I have lots of subdomain in a server. Every subdomain has its own Drupal boost rules, like in below codes:
server {
    server_name  subdomain1.website.com;
    location / {
        root   /var/www/html/subdomain/subdomain1.website.com;
        index  index.php;
        set $boost "";
        set $boost_query "_";
        if ( $request_method = GET ) {
          set $boost G;
        }
        if ($http_cookie !~ "DRUPAL_UID") {
          set $boost "${boost}D";
        }
        if ($query_string = "") {
          set $boost "${boost}Q";
        }
        if ( -f $document_root/cache/normal/$host$request_uri$boost_query.html ) {
          set $boost "${boost}F";
        }
        if ($boost = GDQF){
          rewrite ^.*$ /cache/normal/$host/$request_uri$boost_query.html break;
        }
        if (!-e $request_filename) {
          rewrite  ^/(.*)$  /index.php?q=$1  last;
          break;
        }
    }
    location ~ \.php$ {
            fastcgi_pass    127.0.0.1:9000;
            fastcgi_index   index.php;
            fastcgi_param   SCRIPT_FILENAME /var/www/html/subdomain/subdomain1.website.com$fastcgi_script_name;
            include         fastcgi_params;
    }
}

I adding all subdomain rules manually from time to time. The size of ngin.conf has become too big.
So,
I need one nginx rules which do:
subdomain1.website.com pointing to /var/www/html/subdomain/subdomain1.website.com
subdomain2.website.com pointing to /var/www/html/subdomain/subdomain2.website.com
subdomain3.website.com pointing to /var/www/html/subdomain/subdomain3.website.com

...and so on
(So that no more adding rules for subdomain .website.com I need in the future.)
Answer: You need to use paths like a
root   /var/www/html/subdomain/$host;
fastcgi_param   SCRIPT_FILENAME /var/www/html/subdomain/$host$fastcgi_script_name;

One nginx rules for lots of subdomain


Logical formula with natural numbers

Question: How to write a formula using only quantifiers, variables, brackets, logical operators and $\in$, $\mathbb{N}$, $+$, $\cdot$, $=$, $\leq$ :
Among any three natural numbers exist pair of them such difference beetween them is nonnegative and even?
Is it possible to write it with only quantifiers, variables, brackets, logical conjunction and $\in$, $\mathbb{N}$, $+$, $=$?
Comment: Are you sure that neither negation nor disjunction is allowed?
Comment: If we had disjunction we could say $\forall a,b,c\in\mathbb N\,(\varphi(a,b)\lor\varphi(b,c)\lor\varphi(a,c))$ for some appropriate $\varphi$ ...
Comment: x @Jerry: In that case you can build disjunctions out of negation and conjunction, using De Morgan's laws.
Comment: negations are allowed.
Answer: $(\forall a,b,c \in \mathbb{N}) (\exists x, y \in \{a, b, c\},\; x\neq y)(\exists n \in \mathbb{N}) \; x-y = 2n$
Comment: That doesn't satisfy the conditions -- there's a $\neq$ and negation is not allowed.
Comment: Then we wouldn't be able to specify that $a,b,c$ need to be natural numbers so it's not possible (also changed $\mathbb{R}, \mathbb{Z}$ to $\mathbb{N}$).
Comment: On the other hand "such that" is part of how you pronounce $(\exists x) \varphi$ -- you don't need a separate symbol for it.
Comment: Sorry but i can't use ≠. how to write without it?
Comment: To get rid of the $\neq$ is there a way to directly say that there exists *distinct* $x,y \in \{a,b,c\}$?
Comment: Negation is allowed, forget it.
Comment: To be "precise", we have to rewrite $x−y=2n$ as $x=y+2n$.
Comment: And even so, this is not equivalent to the prose formulation. It is false for $a=b=c=5$, for example, where the difference between $a$ and $b$ **is** nonnegative and even.

Logical formula with natural numbers


Error when deploy uwp application (DEP0001 : Unexpected Error: -2147009290)

Question: When I try to deploy my uwp application to my device(OS:windows phone 10), this error appears "DEP0001 : Unexpected Error: -2147009290"
I have read some similar question, like this? But maybe it can not help me.
Can anyone help me to figure out?
Thanks
Comment: The error code is `0x80073cf6` in hexdecimal display. It has the symbolic constant `ERROR_INSTALL_REGISTRATION_FAILURE`. [Troubleshooting packaging, deployment, and query of Windows Store apps](https://msdn.microsoft.com/en-us/library/hh973484.aspx) offers steps to further diagnose the issue.
Comment: I was facing the same issue all of a sudden.. Restarting my device fixed the issue.. also,try replacing all splashscreen images in the manifest file..
Comment: Have you enabled the developer mode for the device? Have you tried to restart the device? Does your app run on desktop? Not the same error, but may be [worth to try](http://stackoverflow.com/q/36384375/2681948). If possible give also a try to different USB cable. Are you able to deploy any other app/were able before?
Answer: The other post which you linked to did not work for me either.  Not sure if this is your scenario or not, but I already had my app installed on the device from previous builds.  Simply uninstalling it from the phone and then running the deploy again fixed it.


Area in which $x+2{ x }^{ 2 }\sin(\frac { 1 }{ x } )$ is increasing

Question: How would you define the area around $0$ in which:

$f(x)=x+2{ x }^{ 2 }\sin(\frac { 1 }{ x } )$
$(f'(0)=1)$

is increasing?
It's not a neighbourhood of $0$ or an interval which contains $0$.
Comment: Your question is not clear.
Comment: @MhenniBenghorbal yeah, I know. I'll try to edit it and explain.
Comment: @Paz If anything, your edit makes it *less* clear.  You're set is $\{x:f'(x)>0\}$.  You don't need to define it, you need to *describe* it, as you said originally.
Comment: @MarkMcClure: So the only term would be "set"?
Comment: I'm not certain what you mean. I certainly think that the word "set" would be more appropriate than the word "area" in your question.
Comment: @MarkMcClure: I was asking for the mathematical term most accurate to describe these points. I thought there might be a more specific term than "set", but maybe there isn't.
Answer: You might take a look at a plot of the derivative.  It's often positive and often negative in a neighborhood of the origin.  This is why the plot of the function itself has the jagged appearance that it has.  Examining the formula for the derivative itself, it's not hard to see why it's bounces across the $x$-axis infinitely many times in a neighborhood of the origin.


Categorical independent variable and logistic regression

Question: I am creating a logistic regression model as follows. The dependent variable is outcome of a game (Win/Lost) and the independent variable is the degree of MOON on the day of match. So when I take a match, I get the value of Moon in degrees (1 to 360).
I feel that degree is just a measurement from a fixed line of reference point and hence I have to consider the position of Moon as a categorical variable by dividing the 360 degrees into groups and noting the group in which Moon existed during a match.
So I divided the degrees into 12 groups of 30 degrees (based on sun sign) each and note the position of Moon.
Am I right? Can I still divide the whole 360 degrees into 27 divisions (83 or 249 divisions) to get exact information?
Can I have 27 or 83 possible outcome for a single categorical variable?
Let me know if I need to explain my question further.
As of now i have a sample of 900 entries.
Answer: Degree of the moon is not a categorical variable, it is a circular variable. The problem with using it as a continuous variable is not that it is

measurement from a fixed line of reference point

(most if not all measurements are from a fixed line of reference - height is measured from the ground) but that 359 is close to 0 and far from 180.
One method to deal with this would be to use sin(degree) or cos(degree) as your independent variable (a continuous one).
Comment: It is certainly wrong to group the data based on results without some thought as to why this is happening. That's called fishing. If you do that, all your results will be biased.

You can only legitimately do something like that if you do it on a training set and then test it on a testing set.

"If you torture the data long enough, it will confess to anything" - Ronald Coase
Comment: for eg: I observed in my data that between 30 to 36 degrees, the outcome is WIN many times  and from 36 to 42 i observe more LOST matches. Is it wrong to then group the degrees and find which group of Degrees are more beneficial for WIN ?
Comment: Well i grouped the degrees based on Sun sign before attempting any statistical analysis. As my question reads, My main Doubt was treating it as categorical or Not and if i can group them , can i keep 12 or 27 or 83 divisions with just a sample size of 900 matches.
Comment: If your initial hypothesis was "sun sign" then you should use "sun sign". The rest of what you are doing looks like fishing
Comment: I am not using sun signs because it would not have scientific background.. I wish to statistically take the indepedent variable and find if any relation exists. . Its a odd combination idea but my feeling is that if i can scientifically and statistically prove/ disprove it.
Comment: Either you are using sun signs (as you said in a previous comment) or you are not (as you say in this comment).
Comment: @ Peter. So shall i convert the degree into sin( Degree) and then run the Logistic regression? Am i right?
Comment: At this point, I am not at all sure what you are trying to do, but if you think something is related to degrees, then using sin(degree) makes sense.
Comment: ITS A SIMPLE REGRESSION MODEL THAT I AM TRYING TO BUILD( lATER I CAN ADD MORE VARIABLES). The dependent variable is Result of a game (win/loss) and the IV is the position of Moon in Degrees. I have selected the sample ( Around 900)when ever INDIA played. As you say, i will convert the degrees into sin( degrees) and then can i run the Logistic Regression? .
Comment: Yes, that is what I have been saying
Comment: Thanks a lot. I will get back after some analysis. Will you help me to interpret the output? I am using SPSS .
Answer: Aside from the circularity issue and clever sin or cos transforms Peter Flom notes, it's fine to bin a continuous predictor into a categorical factor. The number of factor levels is not an issue so long as you have enough observations in each bin.
You may also find it helpful to create additional predictors, e.g., maybe a feature for right angles, and a feature for deviation from the nearest right angle. Or a zodiac feature. Or something else particular to your game.
Comment: If one is principled in choice of binning procedure, then binning can be a useful way to deal with predictor nonlinearity. It really depends on the predictor and the domain.
Comment: This kind of trying 27 or 83 or 249 is exactly what @PeterFlom is wisely criticizing. It's arbitrary, non-principled, meaningless. But if you use exactly the binning rules in the astrological literature, then you can talk about your model in terms of the literature.
Comment: Sorry, but I disagree with it "being fine to bin a continuous predictor". Such binning inevitably loses power; it also invokes a sort of "magical thinking". I wrote about this on my blog in a post called [perils of categorizing a continuous variable](http://www.statisticalanalysisconsulting.com/the-perils-of-categorizing-continuous-variables/)
Comment: OK, binning based on some theory (or principled choice) can be good, I agree (although I still might prefer a spline model with fixed knots). But what this person seems to be doing doesn't seem to be principled.

e.g., if the variable is "age" then, for some purposes, "Under 18" and "18 and up" makes a lot of sense.

I agree that it "depends on the predictor and the domain".
Comment: Exactly ! I am trying to find if any relation exists between Moons position and the outcome of a game. The astrological literature recommend s that we consider the position of moon by grouping the 360 degrees in groups totaling to 249.
Comment: @ Jack ....Yes when i have 83 divisions i get almost 10 observations in each bin but 249 divisions  gives on an average 4 observations. 27 divisions give almost 25 observations in each bin...... So which one will be the best ?


A question related to $f(n)=n^4+n^2+1$

Question: If $$f(n)=n^4+n^2+1$$ then we have to evaluate $$\frac{f\left(3\right)f\left(5\right)f\left(7\right)f\left(9\right)f\left(11\right)f\left(13\right)}{f\left(2\right)f\left(4\right)f\left(6\right)f\left(8\right)f\left(10\right)f\left(12\right)}$$ which, when run in Desmos, returns 61. But obviously we can't evaluate this with brute force. The farthest I have reached is that $$n^4+n^2+1=n^2(n+1)+\frac{n+1}{n+1}=(n^2+\frac{1}{n+1})(n+1)$$ Any hints?
Comment: $f(n)= (n^2+1)^2-n^2=(n^2-n+1)(n^2+n+1)=(n(n-1)+1)(n(n+1)+1)$
Comment: Don't know if it helps $x^4+x^2+1=(x^2+x+1)(x^2-x+1)$
Answer: We note that $n^4+n^2+1 = (n^4+2n^2+1)-n^2 = (n^2+1)^2-n^2 = (n^2+n+1)(n^2-n+1)$
Writing the value of $(n^2+n+1) = g(n)$, the value of $g(n-1) = n^2-n+1$
So we get eg $f(n)=g(n)g(n-1)$
And  $\frac{f(3)f(5)f(7)...f(13)}{f(2)f(4)f(6)...f(12)}$
is equal to $\frac{g(2)g(3)g(4)...g(12)g(13)}{g(1)g(2)g(3)g(4)...g(12)} = \frac{g(13)}{g(1)}$
This evaluates to $(13*14+1)/(1*2+1)$ or $\frac{183}{3} = 61$
Comment: x^4+x^2+1, is in base x. 1,0,1,0,1.  This is 1,1,1 * 1,-1,1.  So it was immediately seen that this function is the product of 1,1,1 in two consecutive bases.  Since there is a regular step of 2 in both the numerator and denominator, it amounts to simply cancelling out most of them, and leaving what's left.  It's a special case.  x^4-3x+1 also works, as 1,1,-1 * 1,-1,-1.
Comment: How did you know to use this technique? While I can follow each step, I wouldn't have known to combine them in this way. Is it a special case of a more general technique? Is this technique common?
Answer: By using Sophie German Identity
$$f(n)=n^4+n^2+1=n^4+2n^2+1-n^2=(n^2+1)^2-n^2=(n^2-n+1)(n^2+n+1)$$
$$\frac{f\left(3\right)f\left(5\right)f\left(7\right)f\left(9\right)f\left(11\right)f\left(13\right)}{f\left(2\right)f\left(4\right)f\left(6\right)f\left(8\right)f\left(10\right)f\left(12\right)}=\frac{7\times 13\times 21 \times 31\times 43\times 57\times 73\times 91\times 111\times 133\times 157\times 183}{3\times 7\times 13 \times 21\times 31\times 43\times 57\times 73\times 91\times 111\times 133\times 157}=61$$

A question related to $f(n)=n^4+n^2+1$


Javascript confirm box-checkbox

Question: Im interested in how to make a confirm box in Javascript that would be triggered by onchange method on several cboxes.
So i need 2 checkboxes for like ON and OFF values. If someone checks or unchecks one, confirm box will show and if clicked OK, then the state of cbox will change, if not then the value will not be changed. Any ideas?
Thank you.
So far i tried this:
 On
<input type="checkbox" name="output2Radio"  id="output2Radio1" onchange="conf(this);">
 Off
<input type="checkbox" name="output2Radio"  id="output2Radio1" onchange="conf(this);">

Javascript confirm box-checkbox


Basketball throw-in - deflected inbound pass

Question: Player A inbounds the ball but Player B knocks the ball back at him.
Player A is still out-of-bounds when the batted ball hits him.
Is it Team A's ball because Player A never became a "live" player?
Is it Team B's ball because the ball hit him as he was standing out-of-bounds?
Answer: According to (NBA) Rule 8-Section II-c:

The ball is caused to go out-of-bounds by the last player to touch it before it goes out, provided it is out-of-bounds because of touching something other than a player. If the ball is out-of-bounds because of touching a player who is on or outside a boundary, such player caused it to go out. [My emphasis.]

The similar rule in the (FIBA) Official Basketball Rules 2012 is:

23.2.2 If the ball is out-of-bounds because of touching or being touched by a player who is on or outside the boundary line, this player causes the ball to go out-of-bounds.

So, the ball is now Team B's.


Data transformation using ionic pipe

Question: I try to use pipe in ionic project but can't change data, It shows some error.
please suggest a solution for this.
pipe:
@Pipe({
  name: 'statusupdater'
})
export class StatusUpdater {

  transform(value, args) {
    let status=value;
    if(value=='L')
    {
      status='Landed'
    }
    if(value=='A')
    {
      status='Estimated'
    }
    if(value=='C')
    {
      status='Cancelled'
    }

    return status;
  }
}

html:
{{item.status | statusupdator}}

Error:
Comment: Where are you declaring the pipe?
Comment: Maybe this can help you: https://stackoverflow.com/questions/39007130/the-pipe-could-not-be-found-angular2-custom-pipe
Comment: D.Simon i declared in app.module.ts
import {StatusUpdater} from "../pipes/statusupdater";
Comment: Have you added pipe to declarations in module?
Answer: You're missing implementing the PipeTransform interface.
@Pipe({
  name: 'statusupdater'
})
export class StatusUpdater implements PipeTransform {
   ...
}

Answer: You declare it as 'statusupdatEr' but then use it as 'statusupdatOr'.

Data transformation using ionic pipe


Use function shift in pandas dataframe

Question: I have a dataframe with date, previous_day, and price.
DATE       | prev_day |  price
01-01-2018 |    1     |  44
02-01-2018 |    1     |  45
02-01-2018 |    2     |  41
03-01-2018 |    1     |  54
03-01-2018 |    2     |  49
03-01-2018 |    3     |  46

I would like to create the next day and prior day using the next step:
DATE       | prev_day | price | next_day | prior_day
01-01-2018 |    1     |  44   |          |
02-01-2018 |    1     |  45   |          |
02-01-2018 |    2     |  41   |          |
03-01-2018 |    1     |  54   |          |
03-01-2018 |    2     |  49   |          |
03-01-2018 |    3     |  46   |          |

Where the logic consists of each next_day equals the price with DATE + 1 day and prev_day + 1 day, and prior_day equals the price with DATE - 1 day and prev_day - 1 day.
Comment: Please show us an example output dataframe
Comment: The logic for `prev_day` is unclear. What does it refer to? The day of the month? Row index?
Comment: I really suggest you to clarify the question and request to reopen this question. Then you may get other answers that better fit your needs.
Answer: IIUC, you can groupby "prev_day" and shift:
df['prior_day'] = df.groupby('prev_day')['price'].shift()
df['next_day'] = df.groupby('prev_day')['price'].shift(-1)

output:
         DATE  prev_day  price  prior_day  next_day
0  01-01-2018         1     44        NaN      45.0
1  02-01-2018         1     45       44.0      54.0
2  02-01-2018         2     41        NaN      49.0
3  03-01-2018         1     54       45.0       NaN
4  03-01-2018         2     49       41.0       NaN
5  03-01-2018         3     46        NaN       NaN

Comment: @MuriloBarbosa But does the solution really do what you requested? According to your instructions, for the row with `DATE==02-01-2018` and `prev_day==2`, `prior_day` should match the price of `DATE-1` (01-01-2018) AND `prev_day-1`=1 which should match the price=44. However, this solution returns NaN!
Comment: @MuriloBarbosa I'm confused. The row DATE = 02-01-2018 and prev_day=2 DOES exist in above data frame! And also the row with DATE-1 AND prev_day-1 (01-01-2018, 1) as well as DATE+1 AND prev_day+1 (03-01-2018, 3) both exist in the above data frame. The instructions just don't make sense to me. Anyhow, +1 for this answer, despite all lack of clarity. I'm muted.
Comment: @Normanius as DATE == 02-01-2018 and prev_day==2 does not exist in the dataframe, the output will actually be NaN... just like in the case of DATE == 03-01-2018 and prev_day == 3 does not exist in the dataframe, the output will really be NaN
Comment: to get the price value of DATE = 02-01-2018 and prev_day=2 is calculated as follows: DATE - prev_day where the result is 31-01-2018 and this value does not exist in the dataframe, so it receives the value NaN. Was the explanation clearer?
Comment: @MuriloBarbosa Okay, now it's clearer. But compare your explanation with your original question above. It's not the same. Plus: The accepted answer here does not compute what you think it does. Try with different data...

Use function shift in pandas dataframe


How can I fade-out a row (TR) in IE6 or 7

Question: I'm using JQuery to fade-out rows (TR) when the user clicks a Delete button on a row (TR).  By fade-out, I mean the entire row (TR) background-color is changed to an off red and then it fades to white and disappears.  This is a great little animation for showing the user an instant reaction for what the did.
The JavaScript looks like this:
<code>$(tr).css("background-color", "rgb(255,200,200)");
$(tr).fadeOut(500, RemoveDomElement);
</code>
This works beautifully in Firefox, Safari, Opera and Chrome, but - of course - not in IE.  IE will execute the code and finish the cleanup, but the actual fade-out animation isn't shown.
What can I do for IE?
Answer: Fade out (and remove) the child cells (TD) instead of the row.
Do this:
<code>$(tr).children().css("background-color", "rgb(255,200,200)");
$(tr).children().fadeOut(500, RemoveDomElement);
</code>
Even though each of the TDs is doing it's own thing, this will work quickly enough to the human eye to be the same as just fading/removing the TR.
Comment: That means each row fade-out will really be 12 cell fade-outs
Comment: So, what's not to like?  It'll work fast and clean and give off the same effect.
Comment: Absolutely.  IE does not allow you to apply certain css styles to TRs like other browsers do.
Comment: Why are you deleting your answers? They are still visible in the history, so it seems like a lot of trouble for not much gain.
Comment: I've got to ask too, why are you deleting all your non-accepted answers?
Comment: This looks nice in IE8 and worked as desired. Great work around. But in IE8 compatibility mode (should be approx equivalent of IE7) it looks terrible, all the cells change at different rates and it looks very rough. But in IE8 normal mode, then fadeIn() doesn't bring them back after fadeOut(). So once they're gone, they're gone. But in compatibility mode, of course faceIn() DOES bring them back!!! Stupid IE8. I've found so many holes in it its not funny lately. When will the big corporates wake up and stop using it, its nothing but trouble.


Populating Database from Api Response in Php Laravel

Question: please i had been having headache in trying to access this Api Response from Guzzlehttp, the Format is the Problem here, i dont understand i need help.
Hello Guys! please i had been having headache in trying to access this Api Response from Guzzlehttp, the Format is the Problem here, i dont understand i need help.
this is the code

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use GuzzleHttp\Client;
use App\Country;
use App\Globas;

class DataController extends Controller
{
public function getClient(){
  $client=new Client();
  $response = $client->request('GET', 'https://api.covid19api.com/summary');
  $data= json_decode($response->getBody()->getContents(),true);

//delete all row in the database table
Globas::truncate();
Country::truncate();
  foreach($data as $da){
   Globas::create($da);
   Country::create([
       'Country'=> $data['Country'],
       'CountryCode'=>$data['CountryCode'],
       'Slug'=>$data['Slug'],
       'Date'=>$data['Date'],
       'NewConfirmed'=>$data['NewConfirmed'],
        'TotalConfirmed'=>$data['TotalConfirmed'],
           'NewRecovered'=>$data['NewRecovered'],
              'TotalRecovered'=>$data['TotalRecovered'],
               'NewDeaths'=>$data['NewDeaths'],
               'TotalDeaths'=>$data['TotalDeaths']
   ]);
return $data;
  }
}

}

**This is the Response**

{"Global":

{"NewConfirmed":259470,"TotalConfirmed":19636772,"NewDeaths":5457,"TotalDeaths":726765,"NewRecovered":201182,"TotalRecovered":11938458},"Countries":[{"Country":"Afghanistan","CountryCode":"AF","Slug":"afghanistan","NewConfirmed":39,"TotalConfirmed":37054,"NewDeaths":5,"TotalDeaths":1312,"NewRecovered":57,"TotalRecovered":25960,"Date":"2020-08-09T17:38:36Z","Premium":[]},

......

{"Country":"Zimbabwe","CountryCode":"ZW","Slug":"zimbabwe","NewConfirmed":124,"TotalConfirmed":4575,"NewDeaths":0,"TotalDeaths":102,"NewRecovered":71,"Total``Recovered":1416,"Date":"2020-08-09T17:38:36Z","Premium":[]}],"Date":"2020-08-09T17:38:36Z"}

**Country Model**

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
   protected $fillable=['Country','CountryCode','Slug','Date',
   'NewConfirmed', 'TotalConfirmed','NewRecovered','TotalRecovered','NewDeaths','TotalDeaths'];
}

**Globas Model**

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Globas extends Model
{
   protected $fillable=['NewConfirmed','TotalConfirmed','NewRecovered','TotalRecovered','NewDeaths','TotalDeaths'];
}

Thank you...
Answer: i am get the ErrorException (E_NOTICE)
Undefined index: NewConfirmed
when i did something like this
 foreach($data['Countries'] as $country){

     $counter=   Country::create([
               'Country'=> $country['Country'],
               'CountryCode'=>$country['CountryCode'],
               'Slug'=>$country['Slug'],
               'Date'=>$country['Date'],
               'NewConfirmed'=>$country['NewConfirmed'],
                'TotalConfirmed'=>$country['TotalConfirmed'],
                   'NewRecovered'=>$country['NewRecovered'],
                      'TotalRecovered'=>$country['TotalRecovered'],
                       'NewDeaths'=>$country['NewDeaths'],
                       'TotalDeaths'=>$country['TotalDeaths']
           ]);

            }

   foreach($data as $da){
    $globals=Globas::create([
        'NewConfirmed'=>$da['NewConfirmed'],
        'TotalConfirmed'=>$da['TotalConfirmed'],
                       'NewRecovered'=>$da['NewRecovered'],
                          'TotalRecovered'=>$da['TotalRecovered'],
                           'NewDeaths'=>$da['NewDeaths'],
                           'TotalDeaths'=>$da['TotalDeaths']
    ]);

    }
}

Answer: You have to assign a variable to the return of Global::create() and Country::create(). Like so $global = Global::create(...) the run $global->save() to store it in the database.
Edit: Based on you latest reply, your iterating over the data, when you shouldn't because the data returned is not an array. For globals, you don't need to iterate. You can do something like this:
$response = $client->request('GET', 'https://api.covid19api.com/summary');
$data = json_decode($response->getBody()->getContents(),true);

$globals=Globas::create([
    'NewConfirmed'=>$data['NewConfirmed'],
    'TotalConfirmed'=>$data['TotalConfirmed'],
    'NewRecovered'=>$data['NewRecovered'],
    'TotalRecovered'=>$data['TotalRecovered'],
    'NewDeaths'=>$data['NewDeaths'],
    'TotalDeaths'=>$data['TotalDeaths']
]);

$globals->save();

foreach($data['Countries'] as $country) {
     $country = Country::create([
               'Country'=> $country['Country'],
               'CountryCode'=>$country['CountryCode'],
               'Slug'=>$country['Slug'],
               'Date'=>$country['Date'],
               'NewConfirmed'=>$country['NewConfirmed'],
               'TotalConfirmed'=>$country['TotalConfirmed'],
               'NewRecovered'=>$country['NewRecovered'],
               'TotalRecovered'=>$country['TotalRecovered'],
               'NewDeaths'=>$country['NewDeaths'],
               'TotalDeaths'=>$country['TotalDeaths']
           ]);

    $country->save();
}

Answer: Inside foreach you should refer to $da variable, not $data in that place:
Country::create([
       'Country'=> $data['Country'],
       'CountryCode'=>$data['CountryCode'],
       'Slug'=>$data['Slug'],
       'Date'=>$data['Date'],
       'NewConfirmed'=>$data['NewConfirmed'],
        'TotalConfirmed'=>$data['TotalConfirmed'],
           'NewRecovered'=>$data['NewRecovered'],
              'TotalRecovered'=>$data['TotalRecovered'],
               'NewDeaths'=>$data['NewDeaths'],
               'TotalDeaths'=>$data['TotalDeaths']
   ]);

another point is that countries is an array too, so you should probably make another foreach for countries.

foreach ($data['Countries'] as $country)
{

}


Shortest distance between parabola and point

Question:
Find the shortest distance between the parabola defined by $y^2 = 2x$ and a point $ E:= (1.5, 0)$.

I can't use the distance formula because I'm missing a set of points $(x, y)$ to plug into. So, instead, I have a normal that passes through the point $E$ from the parabola. Which is the definition of the shortest distance to a point.
$$y - y_1 = m(x - x_1)$$
The slope of the normal is $\frac{1}{y_1}$ by using implicit differentiation and that's where I'm stuck, because I plug the point E into it and I get
$$y_1^2=x_1-1.5$$
How do I prove the shortest distance is $\sqrt{2}$?
Answer: Given a point $P=\left(\frac{y^2}2,y\right)$ of your parabola, consider the line segment joining $P$ to $C=\left(\frac32,0\right)$. The slope of this line segment is $\frac{2y}{y^2-3}$. And the slope of the tangent to the parabola at $P$ is $\frac1y$. Since two lines are orthogonal if and only if one of them is horizontal and the other one is vertical or when the product of their slopes is $-1$, these lines are orthogonal if and only if $y=0$ or $\frac2{y^2-3}=-1$, which means that $y=0$ or that $y=\pm1$. Forget $0$: that's a local maximum. So, the distance from the parabola to $C$ is$$\left\|\left(\frac12,1\right)-\left(\frac32,0\right)\right\|=\sqrt2.$$
Comment: +1 for picture.
Comment: @MatthewLeingang Also for the answer :-)
Answer: For a point $(x,y)$ on the parabola we have that
$$d^2=(y-0)^2+\left(x-\frac32\right)^2=y^2+x^2-3x+\frac94=x^2-x+\frac94$$
and the minimum is attained for $x=\frac12$ thus at the point $(\frac12,1)$ and therefore
$$d=\sqrt{1^2+1^2}=\sqrt 2$$
Comment: Note that there are two points – $(\frac 12, 1)$ and $(\frac 12, -1)$ – where the same minimum distance is attained, see the image in José's answer.
Comment: @PaŭloEbermann Yes of course by symmetry, indeed the distance for y positive or negative is the same $$d=\sqrt{(y-0)^2+\left(x-\frac32\right)^2}=\sqrt{(-y-0)^2+\left(x-\frac32\right)^2}$$
Answer: Any point of the parabola is of the type $(x,Y)$ with $y^{2}=2x$. The distance between $(x,y)$ and $(1.5,0)$ is $\sqrt (x-1.5)^{2}+y^{2}=(x-1.5)^{2}+2x$. You have to find the minimum value of this quantity over all $x \geq 0$. [$x=(y^{2} /2) \geq 0$ on the curve]. Equivalently, you can mimimize teh square of teh distance.  Differentiate and set the derivative equal to 0. You will find that the minimum is attained at $x=/2$. The minumum value is $\sqrt 2$.
Answer: Continuing your method: Instead of considering $y^2 = 2x$, $(1.5,0)$, consider $y=\frac{x^2}{2}, (0,1.5)$ for convenience. The normal line at $(x_0,y_0)$ is:
$$y'=x_0 \Rightarrow y=-\frac{1}{x_0}x+y_0+1\Rightarrow y=-\frac{1}{x_0}x+\frac{x_0^2}{2}+1$$
The normal line must pass through $(0,1.5)$:
$$1.5=\frac{x_0^2}{2}+1 \Rightarrow x_0=1 \Rightarrow y_0=0.5.$$
The distance between $(0,1.5)$ and $(1,0.5)$ is:
$$d=\sqrt{(0-1)^2+(1.5-0.5)^2}=\sqrt{2}.$$
Answer: $y^2=2x;$
Point on parabola: $(x,y)$.
Distance^2 to $(1.5,0)$:
$d^2:=(x-1.5)^2+(y-0)^2=$
$(x-1.5)^2+2x= x^2-x+ (1.5)^2=$
$(x-1/2)^2-1/4 +2.25.= $
$(x-1/2)^2 +2;$
Since the square is $\ge 0:$
$d_{min}=√2.$
Comment: Nice alternative Peter!
Comment: Thanks.Practice in completing the square:))
Answer: In your implicit differentiation, you got $$\dfrac{dy}{dx} = \dfrac{1}{y_1},$$ so $\dfrac{1}{y_1}$ is the slope of the tangent. The slope of the normal is its negative reciprocal: $$-\dfrac{1}{\frac{1}{y_1}} = -y_1$$ With that, you instead get $y_1 = -y_1(x_1 - 1.5)$ as your point-slope equation. Solve this: \begin{align}y_1 &= -y_1(x_1 - 1.5) \\ 0 &= -y_1(x_1 - 1.5) - y_1 \\ 0 &= y_1(-(x_1 - 1.5) - 1) \\ 0 &= y_1(0.5 - x_1)\end{align} So $y_1 = 0$ or $x_1 = 0.5$. Solve $y_1^2 = 2x_1$ to get the other coordinate (since $(x_1, y_1)$ is on the parabola).

If $y_1 = 0$, then $x_1 = 0$. The distance between $(0, 0)$ and $(1.5, 0)$ is $1.5$.
If $x_1 = 0.5$, then $y_1 = \pm 1$. The distance between $(0.5, 1)$ and $(1.5, 0)$ is $\sqrt{2}$. The distance between $(0.5, -1)$ and $(1.5, 0)$ is also $\sqrt{2}$.

The shortest distance among these three possibilities is $\sqrt{2}$.
Answer: A reply to an old comment brought me back here, and I noticed that no one had offered a Lagrange multiplier solution.  You're looking for the minimum of
$$
    f(x,y) = (x-1.5)^2 +y^2
$$
subject to the constraint that $g(x,y) = 0$, where
$$
    g(x,y) = y^2-2x
$$
The critical points satisfy $\nabla f(x,y) = \lambda \nabla g(x,y)$ for some $\lambda$.  Or,
\begin{align*}
    2x-3 &= -2\lambda \\ 2y &= 2 \lambda y
\end{align*}
The second of these implies either $y=0$ or $\lambda = 1$.  If $y=0$, then $x=0$ and $f(0,0) = \frac{9}{4}$.  If $\lambda = 1$, we can substitute it into the first equation and get $x = \frac{1}{2}$.  If $x =\frac{1}{2}$, then $y = \pm 1$, and $f(\frac{1}{2},\pm1) = 2$.  So the minimum value of $f$ is at these two points, and the shortest distance is $\sqrt{2}$.