text:
Q: Difference between Nano and Vim I have recently started using Ubuntu and hence, the terminal.
As text editor, I have used the pre-installed nano. Now I wonder whether I should install and use vim as well.
What are each of those text editors' special features, advantages and disadvantages? Which one is better suited for newcomers, and for what use cases would the other be preferable?

A: In a nutshell: nano is simple, vim is powerful.
If you only want to simply edit some textfiles, nano will be enough. In my opinion, vim is pretty advanced and complicated to use. You should expect some time to get into it before you're able to properly use it.
Funny (but not too unrealistic) quote about vim: (source)

I've been using vim for about 2 years now, mostly because I can't figure out how to exit it.

A: Vim and Nano are completely different terminal text editors.
Nano is simple, easy to use and master while Vim is powerful and tough to master.
To differentiate, it will be better to list some features of them. Since we don't use terminal editors for normal edits or coding, I'm listing some of the most interesting features that help for the way we use them today.
Nano:

*

*Easy to use and master.

*Nano has most of the shortcuts listed at the bottom of the window, making it extremely simple to use.

*Search function

*Search and replace

*"Goto line" command

*Automatic indentation

Vim:

*

*Tough to get started with and master. The editing and command modes will confuse beginners.

*Session recovery

*Split screen

*Tab expansion

*Completion commands

*Syntax coloring

Although I hated Vim when I first met it, now I prefer it over Nano.

A: You don't need vi or vim if you like nano.
Nano is easier to use if you are not familiar with vim.
Vim is similar to vi, which is universal (it installed on almost all unix-like systems), but if you never used it before, you will need to look at some documentation/tutorial before you will be able to do anything with it.

A: I read through the other posts. Initially I would have agreed with them. However, I have taken the time to really learn nano. It is actually quite powerful. For example, you can have syntax highlighting. You just need to configure your .nanorc file. And there are many samples that come on the server in the /usr/share/nano location. Just add an include /usr/share/nano/sh.nanorc line to your ~/.nanorc file for bash shell highlighting.
There are a large number of additional keyboard commands that you can use. I made myself a whole page of shortcuts. It is very much like using Wordstar or other text based word processors of the old days. I find now that I install nano on servers it is not on as one of my first steps because it has become so intuitive for me, and so much more efficient than vi/vim. I would not say it is more powerful, but it is as powerful.
Start with this nano cheat sheet to find a large number of the commands. If you have used emacs you will find this is very similar, but in my mind easier. I don't fault people that still use vim. There have been holy wars for years for vim vs emacs. Adding nano has just added a third very powerful editor to that discussion. But do not discount it as a weak beginners tool.
The big difference is that vim is modal and nano is not. So with vim you are constantly changing between command mode and edit mode. In nano, as in emacs, you are in one mode and your commands use special key combinations. As you use the editor more you will start to learn all the most used commands. And if you use it a lot you will learn most of them. One other note is that for the read file function there are two mode for that. Either it will read a file into the current edit buffer, or into a new buffer to go between. Make sure to look that one up.

A: They're both text editors, but the similarity pretty much ends there. It may seem strange that two text editors could be so different. The key is that they're both specialized text editors, made for two very different tasks. nano and vim (or rather, pico and vi, which they imitate) were designed for writing e-mails and programs, respectively.
You're not meant to spend a lot of time in nano: you go in, you type up your e-mail message (or whatever you were writing), and you get out quickly. Everything is based around getting you in and out as quickly as possible, so you can get back to whatever else you were doing. It goes so far as to list all the functionality at the bottom of the window, so you don't have to waste time looking up help screens. Of course, there's only so much room at the bottom of the window, and so functionality is constrained to whatever can be expressed, alongside all other functionality, in two lines of text. The result is extremely convenient for some things.
You're meant to spend much (if not almost all) of your time in vim, so it tries to stay out of your way while helping you sling large chunks of text around quickly. A basic startup screen gives almost no information, and when you open a file you get only slightly more about where you are. And in both cases, you can't type text straight away: you start in "normal mode" and have to press i to go into "insert mode" first (there are also a few other letters you can press instead of i, offering some variations on this theme, and there are also some other modes I haven't mentioned). The learning curve is extremely steep: it comes with vimtutor to help people out, but some people have gone so far as to write entire games dedicated solely to learning vim's interface. Think about that for a second. An entire game, just to learn how to use a text editor. And people pay for it.
There is no question that nano is better for the newcomer. I'm something of a vim-zealot, and even I can't dispute that one. I've seen vim turn newcomers off of Linux in general. And if you don't plan to do a lot of text-editing, or your text-editing tasks are all fairly light (like, say, writing e-mails), then nano may be all you need.
That said, while mastering vim takes a long time, the return on investment is high. I realize that the rest of this post sounds kind of down on vim, but that's not my intent. You just need to know what you're getting into, because vim is hard. But even its default configuration contains functions that automate a lot of common (and very repetitive) text-editing tasks: you can do with a few keystrokes things that could take many minutes, or even hours, if you had to do them all manually. There are plugins and scripts that take this even further. If you're going to be doing a lot of programming, or similarly long and involved tasks (dissertations, novels, etc), then vim is ultimately the better choice, but you should still figure out nano first: if an emergency comes up and you need to do something before you've figured out the basics of vim, you'll want to be able to drop into something you're comfortable with.
Bottom line: start with nano, and move to vim if nano gets tedious.

A: Vim is powerful, but tough to learn. It is so called "modal editor", as opposed to usual editors, like nano. Vim allows you to reach all text with just a few key presses, so if you have touch-type ability, your movement without a mouse would be even faster than with one.
So, if you do not work with text a lot (e.g. like programmers do), you may stick to whatever common editor. Otherwise I'd suggest you to learn Vim.
It is worth noting that nowadays there's more than one vim. "Vim" become sort of standard which is implemented in many other editors and IDEs as either a checkbox in settings or a plugin. For example, I use Emacs with Evil (a vim-mode plugin).
A side effect of learning Vim that for some reason nobody mentions: if you can't touch-type yet, but wanted to learn it — just learn Vim, and use it everyday. Vim forces you to move without arrows (h,j,k,l instead), and as you can't look at the keyboard every time you move, you would be forced to learn more and more key locations. This is how I learned to touch-type by the way ☺


text:
Q: How to read Git 3-way unified diff output format? Preface
This question is about understanding the basic unified diff output format. Three way diffing and merging is probably something best done from the comfort of a proper GUI merge tool, or at the very least, vim diff mode with plugins like fugitive.vim.
Question
I find that running git diff while merging a conflict produces a diff view that has two columns of pluses and minuses.
It's clear that in comparing three different versions of the same data we'll need more information than when comparing just two. But what do these columns actually mean? There are clearly now a lot more combinations for the possible "bucket" that a given line now belongs to. It used to just be either blank (same), + (added) or - (deleted), and now we have blank, ++, --, + ,  +, - , and  -. And possibly even more that I hadn't seen.

A: You are referring to the 'combined diff format'. This extension of the original uni-diff format deals with two or more files as input and one file as the result merge. This format is described in details as part of the 'combined diff format' section of the git-diff command manual.

A: Note that the git diff "combined diff format", with one column for each of fileN is prepended to the output line to note how X's line is different from it, can be costly to generate.
The recent commit 72441af (April 2014) from Kirill Smelkov is very instructive on how such a diff will now be optimized (for Git 2.x, Q3 2014)

D(A,P2) is huge, because, if merge-base of A and P2 is several dozens of merges (from A, via first parent) below, that D(A,P2) will be diffing sum of merges from several subsystems to 1 subsystem.
The solution is to avoid computing n 1-parent diffs, and to find changed-to-all-parents paths via scanning A's and all Pi's trees simultaneously, at each step comparing their entries, and based on that comparison, populate paths result, and deduce we could skip recursing into subdirectories, if at least for 1 parent, sha1 of that dir tree is the same as in A.
That would save us from doing significant amount of needless work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Child and parent not working I have three circles with the same features except color and position inside a table class, but in the css isn't getting the features the child.

text1

text2

text3

And in the scss:
    .circle{
       width: 84px;
       height: 84px;
       display: inline-block;
       border-radius: 48px;

       .circle-1{
          box-shadow: 0 0 0 5px $b1;
          background-color:$b1;
       }
       .circle-2{
          box-shadow: 0 0 0 5px $b2;
          background-color:$b2;
          margin-left:150px;
       }
       .circle-3{
          box-shadow: 0 0 0 5px $b3;
          background-color:$b3;
          margin-left:300px;
       }
    }

Any help? Thanks!

A: http://jsfiddle.net/ek505903/
It looks is SCSS code, but the .circle class is missing from HTML.

text1

text2

text3

.circle {
   width: 84px;
   height: 84px;
   display: inline-block;
   border-radius: 48px;
   text-align: center;
}

.circle span {
    /*to center the text vertically use the same value as .circle height*/
    line-height: 84px;
}

.circle-1{
  box-shadow: 0 0 0 5px black;
  background-color: red;
}

.circle-2{
  box-shadow: 0 0 0 5px black;
  background-color: green;
  margin-left:150px;
}

.circle-3{
  box-shadow: 0 0 0 5px black;
  background-color: yellow;
  margin-left:300px;
}

A: If you don;t want to modify HTML code, you could try this one:
.circles {
  & > div { // affect direct child div (circle-1,circle-2,circle-3)
   width: 84px;
   height: 84px;
   display: inline-block;
   border-radius: 48px;
 }
 .circle-1{
      box-shadow: 0 0 0 5px $b1;
      background-color:$b1;
   }
 .circle-2{
      box-shadow: 0 0 0 5px $b2;
      background-color:$b2;
      margin-left:150px;
   }
 .circle-3{
      box-shadow: 0 0 0 5px $b3;
      background-color:$b3;
      margin-left:300px;
   }
}


text:
Q: Failed to highlight a selected item on RecyclerView I've a master-details app that has split view screen using Fragments. The master screen is a list containing RecyclerView. Here's the layout XML.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

      <TextView
            android:layout_width="match_content"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:text="Page Title" />

      <android.support.v7.widget.RecyclerView
             android:id="@+id/page_list"
             android:layout_width="match_parent"
             android:layout_height="match_parent" />

</LinearLayout>

And the item row layout xml is as follows.
 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:background="?android:attr/selectableItemBackground"
    android:clickable="true"
    android:id="@+id/item_layout">

<TextView
    android:id="@+id/contact_name"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    />

<Button
    android:id="@+id/message_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:textSize="10sp"
    />
</LinearLayout>

On the adapter class, I created a variable to hold position of selected item
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ListViewHolder> {
     private int selectedPos;

     @Override
     public void onBindViewHolder(ListViewHolder holder, int position) {
       holder.itemView.setSelected(selectedPos == position);
       holder.bind(mData.get(position));
     }

     class ListViewHolder extends RecyclerView.ViewHolder {
         public ListViewHolder(View itemView) {
             super(itemView);
         }
         public void bind(ListEntity entity) {
           //UI rendering
         }
         @OnClick(R.id.layout_campaign)
         public void onItemClicked(View view) {
            notifyItemChanged(selectedPos);
            selectedPos = getLayoutPosition();
            notifyItemChanged(selectedPos);
         }
}

When I click an item on the list, the list item is not highlighted. Looked into quite a few similar posts regarding this issue, but couldn't get it to work. Am I missing anything?

A: If you want to highlight when user press on the row, then just use selectors in the background of your row's parent layout.
row_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
      <item android:state_selected="true"
           android:drawable="@color/red" /> <!-- pressed -->
     <item android:state_pressed="true"
           android:drawable="@color/red" /> <!-- pressed -->
    <item android:drawable="@color/gray" /> <!-- default -->
</selector>

put this xml in drawable and set as background of your parent layout.
Hope it will work :)


text:
Q: Variable value isn't changing according to checkbox value from rtf theme Preparing a bootstrap application to install some msi packages. Have option to choose the packages to install. But the variable value is not changing as per the user selection.
 This is how I use variable in my Bundle.wxs file
<Variable Name="spectrumDb" Persisted="yes"  bal:Overridable="yes"  Value="1"  />
<Variable Name="spectrumGateway" Persisted="yes"  bal:Overridable="yes"  Value="1" />
<Variable Name="spectrumServiceManager" Persisted="yes"  bal:Overridable="yes" Value="1" />
<Variable Name="spectrumIISparts" Persisted="yes"  bal:Overridable="yes" Value="1"  />
<Variable Name="spectrumConnecter" Persisted="yes"  bal:Overridable="yes"  Value="1" />

I have some checkboxes in rtf theme for the user to select components to install
<Page Name="Options">
     <Text X="11" Y="65" Width="-11" Height="30" FontId="2" DisablePrefix="yes">Select components</Text>
     <Checkbox Name="spectrumDb" X="40" Y="120" Width="200" Height="17" TabStop="yes" FontId="3" HideWhenDisabled="no"   >spectrumDb</Checkbox>
     <Checkbox Name="spectrumGateway" X="40" Y="140" Width="200" Height="17" TabStop="yes" FontId="3" HideWhenDisabled="no">spectrumGateway</Checkbox>
     <Checkbox Name="spectrumServiceManager" X="40" Y="160" Width="200" Height="17" TabStop="yes" FontId="3" HideWhenDisabled="no" >spectrumServiceManager</Checkbox>
     <Checkbox Name="spectrumIISparts" X="40" Y="180" Width="200" Height="17" TabStop="yes" FontId="3" HideWhenDisabled="no" >spectrumIISparts</Checkbox>
     <Checkbox Name="spectrumConnecter" X="40" Y="200" Width="200" Height="17" TabStop="yes" FontId="3" HideWhenDisabled="no" >spectrumConnecter</Checkbox>
</Page>

The installer install irrespective of the checkbox value. This is the part of logfile where I find that
[0404:0B44][2018-05-28T08:43:07]i000: Running detect complete custom action
[0404:0B44][2018-05-28T08:43:07]i199: Detect complete, result: 0x0
[0404:178C][2018-05-28T08:43:09]i000: Setting numeric variable 'EulaAcceptCheckbox' to value 1
[0404:178C][2018-05-28T08:43:20]i000: Setting numeric variable 'spectrumDb' to value 1
[0404:178C][2018-05-28T08:43:20]i000: Setting numeric variable 'spectrumGateway' to value 1
[0404:178C][2018-05-28T08:43:20]i000: Setting numeric variable 'spectrumServiceManager' to value 1
[0404:178C][2018-05-28T08:43:20]i000: Setting numeric variable 'spectrumIISparts' to value 1
[0404:178C][2018-05-28T08:43:20]i000: Setting numeric variable 'spectrumConnecter' to value 1

I use wix 3.11 to make this project.
ide is visual studio 2010.
bootstrap application type ref WixExtendedBootstrapperApplication.RtfLicense

A: The bootstrapper will set the variable when it runs this function:
void SavePageSettings(
    __in WIXSTDBA_PAGE page
    )
{
    THEME_PAGE* pPage = NULL;

    pPage = ThemeGetPage(m_pTheme, m_rgdwPageIds[page]);
    if (pPage)
    {
        for (DWORD i = 0; i < pPage->cControlIndices; ++i)
        {
            // Loop through all the checkbox controls (or buttons with BS_AUTORADIOBUTTON) with names and set a Burn variable with that name to true or false.
            THEME_CONTROL* pControl = m_pTheme->rgControls + pPage->rgdwControlIndices[i];
            if ((THEME_CONTROL_TYPE_CHECKBOX == pControl->type) ||
                (THEME_CONTROL_TYPE_BUTTON == pControl->type && (BS_AUTORADIOBUTTON == (BS_AUTORADIOBUTTON & pControl->dwStyle)) &&
                pControl->sczName && *pControl->sczName))
            {
                BOOL bChecked = ThemeIsControlChecked(m_pTheme, pControl->wId);
                m_pEngine->SetVariableNumeric(pControl->sczName, bChecked ? 1 : 0);
            }

            // Loop through all the editbox controls with names and set a Burn variable with that name to the contents.
            if (THEME_CONTROL_TYPE_EDITBOX == pControl->type && pControl->sczName && *pControl->sczName && WIXSTDBA_CONTROL_FOLDER_EDITBOX != pControl->wId)
            {
                LPWSTR sczValue = NULL;
                ThemeGetTextControl(m_pTheme, pControl->wId, &sczValue);
                m_pEngine->SetVariableString(pControl->sczName, sczValue);
            }
        }
    }
}

The SetVariableNumeric function won't log anything for an already existing variable.
You can verify your variables are being set by running your bootstrapper, unchecking a few check boxes, going to the next page, and then cancelling your bootstrapper.
When you close the bootstrapper it logs all variables and their values. In the logs after you close the bootstrapper, you should see that the variables corresponding to the checkboxes you unchecked should now have a value of 0.


text:
Q: ¿Es posible mostrar unos datos determinados? En el código que voy a dejar muestro todos los registros de la tabla oferta, ahora bien, ¿es posible mostrar solo las ofertas de registradas en un día determinado por ejemplo?. Había pensado en hacer otra tabla con esos datos registrados y mostrar los registros de dicha tabla, pero tal vez sea posible mostralos a través de una misma tabla. Dejo el código:

    <ui:composition template="./WEB-INF/Template.xhtml">

         <ui:define name="content">
            <h:outputText value="Total de ofertas:#{ofertasFacadeREST.countREST()}
          "/>

<h:form>

<h:outputText value="Lista de ofertas disponibles"/>

            <f:facet name="header">
                <h:outputText value="Id"/>
            </f:facet>
            <h:outputText value="#{item.id}"/>

            <f:facet name="header">
                <h:outputText value="Nombre"/>
            </f:facet>
            <h:outputText value="#{item.nombre}"/>

            <f:facet name="header">
                <h:outputText value="Descripción"/>
            </f:facet>
            <h:outputText value="#{item.descripcion}"/>

            <f:facet name="header">
                <h:outputText value="Fecha de incorporación"/>
            </f:facet>
            <h:outputText value="#{item.fecha_Insc}"/>

            <f:facet name="header">
                <h:outputText value="Puesto de trabajo"/>
            </f:facet>
            <h:outputText value="#{item.puesto}"/>

            <f:facet name="header">
                <h:outputText value="Requisitos"/>
            </f:facet>
            <h:outputText value="#{item.requisitos}"/>

</h:form>

A: Si, es posible. Primefaces te provee formas de filtrar, con algoritmos ya provistos por el Framework o permitiéndote crear un filter custom.
Para tu caso podrías crearte un método en tu backing bean para poder filtrar las ofertas.

    <f:facet name="header">
        <h:outputText value="Fecha de incorporación"/>
    </f:facet>
    <h:outputText value="#{item.fecha_Insc}"/>

Del lado de tu Backing bean vas a necesitar implementar el método filtrarPorFecha
public boolean filtrarPorFecha(Object value, Object filter, Locale locale) {
//value es el que viene en la columna de tu datable
//filter es la fecha que ingresa el usuario para filtrar
//locale es opcional y lo podes usar o no segun el caso

//debes retornas true si el valor de la columna es aceptado por el filtro
//o false si no, o sea, si el filtro lo deja afuera
}

Por otro lado, algunas recomendaciones.
Tus backing bean no debería tener lógica de negocio, sino de presentación. Y tené en cuenta que JSF es un framework orientado al servidor, muy pocas cosas se resuelven del lado del cliente. Las invocaciones al servicio rest que por lo visto invocas debería estar encapsulada en una capa de servicios. Y el backing bean debería invocar a este servicio para poder armar la pantalla.


text:
Q: Cannot set Column 'name'. The value violates the MaxLength limit of this column I have a table with 5 columns.
They are:
fItemID - Int IDENTITY Primary Key
fItemName - varchar(50)
fItemType - varchar(50)
fItemModel - varchar(50)
fItemWeight - int
When I try to add data to the table, using a DataGridView, I have no problems as long as I keep the values under 10 characters, but when I try to add 11 or more, I get an error message on three of the columns.
For fItemName and fItemType, I get:

Cannot set Column 'name'. The value violates the MaxLength limit of this column.

When I try to add more then 10 characters to fItemWeight, I get:

System.FormatException: Value was either too large or too small for an Int32. ---> System.OverFlowException: Value was either too large or too small for an Int32.

I have no idea why I am getting these errors, as adding info to fItemModel works perfectly.
As usual, I am using VS2013 Ultimate and VB.Net.

The following is all the code for the form:
Public Class frmBOMNonSteel

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'DbStarFliteSystemsDataset.tblItemsQuery' table. You can move, or remove it, as needed.
        Me.TblItemsQueryTableAdapter.Fill(Me.DbStarFliteSystemsDataset.tblItemsQuery)
        'TODO: This line of code loads data into the 'DbStarFliteSystemsDataset.tblItems' table. You can move, or remove it, as needed.
        Me.TblItemsTableAdapter.Fill(Me.DbStarFliteSystemsDataset.tblItems)
        'TODO: This line of code loads data into the 'DbStarFliteSystemsDataset.tblItems' table. You can move, or remove it, as needed.
        Me.TblItemsTableAdapter.Fill(Me.DbStarFliteSystemsDataset.tblItems)
        'TODO: This line of code loads data into the 'DbStarFliteSystemsDataset.tblItems' table. You can move, or remove it, as needed.
        Me.TblItemsTableAdapter.Fill(Me.DbStarFliteSystemsDataset.tblItems)
        'TODO: This line of code loads data into the 'DbStarFliteSystemsDataset.tblItems' table. You can move, or remove it, as needed.
        Me.TblItemsTableAdapter.Fill(Me.DbStarFliteSystemsDataset.tblItems)
        Me.txtJobNumber.Text = frmParent.ToolStripTextBox1.Text

        With FItemTypeComboBox
            .DataSource = DbStarFliteSystemsDataset.tblItemsQuery
            .ValueMember = "fItemType"
        End With
    End Sub

    Private Sub SteelToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SteelToolStripMenuItem.Click

        Me.Close()
        frmBOMSteel.MdiParent = frmParent
        frmBOMSteel.Show()
        frmBOMSteel.WindowState = FormWindowState.Maximized
    End Sub

    Private Sub NonSteelToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NonSteelToolStripMenuItem.Click

        Me.MdiParent = frmParent
        Me.Show()
    End Sub

    Private Sub WeightsRevisionsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles WeightsRevisionsToolStripMenuItem.Click

        Me.Close()
        frmBOMWeightsRevisions.MdiParent = frmParent
        frmBOMWeightsRevisions.Show()
        frmBOMWeightsRevisions.WindowState = FormWindowState.Maximized
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        frmModalNewItem.ShowDialog()
    End Sub

    Private Sub FItemTypeComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles FItemTypeComboBox.SelectedIndexChanged

        Me.FItemNameComboBox.Text = ""

        Dim selected As Object = Me.FItemTypeComboBox.SelectedItem

        If (TypeOf selected Is DataRowView) Then

            Dim row As DataRow = DirectCast(selected, DataRowView).Row
            Dim fItemType As String = CStr(row.Item("fItemType"))
            Dim view As New DataView(DbStarFliteSystemsDataset.tblItems)

            view.RowFilter = String.Format("[fItemType]='{0}'", fItemType)
            Me.FItemNameComboBox.DataSource = view.ToTable(True, "fItemName")
            Me.FItemNameComboBox.DisplayMember = "fItemName"

        End If
    End Sub

    Private Sub TblItemsBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs)
        Me.Validate()
        Me.TblItemsBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.DbStarFliteSystemsDataset)

    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs)
        Me.Validate()
        Me.TblItemsBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.DbStarFliteSystemsDataset)

    End Sub

    Private Sub TblItemsBindingNavigatorSaveItem_Click_1(sender As Object, e As EventArgs)
        Me.Validate()
        Me.TblItemsBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.DbStarFliteSystemsDataset)

    End Sub

    Private Sub TblItemsBindingNavigatorSaveItem_Click_2(sender As Object, e As EventArgs)
        Me.Validate()
        Me.TblItemsBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.DbStarFliteSystemsDataset)

    End Sub
End Class

The following is the code for my Table:
CREATE TABLE [dbo].[tblItems] (
    [fItemID]     INT          IDENTITY (1, 1) NOT NULL,
    [fItemName]   VARCHAR (50) NULL,
    [fItemType]   VARCHAR (50) NULL,
    [fItemModel]  VARCHAR (50) NULL,
    [fItemWeight] INT          NULL,
    CONSTRAINT [PK_tblItems] PRIMARY KEY CLUSTERED ([fItemID] ASC)
);

A: I believe that your adapters are not in sync with the database. You could try remapping or you could try appending this within the load method:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.DbStarFliteSystemsDataset.tblItems.Columns("fItemName").MaxLength = 50
    Me.DbStarFliteSystemsDataset.tblItems.Columns("fItemType").MaxLength = 50
    Me.DbStarFliteSystemsDataset.tblItems.Columns("fItemModel").MaxLength = 50
    '.....
End Sub

Remapping
When you add a DB (database) to your project VS (Visual Studio) creates a strongly typed in-memory cache representing the data. This enables you to use a DataSet in your application with the same schema as your DB. However, if the DB schema changes afterwards (e.g. you have changed a type/length/name of a column), the cache is not updated. In the "Solution Explorer" pane there should be a file named [NameOfDB]DataSet.xsd. Double-clicking this file will open an editor allowing you to edit the DS and all its tables. Ensure it reflects the updated DB schema - close - save - rebuild.

A: I know this is an old post, but for those struggling with a similar issue:
I resolved this by simply deleting the dataset out of the project explorer and re-adding it via the "Add New Data Source" option in the project menu. As long as you don't delete the table references that sit at the bottom of the form editor, you're databindings will be OK.
When you re-add the dataset, it must be called the exact same name as the one you had before you deleted it. If done correctly, any edited columns in the database will now be back in sync.

A: **in the first time you need change the maxlength in your table from DB
try this ( in -VS 2010-)
Go to Solution Explorer
click right on 'YourFile'.xsd/ open
Search & click right on the Column name in conflict
Properties
change MaxLength to your need
Save


text:
Q: How to prompt user that asks a user for a file name? I am going through Intro to Programming so basic stuff here, I have an assignment to "write a program that asks a user for a file name and then displays the first 5 lines of the file," I just can't figure out how to use the input command in this situation and then transfer to open()
Edit: Sorry here is a code snippet I had, I just don't get how to apply input from here.
def main():
    #This function writes to the testFile.docx file
    outfile = open('testFile.docx', 'w')
    outfile.write('Hello World\n')
    outfile.write('It is raining outside\n')
    outfile.write('Ashley is sick\n')
    outfile.write('My dogs name is Bailey\n')
    outfile.write('My cats name is Remi\n')
    outfile.write('Spam Eggs and Spam\n')
    outfile.close()

    infile = open('testFile.docx', 'r')
    testFileContent = infile.read()
    infile.close()
    print(testFileContent)

main()

A: First, we ask for a filename. Then we use the try clause, which checks whether the file exists. If it does it will print 5 lines. If it does not, it will print No such a file found!
x = input('Enter a file name')
try:
    with open(x) as f:
        data = f.readlines()
    for i in range(5):
        print(data[i])
except:
    print('No such a file found!')

A:  input() is used to receive input from the user. Once we recieve the input, we use the open() method to read the file in read mode.
def main():
    file = input("Please enter a file name")
    with open(file, 'r') as f:
        lines = f.readlines()
    print(lines[:5])

The with statement makes sure that it closes the file automatically without explicitly calling f.close()
The method f.readlines() returns an array containing the lines in the file.
The print() statement prints the first 5 lines of the file.

A: Using a simple function,
def hello_user():
    user_input = input('Enter file name: ')
    try:
        with open(user_input, 'r') as f:
            data = f.readlines()

        data = data[:5]
        for o in data:
            print(o.strip())

    except FileNotFoundError:
        print('Not found ')

hello_user()

*

*It asks for a file name

*If the file exists in the same directory the script is running, it opens the file and read each lines (white lines inclusive)

*We select only the first 5 lines

*We iterate through the list and remove the extra whitespace character(e.g \n).

*If the file was not found,  we catch the exception.


text:
Q: Import specific fields into MongoDB from exported mongo json file I want to import an exported json file into existing collection (the same one) using --upsert option, but the problem is that I wanna just update specific fields not all the data. As an example I've a collection named users, I exported it to users.json, then I wanna import this json file into another database which has the same collection, but I want just to import fields like email,username & avatar, so I can keep the other data as it is without any changes. How can I do something like this? Do you've any idea or a quick hack to fix this problem?

A: Here an example. The first request export a JSON file.
The second request import the file with the merge option.
mongoexport --db mydb --collection mycollection --fields field1,field2 --query "add a query if necessary" > test.json

mongoimport --db mydb --collection mycollection --file test.json --mode merge

A: Using python
import pymongo
import json

conn = pymongo.MongoClient()
collection = conn['db']['collection']

for doc in json.load(open('users.json')):
    new_doc = {k: v for k, v in doc.iteritems() if k in ('email', 'username', 'avatar')}
    collection.update({'_id': doc['_id']}, {'$set': new_doc})

A: Limit the fields you export is probably the more elegant approach. There is the --fields flag available in mongoexport:
mongoexport --fields foo, bar, baz

will only export _id, foo, bar and baz.


text:
Q: Change menu based on session value with Angular and Codeigniter I wan't to dynamically display menu items based on session state in codeigniter. Let me show you my code with following explanations.
This is my index.html file

That link data comes out of this controller
sessionFactory.isLoggedIn().then(function(data){
    var loggedIn = data.logged_in;
    if(loggedIn == true){
        $scope.link1 = $sce.trustAsHtml('My profile');
        $scope.link2 = $sce.trustAsHtml('Logout');
    }else{
        $scope.link1 = $sce.trustAsHtml('Login');
        $scope.link2 = $sce.trustAsHtml('Register');
    }
})

This is my session factory
//Factory for Session
app.factory('sessionFactory', ['$http', '$location', function($http, $location){
    var factory = {};

    factory.logOutUser = function(){
        console.log("woot");
        return $http({
            method: 'POST',
            url: $location.protocol() + '://' + $location.host() + '/server/api/users/logout'
        }).then(function successCallback(response) {
            console.log(response);
        },function errorCallback(response) {
            console.log('error logging out: ' + response);
        });
    }

    factory.isLoggedIn = function(){
        console.log("checking login");
        return $http({
            method: 'GET',
            url: $location.protocol() + '://' + $location.host() + '/server/api/users/isLoggedIn'
        }).then(function successCallback(response) {
            console.log(response.data);
            return response.data;
        },function errorCallback(response) {
            console.log('Checking login failed: ' + response);
        });
    }

    /*
    /server/api/users/logoutfactory.currentUserId = function(){
        return $http.get($location.protocol() + '://' + $location.host() + '/server/api/users/userId');
    }
    */
    return factory;
}]);

Api /server/api/users/isLoggedIn returns
{"success":true,"logged_in":true}

or
{"success":true,"logged_in":false}

So i have the problem that when user logs in or logs out

 items don't change. I have to press f5 to refresh web page.
If you need any additional information, please let me know and i will provide.
Thank you in advance.

A: You could fire an event on the $rootScope with
$rootScope.$emit("authenticationChanged")

on your session factory when the user logs in and out and then in the controller run

function checkIfLogged() {
  var loggedIn = data.logged_in;
  if (loggedIn == true) {
    $scope.link1 = $sce.trustAsHtml('My profile');
    $scope.link2 = $sce.trustAsHtml('Logout');
  } else {
    $scope.link1 = $sce.trustAsHtml('Login');
    $scope.link2 = $sce.trustAsHtml('Register');
  }
}
checkIfLogged(); //RUN THE FIRST TIME THE PAGE LOADS

$rootScope.$on("authenticationChanged", function(){
    checkIfLogged(); //RUN WHEN AUTHENTICATION CHANGE
});

For more informations about events check https://docs.angularjs.org/api/ng/type/$rootScope.Scope

A: You can try using functions for getting the link contents:

$scope.getLink1Content = function (loggedIn) {
    var linkContent = loggedIn ? 'My profile' : 'Login';

    return linkContent;
};

$scope.getLink2Content = function (loggedIn) {
    var linkContent = loggedIn 'Logout' : 'Register';

    return linkContent;
}

sessionFactory.isLoggedIn().then(function(data){
    var loggedIn = data.logged_in;

    $scope.getLink1Content(loggedIn);
    $scope.getLink2Content(loggedIn);
});


text:
Q: Should I test private/protected methods? Why? I have a doubt regarding the testing of private/protected methods. This is a general question that addresses unit testing for any platform. But just to tell you, I am working with phpunit a platform to unit test php.
Should we test private/protected methods? Accepted answer on this question says we normally should not.
From that answer :

Usually you just don't test or mock the private & protected methods directy.
What you want to test is the public API of your class. Everything else is an
      implementation detail for your class and show not "break" your tests if you change it.

But at the same time other answers in so many questions provides a way to test them (I assume these answers mean we should test private/protected methods as they don't say that we should or should not test them).
Please explain me with reasons. Thank you.

A: As for me - it depends on complexity of private/protected members.
For example you have private methods Func1() and Func2() with complex computation or algorithms with many input parameters. And you have a public API that uses both them. And on some data Func1() is broken and returns incorrect data, but during processing in Func2() this data somehow converts to correct result (as a result of other issue). Total result of public API method will be correct - that means YOU HAVE INCORRECT Func1 and Func2 but your API returs correct somehow. And you testet it and it's fine.
Now you gave you code to somebody, and he/she created Func3() and one more public API method that uses Func1() and Func3() and unit test for this API method fails. How much time he/she will spend to find out that the reason is in Func1? And when Func1 will be fixed you will have previous test with Func2 failing... That's totaly not good.
So, IMHO you SHOULD test private/protected methods if they are complex (much code or usage of not obvious algo) and reusable. And of course you don't need to create 100 unit tests for private method that returns a + b or writing debug log record.
Hope my answer helps you!
Best regards, Mikhail.

A: Private and protected methods are implementation details of the code under test and should not be tested.  Your tests tell you "what" your code is supposed to do.  Testing private and protected methods starts getting into "how" your code is supposed to do what ever it is doing.
When you modify your class to add some private methods because you found some code reuse and you have tests failing you know that it is because you changed some functionality and need to fix that test case.  If you have tests for private and protected methods and you do the same thing now you need to see if the tests are failing for a valid reason or are from your re-factoring.  The private and protected methods are covered via the tests for the public interface of the class and do not need any tests of their own.
Just because you "can" do something doesn't mean that you "should" do something.
When I am testing, I consider the system under test to be a black box.  I give it something and I expect something to happen.  I do not care about what happens inside.  All that is important is that the correct output is given.
Complicated internal functions are a code smell that perhaps I have my class doing too much and probably has another class hiding inside.

A: I believe the testing of the Private/Protected methods depends on where/how they are accessed, and what is being tested.
If I am building a reusable library of common code, then the private and protected methods within these classes are tested within the library test cases.  These tests ensure that the lower level code works so I can have faith in the library.
Now, when I write a business application that accesses this library, I do not write tests for the library objects, as they will be mocked in the tests for the business application.  The library tests shows that the library works, and then the business application tests show that the application works.
The business application does not try to test the private/protected methods of the library, as I consider that a black box of code that I do not know about (similar to an external library or web service).  I do however test the private and protected methods of the business application in the test suite for the business application, again, to ensure that methods/functions are behaving as they should.
As an example then, assume the following Business Classes (very brief to convey thought, not functions):
<?php
class ACCOUNTS
{
    protected GetEstimation()
    {
        ...
        return $CalculatedValue;
    }
}

class CUSTOMER_ACCOUNT extends ACCOUNTS
{
    protected GetEstimation()
    {
        $BaseEstimation = parent::GetEstimation();
        ...
        return $NewCalculatedValue
    }
}

class RESELLER_ACCOUNT extends ACCOUNTS
{
    protected GetEstimation()
    {
        ...
        return $ResellerCalculatedValue; // Note: No call to parent
    }
}
?>

In this example there are different values that are going to be returned.  The Protected function was used so it could be overridden, and it does not have to rely on the parent class functionality.  In this example, I do want to test all these classes return the proper values when they are used.
The basic ACCOUNTS class should return the Estimation after doing its calculations, based on the class values.  As a rule, I simply set the values and test the returns:
<?php
class ACCOUNTSTest extends PHPUnit_Framework_TestCase
{
    protected $Accounts;

    protected function setUp()
    {
        $this->Accounts = new ACCOUNTS();
    }

    public function testEstimationHome()
    {
        $this->Accounts->InternalValue1 = 1;
        $this->Accounts->InternalValue2 = 10;
        $this->Accounts->InternalValue3 = 100;
        $this->assertEquals(523, $this->Accounts->GetEstimation(), 'Test Home Account with values 1, 10, 1000');
    }

    public function testEstimationHome2()
    {
        $this->Accounts->InternalValue1 = 5;
        $this->Accounts->InternalValue2 = 2;
        $this->Accounts->InternalValue3 = 10;
        $this->assertEquals(253, $this->Accounts->GetEstimation(), 'Test Home Account with values 5, 2, 10');
    }

    protected function tearDown()
    {
        unset($this->Accounts);
    }
}
?>

These tests will now ensure that the ACCOUNTS->GetEstimation() is working correctly.  I would then test CUSTOMER_ACCOUNT, and have similar tests to ensure that the class is calculating correctly.
Yes, if the base class changes, then I might need to update the tests in the CUSTOMER_ACCOUNT since the ACCOUNTS->GetEstimation() changed, but I also have an extra check that the base class is still returning correctly.
Alternately, I could change this structure and use Dependency Injection to provide certain information (ACCOUNTS) to ensure that if the parent estimation was always 523, then this class returns the proper values. If ACCOUNTS changes the estimate returned, and it does not matter to this class (maybe this class is simply adding additional values), then I isolate my test and do not need to worry.
Hopefully this update helps to illustrate what I am saying.


text:
Q: A question in Dynamical systems Considering the discrete time logistic growth model,
$$N_{t+1} = \lambda N_t\left(1-\frac{N_t}{K}\right)$$
where $\lambda = 1+ b -d >0$ is the net reproductive rate and $K>0$ is a parameter that affects how the population grows when the population is large.
I have determined the two equilibrium points of this system which are,
$$N^*=0$$
$$N^* = K\left(1-\frac{1}{\lambda}\right)$$
found the conditions for each of the equilibria that I found above to be unstable.
Here is my explanation below,
$$f'(x) = \lambda -\frac{2x\lambda}{K}$$
Using $x=0$
$$f'(0) = \lambda$$
So it is unstable when $\lambda>1$
Using $x = K\left(1-\frac{1}{\lambda}\right)$ it is unstable when $\lambda >3, 0 < \lambda <1$
I believe I have done everything correct to this point.
My question is how do I give the values of $N_0>0$, $K>0$ and $\lambda>0$ such that $N_1<0$, and how do I calculate $N_1$? Thanks!

A: Yes. All of your assumptions are correct. I checked it. But according to your problem if $N_0, K$ and $\lambda$ are positive, then from the first iteration $$N_1=\lambda N_0\left(1-\frac{N_0}{K}\right),$$ you always get $N_1$ as non negative since $N_0<K$ (the population is at most its carrying capacity).
But what is your actual motivation according to the problem? I think it may be positiveness of population in the model.


text:
Q: Rcmdr problems with loading packages i'm having problems with the download of R commander on my Mac (Ventura 13.0.1)
R is in its latest version 4.2.2
the problem is with the package RcmdrMisc, i have already tried to download the single package typing install.packages("RcmdrMisc") but when i launch R commander it continues saying that this package can not be loaded.
i was wondering why, could anyone help me?
this is what comes out
> library(Rcmdr)
Caricamento del pacchetto richiesto: splines
Caricamento del pacchetto richiesto: RcmdrMisc
Caricamento del pacchetto richiesto: car
Caricamento del pacchetto richiesto: carData
Caricamento del pacchetto richiesto: sandwich
Error: caricamento pacchetto o namespace fallito per 'RcmdrMisc' in dyn.load(file, DLLpath = DLLpath, ...):
 non è possibile caricare un oggetto condiviso '/Library/Frameworks/R.framework/Versions/4.2/Resources/library/glue/libs/glue.so':
  dlopen(/Library/Frameworks/R.framework/Versions/4.2/Resources/library/glue/libs/glue.so, 0x0006): Library not loaded: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libR.dylib
  Referenced from: <D964920A-2ED4-342B-BF74-A11790182FFA> /Library/Frameworks/R.framework/Versions/4.2/Resources/library/glue/libs/glue.so
  Reason: tried: '/Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libR.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libR.dylib' (no such file), '/Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libR.dylib' (no such file), '/usr/local/lib/libR.dylib' (no such file), '/usr/lib/libR.dylib' (no such file, not in dyld cache)
Errore: il pacchetto 'RcmdrMisc' non può essere caricato

i tried to install the single package RcmdrMisc but without any success


text:
Q: Select a div using tab key and add event on enter key I using tab key selection for select a div .when I select that div using tab key and on click enter I want to execute a function .
the code I am using is given below:
$(document).on('keydown', '#tree', function (event) {

        if (event.keyCode === 13) {debugger
                if($(".userLi").is( ":focus" )){
                    debugger
                }
        }
    });

but this focus div is not getting for me. is thare any idea to do this ?

A: If you want to allow the tab key to focus on a div element you'll need to add a tabindex attribute to it. Note that this may not work in older browsers.
From there you can use the target property of the event passed to the handler function to reference the individual div which raised the event. Try this:

$(document).on('keyup', '#tree', function(e) {
  if (e.which == 13)
    showTextInConsole($(e.target).text());
});

function showTextInConsole(text) {
  console.log(text);
}

One

Two

Three

Four

Five

A: You need to do (".userLi:focus") to get the focused .userLi element. The code $(".userLi").is( ":focus" ) will return you the boolean value if the element is focused or not. But not the actual element that is focused.


text:
Q: HTTP JSON request in JS - CORS issue The goal of this project is to use IBM's Watson and its natural language understanding AI.
When I use Insomnia (a REST client) I can get a POST request to go through and get a JSON response.
However, when I try using javascript I am not able to POST a request and receive the following error:
"Access to XMLHttpRequest at 'WEBSITE-I'M-TRYING-TO-REACH' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request."
Here is the code I am using:

var url = "http://newsroom.ibm.com/Guerbet-and-IBM-Watson-Health-Announce-Strategic-Partnership-for-Artificial-Intelligence-in-Medical-Imaging-Liver"

getData(url);

function getData(url){
  var data = JSON.stringify({
    "url": url,
    "features": {
      "sentiment": {},
      "categories": {},
      "concepts": {},
      "entities": {},
      "keywords": {}
    }
  });

  var postURL = "https://api.us-south.natural-language-understanding.watson.cloud.ibm.com/instances/9d2bd18a-8017-4e44-8de9-acc01a9f0795/v1/analyze?version=2019-07-12"

  var xml = new XMLHttpRequest();
  xml.withCredentials = true;

  xml.addEventListener("readystatechange", function () {
    if (this.readyState === this.DONE) {
      console.log(this.responseText);
    }
  });

  var username = "myUsername";
  var password = "myPassword";
  xml.open("POST", postURL);
  xml.setRequestHeader("content-type", "application/json");
  xml.setRequestHeader("Authorization", "Basic " + username + ":" + password)

  xml.send(data);
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JSON Requests</title>

JSON Requests

A: As said, put the origin key in the header :
xml.setRequestHeader("Origin", "https://the-great.site");


text:
Q: Some confusion regarding Jordan block form of a matrix I am given that a $5\times 5$ matrix over the field of complex numbers has characteristic polynomial $f=(x-2)^3(x+7)^2$ and minimal polynomial $p=(x-2)^2(x+7)$. From this, and this other Math.SE question, I have deduced that the JCF for this matrix is given by, $$\begin{bmatrix}2 & 1 & 0 & 0 & 0 \\ 0 & 2 & 0 & 0 & 0 \\ 0 & 0 & 2 & 0 & 0 \\ 0 & 0 & 0 & -7 & 0 \\ 0 & 0 & 0 & 0 & -7\end{bmatrix}.$$ However, in some literature the JCF is given as, $$\begin{bmatrix}2 & 0 & 0 & 0 & 0 \\ 1 & 2 & 0 & 0 & 0 \\ 0 & 0 & 2 & 0 & 0 \\ 0 & 0 & 0 & -7 & 0 \\ 0 & 0 & 0 & 0 & -7\end{bmatrix},$$ with the only difference being the position of the $1$. Are both correct? Or am I missing something?

A: Yes the two forms are both valid as also the following for example
$$\begin{bmatrix}2 & 0 & 0 & 0 & 0 \\ 0 & 2 & 1 & 0 & 0 \\ 0 & 0 & 2 & 0 & 0 \\ 0 & 0 & 0 & -7 & 0 \\ 0 & 0 & 0 & 0 & -7\end{bmatrix}\quad \begin{bmatrix}-7 & 0 & 0 & 0 & 0 \\ 0 & -7 & 0 & 0 & 0 \\ 0 & 0 & 2 & 1 & 0 \\ 0 & 0 & 0 & 2 & 0 \\ 0 & 0 & 0 & 0 & 2\end{bmatrix}.
$$
$$\begin{bmatrix}2 & 0 & 0 & 0 & 0 \\ 1 & 2 & 0 & 0 & 0 \\ 0 & 0 & 2 & 0 & 0 \\ 0 & 0 & 0 & -7 & 0 \\ 0 & 0 & 0 & 0 & -7\end{bmatrix}\quad \begin{bmatrix}-7 & 0 & 0 & 0 & 0 \\ 0 & -7 & 0 & 0 & 0 \\ 0 & 0 & 2 & 0 & 0 \\ 0 & 0 & 1 & 2 & 0 \\ 0 & 0 & 0 & 0 & 2\end{bmatrix}.
$$


text:
Q: Starting multiple PHP processes So I have a script which does the following:
for ($i = $start;$i<=$end;$i++){
    shell_exec("php /home/mysql_box/script.php phrases $i {$argv[3]} > /dev/null 2>&1 &");
}

On one of my servers I would like this script to run 400 times. As part of the call it connects to a Mysql server on a different box but for some wierd reason hits about 130 connections and then errors saying "Mysql server has gone away".
I appreciate this is quite common and the MySQL manual states:

You can also encounter this error with applications that fork child processes, all of which try to use the same connection to the MySQL server. This can be avoided by using a separate connection for each child process.

However I wouldn't be using the same connection surely? My wait_timeout is the default - but huge so why would some connections simply not be able to connect?
A couple of other points from the manual:

*

*The connection uses the IP not host name

*I didn't start mysql with skip-networking

*The query is a single one liner - its not big

*I am using Ubuntu

*I am connecting with PDO

I hope I've given enough info to help.

A: So I believe I have discovered the issue and I hope this helps anyone else. The reason being was that the initial query that was run on each loop took aprox 15 seconds. For some reason this reduced the amount of concurrent new connections and as such crashed out. The solution was to therefore reduce the query time required and so if you experience this problem as well - play around with the queries themselves.

A: You are spawning 400 php processes and letting them to run in background. Having more than 130 simultaneous connections might be hard for your MySQL server handling.
You might want to wait a little to launch all this process:
for ($i = $start;$i<=$end;$i++){
    shell_exec("php /home/mysql_box/script.php phrases $i {$argv[3]} > /dev/null 2>&1 &");
    if ($i%50 === 0) //every 50 process wait 1 second, so you give a chance that they're finished, and hopefully your db server will be able to handle more connections
        sleep(1);
}

A: I think that firing 400 queries almost simultaneusly by the scripts invoked in the for loop is a bad idea per se.
Even if each query takes little time to execute the loop will act faster.
You may hit the maximun numer of allowed connection set on the server running mysql: max_connections. I'm not 100% sure this is the issue you have because normally the error you would get is Too many connections: see Too many connections
You may also hit the maximum number of network connections allowed by the destination server (this is more likely to lead to a Mysql server has gone away)
Consider also you're spawning 400 processes at once each one running the PHP intepreter. Quite heavy for the local server.

The quickest dirty fix is to set some delay between scripts invocation.
for ($i = $start;$i<=$end;$i++){
    shell_exec("php /home/mysql_box/script.php phrases $i {$argv[3]} > /dev/null 2>&1 &");
    usleep( 1000 * 1000 * 100 ); // 0.1 SECS
}

However this is leading you versus a "syncronous" approach which may not be what you want.
The proper solution would be to implement a system to know when a spawned script has ended. Then start running the scripts in parallel but avoid more than ex. 50 running simultaneously.
You may consider implementing multithreading directly in your PHP scripts, see:
PThreads / PHP PThreads
PHPThread
GPhpThread

If "hitting the server more gently" (you may even try as a problem-isolation-strategy to run the scripts with high delay or syncronously) doesn't solve the problem (but you should issue less queries at once anyway in my opinion) then the problem falls into the MySQL server has gone away category.
I quote from the linked docs what may be the causes in my opinion (for the full list go to ht elink above)

*

*You tried to run a query after closing the connection to the server. This indicates a logic error in the application that should be corrected.

*A client application running on a different host does not have the necessary privileges to connect to the MySQL server from that host.

*You have encountered a timeout on the server side and the automatic reconnection in the client is disabled (the reconnect flag in the MYSQL structure is equal to 0).

*You may also see the MySQL server has gone away error if MySQL is started with the --skip-networking option.


text:
Q: Read a RAID device directly using read(2) I have create a Linux Software RAID, with chunk size 4096B, and 4 disks.
Then, I'm trying to do write and read test on the RAID, say /dev/md0.
The following code is read test and BLOCK_SIZE is the amount I want to read. However, whenever I set it not power of 2, such as 3*4096, I will get an error after read, saying "Invalid Argument". And it is the same case with write.
As far as I can understand, read(2) and write(2) should be able to perform operation on any amount of bytes the user wants, so please help me with it and the code.
#define _GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <sys/time.h>
#include <errno.h>
#define BLOCK_SIZE 8*4096 //bytes
#define BUFF_OFFSET 8*4096

int main(int argc, char *argv[]){
    char device[64];
    int fd;
    void *buff;
    int size; //bytes
    int seek;

    fd = open(argv[1], O_DIRECT | O_RSYNC | O_RDONLY);

    posix_memalign(&buff, BUFF_OFFSET, BLOCK_SIZE);

    int load;
    seek = lseek(fd,0,SEEK_SET);
    load = read(fd,buff,BLOCK_SIZE);
    if (load < 0){
        printf("Cannot read\n");
        perror("because");
        break;
    }
    else{
        printf("%d\n",load);
    }
    close(fd);
    return 0;
}


text:
Q: Why db.session.remove() must be called? I'm following a tutorial to learn flask web developing, and here is its unit testing file:
import unittest
from flask import current_app
from app import create_app, db

class BasicsTestCase(unittest.TestCase):
    def setUp(self):
        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()
        self.app_context.pop()

    def test_foo(self):
        pass

Also, I've found these sentences in SQLAlchemy document:

Using the above flow, the process of integrating the Session with
  the web application has exactly two requirements:

*

*......

*Ensure that scoped_session.remove() is called when the web request ends, usually by integrating with the web framework's event system to
  establish an "on request end" event.

My question is: Why do I need to call db.session.remove()?
I think as long as db.session.commit() is not invoked, the database won't be modified. Also, when I comment out this line, the application will still be able to pass the unit test.
I've consulted the documents of both Flask-SQLAlchemy and SQLAlchemy, but the former doesn't even mention db.session.remove(), while the latter is too abstract for me to understand.

A: I haven't understand why db.session.remove() is necessary until I inspected the whole project:
This is because in config.py, SQLALCHEMY_COMMIT_ON_TEARDOWN is set to True. As a result, changes made to db.session would be auto-commited if db.session isn't destroyed.

A:
Using the above flow, the process of integrating the Session with the web application has exactly two requirements:

*

*......

*Ensure that scoped_session.remove() is called when the web request ends, usually by integrating with the web framework's event system to establish an "on request end" event.

In SQLAlchemy, above action is mentioned because sessions in web application should be scoped, meaning that each request handler creates and destroys its own session.
This is necessary because web servers can be multi-threaded, so multiple requests might be served at the same time, each working with a different database session.
This scenario is beautifully handled by Flask-SQLAlchemy, it creates a fresh or new scoped session for each request. If you dig further it you will find out here, it also installs a hook on app.teardown_appcontext (for Flask >=0.9), app.teardown_request (for Flask 0.7-0.8), app.after_request (for Flask <0.7) and here is where it calls db.session.remove().
The testing environment does not fully replicate the environment of a real request because it does not push/pop the application context. Because of that the session is never removed at the end of the request.
As a side note, keep in mind that functions registered with before_request and after_request are also not called when you call client.get().
You can force an application context automatically push and pop with a small change to your test instead of manually push in setUp() and pop in tearDown():
def test_foo(self):
  with app.app_context():
      client = app.test_client()
      # do testing here for your endpoints

with this change the test passes without manually writing db.session.remove().
The documentation for Flask-Testing seems to be wrong or more likely outdated. Maybe things worked like they describe at some point, but that isn't accurate for current Flask and Flask-SQLAlchemy versions.
I hope this helps!


text:
Q: Spring prototype bean state & thread safety I'm working on a project and there is such piece of code:
public abstract class Abstract_Mail {

@Value("${general.Mail.sAddressDefaultFrom}")
private String sFrom;
@Value("${general.Mail.sAddressNoreply}")
private String saTo;
private String sToName;
private String sHead = "Subject";
private String sBody = "Text";
@Value("${general.Mail.sUsername}")
private String sAuthUser; //"user";
@Value("${general.Mail.sPassword}")
private String sAuthPassword; //"password";
@Value("${general.Mail.sHost}")
private String sHost; //"gmail.com";
@Value("${general.Mail.nPort}")
private Integer nPort; //Integer.valueOf(mailServerPort);
@Value("${general.Mail.bUseSSL}")
private boolean bSSL;
@Value("${general.Mail.bUseTLS}")
private boolean bTLS;
public Abstract_Mail() {
}

public String getFrom() {
    return sFrom;
}

public Abstract_Mail _From(String sFrom) {
    this.sFrom = sFrom;
    return this;
}

public String getTo() {
    String[] adress = saTo.split("\\,");
    if (adress.length == 1 && sToName != null &&
    !"null".equalsIgnoreCase(sToName)) {
        return sToName + "<" + saTo + ">";
    }
    return saTo;
}

public Abstract_Mail _To(String saTo) {
    this.saTo = saTo;
    return this;
}

public String getToName() {
    return sToName;
}

public Abstract_Mail _ToName(String ... saToName){
    String fullName = saToName[0];
    if (saToName.length > 1) {
        for (int i = 1; i < saToName.length; i++) {
            fullName = fullName + " " + saToName[i];
        }
    }
    this.sToName = fullName;
    return this;
}

public String getHead() {
    return sHead;
}

public Abstract_Mail _Head(String sHead) {
    this.sHead = sHead;
    return this;
}

public String getBody() {
    return sBody;
}

public Abstract_Mail _Body(String sBody) {
    this.sBody = sBody;
    return this;
}

public String getAuthUser() {
    return sAuthUser;
}

public Abstract_Mail _AuthUser(String sAuthUser) {
    this.sAuthUser = sAuthUser;
    return this;
}

public String getAuthPassword() {
    return sAuthPassword;
}

public Abstract_Mail _AuthPassword(String sAuthPassword) {
    this.sAuthPassword = sAuthPassword;
    return this;
}

public String getHost() {
    return sHost;
}

public Abstract_Mail _Host(String sHost) {
    this.sHost = sHost;
    return this;
}

public Integer getPort() {
    return nPort;
}

public Abstract_Mail _Port(Integer nPort) {
    this.nPort = nPort;
    return this;
}

public boolean isSSL() {
    return bSSL;
}

public Abstract_Mail _SSL(boolean bSSL) {
    this.bSSL = bSSL;
    return this;
}

public boolean isTLS() {
    return bTLS;
}

public Abstract_Mail _TLS(boolean bTLS) {
    this.bTLS = bTLS;
    return this;
}

abstract public void send() throws Exception;

}
And:
@Service("mail")
@Scope("prototype")
public class Mail extends Abstract_Mail {

@Autowired
MethodsCallRunnerUtil methodCallRunner;

@Autowired
GeneralConfig generalConfig;

@Autowired
UniSender oUniSender;

private final static Logger LOG = LoggerFactory.getLogger(Mail.class);
private static final Logger LOG_BIG = LoggerFactory.getLogger("MailBig");

Properties oProps = new Properties();
String DEFAULT_ENCODING = "UTF-8";
private Session oSession = null;
//private String sContext="";
private Multipart oMultiparts = new MimeMultipart();

public Mail() {
}

@Override
public void send() throws EmailException {
    LOG.info("send mail started...");
    LOG.info("(getFrom()={})", getFrom());
    LOG.info("(getTo()={})", getTo());
    String sTo = getTo();
    String sToNew = sTo;
    sToNew = sToNew.replace("\"", "");
    sToNew = sToNew.replace("\"", "");
    if (!sToNew.equals(sTo)) {
        LOG.info("(getTo()(fixed)={})", sToNew);
        _To(sToNew);
    }
    LOG.info("(getHead()={})", getHead());

    Boolean bUniSender = generalConfig.isEnable_UniSender_Mail();
    LOG.info("(bUniSender={})", bUniSender);
    LOG_BIG.info("(bUniSender={})", bUniSender);
    LOG_BIG.debug("(getFrom()={})", getFrom());
    LOG_BIG.debug("(getTo()={})", getTo());
    LOG_BIG.debug("(getHead()={})", getHead());
    LOG_BIG.debug("(getBody={})", getBody());

    StringBuilder sbBody = new StringBuilder(500);
    sbBody.append("host: ");
    sbBody.append(getHost());
    sbBody.append(":");
    sbBody.append(getPort());
    sbBody.append("\nAuthUser:");
    sbBody.append(getAuthUser());
    sbBody.append("\nfrom:");
    sbBody.append(getFrom());
    sbBody.append("\nto:");
    sbBody.append(getTo());
    sbBody.append("\nhead:");
    sbBody.append(getHead());

    if (bUniSender) {
        try {
            if (!sendWithUniSender()) {
                sendAlternativeWay(sbBody.toString());
            }
        } catch (Exception oException) {
            LOG.warn("Try send via alter channel! (getTo()={})",
    oException.getMessage(), getTo());
            LOG.trace("FAIL:", oException);
            try {
                //msgService.setEventSystem("WARNING", null, null,
    "sendWithUniSender", "Error send via UniSender", sbBody.toString(),
    oException.getMessage(), null);
            } catch (Exception e) {

            }
            sendAlternativeWay(sbBody.toString());
        }
    } else {
        sendAlternativeWay(sbBody.toString());
    }

    LOG.info("send mail ended ehith sbBody: " + sbBody.toString());
}

public void sendOld() throws EmailException {
    LOG.info("sendOld started...");
    LOG.info("init");
    try {
        MultiPartEmail oMultiPartEmail = new MultiPartEmail();
        LOG.info("(getHost()={})", getHost());
        oMultiPartEmail.setHostName(getHost());

        String[] asTo = { sMailOnly(getTo()) };
        if (getTo().contains("\\,")) {
            asTo = getTo().split("\\,");//sTo
            for (String s : asTo) {
                LOG.info("oMultiPartEmail.addTo (s={})", s);
                oMultiPartEmail.addTo(s, "receiver");
            }
        }

        LOG.info("(getFrom()={})", getFrom());
        LOG_BIG.debug("(getFrom()={})", getFrom());
        oMultiPartEmail.setFrom(getFrom(), getFrom());//"iGov"
        oMultiPartEmail.setSubject(getHead());
        LOG.info("getHead()={}", getHead());
        String sLogin = getAuthUser();
        if (sLogin != null && !"".equals(sLogin.trim())) {
            oMultiPartEmail.setAuthentication(sLogin, getAuthPassword());
            LOG.info("withAuth");
        } else {
            LOG.info("withoutAuth");
        }
        //oMultiPartEmail.setAuthentication(getAuthUser(), getAuthPassword());
        LOG.info("(getAuthUser()={})", getAuthUser());
        //LOG.info("getAuthPassword()=" + getAuthPassword());
        oMultiPartEmail.setSmtpPort(getPort());
        LOG.info("(getPort()={})", getPort());
        oMultiPartEmail.setSSL(isSSL());
        LOG.info("(isSSL()={})", isSSL());
        oMultiPartEmail.setTLS(isTLS());
        LOG.info("(isTLS()={})", isTLS());

        oSession = oMultiPartEmail.getMailSession();
        MimeMessage oMimeMessage = new MimeMessage(oSession);

        LOG.info("oMimeMessage oSession: " +  oSession);

        //oMimeMessage.setFrom(new InternetAddress(getFrom(), "iGov", DEFAULT_ENCODING));
        oMimeMessage.setFrom(new InternetAddress(getFrom(), getFrom()));
        //oMimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(sTo, sToName, DEFAULT_ENCODING));

        LOG.info("oMimeMessage From: " + getFrom());

        String sReceiverName = "receiver";
        if (asTo.length == 1) {
            sReceiverName = getToName();
        }
        for (String s : asTo) {
            LOG.info("oMimeMessage.addRecipient (s={})", s);
            //oMultiPartEmail.addTo(s, "receiver");
            oMimeMessage.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(s, sReceiverName, DEFAULT_ENCODING));
        }

        //oMimeMessage.addRecipient(Message.RecipientType.TO,
        //        new InternetAddress(sTo, "recipient", DEFAULT_ENCODING));
        //new InternetAddress(getTo(), "recipient", DEFAULT_ENCODING));
        oMimeMessage.setSubject(getHead(), DEFAULT_ENCODING);
        LOG.info("oMimeMessage head: " + getHead());

        _AttachBody(getBody());
        LOG.info("(getBody()={})", getBody());
        oMimeMessage.setContent(oMultiparts);
        LOG.info("oMimeMessage content: " + oMimeMessage.getContent().toString());
        //            oMimeMessage.getRecipients(Message.RecipientType.CC);
        //methodCallRunner.registrateMethod(Transport.class.getName(), "send", new Object[]{oMimeMessage});

        try{

            Transport.send(oMimeMessage);
        }
        catch(Exception ex){
            LOG.info("There are some eroor during mail transport: " + ex);
        }

        LOG.info("Mail was transported....");
        LOG.info("Send " + getTo() + "!!!!!!!!!!!!!!!!!!!!!!!!");
    } catch (Exception oException) {
        LOG.error("FAIL: {} (getTo()={})", oException.getMessage(), getTo());
        LOG.trace("FAIL:", oException);
        throw new EmailException("Error happened when sending email (" + getTo() + ")"
                + "Exception message: " + oException.getMessage(), oException);
    }
    LOG.info("SUCCESS: Sent!");
    LOG.info("sendOld ended...");
}

public Mail _AttachBody(String sBody) {
    try {
        MimeBodyPart oMimeBodyPart = new MimeBodyPart();
        //oMimeBodyPart.setText(sBody,DEFAULT_ENCODING,"Content-Type: text/html;");
        oMimeBodyPart.setText(sBody, DEFAULT_ENCODING);
        //         oMimeBodyPart.setHeader("Content-Type", "text/html");
        oMimeBodyPart.setHeader("Content-Type", "text/html;charset=utf-8");
        oMultiparts.addBodyPart(oMimeBodyPart);
        LOG.info("sBodylength()={}", sBody != null ? sBody.length() : "null");
    } catch (Exception oException) {
        LOG.error("FAIL:", oException);
    }
    return this;
}

public Mail _Attach(File oFile) {
    _Attach(new FileDataSource(oFile), oFile.getName(), "");
    return this;
}

public Mail _Attach(File[] aFile) {
    LOG.info("(aFile.length={})", aFile.length);
    for (File oFile : aFile) {
        _Attach(oFile);
    }
    return this;
}

public Mail _Attach(DataSource oDataSource, String sFileName, String sDescription) {
    LOG.info("_Attach started..");
    try {
        MimeBodyPart oMimeBodyPart = new MimeBodyPart();
        oMimeBodyPart.setHeader("Content-Type", "multipart/mixed");
        oMimeBodyPart.setDataHandler(new DataHandler(oDataSource));
        oMimeBodyPart.setFileName(MimeUtility.encodeText(sFileName));
        oMultiparts.addBodyPart(oMimeBodyPart);
        LOG.info("(sFileName={}, sDescription={})", sFileName, sDescription);
    } catch (Exception oException) {
        LOG.error("FAIL: {} (sFileName={},sDescription={})", oException.getMessage(), sFileName, sDescription);
        LOG.trace("FAIL:", oException);
    }
    LOG.info("_Attach ended..");
    return this;
}

public Mail _Attach(URL[] aoURL) {
    return _Attach(aoURL, null);
}

public Mail _Attach(URL[] aoURL, String[] asName) {
    LOG.info("(asName={})", asName);
    for (int n = 0; n < aoURL.length; n++) {
        try {
            if (asName == null) {
                _Attach(aoURL[n], null);
            } else {
                _Attach(aoURL[n], asName[n]);
            }
        } catch (Exception oException) {
            LOG.error("FAIL:", oException);
        }
    }
    return this;
}

public Mail _Attach(URL oURL, String sName) {
    try {
        MimeBodyPart oMimeBodyPart = new MimeBodyPart();//javax.activation
        oMimeBodyPart.setHeader("Content-Type", "multipart/mixed");
        DataSource oDataSource = new URLDataSource(oURL);
        oMimeBodyPart.setDataHandler(new DataHandler(oDataSource));
        //oPart.setFileName(MimeUtility.encodeText(source.getName()));
        oMimeBodyPart.setFileName(
                MimeUtility.encodeText(sName == null || "".equals(sName) ? oDataSource.getName() : sName));
        oMultiparts.addBodyPart(oMimeBodyPart);
        LOG.info("(sName={})", sName);
    } catch (Exception oException) {
        LOG.error("FAIL: {} (sName={})", oException.getMessage(), sName);
        LOG.trace("FAIL:", oException);
    }
    return this;
}

public static String sMailOnly(String sMail) {
    String sMailNew = sMail;
    try {
        if (sMailNew.contains("<")) {
            String[] asMail = sMailNew.split("\\<");
            sMailNew = asMail[1];
            asMail = sMailNew.split("\\>");
            sMailNew = asMail[0];
        }
    } catch (Exception oException) {
        LOG.warn("FAIL: {} (sMail={},sMailNew={})", oException.getMessage(), sMail, sMailNew);
    }
    return sMailNew;
}

//public void sendWithUniSender() throws EmailException {
public boolean sendWithUniSender() {
    LOG.info("Init...");
    boolean result = true;
    Object oID_Message = null;
    StringBuilder sbBody = new StringBuilder();
    try {
        sbBody.append("host: ");
        sbBody.append(getHost());
        sbBody.append(":");
        sbBody.append(getPort());
        sbBody.append("\nAuthUser:");
        sbBody.append(getAuthUser());
        sbBody.append("\nfrom:");
        sbBody.append(getFrom());
        sbBody.append("\nto:");
        sbBody.append(getTo());
        sbBody.append("\nhead:");
        sbBody.append(getHead());

        String sKey_Sender = generalConfig.getKey_UniSender_Mail();
        long nID_Sender = generalConfig.getSendListId_UniSender_Mail();
        if (StringUtils.isBlank(sKey_Sender)) {
            throw new IllegalArgumentException("Please check api_key in UniSender property file configuration");
        }

        LOG.info("oUniSender - {}", oUniSender);
        LOG.info("methodCallRunner - {}", methodCallRunner);
        oUniSender.setMethodCallRunner(methodCallRunner);

        if (getTo().contains(",")) {
            String[] asMail = getTo().split("\\,");
            for (String sMail : asMail) {
                sMail = sMailOnly(sMail);
                UniResponse oUniResponse_Subscribe = oUniSender
                        .subscribe(Collections.singletonList(String.valueOf(nID_Sender)), sMail, getToName());
                LOG.info("(sMail={},oUniResponse_Subscribe={})", sMail, oUniResponse_Subscribe);
            }
        } else {
            String sMail = sMailOnly(getTo());
            UniResponse oUniResponse_Subscribe = oUniSender
                    .subscribe(Collections.singletonList(String.valueOf(nID_Sender)), sMail, getToName());
            LOG.info("(oUniResponse_Subscribe={})", oUniResponse_Subscribe);
        }

        String sBody =  getBody();
        //sBody = sBody + "" + "
Для отписки перейдите по ссылке";
        sBody = sBody + "" + "
Якщо Ви бажаєте відмовитися від повідомлень, будь ласка, натисніть <a href=\"{{UnsubscribeUrl}}\"тут/";

        CreateEmailMessageRequest.Builder oBuilder = CreateEmailMessageRequest
                //.getBuilder(sKey_Sender, "en")
                .getBuilder(sKey_Sender, "ua")
                .setSenderName("no reply")
                .setSenderEmail(getFrom())
                .setSubject(getHead())
                .setBody(sBody)
                .setListId(String.valueOf(nID_Sender));

        try {
            int nAttachments = oMultiparts.getCount();
            for (int i = 0; i < nAttachments; i++) {
                BodyPart oBodyPart = oMultiparts.getBodyPart(i);
                String sFileName = oBodyPart.getFileName();
                InputStream oInputStream = oBodyPart.getInputStream();
                oBuilder.setAttachment(sFileName, oInputStream);
            }
        } catch (IOException e) {
            throw new Exception("Error while getting attachment.", e);
        } catch (MessagingException e) {
            throw new Exception("Error while getting attachment.", e);
        }

        CreateEmailMessageRequest oCreateEmailMessageRequest = oBuilder.build();

        UniResponse oUniResponse_CreateEmailMessage = oUniSender.createEmailMessage(oCreateEmailMessageRequest);
        LOG.info("(oUniResponse_CreateEmailMessage={})", oUniResponse_CreateEmailMessage);

        if (oUniResponse_CreateEmailMessage != null && oUniResponse_CreateEmailMessage.getResult() != null) {
            Map<String, Object> mParam = oUniResponse_CreateEmailMessage.getResult();
            LOG.info("(mParam={})", mParam);
            oID_Message = mParam.get("message_id");
            if (oID_Message != null) {
                LOG.info("(oID_Message={})", oID_Message);
                CreateCampaignRequest oCreateCampaignRequest = CreateCampaignRequest.getBuilder(sKey_Sender, "en")
                        .setMessageId(oID_Message.toString())
                        .build();

                UniResponse oUniResponse_CreateCampaign = oUniSender
                        .createCampaign(oCreateCampaignRequest, getTo());
                LOG.info("(oUniResponse_CreateCampaign={})", oUniResponse_CreateCampaign);
            } else {
                result = false;
                LOG.error("error while email creation " + oUniResponse_CreateEmailMessage.getError());
                //throw new EmailException("error while email creation " + oUniResponse_CreateEmailMessage.getError());
            }
        }
    } catch (Exception oException) {
        result = false;
        LOG.error("FAIL: {} (oID_Message()={},getTo()={})", oException.getMessage(), oID_Message, getTo());
        new Log(oException, LOG)
                ._Case("Mail_FailUS")
                ._Status(Log.LogStatus.ERROR)
                ._Head("First try send fail")
                ._Param("getTo", getTo())
                ._Param("sbBody", sbBody)
                ._Param("oID_Message", oID_Message)
                .save()
        ;
    }
    LOG.info("SUCCESS: sent!");
    return result;
}

private void sendAlternativeWay(String sbBody) {
    LOG.info("sendAlternativeWay started...");
    try {
        sendOld();
    } catch (Exception oException1) {
            new Log(oException1, LOG)//this.getClass()
                    ._Case("Mail_FailAlter")
                    ._Status(Log.LogStatus.ERROR)
                    ._Head("Final send trying fail")
                    //._Body(oException1.getMessage())
                    ._Param("getTo", getTo())
                    ._Param("sbBody", sbBody)
                    .save()
            ;
    }
    LOG.info("sendAlternativeWay ended...");
}

}

Client class lokks like this:
SomeController {

@Autowired
Mail mail;

sendTo() {
  mail.setTo("Some address");
  mail.set....
  mail.set....
  mail.set....
  mail.send();
 }
}

As far as I know Prototype scope means that bean is created "each time it is injected". Thus each time we request sendTo() of SomeController we change state of the same Mail and get race condition. Isn't it right?
P.S
I've added such a lot of code cause I thought maybe there are some datails making this approach sensible.


text:
Q: How should I capture object state when a JUnit test throws? I have a simple test set up in JUnit, along the lines of
public void testGetBar() throws MyException{
  Foo f = new Foo();
  f.setup();

  assertEquals(new Bar("1234"), f.getBar());
}

Suppose getBar() threw a MyException: JUnit notes this as a test "in error", and I notice that I screwed up the method.  Yay, unit testing works!  However, I have no way of knowing what was wrong with my Foo object that made it throw when I tried to getBar() on it, without going back and e.g. running the test through a debugger, or adding a logging statement.  Everybody says it's a bad idea catch exceptions in your JUnit tests, so it seems hamfisted to do this:
try{
  assertEquals(new Bar("1234"), f.getBar());
} catch(MyException e) {
  log.error(f.toString());
  throw e;
}

but it's all I can think of.  Is there no JUnit-y shorthand of saying "when there's an exception in this test, log out this, that, and the other object state (somehow)" to make it easy to figure out where things went wrong?

A: You should improve the quality of information in the exceptions you throw so that you can understand what went wrong in the unit test.  This ensures that later if an exception is thrown in production you will have a useful exception message rather than something cryptic.
I'm not sure why you want to conditionally log exceptions.  A unit test should always pass or always throw an exception.  If you want to expect an Exception add the Annotation @Test(expection=Exception.class)
If you really want to log exceptions the most elegant way is to annotate your test class with @RunWith(MyRunner.class) and create a class MyRunner extends BlockJUnit4Runner that handles the logging.

A: You wouldn't wrap all your unit testing code in exception handlers: just the ones your having trouble with. Leaving JUnit to catch unanticipated exceptions as errors is also fine: wrap the offending code in a handler when that happens and you're investigating the problem (then remove again).
This should all be fairly infrequent though: you don't want code that throws random exceptions when you're unit testing (which should be as clean and repeatable as possible).
Of course, you will want to unit test your exception generation too: in which case you will definitely want to wrap the call to the offending function in a handler, then throw a fail() if the exception does not occur.


text:
Q: Complex Analysis. How to use cauchy intergral Given the following integral of gamma on the path $[0,2]$ and $[-2,2]$ we have the integral $$ \int_\gamma \frac{z} {(z^2-1)(z-3)}dz$$
I set it up like
$$ \int_\gamma \frac{\frac{z}{(z+1)(z-3)}}{z-1}=2\pi i $$
and i get that =
$$ \frac{-\pi i}{2} $$
and then i did the following for $[-2,2]$ but i dont believe they are set up correctly and was wondering if i can have some guidance or the error pointed out
$$ \int_\gamma \frac{\frac{z}{(z^2-1)}}{z-3}=2\pi i $$
then after everything i get its = 0 or pi i/4

A: If I understand your notation, by $[-2,2]$ you mean the circle of radius $2$ centered at $-2$.  But the integrand's only pole is then at $z=-1$.
So you get $\oint_Cf(z)/(z+1)$, where $f(z)=z/((z-1)(z-3))$. So the integral is equal to $2\pi if(-1)=2\pi i(-1/8)=-\pi i/4$.


text:
Q: htaccess dynamic rewrite rule I have some request parameters which I am converting to friendly URL
For example:
http://domain.com/members/girls/sort/last_reg/nick/ted/from/18/to/28/hfrom/150/hto/190/bbody/Athletic/

The parameters are dynamic so the URL could be
http://domain.com/members/girls/nick/ted/from/18/to/28/hfrom/150/hto/190/bbody/Athletic/

or
http://domain.com/members/men/nick/ted/to/28/hfrom/150/hto/190/bbody/Athletic/

The parameters are in pairs
parameter_name/parameter_value

The only thing which is constant is
http://domain.com/members/

How to transform this URL to
http://domain.com/filename.php?sex=men&pram1=value1&param2=value2 ......

or
http://domain.com/filename.php?sex=girls&pram1=value1&param2=value2 ......

A: Put this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On

## recucrsion based rule to convert
## /members/men/n1/v1/n2/v2 to /members.php?n2=v2&n1=v1&sex=men

RewriteRule ^(members)/(girls|men)(/.*)?$ /$1/$3?sex=$2 [L,QSA,NC]

RewriteRule ^(members)/([^/]*)/([^/]*)(/.*)?$ /$1/$4?$2=$3 [L,QSA,NC]

RewriteRule ^(members)/?$ /$1.php [L,NC]

A: This may help:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/(.*)/(.*)/(.*)/$ filename.php?$1=$2&$3=$4 [L,QSA]


text:
Q: Selecting rows from a HTML table with only specified value? There is a table and a text input box on the HTML page. Whenever the user types a value in the box, the Javascript should filter the table and show only the rows which has the value in the data.
I have done with this part but the main problem is if the user types space in the box and then types another value then the js should filter the data where all of the words (text separated with space) are present at least once in any cell of the row, just like Google Suggestions but with table.
Does anyone have a solution?
HERES THE CODE
for(var i=0; i < trs.length; i++ )
{
    tds = trs[i].getElementsByTagName("td");
    //alert(tds );

    for( var j=0; j < tds.length; j++ )
    {
        if( hasWords )
        {
            for( k = 0; k < searchWords.length; k++ )
            {
                if( searchWords[k].toLowerCase() != "" && tds[j].innerHTML.toLowerCase().search( searchWords[k].toLowerCase() ) == -1 )
                {
                    found = false;
                    //foundRows.push(trs[i]);
                }
                else {
                    found = true;
                    foundRows.push(trs[i]);
                }
            }
        }
        else
        {
            if( searchText != "" && tds[j].innerHTML.toLowerCase().search( searchText.toLowerCase() ) != -1 )
            {
                found = true;
                foundRows.push(trs[i]);
            }
        }

        /*
        if( tds[j].innerHTML.toLowerCase().search( searchText ) != -1 )
        {
            found = true;
            foundRows.push(trs[i]);
        }
        */
    }
}

A: First possibility
Do the same thing as you did with one word. Split user's input into separate words and test for each of them.
Second possibility - optimised filtering
Traversing the whole table seems very time consuming which could quite easily be optimised with a small overhead at the beginning. Since javascript objects are a kind of associative arrays you could do this:

*

*When page loads traverse table and parse texts of each cell. Parsing should be done using regular expressions, because it will make it simpler to exclude any punctuation and similar var rx = /([a-z]+)/gi. You can easily explude any single letter words here as well var rx = /([a-z]{2,})/gi.

*Store each word in associative object with relation to row.

*Filter using this object.

How should your associative object look like:
var data = {
    "tomorrow": [1, 2, 3],
    "will": [3, 5, 6],
    "be": [78],
    "sunny": [3, 9, 19],
    ...
};

arrays of each word correspond to table row index. So when user enters whatever data in the textbox, you can easily split that into separate words and get all arrays:
var filter = $("#search_filter").val().split(" ");
var firstWordRows = data[filter[0]];

Then all you have to do is intersect those arrays and hide all rows except resulting ones.
The good thing is you can define stop words that you don't filter (like in, a, the, of, at, etc.)...
Why even bother with the second one? If the page is more likely to be filtered several times as opposed to being loaded, then this overhead at page load will make your filtering snappy. Filtering will be very fast and less processor hungry.
Suggestion
I strongly suggest you do use some Javascript library that will make your life much simpler. Use jQuery for instance which doesn't have a long learning curve and works very well along with existing scripts you may have.

A: If you've already got it working for one word, just split the input on spaces (input.split(" ")), and then filter in the same manner, except checking for every word.
If you were using a JS library, though, it'd surely be easier.


text:
Q: On $routeChangeStart loads controller issue? I am navigating one page to another page in angular , when i in second page on click on back button i am returning to first page for this i used $routeChangeStart, This will loading my controller once again , How to avoid this one ,
Here is my code .
homepal.run(function run($http, $cookies,$rootScope,$location){
    $rootScope.contactwdgt="contact-wdgt";
    $rootScope.header=true;
    $rootScope.homepage=true;
    $rootScope.innerHeader="";
    $rootScope.filter=false;

});

And in my index.html

Now my  $routeChangeStart ,
a.$on('$routeChangeStart', function(scope, next, current) {

        b.homepage = true;
        b.innerHeader = "";
        b.searchFilter = false;

        srchCls_Element.removeClass('listing-navbar');

    });

Whenever root changes my home page loads first then second page(till response comes till will show home page only.)


text:
Q: VBA Transposing a dynamic range in excel Basically I have a dynamic range that will always be in columns A:C in sheet 1. I'm trying to write a personal macro that copies the dynamic range and transposes this onto sheet 2 to allow mail merge to be able to read row 1 as mail merge fields.
Currently the error appears at this line:
Set sourceRange = ActiveSheet.Range(Cells(1, 1), Cells(lastRow, 1))

The entire code is listed below. There is probably a simple mistake I'm missing or perhaps even an easier way to achieve my desired result, however this is what I currently have come up with.
Sub TrasposeData()
'
' TrasposeData Macro
' Takes the data from sheet one and transpose it to sheet 2 to allow for mail merge compatibility.

Sheet1.Activate

Dim sourceRange As Range
Dim targetRange As Range
Dim lastRow As Long

lastRow = WorksheetFunction.CountA(Range("A:A"))
Set sourceRange = ActiveSheet.Range(Cells(1, 1), Cells(lastRow, 1))

Sheet2.Activate

Set targetRange = ActiveSheet.Cells(1, 1)

Sheet1.Activate

sourceRange.Copy

Sheet2.Activate

targetRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True

' Keyboard Shortcut: Ctrl+t
'
    Application.Run "PERSONAL.XLSB!TrasposeData"
    ActiveWindow.Close
End Sub

Any help would be much appreciated.

A: So I spent A little more time researching today and finally got it to work. the script is posted below:
Sub TransposeData()
'
' TransposeData Macro
' Traspose the data on sheet1 to sheet2 to allow for mail merge
'

Sheets("Sheet1").Select

Dim sourceRange As Range
Dim lastRow As Long

lastRow = Cells(Rows.Count, "A").End(xlUp).Row

Set sourceRange = ActiveSheet.Range("A1:C" & lastRow)

sourceRange.Copy

Sheets("Sheet2").Select

Cells(1, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,    SkipBlanks:=False, Transpose:=True

' Keyboard Shortcut: Ctrl+Shift+T
'
End Sub

Thanks El Scripto and KazJaw for your suggestions, much appreciated.

A: In your code, doing:
 lastRow = WorksheetFunction.CountA(Range("A:A"))
 Set sourceRange = ActiveSheet.Range(Cells(1, 1), Cells(lastRow, 1))

counts the number of none empty cells, but it may not give you the last cell (logical error). Like KazJaw wrote above, it might be also the reason for a possible error.
A better way would be to use (it replaces the above two lines):
  Set SourceRange = ActiveSheet.Range(Cells(1, 1), _
                         Cells(ActiveSheet.UsedRange.Rows.Count, 1))

Try it, and if it fails, please post the error message.
A simple way to copy the error is just click on the error messagebox, then
press CTRL+C, and it should copy the error details in plain text to the clipboard, so you could paste it here.


text:
Q: Listar arquivos e pegar comentários PHP com script PHP Gostaria de uma ideia se possível ou um script que primeiramente lesse todos os arquivos de extensão .php de uma pasta pegando de cada um o comentário PHP, que fica no inicio das paginas que tiverem depois do File Name:.
<?php
/*
File Name: exemplo
*/
?>

e jogasse todos em um tag html select option

A: Opa,
Já tentou utilizar REGEX?
Por exemplo: [ CORRIGIDO ]
<?php

$re = '/\<\?php\r\n\/\*\r\n(.*[A-z_])\r\n\*\//is';
$str = '<?php
/*
File Name: exemplo
*/';

preg_match_all($re, $str, $matches);

var_dump($matches);

Veja se te ajuda.

A: Solução que utilizei.
function comment_titlePage() {
    $ap = WFOX_SITE_THEME . '/'; // PASTAS DO TEMA ATUAL

    if (is_dir($ap)) {
        // ABERTUR DA PASTA
        $dh = opendir($ap);

        if ($dh) {
            $arquivos = glob("$ap{*.php}", GLOB_BRACE);

            $mArray = array();
            foreach($arquivos as $php){
                $re = '/\<\?php\r\n\/\*\r\n(.*[A-z_])\r\n\*\//is';
                $str = file_get_contents($php);

                preg_match_all($re, $str, $matches);

                $return_matches = $matches[1][0];
                $loop_matches = preg_split("[File Name: ]",$return_matches);
                $mArray[$php] = $loop_matches[1];
            }

            return $mArray;

        }
    }
}


text:
Q: with raphael.pan-zoom.js library, how can i reset my draggable function i did a draggalbe function, it works good , but when i zoom in \ zoom out with  raphael.pan-zoom.js  library , my draggable function move the object unsynchronously , the following is my draggable function :
(function(R) {
R.el.draggable = function(move, start, up) {
    this._ui = this._ui || {};
    var that = this;
    this._ui.onMove = R.is(move, 'function') ?
    move : function(distanceX, distanceY, x, y, deltaX, deltaY) {
        that.translate(deltaX, deltaY);
        event.stopPropagation();
    };
    this._ui.onStart = R.is(start, 'function') ? start : function(x, y) {
        event.stopPropagation();
    };
    function onMove(distanceX, distanceY, x, y) {
        var deltaX = x - that._ui.lastX;
        var deltaY = y - that._ui.lastY;
        that._ui.lastX = x;
        that._ui.lastY = y;
        that._ui.onMove(distanceX, distanceY, x, y, deltaX, deltaY);
        //that.paper.safari();
        event.stopPropagation();
    };
    function onStart(x, y) {
        that._ui.lastX = x;
        that._ui.lastY = y;
        that._ui.onStart(x, y);
        event.stopPropagation();
    };
    return this.drag(onMove, onStart, up);
};

})(Raphael);
how can i fix it?

A: i know how to do
(function(R) {
    R.el.draggable = function(move, start, up) {
        this._ui = this._ui || {};
        var that = this;
        this._ui.onMove = R.is(move, 'function') ?
        move : function(distanceX, distanceY, x, y, deltaX, deltaY) {
            that.translate(deltaX, deltaY);
            event.stopPropagation();
        };
        this._ui.onStart = R.is(start, 'function') ? start : function(x, y) {
            //event.stopPropagation();
        };
        function onMove(distanceX, distanceY, x, y) {
            var deltaX = x - that._ui.lastX;
            var deltaY = y - that._ui.lastY;
            that._ui.lastX = x;
            that._ui.lastY = y;
            //console.log("before deltaX:"+deltaX+" deltaY:"+deltaY);
            // 根据raphael.pan-zoom.js 提供的zoom值 计算当前 缩放比例下的 移动值
            deltaX=deltaX*(1-that.paper.zoom.currZoom/10);
            deltaY=deltaY*(1-that.paper.zoom.currZoom/10);

            console.log("after deltaX:"+deltaX+" deltaY:"+deltaY);
            that._ui.onMove(distanceX, distanceY, x, y, deltaX, deltaY);
            //that.paper.safari();
            event.stopPropagation();
        };
        function onStart(x, y) {
            that._ui.lastX = x;
            that._ui.lastY = y;
            that._ui.onStart(x, y);
            event.stopPropagation();
        };
        return this.drag(onMove, onStart, up);
    }})(Raphael);


text:
Q: Undefined variable in json output of php I just don't get what's wrong in my code!
In browser, it shows that undefined variable!
But I declared it in a while loop before!

In browser it shows:
  Notice: Undefined variable: dhkBlood in C:\xampp\htdocs\JSONdata.php on line 371*

The PHP Code that I wrote is something like below:
if($retrieve1){
    while($row = mysql_fetch_assoc($retrieve1))
    {
        $dhkBlood[] = array("ID" => $row['PID'], "PlaceName" => $row['PName'], "Address" => $row['Address'], "DeploymentName"  => $row['DName'], "Latitude" => $row['Latitude'], "Longitude" => $row['Longitude']);
    }
}

Code:
370. $result = array();
371. $result["dhakaBlood"]=$dhkBlood;
372. $finalResult = array();
373. $finalResult['data']=$result;
374. echo json_encode($finalResult);

P.S. $retrieve1 variable here is a variable that I used to assign a mysql query that generally retrieves information from my database!

A: Add
   $dhkBlood = array();

Before
 if($retrieve1){
  while($row = mysql_fetch_assoc($retrieve1))
   {
    $dhkBlood[] = array("ID" => $row['PID'], "PlaceName" => $row['PName'], "Address" => $row['Address'], "DeploymentName"  => $row['DName'], "Latitude" => $row['Latitude'], "Longitude" => $row['Longitude']);
   }
  }

A: $dhkBlood = array(); //defined array first
if($retrieve1){

    while($row = mysql_fetch_assoc($retrieve1)) {

        $dhkBlood[ID] = $row['PID'];
        $dhkBlood[PlaceName] = $row['PName'];
        $dhkBlood[Address] = $row['Address'];
        $dhkBlood[DeploymentName] = $row['DName'];
        $dhkBlood[Latitude] = $row['Latitude'];
        $dhkBlood[Longitude] = $row['Longitude'];

    }

}

defined array before use, and assign value in array as above,


text:
Q: Erlang - функция flatten. Время выполнения Добрый день!
Есть функция которая выглядит вот так:
flatten ([]) -> [];
flatten([H|T]) -> H ++ flatten(T).
Входной лист в функцию может в себе содержать другие листы
К примеру:
flatten([[1,2,3],[4,7],[9,9,9,9,9,9]]).
Какое время выполнения этой функции (Time complexity)? И почему?
У меня получается O(n) где n это количество элементов во входном листе
К примеру:
flatten([[1,2,3],[4,7],[9,9,9,9,9,9]])    n=3
flatten([[1,2,3],[4,7],[9,9,9,9,9,9],[3,2,4],[1,4,6]])    n=5
Спасибо за помощь