Gridview updating

Question: Data source of my grid view comes of stored procedure by using linqdatasource. The parameter of this linqdatasource is the textbox (txtSearchKeywords) ,when I press the search button the gridview takes the data according to below code.
Now I like to update or delete some rows of gridview, so I have added command field (edit/delete) to gridview and enabled edit/delete linqdatasource but I cannot update the row, actually I cannot even type in the row. Nothing is active , just shows edit/update/cancel buttons.
Please help how I can solve?
Stored procedure:
ALTER PROCEDURE [dbo].[spQuickSearchDoc]
  @Searchtext varchar(50)=null
AS
 select DocId,DocumentNo,Title,Unit
 from tblDocuments
 where DocumentNo like '%'+@SearchText + '%'
  or Title like '%'+@SearchText + '%'
  or Unit like '%'+@SearchText + '%'

linqdatasource:
 <asp:LinqDataSource ID="LinqDataSource2" runat="server"
          ContextTypeName="EDMSDataContext" OnSelecting="LinqDataSource2_Selecting"
          EnableDelete="True" EnableUpdate="True" TableName="tblDocuments" EnableInsert="True"
           >
          <WhereParameters>
    <asp:ControlParameter Name="Subject"
                          ControlID="txtSearchKeywords"
                          PropertyName="Text"
                          Type="String" />
</WhereParameters>
      </asp:LinqDataSource>

Gridview:
<asp:GridView ID="GridViewDocuments_Search" runat="server" AutoGenerateColumns=False
          Visible="False" onrowcommand="GridViewDocuments_Search_RowCommand" DataKeyNames="DocId"
          PageSize="100" DataSourceID="LinqDataSource2"  >
    <Columns>
        <asp:BoundField DataField="DocumentNo" HeaderText="DocumentNo"
            SortExpression="DocumentNo" ReadOnly="True" />

        <asp:BoundField DataField="TITLE" HeaderText="TITLE" ReadOnly="True"
            SortExpression="TITLE" />

       <asp:BoundField DataField="Unit" HeaderText="Unit" SortExpression="Unit"
            ReadOnly="True" />
        <asp:BoundField DataField="DocId" HeaderText="DocId" ReadOnly="True"
            SortExpression="DocId" />
        <asp:CommandField ShowEditButton="True" />
        <asp:CommandField ShowDeleteButton="True" />
    </Columns>
</asp:GridView>

Code:
public void LinqDataSource2_Selecting(object sender, LinqDataSourceSelectEventArgs e)
 {
_DataContext = new EDMSDataContext();

 var subjectFilter = e.WhereParameters["Subject"];

 var query = _DataContext.spQuickSearchDoc(subjectFilter.ToString());

e.Result = query;
}

  protected void btnSearch_Click(object sender, EventArgs e)
{
    _DataContext = new EDMSDataContext();
    this.LinqDataSource2.WhereParameters["Subject"].DefaultValue = this.txtSearchKeywords.Text;

    GridViewDocuments.Visible = false;
    GridViewDocuments_Search.Visible = true;
    this.GridViewDocuments_Search.DataBind();

}

Answer: There is RowCommand event available into DataGridview. You need to call your CommandName into and perform your operation in that.Please refer given link It's very helpful to you.
Answer: Do you get an error when you click on the Edit link in the grid view row?
You can handle the following three events in order to enable the data in your grid to be updated:
1) RowEditing
2) RowUpdating
3) RowCancellingEdit
A simple google search with the event name + linq datasource in grdiview will bring up more than enough examples on how

Gridview updating


i have an issue with the echo command

Question: so this is my first line of code without youtube.
once i get down to NQ2 the code play but crashes i tested it by adding a pause after but it wont play the echo, any ideas.
@echo off
cls
:menu
color 9f
cls
echo hello Aidan
echo Options :
echo 1) start the game
echo 2) exit
set /p me=

if %me% == 1 goto Q/A
if %me% == 2 exit

:Q/A
cls
echo who likes pina coladas
echo 1) Rupert Holmes
echo 2) Donald Trump
set /p logo=
if %logo% == 1 goto correct
if %logo% == 2 goto incorrect

:correct
cls
echo Yayy GOOD JOB restart(y/n)
set /p asd=

if %asd% == y goto gnv
if %asd% == n goto Next_question

:incorrect
cls
echo YOU SUCK RESTART (y/n)
set /p kld=

if %kld% == y goto gnv
if%kld% == n goto next question 2
:next_question
cls

echo whom better
echo 1) Donald trump
echo 2) Hillary clinton
set /p logo=
if %logo% == 1 goto correct 2
if %logo% == 2 goto incorrect 2

:correct 2
cls
echo congrats you not a demo crap restart (y/n)
set /p asd=
if %asd% == y goto menu
if %asd% == n goto NQ2

:incorrect 2
cls
echo your a democrap kys restart (Y/N)
set /p kld=

if %kld% == y goto menu
if %kld% == n goto NQ2
cls

:NQ2
pause
cls

echo which has more power
echo 1) C4
echo 2) TNT
if %logo% == 1 goto correct 3
if %logo% == 2 goto incorrect 3

:correct 3
cls
echo congrats your correct, c4 has about 1.2 more times the power of TNT Restart (y/n)
cls
if %asd% == goto menu
if %asd% == goto next question 2`enter `

Comment: for troubleshooting, don't start it with a doubleclick. Open a command window and start it from there (best without the `@echo off`). You then will see an errormessage (probably `echo was unexpected...`), followed by the failed line (probably `if == 1 goto...` (unrelated tip: labels don't support spaces) You forgot a `set /p logo=`. You may be interested in the [choice](https://ss64.com/nt/choice.html) command.
Answer: Batch labels may not contain spaces, so correct is a label, not correct 4.
Comment: im a little confused what do you need me to do. is there any way for the correct spacing
Comment: Every label must be unique. Labels may not contain spaces, so `correct 4` might become `correct_4` or `correct4` for instance. Attempting to have `correct`, `correct 2` and `correct 4` will mean that `cmd` will see *each* of these labels as `correct` so the code will appear to `goto` the wrong place`

i have an issue with the echo command


Mapeamento de View com Entity Framework

Question: Estou com dúvida de como fazer o mapeamento de um View criada no Banco Oracle 11G com Fluent-API.
Segue um trecho da view com alias:
tran.id_transporte AS "ID Navio",
tran.ds_nome_transporte AS "Navio",
pemb.id_porto AS "ID Porto Embarque",
pemb.ds_porto AS "Porto Embarque",
temb.id_terminal AS "ID Terminal",

No mapeamento fiz da seguinte forma:
        public VWProgramacaoEmbarque_Mapping()
    {
        this.HasKey(t => t.IdTerminal);
        this.ToTable("VW_PROGRAMACAO");

        this.Property(t => t.IdNavio).HasColumnName("ID_TRANSPORTE");
        this.Property(t => t.Navio).HasColumnName("DS_NOME_TRANSPORTE");
        this.Property(t => t.IdPortoEmbarque).HasColumnName("ID_PORTO");
        this.Property(t => t.PortoEmbarque).HasColumnName("DS_PORTO");
        this.Property(t => t.IdTerminal).HasColumnName("ID_TERMINAL");
    }

No Oracle consigo realizar a consulta de uma coluna com alias.
select distinct("ID Navio") from vw_programacao;

Na minha aplicação estou realizando a consulta da seguinte forma:
var idNavios = Context.VWProgramacao.Select(e => e.IdNavio).Distinct();

Mas gera o seguinte erro:

{"ORA-00904: \"Extent1\".\"ID_TRANSPORTE\": identificador inválido"}

Acredito que seja por causa do meu mapeamento que esteja errado ou talvez seja por causa do alias da minha view.
Alguma ideia do que possa ser? onde estou errando?
Comment: Se tu estás a expor a view com esses alias, não tens a coluna ID_TRANSPORTE, mas sim ID Navio (Muito cuidado com esses espaços, não recomendo nada fazer isso). E substituir para o valor correcto em todas essas properties.
Comment: Sim. Nessas linhas de código, estás a associar a propriedade do teu objecto à coluna da tabela /view. Neste caso, a tua view tem como nomes de colunas esses alias.
Comment: @RenatoAfonso Essa view foi criada por outro setor onde trabalho, nesse caso na minha aplicação o nome da minha coluna fica ...HasColumnName("ID NAVIO"); ?
Comment: @RenatoAfonso Entendi, irei alterar e fazer o teste novamente.
Comment: Não se mapeia view com o EF e sim tabelas.. você poder fazer um select que retorne tudo que você precisar com elas.
Comment: @RenatoAfonso Retirei minha resposta para priorizar a sua, se tiver interesse de responder uma solução com base no que disse, irei aceitar, pois funcionou como falou.
Comment: @samuelrvg, já coloquei como resposta. Obrigado
Answer: Se tu estás a expor a view com esses alias, não tens a coluna ID_TRANSPORTE, mas sim ID Navio (Muito cuidado com esses espaços, não recomendo nada fazer isso). E substituir para o valor correcto em todas essas properties.
Answer: Este erro se dá porque você sua VIEW não possui a coluna ID_TRANSPORTE, talvez na hora que você a criou você tenha colocado:
Veja que você colocou essa COLUNA como "ID Navio"

tran.id_transporte AS "ID Navio"

Então na hora de mapear para o Entity, você precisaria por o nome do "ALIAS" e não da COLUNA em si, ou se você retirar os apelidos ai sim poderá por o nome das COLUNAS.
Por exemplo, seu mapeamento deveria ficar assim:
SUA VIEW
tran.id_transporte AS "ID Navio",
tran.ds_nome_transporte AS "Navio",
pemb.id_porto AS "ID Porto Embarque",
pemb.ds_porto AS "Porto Embarque",
temb.id_terminal AS "ID Terminal",

SEU MAPEAMENTO TERIA QUE FICAR ASSIM
public VWProgramacaoEmbarque_Mapping()
{
    this.HasKey(t => t.IdTerminal);
    this.ToTable("VW_PROGRAMACAO");

    this.Property(t => t.IdNavio).HasColumnName("ID Navio");
    this.Property(t => t.Navio).HasColumnName("Navio");
    this.Property(t => t.IdPortoEmbarque).HasColumnName("ID Porto Embarque");
    this.Property(t => t.PortoEmbarque).HasColumnName("Porto Embarque");
    this.Property(t => t.IdTerminal).HasColumnName("ID Terminal");
}

Precisaria usar os "ALIAS", se caso você for mapear usando os nomes das COLUNAS simplesmente não precisaria por os Apelidos.

Mapeamento de View com Entity Framework


Knockout Complex Data Model Binding

Question: Let's start with the code..
Javascript to bind viewmodel and display dialog
$("#add-song").click(function () {
    $("
")
        .attr("data-bind", "template: { name: 'manage-song-template' }")
        .dialog({
            resizable: false,
            modal: true,
            title: "Add Song",
            width: 960,
            height: 490,
            buttons: [
                {
                    text: "Create Song",
                    'data-bind': 'click: savechanges',
                    click: function () {

                    }
                },
                {
                    text: "Close",
                    click: function () {
                        $(this).dialog("close");
                    }
                }
            ],
            close: function () {
                $(this).dialog('destroy').remove();
            },
            open: function () {
                ko.applyBindings(new my.managesongviewmodel());
                jquerybindings();
            }
        });
});

Now let's take a look at the view model
my.managesongviewmodel = function () {
    var
        //Scalar Properties
        song = null,

        //Functions
        loadfromserver = function (Id) {
            $.post("/song/getsong", "id=1", function (response) {
                if (response.Success) {
                    var data = response.Data;
                    var song = response.Data.Song;

                    var songdata = {
                        Song: {
                            Id: song.Id,
                            Title: song.Title,
                            Description: song.Description,
                            Lyrics: song.Lyrics,
                            isMaster: song.isMaster,
                            AudioFilePath: song.AudioFilePath,
                            CoverImageFilePath: song.CoverImageFilePath,
                            CreatedDate: song.CreatedDate
                        },
                        Genres: data.Genres,
                        SongAlternateTitles: data.SongAlternateTitles,
                        Exploitations: data.Exploitations,
                        SongWriterSongs: data.SongWriterSongs
                    };
                    song = new my.song(songdata);
                    alert(song.title());
                }
            });
        },

        savechanges = function () {
        };

    loadfromserver();
    return {
        song: song,
        loadfromserver: loadfromserver
    };
};

my.song = function (data) {
    var
        //Scalar Properties
        id = ko.observable(data.Song.Id),
        title = ko.observable(data.Song.Title),
        description = ko.observable(data.Song.Description),
        lyrics = ko.observable(data.Song.Lyrics),
        ismaster = ko.observable(data.Song.isMaster),
        audiofilepath = ko.observable(data.Song.AudioFilePath),
        coverimagefilepath = ko.observable(data.Song.CoverImageFilePath),
        createddate = ko.observable(data.Song.CreatedDate),

        //Arrays
        genres = ko.observableArray(data.Genres),
        alttitles = ko.observableArray(data.SongAlternateTitles),
        exploitations = ko.observableArray(data.Exploitations),
        songwritersongs = ko.observableArray(data.SongWriterSongs);

    return {
        id: id,
        title: title,
        description: description,
        lyrics: lyrics,
        ismaster: ismaster,
        audiofilepath: audiofilepath,
        coverimagefilepath: coverimagefilepath,
        createddate: createddate,

        genres: genres,
        alttitles: alttitles,
        exploitations: exploitations,
        songwritersongs: songwritersongs
    };
};

Here is my template

Chrome is throwing the error "Cannot read property 'title' of null;" when I launch the dialog.  That said, the "alert(song.title());" actually shows a the song title.
Any thoughts on where I've gone wrong?
Update
I have created a jsfiddle that replicates the issue.  http://jsfiddle.net/mcottingham/H7jqa/28/
Comment: This isn't working because the bindings happen before the AJAX call is finished.
Answer: It's easy. In the moment when you shows modal window your song var still equals null. So you have to wait while info about song will be loaded from server:
$("
").attr("data-bind", "template: { name: 'manage-song-template' }").dialog({
   // another options
   open: function (event, ui) {
     var vm = new my.managesongviewmodel(), domNode = this;
     vm.loadfromserver().done(function() {
       ko.applyBindings(vm, domNode);
       jquerybindings();
     });
   }
})

// another code
And add return statement at the begining of loadfromserver function:
loadfromserver = function (Id) {
   return $.post("/song/getsong", "id=1", function (response) {
    // code
   });
}

Comment: @mcottingham Yes, you are right. There is also another error with not proper usage of closure. Your viewmodel looked a bit complicated for me, so I decided to re-factor it. You can find working result at http://jsfiddle.net/DaFNL/1/
Comment: @mcottingham in your source code you defined `song` variable twice: once - in scope of `my.managesongviewmodel` function and second - in scope of ajax callback function. So, when you assign new instance of `my.song` pseudo-class it was assigned to local `song` var and not to `song` var of your view model. So, when I suggested my solution with `vm.loadfromserver().done` there was still error with that local `song` var inside `$.post(...,..., function () { var song = ..}`
Comment: Exactly the answer I was typing. +1 for proper handling of the jqxhr object.
Comment: Also as the code improvment you can replace `ko.applyBindings(vm, domNode)` with `ko.applyBindingsToNode(domNode, { template: { name: 'manage-song-template' } })`. Then you can also remove call of `attr('data-bind', ...)` method. This change makes your code faster and more elegant
Comment: @Serjio I've made the modification suggested, however, I am still getting the same error.  The alert is still showing the title text.
Comment: @mcottingham can you give me a url of jsfiddle, etc?
Comment: I've created a jsfiddle: http://jsfiddle.net/mcottingham/H7jqa/10/  I've never made one before so I'm not 100% sure that I've done it correctly.  Any assistance would be greatly appreciated.
Comment: @Serjio Thank You!  I've been staring at this for 3 days and have not been able to find the issue.  Where was my issue with closure?
Comment: @Serjio ah, ok.  I guess that I wasn't thinking that the 'song' of my.managesongviewmodel would be in scope of the callback function.  I guess it is sort of obvious now that you mention it.  Thank you!

Knockout Complex Data Model Binding


Get Link value in Media entity

Question: We have a Media type called Documents that has a Link field called field_link. We need to obtain the URL (external or internal) from the field so that we can use to wrap block elements inside of a  tag in our twig templates. All works fine when the link is an external URL, but when linking to an internal page, the following code does not work in our mymodule_preprocess_media hook.
How can I obtain both the internal and external link within the field_link field inside of the mymodule_preprocess_media hook?
This is what we have tried, but only works for external links.
function mymodule_preprocess_media(&$variables) {
  $media_entity = $variables['elements']['#media'];
  $link = $media_entity->get('field_link')->first();

  // This works for external, but not internal
  $link_value = $link->getUrl()->getUri();

  $variables['custom_var'] = [
    'link_value' => $link_value,
  ];
}

media--document.html.twig

{{ name }}

When using ksm($link->getUrl()), we find that the uri value is NULL when the link is internal.
Goals:

Get the internal link (absolute) using hook_preprocess_media
Get the external link using hook_preprocess_media
Comment: Normally it doesn't matter if you have a field object or a field item, but for the Link field it does, use `->first()` and then it should work, see https://drupal.stackexchange.com/questions/199262/how-to-get-the-valid-url-of-a-link-field-from-within-a-twig-template
Comment: Just a guess: `if (is_null($link->getUrl()->getUri())) { $link_value = \Drupal\Core\Url::fromUri($link); }`
Comment: @4k4 adding the `->first()` did solve part of the issue, but it was still having an issue with `internal` links so i followed the solution provided by `berramou`
Comment: Yes, the key is the url object. Once you've got it from the field item all problems are solved. Then the possible solutions are countless, because all url handling in Drupal is built around this object. See the answers in the linked question and here.
Answer: Try the following:
/**
 * Implements hook_preprocess_media().
 */
function mymodule_preprocess_media(&$variables) {
  $media_entity = $variables['elements']['#media'];
  /**
   * @note: in case your field not multiple, otherwise loop through the field.
   */
  $link = $media_entity->get('field_link')->first();
  if ($link->isExternal()) {
    //- External.
    $link_value = $link->getValue()['uri'];
  }
  else {
    //- internal.
    $link_value = $link->getUrl()->toString();
  }
  $variables['custom_var'] = [
    'link_value' => $link_value,
  ];
}

Comment: this lead to my solution so it is being marked as such. if someone wants to get the absolute URL for `internal` links then they replace `$link->getUrl()->toString()` with `URL::fromRoute($link->getUrl()->getRouteName(), $link->getUrl()->getRouteParameters(), ['absolute' => true])->toString();`. Not sure if you want to update the answer to reflect this, but adding it just in case as a comment.

Get Link value in Media entity


Replace the contents of a specific tab in a dojo/dijit TabContainer?

Question: I need to change the class of one of the the tabs - that panel will change from a subclassed ContentPane widget to a subclassed BorderLayout widget.
At the very least I can probably delete the child from the TabContainer and then insert a new child with the same tab title at the position of that destroyed tab. But is there a legitimate shortcut to simply replace the backing control without invalidating the tabs?
(Dojo 1.8 - programmatic instantiation of widgets)
Comment: Once you call `addChild(child)`, you pass a `var` of the type `ContentPane` rigth? Wouldn't it be possible, to override that `var` wih the new `BorderContainer`?
Comment: well, I can change that var - but that won't change whatever TabContainer-internal vars are pointing at the old ContentPane...  I need to tell the container that its contents are changing.  Or am I misunderstanding you?
Comment: well, than i thing this migth simply not be possible. As you already said, the `TabContainer` does not provide a `replace` Method or anything similar. But it should be possible to do a nasty workaroud doing `yourContentPane.set('content', yourBorderContainer.domNode);` or sth. like that.
Answer: Instead of adding tab via dijit/layout/ContentPane add it as dijit/layout/StackPane. Then use StackPane's methods addChild(widget), removeChild(widget)and/or selectChild(widget):
var tab1 = registry.byId("tab1"); // dijit/layout/StackContainer

var bc = new BorderContainer();
var cp1 = new ContentPane({
    content: "content pane 1",
    region: "top"
});
var cp2 = new ContentPane({
    content: "content pane 2",
    region: "center"
});
bc.addChild(cp1);
bc.addChild(cp2);

tab1.addChild(bc);
tab1.selectChild(bc);

See it in action: http://jsfiddle.net/phusick/szCb4/
Comment: Does exactly what I asked, thanks (Just 1 note for others: this requires knowing that you're going to be swapping a particular tab, and preparing ahead of time - would still be curious if there's a post-hoc method too.  But this works fine for now!)


Como estender um DIV até o fim da tela?

Question: Bom criei um div principal para comportar todos os elementos da página. Dentro dele tenho 3 outros divs: 1 barra de menu, 1 barra lateral, 1 area de conteudo.
HTML:

    Barra de menu

    Menu lateral:
.
.
.

    Area de conteudo:
.
.
.
.
.
.
.
.
.

CSS:
.principal{background-color:red;height:100%;}
.barra_menu{background-color:gray;widht:100%;}
.menu_lateral{background-color:blue;width:30%;float:left;}
.area_conteudo{background-color:green;width:70%;float:left;}

Eu quero que o menu lateral se estenda da posição de onde ele se encontra até o fim da página, mas não sei a solução.
Gostaria de obter uma solução baseada apenas em HTML/CSS preferencialmente sem utilizar posicionamento absoluto.
A seguir um exemplo visual do que eu quero fazer: https://jsfiddle.net/m17wuaLc/2/
Answer: Lhe recomendo utilizar a técnica do Sticky Footer, caso haja necessidade de compatibilidade com navegadores antigos.
Sua estrutura HTML ficaria assim:

* {
  margin: 0;
}
html, body {
  height: 100%;
}
.page-wrap {
  min-height: 100%;
  /* equal to footer height */
  margin-bottom: -142px;
}
.page-wrap:after {
  content: "";
  display: block;
}
.site-footer, .page-wrap:after {
  height: 142px;
}
.site-footer {
  background: orange;
}
.side-left{
  float:left;
  width: 30%;
}
.content{
  float:left;
  width: 70%;
}

    Menu

    Content!

  I'm the Sticky Footer.

Comment: Pode adicionar um exemplo de uso na reposta?
Comment: Sim, claro. Mas o link tem os detalhes completo.
Comment: É porque resposta com links apenas não estão dentro do tipo de resposta que o site aceita como positiva. Para que sirva de referencia no futuro, caso este link deixe de existir, seria interessante ter um exemplo de uso na resposta também.
Comment: Pronto, exemplo incluso.
Comment: achei essa técnica muito interessante, mas o que estou fazendo aqui não tem um rodapé fixo, é um layout que se assemelha a de um aplicativo
Answer: Pode usar a propriedade:

1vh (viewport height) = 1% of viewport height

vai ficar assim
min-height:100vh;

Comment: o menu lateral  não se localiza no topo da página, há uma barra vertical antes dele. ao aplicar a propiedade proposta o menu é estendido além do limite da tela. Procuro uma solução que estenda o menu da posição onde ele se encontra até o fim da tela
Answer: Primeiramente você deve dar ao body um
height: 100%

E a seu menu lateral-direito, o mesmo. Ficaria assim:
body{
   height: 100%
}
.menu_lateral{
   height: 100%;
}

O body possui de padrão um
     height: auto
Devido a isso o body se estenderá ao tamanho do maior elemento. Dando um height: 100% isso será desfeito e ele terá o tamanho da tela.
Comment: o detalhe que o menu lateral não se localiza no topo da página, há uma barra de menu antes dele. De modo que se aplicar um height 100% no menu lateral será considerado o tamanho da body relativo a posição que ele se localiza, o que estende o menu lateral além do limite da tela/elemento-pai
Comment: eu queria que pegasse da posição que ele se encontra até o fim da tela
Comment: Olhe esse jsfiddle, se for o que queria, explico em detalhes o que fiz. https://jsfiddle.net/m17wuaLc/6/
Comment: samir braga, acaba entrando no problema de todas as respostas até aqui, como há uma barra de menu antes do menu lateral é atribuido ao elemento o height:100% considerando a posição que o elemento se encontra, esticando o menu além do limite da tela... compare o seu exemplo com este: https://jsfiddle.net/m17wuaLc/7/
Comment: Não entendo a que se refere, se está se referindo ao fato do barra lateral ultrapassar o menu, isso não aconteceu no meu exemplo. Até mesmo quando atribuo um height ao menu superior. Olhe https://jsfiddle.net/m17wuaLc/8/ .

Como estender um DIV até o fim da tela?


Choosing a guitar: left handed or right handed

Question: When I was a kid and took a guitar for the first time my first instinct was to hold it in a left handed manner. I still feel, that it's my natural way to play.
But today I watched the video "How to choose an Acoustic Guitar" where mr. Gary Wineroth - an experienced player says:
"The guitar was invented by a left handed person, so your dexterity was upon your left hand upon the fingerboard. I am a left handed person but I play with my left hand upon a fingerboard which is considered a right handed position.
Regardless whether you are left handed if you haven't started playing we always recommend that you play it in a normal right handed position."
So if I haven't played yet and want to learn, should I go against my instinct and buy a right handed guitar? Plus they are cheaper and there is a bigger variety of such guitars in the shops.
Comment: I would go to a store with both and play around with each kind and pick the one most comfortable to you. You may spend a huge amount of time and money on playing guitar, so it makes more sense if you are enjoying yourself. Choose the kind of guitar that is most fun and interesting and comfortable for you. Pretty much any guitar can be strung left-handed if the nut is changed out.
Comment: I would like the citation for "The guitar was invented by a left handed person." Although Gary is an experienced player..
Comment: There are several questions and answers on this subject already on this site. Just about every aspect of this has been covered.
Answer: I would advise NOT making the mistake I did 45yrs ago and allow yourself to be talked into learning right-handed (usually by a "righty"). Down the track it will be your greatest regret and it will also be impossible to change (I've tried many times over the years).
Play some "air guitar" and ask yourself what "feels" right (?)
Naturally, you will feel more comfortable playing left-handed for sure, so I'd go with it if I was you. Just listen to what your body is telling you feels comfortable.
Here are the main reasons:
Good rhythm, picking, runs (especially with a plectrum) will develop to a high level much quicker with your left hand than with your right.
Fretboard fingering is just muscle memory. Either hand can learn that well.
What you do with your other hand on the strings is more than just "muscle memory". It is the hand that of produces the sound from the guitar and that is were the music comes from!
Music is about rhythm, expression, delicacy when required and all sorts of string-hand dexterity and none of those things are "muscle memory".
Which hand do you think those most important qualities I mentioned are going to come from the best, giving each hand the same amount of practice time?
Answer: Whether you learn to play a "right handed" guitar or a "left handed" guitar, you will still need to develop skill and dexterity in both hands.  If you play around with both lefty and righty guitars and feel more comfortable with one or the other, then you can certainly learn to play either one.
Either way, it will take a tremendous amount of practice and repetition and dedication and commitment to learn to contort your fretting hand fingers into very strange and unnatural configurations and to learn to accurately play individual strings or maintain various strumming patterns with your strumming hand.
Once you learn one way - if you are like most folks, you will not be able to play the other way and will not want to re-invest the time and energy to re-learn from scratch.  In other words, if you learn to play on the more common "right handed" guitar and then later decide to switch to a left handed guitar, it will be like starting all over again from scratch - so you won't want to do that (it's like going backwards in your development).
So once you get to a certain point with either righty or lefty guitar, you will pass a point of no return (for all intents and purposes).  It is absolutely true that you will find a much wider selection of guitars to choose from if you learn to play with your left hand as the fretting hand and your right hand as your strumming/picking hand.  It's not uncommon to go into a music store and find over 100 "right handed" guitars and perhaps only one or two "left handed" guitars.
You can order a guitar to be built either as a left handed or right handed, and you can flip the nut and saddle and pickguard and convert some right handed guitars (if there is no cutaway).  But either of those options translates into more money on each guitar (custom ordered are usually more expensive than in-store inventory).  Eventually you may want several guitars and the scarcity and expense of finding "left handed" guitars could ultimately contribute to some frustration.
If you are at ground zero in your journey towards becoming a guitar player and  equally inept at the present time with either a left or right handed guitar, and you don't have a strong sense that it will be easier for you to learn to fret with one hand versus the other - then you might want to learn to play the more readily available, less expensive, "right handed" guitar.
However, if you find it much easier to make progress learning to fret with your right hand and strum and pick with your left hand, and don't mind the limited selection and higher prices associated with being a "left handed guitar player", then you could certainly learn to play "left handed".
Good luck with your journey whichever direction you choose to point your guitar!
Comment: I am right handed and play a standard right handed strat. I have tried playing a left-handed guitar and to my surprise found that the chord fingers (my right hand) knew what to do quite quickly. The strumming with left hand was more difficult, but then thats was a part I struggled with when learning so makes sense. Thus i'm not sure it's necessarily true that once you've committed one way or the other, that's it. I thinkit would be possible to change.
Comment: @user2808054  Certainly possible.  I agree.  But most folks don't adapt as readily and easily as you seem to be able to do.  I find it virtually impossible to play left handed - both strumming and forming chords.
Comment: there's me judging everyone by my own standards. fair point Mr. RC
Answer: I'm a lefty and I play lefty; no regrets.   Many righties here will give you advice about how you have an advantage if you play right-handed because your left hand is so well trained.   The question I have for them is then why don't they play left-handed?  It's the same theory.
Playing guitar is like using scissors.  Either you can do it right-handed or not.  The only advantage of playing right-handed that I've found is that there are more right-handed guitars available then left-handed guitars.    You're more likely to find a cool right-handed guitar at the guitar store than the lefty version -- if there even is a lefty version (note, used lefties are cheaper than their right-handed counterparts unless you're talking Rickenbackers and such).
Martin makes left-handed models without charging you extra.   Gibson charges like $50.  Left-handed Strats and Teles abound.  Access to left-handed guitars isn't hard.  The problem is that you may have to commit and buy a lefty guitar before you can try it because if it's new, it's probably being special ordered just for you.
I literally couldn't play right-handed and probably would have quit had I not tried left-handed.   Do what come natural.
Answer: My advice to you would be to play right handed guitars if at all possible. I know for some lefties it just simply becomes impossible but if you can in any way manage play the conventional way round.
There is real benefits for actual left handed players in doing this as your smart hand becomes the picking hand which requires a fair amount more dexterity than the one holding the strings down.
It will aid you in doing this but if you really struggle in passing the brain hemispheres then a left hand guitar may be OK.
Comment: Not sure at all about the 'smart hand' needing more dexterity. In fact, maybe the same, but probably more guitarists don't fingerpick than do.
Comment: Ironic - since the word dexterous has its roots in 'right-handed'!
Answer: I know a leftie who plays right-handed guitars in left-handed position -- so the bass string is nearest the floor. It suited him because he can pay "conventional" guitars using the hand that feel natural to him.
I don't really recommend that, but the moral is that you should play the way that feels natural to you.
Another illustrative anecdote: I took violin lessons as a child. My parents noticed that outside "duty" practice, I would play tunes by holding the violin like a guitar or ukulele. So they bought me a uke.
If you have an instinct for holding a certain type of instrument a certain way, then go with it.
Answer: go left handed! You said it's more natural for you :) I'm a right handed guitar teacher (greenwich music school and blackheath conservatoire). The picking/plucking hand should be the one you use to write. Do this exercises:

with the pick try down up down up, with a good flexible wrist movement of course ;) each string. start from the first string and go up (it's basically 4 times each string) and backwards. do it first with one hand and then the other side.

with fingers, do this exercise: pluck each string 4 times with your index and middle fingers (index - middle - index - middle). same order of previous exercise (all strings and backwards, try with one hand and than the other one). good relaxed/ soft finger tip ;)

Try different speeds, and you'll see ;) both exercises require only one hand at the time
Danilo
Answer: The world has vastly more of one of those configurations of guitar than the other; why would you want to limit yourself to only being able to comfortably play a small sub-section of all guitars?
Like RockinCowboy said, both of your hands/fingers on both of your hands need to learn how to do something. They don't care which is which.
Learning with a nonstandard instrument seems like it presents a miniscule upside, if even that, with a LOAD of downside.
Comment: The guitar market is so oversaturated and even for lefties so many instruments of all the common styles available that this isn't much of an argument. It may become an argument when looking for some unusual special configuration instruments, but because the guitar world is so stupidly conservative chances are off there anyway – if you want something like microtonal frets then you'll have to have it purpose-built regardless, and then it's again just as easy to have it built lefty as righty. — The availability argument _is_ relevant for for string instruments though, in particular bowed strings.


Bitwise operator in if statement

Question: While going through a code i saw this.
for(i=0; i<n; i++)
{
    for(j=0; j<n; j++)
    {
    if(i & (1<<j))
       {
         //code
       }
    }
}

can anyone how this loop will work?
I know that right part will give be pow(2,j), but i don't understand how will & work here.
Comment: Note that this code is only valid if `n < CHAR_BIT*sizeof(int)`.
Comment: okay could you explain how i & 2^j will yield result?
Answer: It loops over all values from 0 to n, and for each of these:
It loops over each bit in the value.  if the value is set:
It executes //code
Lets examine the complex part:
if(i & (1<<j))

1<<j is a common way to set the jth bit (starting from zero).  If j==0, then it's 0b00001, if j==3 then it's 0b01000.  Then i & <bit> evaluates to <bit> if that bit is set in i, and otherwise it evaluates to 0.  So this checks to see if the jth bit is set in i.
The value pairs that trigger the code are these:
i binary     js
0    000
1    001     0
2    010        1
3    011     0, 1
4    100           2
5    101     0,    2
6    110        1, 2
etc...
31 11111     0, 1, 2, 3, 4,

Notice how the 1s in the binary mirror the j values for which the code triggers.
Note that if n>=32 then it tries to shift the values too far, and that's undefined behavior.  Be sure that doesn't happen.

Bitwise operator in if statement


How do I create a bar between navigation bar and table header?

Question: In NYTimes iPhone application, one bar exist in between table header and navigation bar on the top news screen.
what bar is that? or it's just a label in between navigation bar and table header?
Thanks in advance.
Comment: It might be easier to get some help if you provide a screenshot of what you are referring to.
Answer: Yes, that's probably just a pair of labels with their background color set to gray and their text color to white. They might actually be implementing it in some other fashion (I haven't seen their code), but certainly that's the easiest way to do it.


How do we differentiate y = $\frac{x\sin x}{1+\tan x}$?

Question: How do we differentiate y = $\frac { x\sin x}{1+\tan x}$ ?
I am confused whether to use product rule for $x\sin x$ first but If do this. Then , when I will use division rule over this since I need to do for $1+\tan x$ also. I would have differentiated $x\sin x$ twice  or division rule for $x\sin x/1+\tan x$ but then I didn't use product rule first $x\sin x$
Comment: What happens when you try both ways?   Do you get different answers?
Comment: Either way works. You can view it as a product $x$ times $\sin x/(1+\tan x)$, and then do a quotient rule as part of that, or as a quotient of $x \sin x$ and $1 + \tan x$, and then do a product rule for part of that.
Comment: @RobertTheTutor Ohk. I didn't understand the second part you told . First one I got .
Comment: Please do not use tags that are inappropriate!
Answer: In general, if you need $(\frac{AB}{C})'$, you can view that as $A$ times $B/C$, or as $B$ times $A/C$, or as $AB$ divided by $C$.  Once you choose that, you find that you need another rule, quotient in the first two cases, or product in the last, in order to finish the overall rule you are doing.
So, $$\big(AB/C\big)' = ( A \cdot (B/C) )' = A' \cdot (B/C) + A \cdot (B/C)' = A'B/C + A \cdot (CB' - BC')/C^2$$
or for the last case, you can do
$$\big(AB/C\big)' = ( (AB)/C) )' = \frac{C \cdot (AB)' - (AB)C'}{C^2} = \frac{C\cdot[A'B + AB'] - (AB)C'}{C^2}$$
In your case, $A= x, B = \sin x$, and $C = 1 + \tan x$.
Answer: Here are four approaches. The first two are (I think) what you are deliberating over. The latter two are techniques that, for what its worth, avoid using the quotient rule.

You can view it as $\frac{[x\sin x]}{1+\tan x}$ and use the quotient rule first: $$\frac{(1+\tan x)\frac{d}{dx}[x\sin x]-[x\sin x]\frac{d}{dx}(1+\tan x)}{(1+\tan x)^2}$$ and then you need to use the product rule.

You can view it as $x\cdot\left[\frac{\sin x}{1+\tan x}\right]$ and use the product rule first: $$\frac{d}{dx}x\cdot \left[\frac{\sin x}{1+\tan x}\right]+x\cdot \frac{d}{dx}\left[\frac{\sin x}{1+\tan x}\right]$$ and then you need to use the quotient rule.

You can multiply to get $y(1+\tan x)=x\sin x$ and then use the product rule on each side: $$\frac{d}{dx}y\cdot(1+\tan x)+y\cdot\frac{d}{dx}(1+\tan x)=\frac{d}{dx}x\cdot\sin x+x\cdot\frac{d}{dx}\sin x$$ and then you can solve for $y'$. That will leave a $y$ hanging around, which you can substitute the orignial expression for.

You can apply $\ln\lvert\cdot\rvert$ to get $\ln\lvert y\rvert=\ln\lvert x\rvert+\ln\lvert\sin(x)\rvert-\ln\lvert1+\tan x\rvert$ and now differentiate using the chain rule: $$\frac{y'}{y}=\frac{1}{x}+\frac{\frac{d}{dx}\sin(x)}{\sin x}-\frac{\frac{d}{dx}(1+\tan x)}{1+\tan x}$$ That will leave a $y$ hanging around, which you can substitute the original expression for.
Comment: For the 1st one , we need to use product rule only for xsinx right ?
Comment: @Rider That's right.
Answer: A good mnemonic is "low d high minus high d low, down below the square must go".
You could use the quotient rule.  Get $\dfrac {(\sin x+x\cos x)(1+\tan x)-x\sin x (\sec^2 x)}{(1+\tan x)^2} $, then try to simplify.
I don't see much point in quibbling over whether to use the product rule or the quotient rule, it all amounts to the same thing.
Answer: Ask yourself: When evaluating the right hand side, what's the last operation you do, a product or a division? The answer to that question tells which which derivative rule to use first, the product rule or the division rule.


Output prediction cannot understand the while statement

Question: I'm looking for the expalanation of this problem. I cannot understand the while part and why does it print 6.
#include <stdio.h>
#include<stdlib.h>

int main()
{
    int array[] = {1, 2, 4, 0, 4, 0, 3};
    int *p, sum = 0;

    p = &array[0];

    while (*p++)
        sum += *p;

    printf("%d\n", sum);
    return 0;
}

Comment: Any `non-zero` number is `true` condition. Thus your loop runs till first `0`.
Comment: For your own sake (and ours too) please invest a minute or two of your time and format your code
Comment: the root cause of the problem is the ignoring of the C operator precedence, where the `++` will be performed, then the dereference
Answer: This is a more readable form of your while loop:
while (*p != 0)
{
  p = p + 1;   // you can put "p++;" here, which has the same effect
  sum += *p;
}

Now you should understand on your own.
Answer: Initially the pointer p points to the first element of the array.
p = &array[0];

However after evaluation the condition of the while statement
while(*p++)

the pointer was incremented and after that it points to the second element of the array that is to 2.
Within the body of the loop there is used the incremented pointer.
So you will have
2 + 4

The forth element of the array is equal to 0. So the loop stops its iterations.
You can consider the condition in the while loop the following way if to rewrite it as a for loop
#include <stdio.h>

int main(void)
{
     int array[] = {1,2,4,0,4,0,3};
    int *p, sum=0;
    p = &array[0];

    for ( int *tmp = p; ( ++p, *tmp != 0 ); tmp = p )
    {
        sum += *p;
    }

    printf("%d\n",sum);

    return 0;
}

If within the body to use the statement
sum += *tmp;

instead of
sum += *p;

then you will get the expected result equal to 7.
Answer: you are discarding the value from first element of array.
that is the reason why you see answer 6
you sum elements after you already moved to the next element of array
you should increment pointer in the end of iteration
while(*p){
  sum += *p;
  p++;
}

or
for( ; *p ; p++){
  sum += *p;
}

Answer: The loop runs until it encounters a zero value. However you increment your pointer before adding what it points to, to "sum".
So the loop adds the second and third elements to sum and stops at the fourth.
The value of sum is then: 0 + 2 + 4 = 6
Answer: Just modify your while loop as
while(*p)
sum += *p++;

Explanation
++, –– are unary operators used to increment, decrement the value of a variable by 1.
They can be used as postfix or prefix
But this was not just your problem. While loop terminated when it receives 0. Your array contains one of it.
So, instead use
for(int i=0;i<7;i++)  //7 -> size of array
sum += *p++;

o/p - 14


What happens if a goal is deflected by the referee?

Question: What happens in football if a player shoots the ball and the ball goes in the goal after deflecting off the referee? As far as I know it is given as a goal, but are there any other consequences?
Comment: I think the question is quite clear ("Is it a goal even if the ball hits the referee first") and the answers are good.
Answer: According to old FIFA Law 9: The ball in and out play:

If, when the ball is in play, it touches the referee or an assistant
  referee who is temporary on the field of play, play continues because
  the referee and the assistant referees are part of the match. (emphasis mine)

If a ball is deflected bouncing off a referee and goes into the goal, it's a goal in the same way a goal is scored when a ball is bounced off a goalpost  or crossbar and goes into the goal.
According to Law 9, 2. Ball in play of the new IFAB Laws:

The ball is in play at all other times, including when it rebounds off
  a match official, goalpost, crossbar or corner flagpost and remains in
  the field of play.

It happens very rarely, especially in a professional football game, because referees are trained well enough to be in a position where there is a very little chance of a ball touching them. Even if it happens, the game will go on.
Answer: Here is an instance of a referee "scoring" a goal. There was much protest from the defending side but the goal stood.
The referee in that match was José de Assis Aragão.

In the 1983 championship José de Assis Aragão refereed a Santos versus Palmeiras match in the Morumbi stadium. Santos lead by 2-1, but in the second minute of extra time there was a scrimmage in the Santos penalty box, the ball cannoned between legs and by accident the last leg it hit before ending up in the goal was the referee's. Aragão validated the goal correctly despite a lot of predictable complaints by the Santos side.

So the referee did the right thing in awarding the goal.


For Each com Where e Break By

Question: Não consegui encontrar um título adequado para a minha dúvida, mas vamos lá...
Considerando o trecho de código abaixo como exemplo:
def temp-table tt-test
    field id       as int
    field customer as int
    field added    as char.

create tt-test.
assign tt-test.id       = 1
       tt-test.customer = 100
       tt-test.added    = "".
create tt-test.
assign tt-test.id       = 2
       tt-test.customer = 100
       tt-test.added    = "".
create tt-test.
assign tt-test.id       = 3
       tt-test.customer = 100
       tt-test.added    = "".
create tt-test.
assign tt-test.id       = 4
       tt-test.customer = 100
       tt-test.added    = "".

def buffer b-tt-test for tt-test.

for each tt-test
   where tt-test.added <> "S"
   break by tt-test.customer:

    if tt-test.id = 2 then
        for first b-tt-test
            where b-tt-test.id = 4:
            assign b-tt-test.added = "S".
        end.

    disp tt-test.id
         tt-test.added
         last-of(tt-test.customer).
end.

Qual problema estou enfrentando: o for each continua trazendo o registro de id = 4 sendo que esse registro teve o campo added setado para "S", e no where do for each existe uma condição tt-test.added <> "S", ou seja, pela lógica ele não deveria aparecer.
O que eu preciso: no caso do código acima, preciso que o last-of(tt-test.customer) seja o registro de id = 3, visto que o registro de id = 4 não deveria mais ser lido pelo for each.
A título de curiosidade: se retirar a cláusula break by do for each, então o registro de id = 4 não é lido, mas em contrapartida sem o break by não posso usar o last-of.
Answer: O que vc precisa saber é que seria impossível ter um LAST-OF ou FIRST-OF sem uma pré-seleção dos registros. Por isso o registro 4 aparece com o break by, porque ele foi pré-selecionado antes mesmo da primeira iteração do laço ocorrer.
O ideal seria vc alterar os registros que podem estar à frente em um laço e fazer um for each sem restrições a seguir, tendo então dois laços, ou, se esse processo tiver que ser feito simultaneamente ao display, adicione um if antes do display.
Se você só queria uma resposta, pode parar de ler. Como um conselho, lembre-se que o display (a menos que isso seja um relatório com saída que não seja o terminal) pode levar tempo pra ser visualizado pelo usuário, e como vc está alterando o registro, o Progress automaticamente faz upgrade do bloco para uma transação, pra poder acomodar o seu assign. Você não explicitou um lock, então o Progress assume SHARE-LOCK. Se isso fosse uma tabela física, o Progress seguraria o lock enquanto o usuário está olhando os registros. Isso aumenta a chance de um dead lock.
Muito embora vc esteja trabalhando com temp-tables, eu evitaria essas construções pra não acontecer de mais tarde você acabar fazendo o mesmo com tabelas físicas. Acostume-se a escrever blocos com lock explícito (NO-LOCK ou EXCLUSIVE-LOCK, sempre), e defina as transações em blocos específicos. Tente ao máximo fazer iterações de leitura serem seu próprio bloco com no-lock, e seus updates dentro de blocos com exclusive-lock, e com transações explicitadas (de novo, pra temp-table em geral não precisa), essas boas práticas vão te poupar bastante dor de cabeça no futuro.
Comment: Obrigado pela resposta. Acabei descobrindo que para solucionar minha situação basta adicionar um índice na temp-table com o campo added ou customer, assim o registro de número 4 desaparece e o last-of passa a ser o registro de id = 3.

For Each com Where e Break By


Remove the resizing of images that are bigger then the max resolution. (reject instead)

Question: I'm using a very specific theme on the site where an image need to be exactly 1110x540.
I've set up the min and max resolutions and everything works perfectly, except when I upload an image that's bigger then 540px. Then the image rescales.
Is there a setting that rejects these images instead of resizing them ?
I'm using Drupal 7 btw.
Comment: Image styles don't 'accept' or 'reject' images, they just create an image from the options given to them. Form validation (i.e. based on your field instance settings) is used for validation; they're 2 separate parts of the system that don't talk to one another by default. Sounds like you'll need to write your own image style handler which does exactly what the standard scale/crop formatters do already, but while preserving the EXIF data.
Comment: Do you not just need to set maximum resolution in the field settings? Then the upload will fail altogether
Comment: Well no. This is the explanation of the filter: The maximum allowed image size expressed as WIDTHxHEIGHT (e.g. 640x480). Leave blank for no restriction. If a larger image is uploaded, it will be resized to reflect the given width and height. Resizing images on upload will cause the loss of EXIF data in the image.
Answer: Set min/max on the FIELD ITSELF, under content types. Not on the image style.
Comment: I might have explained myself badly. I'm not talking about image styles, I'm actually talking about the field settings. If you set a max size, and upload an image bigger then the max size, it will resize to fit. I'm looking for a solution that just plainly rejects it.
Comment: No, you explained fine, I simply had never noticed those fields aren't actually limits but rather they are guides, having always used image styles to handle resizing and cropping. You'll need to implement one of the file upload hooks like hook_file_presave to do this.
Answer: I know it's too late... you asked this 2 years ago hahaha
The scale filter is in includes/file.inc line 1809, specifically it tries to resize the image when is bigger than your setting... if it can't do it then returns the error "The image is too large; the maximum dimension...". So you have to comment the condition... you just return the error.
I know editing that kind of files is not a good idea but at least for me it worked.
I'm not pretty sure but maybe you can use hook_field_validate to override that condition.


pthread condition variables and mutex, program has a deadlock

Question: I'm having a problem with my multithreading code, there is a deadlock but I don't know how to fix it since I'm pretty new to pthreads.
The code below shows a function named "idle" that is waiting for a simulated process to be placed on a readyqueue, the push function is supposed to place that process on the queue and then signal that there is a process ready to be scheduled.
Here are the two functions that cause the deadlock:
void push(pcb_t *pcb) {
    pthread_mutex_lock(&queue_mutex);
    if (head == NULL) {
        head = pcb;
        tail = pcb;
    } else {
        pcb_t *old_tail = tail;
        tail = pcb;
        old_tail->next = tail;
    }
    pthread_cond_signal(&proc_ready);
    pthread_mutex_unlock(&queue_mutex);
}
extern void idle(unsigned int cpu_id)
{
    pthread_mutex_lock(&queue_mutex);

    while(head == NULL) {
        pthread_cond_wait(&proc_ready, &queue_mutex);
    }
    pthread_mutex_unlock(&queue_mutex);
    schedule(cpu_id);

    /*

     * idle() must block when the ready queue is empty, or else the CPU threads
     * will spin in a loop.  Until a ready queue is implemented, we'll put the
     * thread to sleep to keep it from consuming 100% of the CPU time.  Once
     * you implement a proper idle() function using a condition variable,
     * remove the call to mt_safe_usleep() below.
     */
}

Here is the gdb backtrace:
Thread 2 (Thread 0xb7df7b40 (LWP 3443)):
#0  0xb7fdd424 in __kernel_vsyscall ()
No symbol table info available.
#1  0xb7fb59e2 in __lll_lock_wait ()
    at ../nptl/sysdeps/unix/sysv/linux/i386/i686/../i486/lowlevellock.S:144
No locals.
#2  0xb7fb1267 in _L_lock_847 () from /lib/i386-linux-gnu/libpthread.so.0
No symbol table info available.
#3  0xb7fb10a0 in __GI___pthread_mutex_lock (mutex=0x804c75c <queue_mutex>)
    at ../nptl/pthread_mutex_lock.c:79
        __PRETTY_FUNCTION__ = "__pthread_mutex_lock"
        type = 0
        id = <optimized out>
#4  0x080489d9 in idle (cpu_id=0) at student.c:116
No locals.
#5  0x08048f65 in simulator_cpu_thread (cpu_id=0) at os-sim.c:259
        state = CPU_IDLE
#6  0x08049b4a in simulator_cpu_thread_func (data=0x0) at os-sim.c:618
No locals.
#7  0xb7faef70 in start_thread (arg=0xb7df7b40) at pthread_create.c:312
        __res = <optimized out>
        pd = 0xb7df7b40
        now = <optimized out>
        unwind_buf = {cancel_jmp_buf = {{jmp_buf = {-1208217600, -1210090688, 4001536,
                -1210092504, -193645269, -1085428949}, mask_was_saved = 0}}, priv = {
            pad = {0x0, 0x0, 0x0, 0x0}, data = {prev = 0x0, cleanup = 0x0,
              canceltype = 0}}}
        not_first_call = <optimized out>
        pagesize_m1 = <optimized out>
        sp = <optimized out>
        freesize = <optimized out>
---Type <return> to continue, or q <return> to quit---
        __PRETTY_FUNCTION__ = "start_thread"
#8  0xb7ee5bee in clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:129
No locals.

Thread 1 (Thread 0xb7df8700 (LWP 3439)):
#0  0xb7fdd424 in __kernel_vsyscall ()
No symbol table info available.
#1  0xb7fb59e2 in __lll_lock_wait ()
    at ../nptl/sysdeps/unix/sysv/linux/i386/i686/../i486/lowlevellock.S:144
No locals.
#2  0xb7fb1267 in _L_lock_847 () from /lib/i386-linux-gnu/libpthread.so.0
No symbol table info available.
#3  0xb7fb10a0 in __GI___pthread_mutex_lock (mutex=0x804c75c <queue_mutex>)
    at ../nptl/pthread_mutex_lock.c:79
        __PRETTY_FUNCTION__ = "__pthread_mutex_lock"
        type = 0
        id = <optimized out>
#4  0x0804886f in push (pcb=0x804c660 <processes>) at student.c:42
No locals.
#5  0x08048acb in wake_up (process=0x804c660 <processes>) at student.c:205
No locals.
#6  0x08049a14 in simulate_io () at os-sim.c:590
        completed = 0x804d0f8
        pcb = 0x804c660 <processes>
#7  0x08048e0f in simulator_supervisor_thread () at os-sim.c:189
No locals.
#8  0x08048dcc in start_simulator (new_cpu_count=1) at os-sim.c:161
        n = 1
        __PRETTY_FUNCTION__ = "start_simulator"
#9  0x08048ba8 in main (argc=2, argv=0xbffff284) at student.c:240
        cpu_count = 1
        __PRETTY_FUNCTION__ = "main"

edit: pop function that also uses the queue_mutex
pcb_t * pop() {
    pcb_t *pcb = NULL;
    pthread_mutex_lock(&queue_mutex);
    if (head == NULL) {
        return NULL;
    } else if (head == tail) {
        pcb = head;
        head = NULL;
        tail = NULL;
    } else {
        pcb = head;
        head = head->next;
    }
    pthread_mutex_unlock(&queue_mutex);
    pcb->next = NULL;
    return pcb;
}

Comment: Is the mutex used anywhere else? If it is, you need to show that code too.
Comment: pop: return NULL. does not unlock the mutex.
Comment: ok I added the only other function that uses the queue_mutex. It's at the bottom of the post.
Answer: Your pop function does not unlock the mutex when in the head == NULL case.
Comment: Thank you so much, moved the check outside the mutex lock and it works perfectly now.
Answer: Your mutex object should have been locked in an appropriate way after controlling if head is null in pop function, otherwise it remained blocked. And also, pthread_cond_signal function may be called by a thread whether or not it currently owns the mutex that threads calling pthread_cond_wait has associated with the condition variable during its wait; however, if predictable scheduling behaviour is required, then that mutex is locked by the thread calling pthread_cond_signal.
Comment: I did read it. So maybe I'm not understanding your point. The given code structure is text book and is correct. So I don't understand your point. Have a look at the example in the pthread_cond_init manual page. It is exactly the structure that vicg has used.
Comment: Again, don't think that's correct. Read the pthread_cond_wait manual. It unlocks the mutex before blocking on the conditional var.
Comment: @AlanAu Actually, It is correct. Why don't you read pthread_cond_signal manual ? http://pubs.opengroup.org/onlinepubs/007908775/xsh/pthread_cond_signal.html
Comment: @AlanAu I think there's been a misunderstanding. We're both saying the same thing over signal & wait functions differently. The problem was controlling list's head value before waiting for mutex object in appropriate signalling.
Answer: Your idle function locks the mutex, and then spin locks on your pthread_cond_wait.  Then when the scheduler feels like it, the push function is allowed to execute, but the first thing the push function does is attempt to grab the mutex.  Unfortunately, the mutex is already owned by the idle thread.  Therefore the push thread blocks, waiting for the mutex to be freed, which will never happen, because the idle function is spin locking on the pthread_cond_wait.
Comment: I don't think that is right. Read the pthread_cond_wait manual. It unlocks the mutex before blocking on the conditional var.
Comment: Correct, I missed that the cond_wait call does in fact unlock the mutex first.


Explanation of a recurrence relation in combinatorics

Question: I have the answer to the following question but I am not sure how this answer was solved. I am looking for some help with this explanation, thanks!

Find the recurrence relation for the number of ways to arrange flags on an $n$-foot flagpole using the three types of flags: red flags $2$ foot high, yellow flags $1$ foot hight and blue flags $1$ foot high

The solution is: $a_{n+1} = 2a_n + a_{n-1}$
My thinking was to consider cases, where it starts with a blue flag, or starts with a yellow flag or starts with a red flag.
And what are the initial conditions of this recurrence relation?
Comment: Well, the top flag is either red, blue or yellow.  If it is red then the remaining arrangement belongs to $a_{n-1}$.  If it is blue or yellow, the remaining arrangement belongs to $a_{n}$.
Comment: why does the remaining arrangements belong to $a_{n-1}$ if the top is red?
Comment: Because the red flag is $2$ feet long so, if the total length is $n+1$ then the other flags must take up $n+1-2=n-1$ feet.
Comment: and then the same explanation for if it is blue or yellow?
Comment: Well, follow the same logic only know the blue (or yellow) flag has length $1$.
Comment: also is this answer equivalent to $a_n = 2a_{n-1} + a_{n-2}$
Comment: Of course.  Though in both cases you have to specify initial conditions as well.
Comment: and what would $a_0, a_1$ be?
Comment: that's my next question
Comment: Please put in some effort of your own.  Note: it isn't clear what $a_0$ even means so you might be better off computing $a_1,a_2$.
Comment: thanks for your help
Answer: This is the same as counting the strings with length $n$ over the alphabet $\Sigma=\{RR,Y,B\}$.
Let us denote their number as $L_n$. We have $L_1=2$ (strings $Y$ and $B$), $L_2=5$ (strings $YY,BB,YB,BY,RR$) and for any $n\geq 3$
$$ L_{n} = 2 L_{n-1}+L_{n-2} $$
by considering the removal of the first symbol in a string with length $n$. If the first symbol is $RR$ the truncated string is a valid string with length $n-2$, if the first symbol is $Y$ or $B$ the truncated string is a valid string with length $n-1$. Conversely, each string with length $n$ can be obtained by pre-pending $RR$ to a string with length $n-2$, or by pre-pending $Y$ or $B$ to a string with length $n-1$.

By the generating functions machinery, $L_n$ behaves like $C\cdot(1+\sqrt{2})^n$ for large values of $n$.
You are actually dealing with Pell numbers.
Comment: thanks for this explanation, what would $a_1,a_2$ be? I am now trying to solve it
Comment: @mt12345: it is already there. $L_1=2$ and $L_2=5$.
Comment: thanks for your help, I think I understand!
Comment: is there no $a_0$?
Comment: shouldn't $a_0=1$?
Comment: @mt12345: yes, there is a single empty string.
Comment: awesome, thanks for your time!


Finding this probability, I need some explanation.

Question: If green and yellow seeds per plants are crossed and $15$ seeds are obtained calculate the probability of getting $(0,1,2,....15)$ green seeds. Green is a  dominant and hybrid gene, yellow is a recessive gene.
What will be sample space, event and the probability for green to be 0, 1 and so on?
Comment: Can you fix your spelling errors?? I'm having trouble understanding this question
Comment: Is the green seed parent heterozygous or homozygous?
Comment: If green is Heterozygous then? What will be the probability of getting 0 greens, 1 green and so on upto 15?
Answer: Do you know how to use the chart(2x2) that is usually taught in 7th grade that is used to find the probability? If not here's a link: https://en.wikipedia.org/wiki/Punnett_square
Then, use the Counting Principle to find all the probabilities for all of the independent events. Hope this helped!


plugin nao funcionando, routes e jquery

Question: Estou usando este plugin para explorar routes com jQuery sem precisar migrar para o AngularJS. Porem nao estou recebendo a resposta na caixa de log, que era pra retornar com o seguinte código
<code>$.router.add(/items/:item", "foo", function(data) {
console.log(data.item);
});
</code>
Qual ponto eu estou errando em especifico?
http://jsfiddle.net/kbsa5269/2/
No jsfiddle contem o link do plugin e uma demonstração, que nao esta a funcionar.
Answer: Acho que temos um erro de sintaxe.
<code>$.router.add("/items/:item", "foo", function(data) {
  console.log(data.item);
 });
</code>

plugin nao funcionando, routes e jquery


Rationale behind ad-hoc method definitions in Objective-C

Question: I started programming in C++. Because of this, I was taught early on that for each definition, there should be a declaration. With member functions, it is a requirement.
Now that I have started learning Objective-C, I was somewhat "shocked" to find out that you don't need to pair them up. Obviously, if you don't define a method, it will not be called. If you don't declare a method, but define it, it will be called.
What's the rationale for allowing this type of ad-hoc definitions? Since I'm biased by C++, I find it annoying to read other people's code, as many times, the methods aren't declared. It's hard to get an overview of the class's interface.
I found a couple of answers here: Objective c: method relation .h and .m. Unfortunately they're not very conclusive.
Answer: Objective-C and other languages include meta-programming tooling that allows you to define methods dynamically, so you could declare a specific method and have something else define it in runtime, you can see a classic example of this feature on this question about how to implement method_missing like functionality on Objective-C.
As for the other end, having methods implemented but not declared, there's no definite way to define private methods on Objective-C and from time to time you want to define methods that are known only to your own classes and not for everyone else. So, you don't declare the method in your .h file, but you implement it nonetheless at your .m file.
The compiler will usually complain that you are using an undefined method, but you can either ignore this or declare these private methods at your .m file as a special category, it would look like this:
<code>@interface YourClass (PrivateMethods)
  - (void) somePrivateMethod;
@end

@implementation YourClass
  - (void) somePrivateMethod { NSLog(@"Something!"); }
@end
</code>
Common patterns like Proxies (local or remote ones) usually rely on these meta-programming tooling to be available and they are quite common in languages like Java, Ruby, Python and Objective-C itself.
Comment: @private is for variables, not methods. Objective-C, like it's indirect parent, Smalltalk, does not have the notion of private methods.
Comment: I have this book that claims you can use `@private` to protect your methods... Is it just for show?
Comment: In ObjC2, you should no longer put "PrivateMethods" in the parentheses of your private API category (now "extension"). This word is just a comment, but including it causes the compiler to not check that `somePrivateMethod` is implemented. If you just use `@interface YourClass ()`, then the compiler will force you to implement all of the methods in the `interface` block. This is a new feature in ObjC2, and a welcome addition.
Comment: @Rob: Thanks! `@interface YourClass ()` is something I will definitely use to catch silly errors ASAP.


Dismiss keyboard on UITextField using Interface Builder

Question: I've seen this, but don't remember what Jedi technique exactly was used through interface builder to dismiss uikeboard when return key is pressed. Anyone knows how to do this?
Please do not post about using UITextFieldDelegate, I know that method, I'm only interested in forcing keyboard to be dismissed on return key being hit without any additional logic or protocol conformation.
Answer: Connect the IBAction with "Did End On Exit"  event in your xib of your textfield

<code>-(IBAction)textFieldDidEndOnExit:(UITextField *)sender
{

}
</code>
Comment: view.endEditing(true)
use this code for dismissing keyboard
Answer: <code>override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    if let touch = touches.first{
        view.endEditing(true)
       }
}
</code>


I want to start a ngrok server and log everything to a file and to the terminal but it isnt working

Question: Code:
<code>from pyngrok import ngrok

public_url = ngrok.connect(
    log_stdout=True, log_file="ngrok.log", log_format="json", log_level="debug", proto="tcp", addr="8080"
)
print(public_url)
while True:
    pass
</code>
I found this on the internet but it aint working, well its starting the server but its not logging anything, how do i make it log things?
thanks
Comment: Curious where you found this. `pyngrok`'s `connect()` does take `kwargs`, but I'm not sure passing those `log_` args would actually do anything, and in fact `pyngrok` cannot log to a file, as the wrapper relies on console log output for its own execution.

Might I suggest using the `log_event_callback` instead? I think that could possibly work for what you're trying to do, and it's documented [here](https://pyngrok.readthedocs.io/en/latest/index.html#event-logs).
Answer: I'm not familiar with that approach but in general, you probably want to do it a little bit differently. Check out the local ngrok API - https://ngrok.com/docs/ngrok-agent/api#list-captured-requests - which will let you capture all the requests in JSON for logging, replay, or whatever.
~ an ngrok employee


how to compare accuracy of the output of 2 nn trained with different perform functions

Question: Let's say I have 2 equal FFNN trained with the same data (multidimensional data, n>10), except that one uses mse as perfFcn and the other use sse.
If t is the target data, t1 and t2 are the output of each network. How can I compare t1 and t2 (so I can choose one network over the other). I was thinking of relative error:||t-ti||/||t|| but I'm not really sure.
Regards,
Answer: The only difference between sum of squares (SSE) and mean squared error (MSE) is the division by the dataset size:
MSE = SSE/n, where n is dataset length (or batch size)
So there is no qualitative difference between the loss functions, since the relationship is linear. Each optimum for MSE is also the optimum for SSE.
So in order to compare your models you can use MSE or SSE and you will get the same result. MSE is better for comparing because it takes the dataset length into account, but if you use the same test dataset it does not matter.
If you use NNs i would recommend MSE, because SSE messes with the learning rate for batch sizes larger then 1. MSE on the other hand scales the loss independent of the batch size.
Comment: What about sae, mae and crossentropy?
Comment: SAE and MAE are identical, except for the normalization. Cross Entropy is a different metric.
Comment: then, how can i compare nn trained with mse and crossentropy?


Cannot click on radio button - Cypress

Question: I cannot interact with the input element to select the first radio button.

Below is what I've tried by far;
export function clickOnMediaAutoLevel(level) {
  // button is not clickable without force: true, it is set to hidden in the CSS
  cy.get(locators.screen)
    .within(($screen) => {
      cy.get('div.radio-buttons')
      .contains('Media Audio Level')
      .find('input')
      .click( { force: true } )
    })
  cy.pause()
}

What am I doing wrong?
Comment: What is happening? Are there any errors on the console? And how does the HTML looks like?
Answer: Try to use .check() no .click(). Source - https://docs.cypress.io/api/commands/check.html#Syntax
Comment: Yes, for radio/checkbox, we can properly use check() instead of click(). Works for disabled elements.
Answer: Your input has a prop "hidden" and it is possible that it prevents firing of that event (like a prop "disabled" would do).

The hidden global attribute is a Boolean attribute indicating that the element is not yet, or is no longer, relevant. For example, it can be used to hide elements of the page that can't be used until the login process has been completed. Browsers won't render elements with the hidden attribute set.
The hidden attribute must not be used to hide content just from one presentation. If something is marked hidden, it is hidden from all presentations, including, for instance, screen readers.
Hidden elements shouldn't be linked from non-hidden elements, and elements that are descendants of a hidden element are still active, which means that script elements can still execute and form elements can still submit. Elements and scripts may, however, refer to elements that are hidden in other contexts.
https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden

Try to mimic clicking on the label, because right now you don't click input itself in an application. You should consider removing a "hidden" prop completely in that context.

Cannot click on radio button - Cypress


Unbalance images dataset

Question: I want to create a deep learning model to classify images. My dataset has around 400 classes and the classes have different number of images..

How can I train the deep learning network on unbalanced datasets of images?

I will use data augmentation to increase the amount of data. Also I will apply oversampling..

When should I apply oversampling before or after splitting the images into training, testing, validation sets?
Should I make oversampling manually?
Comment: what's the use of oversampling testing and validation anyways. I'd over sample training, but let test and validation be bit larger than they'd be with no oversampling..
Answer: Unbalanced classes are almost certainly not a problem, and oversampling will not solve a non-problem: Are unbalanced datasets problematic, and (how) does oversampling (purport to) help?
(See here for a general motivation for this answer. See here for a motivation for short answers. Longer answers are always welcome.)

Unbalance images dataset


Betting on a sample from a known distribution

Question: This was an interview question. Given a known distribution, sample a value from it with replacement for many times. Two people A and B bet on the sample with their own guesses, and the one closer to the actual sample value wins. What's your betting strategy?
The interviewer claimed the median value is better than mean. I didn't get it. Can someone explain? Thanks.
Comment: Try a simple example, such as a Bernoulli$(p)$ distribution.  When $p\ne 1/2$ the median and mean differ, but it is easy to see which strategy is better and why.
Answer: The mean is affected by outliers in the distribution, so does not inform us about the mid-point of the distribution. The median is not affected by outliers.
Consider three example distributions and see how the presence of one outlier affects the mean but not the median:

Example
Distribution
Median
Mean

1
[1, 2, 3, 4, 5]
3
3

2
[1, 2, 3, 4, 10]
3
4

3
[1, 2, 3, 4, 20]
3
6

So relating these examples back to your interview question: assume A picks the median, so 50% of the time the sample will be less than A's guess and 50% of the time greater. Therefore, if B picks a different value from A, A's guess must be closer to the sample value at least 50% of the time.
Now assume B picks the mean. In the first case, they pick the same number, so the outcome is a draw. In the second case, A wins 60% of the time, B wins 20% of the time and it's a draw 20% of the time. In the third case, A wins 80% of the time and B wins 20% of the time.
Comment: @jesse If B picks above A's guess, A is closer to all under-median samples, which are 50% of all possible samples. If B picks below A's guess, A is closer to all over-median samples, which also comprise 50% of all possible samples. No matter what side of A is picked by B, A is closer to at least half of all possible samples, so should be expected to win at least half the time (assuming B doesn't also pick the median).
Comment: Re "Therefore, if B picks a different value from A, A's guess must be closer to the sample value at least 50% of the time:" why does this follow?  It's not an obvious consequence of the definition of the median, which you haven't quite correctly characterized: it is not always the case that 50% of the time the sample will be less than the median.  What you can say is that *at least* 50% of the time the value will be *no greater* than the median.
Comment: It makes sense that "50% of the time the sample will be less than A's guess and 50% of the time greater.", while I don't understand why "A's guess must be closer to the sample value at least 50% of the time." How did you derive that?
Comment: @NuclearHoagie Very clear explanation, Thank you!
Answer: The median minimizes expected absolute distance between observations sampled from the distribution and a single value. That is:
$$
\underset{m}{\text{min}}\text{ }\mathbb E\left[
\left\vert X - m\right\vert
\right] = \text{median}
$$
This is in contrast to the mean, which minimizes expected squared distance.
$$
\underset{m}{\text{min}}\text{ }\mathbb E\left[
\left( X - m\right)^2
\right] = \text{mean}
$$
I think this is what the interviewer wanted to test if you knew.
Comment: This is the formal derivation I was looking for. Thank you!


CSS não carrega na build estática (next export)

Question: Estou usando yarn create next-app, para o meu primeiro projeto de site em React. Então usei o export para gerar o site estático e subi a pasta "out" no servidor para ver o resultado. Mas aparentemente todo o css está sendo ignorado. A documentação fala que não precisa nenhuma configuração, alguém sabe o que pode estar acontecendo?
Answer: Erro de principiante. Eu subi a pasta "out" e ela estava alterando o caminho onde o next coloca o css. Subindo o conteúdo dela diretamente no servidor funciona.


Use setTimeout with Recursion funtion

Question: I'm trying to make a slideshow. I peek at some snippets and then try to recreate them without plainly copying.
This is the snippet:
var slideIndex = 0;
showSlides();

function showSlides() {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > slides.length) {slideIndex = 1}
  slides[slideIndex-1].style.display = "block";
  setTimeout(showSlides, 2000); // Change image every 2 seconds
}

Well, what I do not understand how does the setTimeout works when the function was just called once, and why not to use setInterval outside the function.
Thanks a lot.
Comment: Why can you not use setInterval outside the function?
Comment: Actually this is my doubt.
When and why should I use the recursion with setTimeout instead a setInterval outside of it.
Comment: It totally depends on you how you code. There's no exact definition of how people are to code.
Answer: The last thing showSlides does is set a timeout to call itself again after 2 seconds. After that call finishes, it sets another timeout. That will continue forever.
In this case, there wouldn't be a noticeable difference if you used setInterval. Both would accomplish the same thing. setInterval would be easier to cancel though, which is an advantage.
Be sure to remove the call to setTimeout in showSlides if you do use setInterval though:
var slideIndex = 0;

function showSlides() {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > slides.length) {slideIndex = 1}
  slides[slideIndex-1].style.display = "block";
}

setInterval(showSlides, 2000);

To cancel the interval, capture the ID returned by setInterval and call clearTimeout:
let id = setInterval(showSlides, 2000);
clearTimeout(id); // This will clear and cancel the setInterval

Comment: Thanks a lot. I didn't know why the setTimeout was doing its thing, it was very clarifying.
Answer: check this snippet, It will work!, you need to use setInterval
   setInterval(showSlides, 2000);

var slideIndex = 0;
showSlides();

function showSlides() {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > slides.length) {slideIndex = 1}
  slides[slideIndex-1].style.display = "block";
}

setInterval(showSlides, 2000);

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5

Comment: Thanks for answering, both answers were great.

Use setTimeout with Recursion funtion


Change URL of WebBrowser in C#

Question: I am designing a simple application using c# and it has a web browser in it. I need to either (preferably) refresh the page that is currently inside the broswer, or navigate to a "new" url. I tried Browser.Url = new Uri("http://www.pandora.com/"); but I get an error when I try to compile it.

Error 1 Cannot implicitly convert type
  'string' to
  'System.Uri' c:\users\sean\documents\visual
  studio
  2010\Projects\Pandora\Pandora\Form1.cs 51 27 Pandora

What am I doing wrong?
Comment: It's working fine in my machine.  What's the line 51 in Form1.cs?
Comment: http://msdn.microsoft.com/en-us/library/system.uri(VS.80).aspx#CodeSnippetContainerCode2 I don't see any mistakes in your Uri definition :-?
Comment: Same here - your sample code looks just fine.
Answer: For some reason, it wanted me to write it like this:
Browser.Url = new System.Uri("https://www.pandora.com/", System.UriKind.Absolute);

This works so thats good.

Change URL of WebBrowser in C#


'WHERE' condition in an UPDATE TRIGGER giving syntax error :mysql version 5.7

Question: I am using mysql database(VERSION 5.7).
I created a table with the following CREATE command:
CREATE TABLE `attendance` (
  `id` varchar(11) NOT NULL,
  `hash` char(8) NOT NULL,
  `time_in` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `time_out` datetime DEFAULT NULL,
  `time_spent` time DEFAULT NULL,
  `purpose` char(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

I have a trigger with the following query:
DELIMITER $$

CREATE TRIGGER test_trigger
BEFORE UPDATE ON attendance
FOR EACH ROW
BEGIN
SET NEW.time_spent=TIMEDIFF(NEW.time_out,OLD.time_in) WHERE OLD.time_spent IS NULL;
END$$

DELIMITER ;

But mysql gives the following error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE OLD.time_spent IS NULL; END' at line 1

(The where condition makes sure that only current days records get updated)
How am I supposed to write the query?
Answer: You can't use a WHERE clause with SET inside a trigger.  Use IF instead:
DELIMITER $$

CREATE TRIGGER test_trigger
BEFORE UPDATE ON attendance
FOR EACH ROW
BEGIN
    IF OLD.time_spent IS NULL THEN
        SET NEW.time_spent = TIMEDIFF(NEW.time_out, OLD.time_in);
    END IF;
END$$

DELIMITER ;


Why is no second football game televised (possibly just in NY)?

Question: Something confuses the heck out of me in regards to TV broadcasting of (American) Football.
I used to live in Seattle.  On Sunday, there were the early games, and the later games.  One was selected to be televised at 1:00 (EST), and one at 4:00 (EST), regardless of which time slot the local team (Seahawks) were playing in.  Easy enough.
I now live in New York.  There are still early and late games, of course, at the same times.  There are two local teams (Giants/Jets).  But often if neither of those teams is playing in the later time slot, no game will be shown.  Why?
Now, the first impression I had was that this was just a remarkably poor programming decision made by TV execs...but I once heard the announcers at the end of the early game say something like:

A: And coming up next, you'll be seeing one of these three games...
B: Unless you're in New York, of course.
A: Of course.

Wha?
It sounded slightly sarcastic, like they understood that the policy was strange, but expected.
Is there a straightforward explanation for what's going on?
Comment: Typically your broadcast schedule is dictated by your local network, NYC gets special mention cuz it's huge...
Comment: For more information on an ongoing basis as to which games are televised where, I suggest checking out http://the506.com/nflmaps/ as well as reading their FAQ. It duplicates Zack's answer pretty much, but adds some more detail like going into what a primary vs secondary market is and how it is determined, etc.
Comment: @waxeagle It's true...but the way they were phrasing it made it sound like there was something else going on.  I'm having a tough time imagining why a NY network would decide that they weren't going to show a live NFL game, because a M*A*S*H rerun would be more profitable (yes, that was what they were showing instead).  Something smells fishy.  I know the NFL has very complex rules regarding television coverage, so I suspect that's the culprit somehow...but I can't locate the exact cause yet.
Comment: The FCC is considering new rules to force the NFL to change their blackout policies: http://www.buffalonews.com/city-region/fcc-seeks-an-end-to-blackout-of-tv-sports-20131101
Answer: An NFL franchised market (i.e. New York, Chicago, Dallas, etc.).
On a week when the NFL team (or teams) in a market is on the ROAD Sunday, Monday or Thursday night or Saturday afternoon, the market will receive three Sunday games... two telecasts by the network with the doubleheader week and one game by the network with the single game week. When an NFL team in the market is playing at HOME on Sunday afternoon, the market will receive two games... one game on FOX and one game on CBS, regardless of which network has the doubleheader week.
Situation #1: So lets say the NY Jets are playing at home on Sunday and the NY Giants are playing away on Sunday. Since both teams are in the NY market, the NY market will receive two games (JETS and GIANTS), one on CBS and one on FOX.
Situation #2: So lets say the NY Jets are playing on the road Sunday and the NY Giants are also playing on the road Sunday. Since both teams are in the NY market, the NY market will receive receive one double header station and one single game station. Since both teams are in the New York market, they CANNOT play at the same time. This means one team has to play on the doubleheader station and the other team has to play on the single game station. So a mock up of the schedule would look like this. Fox (doubleheader station) would air the Jets and Seahawks at 1:00 and CBS would air the Giants at 4:00.
This is the only way I can see your problem occurring.
Comment: Hmm.  This would explain things...because in NY, one team was traditionally *always* playing at home (either the Jets or the Giants), because they shared a stadium.  This would mean that the market would receive only two games.  If either had a non-standard start time (Thursday, evening, Monday, etc.) that would leave at least Sunday day slot open.  The rules surrounding this are exceedingly strange, intensely confusing, and endlessly frustrating.
Comment: Thanks, this clarifies why we only ever get 3 games. I always figured it was a local network preference and that seemed ridiculous. Glad to know it's actually a contractual thing.
Comment: Yeah, unless you have some sort of package from your cable provider, you're going to miss games.
Comment: Now I wonder what the heck the point of three vs two games is, based on when a local team is playing at home.  I think this whole thing infuriates me more than it should.
Comment: Most likely the imbalance is designed to encourage fans to go to games. When your team is home you have fewer games so you're more likely to go?
Comment: If the local market team is at home the market could still get three games if the local team is playing on the doubleheader network. For example lets say the Cleveland Browns play home to the Pittsburgh Steelers at 1 pm and CBS has the doubleheader that week. In that case CBS will show Browns-Steelers at 1 and the national game at 425 and Fox will show a game at 405


Proving Mathematical Induction

Question: I have the following exercise which I am trying to understand:
For which nonnegative integers $n$ is $2n + 3 ≤ 2^n$? Prove
your answer.
I know that we first have to inspect for the basis case and so we find that $n > 3$, since $n=1,2,3$ do not hold but $4$ plus does, so $n > 3.$ But for the Induction step I don't understand how to start it and the textbook solution is unclear, could anyone explain to me what this means?
Textbook solution: For the inductive step assume that $P(k)$ is true. Then, by the
inductive hypothesis, $2(k + 1) + 3 = (2k + 3) + 2 < 2^k + 2.$
But because $k ≥ 1 , 2^k + 2 ≤ 2^k + 2^k = 2^k+1$. This shows that
$P(k+1)$ is true.
Comment: Can you state explicitly which part of the solution is not clear to you?
Comment: Please use math latex formatting.

1) Show it's true for $P(4)$. 2) that $P(k)$ implies $P(k+1)$ 3) conclude it's true for all $k\geq 4$ by induction.
Comment: The Induction part is not clear to me, i dont understand how they got to 2^k+2 then 2^k+1.
Comment: The $(2k+3)+2<2^k+2$ comes from applying the induction hypothesis that $2k+3<2^k$.
Comment: Ok so far i understand that if we expand 2(k+1)+3 we get 2k+2+3 but why does the right side of the inequality have +2? shouldn't it have been 2^k+1?
Comment: If you are having trouble with the notion of mathematical induction itself, you could look at this [link](https://math.stackexchange.com/questions/581127/the-concept-of-mathematical-induction?rq=1) or [this one](https://en.wikipedia.org/wiki/Mathematical_induction).
Answer: $$2^1<2^2<\cdots<2^k$$ Hence $$2^k +2<2^k+2^k=2\cdot 2^k=2^{k+1}$$
Comment: Have you done inductive proofs before? This is what we call the "inductive hypothesis"… in other words we are assuming it to be true for that $k\in \mathbf{N}$.
Comment: Could you please explain where the +2 came from?
Comment: You said in your question $$2(k+1)+3=(2k+3)+2=2^k+2$$
Comment: So basically 2(k+1)+3 = 2k+3+2 then 2k+3 = 2^k then you add the +2? I feel stupid but how did you get 2k+3 to be 2^k?
Answer: Normally, when you have two functions $f(n)$ and $g(n)$,
where for all $n \in \Bbb{Z^+}$, you have that $0 < f(n), g(n),$
and you establish a base case $n_0 \in \Bbb{Z^+}$ such that $f(n_0) < g(n_0),$
you then have two separate strategies that you might follow
to inductively prove that for all $n \in \Bbb{Z^+}$ such that $n \geq n_0,$
it is true that $f(n) < g(n)$.

The first strategy would be to examine the general ratios:
$\displaystyle R_n = \frac{f(n+1)}{f(n)}, ~S_n = \frac{g(n+1)}{g(n)}.$
If you can show that for all $n \in \Bbb{Z^+},$ such that $n \geq n_0$,
that $0 < R_n < S_n$, then you can reason as follows:
Suppose that $f(n) < g(n)$.
Then, you also have that $f(n+1) = R_n \times f(n)$
and $g(n+1) = S_n \times g(n)$.
Therefore, since $0 < f(n) < g(n)$ and $0 < R_n < S_n,$
then $R_n \times f(n) < S_n \times g(n).$

The second strategy is very similar to the first strategy, except that instead of focusing on ratios, you focus on differences.
That is,
let $F_n$ denote $f(n+1) - f(n)$ and
let $G_n$ denote $g(n+1) - g(n)$.
Suppose that you can show that for all $n \in \Bbb{Z^+}$
such that $n \geq n_0$, you have that
$F_n < G_n$.
Then, you can reason as follows:
Assume that $f(n) < g(n)$.
Then, $f(n+1) = F_n + f(n)$
and $g(n+1) = G_n + g(n)$.
Then, because $f(n) < g(n)$ and $F_n < G_n$
you have that $F_n + f(n) < G_n + g(n).$

The second strategy above is what the offered solution focused on, differences.

To prove:
For all $n \in \Bbb{Z^+}$ let $f(n) = 2n + 3$ and let $g(n) = 2^n.$
Then for all $n \in \Bbb{Z^+}$ such that $n \geq 4$
$f(n) < g(n)$.

First, the assertion was manually verified for $n = 4$.
Then, (in effect), the offered solution noted that
$F_n = f(n+1) - f(n) = [2(n + 1) + 3] - [2(n) + 3] = 2.$
$G_n = g(n+1) - g(n) = 2^{n+1} - 2^n = 2^n.$
Then, the offered solution noted that for $n \geq 4$, you have that:
$F_n < G_n$.
This conclusion allowed the second strategy above, that focuses on differences, to be invoked.
Comment: I understand how you did it but the method we are following from the textbook is different i believe.
Comment: @MathStudy1 The only difference between the textbook approach and my Strategy 2, is that the textbook (in effect) said that $f(n) + F(n) < g(n) + F(n) < g(n) + G(n).$

Proving Mathematical Induction


Erro ao usar o comando add-migration. Usando json como arquivo de configuração

Question: Bom dia!
Ao realizar o comando add-migration, para fazer as migrações, estou recebendo o sequinte erro:
Add-Migration : Exception calling "AddFromFile" with "1" argument(s) : "'basePath'
        não pode ser uma cadeia de caracteres vazia("") nem começar com o caractere nulo.
        Nome do parâmetro: basePath"At line:1 char:1
        + add-migration Initial
        + ~~~~~~~~~~~~~~~~~~~~~
         + CategoryInfo          : NotSpecified: (:) [Add-Migration], MethodInvocationE
            xception
            + FullyQualifiedErrorId : ArgumentException,Add-Migration

Minha classe context
protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        ////////////////////////// MAPEAMENTOS ////////////////////////
        #region FluentAPI

        #region Barcos

        modelBuilder.Entity<Barco>()
           .ToTable("Barcos");

        modelBuilder.Entity<Barco>()
            .Property(e => e.Nome)
            .HasColumnType("varchar(150)")
            .IsRequired();

        modelBuilder.Entity<Barco>()
            .Property(e => e.CapacidadeAgua)
            .HasColumnType("varchar(50)")
            .IsRequired();

        modelBuilder.Entity<Barco>()
             .Property(e => e.CapacidadeOleo)
             .HasColumnType("varchar(50)")
             .IsRequired();

        modelBuilder.Entity<Barco>()
             .Property(e => e.SapId)
             .HasColumnType("varchar(10)")
             .IsRequired();

        modelBuilder.Entity<Barco>()
            .Ignore(b => b.ValidationResult);

        modelBuilder.Entity<Barco>()
            .Ignore(b => b.CascadeMode);

        modelBuilder.Entity<Barco>()
           .HasOne(b => b.CategoriaBarco)
           .WithMany(c => c.Barcos)
           .HasForeignKey(b => b.CategoriaBarcoID)
           .IsRequired();

        modelBuilder.Entity<Barco>()
            .HasOne(b => b.TipoOperacao)
            .WithMany(b => b.barcos)
            .HasForeignKey(b => b.TipoOperacaoID)
            .IsRequired();

        #endregion

        ////////////////////////// FIM MAPEAMENTO BARCOS////////////////////////

        #region CategoriaBarco

        modelBuilder.Entity<CategoriaBarco>()
           .ToTable("CategoriaBarco");

        modelBuilder.Entity<Barco>()
        .Ignore(b => b.ValidationResult);

        modelBuilder.Entity<Barco>()
            .Ignore(b => b.CascadeMode);

        #endregion

        #region TipoOperação

        modelBuilder.Entity<TipoOperacao>()
           .ToTable("TipoOperacao");

        modelBuilder.Entity<Barco>()
        .Ignore(b => b.ValidationResult);

        modelBuilder.Entity<Barco>()
            .Ignore(b => b.CascadeMode);

        #endregion

        #endregion

        base.OnModelCreating(modelBuilder);

    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {

        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();

        optionsBuilder.UseOracle(config.GetConnectionString("DefaultConnection"));

    }

}

}
Meu json file:
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=YOURSERVERNAME;   Database=YOURDATABASENAME; Trusted_Connection=True; MultipleActiveResultSets=true"

},
 "Logging": {
   "IncludeScopes": false,
     "LogLevel": {
     Default": "Debug",
      "System": "Information",
         "Microsoft": "Information"
}

}
}
O erro diz que o basepath está vazio, mas não está
Eu ainda não tenho as conexões do banco, pq ele vai ser online e ainda não passaram as informações, pode ser isso o problema?
Acho estranho pq para fazer as migrations, eu acho que não precisa de um banco (eu acho)
Comment: Conseguiu resolver este problema?
Answer: Verifique a estrutura do seu projeto em Propriedades > Aplicativo:

Depois verifique se essa versão está instalada no seu computador:
C:/Program Files/dotnet/shared/Microsoft.NETCore.App


Changing Rubber on a Ping Pong Paddle

Question: I have a ping pong paddle with one side that has sandpaper grip and another paddle with a nicer rubber that unfortunately is broken.
I want to put the rubber from the broken paddle on the paddle with the sandpaper rubber. Is there an easy way to change the rubber on a ping pong paddle?
Answer: You will need the following items:

Heat Gun (a hair dryer would suffice also)
Spray Adhesive

To remove rubber from a side of a ping-pong paddle:

Use the heat gun to warm the adhesive between the rubber and the paddle.
When the adhesive is warm enough, slowly begin to remove the rubber.

If your attempt to remove the rubber is of any trouble, repeat step 1.
It is important not to tear the rubber in any way, shape, or form.

Optional: If clunky remains of adhesive remain on either the paddle or rubber, you may use the heat gun to warm and slowly attempt to remove the adhesive.

To apply new rubber to a side of a ping-pong paddle (assuming old rubber has been removed):

Evenly apply spray adhesive to the paddle (assuming there are no clunky remains of adhesive are present).
Evenly apply the backside of the rubber onto the paddle.
Give the adhesive an adequate amount of time to bond between the rubber and paddle.

Applying weight to the applicable side of the rubber/paddle may accelerate the process.
Comment: Do you know of anywhere I could find an appropriate adhesive? @edmastermind29
Comment: This may be an [appropriate adhesive](http://www.amazon.com/Donic-Formula-First-table-tennis/dp/B003A2CLHK/ref=sr_1_5?s=sporting-goods&ie=UTF8&qid=1375880640&sr=1-5&keywords=table+tennis+glue). Personally, I would be satisfied with a general purpose spray adhesive with better than normal bond.

Changing Rubber on a Ping Pong Paddle