text:
Q: O Delphi possui coletor de lixo? O Delphi possui coletor de lixo automático? De que maneira ele funciona. Caso não exista, que ferramentas podem fazer isso?

A: Não existe no sentido mais aceito de garbage collector, embora dê para questionar este conceito. Delphi é uma linguagem de gerenciamento de memória manual com algumas facilidades na biblioteca, semelhante ao que se usa em C++ moderno, para quem conhece esta linguagem.
Vários tipos existentes na biblioteca padrão possuem um controle próprio da alocação da memória, em geral, através de um contador de referências que é uma técnica de coleta de lixo, mas que alguns não consideram exatamente um GC. Strings e arrays dinâmicos são exemplos de tipos que usam esta técnica.
Outra forma é através do TComponent. Todos descendentes dele se "auto gerenciam", assim quando um objeto é destruído ele fica responsável por liberar os seus filhos. A soma das duas técnicas citadas e o uso de interfaces podem facilitar bastante o trabalho quando estruturas complexas de objetos são montadas. Além disto é possível fazer o controle explícito com try-finally de forma muito semelhante ao que ocorre em Java e C# quando quer explicitar que um recurso deve ser liberado, com a diferença que o Delphi pode liberar o recurso e a memória no mesmo momento.
A facilidade do reference counting está disponível na biblioteca - implementando com interfaces - para ser usado com outros tipos que você deseje criar e ele seja necessário. A maioria dos tipos não precisam graças ao conceito de propriedade do objeto (só existe um proprietário).
Particularmente se a coleta do lixo é feita de forma automática sem intervenção do programador eu considero que de certa forma o Delphi tem um GC. É preciso deixar claro que a forma dele é por contagem de referência e não de rastreamento de referências (tracing GC). Oficialmente se diz que Delphi não é uma linguagem com GC, mas a biblioteca possui funcionalidade semelhante. Claro que no momento que você vai criar tipos, precisa se lembrar de cuidar do gerenciamento usando o que a biblioteca já oferece ou outra forma, mas o uso dos objetos passa ser gerenciado se usar o que está disponível.
Claro que é possível usar um GC rastreador se ele for absolutamente necessário mas não faz parte da linguagem - por isto não há muitas facilidades - ou da biblioteca padrão, você tem que providenciar toda infraestrutura dele. E não é aconselhável em quase nenhum caso.
Há uma experiência no site da Embarcadero (ou sei lá o nome que a empresa tem agora) para implementar o GC Boehm que é um dos GCs mais simples que existe, quase sempre tão ineficiente que não vale o esforço quando existe outra forma de gerenciar a memória automaticamente.
A linguagem organiza a memória de forma que falta metadados para um GC mais moderno já que ela foi pensada para não usar um GC.
Ao contrário da crença popular, um GC moderno consegue gerenciar a memória de forma mais rápida que outras formas. Em refcount é necessário incrementar o contador, depois decrementar e verificar se chegou a zero, tudo isso pode ser preciso fazer de forma sincronizada (atômica) o que é bem caro de realizar. E pode ser necessário fazer uma coleta para evitar vazamento por referências cíclicas ou usar uma técnica que pode gerar falhas. Em GC a alocação da memória costuma ser apenas um incremento em um ponteiro de forma semelhante ao que ocorre na stack e não há custo para desalocar quando o objeto não mais é necessário. O problema do GC moderno é o retardamento da desalocação e isto traz algumas desvantagens:

*

*O momento da liberação de recursos não é determinístico e ferramentas auxiliares na linguagem são necessárias para garantir esta liberação no momento certo.

*Também é indeterminado o tempo que levará para fazer toda liberação. É verdade que outras formas de liberação de memória também não podem ter o tempo determinado mas assim como no GC, há acúmulo, a indeterminação fica maior.

*Como o GC precisa determinar o que é útil e o que é lixo e em algumas implementações precisa copiar dados, o processamento total para a liberação acaba sendo maior. Há exceções.

Para saber mais sobre implementações de GC o artigo da Wikipedia mostrado acima já é um bom começo. Lá tem recomendação de bons livros sobre o assunto.
No caso do Delphi a "falta de um GC" faz pouca diferença para a maioria dos usuários, principalmente porque ele costuma ser usado em um conjunto mais específico de problemas. Para quem faz as bibliotecas o trabalho extra de gerenciamento costuma ser um problema maior.
Outra questão é que implementar um GC decente é bem complexo enquanto implementar um mecanismo de contagem de referência é trivial.
Coloquei no GitHub para referência futura.

A: Não o Delphi não tem GC. O GC na minha concepção é a liberação automática de objetos alocados pelo programa por codigo gerado pelo compilador no executável. Codigo este que está à margem da execução principal, liberando o programador desta tarefa (de desalocar a memória préviamente alocada)
Exemplo : uma thread poderia executar o GC. Mas somente se o compilador gerasse codigo para registrar, em memória global, tudo que é alocado em tempo de execução, mas isso não é feito. o registro do que é alocado é somente feito para os tipos  :  Long strings, strings, dynamic arrays, variants e interfaces. E o motivo disso não ser feito para os outros tipos ou objetos é a queda de performance do executável, pois se a cada alocação de memória (e são muitas num executável) numa chamada de função fosse gerado codigo de registro de tudo que é alocado e a sua desalocação em momento inapropriado pela thread GC, a performance de execução teria uma queda e um custo na velocidade de execução.
O refCount que é usado para strings, arrays, variants e interfaces não pode ser considerado um GC, se fosse seu nome não seria refcount, mas GC.
O Delphi sempre foi uma linguagem intermediária no sentido de não ser nem de alto nível como o JAVA ou VB (que produz bytecode ao invés de codigo nativo) e nem de baixo nível como o Assembler que produz linguagem de máquina de altíssima velocidade de execução.
O Delphi está no meio, equiparável ao C, c++ (que também não tem GC)
A busca pela performance do executável juntamente com as características e padrões de linguagem adotados lá no inicio vindo do Pascal, Turbo Pascal e  Object Pascal fazem do Delphi uma linguagem sem GC, porém de alta performance e bem superior a seus pares  como VB e Java no que diz respeito a performance.

Senhores :
vejam esse estudo no link abaixo onde a pessoa faz um estudo detalhado sobre performance comparativa entre C#, Delphi Prism, Delphi 2009 e C++ Builder 2009.
E a conclusão é que o Delphi é superior em performance à essas 3 linguagens.
Infelizmente não tenho o mesmo estudo em comparação com o Java apenas para lhe satisfazer porque para mim não resta dúvida alguma do que postei, apenas não posso confirmar por estudos publicados.
E o que eu afirmei sobre o Delphi ser superior seria em Performance apenas, até poderia afirmar em relação a outros aspectos mas esperarei outros tópicos, pois a questão aqui era o GC.
Segue o link do estudo comparativo de performance :
http://www.ijcaonline.org/volume26/number1/pxc3874199.pdf
Conclusão do Estudo :

4.CONCLUSION
In terms of response time, the fastest programming language is the Delphi 2009 and the slowest programming language is the C++ Builder 2009. Although the managed language C# and the Delphi Prism are powerful in terms of code density, they are weak in terms of memory consumption and response time.
The Delphi 2009 is the most powerful programming language both in terms of memory consumption and response time

O contador de referência (refCount) implementado pela Embarcadero no Delphi tem objetivo de otimização de consumo de memória e performance no acesso a mesma (alocação e desalocação) uma vez que o custo de alocação de memória no HEAP por API do windows é alto em termos de ciclos de CPU utilizado. Desta forma o compilador aloca um grande quantidade de memória na inicialização do executável e esta memória vai sendo consumida em pedaços distribuidos para as várias alocações que são feitas durante a execução do módulo executável.
Neste modelo de contagem de referência, um pedaço de memória alocado por exemplo por uma WideString ou array dinâmico não é obtida diretamente de uma API do Windows mas é feito um pedido ao gerenciador de memória do Delphi FastMM que através do algoritimo RefCount se encarrega de entregar um pedaço de memória à string por um custo baixo em termos de ciclos de CPU utilizados.
O RefCount é um excelente otimizador de uso de memória, a não utilização do mesmo resultaria em duplicação de memória desnecessária. Já com sua utilização a memória é otimizada,
considere o exemplo abaixo :
Var
a, b : String;

Begin
a := 'asdqwe';

b := a;

End;
Com o RefCount não há duplicação. A alocação é feita primeiro para A que conta 1 no RefCount. Na instrução abaixo não há uma alocação nova de memória, não há copias, B simplesmente aponta para o mesmo endereço de A e o RefCount de A é incrementado em 1 resultando 2.
Na desalocação é feita o decremento dos contadores de referência. Quando o Contador chegar a zero a memória volta para o FASTMM para que seja usada novamente por novas alocações.
Conclusão :
O RefCount é um excelente otimizador de recursos de memória além de proporcionar velocidade no acesso a mesma, mas não pode ser considerado um Garbage Collector como alguns academicistas ou "programadores de lousa" querem fazer crer.
Referências :
http://docwiki.embarcadero.com/RADStudio/XE6/en/Memory_Management
http://docwiki.embarcadero.com/RADStudio/XE6/en/Internal_Data_Formats

Garbage Collection (ou garbage collector)
É uma estratégia para automação do gerenciamento de memória onde o compilador gera codigo para desalocação de forma automática liberando o programador da tarefa de desalocação (ou finalização de um objeto).
Vantagens
Retira a preocupação do programador em ter que liberar a memória alocada, provendo sempre uma memória em que não há vazamentos.
O problema é que a desalocação em muitos casos não é feita no momento em que o programa se desfaz da variável ou objeto em memória e isso traz desvantagens como queda de performance na execução do aplicativo, como pode ser visto abaixo;
Destanvangens
Apesar de ter a vantagem citada no primeiro parágrafo ele possui desvantagens. São processos que consomem recursos computacionais para decidir quais partes da memória podem ser liberadas, enquanto no gerenciamento manual esse consumo é mínimo. Outro ponto negativo é que o momento em que o objeto é realmente desalocado não é determinístico, o que pode acarretar na variação do tempo de execução de algoritmo em partes aleatórias.
A queda de performance de uma aplicação pode ser tal forma que àquelas que necessitam de uma performance superior teriam que suspender temporariamente o GC para não interferir no processamento. No .NET 4.6 já há diretivas ou métodos (TryStartNoGCRegion e EndNoGCRegion) para bloquear o GC de operar em um determinado trecho de codigo.
Referências :
http://pt.wikipedia.org/wiki/Coletor_de_lixo_%28inform%C3%A1tica%29
https://msdn.microsoft.com/en-us/library/ee787088%28v=vs.110%29.aspx
https://msdn.microsoft.com/en-us/library/system.gc%28v=vs.110%29.aspx


text:
Q: Workbooks.OpenText doesn't take 'fieldinfo' parameter The following code demonstrates the problem which is stated in questions title.
Copy & paste it in a new Microsoft Excel 2003 workbook.
Sub mytest()
    mypath = Application.GetSaveAsFilename()

    Workbooks.OpenText Filename:=mypath, DataType:=xlDelimited, _
        TextQualifier:=xlTextQualifierDoubleQuote, _
        semicolon:=True, _
        fieldinfo:=Array(Array(1, 2), Array(2, 2), Array(3, 2), Array(4, 2)), _
        Local:=True
End Sub

Execute the code. It will ask for an input file where you should use this semicolon-seperated test.csv.  It creates a new workbook and imports all the data from test.csv to sheet1.
The picture below shows the result

But It should have shown a result like this

fieldinfo:=Array(Array(1, 2), Array(2, 2), Array(3, 2), Array(4, 2))
states that Excel should treat all imported data as text.  Unfortunately it doesn't.

*

*The two-dimensional array: first number is the column number, second number stands for data type where 2 stands for text

*I have to use the 'local'-parameter because I'm on a localized OS with a localized Office 2003

*The operating system is irrelevant since it happens on Windows XP and on Windows 7

Can someone show me how to use opentext and fieldinfo in the correct way?
I already know the work-around with QueryTables.Add(Connection[...].
But thats not a solution for my case.

A: If you rename the extension from the input file from .csv to .txt the fieldinfo parameter works as designed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery Click Event for 'body' not working on iOS So to make click events work on iOS I know that it needs to have onClick="" or cursor:pointer...
However my click event is on my body (to close the menu) so how can I fix this without having the cursor always be a pointer? I tried @media screen but that doesn't work because if someone has a smaller computer it still has the pointer all the time (and I want it to work for tablets).
I tried <body onClick=""> with no luck.
My Code:
<pre>
  /* Open the sidenav */
  function openNav() {
    document.getElementById("mySidenav").style.width = "150px";
  }

  /* Close/hide the sidenav */
  function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
  }

  $('body').click(function(e){
    closeNav();
  });

  $('#mySidenav').click(function(e){
    openNav();
    e.stopPropagation();
  });

  $('.hamburger').click(function(e){
    openNav();
    e.stopPropagation();
  });
  </script>
</pre>

A: You should be able to detect iOS devices and only set the cursor: pointer in those cases.
var isiOS = (navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false);
if (isiOS) {
    $('body').css('cursor', 'pointer');
}


text:
Q: DECIMAL mysql and storage space? From my understanding of the manual for DECIMAL in the mysql docs, it states that each multiple of nine digits requires 4 bytes and the following for left over digits;
number of digits leftover  |   bytes

0                          |   0
1                          |   1
2                          |   1
3                          |   2
4                          |   2
5                          |   3
6                          |   3
7                          |   4
8                          |   4

So a decimal(12,6) would be equal to 6 bytes in total storage?
I know that the fractional part will always equal 6 digits as zeros are padded, but the integer part is not so for a DECIMAL(12,6) column does the storage get valued per row or at column definition?
Example
    DECIMAL(12,6)
 1: 178.999999 // 3 digits for integer part so total would be 5 bytes?
 2: 0.880000 // 1 digits for integer part so total would be 4 bytes?
 3  123456.123456 // 6 digits would equal 6 bytes?

Or will it always be 6 bytes if declared (12,6)?
EDIT
Also a decimal declared as (5,5) would take 6 bytes to store and a decimal declared as (12,6) would also take 6 bytes to store. Seeing as the storage size is not an issue would the difference in size affect how mysql retrieves or indexes the column?

A: For MySQL 5.1 (and higher), it splits up the storage for the integer part and the fractional part, and makes room for storage for the largest possibly number. So for a DECIMAL(12,6), you need 3 bytes for the integer part and 3 bytes for the fractional part. It doesn't look like it decreases storage based on the value; it sets the memory aside no matter what the value is.
You can check out the documentation here:
MySQL Decimal Manual Page

A: DECIMAL(12,6)

1: 178.999999 // 3 digits for integer part so total would be 5 bytes(Correct)
 2: 0.880000 // 1 digits for integer part so total would be 4 bytes?(Wrong)
 3  123456.123456 // 6 digits would equal 6 bytes?(Correct)
Explanation:
Leftover Digits Number of Bytes
0    0
1  1
2   1
3   2
4   2
5   3
6   3
7   4
8   4
and all multiples of 9 will contain 4 bytes
so 0.880000 will take 0 for integer part and 3 for fractional part hence 0+3=3


text:
Q: CSS and Images in HTML E-Mail I'd like to send HTML E-Mails from my ASP.NET Core application.
For that I'm using a library called FluentEmail. With that you can also user Razor as template engine for your Mail templates.
My problem is that the CSS, which is inside a style tag inside my templates head tag, has no effect on the mail when viewing in Gmail or Outlook for example.
Also images which lie on a ftp server don't display properly. In Outlook I get the error message:

The linked image cannot be displayed. The file may have been moved,
renamed, or deleted. Verify that the link points to the correct file
and location.

The weird thing is that when I reply to that E-Mail the image gets displayed fine in my answer.
My CSHTML looks something like this:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>???</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        CONTENT HERE

My C# code looks like this:
var assembly = Assembly.GetExecutingAssembly();

await Email.From("???", "???")
  .To(recipients)
  .Subject(mail.Subject)
  .UsingTemplateFromEmbedded(mail.TemplateFile, mail.TemplateModel, assembly)
  .SendAsync();

Do I have to pay attention to something special when using images and css in HTML Mails?


text: Q: Bounds of Integration for Nonhomogenous Linear System of Differential Equations For the method of variation of parameters for a system of linear differential equations, I'm just confused about the integration part. When you integrate from t0 to t, does it matter what t0 you choose as long as it is in the domain? Or are you supposed to choose 0? Because the integral yields different +C answers in both components of the matrix depending on your choice of t0.


text:
Q: Android - MediaPlayer Crash I'm making an android application that plays music. When I run it, I get a NullPointer exception, and I have no clue why!!
Here is the code in my onCreate() in my activity:
MediaPlayer mp = MediaPlayer.create(this, R.raw.tekno);
    mp.start();

Here is my log cat:
06-03 17:09:51.520: D/MediaPlayer(19255): create failed:
06-03 17:09:51.520: D/MediaPlayer(19255): java.io.IOException: setDataSourceFD failed.: status=0x80000000
06-03 17:09:51.520: D/MediaPlayer(19255):   at android.media.MediaPlayer.setDataSource(Native Method)
06-03 17:09:51.520: D/MediaPlayer(19255):   at android.media.MediaPlayer.create(MediaPlayer.java:735)
06-03 17:09:51.520: D/MediaPlayer(19255):   at com.jlennon.gametest.PlayGameActivity.onCreate(PlayGameActivity.java:31)
06-03 17:09:51.520: D/MediaPlayer(19255):   at android.app.Activity.performCreate(Activity.java:4465)
06-03 17:09:51.520: D/MediaPlayer(19255):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
06-03 17:09:51.520: D/MediaPlayer(19255):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
06-03 17:09:51.520: D/MediaPlayer(19255):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
06-03 17:09:51.520: D/MediaPlayer(19255):   at android.app.ActivityThread.access$600(ActivityThread.java:123)
06-03 17:09:51.520: D/MediaPlayer(19255):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
06-03 17:09:51.520: D/MediaPlayer(19255):   at android.os.Handler.dispatchMessage(Handler.java:99)
06-03 17:09:51.520: D/MediaPlayer(19255):   at android.os.Looper.loop(Looper.java:137)
06-03 17:09:51.520: D/MediaPlayer(19255):   at android.app.ActivityThread.main(ActivityThread.java:4424)
06-03 17:09:51.520: D/MediaPlayer(19255):   at java.lang.reflect.Method.invokeNative(Native Method)
06-03 17:09:51.520: D/MediaPlayer(19255):   at java.lang.reflect.Method.invoke(Method.java:511)
06-03 17:09:51.520: D/MediaPlayer(19255):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-03 17:09:51.520: D/MediaPlayer(19255):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-03 17:09:51.520: D/MediaPlayer(19255):   at dalvik.system.NativeStart.main(Native Method)
06-03 17:09:51.530: D/AndroidRuntime(19255): Shutting down VM
06-03 16:36:23.340: W/dalvikvm(15997): threadid=1: thread exiting with uncaught exception (group=0x40a431f8)
    06-03 16:36:23.350: E/AndroidRuntime(15997): FATAL EXCEPTION: main
    06-03 16:36:23.350: E/AndroidRuntime(15997): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jlennon.gametest/com.jlennon.gametest.PlayGameActivity}: java.lang.NullPointerException
    06-03 16:36:23.350: E/AndroidRuntime(15997):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
    06-03 16:36:23.350: E/AndroidRuntime(15997):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
    06-03 16:36:23.350: E/AndroidRuntime(15997):    at android.app.ActivityThread.access$600(ActivityThread.java:123)
    06-03 16:36:23.350: E/AndroidRuntime(15997):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
    06-03 16:36:23.350: E/AndroidRuntime(15997):    at android.os.Handler.dispatchMessage(Handler.java:99)
    06-03 16:36:23.350: E/AndroidRuntime(15997):    at android.os.Looper.loop(Looper.java:137)
    06-03 16:36:23.350: E/AndroidRuntime(15997):    at android.app.ActivityThread.main(ActivityThread.java:4424)
    06-03 16:36:23.350: E/AndroidRuntime(15997):    at java.lang.reflect.Method.invokeNative(Native Method)
    06-03 16:36:23.350: E/AndroidRuntime(15997):    at java.lang.reflect.Method.invoke(Method.java:511)
    06-03 16:36:23.350: E/AndroidRuntime(15997):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    06-03 16:36:23.350: E/AndroidRuntime(15997):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    06-03 16:36:23.350: E/AndroidRuntime(15997):    at dalvik.system.NativeStart.main(Native Method)
    06-03 16:36:23.350: E/AndroidRuntime(15997): Caused by: java.lang.NullPointerException
    06-03 16:36:23.350: E/AndroidRuntime(15997):    at com.jlennon.gametest.PlayGameActivity.onCreate(PlayGameActivity.java:32)
    06-03 16:36:23.350: E/AndroidRuntime(15997):    at android.app.Activity.performCreate(Activity.java:4465)
    06-03 16:36:23.350: E/AndroidRuntime(15997):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
    06-03 16:36:23.350: E/AndroidRuntime(15997):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
    06-03 16:36:23.350: E/AndroidRuntime(15997):    ... 11 more

What I;m getting from this is that my MediaPlayer.create() is returning null, and I guess that must have something to do with my file.  My music file is tekno.wav.
Thanks a lot in advance!

A: 06-03 17:09:51.520: D/MediaPlayer(19255): java.io.IOException: setDataSourceFD failed.: status=0x80000000

It seems your WAV file isn't readable by Android for some reason. See the links below for some information that may be relevant:
setDataSourceFd Failed
MediaPlayer.setDataSource causes IOException for valid file

A: Try not to use getApplicationContext, this might return null.
Maybe that's what happened here as well.
So for example:
MediaPlayer mp = MediaPlayer.create(this, R.raw.tekno);

A: Try this:
MediaPlayer mp = MediaPlayer.create(this, R.raw.tekno);
mp.start();


text:
Q: LWC user id undefined I am developing a lightning component with LWC. In order to get the contact associated to the current connected user, I am getting the user id using this line of code :
import currentUserId from '@salesforce/user/Id';

The import does not show any issue, but when I try to access the value of the property it seems to be 'undefined'  even if I am using the component in a connected Salesforce environnement.
An example of the code used the property below
In the connected callback method :
  connectedCallback(){
     if(this.currentUserId){
         console.log('user id');
         console.log(this.currentUserId);
         this.currentConsultant = getContactFromUser(this.currentUserId);
         console.log('current consultant');
         console.log(this.currentConsultant);
         this.isGlobalView = (this.currentConsultant==null && (this.currentConsultant=== undefined))
     }  ...

//in rendered callback method

   renderedCallback() {
     console.log('rendered');
     console.log(this.currentUserId);

 }

Thank you in advance.
Have a great day.

A: Imported properties are like constants in LWC or ES6 in general, they can be accessed directly and does not need a this keyword.
Either you can use the property directly currentUserId without this:
console.log(currentUserId);

or
Define a local property, then you can use access the record id via this keyword:
import { LightningElement } from 'lwc';
import Id from '@salesforce/user/Id';

export default class ExampleGetUserId extends LightningElement {
    currentUserId = Id;
    connectedCallback() {
        if (currentUserId) {
            console.log("user id");
            console.log(currentUserId);
        }
    }
    renderedCallback() {
        console.log("rendered");
        console.log(currentUserId);
    }
}


text:
Q: Display WordPress post using bootstrap tabs and pagination I have been trying to display a list of posts with the bootstrap tab and pagination.
I have three tabs (Both, Blog, News). I am using next_posts_link and previous_posts_link for pagination. My bootstrap tab is working fine so is pagination. But when I try to go to another tab like the blog and try to paginate there the system is taking me to the first tab. Here is my full code:

    <button class="nav-link active" id="home-tab" data-bs-toggle="tab" data-bs-target="#home" type="button" role="tab" aria-controls="home" aria-selected="true">Both</button>

    <button class="nav-link" id="profile-tab" data-bs-toggle="tab" data-bs-target="#profile" type="button" role="tab" aria-controls="profile" aria-selected="false">Blog</button>

    <button class="nav-link" id="contact-tab" data-bs-toggle="tab" data-bs-target="#contact" type="button" role="tab" aria-controls="contact" aria-selected="false">News</button>

        <?php
            $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

            $the_query = new WP_Query(
                array(
                  'posts_per_page' => 6,
                  'post_type' => 'post',
                  'paged' => $paged
                )
              );
              $page_amount = $the_query->max_num_pages;

?>

Page <?php echo $paged ?> of <?php echo $page_amount ?>

<?php

if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post();
$post_id = get_the_ID();
?>

                <img src="<?php the_post_thumbnail_url() ?>" class="card-img-top" alt="...">

<?php the_title() ?>

<?php the_excerpt(); ?>

                        <a href="<?php the_permalink() ?>" class="read-more" >
                            <svg xmlns="http://www.w3.org/2000/svg" width="24.111" height="23.646" viewBox="0 0 24.111 23.646" style="margin-right: 10px; margin-top: -5px;">
                                <path
                                    id="Path_84"
                                    data-name="Path 84"
                                    d="M9.544.241a3.061,3.061,0,0,1,3.348.642c1.4,1.427,4.322,1.638,5.638,2.976,1.49,1.518,1.358,4.151,2.856,5.584a7.9,7.9,0,0,1,2.163,8.913,7.942,7.942,0,0,1-3.789,4.323c-6.319,2.6-14.617-.268-18.3-5.889-1.8-2.745-2.12-6.848.122-9.133C3.947,5.245,5.608,1.887,9.544.241Z"
                                    fill="#f3943f"
                                />
                            </svg>
                            Read More

        <?php

                    endwhile;
                        wp_reset_postdata();

                endif;?>

                <?php next_posts_link( 'Next →', $the_query ->max_num_pages); ?>
                <?php previous_posts_link( 'Previous ← ' ); wp_reset_query();?>

        <?php
            $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

            $the_query = new WP_Query(
                array(
                  'posts_per_page' => 6,
                  'post_type' => 'post',
                  'category_name' => 'blog',
                  'paged' => $paged
                )
              );
              $page_amount = $the_query->max_num_pages;

?>

Page <?php echo $paged ?> of <?php echo $page_amount ?>

<?php

if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post();
$post_id = get_the_ID();
?>

                <img src="<?php the_post_thumbnail_url() ?>" class="card-img-top" alt="...">

<?php the_title() ?>

<?php the_excerpt(); ?>

                        <a href="<?php the_permalink() ?>" class="read-more" >
                            <svg xmlns="http://www.w3.org/2000/svg" width="24.111" height="23.646" viewBox="0 0 24.111 23.646" style="margin-right: 10px; margin-top: -5px;">
                                <path
                                    id="Path_84"
                                    data-name="Path 84"
                                    d="M9.544.241a3.061,3.061,0,0,1,3.348.642c1.4,1.427,4.322,1.638,5.638,2.976,1.49,1.518,1.358,4.151,2.856,5.584a7.9,7.9,0,0,1,2.163,8.913,7.942,7.942,0,0,1-3.789,4.323c-6.319,2.6-14.617-.268-18.3-5.889-1.8-2.745-2.12-6.848.122-9.133C3.947,5.245,5.608,1.887,9.544.241Z"
                                    fill="#f3943f"
                                />
                            </svg>
                            Read More

        <?php

                    endwhile;
                        wp_reset_postdata();

                endif;?>

                <?php next_posts_link( 'Next →', $the_query ->max_num_pages); ?>
                <?php previous_posts_link( 'Previous ← ' ); wp_reset_query();?>

        <?php
            $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

            $the_query = new WP_Query(
                array(
                  'posts_per_page' => 6,
                  'post_type' => 'post',
                  'category_name' => 'news',
                  'paged' => $paged
                )
              );
              $page_amount = $the_query->max_num_pages;

?>

Page <?php echo $paged ?> of <?php echo $page_amount ?>

<?php

if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post();
$post_id = get_the_ID();
?>

                <img src="<?php the_post_thumbnail_url() ?>" class="card-img-top" alt="...">

<?php the_title() ?>

<?php the_excerpt(); ?>

                        <a href="<?php the_permalink() ?>" class="read-more" >
                            <svg xmlns="http://www.w3.org/2000/svg" width="24.111" height="23.646" viewBox="0 0 24.111 23.646" style="margin-right: 10px; margin-top: -5px;">
                                <path
                                    id="Path_84"
                                    data-name="Path 84"
                                    d="M9.544.241a3.061,3.061,0,0,1,3.348.642c1.4,1.427,4.322,1.638,5.638,2.976,1.49,1.518,1.358,4.151,2.856,5.584a7.9,7.9,0,0,1,2.163,8.913,7.942,7.942,0,0,1-3.789,4.323c-6.319,2.6-14.617-.268-18.3-5.889-1.8-2.745-2.12-6.848.122-9.133C3.947,5.245,5.608,1.887,9.544.241Z"
                                    fill="#f3943f"
                                />
                            </svg>
                            Read More

        <?php

                    endwhile;
                        wp_reset_postdata();

                endif;?>

                <?php next_posts_link( 'Next →', $the_query ->max_num_pages); ?>
                <?php previous_posts_link( 'Previous ← ' ); wp_reset_query();?>

Can you guys please me here?

A: I solved this by using this script.
$(document).ready(function(){
    $('a[data-toggle="tab"]').on('show.bs.tab', function(e) {
        localStorage.setItem('activeTab', $(e.target).attr('href'));
    });
    var activeTab = localStorage.getItem('activeTab');
    if(activeTab){
        $('#myTab a[href="' + activeTab + '"]').tab('show');
    }

});


text:
Q: How to move an entire div element up x pixels? I want to reposition an entire div and its contents up about 10-15 pixels.
How can I do this?
Note:  this is slider element, so when I click a button the slider slides down.  Once it is finished I want to reposition it up about 15 pixels.

A: $('#div_id').css({marginTop: '-=15px'});

This will alter the css for the element with the id "div_id"
To get the effect you want I recommend adding the code above to a callback function in your animation (that way the div will be moved up after the animation is complete):
$('#div_id').animate({...}, function () {
    $('#div_id').css({marginTop: '-=15px'});
});

And of course you could animate the change in margin like so:
$('#div_id').animate({marginTop: '-=15px'});

Here are the docs for .css() in jQuery: http://api.jquery.com/css/
And here are the docs for .animate() in jQuery: http://api.jquery.com/animate/

A: $('div').css({
    position: 'relative',
    top: '-15px'
});

A: In css add this to the element:
margin-top: -15px; /*for exact positioning */
margin-top: -5%; /* for relative positioning */

you can use either one to position accordingly.

A: you can also do this
margin-top:-30px;
min-height:40px;

this "help" to stop the div yanking everything up a bit.


text:
Q: SSL Handshake Client_Hello version I have a very basic question: how does client_hello or server_hello in SSL handshake determine what SSL/TLS version can it support? I mean, as far as I understand, first client and then server send out the highest possible SSL version they support. But, how is this determined?
Is it the version field in a certificate?
Best regards,
HL

A: This is all described in the TLS specification, appendix E. This is phrased slightly differently in the TLS 1.0, 1.1 and 1.2 specification, but the principle remains the same.
Essentially, the client asks for the highest version it can support and the server responds with the highest version it can support up to the client's version:
min(max. client supported version, max. server supported version)

This works as long as there the resulting version is indeed supported by both parties.

A: The client is responsible for initiating an SSL handshake by sending the ClientHello message. If this isn't the first message that is sent, the server responds with an error and shuts down the socket.
The client advertises to the server which cipher specs it supports, it's not required to support all of them.
The client sends the server the client's SSL version number, cipher settings, session-specific data, and other information that the server needs to communicate with the client using SSL.
The client also sends a challenge token, which the server must encrypt using the newly negotiated key before sending back the encrypted value, in its hello message. The client verifies that the decrypted token is the same as what was sent. If it's not, the handshake is rejected.
View the complete demo here


text:
Q: How to draw an double type 2D Image to an Axis Handle In matlabUI I have a double 2D image that I want to use in my UI that I made with guide.  I have a axis handle which I want to draw it to.  I tried this with no success, my image is all blue.
    function ComputeMap_Callback(hObject, eventdata, handles)
% hObject    handle to ComputeMap (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global healthyImage;
global sickImage;
global tumorMapImage;
global costFunction;
if(get(handles.radiobuttonMSE,'Value') == get(hObject,'Max'))
    costFunction = 0;

else

    costFunction = 1;
end
disp(costFunction);
tumorMapImage = mexFunction(im2double(sickImage),im2double(healthyImage),get(handles.blockSize,'Value'),get(handles.windowSize,'value'), costFunction);

image(tumorMapImage,'parent',handles.sImageGUI);

This mexFunction returns a double 2D image.  If I just call this function without matlab and imShow (resultImage); I get the right result.  So I believe it has something to do with the colormapping of the double and the fact that the image is not 3D but 2D.  But I am 0 familiar with gui in matlab to be sure what to do.  I've done some more researches and I think my problem might be related to the AlphaData property, but I don't know what to do with that.

A: your image values must be in range [0, 1] in order to be plotted properly by the image function.
imshow works because it first looks at the min and max value in your image and  then scales values to match this range. or so. (maybe it works differently internally, but whatever..)


text:
Q: Android Location Service broken when using tabs I'm building an android application which uses gps to locate the user. I have a class called LocationService which extends Service and implements LocationListener. In my activity I have the following code. When I want to turn on the service and listen for locations, I call the startLocationService() method. All this is working fine.
I then put this activity in a tab in a tabhost. Now when I call startLocationService(), nothing happens, the onCreate() method in LocationService is not even called. I checked the "this" reference in the line
Intent i = new Intent(this, LocationService.class);
and it refers to the correct activity, not the TabActivity.
I'm at a loss to explain why LocationService is not being started. I'd appreciate any light anyone can shed on this.
thanks,
Paul
private LocationService service = null;
private ServiceConnection svcConn = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder binder) {
        service = (LocationService)binder;
        try {
            service.registerCallback(cbListener);
            service.enableProximityPoints();

        } catch (Throwable t) {
            Log.e("MyPath", "Exception in call to registerAccount()", t);
        }
    }
    public void onServiceDisconnected(ComponentName className) {
        service = null;
    }
};

private void startLocationService(){
    Intent i = new Intent(this, LocationService.class);
    bindService(i, svcConn, 0);
    startService(i);
}

A: Looks like someone else has had a similar problem: http://www.mail-archive.com/android-beginners@googlegroups.com/msg08047.html
They solved their problem by moving the service connection up into the TabActivity class.

A:
I checked the "this" reference in the
  line Intent i = new Intent(this,
  LocationService.class); and it refers
  to the correct activity, not the
  TabActivity.

That might well be the problem - I've found activities as contents of tabs behave slightly differently to what I expect sometimes.
In the activity which is the 'tab content' activity try defining a class instance member...
private Context parent = null;

Then in onCreate() ...
parent = this.getParent(); // Gets the TabActivity context

Then in startLocationService() use...
Intent i = new Intent(parent, LocationService.class);

Not sure if it will work but worth a try. I'm currently working on a TabActivity based app and I'm having to do things like this in various places in the 'tab content' activities to get things to work correctly.


text:
Q: Parse CDATA with tag inside, using XMLReader PHP I would need to parse an XML file which contains a CDATA tag. Inside this tag, there is another tag that I want to get. How can I achieve this by using XMLReader?
Example:
<glz:Param name="TITLE">
       <![CDATA[Yellow <http://www.yellow.it>]]>
</glz:Param>

How can I get the whole info Yellow <http://www.yellow.it>? I can only get 'Yellow'.
This is my code:
// load file, create a reader variable, etc.
if($reader->nodeType == XMLReader::CDATA)
{
   echo $reader->value;
}

A: As per your comments:
The issue is likely that XmlReader correctly fetches the entire content in the CDATA tag, but your browser inteprets it as html again. Check the page source to see if it contains the a element. If so, try
echo htmlentities($reader->value);

or send a header with content-type: text/plain.

A: You can get it by string search. As you can see, String "http://www.yellow.it]]>"is not XML so that you can not parse it using XMLReader.
Please search string on it.
For example, you can split the string as "http:" and you can get 2 sub strings.
From second String, you can get the full link without ">]]>".
Hope it will be helpful.


text:
Q: pandas: How to Series.sort_index() in-place? Is it possible to sort_index a pandas' Series in-place?
Well, of course, you can do this:
ser = ser.sort_index()

What I'm actually trying to do is to sort_index a Series-derived class, like this:
class SeriesAutoSorted(Series):

    def append(self, index, value):
        self[index] = value
        self.sort_index(inplace=True)
        # Won't work: No inplace option for Series

where self = self.sort_index() won't work either obviously.

A: There's an undocumented Series._update_inplace() method that you could use. Pandas uses this internally
Here's an example:
In [50]: ser = pd.Series([5,6,7,5,4], index=[3,2,1,4,5])

In [51]: ser
Out[51]:
3    5
2    6
1    7
4    5
5    4
dtype: int64

In [52]: ser._update_inplace(ser.sort_index())

In [53]: ser
Out[53]:
1    7
2    6
3    5
4    5
5    4
dtype: int64


text:
Q: What security type is best for WCF (wsHttpBinding) Service and its Client sitting cross domain, and both uses same database So I have a WCF service i.e. a Proxy Service having Internet connection and hosted in Windows Service, which I want to expose wsHttpBinding.
Client for it is another WCF service (hosted in IIS) but has no Internet connection and uses Proxy service cross domain.
I am not able to connect that using wsHttpBinding unless I change Security Mode to "None".
What would be the best security authentication and configuration for this environment?
They both uses same database server.

A: Since you indicated you're not able to connect unless you change the Security Mode to 'None', I suspect this is because of your ClientCredentialType setting.  WsHttpBinding defaults to 'Windows' for the client credential.  This works great when client and service are in the same domain.  Since you're crossing security realms (domains), consider using 'UserName' as your client credential type instead.
Here is a sample.
As for which is best, that's hard to say with the limited amount of information here.  However, here's a link to Common Security Scenarios with guidance on how to configure your services for each.


text:
Q: Remove only specific table tags from HTML files using BeautifulSoup I am working on parsing hundreds of HTML documents using BeautifulSoup package. My code is able to parse entire documents very well.
I want to remove the content of all table tags depending upon on a condition. Since few tables (as per HTML tags) might not actually be tables, rather text presented inside a table. If the content of a table has more than 75% of characters as numbers, I would like to treat it as actual table and remove it, otherwise I would like to keep it.
I am new to Python and not sure how can I remove entire content of only specific  tables.
Suppose my HTML document is:
<document>

100

<text>
Hello Word
</text>

Test

</document>

Following code will generate content of entire HTML document i.e.
100
Hello Word
Test

What I want is:
Hello Word
Test

Please note that code also contains one function that is useful to check if text is useful or not. I am counting both alphabetical as well as numerical characters separately because there could be a lot of white spaces and other garbage characters.
Please help me in removing tables which are not useful i.e which contain more than 75% numerical characters. Please also note that table need not to be direct child of document.
from bs4 import BeautifulSoup
import html5lib
def isTableUseful(text): #Returns True if table is to be included
    try:
        countAlpha = 0
        countNumeric = 0
        for char in text:
            if char.isalpha():
                countAlpha += 1
            if char.isnumeric():
                countNumeric += 1
        FracNumeric = countNumeric/(countNumeric+countAlpha)
        return FracNumeric < 0.75
    except:
        return False
soup = BeautifulSoup("<document>
100
<text>Hello Word</text>
Test
</document>", "html5lib")
print ('\n'.join([e.encode("utf-8") for e in soup.recursiveChildGenerator() if isinstance(e,unicode) and e.strip()!=""]))

A: This should do it.
def should_remove(text):
    count_number = 0
    for c in text:
        if c.isnumeric():
            count_number = count_number + 1
    return count_number / len(text) > 0.75

# TODO: Initialize soup

# Remove all undesired tags from soup.
[s.extract() for s in soup.find_all('table') if should_remove(s.get_text().strip())]

#  Extract, format and print remaining text in soup.
# in Python3
[print(s.strip()) for s in soup.get_text().split('\n') if s.strip() != '']

# OR in Python2:
result = [s.strip() for s in soup.get_text().split('\n') if s.strip() != '']
for line in result:
    print line

Edit: Corrected list comprehension, extract text from soup.

A: You can check this: regex pattern in python for parsing HTML title tags
You have to adjust this below, from that link, to meet your needs:
title = soup.find('title').text

Then iterate all over them.
Or you can do regex, as suggested on that link too.


text:
Q: reverse engineering a serial protocol with a scope In lieu of a serial capture device are we able to look at the output of an rs-232 feed and correlate what we see on the scope with ASCII/hex representations (do certain voltages tend to correspond with this character representation or that  character representation? Line feeds and carriage returns come to mind) or are there too many variable to reverse engineer a serial protocol in this manner?

A: I have no idea what you mean by "X" and "Z".
Standard way to reverse engineer an RS-232 signal would be:

*

*Use the oscilloscope to figure out the baud rate. e.g., 0.104 ms pulse width would indicate 9600 baud. (\$ \frac {1}{0.104m} = 9600) \$.

*Use the oscilloscope to figure out the number of bits.

*Count the bits and see if the last bit changes state to keep the parity even or odd. If you can't see a pattern you can assume no parity bit.

*Hook up to a PC running a terminal emulator such as PuTTY.

*Set the baud rate to match and try various combinations of parity and stop bits until you start to see sensible data.

That will give you the raw serial data. You now have to figure out what it means.

A: Determine the baud rate, stop, start, parity with scope. Then use a computer terminal window to capture traffic. Even better would be to use Wireshark with PCAP and usb to rs232 converter. If the serial protocol is one of known protocols by Wireshark, it will detect and dissect the packets of data automaticly.

A: The difficulty in capturing and analyzing RS-232 signals on a scope is that the start pulse -- where the voltage first drops from a high logic level to a low one (if one is looking at UART levels), or rises from a negative voltage to a positive one (if one is looking at RS-232 levels) -- looks the same as any other bit, so it can be difficult to trigger on the first edge (whether trailing or leading) of the start pulse of the first character.
If you do trigger on one of the beginning edges of of the bits (whether the start bit or another one, if your sweep set so that you can capture more than one character, then you will be able to see any complete characters after the trigger -- the signal should break up into characters since the stop bit is longer than the others.  Look at the start bit, and then from the middle of the start bit, the middle of the bits that follow it will be dependent on the baud rate. At 9600 baud, that is 104 µS, and at 115,200 baud it is 8.68 µS for example.

The data in the two bytes (0x3D and 0x68) could either be hex data with the values as shown, or ASCII characters, also given.  Without other context it is impossible to tell.
The top diagram shows the RS-232 levels that you would see on a PC COM port (seldom seen anymore) or a USB to RS-232 cable.  The spacing or idle condition (0) is a negative voltage between -5 and -12v, and a marking condition (1) is a positive voltage between +5 and +12.
This bottom diagram shows the logic levels that you would see on the TX and RX leads of a UART.  Note that the bits are inverted -- a high logic level is a 0 (called spacing) and a low logic level is a 1 (called marking).
Here is a table to convert the bits to ASCII.
That said, many scopes now come with protocol analyzers for UART, I2C and SPI either standard or an optional module you can buy.  Or you can buy a stand-along logic analyzer that display the waveform on using a PC as the the display.

A: Note RS232 is a voltage standard, it does not define a protocol.  It defines what a one is and a zero, and pinouts for the connectors.
As far as decoding the serial protocol on a scope, it is not always possible (often not possible), and although scopes have uart, i2c, etc decoders, they dont always do a good job so it is better to take anything the scope tells you with a grain of salt and decode it yourself.  You will waste a lot of time debugging something assuming the scope software is right (for any serial protocol not just a uart style protocol).
As far as a serial protocol, the only time you are going to have a chance is if there is a long (more than a character) period between the stop bit and the next start bit.  From the scope with enough characters you can determine the baud rate.
By inspection with or without software or hardware for that matter you may not be able to determine how many data bits, if there is parity or not, how many stop bits.   If you manage to capture one character in isolation (has many idle/stop bits before and many after (and elsewhere you have determined the bit rate), you can figure out how many bits make up a character but you still wont know if there is parity or not, so you still cannot make any assumptions as to the values of those characters.
If you happen to know the size of the character and the parity, you can get there faster, but still have to work through framing errors deciding from the the middle of a continuous stream.  If there are enough idle periods before a start bit to insure that is really a start bit, and you know the data length and if there is parity, what kind and the number of stop bits, that is your best bet for decoding by hand (or having the scope software try to do it, hand check the first few characters or more of the scope's guess to make sure it is doing it right).
The scopes decoder if any and any real uarts are all going to have their own opinion of how the data is decoded, starting in the middle of a stream each will have its own way of working through framing errors and trying to sync up again, eventually they should all, if they know the protocol parameters (data bits, parity, stop bits, baud) should lock on if they are uarts worth using.  You may not have captured enough data in a stream to work through that either with the scopes software or by hand.
So you will need enough different characters in order to convince yourself what the baud/bit rate is.  But need some dead periods around single characters to isolate one and determine bits in a character.  And if you capture a dead period before a stream of characters, then you at least have a good start at decoding if you know the data bits, parity and stop bits.
Remember RS232 is basically inverted, a one is a negative value and a zero is a positive.  And uart protocols are normally lsbit first.


text:
Q: Dynamics CRM 2011 LinQ to Find New Records I have a bunch of custom entity records in a List (which comes from a csv file).
What is the best way to check which records are new and create those that are?
The equality check is based on a single text field in this case, but I need to do the same thing elsewhere where the equality check is based on a lookup and 2 text fields.
For arguments sake lets say I was inserting Account records, this is what I currently have:
    private void CreateAccounts()
    {
        var list = this.GetAccounts(); // get the list of Accounts, some may be new
        IEnumerable<string> existingAccounts = linq.AccountSet.Select(account => account.AccountNumber); // get all Account numbers in CRM, linq is a serviceContextName variable
        var newAccounts = list.Where(account => !existingAccounts.Contains(account.AccountNumber)); // Account numbers not in CRM
        foreach (var accountNumber in newAccounts) // go through the new list again and get all the Account info
        {
            var account = newAccounts.Where(newAccount => newAccount.AccountNumber.Equals(accountNumber)).FirstOrDefault();
            service.Create(account);
        }
    }

Is there a better way to do this?
I seem to be iterating through lists too many times, but it must be better than querying CRM multiple times:
foreach (var account in list)
        {
            // is this Account already in CRM
            // if not create the Account
        }

A: Your current method seems a bit backwards (get everything out of CRM, then compare it to what you have locally), but it may not be too bad depending on how many accounts you have ie < 5000.
For your simple example, you should be able to apply a where in statement.
Joining on multiple fields is a little more tricky.  If you are running CRM > R12, you should be able to use the ExecuteMultipleRequests, creating a seperate request for each item in your list, and then batching them all up, so there is one big request "over the wire" to CRM.


text:
Q: Recommendations for preventing RequireJS from interfering with legacy code I'm developing a 'widget', for lack of a better word, that will be loaded in many different sites that I don't control.
We're using RequireJS to keep things easy, but this has the side effect of breaking A LOT of sites that don't already use/support it.
The be clear - we don't control the sites, and the cause is that many of the sites existing libraries are loading into RequireJS instead of globally, and the code on these sites expects them to be loaded globally.
The only practical solution I can think of so far is to rename RequireJS' require() and define() (and perhaps others), then edit every library we rely on (using sed, of course) to load using the 'new' functions.
Has anyone else dealt with this? Is there a better method I'm missing?

*

*Michael

A: For anyone who stumbles upon this, here's what I ended up doing...
There isn't a good solution for this at the moment as:
1) All libraries that load into RequireJS need define() to exist in their scope at execution time
and
2) There isn't any mechanism for asynchronously loading scripts that would allow define to be defined (pun not intended) and undefined before/after execution, aside from eval(), and that's just not a good option.
This means that, it's not really possible to have some type of scoped RequireJS without it possibly interfering with other scripts on-page that CAN use RequireJS, but are intended to load globally on that particular site.
So... here's the hacky solution I did...
Instead of loading the JS libraries myself, I bundled them on the fly, along with RequireJS, and wrapped in an immediately executing function.
The reason for doing this on-the-fly, is that some site specific data is necessary for the program to function, and it saves an HTTP request to obtain it (at the expense of a larger file download).
This allowed me to:
1) Use libraries that need to run under RequireJS (or similar) to work property
2) Avoid cluttering up the global namespace for stuff like jQuery
3) Avoid editing library source (eg. changing define() to my_special_define() or similar)
I hope this helps someone if they're trying to do the same thing as me :)


text:
Q: How to set up a socket for UDP multicast with 2 network cards? this problem like How to set up a socket for UDP multicast with 2 network cards present?, but this is for C++, But I am in mono, So I want to know how to do this in C#.
I use follow code :
this.m_DhcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
this.m_DhcpSocket.Bind(new IPEndPoint(m_DhcpInterface.GetIPProperties().MulticastAddresses.FirstOrDefault().Address, DhcpPort));

but there is no Multicast address under Linux.
Can anybody help me?


text:
Q: Can't acces specific values in my node.js mongoose Model (only the Object) I have been working at this for the past 4 hours. I would therefore like some help. I want to access the specific values in my database, eg. as response.data.values.imglink although when adding imglink in console.log() I get undefined. I can get the general object but not the specifik values.
I have defined my Song Schema as:
const songSchema = new Schema({
    values: [{
    imglink: {
      type: String
    },
    id: {
      type: String
    },
    spotify: {
      type: String,
    },
    soundCloud: {
      type: String,
    },
    youtube: {
      type: String,
    },
    appleMusic: {
      type: String,
    }}
  ],
}, {
    timestamps: true,
})

As you can see values is an array of objects. People with a similiar problem on here hadn't included the correct values in their Schema, so maybe that's my problem? Although to me it looks correct. I then GET the values in my database. The JSON object usually looks something like this:
    [
  {
    "_id": "5ffbba4dc47e847a79c9c68f",
    "values": [
      {
        "_id": "5ffbba4dc47e847a79c9c690",
        "imglink": "imagelink",
        "id": "id",
        "soundCloud": "soundcloudvalue",
        "youtube": "youtubevalue",
        "appleMusic": "applemusicvalue",
        "spotify": "spotifyvalue"
      }
    ]
  }
]

I call it by this function, which is supposed to print out the individual values:
      const getAllSongs = () => {
    axios.get('http://localhost:5000/songs/'+id)
    .then(function (response) {
      console.log(response); // returns an object
      console.log(response.data.values.imglink); // returns an object
    })
    .catch(function (error) {
        // handle error
        console.log(error);
    })
  }

I have an Express route object that allows me to access a song by it's id as GET http://localhost:5000/songs/id in the VS-code HTTP client (similiar to postman):
    router.get(`/:id`, function(req, res) {
    return Song.find(
        {"values.id": req.params.id}
    ).then(function(song) {
        // return orders when resolved
        res.send(song);
        console.log(id);
        res.json('works yesss');
    })
    .catch(function (err) {
        // handle error
        res.status(400).json('Error: '+err)
    })
});

Here are some popular solutions I have tried:
Wrapping response in JSON.stringify() doesn't work.
toObject() and toJSON() don't work either as they aren't defined when I use them.
the _doc hack doesn't work either.
I have tried looking at the Schema which is where I think the problem is. The POST-request adds the right data, the GET-request goes through I just can't acces the specific values.
I hope you have the time to help, thanks. I will be extremely grateful. And of course let me know if you have any questions.

A: the result of find() is a Array so to access the desired key, if length of result Array is one, to access the desired key is response.data[0].values[0].imglink.
note: the values key is a array of obejct
If the array size is more than one, you want to see the result, you can use  map()
if it's not worked, using lean() like this
    router.get(`/:id`, function(req, res) {
    return Song.find(
        {"values.id": req.params.id}
    ).lean().then(function(song) {
        // return orders when resolved
        res.send(song);
         console.log(song[0].values[0].imglink); // type of song is array of object [] and values is array
        res.json('works yesss');
    })
    .catch(function (err) {
        // handle error
        res.status(400).json('Error: '+err)
    })
});


text:
Q: Changing string to NULL after the first iteration of cycle. Memory allocation The program should get the string from the file and separate them finding string "delim" in it. I should use dynamic memory but to my sorry I can't use it perfectly. Whats the reason for changing "cpystr" from "SUCCESSZOMBIEAAAAAAAaaaAZOMBIEaaAZOMBIEdf" to NULL after the first iteration of the cycle?"SUCCESSZOMBIEAAAAAAAaaaAZOMBIEaaAZOMBIEdf" where "ZOMBIE" is "delim". Help me to fix that. Thx for the help in advance!
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string>

char** split(const char *str, const char *delim)
{
    int cntr1, cntr2, cntr3, cntdelim=0;
    bool check;
    //counting "delim" in the str

    char **maspntr=NULL;
    char *cpystr=NULL;
    cpystr=_strdup(str); //reserve copy of the "cpy"
    strcpy(cpystr,str);
    for (cntr1=0;cntr1<(strlen(cpystr)+1);cntr1++) //THE PROBLEM WITH THIS CYCLE!
    {

    check=1;
    for (cntr2=0, cntr3=cntr1;cntr2<strlen(delim); cntr2++, cntr3++) //searching for "delim"
        if (!(cpystr[cntr3]==delim[cntr2]))
            {

                check=0;
                break;
            }
        if (check) //if it's foound, it copies the first N characters as the first element of pointers' array
        {

            maspntr=(char**)realloc(maspntr,(cntdelim+1)*sizeof(char*));
            maspntr[cntdelim]=(char*)calloc(cntr1, sizeof(char));
            cntdelim++;
            for (cntr3=0;cntr3<=(strlen(cpystr)-(cntr1+strlen(delim)-2));cntr3++)
            {
                cpystr[cntr3]=cpystr[cntr3+cntr1+strlen(delim)];
                cpystr=(char*)realloc(cpystr,(strlen(cpystr)+1-cntr1-strlen(delim))*sizeof(char)); //delete first N characters +"delim" by copying the characters from the end then modifying memory
            }

        }
         if(cpystr[cntr1]='\0') //if it is the end of string return
         {

             for (cntr1=0; cntr1<sizeof(maspntr); cntr1++)
         {
             printf(maspntr[cntr1],'\n');
         }
             free(cpystr);

             return(maspntr);
         }

    }   //Changing "cpystr" to NULL right here

}
int main()
{
    char singlech;
    int len=0;

    //copy string from the file to the variable
    FILE* foo;
errno_t err;
    err=fopen_s(&foo,"input.txt","r");
    if( err == 0 )
  {
      printf( "The file 'input.txt' was opened\n" );
  }
  else
  {
      printf( "The file 'input.txt' was not opened\n" );
  }
    while (!feof(foo))  //rather stupid way of getting memory
    {
        fscanf_s(foo, "%c", &singlech);
        len++;
    }
    char *str=NULL, *delim=NULL;

    str=(char*)calloc(len,sizeof(char));
    rewind(foo);
    fgets(str,len,foo);
    delim=(char*)calloc(sizeof("ZOMBIE")+1, sizeof(char));
    strcpy(delim,"ZOMBIE");
    split(str,delim);
    printf(str);
    free(str);
    free(delim);

    getchar();

}

A: I did not read all your code, but
cpystr = (char*)malloc(sizeof(cpystr))

allocates "size of pointer" bytes (perhaps 4 or 8), therefore the following strcpy()
writes beyond the allocated memory.
You probably mean
cpystr = malloc(strlen(str) + 1); // casting the return value of malloc not needed

But why not write simply
cpystr = strdup(str);

instead of malloc() + strcpy() ?


text:
Q: SAML WebSSO profile implementation I am going to implement ServiceProvider part using SAML 2.0 WebSSO profile. According to the SAML specification, the two supported flows are SP initiated and IDP initiated. I want to implement only IDP initiated flow because of time constraints. Will it work? or is it required to implement both the flows?
I dont want to generate any metadata for my SP. Can I still register my SP at IDP without providing any metadata by giving only default Assertion Consumer Service URL?

A: Short answer is yes it will work but... and yes if it is supported.
About implementing the IDP init SSO. It will work with only IDP init SSO if the IDP supports it. But your implementation will not be conformant with the SAML standard.
SAML does not require one to use metadata, this is just a good way to transport configuration data. If this will work depends if your IDP can be configured without using metadata. I have seen many that can do this.

A: Agree with @Stefan - no, you don't have to implement both flows.
SAML has many options - generally there is not enough information in the Assertion Consumer Service to fully configure e.g. certificates, public keys, supported endpoints etc.
But if the IDP allows this, you can do it manually - you just have to provide all the bits and pieces. And you'll have to do this again when the certificate expires etc. Metadata makes this all easier.
Java or .NET? If .NET, there are classes available to generate the metadata. Not sure for Java but would be surprised if there aren't.


text:
Q: ASP.NET MVC5 accessing one object from multiple instance I have the following code, which used in a web application using C# ASP.NET MVC5
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        var Db = new ApplicationDbContext();
        var user = await UserManager.FindAsync(model.UserName, model.Password);
        if (user != null)
        {
            await SignInAsync(user, model.RememberMe);

            user.LastLogin = DateTime.UtcNow;
            Db.Entry(user).State = System.Data.Entity.EntityState.Modified;
            await Db.SaveChangesAsync();
            return RedirectToLocal(returnUrl);
        }
        else
        {
            ModelState.AddModelError("", "Invalid username or password.");
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

What i want to do is to use the same object to do two different tasks:
 1. Login verfication
 2. Update the object's data. The data is saved in a SQL Server database.
The code above throws an exception that says:
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

Does anyone know how should i mitigate this?
EDIT #1
This is how my constructor looks like.
public AccountController(): this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{

}

public AccountController(UserManager<ApplicationUser> userManager)
{
    UserManager = userManager;
}

A: Ok i found the solution
What i did is by assigning different object. And use that object on a separate context.
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            var Db = new ApplicationDbContext();

            var user = await UserManager.FindAsync(model.UserName, model.Password);
            if (user != null)
            {
                await SignInAsync(user, model.RememberMe);

                var temp = Db.Users.Find(user.UserName);
                temp.LastLogin = DateTime.UtcNow;
                Db.Entry(temp).State = EntityState.Modified;
                await Db.SaveChangesAsync();

                return RedirectToLocal(returnUrl);
            }
            else
            {
                ModelState.AddModelError("", "Invalid username or password.");
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

A: You already have a context to use that you pass into the UserStore. You can reuse that and never have to deal with multiple contexts.
public class AccountController : Controller
{
    public AccountController ()
    {
        Context = new ApplicationDbContext()
        UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(Context));
    }

    protected ApplicationDbContext Context { get; private set; }

    protected UserManager<User> UserManager { get; private set; }
}

Now just use Context to get a reference to your DB. I would also recommend looking into a BaseController class to hold this for reuse and a Unit of Work pattern to hold your context.


text:
Q: how to use ComparisonPredicate as part of query in a procedure using oracle I am writing a query where I am checking for column value based on the values like Equals,Not Equals and Starts With.I want to pass these values to query dynamically. can any one suggest me.
SELECT * FROM EMP E WHERE E.SAL >= 30000

I should be able to pass >=,=<,like operators dynamically in procedure. please suggest me design.
UPDATE
THis is what I am looking for
SELECT e.ename,e.empno,e.job,e.sal,d.deptno
FROM   DEPT D,emp  e
WHERE  d.deptno = e.deptno
AND CASE
WHEN e.deptno = 10
AND  e.sal >= 1000 and e.name like('%j')
-- THEN e.name like('%j')
THEN 1
ELSE 0
END = 1;

I miss understood the THEN. we can have only expression as part of it.
thank you every one.

A: Don't discount the simple approach:
CASE in_comparison_operator
WHEN '>=' THEN
  SELECT * INTO ... FROM EMP E WHERE E.SAL >= 30000;
WHEN '<=' THEN
  SELECT * INTO ... FROM EMP E WHERE E.SAL <= 30000;
WHEN 'LIKE' THEN
  SELECT * INTO ... FROM EMP E WHERE E.ENAME like ('J%');
END;

A: you have to write some dynamic stored procedure, based of if else condition.
Below is an idea, rest you can implement your login here
create procedure DynamicQuery
@ColumnName varchar(20),
@Operator varchar(10),
@Value varchar(10)
as

declare @qry nvarchar(max)
set @qry = 'select * from Emp e where ' + @ColumnName + ' '
if(@Operator = 'like')
begin
set @qry = @qry + ' like (''' + @Value + ''')'
end

else
begin
set @qry = @qry + ' ' + @Operator + ' '  + @Value
end
print @qry

exec sp_executesql @qry


text:
Q: LINQ query is too slow, Equivalent SQL is fine I am trying to query for daily active users in a database using C# and LINQ. I have a SQL query that works fine. It finishes running in < 4 seconds.
My table is called Logins, with properties: (DATETIME)Date, (GUID)UserId, etc
SELECT CAST([DATE] AS DATE) Date , COUNT (DISTINCT USERID) DailyActives
  FROM  Logins
  GROUP BY CAST([DATE] AS DATE)
  ORDER BY CAST([DATE] AS DATE)

Which counts the distinct users that logged in on that day. My LINQ query that gives the correct answer, but very slowly (Many minutes). Here I am selecting from a specific month
from rows in Logins
where rows.Date.Month == 04 && rows.Date.Year == 2013
group rows by rows.Date.Day into MyGroup
orderby MyGroup.Key
select new
    {
      LoginDate = MyGroup.Key,
      Count = MyGroup.Select(u => u.UserId).Distinct().Count()

    }

After testing, it seems like the Count statement takes forever when I have to Select(u=>u.UserId) because I think it has to map back to the list of UserId's. How can i write the query more efficiently?
Any help is appreciated. Thanks!

A: I would do as follows...
var UserCount = Logins.Where(x => x.Date = DateTime.Today)
                    .Select(x => x.UserId).Distinct().Count();

You can of course substitute the day with whichever day you would like to get the count for.


text:
Q: Line Profile Diagonal When you make a line profile of all x-values or all y-values the extraction from each pixel is clear. But when you take a line profile along a diagonal, how does DM choose which pixels to use in the one dimensional readout?

A: Not really a scripting question, but I'm rather certain that it uses bi-linear interpolation between the grid-points along the drawn line. (And if perpendicular integration is enabled, it does so in an integral.)  It's the same interpolation you would get for a "rotate" image.
In fact, you can think of it as a rotate-image (bi-linearly interpolated) with a 'cut-out' afterwards, potentially summed/projected onto the new X-axis.
Here is an example
Assume we have a 5 x 4 image, which gives the grid as shown below.
I'm drawing top-left corners to indicate the coordinates system pixel convention used in DigitalMicrgraph, where
(x/y)=(0/0) is the top-left corner of the image

Now extract a LineProfile from (1/1) to (4/3). I have highlighted the pixels for those coordinates.
Note, that a Line drawn from the corners seems to be shifted by half-a-pixel from what feels 'natural', but that is the consequence of the top-left-corner convention. I think, this is why a LineProfile-Marker is shown shifted compared to f.e. LineAnnotations.
In general, this top-left corner convention makes schematics with 'pixels' seem counter-intuitive. It is easier to think of the image simply as grid with values in points at the given coordinates than as square pixels.

Now the maths.
The exact profile has a length of:

As we can only have profiles with integer channels, we actually extract a LineProfile of length = 4, i.e we round up.
The angle of the profile is given by the arc-tangent of dX and dY.
So to extract the profile, we 'rotate' the grid by that angle - done by bilinear interpolation - and then extract the profile as grid of size 4 x 1:

This means the 'values' in the profile are from the four points:

Which are each bi-linearly interpolated values from four closest points of the original image:

In case the LineProfile is averaged over a certain width W, you do the same thing but:

*

*extract a 2D grid of size L x W centered symmetrically over the line.i.e. the grid is shifted by (W-1)/2 perpendicular to the profile direction.

*sum the values along W


text:
Q: prevent duplicate result when using self-join in mysql I have some hotel with different hotel view for each room , and my end user when want 3 rooms for example each the room is 2 bed I have to combination the record for that , some times some fields may be duplicated and It's not important , and the user may have different room type in this situation I make example to each room have 2 bed number :
I have problem when get result :
I use self-join in "mysql" and all thing are true but some problem is have same row in this situation this is my code:
    SELECT
   table1.id,
   table2.id,
   table3.id,
   table1.num_bed,
   table2.num_bed,
   table3.num_bed
   LEFT JOIN
      tour_package table2
      ON table1.tour_id = table2.tour_id
      AND table1.hotel_id = table2.hotel_id
      AND table1.start_date = table2.start_date
   LEFT JOIN
      tour_package table3
      ON table2.tour_id = table3.tour_id
      AND table2.hotel_id = table3.hotel_id
      AND table2.start_date = table3.start_date
WHERE
   table1.num_bed = 2
   AND table2.num_bed = 2
   AND table3.num_bed = 2

the result is :

Please attention to id , the one is table1.id, two is table2.id and three is table3.id
In the result we have some result like :
1-2-1
1-1-2
and etc
I want to prevent this and have one of them , please help me

A: I assume the goal of the query is to list up to 3 rooms per record in the same hotel, for the same tour and dates that have 2 bed.
(I honestly do not get the point of the query because it will list all 2-bed rooms in the tour_package table.)
This means that not only 1-1-2 and 1-2-1 are duplicates, but also the 2nd 1 is a redundant information. In hotel no. 7 there are only 2 rooms that satisfy this criteria: 1 and 2.
In the join criteria I would require that a record with different id should be returned from each of the tables. This would force the query to return list of unique ids in a record.
SELECT
   table1.id,
   table2.id,
   table3.id,
   table1.num_bed,
   table2.num_bed,
   table3.num_bed
FROM tour_package table1
LEFT JOIN
      tour_package table2
      ON table1.tour_id = table2.tour_id
      AND table1.hotel_id = table2.hotel_id
      AND table1.start_date = table2.start_date
      AND table1.id<table2.id
LEFT JOIN
      tour_package table3
      ON table2.tour_id = table3.tour_id
      AND table2.hotel_id = table3.hotel_id
      AND table2.start_date = table3.start_date
      AND table2.id<table3.id
WHERE
   table1.num_bed = 2
   AND table2.num_bed = 2
   AND table3.num_bed = 2

However, the above query can potentially still return redundant data if there are at least 2 rooms with the above criteria in a hotel. Assuming the 2 rooms have the ids 1 and 2, the query would return 1, 2, null and 2, null, null. To overcome this issue, I would just simply write:
select id, hotel_id from tour_package
where tour_package.num_bed=2
order by tour_id, hotel_id, start_date

The reason: even your on query will show all 2-bed rooms in your tour_package table.


text:
Q: SQL Server hierarchical query I have a table of users setup like this in SQL Server database
UserID  ReportsToUserID
1        NULL
2        NULL
3        1
4        2
5        2
6        3
7        5
...

Is there a way in SQL where I can get all the employees on the reporting chain. For example when I supply 1, I am expecting to get employeesID 3,6
When I supply 2 I am expecting 4,5,7
I do not know max number of chain it can go under

A: Here is a recursive CTE where you can set the @Top with either NULL for the entire hierarchy or with a specific UserID
Declare @YourTable Table ([UserID] int,[ReportsToUserID] int)
Insert Into @YourTable Values
 (1,NULL)
,(2,NULL)
,(3,1)
,(4,2)
,(5,2)
,(6,3)
,(7,5)

Declare @Top int = null --<<  Sets top of Hier Try 1 or 2

;with cteP as (
      Select UserID
            ,ReportsToUserID
            ,HierID = convert(hierarchyid,concat('/',UserID,'/'))
      From   @YourTable
      Where  IsNull(@Top,-1) = case when @Top is null then isnull(ReportsToUserID ,-1) else UserID end
      Union  All
      Select UserID  = r.UserID
            ,ReportsToUserID  = r.ReportsToUserID
            ,HierID = convert(hierarchyid,concat(p.HierID.ToString(),r.UserID,'/'))
      From   @YourTable r
      Join   cteP p on r.ReportsToUserID  = p.UserID)
Select Lvl   = HierID.GetLevel()
      ,UserID
      ,ReportsToUserID
      ,HierID_String = HierID.ToString()
 From cteP A
 Order By HierID

Returns

Now if @Top was set to 1


text:
Q: Break Error in C So I'm trying to remove a 2000hz sine wave from an audio file in C and this is my program:
#include <stdio.h>
#include <math.h>
#define PI (4*atan(1))

int main( void)
{
   int s;
   double d1, newsound, t, i;
   for ( i=0; i>=0; ++i);
      {
         s=scanf( "%lf", &d1);
         if (s != 1) break;
         t=i/8000;
         newsound = d1-sin(2*PI*2000*t);
         printf( "%g\n", newsound);
      }
return 0;
}

i keep getting an error that says:
error: break statement not within loop or switch

A: This loop has an empty body
  for ( i=0; i>=0; ++i); // mind the semicolon

the following braces start a "floating" block
{ /* floating block */ }


text:
Q: Armadillo -> Sparse matrix with repeated (translated) rows Is there an optimal way of using such a construct? Let M be a matrix
xx0000...

00xx00...

0000xx...

Forgive the ASCII description of the matrix, I could not get latex to work.
I am dealing with huge matrices, so an optimization is needed. I thank you in advance.

A: Such a matrix is called a band(ed) matrix (Yours is upper triangular as well). Armadillo doesn't have built-in support for them, but you could store it as a sparse matrix or as a 2 by n dense matrix (and roll your own operations).
You could try using another library, I've used band matrices in FLENS. See here for an example.


text:
Q: Creating a GLUT popup menu in Python-OpenGL I'm trying to create a right-click-popup-menu in a Python(v2.7) program using GLUT. I haven't found Python-specific documentation for doing this, so I used C++ documentation, which is usually almost similar.
Here's what I have:
if __name__=="__main__":
    glutInit(sys.argv)
    #...more initialization code...
    createMenu()
    init()
    glutMainLoop()

And here are the functions that create the menu:
def createMenu():
    menu = glutCreateMenu(processMenuEvents)
    glutAddMenuEntry("One", 1)
    glutAddMenuEntry("Two", 2)
    glutAttachMenu(GLUT_RIGHT_BUTTON)

def processMenuEvents(option):
    logging.debug("Menu pressed")
    # not using 'option' right now

The menu gets displayed correctly, but when I click on an item, I get this error:
DEBUG:root:Menu pressed:
Traceback (most recent call last):
  File "_ctypes/callbacks.c", line 338, in 'converting callback result'
TypeError: an integer is required
Exception  in <function processMenuEvents at 0x1760b90> ignored

Does python-opengl have a different way of doing this? What am I doing wrong here?
Thanks.

A: Unfortunately, the way that PyOpenGL has defined the callback function, it expects an int as the return type, not void.  Below is an updated version of your CreateMenu callback function that should work.
def CreateMenu():
    menu = glutCreateMenu(processMenuEvents)
    glutAddMenuEntry("One", 1)
    glutAddMenuEntry("Two", 2)
    glutAttachMenu(GLUT_RIGHT_BUTTON)
    # Add the following line to fix your code
    return 0

A: Specifying callback functions via ctypes in Python doesn't quite work like you are expecting. You should use CFUNCTYPE to create the callback function and use the resulting variable as the parameter to glutCreateMenu.
You will find more details on ctypes and callback functions here: http://docs.python.org/release/2.5.2/lib/ctypes-callback-functions.html

A: This example helped me identify the requirement for specifying function parameter ctypes to solve the same problem. Found following the pyopengl glut docs on glutAddMenuEntry(). Ctype data types for your function args are specified here.
This snippet shows an example of an f(int)->int function, referenced via an object instance:
class Menu:
 def select_menu(self, choice):
    def _exit():
        import sys
        sys.exit(0)
    {
        1: _exit
    }[choice]()
    glutPostRedisplay()
    return 0

 def create_menu(self):
    # --- Right-click Menu --------
    from ctypes import c_int
    import platform
    #platform specific imports:
    if (platform.system() == 'Windows'):
        #Windows
        from ctypes import WINFUNCTYPE
        CMPFUNCRAW = WINFUNCTYPE(c_int, c_int)
        # first is return type, then arg types.
    else:
        #Linux
        from ctypes import CFUNCTYPE
        CMPFUNCRAW = CFUNCTYPE(c_int, c_int)
        # first is return type, then arg types.

    myfunc = CMPFUNCRAW(self.select_menu)

    selection_menu = glutCreateMenu( myfunc )
    glutAddMenuEntry("Quit", 1);
    glutAttachMenu(GLUT_RIGHT_BUTTON);
    # ---------------------------------


text:
Q: Can I create a file without metadata? As a follow up of my related question, is it possible to create a file without metadata? Or alternatively, can I remove all metadata of a given file?
This is quite a "philosophical issue". If this were possible, then, given my previous question, it would be possible to create an "infinite" number of files within a finite space disk. This is surely an experiment worth trying.
For example, creating 100 empty files in my 3 year old system:
lucho@lucho-HP:~test/$ time seq -f "%04.0f" 100 | xargs -I "{}" touch test"{}".txt
real    0m0.231s
user    0m0.000s
sys 0m0.032s

Thus, in one second, I can create roughly 400 files. So, in 8 hours (say, whilst sleeping), I can create 11 million files. Not much but you get the idea.

A: The information-theoretical answer to your previous question answers this too: if you're creating files, even reduced to their minimum representation, and you want to be able to retrieve something about them, then the creation consumes some disk space, so you'll eventually run out (however the allocation works). Thus you can't create an infinite number of files within a finite amount of disk space.
To answer your stated question, file systems I know don't allow you to remove file metadata, but there's nothing preventing you from writing your own file system that ignores whatever metadata you want — I guess the minimum you need is a file name and some way of tracking the file's contents on disk (and perhaps not even the latter, if your file system can only store empty files).

A: A file must have, at the very least a location for the first block on disk that it consumes.  This limits, based on the filesystem in question, how many files can be created regardless of how much space on disk they consume.  Most filesystems have limits for the number of files that can be contained (i. e. the number of entries in the "table of contents", so to speak, is capped).
The POSIX specification mandates a filesystem in which each file must have an inode on the filesystem describing it, which must have:

*

*The size of the file

*An identifier for the device containing the file

*The UID of the file owner

*The GID of the file

*The file's permission set

*Additional system and user flags (e. g. ACLs)

*Timestamps (e. g. ctime, mtime, atime)

*A count of the number of hard links to the inode

*Pointers to the disk blocks that store the file's contents

These data consume space, which limits the number of files that can be stored no matter how small the actual files are.


text:
Q: If $A$ is diagonalizable, find $\alpha$ and $\beta$
Let $A$ be a $5 \times 5$ matrix whose characteristic polynomial is given by
  $$p_A(\lambda)=(λ + 2)^2 (λ − 2)^3$$
      If $A$ is diagonalizable, find $\alpha$ and $\beta$ such that
  $$A^{-1} = \alpha A + \beta I$$

I am unable to find the inverse of $5\times 5$ matrix, I only know how to invert $3\times 3$ matrices. I don't know how to find the values of $α$ and $β$.
If anybody can help me I would be very thankful to them.

A: Since $A$ is diagonalizable and $p_A(\lambda)=(\lambda + 2)^2 (\lambda − 2)^3$,
we have that there exists an invertible matrix $M$ such that
$$A=M\mbox{diag}(-2,-2,2,2,2)M^{-1}.$$
Hence
\begin{align*}A^{-1}&=(M\mbox{diag}(-2,-2,2,2,2)M^{-1})^{-1}=
M\mbox{diag}\left(-\frac{1}{2},-\frac{1}{2},\frac{1}{2},\frac{1}{2},\frac{1}{2}\right)M^{-1}\\&=\frac{1}{4}M\mbox{diag}(-2,-2,2,2,2)M^{-1}=\frac{1}{4}A.
\end{align*}

A: The fact that A is diagonalizable means that there exist an invertible matrix, P, such that $PAP^{1}= \begin{bmatrix}2 & 0 & 0 & 0 & 0 \\ 0 & 2 & 0 & 0 & 0 \\ 0 & 0 & -2 & 0 & 0 \\ 0 & 0 & 0 & -2 & 0 \\ 0 & 0 & 0 & 0 & -2 \end{bmatrix}$.  So $(PAP^{1})^{-1}= PA^{-1}P^{-1}= \begin{bmatrix}\frac{1}{2} & 0 & 0 & 0 & 0 \\ 0 & \frac{1}{2} & 0 & 0 & 0 \\ 0 & 0 & -\frac{1}{2} & 0 & 0 \\ 0 & 0 & 0 & -\frac{1}{2} & 0 \\ 0 & 0 & 0 & 0 & -\frac{1}{2} \end{bmatrix}$.
So $A^{-1}= P^{-1}\begin{bmatrix}\frac{1}{2} & 0 & 0 & 0 & 0 \\ 0 & \frac{1}{2} & 0 & 0 & 0 \\ 0 & 0 & -\frac{1}{2} & 0 & 0 \\ 0 & 0 & 0 & -\frac{1}{2} & 0 \\ 0 & 0 & 0 & 0 & -\frac{1}{2} \end{bmatrix}P$.


text:
Q: Set height and width to fraction of parents height/width? I'm new to LESS.  Is there a way to get the parent height and width?  I'm trying to set something to be a percentage of the parent.  For instance:
fictitious pseudo code because I have no idea what I'm doing
@myheight: parent.height / 4;
@mywidth: parent.width / 4;

.myRelObject {
    height: @myheight
    width: @mywidth
}

The closest I found was this SO question, so if someone can just tell me if/how to get parent height/width I can probably get it from there.

A: You don't need LESS for this
.myRelObject {
    height: 25%;
    width: 25%;
}

edit: I should be more specific, unless the parents have a set height and width you can't get that value until it is rendered in the DOM, so it is better to use vanilla CSS like above.


text:
Q: Bash script to read file line by line with some words quoted and containing spaces I am trying to create a shell script that reads a file with parameters for a python script the shell script is supposed to execute in a loop:
#!/bin/bash
while read -r i ; do python catfisher.py $i ; done < fishes

where 'fishes' might contain:
vesper "purplish green" fender
vespa "dimmer grey" "stradivarius veil"

The problem is that the python script's argparser interprets the parameters like so:
python purplish green fender
even when echoing $1 in the bash script outputs:
vesper "purplish green" fender
The python script is fine if run manually:
python catfisher.py "purplish green" fender
so I'm assuming it's my lacking bash script skills that are the culprit, rather than my lacking argparser skills but pray advice if I'm mistaken.

A: Well, the problem is that to do this 100% correctly, you'd have to define a data format for your fishes file and create a parser for it.
You could approximate your desired results by saying "ok, I'd like anything in fishes to be interpreted like a shell would interpret commands to an argument", but that also entails other metacharacters than spaces and quotes which you already have, such as dollar signs, braces, tildes, parentheses, etc.
Since you are using variable expansion to feed your line to Python, your shell is already past the quoting phase, thus not interpreting quotes contained in the variable.
Unfortunately, there are no mechanisms to selectively carry out shell parsing phases, like you want to do, ignoring dangerous parts.
You can pass the text to a new shell, but that allows your data to contain commands, making your software vulnerable to code injection:
while read -r i ; do bash -c "python catfisher.py $i" ; done < fishes
The best solution would probably be close to the first suggestion, except rather than defining your own data format, you could use an existing one, such as CSV, some dialects of which already allow for quoting, and are widely supported by libraries, like the csv module, built into Python's standard library.


text:
Q: WCF service to return JSON-formatted faults Is it possible to get a WCF service to return a 'fault' to the client? I'm led to believe this is possible when using SOAP, but I'd like to be returning JSON.
Ideally, the HTTP response code would be set to something to indicate that an error occured, and then details of the problem would be available in the JSON response.
Currently, I'm doing something like this:
[ServiceContract]
public class MyService
{
    [OperationContract]
    [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    [FaultContract(typeof(TestFault))]
    public MyResult MyMethod()
    {
        throw new FaultException<TestFault>(new TestFault("Message..."), "Reason...");
    }
}

Where TestFault looks like this:
[DataContract]
public class TestFault
{
    public TestFault(string message)
    {
        this.Message = message;
    }

    [DataMember]
    public string Message { get; set; }
}

There's nothing particularly special in the service configuration at the moment.
This results in a '400 Bad Request' response, with an HTML-formatted error. (When I includeExceptionDetailInFaults, I can see the 'Reason...' and details of the FaultException, but no details on the TestFault.)
The web service returns JSON ok when an Exception (or FaultException) isn't being thrown.
Any suggestions..?

A: Edit: fixed link + added summary.
You can find an explanation and a solution here
To summarize the solution from the link, extend WebHttpBehavior and override AddServerErrorHandlers in order to add your own implementation of IErrorHandler. This implementation will extract the error from the service call and generate fault information.
The linked article also shows how to write your own Service Host Factory that sets up this behavior.

A: All what you need is possible starting with .NET 4. see here for details. For example:
throw new WebFaultException<string>(
    "My error description.", HttpStatusCode.BadRequest);

A: The error callback of your jQuery.ajax() call should look like this:
error: function (xhr, status, error) {
  var responseObj = JSON.parse(xhr.responseText);
  alert('Request failed with error: "' + responseObj.Message);
}

In your WCF Service, pass an exception to the WebFaultException constructor.  Your custom message will be accessible via responseObj.Message in the above javascript:
public class AJAXService : IAJAXService
{
  public void SomeMethod()
  {
    throw new WebFaultException<Exception>(new Exception("some custom error message!"), HttpStatusCode.InternalServerError);
  }
}


text:
Q: How to sort tableview cells in this use case What is the best practice of sorting this table in Swift 4?
A-Z
    override func viewDidLoad() {

        super.viewDidLoad()

        list = [ ghost(name:"alphabet".localized, id:"1"),
             ghost(name:"élephant".localized, id:"2"),
             ghost(name:"delegate".localized, id:"3")]
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if filtering() {
            return filter.count
        }
        return list.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "library", for: indexPath)
        var data: ghost

        if filtering() {
            data = filter[indexPath.row]
        }
        else {
            data = list[indexPath.row]
        }

        cell.textLabel!.text = data.name
        return cell
    }

I am using translated strings a lot. So it would be nice, if the table can be loaded alphabetically in different language. Can someone help me with that? I searched the whole internet and just got too exhausted of this... Thanks a lot!

A: You can use it as follows:
func sortAlpha() {

    if filtering() {
        filter.sort { (item1, item2) -> Bool in
            return item1.name > item2.name
        }
    }
    else {
        list.sort { (item1, item2) -> Bool in
            return item1.name > item2.name
        }
    }
    self.tableView.reloadData()
}

then just call sortAlpha()


text:
Q: Retrieving image stored in long datatype I have one web application, having one table in oracle10g having following structure:
Column Name       DataType
UserImage         long

My problem is that how should I display the IMAGE on my aspx page which is stored in long format?
If data type is BLOB or CLOB then it could be easier one, but it's stored in long.
I could not change the datatype since this is third party DB.
Please suggest me how could I achieve this. The solution could be either using Oracle or C#, I'm fine with both.
Thanks in advance.

A: You can't store an image in a 'long' datatype.
Instead - hold a static list of key-value pairs, each pair defines an index (say, from 1 to n) of an image
and the value holds the Image's file name.
For instance, the following pseudo code demonstrates a similar approach (should be implemented on the client/server side of your application, not in the DB
SWITCH (USERIMAGE)
    CASE 1:
         SETIMAGE("IMAGES/IMAGE_NUMBER_ONE.JPG");
         BREAK:
    CASE 2:
         SETIMAGE("IMAGES/IMAGE_NUMBER_TWO.JPG");
         BREAK:

and so on.
Another solution:
Assume your 1st table is called "Table1". create a new table in your database called my_images
Column name     Column type       Comments
UserImage       LONG              Foreign key to Table1.UserImage
ImageData       BLOB

And,
SELECT t1.ImageData FROM Table1 t1, my_images mi
WHERE t1.UserImage == mi.UserImage;

A: The "chunk" characters you have posted seem to be a TIFF image. That gives an idea how the images are stored. In fact, the binary image data seems to be stored as character data. That's certainly completely unsupported and very fragile. I'd recommend converting it as soon as possible.
In the mean time, I can propose two ways of retrieving the data so I cannot guarantee that either one works.
But approaches are susceptible to characters sets: If two or more character sets are involved, your data will be converted and thereby destroyed. And both are susceptible to the maximum length of certain data types.
Approach 1:
Try to go via the RAW data type and retrieve it as a byte array. It's certainly limited to 32'000 characters, maybe even less.
SELECT UTL_RAW.CAST_TO_RAW(UserImage) FROM UNNAMED_TABLE WHERE ...

On the C# side, you should get an OracleBinary or byte[] instance.
Approach 2:
Try to retrieve it as a string. Then convert the string into a byte array using the original encoding (Encoding.GetBytes. With enough luck, the original data can be restored.