text:
Q: Error in checkboxall in pageblocktable Iam trying to get checkbox all functionality in pageblocktable.
But Iam getting an error

Invalid field selected for SObject ZIP__c

List<zipwrapper> zipList = new List<zipwrapper>();
    List<Zip__c> selectedZips = new List<Zip__C>();
public List<zipwrapper> getZips()
    {
        for(Zip__c z : [select Id, Name from Zip__c ])
        zipList.add(new zipwrapper(z));
        return zipList;
    }

public PageReference getSelected()
    {
        selectedZips.clear();
        for(zipwrapper zipwrapper : zipList)
        if(zipwrapper.selected == true)
        selectedZips.add(zipwrapper.zip);
        return null;
    }
     public List<ZIp__c> GetSelectedZips()
    {
        if(selectedZips.size()>0)
        return selectedZips;
        else
        return null;
    }
    public class zipwrapper
    {
        public zip__c zip{get; set;}
        public Boolean selected {get; set;}
        public zipwrapper(Zip__c z)
        {
            zip = z;
            selected = false;
        }
    }

What I am missing?
<apex:pageblockTable value="{!zipinfo}" var="zip" style="width:100%" id="ziptable">
                                       <apex:column >

                                           <!-- <apex:facet name="header">
                                                <apex:inputCheckbox value="{!allChecked}">
                                                    <apex:actionSupport event="onclick" action="{!CheckAll}" rerender="ziptable"/>
                                                </apex:inputCheckbox>
                                            </apex:facet>-->
                                            <apex:facet name="header"> <apex:inputCheckbox >
                                            <apex:actionSupport event="onclick" action="{!GetSelected}" onsubmit="checkAll(this)" rerender="ziptable"/>
                                            </apex:inputCheckbox></apex:facet>

                                           <apex:inputCheckbox value="{!zip.selected}" id="checkedone" />
                                       </apex:column>
                                       <apex:column value="{!zip.name}" headerValue="Zip" />
                                       <apex:column value="{!zip.City__c}" headerValue="City" />
                                       <apex:column value="{!zip.State__c}" headerValue="State" />

                                   </apex:pageblockTable>
                                   </apex:outputPanel>
                                </apex:pageblock>

A: Based on your VF code, you are obviously using Zip__c as an item in the table. If you take a look at last three columns of your simplified snippet:
<apex:pageblockTable value="{!zipinfo}" var="zip" style="width:100%" id="ziptable">
   <apex:column >
       <apex:inputCheckbox value="{!zip.selected}" id="checkedone" />
   </apex:column>
   <apex:column value="{!zip.name}" headerValue="Zip" />
   <apex:column value="{!zip.City__c}" headerValue="City" />
   <apex:column value="{!zip.State__c}" headerValue="State" />
</apex:pageblockTable>

..you will notice that you are accessing fields name, City_c and State_c, which are obviously fields of the Zip__c object, rather than of the zipwrapper object.
In your controller, zipinfo is most probably List of Zip__c and not List of zipwrapper.
Update your VF page so that pageBlockTable uses List of zipwrapper and extend zipwrapper class to contain name/city/state fields.


text:
Q: Accessing separate files from separate threads, is this efficient? I have an application that loads files and processes data. Let's assume I have like 10...20 files to process.
some requirements, to make the question clearer:

*

*files are small, maybe a few MB max

*there might be a dozen files, maybe a hundred

*one example might be parsing CSV data, or JSON, loading game 3d models

One idea is to use some thread pool and process files in parallel. Is this efficient? Can my operating system handle file access from multiple threads?
I found this question:
Accessing a single file with multiple threads
But in my application one thread would access its "own" file, so there wouldn't be any collisions.
In my application, I'm using C++/STL, but I'd like to know the general opinion about filesystems on Linux and Windows.

A: You need to benchmark. (probably in your case it could be worth to use several threads; however in your case, the loading should be so quick, even done sequentially, that your average user won't notice)
In many cases, when you deal with medium sized files (e.g. less than a dozen of megabytes each, or perhaps even half a gigabyte each) which have been accessed recently, these files practically sit in the page cache. So you won't access the disk itself, and your program practically works in RAM (and then multithreading should be effective).
BTW, Linux has readahead(2), posix_fadvise(2), madvise(2) to hint the kernel virtual memory subsystem (that is, to give hints to the page cache).
If your common use case is accessing the disk itself (e.g. because the files are quite big, or because you have not accessed them recently before, so they are not in the page cache), then multi-threading won't help, because the bottleneck becomes the hardware disk.
Remember that a disk (even an SSD one) is many thousands times slower than RAM and it does IO operations sequentially.
Also, you may spend some amount of CPU time in parsing the files. If that takes a significant amount of CPU, it is worth to be run in several independent threads.

A: In my experience you get more performance if the processing of the data is heavy. In this case you really make parallel the execution of your program. You also need to know how many core your cpu have. It is not worth have more threads than cpu cores.
If your processing is "light", probably your threads are always waiting of disk to  complete reading, with little, if ever, gain in performance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flipping a view only works when hiding, but not when showing I'm using the iCarousel library to show a coverflow-like UI. Animating the iCarousel subviews directly tends to blow up, so I create a wrapper for my animation and stick a subview inside of it which looks like the tapped cover. Then I hide the actual iCarousel view, and animate the fake cover on top of it.
I'm using UIView's transitionWithView:duration:options:animations:completion: method, but I'm running into some trouble. When animating another view onscreen for the first time, the view appears without any animation. When animating out, the view correctly flips and hides.
My view hierarchy is as follows:

*

*main view, loaded from a nib

*wrapper view

*

*view to transition from

*view to transition to

The view I'm transitioning to is a UINavigationController's view which contains a UITableViewController subclass. Instead of the initial animation, the UINavigationController appears and then the view grows upward a little, as if it's taking over the space otherwise occupied by a status bar.
Any idea why the table view might be animating like this? (I suspect containment APIs and/or wantsFullscreen, although I'm not explicitly using them. I simply install the views into the wrapper via addSubview:.)
Here's my "flip in" code, that animates every time but the first:
- (void) flipInWithCompletion:(MBTransitionCompletion)completion {
BOOL displayingPrimary = [self isDisplayingPrimaryView];

UIView *frontView = [self frontView];
UIView *backView = [self backView];
UIView *wrapperView = [self wrapperView];

[wrapperView addSubview:frontView];

[UIView transitionWithView:wrapperView
                  duration:0.8
                   options:UIViewAnimationOptionTransitionFlipFromRight
                animations:^{
                    [wrapperView addSubview:backView];
                    [frontView removeFromSuperview];
                }
                completion:^(BOOL finished) {
                    [self setIsDisplayingPrimaryView:!displayingPrimary];
                    if (completion) {
                        completion();
                    }
                }
 ];

}
What might cause the table view to grow instead of allowing the wrapper to flip?
Edit:
I've made a video demoing the exact problem.

A: Sounds like the view isn't properly loaded before it starts to animate in. I think I remember having a similar problem before. Try adding it to your view first, then remove it, and try to animate it into place to see if that fixes it.
That's not really a solution though, but it should give you a clue as to what might be wrong.


text:
Q: Camel iMap - ignore SSL certificat i'm using imap endpoint and i try to ignore SSL certificat by using:
the First class DummySSLSocketFactory :
    public class DummySSLSocketFactory extends SSLSocketFactory {
        private SSLSocketFactory factory;
        public DummySSLSocketFactory() {
            try {
                SSLContext sslcontext = SSLContext.getInstance("TLS");
                sslcontext.init(null,
                                     new TrustManager[] { new

DummyTrustManager()},
                                 null);
            factory = (SSLSocketFactory)sslcontext.getSocketFactory();
        } catch(Exception ex) {
            // ignore
        }
    }

    public static SocketFactory getDefault() {
        return new DummySSLSocketFactory();
    }

    public Socket createSocket() throws IOException {
        return factory.createSocket();
    }

    public Socket createSocket(Socket socket, String s, int i, boolean flag)
                                throws IOException {
        return factory.createSocket(socket, s, i, flag);
    }

    public Socket createSocket(InetAddress inaddr, int i,
                                InetAddress inaddr1, int j) throws IOException {
        return factory.createSocket(inaddr, i, inaddr1, j);
    }

    public Socket createSocket(InetAddress inaddr, int i)
                                throws IOException {
        return factory.createSocket(inaddr, i);
    }

    public Socket createSocket(String s, int i, InetAddress inaddr, int j)
                                throws IOException {
        return factory.createSocket(s, i, inaddr, j);
    }

    public Socket createSocket(String s, int i) throws IOException {
        return factory.createSocket(s, i);
    }

    public String[] getDefaultCipherSuites() {
        return factory.getDefaultCipherSuites();
    }

    public String[] getSupportedCipherSuites() {
        return factory.getSupportedCipherSuites();
    }
}

the second class DummyTrustManager :
public class DummyTrustManager implements X509TrustManager {

    public void checkClientTrusted(X509Certificate[] cert, String authType) {
        // everything is trusted
    }

    public void checkServerTrusted(X509Certificate[] cert, String authType) {
        // everything is trusted
    }

    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}

the third class AllowAll to set java mail propeties:

public class AllowAll {
         public void setsslproperties()  {

                 //DummySSLSocketFactory easy = new EasySSLProtocolSocketFactory();
                 Properties props = System.getProperties();
                 props.setProperty("mail.imap.ssl.enable", "true");
             props.setProperty("mail.imap.ssl.socketFactory.class","com.mycompany.imapssl.DummySSLSocketFactory");
                 props.setProperty("mail.imap.ssl.socketFactory.fallback", "false");
                 props.setProperty("mail.imap.socketFactory.port", "993");
                 Session session = Session.getInstance(props, null);

        }

}

How can i associate this to the iMap EiP to ignore SSL Certificate ?
this is the route:
<route id="timerToLog">
    <from uri="imaps://server:993?username=user_name&password=pass"/>
    <log message="ok"/>

A: If you're using a recent version of JavaMail, set the mail.imap.ssl.trust property to the name of the host you want to trust.  That avoids the need to create your own socket factory.


text:
Q: Pesquisar em um campo com codificação JSON Existe um campo na tabela em que o conteúdo antes de ser gravado é codificado em JSON.
O conteúdo é gravado da seguinte forma:
[["nome_completo","Ana Concei\u00e7\u00e3o Dias"],["idade","27 anos"],["cidade","Lisboa"]]

No PhpMyAdmin, o select abaixo não retorna nenhum resultado:
SELECT *
FROM funcionarios
WHERE custom LIKE '%Ana Concei\u00e7\u00e3o Dias%'

Como fazer a consulta acima retornar o respectivo registo?

A: Meu código abaixo não é uma solução completa, copy/paste não vai funcionar. Destina-se a empurrá-lo na direção certa. Suponho que o meu código pode ter alguns erros, embora eu não estou vendo isso. Se alguém encontrar o erro, por favor, DEIXE UM COMENTÁRIO.
Primeiro queria saber porque você converteu os resultados para Json antes de salvar no banco. Você já tem uma matriz, você não precisa de uma string JSON no seu caso. Você precisa converter de volta com isso:
$yourArray = json_decode($json)

Agora você pode inserir os dados na tabela. Eu não sei como está seu insert , mas se eu olhar para o seu código, eu acho que o seu sql seria algo parecido com isto:
$sql = 'INSERT INTO tabela(id, nome_completo, idade, cidade) VALUES (:id, :nome_completo, :idade, :cidade)';

Portanto, o seu código seria algo parecido com isto:
$stmt = $db->prepare( $sql );
$sql = 'INSERT INTO tabela(id, nome_completo, idade, cidade) VALUES (:id, :nome_completo, :idade, :cidade)';
$stmt->bindParam(':id', $yourArray ['id']);
$stmt->bindParam(':nome_completo', $yourArray['nome_completo']);
...
$stmt = $dbh->prepare( $sql );
$stmt->execute();

Esta é a forma correta de armazenar seus dados "Json", assim você poderá fazer select sem problemas.

A: Encontrei a solução aqui:
http://dev.mysql.com/doc/refman/5.6/en/string-comparison-functions.html#operator_like
Como o MySQL usa sintaxe de escape do C em strings ( por exemplo, "\n" para representar uma nova linha ), é necessário dobrar qualquer "\".
Por exemplo, para procurar "\n" , é necessário especificar "\n". Para procurar "\", especifique-o como "\\" ; isso é porque as barras invertidas são eliminadas uma vez pelo analisador e novamente quando a correspondência de padrões é feita , deixando uma única barra invertida a ser procurada.
A query ficou da seguinte forma:
SELECT *
FROM funcionarios
WHERE custom LIKE '%Ana Concei\\\\u00e7\\\\u00e3o Dias%'


text:
Q: how to fetch all the songs with .mp3 format from SD card and Phone memory I have developed a music Player application in android. I have a class called song manager. Here i am fetching all the .mp3 files but the following code is not fetching all the .mp3 files from SD Card and Phone memory. Can you please help me .
Java File
public class SongsManager {
    // SDCard Path
    final String MEDIA_PATH = Environment.getExternalStorageDirectory().getPath() + "/";
    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
    private String mp3Pattern = ".mp3";

// Constructor
    public SongsManager() {

    }

    public ArrayList<HashMap<String, String>> getPlayList() {
        System.out.println(MEDIA_PATH);
        if (MEDIA_PATH != null) {
            File home = new File(MEDIA_PATH);
            File[] listFiles = home.listFiles();
            if (listFiles != null && listFiles.length > 0) {
                for (File file : listFiles) {
                    System.out.println(file.getAbsolutePath());
                    if (file.isDirectory()) {
                        scanDirectory(file);
                    } else {
                        addSongToList(file);
                    }
                }
            }
        }
        // return songs list array
        return songsList;
    }

    private void scanDirectory(File directory) {
        if (directory != null) {
            File[] listFiles = directory.listFiles();
            if (listFiles != null && listFiles.length > 0) {
                for (File file : listFiles) {
                    if (file.isDirectory()) {
                        scanDirectory(file);
                    } else {
                        addSongToList(file);
                    }

                }
            }
        }
    }

    private void addSongToList(File song) {
        if (song.getName().endsWith(mp3Pattern)) {
            HashMap<String, String> songMap = new HashMap<String, String>();
            songMap.put("songTitle",
                    song.getName().substring(0, (song.getName().length() - 4)));
            songMap.put("songPath", song.getPath());

            // Adding each song to SongList
            songsList.add(songMap);
        }
    }
}

I have also give the following in manifest file. Please see below
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission-sdk-23 android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Pleae help me out

A: This would give you list of mp3 files on SD card
 public static void findFilesRecursively(String directoryName, List<File> files, Pattern pattern) {
    File directory = new File(directoryName);

    // get all the files from a directory
    File[] fList = directory.listFiles();
    for (File file : fList) {
        if (file.isFile()) {
            if(pattern.matcher(file.getName()).find()) {
                files.add(file);
            }
        } else if (file.isDirectory()) {
            findFilesRecursively(file.getAbsolutePath(), files, pattern);
        }
    }
    File dir = Environment.getExternalStorageDirectory();
    List<File> fileResult = new ArrayList<File>();
    findFilesRecursively(dir.getAbsolutePath(), fileResult,Pattern.compile(".*\\.mp3$"));

A: This worked. Anyone can try
String media_path = Environment.getExternalStorageDirectory().getPath();
String[] splitPath= media_path .split("/");
final String MEDIA_PATH = "/" + splitPath[1] + "/";


text:
Q: extending the element to a list that was used in .pop I'm trying to create a pseudo-random sequence generator. There are a couple of constraints, the first one being that there should be 24 instances of each sequence and that there should never be a consecutive occurrence of a sequence in the result. This is my code:
import random
def rgen():
    block_list =[]
    while len(block_list) != 96:
        sequences = ['seq1','seq2','seq3','seq4']
        block_list.extend(random.sample(sequences, 4))
    for x,y in enumerate(block_list):
        count = 'repeat'
        while count == 'repeat':
            if block_list[x] == block_list[x-1]:
                block_list.pop(x)
                block_list.extend(y)
                count = 'repeat'
            else:
                count = 'no repeat'
    sequence_counts = {'seq1':0,'seq2':0,'seq3':0,'seq4':0}
    for i in block_list:
        for k,v in sequence_counts.items():
            if k == i:
                v += 1
                sequence_counts[k] = v
    print 'counts for each sequence: ', sequence_counts
    print block_list

The end result of this however, is that I end up with something like this at the end of the list:
's', 'e', 'q', '1', 's', 'e', 'q', '1', 's', 'e', 'q', '2', 's', 'e', 'q', '4'

when I really just want to extend the entire list element not it's characters individually.
so I want to extent the entire strings above which are really:
'seq1','seq1','seq2','seq4'

A: Your problem comes from using extend() instead of append(). extend() assumes you are adding a list to another list and adds each element of y to block_list. Your use of count is unnecessary since you immediately leave your while loop in the else statement so you can replace it with a break(). There is also an issue with the number of each element. The way you have it you are removing an element which changes the value at index x. To fix this, you know that the value you pop matches the value at index x so just set that to a variable and add it back to your list. You can see this happening if you print block_list[x] before and after the pop()
while 1:
    if block_list[x] == block_list[x-1]:
       y = block_list.pop(x)
       block_list.append(y)
       #Alternatively, but not recommended, is to do .extend([y])
       #That treats y as an element of a list rather than a list itself
    else:
       break

Also the way you have it now you are treating your list as circular. In the first iteration of the first for loop you are comparing index 0 and index -1.
To fix that you will need to use range() like so
for x in xrange(1,len(block_list)):
    while 1:
        if block_list[x] == block_list[x-1]:
            y = block_list.pop(x)
            block_list.append(y)
        else:
            break

['seq2', 'seq1', 'seq3', 'seq4', 'seq1', 'seq2', 'seq4', 'seq3',
 ...,
 'seq3', 'seq1', 'seq2', 'seq4', 'seq3', 'seq2', 'seq3', 'seq4']

A: After you shuffle sequences, check to see if the first seq of sequences matches the last seq of block_list.  If they match, just extend with sequences in reverse.
def rgen():
    sequences = [seq1, seq2, seq3, seq4]
    random.shuffle(sequences)

    for i in range(24):
        random.shuffle(sequences)
        if sequences[:1] != block_list[-1:]:
            block_list.extend(sequences[:])
        else:
            block_list.extend(sequences[::-1])

    return block_list

An observation: rgen() (yours or mine) can't generate all valid permutations of the sequences.  For example, it can't generate:
[seq1 seq2 seq1 .... seq4 seq3 seq4]


text:
Q: How to put single quote and double quote in post filename Is it possible to use special characters like single and double quote in yml front matter

A: Post file name are used to represent the link to the post, so having a file my-post.md will result in /my-post link. Putting quotes there is a bad idea - quotes in the link will be html encoded - so link won't look nice, and it will make your life harder dealing with files with quotes.
I assume you're missing the yml front matter feature - you can name your file with a simple name, but have a title in your post with any character you want:
---
title: W'ha"t e!veR T?<tle@# y04 w4nt
---

A: If I use double quote I need to use > in title like
title: >
    A winter's "day"


text:
Q: How many different unit types can you use for setMargins() We know that to set margins this is one way of doing it
I discovered this example from this answer. it sets margins in the dp unit type.
val param = xml.layoutParams as ViewGroup.MarginLayoutParams

param.setMargins(left, top, right, bottom)

xml.layoutParams = param

This variable i discovered from this answer. It translates pixels to dp allowing you to then use it for one of the parameters shown in my previous example.
val pxToDP = if ( direction == "left" || direction == "right" ) {
                px / ( xml.context.resources.displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT)
            } else if ( direction == "top" || direction == "bottom" ) {
                px / ( xml.context.resources.displayMetrics.ydpi / DisplayMetrics.DENSITY_DEFAULT)
            }

But what if i want to set margin using a variable that represent inches? How would i do that?
And are there any other methods i can use to set margin in Kotlin where the variable represents a different unit type? If so, what are the methods?

A: most often case in Android when setting any dimensions: pixels are used. also setMargins get px values, not dps or any other (according to doc). so if you have some number in different unit then you need to convert it to pixels
for re-calculating some value in given unit use TypedValue class, e.g. like below:
int _10dpInPixelUnit = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10,
            getResources().getDisplayMetrics());

if you want to use inches just use TypedValue.COMPLEX_UNIT_IN (some doc and other units HERE)


text:
Q: Direcciones de memoria distintas? Estoy trabajando en windows 10 y codeblocks, y mi pregunta es porque al hacer esto tengo la posicion de memoria por ejemplo 0060FEFC

1º Codigo

#include <stdio.h>

int main(void){

   int arreglo[4];
   printf("%p\n",arreglo); //Direccion de memoria 0060FEFC
   printf("%p\n",&arreglo[1]);                  //0060FF00
   printf("%p\n",&arreglo[2]);                  //0060FF04
   printf("%p\n",&arreglo[3]);                  //0060FF08

   for(int i=0;i<4;i++){
       printf("%p arreglo[%d]\n",&arreglo[i],i); //Direccion de memoria 0060FEFC arreglo[0]
                                                                      //0060FF00 arreglo[1]
                                                                      //0060FF04 arreglo[2]
                                                                      //0060FF08 arreglo[3]

   }

   return 0;
}

Pero en cambio si solo pongo los printf se puede ver que empieza por 0060FF00

2º Codigo

#include <stdio.h>

int main(void){

    int arreglo[4];
    printf("%p\n",arreglo); //Direccion de memoria 0060FF00
    printf("%p\n",&arreglo[1]);                  //0060FF04
    printf("%p\n",&arreglo[2]);                  //0060FF08
    printf("%p\n",&arreglo[3]);                  //0060FF0C

    return 0;
}

Empieza por 0060FEFC

3º Codigo

#include <stdio.h>

int main(void){
    int arreglo[4];
    for(int i=0;i<4;i++){ ///Direccion de memoria     0060FEFC arreglo[0]
        printf("%p arreglo[%d]\n",&arreglo[i],i);   //0060FF00 arreglo[1]
                                                    //0060FF04 arreglo[2]
                                                    //0060FF08 arreglo[3]
   }

   return 0;
}

A: En general, no hay nada que garantice que en cada ejecución del programa la misma variable vaya a ocupar la misma posición de memoria. Por ejemplo, igual si añades parámetros de entrada cambia la posición de memoria. O igual no. El caso es que, aunque veas que siempre obtienes el mismo valor, no puedes confiar en que sea así.
Pero incluso asumiendo que puedes confiar en que obtienes el mismo valor, la cuestión es que los dos programas que muestras son diferentes. Y que la memoria almacena no solo los datos del programa, sino también el propio código máquina del programa. Eso sería uno de los posibles motivos para la discrepancia.

A: La explicación es que aunque para ti esos códigos sean prácticamente iguales, el binario resultante puede ser muy diferente... incluso es altamente probable que las posiciones de memoria que te da cambien en función de si compilas con o sin optimizaciones
¿Y cual es la diferencia?
En tu caso la diferencia está en la variable i. Ignoro qué compilador y opciones de compilación utilizas, como te digo el resultado es dependiente del compilador y de sus opciones... de hecho, si comparamos los códigos 2 y 3 que son los más sencillos podemos ver bastantes diferencias
Linux - Clang 6.0.0 - opciones: sin optimizaciones
Código 2
main:                                   # @main
    push    rbp
    mov     rbp, rsp
    sub     rsp, 48
    movabs  rdi, offset .L.str
    lea     rsi, [rbp - 32]
    mov     dword ptr [rbp - 4], 0
    mov     al, 0
    call    printf
    movabs  rdi, offset .L.str
    lea     rsi, [rbp - 32]
    add     rsi, 4
    mov     dword ptr [rbp - 36], eax # 4-byte Spill
    mov     al, 0
    call    printf
    movabs  rdi, offset .L.str
    lea     rsi, [rbp - 32]
    add     rsi, 8
    mov     dword ptr [rbp - 40], eax # 4-byte Spill
    mov     al, 0
    call    printf
    movabs  rdi, offset .L.str
    lea     rsi, [rbp - 32]
    add     rsi, 12
    mov     dword ptr [rbp - 44], eax # 4-byte Spill
    mov     al, 0
    call    printf
    xor     ecx, ecx
    mov     dword ptr [rbp - 48], eax # 4-byte Spill
    mov     eax, ecx
    add     rsp, 48
    pop     rbp
    ret
.L.str:
    .asciz  "%p\n"

Código 3
main:                                   # @main
    push    rbp
    mov     rbp, rsp
    sub     rsp, 48
    mov     dword ptr [rbp - 4], 0
    mov     dword ptr [rbp - 36], 0
.LBB0_1:                                # =>This Inner Loop Header: Depth=1
    cmp     dword ptr [rbp - 36], 4
    jge     .LBB0_4
    movabs  rdi, offset .L.str
    lea     rax, [rbp - 32]
    movsxd  rcx, dword ptr [rbp - 36]
    shl     rcx, 2
    add     rax, rcx
    mov     edx, dword ptr [rbp - 36]
    mov     rsi, rax
    mov     al, 0
    call    printf
    mov     dword ptr [rbp - 40], eax # 4-byte Spill
    mov     eax, dword ptr [rbp - 36]
    add     eax, 1
    mov     dword ptr [rbp - 36], eax
    jmp     .LBB0_1
.LBB0_4:
    xor     eax, eax
    add     rsp, 48
    pop     rbp
    ret
.L.str:
    .asciz  "%p arreglo[%d]\n"

Linux - Clang 6.0.0 - opciones: -O3
Código 2
main:                                   # @main
    sub     rsp, 24
    mov     rsi, rsp
    mov     edi, offset .L.str
    xor     eax, eax
    call    printf
    lea     rsi, [rsp + 4]
    mov     edi, offset .L.str
    xor     eax, eax
    call    printf
    lea     rsi, [rsp + 8]
    mov     edi, offset .L.str
    xor     eax, eax
    call    printf
    lea     rsi, [rsp + 12]
    mov     edi, offset .L.str
    xor     eax, eax
    call    printf
    xor     eax, eax
    add     rsp, 24
    ret
.L.str:
    .asciz  "%p\n"

Código 3
main:                                   # @main
    sub     rsp, 24
    mov     rsi, rsp
    mov     edi, offset .L.str
    xor     edx, edx
    xor     eax, eax
    call    printf
    lea     rsi, [rsp + 4]
    mov     edi, offset .L.str
    mov     edx, 1
    xor     eax, eax
    call    printf
    lea     rsi, [rsp + 8]
    mov     edi, offset .L.str
    mov     edx, 2
    xor     eax, eax
    call    printf
    lea     rsi, [rsp + 12]
    mov     edi, offset .L.str
    mov     edx, 3
    xor     eax, eax
    call    printf
    xor     eax, eax
    add     rsp, 24
    ret
.L.str:
    .asciz  "%p arreglo[%d]\n"

Fíjate que una vez aplicadas las optimizaciones los dos binarios son prácticamente iguales... mientras que sin optimizaciones se parecen más bien poco... y resultados diferentes obtendrás al cambiar de compilador... por ejemplo, si compilamos los dos ejemplo scon gcc 4.4.7 obtenemos:
sin optimizaciones
Código 2
.LC0:
    .string "%p\n"
main:
    push    rbp
    mov     rbp, rsp
    sub     rsp, 16
    lea     rax, [rbp-16]
    mov     rsi, rax
    mov     edi, OFFSET FLAT:.LC0
    mov     eax, 0
    call    printf
    lea     rax, [rbp-16]
    add     rax, 4
    mov     rsi, rax
    mov     edi, OFFSET FLAT:.LC0
    mov     eax, 0
    call    printf
    lea     rax, [rbp-16]
    add     rax, 8
    mov     rsi, rax
    mov     edi, OFFSET FLAT:.LC0
    mov     eax, 0
    call    printf
    lea     rax, [rbp-16]
    add     rax, 12
    mov     rsi, rax
    mov     edi, OFFSET FLAT:.LC0
    mov     eax, 0
    call    printf
    mov     eax, 0
    leave
    ret

Código 3
.LC0:
    .string "%p arreglo[%d]\n"
main:
    push    rbp
    mov     rbp, rsp
    sub     rsp, 32
    mov     DWORD PTR [rbp-4], 0
    jmp     .L2
.L3:
    mov     edx, DWORD PTR [rbp-4]
    lea     rax, [rbp-32]
    movsx   rdx, edx
    sal     rdx, 2
    lea     rcx, [rax+rdx]
    mov     eax, DWORD PTR [rbp-4]
    mov     edx, eax
    mov     rsi, rcx
    mov     edi, OFFSET FLAT:.LC0
    mov     eax, 0
    call    printf
    add     DWORD PTR [rbp-4], 1
.L2:
    cmp     DWORD PTR [rbp-4], 3
    setle   al
    test    al, al
    jne     .L3
    mov     eax, 0
    leave
    ret

con optimizaciones
Código 2
.LC0:
    .string "%p\n"
main:
    push    rbx
    mov     edi, OFFSET FLAT:.LC0
    xor     eax, eax
    sub     rsp, 16
    mov     rsi, rsp
    call    printf
    lea     rsi, [rsp+4]
    mov     edi, OFFSET FLAT:.LC0
    xor     eax, eax
    call    printf
    lea     rsi, [rsp+8]
    mov     edi, OFFSET FLAT:.LC0
    xor     eax, eax
    call    printf
    lea     rsi, [rsp+12]
    mov     edi, OFFSET FLAT:.LC0
    xor     eax, eax
    call    printf
    xor     eax, eax
    add     rsp, 16
    pop     rbx
    ret

Código 3
.LC0:
    .string "%p arreglo[%d]\n"
main:
    push    rbx
    xor     edx, edx
    mov     edi, OFFSET FLAT:.LC0
    xor     eax, eax
    sub     rsp, 16
    mov     rsi, rsp
    call    printf
    lea     rsi, [rsp+4]
    mov     edx, 1
    mov     edi, OFFSET FLAT:.LC0
    xor     eax, eax
    call    printf
    lea     rsi, [rsp+8]
    mov     edx, 2
    mov     edi, OFFSET FLAT:.LC0
    xor     eax, eax
    call    printf
    lea     rsi, [rsp+12]
    mov     edx, 3
    mov     edi, OFFSET FLAT:.LC0
    xor     eax, eax
    call    printf
    xor     eax, eax
    add     rsp, 16
    pop     rbx
    ret

Como ves, se parecen más bien poco... a grandes rasgos si tienen algunos detalles en común... pero iguales iguales no son.
No te preocupes por esos detalles ya que la posición exacta de un elemento pocas veces importa... lo realmente importante es que tus punteros apunten a donde deben... las posiciones de memoria son aleatorias y esa aleatoriedad crece conforme se incrementa la complejidad del programa.

A: Aunque las respuestas anteriores son bastante completas, creo que en este caso una respuesta sencilla puede ser la solución:
El compilador suele colocar las instrucciones del programa en una posición, y a continuación la memoria estática.
Como 2º tiene más instrucciones que traducir (1º y 3º son un bucle con 1 instrucción) su posición en memoria es ligeramente superior.


text:
Q: Android WebView always returns null for javascript getElementById on loadUrl I try to fill out a form inside a webview from the android client app. I know how it should work, but the getElementById always returns null for me. I tried it on different websites.
Here is my example for www.google.com.
MyWebView view = new MyWebView(this);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl("http://www.google.com");
view.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView v, String url) {
        v.loadUrl(url);
        return true;
    }
    @Override
    public void onPageFinished(WebView v, String url) {
        v.loadUrl("javascript:document.getElementById('mib').value = 'aaa';");
    }
});
setContentView(view);

And the MyWebView class (only for information).
class MyWebView extends WebView {
    Context context;
    public MyWebView(Context context) {
        super(context);
        this.context = context;
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // do some multi touch stuff
        return true;
    }
}

I always get the error:
09-01 04:35:26.453: I/chromium(2962): [INFO:CONSOLE(1)] "Uncaught TypeError: Cannot set property 'value' of null", source: https://www.google.de/?gws_rd=ssl (1)

But the element "mib" should be on the site. Using a desktop browser (chrome with mobile simulation) everything is working fine. I have no idea, whats going wrong here.
Thanks for hints!
Edit:
I got some progress. Regarding this site, I also need setDomStorageEnabled(true).
No I can find the DOM object and set the value, but instead of showing the modified site I get a new blank one with only the value I set. E.g. a white blank site with the text "aaa".

A: Finally I found a solution! And it is a really strange behaviour.
First of all you need to specify setDomStorageEnabled(true) on your webview. Otherwise the DOM doesn't work. I wonder why no tutorial gave a hint about. But ok.
myview.getSettings().setDomStorageEnabled(true);

After this I ended up in a white blank page with only the value I set. The strange thing is, that javascript:document.getElementById('myfield').value = 'aaa'; returns a value. Namely the one I set. So a new blank page was created that only contains the string "aaa".
I solved it by modifying the javascript to throw away the return result:
javascript:var x = document.getElementById('myfield').value = 'aaa';

And voilá. It is working.

A: I also struggled with this issue for quite some time. I had the same issue with the blank page as @Catscratch and nothing worked. Strangely enough, if you wrap the same code in a Javascript function, it all works.
Thus,
 webView.loadUrl("javascript:(function() { document.getElementById('email_field').value = '" + email + "'; })()");

works, while
webView.loadUrl("javascript:document.getElementById('email_field').value = '" + email + "';");

does not work.
And all of this without needing setDomStorageEnabled(true) and without setWebChromeClient()

A: Another work around that seems to work: make sure you javascript "returns" null, ex:
loadUrl("javascript:document.getElementById('myfield').value = 'aaa'; null");

Oddly however, if you aren't using getElementById then it's OK for loadUrl to return values, the same behavior doesn't occur.  Smells like some kind of bug...it might be this bug but possibly not fixed in some versions of android [?]


text:
Q: How to register with 10DLC if I have another platform requesting me the same as twilio
*

*Do we absolutely have to register with The Campaign Registry (TCR)?

*what happens if we don't

*Confirm that when I fill out the paperwork through Crelate (my other platform) and have to start paying $10 a month to the registry this will also meet the Twilio requirement (we shouldn't have to pay 2x's)

PLEASE YOUR ASSISTANCE WILL BE REALLY APPRECIATED.
Not applicable to this question at the moment.


text:
Q: Laravel 5.1 multiple variables in config::get Im trying to modify a file of my app in order to include also a name except from the email address that is included in the sent email, but i failed.
I can see two instances that are using config::get to parse the email.
I tried modifying them but with no luck.
Original code includes:
'from_email' => Config::get('database.email'),

and
->setFrom(Config::get('database.email'))
I did these changes and they failed. Do I have any syntax wrongs there?
'from_email' => Config::get('database.email', 'My Name'),

and
->setFrom(Config::get('database.email', 'My Name'))

A: Second parameter to Config::get() is the default value that will be returned in case given value is not set in config file. In your case calling Config::get('database.email', 'My Name') will return the value of database.email or, if database.email is not set, it will return My Name.
It is possible that you just put the parenthesis incorrectly. If you do
->setFrom(Config::get('database.email'), 'My Name')

or
->setFrom([Config::get('database.email') => 'My Name']);

then it should work as you want it to. The second form allows you to provide a list of From addresses.

A: Probably you need to set the default value to an email address.
'from_email' => Config::get('database.email', 'email@example.com'),


text: Q: C#: How to view the data that is being sent on a parallel port? I need to be able to read what signals are being sent on a parallel port. I guess you could consider this sniffing. The folks I am working with no longer have the ability to change an old application so they want to monitor the parallel port and log whatever is being sent on it. Can you suggest any C#.NET resources?


text:
Q: Rkt pod exited immediately (without logs) I am currently trying to run a ubuntu rkt pod. It seems to work well with the --interactive option, but when I ask for a simple run without interaction, the pod exits immediately...
I don't have any log (--no entries--) when I checked with journalctl
I just have an exited status.
The image is just an ACI that I got through docker://ubuntu and gave to docker2aci. What I don't understand is that it works well in interactive mode...

*

*Command used to run the pod:
sudo rkt --interactive --insecure-options=image run XXXXXXX.aci

*Command to get the image:
sudo docker2aci docker://ubuntu

A: I just found what was going on. This is just a problem with the run command. run have to come right after rkt. i know, it's stupid, but I may not be the only one facing this.
The right command :
sudo rkt run --insecure-options=image XXXXXXX.aci


text:
Q: Lambda function triggered on loop for unknown reason We have a lambda function that is triggered by S3 Put events (the only trigger for this function).
Recently this lambda was triggered 650k times in two days.
When looking into S3 events, the S3 Put event was triggered less than 1k times.
At first we assumed that the function was running on a loop due to errors or timeouts, but the function had only a single error in that timeframe, due to a timeout.
Does anybody know what may have triggered our Lambda Function?
Thanks!


text:
Q: Django full text search: TrigramDistance not working I am using Django 2.0 and postgresql 9.6.
I have installed pg_trgm extension in the postgresql
I am trying to understand how triagram works: I am trying the following. I want words nearer to "sridam" to be matched using triagram
from django.contrib.postgres.search import TrigramDistance
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
vector = SearchVector('title',config='english_unaccent', weight='A') + SearchVector('description',config='english_unaccent', weight='B')
query = SearchQuery('sridam',config='english_unaccent')
Article.objects.annotate(distance=TrigramDistance(vector, query)).filter(distance__lte=0.7).order_by('distance')

ProgrammingError: operator does not exist: tsvector <-> tsquery
LINE 1: ...SCE("articles_article"."description", '')), 'B')) <-> plaint...
                                                             ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

A: You can't calculate the Trigram distance between a SearchVector and a SearchQuery because "A trigram is a group of three consecutive characters.".
As specified in the Django documentation TrigramDistance "accepts a field name or expression, and a string or expression. Returns the Trigram distance between the two arguments.".

A: Before using postgres extensions you have to apply extension migrations to your model.
SOLUTION 1
Make empty migration file:
python3 manage.py makemigrations --empty yourapp

then go to the new migration file and add following
from django.db import migrations
from django.contrib.postgres.operations import TrigramExtension

class Migration(migrations.Migration):
    operations = [
        TrigramExtension()
    ]

Finally run python3 manage.py migrate to apply migrations to your database and you are ready to use the extension.
SOLUTION 2
You can go to psql console and apply migrations directly:
CREATE EXTENSION pg_trgm;


text:
Q: ("/^[a-zA-Z\_\- ]*$/") in angular not working for input box. I only need to input character not number but this didn't work.it can also accept number username: ['', Validators.required,Validators.pattern("^[a-zA-Z]+([ -][a-zA-Z]+)*$")],
not working in angular

A: If multiple validations need to be added, then it should be passed as an array. Try to correct the syntax for the form validation as follows,
From this
username: ['', Validators.required,Validators.pattern("^[a-zA-Z]+([ -][a-zA-Z]+)*$")],

To
 username: ['', [Validators.required,Validators.pattern("^[a-zA-Z]+([ -][a-zA-Z]+)*$")]],


text:
Q: html "&" and parameters I am passing several parameters through the echonest api using urllib2 in Python.  some artist and track names have the ampersand (&) character.
example:
Tommy James & The Shondells == artist=Tommy%20James%20&20The%20Shondells
How can I pass the ampersand character through the api parameter correctly?
full api query:
http://developer.echonest.com/api/v4/song/search?api_key=KEY_GOES_HERE&artist=Tommy%20James%20&20The%20Shondells&title=Crimson%20and%20Clover

A: Before you add your artist variable to the url, first try replacing each occurrence of '&' with its corresponding uri encoding, '%26'.
artist = artist.replace('&', '%26')

A: You didn't state how you are building your query string, but I urge you to check out the urllib.quote(), urllib.quote_plus() and urllib.urlencode() functions instead of manually encoding anything. The latter will apply quote_plus() to the keys and values you pass in:
>>> from urllib import urlencode
>>> artist = 'Tommy James & The Shondells'
>>> api_key = 'KEY_GOES_HERE'
>>> urlencode({'artist': artist, 'api_key': api_key})
'api_key=KEY_GOES_HERE&artist=Tommy+James+%26+The+Shondells'

Now your artist entry has been encoded using + for spaces and %26 for the ampersand.


text:
Q: Is there any way to make onbeforeunload work in Opera? I know, that Opera doesnt support JS onbeforeunload message and will not support it.
But is there any way to make it work somehow?
Or maybe some jQuery plugins can make it work and let script know if window is going to close?
I found only way to make onclick for every a tag, but this is not the complete solution.

A: Upgrade to Opera 15. onbeforeunload is now supported in that version because they moved to the WebKit engine. It is still not supported in 12.x because that version and all prior versions are based on Presto.

A: It is not possible to use onbeforeunload with Opera. There is a cross-browser solution, but that solution covers practically every big browser except Opera (IE, FireFox, Safari, Chrome).
This explains unbeforeunload and beforeunload a bit better:
http://help.dottoro.com/ljhtbtum.php
Also, this post explains it with a better example: Crossbrowser onbeforeunload?


text:
Q: Maximum length of a pipe through a hall way in three dimensions with a 90 degree turn I have found similar answers to this question in two dimensions but I am having trouble figuring out how to convert this into three dimensions taking into account the height. The question is as follows:
Two hallways, 10 ft wide and 16 ft wide respectively, open into each other at right angles. The ceiling is 12 ft high. Determine the maximum length a pole can have to be transferred from one end to the other.
Upon researching I have found a formula for the length in two dimensions being: $L=(A^{2/3}+B^{2/3})^{3/2}$ such that A and B represent the width of the two hall ways.
However, I am unaware how to take into account the ceiling still and would like to understand the concept behind this. Important to note this is a calculus 3 class.

A: Let $\ell$ be the length of the pole, and let $C$ be the height of the hallways. We should let the pole touch the floor and the ceiling at all times. The vertically projected length $\ell'$ of the pole  will then be given by $\ell'=\sqrt{\ell^2-C^2}$ at all times. This projected length has to be  $\leq L$, or the pole cannot be moved around the corner. The resulting condition therefore is
$$\ell^2\leq C^2+\bigl(A^{2/3}+B^{2/3}\bigr)^3\ .$$


text:
Q: How to get the variables in php page sent from previous page via ajax call I am making an ajax call from one php page to second.in which i m sending three variables.
But i m not able to get it in next php page where i m sending them ...
please check.
Index.php
function loadMoreData(offset){
var part1= "<?php echo ($part1);?>";

var part2="<?php echo ($part2);?>";

    $.ajax({
        type: 'get',
        async:false,
        url: 'getMoreData.php',
        data:{offset:offset,part1:part1,part2:part2},
        success: function(data){

            $(data).appendTo("#product");
        },
        error: function(data){
            alert("ajax error occured…"+data);
        }
    }).done(function(){
        $(window).bind("scroll",function(){
        scrollMore();
    });
    });
}

});

getMoredata.php
 <?php
    include('connection.php');

    $offset = (isset($_REQUEST['offset']) && $_REQUEST['offset']!='') ? $_REQUEST['offset'] : '';
    $limit = 10;
    $var1 = (isset($_REQUEST['part1']) && $_REQUEST['part1']!='') ? $_REQUEST['part1'] : '';

    $var2 = (isset($_REQUEST['part2']) && $_REQUEST['part2']!='') ? $_REQUEST['part2'] : '';

    $qry1 = mysql_query('select * from xml WHERE  PNAME LIKE  \'%$var2\' AND CATEGORY like \'%$var1\' limit ".$offset.", ".$limit."');
    print $qry1;
    ?>

I m able to send the three variables from index.php page but i m not able to get them in getMoreData.php,due to which i m not able to run the sql command...
Please verify guys....

A: Try with this for all variables
$offset = isset($_GET['offset']) ? $_GET['offset'] : $_POST['offset'];

A: Use $_GET instead of $_REQUEST.
Also you are not sending the rows properly, use-
print_r(mysql_fetch_array($qry1));

Then try to check the response in browser's console with - console.log(data) and then manipulate it accordingly.


text: Q: Merging two binary min-heaps I have two binary min-heaps, where each one stores different keys. The trees are also complete binary trees. I want to merge these two into one binary min-heap of size exactly 2n. Preferably in O(long) time and O(1) space.


text:
Q: Reasoning about performance in Haskell The following two Haskell programs for computing the n'th term of the Fibonacci sequence have greatly different performance characteristics:
fib1 n =
  case n of
    0 -> 1
    1 -> 1
    x -> (fib1 (x-1)) + (fib1 (x-2))

fib2 n = fibArr !! n where
  fibArr = 1:1:[a + b | (a, b) <- zip fibArr (tail fibArr)]

They are very close to mathematically identical, but fib2 uses the list notation to memoize its intermediate results, while fib1 has explicit recursion.  Despite the potential for the intermediate results to be cached in fib1, the execution time gets to be a problem even for fib1 25, suggesting that the recursive steps are always evaluated.  Does referential transparency contribute anything to Haskell's performance?  How can I know ahead of time if it will or won't?
This is just an example of the sort of thing I'm worried about.  I'd like to hear any thoughts about overcoming the difficulty inherent in reasoning about the performance of a lazily-executed, functional programming language.

Summary:  I'm accepting 3lectrologos's answer, because the point that you don't reason so much about the language's performance, as about your compiler's optimization, seems to be extremely important in Haskell - more so than in any other language I'm familiar with.  I'm inclined to say that the importance of the compiler is the factor that differentiates reasoning about performance in lazy, functional langauges, from reasoning about the performance of any other type.

Addendum: Anyone happening on this question may want to look at the slides from Johan Tibell's talk about high performance Haskell.

A: Reasoning about performance is generally hard in Haskell and lazy languages in general, although not impossible. Some techniques are covered in Chris Okasaki's Purely Function Data Structures (also available online in a previous version).
Another way to ensure performance is to fix the evaluation order, either using annotations or continuation passing style. That way you get to control when things are evaluated.
In your example you might calculate the numbers "bottom up" and pass the previous two numbers along to each iteration:
fib n = fib_iter(1,1,n)
    where
      fib_iter(a,b,0) = a
      fib_iter(a,b,1) = a
      fib_iter(a,b,n) = fib_iter(a+b,a,n-1)

This results in a linear time algorithm.
Whenever you have a dynamic programming algorithm where each result relies on the N previous results, you can use this technique. Otherwise you might have to use an array or something completely different.

A: Your implementation of fib2 uses memoization but each time you call fib2 it rebuild the "whole" result. Turn on ghci time and size profiling:
Prelude> :set +s

If it was doing memoisation "between" calls the subsequent calls would be faster and use no memory. Call fib2 20000 twice and see for yourself.
By comparison a more idiomatic version where you define the exact mathematical identity:
-- the infinite list of all fibs numbers.
fibs = 1 : 1 : zipWith (+) fibs (tail fibs)

memoFib n = fibs !! n

actually do use memoisation, explicit as you see. If you run memoFib 20000 twice you'll see the time and space taken the first time then the second call is instantaneous and take no memory. No magic and no implicit memoization like a comment might have hinted at.
Now about your original question: optimizing and reasoning about performance in Haskell...
I wouldn't call myself an expert in Haskell, I have only been using it for 3 years, 2 of which at my workplace but I did have to optimize and get to understand how to reason somewhat about its performance.
As mentionned in other post laziness is your friend and can help you gain performance however YOU have to be in control of what is lazily evaluated and what is strictly evaluated.
Check this comparison of foldl vs foldr
foldl actually stores "how" to compute the value i.e. it is lazy. In some case you saves time and space beeing lazy, like the "infinite" fibs. The infinite "fibs" doesn't generate all of them but knows how. When you know you will need the value you might as well just get it "strictly" speaking... That's where strictness annotation are usefull, to give you back control.
I recall reading many times that in lisp you have to "minimize" consing.
Understanding what is stricly evaluated and how to force it is important but so is understanding how much "trashing" you do to the memory. Remember Haskell is immutable, that means that updating a "variable" is actually creating a copy with the modification. Prepending with (:) is vastly more efficient than appending with (++) because (:) does not copy memory contrarily to (++). Whenever a big atomic block is updated (even for a single char) the whole block needs to be copied to represent the "updated" version. The way you structure data and update it can have a big impact on performance. The ghc profiler is your friend and will help you spot these. Sure the garbage collector is fast but not having it do anything is faster!
Cheers

A: Aside from the memoization issue, fib1 also uses non-tailcall recursion. Tailcall recursion can be re-factored automatically into a simple goto and perform very well, but the recursion in fib1 cannot be optimized in this way, because you need the stack frame from each instance of fib1 in order to calculate the result. If you rewrote fib1 to pass a running total as an argument, thus allowing a tail call instead of needing to keep the stack frame for the final addition, the performance would improve immensely. But not as much as the memoized example, of course :)

A: In your particular Fibonacci example, it's not very hard to see why the second one should run faster (although you haven't specified what f2 is).
It's mainly an algorithmic issue:

*

*fib1 implements the purely recursive algorithm and (as far as I know) Haskell has no mechanism for "implicit memoization".

*fib2 uses explicit memoization (using the fibArr list to store previously computed values.

In general, it's much harder to make performance assumptions for a lazy language like Haskell, than for an eager one. Nevertheless, if you understand the underlying mechanisms (especially for laziness) and gather some experience, you will be able to make some "predictions" about performance.
Referential transparency increases (potentially) performance in (at least) two ways:

*

*First, you (as a programmer) can be sure that two calls to the same function will always return the same, so you can exploit this in various cases to benefit in performance.

*Second (and more important), the Haskell compiler can be sure for the above fact and this may enable many optimizations that can't be enabled in impure languages (if you've ever written a compiler or have any experience in compiler optimizations you are probably aware of the importance of this).

If you want to read more about the reasoning behind the design choices (laziness, pureness) of Haskell, I'd suggest reading this.

A: Since allocation is a major cost in any functional language, an important part of understanding performance is to understand when objects are allocated, how long they live, when they die, and when they are reclaimed.  To get this information you need a heap profiler.  It's an essential tool, and luckily GHC ships with a good one.
For more information, read Colin Runciman's papers.


text:
Q: How to deal with null values using Python format I'm looking for a way to essentially strip out the extra period if a value is null or None. If myvar doesn't exist, it should print abc.xyz
myvar="def"
print "abc.{0}.xyz".format(myvar)
abc.def.xyz

myvar=""
print "abc.{0}.xyz".format(myvar)
abc..xyz

A: If a character is present in the original string it will be included regardless after calling format for it.  What needs to be done is to modify the input such that it will include whatever extra character when the intended value is present.  Consider the following (encapsulated in a function as a demo):
def demo(value):
    print("abc.{0}xyz".format(value + '.' if value else ''))

Example usage:
>>> demo('def')
abc.def.xyz
>>> demo('')
abc.xyz

A: You could add the period to myvar.
myvar = (myvar + '.') if myvar else myvar

A: I would do something like this:
>>> myvar=""
>>> print "abc.{0}.xyz".format(myvar) if myvar else "abc.xyz"
abc.xyz

A: You could replace all instances of double periods with just one.
myvar=""
output = "abc.{0}.xyz".format(myvar)
print str.replace(output, "..", ".")
abc.xyz


text:
Q: Why does this SO (shared object) end in .3gf? On ubuntu trusty tahr, when I install libblas3 from the repository, it installs a file at /usr/lib/libblas.so.3gf. Under focal fossa, it behaves differently and installs under /usr/lib/x86_64-linux-gnu/libblas.so.3. I am assuming that the latter follows libtool versioning as per this answer. However I can't find anything about this old .3gf file extension. It is found alongside libblas.so.3 and libblas.so. What does .3gf represent?

A: Typically a shared library comes with a file and two symbolic links:

*

*The file libfoo.so.1.2.3 (with multiple numbers after .so) is named after the version of the library as a software project. It isn't used directly, only through one of the two symbolic links.

*The symbolic link libfoo.so.V (with a single number after .so) is named after the "soversion" (shared object version). The soversion changes every time there is an incompatible change in the library's ABI. Programs are linked against a specific soversion of the library. You can have different versions of the library installed, with different soversions, if you have programs that were built against different versions of the library.

*The symbolic libfoo.so (with no numbers after .so) is the version for which you have development files installed (headers, static library). If you compile a program, it will be linked with whatever soversion libfoo.so points to (which had better be compatible with the header files).

The soversion in the file name is conventionally an integer that is incremented each time there is an incompatible change, but it doesn't have to be.
For a some time, Debian maintained two versions of the BLAS library with incompatible APIs: libblas3 with the API of the upstream project, and libblas3gf with "several minor changes to the C interface". The libblas3 package installed libblas.so.3 for programs linked against the upstream API and the libblas3gf package installed libblas.so.3gf for programs linked against the Debian API.
In 2011, Debian stopped maintaining a separate version of the library. (As far as I understand it, the Debian changes or something like them were merged upstream, and so future versions of libblas3 had everything that the 3gf version had.) So the 3gf version became obsolete, but the .so file was still available to run existing compiled programs. It took several years for the backward compatibility aliases to be removed. Ubuntu 18.04 still had them, but Ubuntu 20.04 no longer has them.


text:
Q: In Crystal Reports, how do I Suppress a Text Object if any row contains a certain value In my report, I want to display a warning text object in the report header if a column value in any row contains a certain value.
"Warning, this report has problems"
How to I construct a suppression formula for the text object to accomplish this?
If there is some other way to hide/display it, that would be fine also.

A: How to I construct a suppression formula for the text object to accomplish this?

*

*Right click the text object

*Go to Common Tab

*There is a Suppress checkbox to the right if it there is a button with a x2, click this button

*In the formula editor write a formula that returns true if this "certain value" is in the row or false otherwise

A: Let's assume you are interested in the ocurrence of value "WarningValue" in the column "MyColumn" in the table "Result".
First, create a formula. Let's call it "MyFormula". It should be like this:
if not isnull({Result.MyColumn}) and {Result.MyColumn} = "WarningValue" then 1 else 0

Then put this formula in details session. You can suppress it.
Then click on the report header using the right button. In the context menu, select "insert section below". Put a text box with the message "Warning, this report has problems" inside this new section. Click in this section using the right button and select "section expert" in the context menu. Put the following formula in the "suppress" option:
sum({@MyFormula}) < 1

So if the report count at least 1 occurrence of the "WarningValue", it will not suppress that message.

A: Nick nailed it, but he left out one step.

*

*Right-click the text object

*Select "Format Text...", which opens the "Format Editor" dialog.

*In the "Format Editor" dialog, go to Common Tab.

*There is a Suppress checkbox. To the right [o]f it, there is a button with a x2. Click this button

*In the formula editor, write a formula that returns true if this "certain value" is in the row, or false otherwise


text:
Q: How can we use style prop in TouchableWithoutFeedback or TouchableWithNativeFeedback? I want to give some style to the TouchableWithNativeFeedback ,  The style prop doesnot work although it works fine with the TouchableOpacity but it wont work with the native feedback. Is there any way we can make it work. I found a solution but I dont want to do it is there any other way.
The solution that I found in github.
link :
https://github.com/facebook/react-native/issues/8307
Answer:

I was having the same issue. But I wrapped the
TouchableWithoutFeedback element with a view and styled the view
instead. And I wrapped everything inside the TouchableWithoutFeedback
with another view with a style identical to the parent view. This
seems to have fixed it for me.

Thank you.

A: This is not possible, since TouchableWithNativeFeedback does not have a style prop. This is documented here in the documentation.
The recommended pattern is the one you do not want to use (for whatever reason).
// the styling in the view of the child of TouchableWithoutFeedback
<TouchableWithoutFeedback onPress={onPress}>
   <View style={styles.button}>
     <Text>Touch</Text>
   </View>
</TouchableWithoutFeedback>


text:
Q: I have an error in php in a loop within a loop I have this error:

Warning: mysql_data_seek() [function.mysql-data-seek]: Offset 9 is invalid for MySQL result index 4 (or the query data is unbuffered)

I have a table messages, and I would like to display the most recent message. If user 1 is logged in, I would like to do this: For instance if user 1 sent an message to user 2, then user 2 to user 1, I would like to show to user 1, the newest message. So it would be the one that was sent by user 2.
So, I have to display to user 1, the ids 2 and 3.

    <?php
             $conexion=mysql_connect('localhost','root','root') or die('No');
    $db=mysql_select_db('carpe',$conexion)or die('no existe la base de datos.');

    $id= $_SESSION['id'];

    $multid_array = array();
    $outercnt=0;
 $consulta=mysql_query("select * from messages where id_from='".$id."'
 or id_to='".$id."' order by id asc");
    while($filas=mysql_fetch_array($consulta)){
        $id=$filas['id'];
        $id_to=$filas['id_to'];
        $id_from=$filas['id_from'];
        $status=$filas['status'];
        $text=$filas['text'];
        $time=$filas['time'];
        echo "lo primero: ";

        echo $id;
        echo " ";

        mysql_data_seek($consulta, 0);
        while($filas2=mysql_fetch_array($consulta)){
            $id2=$filas2['id'];
            $id_to2=$filas2['id_to'];
            $id_from2=$filas['id_from'];
            $status2=$filas2['status'];
            $text2=$filas2['text'];
            $time2=$filas2['time'];
            echo "es ";
            echo $id2;
                if($id_from==$id_from2 && $id_to==$id_to2 && $id2>$id){
                    $id=$id2;
                    echo "el mas grande ";
                    echo $id;
                }
        }
         mysql_data_seek($consulta,$outercnt);
         $outercnt++;

        //Almaceno en un vector los mensajes a mostrar
        $multid_array[]=$id;

        echo "nuevo elemento  ";
        echo $id;
    }

    //Elimino duplicados
    $resultado = array_unique($multid_array);

    for ($x=0;$x<count($resultado); $x++){
        $id=$resultado[$x];
        $consulta=mysql_query("select * from messages where id='".$id."'");
        echo "arreglo ";
        echo $id;
        echo " ";
        while($filas=mysql_fetch_array($consulta)){
            $id_from=$filas['id_from'];
            $id_to=$filas['id_to'];
            $status=$filas['status'];
            $subject=$filas['subject'];
            $text=$filas['text'];
            $time=$filas['time'];
        }

    ?>

Asunto: <?php echo $id?>

            Enviado por: De <?php echo
                         $id_from ?> A <?php echo $id_to ?> - <?php echo $time ?>

<?php echo $text ?>

            Responder

            <?php } ?>

The first error is when I am trying to do:
mysql_data_seek($consulta,$outercnt);
I have another error (2nd) when I do:
$id=$resultado[$x];
this is the second error:
 Notice: Undefined offset: 1
I am currently displaying the messages, but I have those errors. thanks!

A: You're trying to fetch row 9 but there is no row 9.
Check how many rows are returned before you try to fetch them?

A: for ($x=0;$x<count($resultado); $x++){
        $id=$resultado[$x];

it fetches $x element which can be non-existant,
right after for and before $id=$resultado[$x]; , paste:
if (!isset($resultado[$x])){
continue;
}


text:
Q: wrong constructor used in template class I need to use inside my templated class a boost::interprocess::mutex
Inside my function I declared my variable the way below
  named_mutex mutex(open_only, m_name.c_str()
  ,permissions(0666));

I don't know why I cannot compile and I get an error below.
How is it possible that the compiler doesn't use the right constructor (it tries to match a constructor having const reference) and how to force using the right one?
    error: no matching function for call to
    boost::interprocess::named_mutex::named_mutex(const
    boost::interprocess::open_only_t&,   const char*, boost::interprocess::permissions)'
    /usr/local/include/boost/interprocess/sync/named_mutex.hpp:140: note:
    candidates are:
    boost::interprocess::named_mutex::named_mutex(boost::interprocess::open_only_t, const char*)

A: The constructor that takes an open_only_t doesn't take a permission parameter. Wouldn't really make sense - you're trying to open an existing mutex, not to create one.
Remove the permissions and it should find the proper overload.


text:
Q: Java Constructor being called multiple times I'm creating a PokerHand class and using JUnit tests to test it, and for some reason my constructor is called 8 times when I call it in one test method, when I create one PokerHand object.
PokerHand constructor (added a print statement to see how many times it was being called, prints 8 separate times):
//Constructor
public PokerHand (Card cardOne, Card cardTwo, Card cardThree, Card cardFour, Card cardFive) {
    System.out.println("creating hand...");
    //Initialize value array
    value = new int[6];
    //Initialize cards list, add cards, and check for duplicates
    cards = new ArrayList<Card>();

    cards.add(cardOne);
    if (cards.contains(cardTwo)) {
        throw new DuplicateCardException();
    } else cards.add(cardTwo);
    if (cards.contains(cardThree)) {
        throw new DuplicateCardException();
    } else cards.add(cardThree);
    if (cards.contains(cardFour)) {
        throw new DuplicateCardException();
    } else cards.add(cardFour);
    if (cards.contains(cardFive)) {
        throw new DuplicateCardException();
    } else cards.add(cardFive);

    determineValueOfHand();
}

Test case:
    @Test
  public void testFlush() {
      PokerHand a = new PokerHand(D10, DJ, DQ, DK, DA);
  }

I've been staring at a screen for some time and I'm new to JUnit tests and eclipse, so I'm sure I'm just missing a small detail. Any help is greatly appreciated

A: A hint that according to your comment fixed the problem: probably your method determineValueOfHand() erroneously creates other PokerHand objects.
In order to check for that; I recommend that

*

*your constructor

*your testcase

does println()s using the object reference. In addition to that, you could put entry/exit traces into your ctor! That makes it more obvious in which order constructor calls happen.


text:
Q: spark Scala for loop inside again for loop I have a count which is a list as below
   My data in count as below
   (Focus,37)
   (Test,26)

and my code is as below.
         for (i <- count ) {
              for(x <- i {
                 if(x == "Focus"){
                     Focus_cnt=i(x) }
                        else if(x == "Test"){
                           Test_cnt=i(x) }
                           else {
            pass
        }
    }
}

The error i am facing is at line -  for(x <- i   and the error is  i: (Any, Any)
Any better way to get counts in spark Scala.

A: Can you check this ? let me know if i understood wrongly.
In this i am applying filter & taking counts.
scala> Seq(("fa","fb","fc",5,"fe","ff","Focus"),("fba","fbb","fbc",16,"bd","be","Focus"),("fba","fbb","fbc",54,"bd","be","Focus"),("fca","fcb","fcc",135,"fcd","fef","Focus"),("a","b","c",5,"e","f","Test"),("aa","ba","ca",56,"ea","fa","Test"),("ab","cb","cc",35,"de","df","Test")).toDF("a","b","c","d","e","f","status")
res29: org.apache.spark.sql.DataFrame = [a: string, b: string ... 5 more fields]

scala> val df = Seq(("fa","fb","fc",5,"fe","ff","Focus"),("fba","fbb","fbc",16,"bd","be","Focus"),("fba","fbb","fbc",54,"bd","be","Focus"),("fca","fcb","fcc",135,"fcd","fef","Focus"),("a","b","c",5,"e","f","Test"),("aa","ba","ca",56,"ea","fa","Test"),("ab","cb","cc",35,"de","df","Test")).toDF("a","b","c","d","e","f","status")
df: org.apache.spark.sql.DataFrame = [a: string, b: string ... 5 more fields]

scala> val newDF = df.groupBy("status").agg(count("status").as("count"))
newDF: org.apache.spark.sql.DataFrame = [status: string, count: bigint]

scala> val focus_cnt = newDF.filter($"status" === "Focus").select("count").map(_.getAs[Long](0)).head
focus_cnt: Long = 4

scala> val test_cnt  = newDF.filter($"status" === "Test").select("count").map(_.getAs[Long](0)).head
test_cnt: Long = 3


text:
Q: Android TV: How to customize left navigation panel of android TV using Leanbak? Currently I am working an android tv application project and my navigation panel is showing text and icon when it is in expanded mode like -

When navigation panel is collapsed it showing a vertical bar with just color and no icons or something is showing.
But I am trying to achieve this kind of design when navigation panel is collapsed -

Now my question is is this achievable using leanback and if possible how can I implement it?
Any kind of hints, tips or reference will be helpful.
Thanks in advance.

A: This type of functionality is not supported in Leanback. And I too searched the solution for it everywhere but didn't find anything useful. So I ended up writing a Fragment that behaves like the sidebar navigation and works with RowsSupportFragment through an interface for exchanging KeyPad Events.
When in Expanded State -> Menu Icon & Menu Names are shown.
When in Collapsed State -> Menu Icons are shown.
check out this repository TVNavigationMenu

A: try this repo it's fine.let's try this it  will help


text:
Q: SignalR + passing custom object from server to client not working I am trying to pass a custom object from self hosted signalr hub server to all the clients, the method in client side not getting invoked .But if the same custom class object is passed from client to server works fine, meaning it invokes the server method.
below is the sample code :
public class ChatHub : Hub
{
    public void Send(DataContract message)
    {
        //below call not reaching to client while passing custom obj
        Clients.All.SendMessage(message);
        //below string passing works - means invokes client method
        Clients.All.SendMsg("test");
    }
}

custom class defined in both client and server project via dll:
public class DataContract
{
    public string Name
    {
        get;set;
    }

    public int Id
    {
        get;set;
    }
}

client side method:
public class SignalRClient
{
    HubConnection hubConnection = null;
    IHubProxy chat;

    public SignalRClient()
    {
        hubConnection = new HubConnection("https://localhost/");
        chat = hubConnection.CreateHubProxy("ChatHub");
    }
    public void StartConnection()
    {
        if (hubConnection != null)
        {
            hubConnection.Start().Wait();
        }

        chat.On<DataContract>("SendMessage", (stock) =>
            {
                Console.WriteLine("name {0} id {1}", stock.Name, stock.Id.ToString());
            });

          chat.On<string>("SendMsg", (message) =>
        {
            Console.WriteLine(message);
        });
     }

    public void SendMessage(DataContract dd)
    {
          dd.Name = "test";
          chat.Invoke("Send", dd).Wait();
    }

    public void SendMessage(string msg)
    {
          chat.Invoke("SendMsg", "Console app", msg).Wait();
    }
}

//program.cs
main()
{
     SignalRClient client = new SignalRClient();
     client.StartConnection();

     string msg = null;
     while ((msg = Console.ReadLine()) != null)
     {
          DataContract dd = new DataContract { Name = "arun", Id = 9 };
          //below calls reaches to server both string type and custome obj
          client.SendMessage(dd);
          client.SendMessage("client");
     }
}

Any clue on why when calling from server (i.e  Clients.All.SendMessage(message); ) not invoking client method when param is custom object.
Thanks in advance.


text:
Q: 1960s-70s short story: Shapechanging alien invasion scouts on Earth I am looking to identify a story I read in the 1960s or 70s. It was about a scoutship that landed on Earth, prelude to an invasion force. Previous scouts had disappeared without a trace.
The crew members' names were descriptive of their function. I think the protagonist was called Pilot. They are shape-changers. One by one, the crew members defect, taking on forms of Earth creatures that fit their function and personality. Pilot tries desperately to complete the mission. One scene I remember is he assumes human form and walks into a building -- but is unable to blend in, I think because he forgets to form facial features.
He struggles to complete his crew's mission, barricading himself in a room? (perhaps to destroy the planet?) when he sees birds out the window. The people breaking in to stop him see only a large (white?) bird flying out the window, a bit awkward, but quickly gaining control of its wings and soaring away.
Help, please?

A: Shape by Robert Sheckley, aka "Keep Your Shape"; available at the Internet Archive and Project Gutenberg. Long description from this page:

 This is the story of a group of aliens from the planet Glom who have come to earth to take over the planet so they can expand their amount of space and resources. The aliens are creatures from a highly specialized society that regiments specific  body shapes for the creatures to maintain according to the jobs they practice. At birth, the Gloms are formless blobs, but are immediately assigned their jobs and shapes in accordance with those of their ancestors.
 [...]

  Pid, so loyal to the government of Gola, is disgusted by these statements and sneaks into the atomic power installation himself. Right before he activates the displacer in the reactor room, he sees a bird fly past the window, and realizes that this animal has a shape that goes above and beyond his wants and needs. Disregarding all that he has just said and accused his friends of, he jumps out of the window and morphs into the shape of a bird, abandoning the assignment he was given, and deciding to live in the shape most desirable to him.


text:
Q: Getting started with keycloak and kubernetes I am trying to run keycloak on kubernetes so I follow this example on my kubernetes cluster. But when I run command:
kubectl create -f https://raw.githubusercontent.com/keycloak/keycloak-quickstarts/latest/kubernetes-examples/keycloak.yaml

I got database error after 2 minutes.  Why  I can not run this simple example without error ?
00:15:29,210 INFO  [org.keycloak.connections.infinispan.DefaultInfinispanConnectionProviderFactory] (ServerService Thread Pool -- 66) Node name: keycloak-b6b94bd59-v96tk, Site name: null
00:17:39,565 WARN  [org.jboss.jca.core.connectionmanager.pool.strategy.OnePool] (ServerService Thread Pool -- 66) IJ000604: Throwable while attempting to get a new connection: null: javax.resource.ResourceException: IJ031084: Unable to create connection
    at org.jboss.ironjacamar.jdbcadapters@1.4.23.Final//org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:345)
    at org.jboss.ironjacamar.jdbcadapters@1.4.23.Final//org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getLocalManagedConnection(LocalManagedConnectionFactory.java:352)
    at org.jboss.ironjacamar.jdbcadapters@1.4.23.Final//org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createManagedConnection(LocalManagedConnectionFactory.java:287)
    at org.jboss.ironjacamar.impl@1.4.23.Final//org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.createConnectionEventListener(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:1322)
    at org.jboss.ironjacamar.impl@1.4.23.Final//org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.getConnection(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:499)
    at org.jboss.ironjacamar.impl@1.4.23.Final//org.jboss.jca.core.connectionmanager.pool.AbstractPool.getSimpleConnection(AbstractPool.java:632)
    at org.jboss.ironjacamar.impl@1.4.23.Final//org.jboss.jca.core.connectionmanager.pool.AbstractPool.getConnection(AbstractPool.java:604)
    at org.jboss.ironjacamar.impl@1.4.23.Final//org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:624)
    at org.jboss.ironjacamar.impl@1.4.23.Final//org.jboss.jca.core.connectionmanager.tx.TxConnectionManagerImpl.getManagedConnection(TxConnectionManagerImpl.java:440)
    at org.jboss.ironjacamar.impl@1.4.23.Final//org.jboss.jca.core.connectionmanager.AbstractConnectionManager.allocateConnection(AbstractConnectionManager.java:789)
    at org.jboss.ironjacamar.jdbcadapters@1.4.23.Final//org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:151)
    at org.jboss.as.connector@21.0.2.Final//org.jboss.as.connector.subsystems.datasources.WildFlyDataSource.getConnection(WildFlyDataSource.java:64)
    at org.keycloak.keycloak-model-jpa@12.0.4//org.keycloak.connections.jpa.DefaultJpaConnectionProviderFactory.getConnection(DefaultJpaConnectionProviderFactory.java:371)
    at org.keycloak.keycloak-model-jpa@12.0.4//org.keycloak.connections.jpa.updater.liquibase.lock.LiquibaseDBLockProvider.lazyInit(LiquibaseDBLockProvider.java:65)
    at org.keycloak.keycloak-model-jpa@12.0.4//org.keycloak.connections.jpa.updater.liquibase.lock.LiquibaseDBLockProvider.lambda$waitForLock$2(LiquibaseDBLockProvider.java:96)
    at org.keycloak.keycloak-server-spi-private@12.0.4//org.keycloak.models.utils.KeycloakModelUtils.suspendJtaTransaction(KeycloakModelUtils.java:654)
    at org.keycloak.keycloak-model-jpa@12.0.4//org.keycloak.connections.jpa.updater.liquibase.lock.LiquibaseDBLockProvider.waitForLock(LiquibaseDBLockProvider.java:94)
    at org.keycloak.keycloak-services@12.0.4//org.keycloak.services.resources.KeycloakApplication$1.run(KeycloakApplication.java:136)
    at org.keycloak.keycloak-server-spi-private@12.0.4//org.keycloak.models.utils.KeycloakModelUtils.runJobInTransaction(KeycloakModelUtils.java:228)
    at org.keycloak.keycloak-services@12.0.4//org.keycloak.services.resources.KeycloakApplication.startup(KeycloakApplication.java:129)
    at org.keycloak.keycloak-wildfly-extensions@12.0.4//org.keycloak.provider.wildfly.WildflyPlatform.onStartup(WildflyPlatform.java:29)
    at org.keycloak.keycloak-services@12.0.4//org.keycloak.services.resources.KeycloakApplication.<init>(KeycloakApplication.java:115)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at org.jboss.resteasy.resteasy-jaxrs@3.13.2.Final//org.jboss.resteasy.core.ConstructorInjectorImpl.construct(ConstructorInjectorImpl.java:152)
    at org.jboss.resteasy.resteasy-jaxrs@3.13.2.Final//org.jboss.resteasy.spi.ResteasyProviderFactory.createProviderInstance(ResteasyProviderFactory.java:2815)
    at org.jboss.resteasy.resteasy-jaxrs@3.13.2.Final//org.jboss.resteasy.spi.ResteasyDeployment.createApplication(ResteasyDeployment.java:371)
    at org.jboss.resteasy.resteasy-jaxrs@3.13.2.Final//org.jboss.resteasy.spi.ResteasyDeployment.startInternal(ResteasyDeployment.java:283)
    at org.jboss.resteasy.resteasy-jaxrs@3.13.2.Final//org.jboss.resteasy.spi.ResteasyDeployment.start(ResteasyDeployment.java:93)
    at org.jboss.resteasy.resteasy-jaxrs@3.13.2.Final//org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.init(ServletContainerDispatcher.java:140)
    at org.jboss.resteasy.resteasy-jaxrs@3.13.2.Final//org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.init(HttpServletDispatcher.java:42)
    at io.undertow.servlet@2.2.2.Final//io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:117)
    at org.wildfly.extension.undertow@21.0.2.Final//org.wildfly.extension.undertow.security.RunAsLifecycleInterceptor.init(RunAsLifecycleInterceptor.java:78)
    at io.undertow.servlet@2.2.2.Final//io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:103)
    at io.undertow.servlet@2.2.2.Final//io.undertow.servlet.core.ManagedServlet$DefaultInstanceStrategy.start(ManagedServlet.java:305)
    at io.undertow.servlet@2.2.2.Final//io.undertow.servlet.core.ManagedServlet.createServlet(ManagedServlet.java:145)
    at io.undertow.servlet@2.2.2.Final//io.undertow.servlet.core.DeploymentManagerImpl$2.call(DeploymentManagerImpl.java:588)
    at io.undertow.servlet@2.2.2.Final//io.undertow.servlet.core.DeploymentManagerImpl$2.call(DeploymentManagerImpl.java:559)
    at io.undertow.servlet@2.2.2.Final//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42)
    at io.undertow.servlet@2.2.2.Final//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at org.wildfly.extension.undertow@21.0.2.Final//org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
    at org.wildfly.extension.undertow@21.0.2.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1530)
    at org.wildfly.extension.undertow@21.0.2.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1530)
    at org.wildfly.extension.undertow@21.0.2.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1530)
    at org.wildfly.extension.undertow@21.0.2.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1530)
    at io.undertow.servlet@2.2.2.Final//io.undertow.servlet.core.DeploymentManagerImpl.start(DeploymentManagerImpl.java:601)
    at org.wildfly.extension.undertow@21.0.2.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:97)
    at org.wildfly.extension.undertow@21.0.2.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:78)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.jboss.threads@2.4.0.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1990)
    at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
    at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
    at java.base/java.lang.Thread.run(Thread.java:834)
    at org.jboss.threads@2.4.0.Final//org.jboss.threads.JBossThread.run(JBossThread.java:513)
Caused by: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at com.mysql.jdbc@8.0.22//com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
    at com.mysql.jdbc@8.0.22//com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
    at com.mysql.jdbc@8.0.22//com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
    at com.mysql.jdbc@8.0.22//com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.jdbc@8.0.22//com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
    at com.mysql.jdbc@8.0.22//com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198)
    at org.jboss.ironjacamar.jdbcadapters@1.4.23.Final//org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:321)
    ... 57 more
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at com.mysql.jdbc@8.0.22//com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
    at com.mysql.jdbc@8.0.22//com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)
    at com.mysql.jdbc@8.0.22//com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151)
    at com.mysql.jdbc@8.0.22//com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167)
    at com.mysql.jdbc@8.0.22//com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:89)
    at com.mysql.jdbc@8.0.22//com.mysql.cj.NativeSession.connect(NativeSession.java:144)
    at com.mysql.jdbc@8.0.22//com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:956)
    at com.mysql.jdbc@8.0.22//com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:826)
    ... 61 more
Caused by: java.net.ConnectException: Connection timed out (Connection timed out)
    at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399)
    at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242)
    at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.base/java.net.Socket.connect(Socket.java:609)
    at com.mysql.jdbc@8.0.22//com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:155)
    at com.mysql.jdbc@8.0.22//com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:63)
    ... 64 more

00:17:39,573 FATAL [org.keycloak.services] (ServerService Thread Pool -- 66) Error during startup: java.lang.RuntimeException: Failed to connect to database

A: your error is clearly informing keylock is trying to connect with the database but can't get it there might be an issue with your configuration file or environment you are passing.
You can try this out : https://github.com/harsh4870/Keycloack-postgres-kubernetes-deployment
let me know if these files don't work. it's not for a production use case but you can use it for setting up the dev environment.


text:
Q: Can this infinite summation be simplified? I encountered the following infinite summation $$\sum_{k=0,k\neq m}^{\infty}\frac{x^k}{(k-m)k!},x>0,$$ can it be simplified? Thanks!

A: As already mentioned, a possible approach consists in multiplying the sum by $x^{-m}$ which leads to a sum easy to express on exponential form. But what follows with this method is rather arduous, because further integration involves an incomplete Gamma function with negative integer parameter.
In order to save time, we will use another method (a short-cut in fact), starting from the known formula of the incomplete Gamma function in case of negative integer parameter :
$$\Gamma(-m,z)=\frac{(-1)^m}{m!}\big(\psi(m+1)-\ln(z)\big)-\frac{1}{z^m} \sum_{k=0,k\neq m}^{\infty}\frac{(-z)^k}{(k-m)k!}$$
$$\sum_{k=0,k\neq m}^{\infty}\frac{(-z)^k}{(k-m)k!}=z^m\left( \frac{(-1)^m}{m!}\big(\psi(m+1)-\ln(z)\big)-\Gamma(-m,z) \right)$$
For $x$ positive variable : $z=-x$ so that :
$$\sum_{k=0,k\neq m}^{\infty}\frac{x^k}{(k-m)k!}=(-x)^m\left( \frac{(-1)^m}{m!}\big(\psi(m+1)-\ln(-x)\big)-\Gamma(-m,-x) \right)$$
$\ln(-x)$ and $\Gamma(-m,-x)$ are both complex. But, the imaginary part fades in the formula. So, in separating the real part, we can write :
$$\sum_{k=0,k\neq m}^{\infty}\frac{x^k}{(k-m)k!}=(-x)^m\left( \frac{(-1)^m}{m!}\big(\psi(m+1)-\ln(x)\big)-\operatorname{Re}\big(\Gamma(-m,-x)\big) \right)$$
In this formula, $\psi$ is the symbol for the digamma function, $\Gamma$ is the symbol for the Incomplete Gamma function and $\operatorname{Re}$ is the symbol for the real part (to be not confused with the modulus, of course).
The formula has been tested with numerical computations.