text:
Q: How to achieve unicode-agnostic case insensitive comparison in C++ I have a requirement wherein my C++ code needs to do case insensitive comparison without worrying about whether the string is encoded or not, or the type of encoding involved. The string could be an ASCII or a non-ASCII, I just need to store it as is and compare it with a second string without concerning if the right locale is set and so forth.
Use case: Suppose my application receives a string (let's say it's a file name) initially as "Zoë Saldaña.txt" and it stores it as is. Subsequently, it receives another string "zoë saLdañA.txt", and the comparison between this and the first string should result in a match, by using a few APIs. Same with file name "abc.txt" and "AbC.txt".
I read about IBM's ICU and how it uses UTF-16 encoding by default. I'm curious to know:

*

*If ICU provides a means of solving my requirement by seamlessly handling the strings regardless of their encoding type?

*If the answer to 1. is no, then, using ICU's APIs, is it safe to normalize all strings (both ASCII and non-ASCII) to UTF-16 and then do the case-insensitive comparison and other operations?

*Are there alternatives that facilitate this?
I read this post, but it doesn't quite meet my requirements.
Thanks!

A: The requirement is impossible. Computers don't work with characters, they work with numbers. But "case insensitive" comparisons are operations which work on characters. Locales determine which numbers correspond to which characters, and are therefore indispensible.
The above isn't just true for all progamming langguages, it's even true for case-sensitive comparisons. The mapping from character to number isn't always unique. That means that comparing two numbers doesn't work. There could be a locale where character 42 is equivalent to character 43. In Unicode, it's even worse. There are number sequences  which have different lengths and still are equivalent. (precomposed and decomposed characters in particular)

A: Without knowing encoding, you cannot do that. I will take one example using french accented characters and 2 different encodings: cp850 used as OEM character for windows in west european zone, and the well known iso-8859-1 (also known as latin1, not very different from win1252 ansi character set for windows)).

*

*in cp850,   0x96 is 'û', 0xca is '╩', 0xea is 'Û'

*in latin1, 0x96 is non printable(*), 0xca is 'Ê', 0xea is 'ê'
so if string is cp850 encoded, 0xea should be the same as 0x96 and 0xca is a different character
but if string is latin1 encoded, 0xea should be the same as 0xca, 0x96 being a control character
You could find similar examples with other iso-8859-x encoding by I only speak of languages I know.
(*) in cp1252 0x96 is '–' unicode character U+2013 not related to 'ê'

A: For UTF-8 (or other Unicode) encodings, it is possible to perform a "locale neutral" case-insensitive string comparison.  This type of comparison is useful in multi-locale applications, e.g. network protocols (e.g. CIFS), international database data, etc.
The operation is possible due to Unicode metadata which clearly identifies which characters may be "folded" to/from which upper/lower case characters.
As of 2007, when I last looked, there are less than 2000 upper/lower case character pairs.   It was also possible to generate a perfect hash function to convert upper to lower case (most likely vice versa, as well, but I didn't try it).
At the time, I used Bob Burtle's perfect hash generator.  It worked great in a CIFS implementation I was working on at the time.
There aren't many smallish, fixed sets of data out there you can point a perfect hash generator at.  But this is one of 'em.  :--)
Note: this is locale-neutral. So it will not support applications like German telephone books.  There are a great many applications you should definitely use locale aware folding and collation.  But there are a large number where locale neutral is actually preferable.  Especially now when folks are sharing data across so many time zones and, necessarily, cultures.  The Unicode standard does a good job of defining a good set of shared rules.
If you're not using Unicode, the presumption is that you have a really good reason. As a practical matter, if you have to deal with other character encodings, you have a highly locale aware application. In which case, the OP's question doesn't apply.
See also:

*

*The Unicode® Standard, Chapter 4, section 4.2, Case

*The Unicode® Standard, Chapter 5, section 5.18, Case Mappings, subsection Caseless Matching.

*UCD - CaseFolding.txt

A: Well, first I must say that any programmer dealing with natural language text has the utmost duty to know and understand Unicode well. Other ancient 20th Century encodings still exists, but things like EBCDIC and ASCII are not able to encode even a simple English text, which may contain words like façade, naïve or fiancée or even a geographical sign, a mathematical symbol or even emojis — conceptually, they are similar to ideograms. The majority of the world population does not use Latin characters to write text. UTF-8 is now the prevalent encoding on the Internet, and UTF-16 is used internally by all present day operating systems, including Windows, which unfortunately still does it wrong. (For example, NTFS has a decade-long reported bug that allows a directory to contain 2 files with names that look exactly the same but are encoded with different normal forms — I get this a lot when synchronising files via FTP between Windows and MacOS or Linux; all my files with accented characters get duplicated because unlike the other systems, Windows uses a different normal forms and only normalise the file names on the GUI level, not on the file system level. I reported this in 2001 for Windows 7 and the bug is still present today in Windows 10.)
If you still don't know what a normal form is, start here: https://en.wikipedia.org/wiki/Unicode_equivalence
Unicode has strict rules for lower- and uppercase conversion, and these should be followed to the point in order for things to work nicely. First, make sure both strings use the same normal form (you should do this in the input process, the Unicode standard has the algorithm). Please do not reinvent the wheel, use ICU normalising and comparison facilities. They have been extensively tested and they work correctly. Use them, IBM has made it gratis.
A note: if you plan on comparing string for ordering, please remember that collation is locale-dependant, and highly influenced by the language and the scenery. For example, in a dictionary these Portuguese words would have this exact order: sabia, sabiá, sábia, sábio. The same ordering rules would not work for an address list, which would use phonetic rules to place names like Peçanha and Pessanha adjacently. The same phenomenon happens in German with ß and ss. Yes, natural language is not logical — or better saying, its rules are not simple.
C'est la vie. これが私たちの世界です。


text: Q: Can pandas work with multiple result sets? Assuming the database and driver support nextset(), is there a way for me to use pandas to process multiple sets?  I've only been working with pandas for a few days, so I'm not sure what I expect it to look like.  My current workflow is df = pd.read_sql(sql_statement, db), slicing up df into sections as I process them consecutively.  If I could somehow use cursor.nextset() instead, I would be able to simplify the stored proc significantly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Discord bot will not respond, shuts down I am new to programming a Discord bot (and I love it), and it has problems responding. When I start it with node main.js, it works as normal until I do something like -ping, upon which it stops working.
Here is the error that I receive:
ReferenceError: clicent is not defined
    at Client.<anonymous> (C:\Users\Eric Müller\Desktop\Discord bot\Main.js:27:9)
    at Client.emit (events.js:315:20)
    at MessageCreateAction.handle (C:\Users\Eric Müller\Desktop\Discord bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\Eric Müller\Desktop\Discord bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\Eric Müller\Desktop\Discord bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (C:\Users\Eric Müller\Desktop\Discord bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (C:\Users\Eric Müller\Desktop\Discord bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
    at WebSocket.onMessage (C:\Users\Eric Müller\Desktop\Discord bot\node_modules\ws\lib\event-target.js:132:16)
    at WebSocket.emit (events.js:315:20)
    at Receiver.receiverOnMessage (C:\Users\Eric Müller\Desktop\Discord bot\node_modules\ws\lib\websocket.js:825:20)

Here is my code:
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '-';
const fs = require('fs');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));

for(const file of commandFiles){
const command = require(`./commands/${file}`);

    client.commands.set(command.name, command);

}

client.once('ready', () => {

    console.log('Codelyon is online!');

});

client.on('message', message =>{

if(!message.content.startsWith(prefix) || message.author.bot) return;

const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();

if(command === 'ping'){

        client.commands.get('ping').execute(message, args);

}
});

client.login('   '); (DISCLAMER! THE TOKEN IS FILLED IN AND CORRECT)

ping.js:
module.exports = {
name: 'ping',
description: "this is a ping command!",
execute(message, args){
message.channel.send('pong!');
    }
}

A: As the error suggests, you most likely have a typo somewhere in your code:
ReferenceError: clicent is not defined at Client. (C:\Users\Eric Müller\Desktop\Discord bot\Main.js:27:9)
The error tells you that at the beginning of line 27 in Main.js file, you have clicent, but it was probably supposed to be client.


text:
Q: Angular-strap modal shows empty I am trying to implement angular-strap modal, I have an external template of modal but it shows as blank. Whats wrong ?
<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <link data-require="bootstrap-css@3.3.1" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
    <script data-require="angular.js@1.3.13" data-semver="1.3.13" src="https://code.angularjs.org/1.3.13/angular.js"></script>
    <script data-require="angularstrap@*" data-semver="2.1.2" src="//cdnjs.cloudflare.com/ajax/libs/angular-strap/2.1.2/angular-strap.min.js"></script>
    <script data-require="angularstrap@*" data-semver="2.1.2" src="//cdnjs.cloudflare.com/ajax/libs/angular-strap/2.1.2/angular-strap.tpl.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <button class="btn btn-default" content-template="customer.tpl.html" bs-modal="modal">New Customer</button>
  </body>

</html>

Here's link to Plunker

A: Couple of things you need to fix:
The first is to replace content-template with data-template, and the second is that if you have ng-bind="title", you need to have a title variable on the scope, because ng-bind replaces the content of the HTML element it's on with what it's binded to:
<body>
    <button class="btn btn-default" data-template="customer.tpl.html" bs-modal="modal">New Customer</button>
  </body>

To see the text in the modal, either remove ng-bind="content" from the body, or assign content variable some value.
Working Plunker.
Source: http://mgcrea.github.io/angular-strap/##modals-examples


text:
Q: Glimpse not running on remote IIS server Used Nuget and installed Glimpse: Core 1.8.1.0, ADO 1.7, ASP.NET 1.6, EF5 1.6.0.0, and Mvc4 1.5.2 extensions.
Glimpse works great when I launch the web application locally using the VS IIS Express (remote DB). However, I don't get the Glimpse icon when "publishing" the MVC application to our remote IIS server.
Here's what I've tried and noticed:
•ignoring the LocalPolicy in my web.config:
<glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd" >
<logging level="Trace" />
<runtimePolicies>
  <ignoredTypes>
    <add type="Glimpse.AspNet.Policy.LocalPolicy, Glimpse.AspNet"/>
  </ignoredTypes>
</runtimePolicies>
</glimpse>

•  Running Glimpse.axd and press [Turn On Glimpse] shows an hour glass for several  seconds  and trace the DEBUG and INFO startup logs to file.
•  Turning on the Glimpse log does shows DEBUG's for a new default MVC route request and 1 info.
2014-01-22 15:26:15.2282 | INFO | Replaced IView of type 'System.Web.Mvc.RazorView', named 'Index', with proxy implementation. |
2014-01-22 15:26:17.6600 | DEBUG | RuntimePolicy set to 'Off' by IRuntimePolicy of type 'Glimpse.Core.Policy.ContentTypePolicy' during RuntimeEvent 'EndRequest'.

• Below appears at the end of the page source as expected.
<script type='text/javascript' src='/Glimpse.axd?n=glimpse_client&hash=e5937894'></script>
<script type='text/javascript' src='/Glimpse.axd?n=glimpse_metadata&hash=e5937894&callback=glimpse.data.initMetadata'></script>
<script type='text/javascript' src='/Glimpse.axd?n=glimpse_request&requestId=3d258479-bc96-4b0c-a469-d6b713fdb0fc&hash=e5937894&callback=glimpse.data.initData'></script>

(F12) console shows the following errors:
SCRIPT1028: Expected identifier, string or number Glimpse.axd?n=glimpse_client&hash=e5937894, line 3652 character 29
SCRIPT5009: 'glimpse' is undefined Glimpse.axd?n=glimpse_metadata&hash=e5937894&callback=glimpse.data.initMetadata, line 1 character 1
SCRIPT5009: 'glimpse' is undefined Glimpse.axd?n=glimpse_request&requestId=923b9a70-39ac-4639-b812-833e1d051c08&hash=e5937894&callback=glimpse.data.initData, line 1 character 1

A: Problem and Answer was glaring right at me from :
HTML1202: http://mysite/ is running in Compatibility View because 'Display intranet sites in Compatibility View' is checked.
mysite:1111

Disabled via: Override intranet compatibility mode IE8
<system.webServer>
    <httpProtocol>
      <customHeaders>
        <clear />
        <add name="X-UA-Compatible" value="IE=edge" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

Now all is working and after years of Asp.forms client side neglect I'm returning to client side debugging via (F12).  thanks to cgijbels


text:
Q: Create php array from strings that contains bracket literals I have a number of strings, that contain the bracket literals:
0 => string '[139432,97]' (length=18)
1 => string '[139440,99]' (length=18)

I need to create string arrays of [139432,97] and [139440,99].
I've tried using json_decode(), but while it works, it creates arrays as float or int using the above data, however I want them as strings.
array (size=2)
0 => float 139432
1 => int 97

array (size=2)
0 => float 139440
1 => int 97

A: You can put double quotes around the values e.g.
0 => string '["139432","97"]' (length=22)
1 => string '["139440","99"]' (length=22)

This way when you json_decode they should be strings.
Edit:
OK I thought you could control the input - if not then a simple trim and explode could do:
explode(',', trim('[139432,97]', '[]'));

array(2) {
  [0]=>
  string(6) "139432"
  [1]=>
  string(2) "97"
}

Is that enough?

A: Just combining what you already now (json_decode) and what @AlixAxel suggested here you can extract those values to string link:
$subject = '[139432,97]';
$convertedToArrayOfStrings = array_map('strval', json_decode($subject));

or
$convertedToArrayOfString = array_map(function($item){return (string) $item;}, json_decode($subject));

for better performance, see the comment bellow please :)

A: Why not try with loop and use explode function:
$array = array('139432,97', '139440,99');
$finalArray = array();

$i = 0;
foreach ($array as $arr) {
    $explode = explode(",", $arr);
    $j = 0;
    foreach ($explode as $exp) {
       $finalArray[$i][$j] = (int)$exp;
       $j++;
    }
    $i++;
}


text:
Q: Palindromo recursivo C Minhas funções não estão funcionando corretamente, sempre o programa me fala que não é palíndromo, para qualquer situação. Segue o código:
#include<stdio.h>
#include<string.h>

int inverte (char *n, int y, int aux) {

     if (y <= aux) return 1;

     else {
         if (n[y] != n[aux]) return 0;

         return inverte(n, y-1, aux+1);
     }
}

 int palindromo (char *n) {
     int aux1, x = 0;

     aux1 = inverte(n, strlen(n), x);

     if (aux1 == 1) printf("Eh palindromo");

     else printf("Nao eh palindromo");

 }

 int main() {

     char m[30] = {"anna"};

     palindromo(m);

     return 0;
 }

A: A resposta da Taisbevalle é linda, porém senti que não tocou onde o Marcelo de Sousa cometeu seu engano.
Strings
Basicamente, o problema não foi no entendimento de recursão, mas na manipulação da string. Em C, uma string é iniciada pelo índice zero e finalizada pelo caracter '\0'. Assim, a palavra de testes de palíndromo anna tem os seguintes caracteres, nas seguintes posições:
[0] -> 'a'
[1] -> 'n'
[2] -> 'n'
[3] -> 'a'
[4] -> '\0'

O quinto caracter é o terminador da string, necessário em C para indicar seu final.
A função strlen conta quantos caracteres há em determinada string.  anna tem claramente 4 caracteres. Então, o retorno de strlen("anna") é 4.
A função inverte, ele recebe 3 parâmetros:

*

*n, que é a string que perguntamos se é palíndromo ou não

*y, de cujo nome eu não consigo arrancar um significa, mas que no código é algo como a base para fazer a comparação do lado direito da string

*aux, o índice auxiliar que vai sendo percorrido, da esquerda para a direita, para determinar se a string é palíndromo

Na chamada inicial de inverte, são passados os seguintes valores:

*

*n ==> a string em questão

*y ==> o tamanho da string passada como n

*aux ==> 0, a posição inicial da string

A comparação dentro de inverte ocorre sobre o índice esquerdo (aux) e o índice direito (y) da seguinte maneira:
if (n[y] != n[aux]) return 0;

Voltando ao caso da anna; o tamanho da anna é 4, então o valor inicial de y é 4. No primeiro passo da recursão, os valores sendo comparados são os seguintes:
if (n[4] != n[0]) return 0;

Lembrando-se da decomposição inicial que eu fiz para a palavra anna, na posição 0 temos o caracter 'a', enquanto que na posição 4 temos o caracter '\0'! Então, substituindo pelos caracteres sendo comparados:
if ('\0' != 'a') return 0;

E '\0' é direferente de 'a', portanto ele sairá da função nesse ponto. Sempre.
Quase qualquer que seja a string passada para a função palindromo (que por sua vez chama a função inverte), ela comparará o primeiro caracter dessa string com '\0', o que sempre será distinto; a única string que essa função reconhece corretamente como palíndromo é a string vazia, pois assim a comparação do primeiro caracter (fim de string, '\0') e o fim de string dá igual e inverte detecta corretamente que "" é palíndromo. Então, nosso problema está ou na interpretação do índice y ou no valor inicial de y. Então, fiz duas sugestões de correção para isso.
Note que, nas sugestões, adicionei alguns casos a mais de teste.
Sugestão 1: passar a posição da última letra válida
Nessa sugestão, altero como a função palindromo chama inverte. Aqui, a última posição válida para a palavra anna é 3, pois ela tem comprimento 4 e C começa strings na posição 0:
    #include<stdio.h>
    #include<string.h>

    int inverte (char *n, int y, int aux) {
        if (y <= aux) return 1;
        else {
            if (n[y] != n[aux]) return 0;

            return inverte(n, y-1, aux+1);
        }
    }

     int palindromo (char *n) {
        int aux1, x = 0;

        aux1 = inverte(n, strlen(n) - 1, x);

        if (aux1 == 1) printf("Eh palindromo\n");
        else printf("Nao eh palindromo\n");

     }

     int main() {
        palindromo("banana");
        palindromo("anna");
        palindromo("ana");
        palindromo("bananab");
        palindromo("aa");
        palindromo("a");

        return 0;
     }

Vejo no Ideone
Sugestão 2: y é o índice que indica o caracter logo depois do último válido
Nessa sugestão, mudei a interpretação de y: agora, y sempre será o índice depois do último caracter válido. Então, a chamada de palindromo continua idêntica, porém mudei quem estava sendo comparada na comparação de inverte:
#include<stdio.h>
#include<string.h>

int inverte (char *n, int y, int aux) {
    if (y <= aux) return 1;
    else {
        if (n[y - 1] != n[aux]) return 0;

        return inverte(n, y-1, aux+1);
    }
}

 int palindromo (char *n) {
    int aux1, x = 0;

    aux1 = inverte(n, strlen(n), x);

    if (aux1 == 1) printf("Eh palindromo\n");
    else printf("Nao eh palindromo\n");

 }

 int main() {
    palindromo("banana");
    palindromo("anna");
    palindromo("ana");
    palindromo("bananab");
    palindromo("aa");
    palindromo("a");

    return 0;
 }

Vejo no Ideone

A: Seu código está confuso, tem muito if "solto", uma dica é utilizar as chaves {} para separar, na minha opinião fica melhor a visualização.
Como no comentário você disse que está um pouco perdido na recursão, vou te mostrar uma forma de fazer (não é a única). No código abaixo você digita a palavra que você quer e ele retorna se é ou não palíndromo.
#include <stdio.h>
#include <string.h>

// Função recursiva para verificar se a palavra é palíndromo
int palindromo(char palavra[], int tam, int posicao) {

    if (posicao < tam / 2){
        if (palavra[posicao] == palavra[tam - posicao - 1]){
            return 1 * palindromo(palavra, tam, posicao+1);
        }
        else{
            return 0;
        }
    }
    else{
        return 1;
    }
}

int main() {

   char palavra[255];
   int tam;

   printf ("Digite a palavra: \n");
   gets(palavra); // Ler a palavra digitada pelo usuário

   tam = strlen(palavra); // Tamanho da palavra

   if (palindromo(palavra, tam, 0))
      printf("É palíndromo\n");
   else
      printf("Não é palíndromo\n");

   return 0;
}

Veja funcionando no Ideone.
Usando a função int palindromo (char *n) você pode fazer conforme o código abaixo:
#include <stdio.h>
#include <string.h>

// Função recursiva para verificar se a palavra é palíndromo
int inverte(char *n, int tam, int posicao){

    if (posicao < tam / 2){
        if (n[posicao] == n[tam - posicao - 1]){
            return 1 * inverte(n, tam, posicao+1);
        }
        else{
            return 0;
        }
    }
    else{
        return 1;
    }
}

int palindromo(char *n) {

    int aux1, x = 0;

    aux1 = inverte(n, strlen(n), x);

    if (aux1 == 1) printf("Eh palindromo");
    else printf("Nao eh palindromo");

}

int main() {

    char m[30] = {"teste"};
    palindromo(m);

    return 0;
}

Só modifiquei a sua função inverte.
Veja no Ideone.

A: #include <stdio.h>
#include <stdlib.h>
#include <string.h>

int pali(char palavra[], int tam, int i)
{
    if(i > tam/2)

        return 1;

    if(palavra[i] == palavra[(tam-1)-i])

        return pali(palavra, tam, i+1);

    else return -1;
}

int main()
{
    char palavra[15];
    int tam = 0;

    scanf("%s", &palavra);

    tam = strlen(palavra);

    // retorna 1 caso seja palindromo e -1 caso n seja
    if(pali(palavra, tam, 0) > 0)

        printf("A palavra %s e palindromo", palavra);

    else

     printf("A palavra %s nao e palindromo", palavra);

    return 0;
}


text:
Q: seaborn boxplot sort appearance of boxes Here is my code:
order = sorted(subway_df.conds.unique())
g0 = sns.boxplot(subway_df.ENTRIESn_hourly, groupby = subway_df.conds,  data=subway_df, palette = "Set2", order = order )
g0.set(yscale = 'symlog')
g0.set_xlabel('conds', fontdict={'fontsize' : 14})
g0.set_ylabel('ENTRIESn_hourly', fontdict={'fontsize' : 14})
fig.suptitle('Hourly entries at various weather conditions', fontdict={'fontsize' : 16})

and the following graph:

I would like to find a way to sort the appearance of boxes by mean or variance as opposed to alphabetical order. Thanks!


text:
Q: No touch events available when QGraphicsView is visible I have an PyQt4 application which is deployed on a touch device. The central widget is a QTabWidget. All pushbuttons are touch enabled using the setAttribut() method. Now, the application shall get new functionality, which uses a QGraphicView component, which is placed on a new tab.
The As long as the graphic view is not visible, touch events are properly created and processed by the buttons. After the graphic view gets visible, no more touch events are available. Instead, every touch on the screen results in a MousePressEvent.
Which properties have to be set to not get touches as mouse press events only?


text:
Q: how to stop appending the table every time you have change something on a dropdown. I am running in to an tricky problem with my jquery ajax call.
I have following event which is triggering the ajax call to the respective url and will draw the chart.
after drawing the chart I wanted to display the respective data for that chart in a table so i have appended a table as following
$('#managers').on("change", function(){
var drawBubbleChart = bubbleChart.getData();
bubbleChart.drawchart(drawBubbleChart);
$.each(drawBubbleChart, function(index, value) {
    $('#bubbleChart3').append('
'+value[3]+'	'+value[0].toFixed(2)+'	'+value[1].toFixed(2)+'	'+value[2].toFixed(2)+'
');
  });

it works fine like this:

for the first time I change the drop down but every time I have changed the drop down it appends the data and chart on top of this which is not supposed to happen.
if anybody have the idea how do i stop this? would be much more appreciated

A: Could you replace the rows, rather than append them?
$('#managers').on("change", function() {
    var drawBubbleChart = bubbleChart.getData();
    bubbleChart.drawchart(drawBubbleChart);
    var rows = '';
    $.each(drawBubbleChart, function(index, value) {
        rows + ='
 '+value[3]+'	'+value[0].toFixed(2)+'	'+value[1].toFixed(2)+'	'+value[2].toFixed(2)+'
';
    $('#bubbleChart3').html(rows);
});

UPDATE:
To keep the header rows, you could place them inside a
 element and place an empty
 element after that. Then you can change the last line of code to:
$('#bubbleChart3').children('tbody').html(rows);


text:
Q: How to get some specific ID by several columns with the same title SQL ANDROID How to get some specific ID by several columns with the same title i Want to get the price of all computers together Here is a picture that will explain better
 This My Table
I want to get all the prices of computers of all computers
I'm sorry if I'm not clear, but I do not know how to explain it well

A: Check if this works for you, select id, price from table_name where item = 'Computer'
You can join the result with description from other table


text:
Q: How to initialize DateTimePicker for elements added to the DOM on the fly? I need to initialize a Bootstrap-DateTimePicker for inputs using jquery class-selector for elements that were created on the fly.
Typically, I would initialize the datetime picker for elements that were created when page is ready like so
$('.date-picker').datetimepicker({
     format: 'D/M/YYYY',
     useCurrent: false
});

But now I need to also apply the same thing on elements that were created on the dynamically. To get that to work, I did the following hack
$(document).on('focus', '.date-picker', function(){
    $(this).datetimepicker({
        format: 'D/M/YYYY',
        useCurrent: false
    });
});

The above code work only when you focus on the input which then it initialize the date time picker.
The issue with the above code, is that when an input has a "incorrectly formatted" default value, the format does not change. In another word, when the page is loaded the input does not have the DateTime bounded to it.
I tried to call the focus()  event on page load, but that does not seems to be working either. This is what I tried
$(document).on('focus', '.date-picker', function(){
    $(this).datetimepicker({
        format: 'D/M/YYYY',
        useCurrent: false
    });
}).focus();

How can I initialize the datetimepicker for predefined elements and elements that were dynamically created after page load?
I created the following fiddle to show how the datetime is not initialized on page load https://jsfiddle.net/516zsh7b/510/

A: Well, the best way would be to know how/when you add these new elements and add the logic there...
If you really need a reactive way to run a piece of JS code when an element is added to DOM, you could try mutation observers (not the best for performance):
http://ryanmorr.com/using-mutation-observers-to-watch-for-element-availability/


text:
Q: Do SSDs need to be defragmented? I'm not sure if solid state drives need defragmentation. Can anyone tell me if this requirement goes away with the new technology?

A: No, never. Defragmentation is helpful on spinning platter-based drives, if the filesystem doesn't handle it (which HFS+ generally does, on a Mac), because it takes time for the disk to spin around to the right spot, which has to happen more often if one chunk of data is split between several locations. See Access Time.
A solid state drive has no moving parts, so there's no mechanical delay. Reading a section of data takes approximately the same amount of time no matter where it's located in the flash.
Defragmenting a solid state drive is actually harmful because it forces the drive to move data around for no good reason, and flash chips have a limit on how many times they can rewrite a section.


text:
Q: How to handle FLINK window on stream data's timestamp base? I have some question.
Based on the timestamp in the class, I would like to make a logic that excludes data that has entered N or more times in 1 minute.
UserData class has a timestamp variable.
class UserData{
      public Timestamp timestamp;
      public String userId;
    }

At first I tried to use a tumbling window.
SingleOutputStreamOperator<UserData> validStream =
                stream.keyBy((KeySelector<UserData, String>) value -> value.userId)
                        .window(TumblingProcessingTimeWindows.of(Time.seconds(60)))
                        .process(new ValidProcessWindow());

public class ValidProcessWindow extends ProcessWindowFunction<UserData, UserData, String, TimeWindow> {

    private int validCount = 10;

    @Override
    public void process(String key, Context context, Iterable<UserData> elements, Collector<UserData> out) throws Exception {
        int count = -1;
        for (UserData element : elements) {
            count++; // start is 0

            if (count >= validCount) // valid click count
            {
                continue;
            }

            out.collect(element);
        }
    }
}

However, the time calculation of the tumbling window is based on a fixed time, so it is not suitable regardless of the timestamp of the UserData class.
How to handle window on stream UserData class's timestamp base?
Thanks.

Additinal Information

I use code like this.
stream.assignTimestampsAndWatermarks(WatermarkStrategy.<UserData>forBoundedOutOfOrderness(Duration.ofSeconds(1))
.withTimestampAssigner((event, timestamp) -> Timestamps.toMillis(event.timestamp))
.keyBy((KeySelector<UserData, String>) value -> value.userId)
.window(TumblingEventTimeWindows.of(Time.seconds(60)))
.process(new ValidProcessWindow());

I tried some test.
150 sample data. The timestamp of each data increased by 1 second.
result is |1,2,3....59|   |60,61....119| .
I wait last 30 data. but is not processed.
I expected |1,2,3....59|   |60,61....119|  |120...149|.
How can I get last other datas?

Self Answer

I found the cause.
Because I use only 150 sample data.
If use event time at Flink can not progress if there are no elements to be processed.
https://ci.apache.org/projects/flink/flink-docs-release-1.9/dev/event_time.html#idling-sources
So, I tested 150 sample data and dummy data. (dummy data timestamp of each data increased by 1 second).
I received correct data |1,2,3....59|   |60,61....119|  |120...149|.
Thank you for help.

A: So as far as I understand Your problem, You should just use different Time Characteristic. Processing time is using the system time to calculate windows, You should use event time for Your application. You can find more info about proper usage of event time here.
EDIT:
That's how flink works, there is no data to push watermark past 150, so window is not closed and thus no output. You can use custom trigger that will close the window even if watermark is not generated or inject some data to move the watermark.


text:
Q: React to change failures in a pure presentational component I have a pure component that display a type of entity. The component allows the user to interact and make changes to the entity, however these changes may be rejected by the server. In this case, I want the component to do an animation to display to the user that the change failed.
I can add another input to the component for a boolean, that the parent smart component would flip to 'on' when the animation is desired, but it seems like a leaky abstraction.

A: Consider using content projection, similar to how Angular Material deals with the mat-error
In your smart / container component, you'll have something like:
<my-presentation-component>

This is the error

</my-presentation-component>

In your presentation component:

  <ng-content select="[my-presentation-error]"></ng-content>

A guide on ng-content


text:
Q: Error 415 while trying to @POST image with MULTIPART_FORM_DATA (Retrofit) I have an android project in which I'm sending an image to my Intellij server just to save it in a folder. This is the following code in Android:
EscanerFragment.java
upload.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onClick(View v) {

                File file = imgToFile(img);
                RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                MultipartBody.Part myPic = MultipartBody.Part.createFormData("imagen", file.getName(), requestFile);

                Single.fromCallable(() -> daoParte.subirScan(myPic))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(subirScan -> {
                            subirScan.peek(subido -> {
                                Log.d(DEBUG_TAG, "subirScan:success");
                            }).peekLeft(error -> {
                                Log.d(DEBUG_TAG, "subirScan:failure");
                                Log.d(DEBUG_TAG, error.getMessage());
                                Toast.makeText(view.getContext(), "Error al subir el parte escaneado",
                                        Toast.LENGTH_LONG).show();
                            });
                        });
            }
        });

That code snippet runs when I click on a certain button. This next one is the code for the file writting of that ImageView:
private File imgToFile(ImageView img) {
        BitmapDrawable draw = (BitmapDrawable) img.getDrawable();
        Bitmap bitmap = draw.getBitmap();
        try {
            FileOutputStream outStream = null;
            File sdCard = Environment.getExternalStorageDirectory();
            File dir = new File(sdCard.getAbsolutePath() + "/Pictures");
            dir.mkdirs();
            String fileName = String.format("%d.jpg", System.currentTimeMillis());
            File outFile = new File(dir, fileName);
            outStream = new FileOutputStream(outFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            outStream.flush();
            outStream.close();
            return outFile;
        } catch (Exception e) {
            e.getStackTrace();
            return null;
        }
    }

And these next ones are the DAO and API calls:
DaoParte.java
public Either<ApiError, Boolean> subirScan(MultipartBody.Part img) {
        try {
            Call<Boolean> call = parteAPI.subirScan(img);
            Response<Boolean> response = call.execute();
            if (response.isSuccessful()) {
                if (response.body() != null) {
                    return Either.right(response.body());
                } else {
                    return Either.left(ApiError.builder().message("Error al enviar el documento escaneado").fecha(LocalDateTime.now()).build());
                }
            } else {
                return Either.left(ApiError.builder().message("Error de comunicacion").fecha(LocalDateTime.now()).build());
            }
        } catch (Exception e) {
            Log.e(DEBUG_TAG, e.getMessage(), e);
            return Either.left(ApiError.builder().message("Error de comunicacion").fecha(LocalDateTime.now()).build());
        }
    }

ParteAPI
@Multipart
    @POST("api/partes/subirScan")
    Call<Boolean> subirScan(@Part MultipartBody.Part img);

When I try to retrieve my image in the server I get error 415 or this error
[[FATAL] No injection source found for a parameter of type public java.lang.Boolean EE.rest.RestPartes.subirScan(org.glassfish.jersey.media.multipart.FormDataContentDisposition) at index 0.; source='ResourceMethod{httpMethod=POST, consumedTypes=[application/json], producedTypes=[application/json], suspended=false, suspendTimeout=0, suspendTimeoutUnit=MILLISECONDS, invocable=Invocable{handler=ClassBasedMethodHandler{handlerClass=class EE.rest.RestPartes, handlerConstructors=[org.glassfish.jersey.server.model.HandlerConstructor@27b9fb3c]}, definitionMethod=public java.lang.Boolean EE.rest.RestPartes.subirScan(org.glassfish.jersey.media.multipart.FormDataContentDisposition), parameters=[Parameter [type=class org.glassfish.jersey.media.multipart.FormDataContentDisposition, source=image, defaultValue=null]], responseType=class java.lang.Boolean}, nameBindings=[]}']. Please see server.log for more details."

RestPartes.java
package EE.rest;

import dao.modelo.Parte;
import okhttp3.MultipartBody;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import servicios.ServiciosPartes;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.List;

@Path("partes")
public class RestPartes {

    private ServiciosPartes sp = new ServiciosPartes();

    @POST
    @Path("/sancionar")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Parte sancionar(@Body String[] datos, @Context HttpServletRequest request) {
        return sp.sancionar(datos);
    }

    @GET
    @Path("/getAll")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public List<Parte> getPartes() {
        return sp.getPartes();
    }

    @POST
    @Path("/subirScan")
    @Headers("Content-Type:multipart/form-data")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public void subirScan(FormDataMultiPart multiPart) {
        System.out.println("a");
    }
}

What can I do? I've basically tried everything I've seen.
Disclaimer: this is my first question, let me know if you need more details about my problem.


text:
Q: Server Side Includes: variable in
A: Having a look at the mod_include documentation about flow control and the Apache Expressions Syntax shows two things which might interfere here and cause this issue:

*

*The examples in the mod_include documentation about flow control use the v("foo") syntax and not the %{foo} syntax to refer to variables (unless SSILegacyExprParser is set to on, but the legacy syntax seems to be $foo anyways).

*The Apache Expressions Syntax suggests that only a fixed list of server-set variables are usable with the %{…} syntax.

So I assume that there are two different types of variables and only one (the server-provided variables) can be used with the %{…} syntax. (And yes, these different ways to refer to a variable look confusing to me, too.)


text:
Q: Transformar em função Tenho este código que traz os dados do usuário no meu banco de dados:
$resultado = mysqli_query($conexao, "select * from usuarios where id= {$id}");
$dado = mysqli_fetch_assoc($resultado);

echo $dado['nome'];
echo $dado['sobrenome'];

Como faço para transformar este trecho em uma função?

A: Então, consegui aqui.. Fiz da seguinte maneira:
//Função
function dadosUsuario($id, $conexao) {
    $resultado = mysqli_query($conexao, "select * from usuarios where id= {$id}");

    return mysqli_fetch_assoc($resultado);
}

e para chamar a função usei:
$dado = dadosUsuario($id, $conexao);

echo $dado['cidade'];
echo $dado['estado'];

A: Somente transformando seu trecho de código em funçao:
function getUserById ($userId)
{
    $user = new User();
    $resultado = mysqli_query($conexao, "select * from usuarios where id= {$userId}");
    $dado = mysqli_fetch_assoc($resultado);

    echo $dado['nome'];
    echo $dado['sobrenome'];
}

Ou, se quiser a função com retorno, para reaproveitar o código:
function getUserById ($userId)
{
    $user = new User();
    $resultado = mysqli_query($conexao, "select * from usuarios where id= {$userId}");
    $dado = mysqli_fetch_assoc($resultado);

    return $dado;
}
//usar a informação retornada:
$user = getUserById("5001");
echo $user['id'];
echo $user['nome'];
echo $user['sobrenome'];

A: Para criar uma função basta colocar tudo dentro de uma function:
function bsucarUsuarioId($id) {
$resultado = mysqli_query($conexao, "select * from usuarios where id= {$id}");
$dado = mysqli_fetch_assoc($resultado);

return echo $dado['nome'] + $dado['sobrenome'];
}


text:
Q: Rails 5 redirect to external site but log off the user I'm using Devise and trying to redirect to another site upon form submit but I want the user be logged-out(end session) so that if a browser's back button is pressed, the same form cannot be reloaded or resubmitted. The user must instead be redirected to root_url.
In the controller, I've the devise function below but it's not logging out instantly maybe due to timeout parameter.
before_action :authenticate_user!

Now my doubts are:

*

*Is there a devise helper/callback function to activate
session#destroy. Any code snippet?

*Ideally the session must be destroyed after 'successful' redirection,
but then we have lost the controller action as soon as redirection from
app to another site occurs.. So which comes first(redirection or session#end) and how ?

*And if redirection is unsuccessful, then it must redirect back to app and not destroy session. Right now, I can only check uri by parsing but not checking if the site address is right or in other words, the site exists or loads up properly. How to accomplish this?
To load the new site, I've put a sleep(5) just after redirect_to.
apply_mode = 'http://www.google.com'

if @profile.uri?(apply_mode)
  redirect_to apply_mode, confirm: 'You are being redirected to an external site.'
  sleep(5)
else # Application mode is not url
  redirect_to root_path
end

profile.rb
def uri?(string)
    uri = URI.parse(string)
    %w( http https ).include?(uri.scheme)
   rescue URI::BadURIError
    false
  rescue URI::InvalidURIError
    false

end


text:
Q: How to output the results of a calculation I am trying to print out the result of invoking the calcula method as shown in the code below, but when I print the toString() the result I have is this IKCV @ 2a139a55. It seems like I must rewrite the toString() method in my IKCV class, but do not know how to implement it. How do I get the results of my method invocation to print out correctly?
My Test Class:
public class testaTemplateMethod {

  public static void main(String[] args) {
    Orcamento orcamento = new Orcamento(500);
    IKCV ikcv = new IKCV();
    ikcv.calcula(orcamento);
    System.out.println(ikcv);
  }
}

and the class where I think I should implement my method toString()
public class IKCV extends TemplateDeImpostoCondicional {

  @Override
  public String toString() {
    ?????????????????????
  }

  double calcula(Orcamento orcamento) {
    return 0.0; // Obviously not the real implementation
  }

}

A: Just construct any string representing your data inside the overridden toString function and return it. For example, just try return "[IKCV Object]";.

A: Oh! No, you don't need to override toString(). You just want to print out the results of the calculation, don't you?
Just do something like this:
public class testaTemplateMethod {

    public static void main(String[] args) {
        Orcamento orcamento = new Orcamento(500);
        IKCV ikcv = new IKCV();
        ikcv.calcula(orcamento);
        System.out.println("Calcula: " + ikcv.calcula(orcamento));
        // or ikcv.minimaTaxacao(orcamento) or whatever
    }
}

You don't print out the object itself, just print out the result of the method invocation that you care about.


text:
Q: Encoding RGB frames using x264 and AVCodec in C I have RGB24 frames streamed from camera and i want to encode them into h264 ,i found that AVCodec and x264 can do so, the problem is x264 as default accepts YUV420 as input so what i wrote was a program which convert RGB frames to YUV420 .that was by sws_scale function .this works well except that it does not satisfy the required FPS because the converting (RGB->YUV420) takes time.
This is how i setup my encoder context :
videoStream->id = 0;
vCodecCtx = videoStream->codec;

vCodecCtx->coder_type       = AVMEDIA_TYPE_VIDEO;
vCodecCtx->codec_id         = AV_CODEC_ID_H264;
vCodecCtx->bit_rate         = 400000;
vCodecCtx->width            = Width;
vCodecCtx->height           = Height;
vCodecCtx->time_base.den    = FPS;
vCodecCtx->time_base.num    = 1;
//vCodecCtx->time_base      = (AVRational){1,};
vCodecCtx->gop_size         = 12;
vCodecCtx->max_b_frames     = 1;
vCodecCtx->pix_fmt          = AV_PIX_FMT_YUV420P;

if(formatCtx->oformat->flags & AVFMT_GLOBALHEADER)
    vCodecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER;

av_opt_set(vCodecCtx->priv_data, "preset", "ultrafast", 0);
av_opt_set(vCodecCtx->priv_data, "profile", "baseline", AV_OPT_SEARCH_CHILDREN);

if (avcodec_open2(vCodecCtx, h264Codec, NULL) < 0){
    return 0;
}

when i changes AV_PIX_FMT_YUV420P to AV_PIX_FMT_RGB24 ,avcodec_open2 will fail.
i read that there is a version of libx264 for RGB called libx264rgb but i even dont know whether i have to rebuild x264 with enabling this option or to download another source or i have to do it programmatically with the first x264 lib.
the question is how to enable RGB as input to libx264 to use with libavcodec in C .or how to make the encoding or sws_scale more fast .
Edit:
How i built ffmpeg :
NDK=D:/AndroidDev/android-ndk-r9
PLATFORM=$NDK/platforms/android-18/arch-arm/
PREBUILT=$NDK/toolchains/arm-linux-androideabi-4.8/prebuilt/windows-x86_64

GENERAL="\
--enable-small \
--enable-cross-compile \
--extra-libs="-lgcc" \
--arch=arm \
--cc=$PREBUILT/bin/arm-linux-androideabi-gcc \
--cross-prefix=$PREBUILT/bin/arm-linux-androideabi- \
--nm=$PREBUILT/bin/arm-linux-androideabi-nm \
--extra-cflags="-I../x264/android/arm/include" \
--extra-ldflags="-L../x264/android/arm/lib" "

MODULES="\
--enable-gpl \
--enable-libx264"

function build_ARMv6
{
  ./configure \
  --target-os=linux \
  --prefix=./android/armeabi \
  ${GENERAL} \
  --sysroot=$PLATFORM \
  --enable-shared \
  --disable-static \
  --extra-cflags=" -O3 -fpic -fasm -Wno-psabi -fno-short-enums -fno-strict-aliasing -finline-limit=300 -mfloat-abi=softfp -mfpu=vfp -marm -march=armv6" \
  --extra-ldflags="-lx264 -Wl,-rpath-link=$PLATFORM/usr/lib -L$PLATFORM/usr/lib -nostdlib -lc -lm -ldl -llog" \
  --enable-zlib \
  ${MODULES} \
  --disable-doc \
  --enable-neon

  make clean
  make
  make install
}

build_ARMv6

echo Android ARMEABI builds finished

How i built x264 :
NDK=D:/AndroidDev/android-ndk-r9
PLATFORM=$NDK/platforms/android-18/arch-arm/
TOOLCHAIN=$NDK/toolchains/arm-linux-androideabi-4.8/prebuilt/windows-x86_64
PREFIX=./android/arm

function build_one
{
  ./configure \
  --prefix=$PREFIX \
  --enable-static \
  --enable-pic \
  --host=arm-linux \
  --cross-prefix=$TOOLCHAIN/bin/arm-linux-androideabi- \
  --sysroot=$PLATFORM

  make clean
  make
  make install
}

build_one

echo Android ARM builds finished

A: To use RGB pixel formats (AV_PIX_FMT_BGR0, AV_PIX_FMT_BGR24, AV_PIX_FMT_RGB24) with libx264 in libavcodec you need:

*

*use libavcodec from ffmpeg project and not from libav project because currently it is only available in there;

*make sure that libavcodec was compiled with libx264rgb (CONFIG_LIBX264RGB_ENCODER) which as I understand would be enabled if you would use new enough 8-bit libx264 (configured with --enable-libx264);

*use avcodec_find_encoder_by_name("libx264rgb") instead of avcodec_find_encoder(AV_CODEC_ID_H264).

A: Write your own RGB2YUV decoder.
Get pixel map from the frame and run it through your function. No scaling, no nothing, just one for loop.
There are easy formulae to convert RGB888  to YCbCr (YUV4:4:4).
But AV/FFMpeg should be able to do it for you easily.
For YUV420 you'll need to get whole 4:4:4 Y channel, and interpolate every 4 pixels into U and V , using either mean or gaussian, to get 4:2:0.
Like this:
This code expects ABC4:4:4 CB or Cr channel and returns its ABC4:2:0 version of it.
#define uint8 unsigned char
uint8 *ABC_444_to_420 (uint8 *src, uint8 *dst, int w, int h) {
    int dpos, x, y, pl1, pl2;
    dpos = 0;
    for (x=0; x<h; x+=2) {
        for (y=0; y<w; y+=2) {
            pl1 = x*w+y; pl2 = (x+1)*w+y;
            dst[dpos] = (src[pl1]+src[pl1+1]+src[pl2]+src[pl2+1])>>2;
            dpos += 1;
            }
        }
    return dst;
    }

So, you get YUV444 from RGB, then run U and V through code above separately.
If you cannot find appropriate function from AV/FFMpeg that will convert RGB to YCbCr take a look at:
https://msdn.microsoft.com/en-us/library/windows/desktop/dd206750%28v=vs.85%29.aspx
You may, of course, put whole process into one passthrough at RGB to YCbCr conversion, to get ABC4:2:0 out directly.
Do not work directly on AV/FFMpeg frame pixels, get your self raw data in an array. Then you'll get maximum speed, then construct AV/FFMpeg Frame back from the results.


text:
Q: Why can't I run includes on values of an object in typescript? Why do I get typescript errors on this?
const myObj = {
  a: "1",
  b: "2",
  c: "3"
} as const;

const hasFour = Object.values(myObj).includes("4");
// Argument of type '"4"' is not assignable to parameter of type '"1" | "2" | "3"'.ts(2345)

I would expect typescript to know that the result is an array of strings. Why do I need to cast the Object.values to string[] first? Why isn't this inferred?


text:
Q: Create method that opens a file, then lets's user write to file then end when pressing enter on empty line? I want to create a method that which opens a file for writing, then prompts the user to enter lines of text until they press enter on an empty line to stop input.
It's giving some trouble in that I can get the method run and I can input text but it wont close or save? I hit return after my text to go to a blank line and hit return again but it just moves onto another line.
I have written the following but can't get it working correctly.
My code:
 public void writeFile()
{
    String myString;
    clrscr();
    System.out.println("Begin typing: ");
    myString = Genio.getString();
    FileOutputStream outputStream = null;
    PrintWriter printWriter = null;
    // use a try-catch-finally block to catch file-related exceptions
    try
    {
        outputStream = new FileOutputStream("writing.txt");
        printWriter = new PrintWriter(outputStream);
        printWriter.write(myString);
        printWriter.newLine();
        // write information to the file via the PrintWriter
        while (myString  != "")
        {
            printWriter.print(myString + " ");
        }
    }
    catch (IOException e)
    {

        System.out.println("Sorry, there has been a problem opening or writing to the file");
    }
    finally
    {

        if (printWriter != null)
        {
            printWriter.close();
        }
    }
}

If it's needed, Genio is the class that deals with user input:
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Genio
{

public Genio()
{
}

private static String getStr()
{
    String inputLine = "";
    BufferedReader reader =
        new BufferedReader(new InputStreamReader(System.in));
    try
    {
        inputLine = reader.readLine();
    }

    catch(Exception exc)
    {
        System.out.println ("There was an error during reading: "
                            + exc.getMessage());
    }
    return inputLine;
}

public static int getInteger()
{
    int temp=0;
    boolean OK = false;

    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    do
    {
        try
        {
            temp = Integer.parseInt(keyboard.readLine());
            OK = true;
        }

        catch (Exception eRef)
        {
            if (eRef instanceof NumberFormatException)
            {
                System.out.print("Integer value needed: ");
            }
            else
            {
                System.out.println("Please report this error: "+eRef.toString());
            }
        }

    } while(OK == false);
    return(temp);
 }

public static float getFloat()
{
    float temp=0;
    boolean OK = false;

    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    do
    {
        try
        {
            temp = Float.parseFloat(keyboard.readLine());
            OK = true;
        }

        catch (Exception eRef)
        {
            if (eRef instanceof NumberFormatException)
            {
                System.out.print("Number needed: ");
            }
            else
            {
                System.out.println("Please report this error: "+eRef.toString());
            }
        }

    } while(OK == false);

    return(temp);
 }

public static double getDouble()
{
    double temp=0;
    boolean OK = false;
    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    do
    {
        try
        {
            temp = Double.parseDouble(keyboard.readLine());
            OK = true;
        }

        catch (Exception eRef)
        {
            if (eRef instanceof NumberFormatException)
            {
                System.out.print("Number needed: ");
            }
            else
            {
                System.out.println("Please report this error: "+eRef.toString());
            }
        }

    } while(OK == false);

    return(temp);
 }

 public static char getCharacter()
 {
     String tempStr="";
     char temp=' ';
     boolean OK = false;
     do
     {
         try
         {
             tempStr = getStr();
             temp = tempStr.charAt(0);
             OK = true;
         }

         catch (Exception eRef)
         {
             if (eRef instanceof StringIndexOutOfBoundsException)
             {
                 // means nothing was entered so prompt ...
                 System.out.print("Enter a character: ");
             }
             else
             {
                 System.out.println("Please report this error: "+eRef.toString());
             }
         }

     } while(OK == false);

     return(temp);
 }

 public static String getString()
 {
    String temp="";
    try
    {
        temp = getStr();
    }
    catch (Exception eRef)
    {
        System.out.println("Please report this error: "+eRef.toString());
    }
    return(temp);
 }
}

A: You only read myString once, before the while loop starts.

A: You don't compare strings with == or !=
Change
while (myString  != "") to  while (!myString.equals(""))

A: You class works fine for the most part. I fixed the problematic part for you:
// write information to the file via the PrintWriter
while (!myString.equals(""))
{
    myString = Genio.getString();
    printWriter.print(myString + "\n");
}

First the condition inside the while was incorrect. MyString has to be compared using the equals operator (or using the isEmpty method).
Second, you need to keep reading into myString inside the loop, otherwise you get an infinite loop and it will never exit.
Third, you want want to add newlines to the output file, so I added them.

A: You have an infinite loop, because you only read myString before you enter the while loop, so your condition will never be false.
Also, as Rishi Dua said, you can't compare strings with the usual == ou != operators, you have to use either .equals() or .isEmpty.

A: Comparing == and equals method.
Since java.lang.String class override equals method, It return true if two String object contains same content.
But,
== will only return true if two references are pointing to same object.
Modified code:
while (! myString.equals("")){
     // Write your code here
      myString = Genio.getString();
      printWriter.print(myString + "\n");
}


text:
Q: MongoDB Grails GORM unexpected behavior with hasMany / belongsTo Context: I'm using the mongodb plugin, although this may have nothing to do with that.
Let's say I have two domain classes, Foo and Bar, where Foo hasMany Bar and Bar belongsTo Foo:
class Foo {
    static hasMany = [bar:Bar]
}

class Bar {
    static belongsTo = [foo:Foo]
}

I would expect that what would be stored would be a collection (or table) for Foo, an collection for Bar, and a FooBar collection that handles the mappings. Instead I am getting a Foo collection and a Bar collection, where Bar has a "foo" key. It seems like what is happening would be the expected result of only adding the belongsTo but omitting the hasMany...
A) Are my expectations simply incorrect and what is happening is the expected result?
B) If not A, is there something special I need to do to make it match my expectations?
Thoughts?

A: As we know mongodb is non relational database, that is why what is happening is correct, it doesn't create third table or collection for handling has many but as you are using mongodb plugin , you can query it like has many/belongsTo as you generally use with mysql. In your case db structure for foo would be:
{ "_id" : NumberLong(1), "version" : 0  }

and for Bar would be:
{ "_id" : NumberLong(1), "foo" : NumberLong(1), "version" : 0 }

And it will provide you, as it is  cascade delete from parent to child like in case of using mysql
Hope It Helps:)


text:
Q: How to get month to date data in MSSQL? I have a query that I manually change the date to my liking. How can I dynamically pull the current month to date data?
SELECT  SUM(op.price * op.qty)
FROM    dbo.Orders o
        INNER JOIN dbo.OrdersProduct op ON op.orderID = o.orderID
WHERE   o.ID IN ( xx, xx, xx, xx )
AND o.orderDate BETWEEN '3/1/2016' AND '3/10/16'

A: This will get month to date:
SELECT  SUM(op.price * op.qty)
FROM    dbo.Orders o
        INNER JOIN dbo.OrdersProduct op ON op.orderID = o.orderID
WHERE   o.ID IN ( xx, xx, xx, xx )
        AND o.orderDate BETWEEN DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
                        AND
                        DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + 1, 0))


text:
Q: MySQL: SUM Joined Table on Limited Selection of Rows I have a problem similar to this question but a bit more complicated and I'm having trouble figuring out how to do it efficiently. Given two tables, one for a list of athletes and one with a list of races they've run in, e.g.,
ATHLETES

*

*id

*name

*gender

*details

RACES

*

*athlete_id

*year

*points

I want to rank all of the athletes by gender for a given period of years using only their top 4 race finishes (where "top" is defined by points). I feel like I should be able to do this in a subquery but I can't figure out how to reference the outer query from the inner. What I have now looks like this:
SELECT SUM(points) as points, a.* FROM
(SELECT rr.points, inner_a.id as athlete_id
FROM athletes_raceresult rr
INNER JOIN athletes_athlete inner_a ON rr.athlete_id = inner_a.id
WHERE inner_a.gender ='m' AND rr.year BETWEEN 2012 AND 2014
AND inner_a.id = a.id
ORDER BY rr.points DESC) as races
INNER JOIN athletes_athlete a ON races.athlete_id = a.id
GROUP BY races.athlete_id
ORDER BY points DESC

But that doesn't limit the points to 4 rows per athlete. It looks like I want a correlated subquery, but I can't get that to work.

A: The following SQL Fiddle example illustrates how this can be done:
SELECT SUM(rr.points), a.id
FROM athletes_raceresult AS rr
INNER JOIN athletes_athlete AS a ON rr.athlete_id = a.id
WHERE (
  SELECT count(crr.points)
  FROM athletes_raceresult AS crr
  INNER JOIN athletes_athlete AS ca ON crr.athlete_id = ca.id
  WHERE ca.gender = 'm'
  AND crr.year BETWEEN 2012 AND 2014
  AND crr.athlete_id = a.id AND crr.points >= rr.points
) <= 4
AND a.gender = 'm'
AND rr.year BETWEEN 2012 AND 2014
GROUP BY a.id


text:
Q: Flex List limit number of elements Is it possible to define a property to limit the number of elements which will appear in a mx:List ? I've read about setting the property rowCount, but I don't see any effect.
Can a filter be applied to accomplish this? My intention was to avoid removing the items from the list/array collection, but simply "hide" them. Can this be done?

A: You can "hide" items from display in a List-based class, without modifying your underlying source data, by using a Collection class, such as an ArrayCollection, and filtering the data.
Read these docs on Collection filtering.
To quote:

You use a filter function to limit the data view in the collection to
  a subset of the source data object. The function must take a single
  Object parameter, which corresponds to a collection item, and must
  return a Boolean value specifying whether to include the item in the
  view. As with sorting, when you specify or change the filter function,
  you must call the refresh() method on the collection to show the
  filtered results. To limit a collection view of an array of strings to
  contain only strings starting with M, for example, use the following
  filter function:

public function stateFilterFunc(item:Object):Boolean
{
    return item >= "M" && item < "N";
}

A: A different option is to use a new arraycollection and get your limited items from your big arraycollection :
//get first 10 elements
myArrayCollection = new ArrayCollection( myBigArrayCollection.toArray().slice(0,9) );

if you want to work with pagers, you could hold a counter where you keep track of what page the user is on, and get the next elements from you big array collection. example:
//this is just a (very) simple example
//page = integer (counter) for knowing which page the user is on
page = 0;
page_low = page*10;
page_high = page_low + 9;
myArrayCollection = new ArrayCollection( myBigArrayCollection.toArray().slice(page_low,page_high) );

(still using a filter is a more elegant solution)


text:
Q: Use of escape sequence in sed command I want to replace ; by TERMINATED BY '\034' STORED AS TEXTFILE;
I am using sed command but its replacing \0 by ;
sed "s|;|TERMINATED BY '\034' STORED AS TEXTFILE|"

I tried \\034 but its not working.

A: Use this sed:
sed "s|;|TERMINATED BY '\\\034' STORED AS TEXTFILE|"

A: If perl solution is okay, q operator is helpful in such cases
$ echo 'abc ; xyz' | perl -pe "s/;/q(TERMINATED BY '\034' STORED AS TEXTFILE)/e"
abc TERMINATED BY '\034' STORED AS TEXTFILE xyz


text:
Q: Returning an Enumerator as message to exception in Ruby - Junior Dev I'm using Ruby 1.9.3.  I have the following test that I'm trying to pass, which I cannot change:
def test_raising_unordered_enumerator_should_reference_enumerator
  decending_enumerator = 10.downto(1)
  enumerator = CombinedOrderedEnumerator.new(decending_enumerator)

  begin
    enumerator.take(2)
    assert false
  rescue CombinedOrderedEnumerator::UnorderedEnumerator => exception
    assert_equal decending_enumerator, exception.message
  end
end

And I've written the following code (the arguments *args are always going to be zero or more Enumerator objects):
class CombinedOrderedEnumerator < Enumerator
  class UnorderedEnumerator < RuntimeError; end

  def initialize(*args)
    super() do |yielder|
      values = []
      args.each do |arg|
        raise CombinedOrderedEnumerator::UnorderedEnumerator, arg unless arg.each_cons(2).all? { |a, b| (a <=> b) <= 0 }
        arg.each { |x| values.push x }
      end
      values.sort.each { |v| yielder.yield v }
    end
  end
end

When I run the test it fails with this message:
1) Failure:
test_raising_unordered_enumerator_should_reference_enumerator(CombinedOrderedEnumeratorTest) [combined_enumerator_test.rb:102]:
Expected: #<Enumerator: 10:downto(1)>
Actual: "#<Enumerator:0x007ffae1846d20>"

If I inspect the message string in the test (arg.inspect), this comes back when I run the test:
1) Failure:
test_raising_unordered_enumerator_should_reference_enumerator(CombinedOrderedEnumeratorTest) [combined_enumerator_test.rb:102]:
Expected: #<Enumerator: 10:downto(1)>
Actual: "#<Enumerator: 10:downto(1)>"

Finally, If I try to convert the message string to an enumerator using arg.to_enum I get the same thing as using just arg, as shown in code above.  So how can I transform the message string from the exception to pass the test? or am I doing something wrong?  Thanks a lot!
NOTE: Test must expect an object, not a string.  I cannot change the test.

A: You can override the behaviour of your exception class:
  class UnorderedEnumerator < RuntimeError
    def initialize(message)
      @message = message
    end

    def message
      @message
    end
  end


text:
Q: Intersection Observer with React JS I am trying to monitor page sections with IntersectionObserver using React.
Can someone assist me in making this possible, I have created a code sandbox with current code.
https://codesandbox.io/s/eager-agnesi-virvq

A: In your Home.jsx file. You were not calling observe on refs. And the useEffect had unwanted dependencies that made an infinite loop. I have fixed them and now you can see the active id in the log.
Call the unobserve on each ref in the cleanup function when the component gets mounted. (This is important to avoid memory leaks)
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        for (let entry of entries) {
          // if 90% of the section is visible
          if (entry.isIntersecting) {
            // update the active state to the visible section
            setActive(entry.target.id);
          }
        }
      },
      {
        // root property defaults to the browser viewport

        // intersection ratio (90% of section must be visibile)
        threshold: 0.9
      }
    );

    refs.forEach((ref) =>
      // observe the refs that were applied to the sections
      observer.observe(ref.current)
    );

    // cleanup function
    return () => {
      refs.forEach((ref) => ref.current && observer.unobserve(ref.current));
    };
  }, []);

Code sandbox => https://codesandbox.io/s/red-haze-21tm4?file=/src/App.js

A: It is better to understand the concept of IntersectionObserver,
Please check out the Below resource:
MDN: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
https://medium.com/the-non-traditional-developer/how-to-use-an-intersectionobserver-in-a-react-hook-9fb061ac6cb5
https://www.youtube.com/watch?v=2IbRtjez6ag


text:
Q: Problem In Cauchy-Peano proof : why $\int_{t_0}^t C|u(s)-v(s)|ds\leq L(t-t_0)\max_{[t_0,t]}|u(s)-v(s)|$? Here the page of one of my course (picard existence theorem). In my first remark in red, normaly the constant $L$ depend on the first variable. So why next to my second remark, the constant $L$ can go out the integral ? (since it normally depend on $t$ and thus can't go out the integral).
(If the document is written to small, you can zoom, the quality will be better :))

A: No, $L$ does not depend on $x$. In particular, the author says, "here all $x\in [\xi,\xi+a]$, $y,\bar y\in\mathbf R$ are allowed."


text:
Q: Digital Signature field is not setting in PDF template using iTextpdf 5.5.13 I want to set some fields in a from made by using adobe acrobat. I want that the finally generated PDF must contain the digital signature component as it is.
I want to achieve this using Java and itextpdf 5.5.13 jar.
Here is my code so far:
     //Getting PDF Reader
     PdfReader reader = null;
     //getting PDF Stamper
     PdfStamper stamper = null;
     //FacesContext context = FacesContext.getCurrentInstance();
     try {
            String src = "D:\\workspace2\\runtime-EclipseApplication\\Project\\WebContent\\resources\\" +
                    "pdf_form_template\\invoice.pdf";

            reader = new PdfReader(src);
            stamper = new PdfStamper(reader, new FileOutputStream(pdfPath));

            //Query and change fields in existing document by method calls.
            AcroFields form = stamper.getAcroFields();

            form.setField("contactNumber",phone_no);
            form.setField("name",name);
            form.setField("invoiceNumber",invoice_no);
            form.setField("GSTIN",gstin_no);
            form.setField("GSTIN_2",gstin_no);
            form.setField("Date","06/March/2019");
            form.setField("Ms",name);
            form.setField("Address 1",address);
            form.setField("Pin",pin_no);
            form.setField("State Code",state_code);
            form.setField("SNoRow1","1.");
            form.setField("Amount in Words",amount_in_words);
            form.setField("DESCRIPTIONRow1",desc);
            form.setField("HSN CODERow1",HSN_code);
            form.setField("AMOUNTTaxable Value", texable_value);
            form.setField("AMOUNTCGST 18", cgst_value);
            form.setField("AMOUNTSGST 9", sgst_value);
            form.setField("AMOUNTIGST 9", igst_value);
            form.setField("AMOUNTGRAND TOTAL", grand_total);

          //digital signature field in form template
            form.setField("digitalSignature","");

} catch (Exception e) {
    // TODO: handle exception
    e.printStackTrace();
}finally {
    if (stamper != null) {

        try {
            stamper.setFormFlattening(true);
            stamper.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    if (reader != null) {
        reader.close();
    }
}

The output pdf which I get contains all the fields that are set, except digital signature.

A: setFormFlattening(true) is the reason why I'm getting a flattened pdf at last.
Using partialFormFlattening is the correct way.


text:
Q: Short story about two teens stuck on a barren moon I read this in the 1970s:

*

*Two teens were stuck on a barren moon

*They inflate some kind of plastic bubble and line it with some kind of green rubber and use it to get off the Moon

*They may or may not have had to slow the Moon's rotation by using pieces of solid rocket fuel


text:
Q: React, Node, Mongodb : My image file is not being served from backend and trying to render it on the React side throws 404 not found I am uploading the image from React front end.
constructor(props) {
        super(props);
        this.state = {
            uploadRecipesFormData: {},
            selectedFile: null,
            redirect : null,
        };
    }

    uploadRecipe = () => {
        const formData = new FormData();
        formData.append('file', this.state.selectedFile, this.state.selectedFile.name);
        for(const key in this.state.uploadRecipesFormData){
            formData.append(key, this.state.uploadRecipesFormData[key]);
        }
        axios.post(`http://localhost:3000/recipes`, formData, {})
             .then(res =>  {
                 alert(res.data);
                 this.setState({
                     redirect: "/uploaded-recipes"
                 });
             })
             .catch(err => console.error(err));
    }

    onChangeImageHandler = e => {
        this.setState({
            selectedFile: e.target.files[0]
        });
    }

    handleChange = e => {
        e.preventDefault();
        this.handleInputChange(e.target.name, e.target.value);
    }

    handleInputChange = (key, value) => {

        this.setState({
            uploadRecipesFormData: {
                _id: uuidv4(),
                ...this.state.uploadRecipesFormData,
                addedBy: 'guest',
                [key]: value
            }
        });
    }

    submitRecipe = e => {
        e.preventDefault();
        this.uploadRecipe();
    }

On backend Im receiving the image along with other form data:
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'public/images')
    },
    filename: (req, file, cb) => {
        cb(null, `${file.originalname} `)
    }
});

const upload = multer({ storage: storage }).single('file');

/*
Endpoint: /recipes
Outcome: Add recipe
*/
router.post('/', (req, res) => {

    upload(req,res, err => {
        if(err instanceof multer.MulterError) {
            return res.status(500).json(err);
        }
        else if(err) {
            return res.status(500).json(err);
        }
        console.log(req.file.filename);
        console.log(req.body);

            const newRecipeData = new Recipe({
                _id: req.body._id,
                name: req.body.name,
                ingredients: req.body.ingredients.split(','),
                instructions: req.body.instructions,
                cuisine: req.body.cuisine || '',
                image: `http://localhost:3000/images/${req.file.filename}` || '',
                addedBy: req.body.addedBy || ''
        });

          newRecipeData.save()
                     .then(result => {
                         res.status(201).send('Recipe added successfully!');
                     })
                     .catch(err => console.log(err));
    });
});

The data is being stored in MongoDb with path to public directory to image. However, this file is being stored as a binary file instead of an image file.
I have enabled express static in my app.js:

    app.use(express.static('public'));

I am able to see the file in public/images folder but its a binary file due to which when I try to access it from my react front end it throws 404 error. I then manually tried adding an actual image to public/images folder and the it worked. How could I preserve the file type while receiving file data from front end ? Answers online are not clear to me of what I am trying to do.

A: Your code seems okay, however, I can spot a little bug in this block of code that might be causing the error:
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'public/images')
    },
    filename: (req, file, cb) => {
        cb(null, `${file.originalname} `)
    }
});

There is an extra space after ${file.originalname} in this
cb(null, `${file.originalname} `) statement. That extra space would change the file name, consequently, it appears as binary and you can't access it from the front end. Try removing that space and see if it works.


text:
Q: stuck in a problem statement which consist of comparing data for two tables PFB the problem statement .
I tried with dense_rank ,keep function but somehow i am not able to crack it. can anyone please help . This is small data set for problem representation . Original tables have several million rows.
scripts for data set:
CREATE TABLE TRANSACTION (
    ITEM VARCHAR2(25 BYTE),
    LOCATION NUMBER(10,0),
    TRAN_DATE DATE,
    POST_DATE DATE
)

Insert into TRANSACTION (ITEM,LOCATION,TRAN_DATE,POST_DATE) values ('13252099',473,to_date('09-JUL-18','DD-MON-RR'),to_date('09-JUL-18','DD-MON-RR'));
Insert into TRANSACTION (ITEM,LOCATION,TRAN_DATE,POST_DATE) values ('13252099',473,to_date('25-JUL-18','DD-MON-RR'),to_date('25-JUL-18','DD-MON-RR'));
Insert into TRANSACTION (ITEM,LOCATION,TRAN_DATE,POST_DATE) values ('13252098',470,to_date('09-JUL-18','DD-MON-RR'),to_date('09-JUL-18','DD-MON-RR'));
Insert into TRANSACTION (ITEM,LOCATION,TRAN_DATE,POST_DATE) values ('13252098',470,to_date('28-JUL-18','DD-MON-RR'),to_date('28-JUL-18','DD-MON-RR'));

CREATE TABLE RETAIL_DESC (
    ITEM VARCHAR2(25 BYTE),
    LOC NUMBER(10,0),
    UNIT_RETAIL NUMBER(20,4),
    ACTION_DATE DATE
)

Insert into RETAIL_DESC (ITEM,LOC,UNIT_RETAIL,ACTION_DATE) values ('13252099',473,379.97,to_date('09-JUL-18','DD-MON-RR'));
Insert into RETAIL_DESC (ITEM,LOC,UNIT_RETAIL,ACTION_DATE) values ('13252099',473,299.97,to_date('22-JUL-18','DD-MON-RR'));
Insert into RETAIL_DESC (ITEM,LOC,UNIT_RETAIL,ACTION_DATE) values ('13252099',473,0.01,to_date('19-AUG-18','DD-MON-RR'));
Insert into RETAIL_DESC (ITEM,LOC,UNIT_RETAIL,ACTION_DATE) values ('13252099',473,379.97,to_date('25-AUG-18','DD-MON-RR'));
Insert into RETAIL_DESC (ITEM,LOC,UNIT_RETAIL,ACTION_DATE) values ('13252098',470,500.18,to_date('08-JUL-18','DD-MON-RR'));
Insert into RETAIL_DESC (ITEM,LOC,UNIT_RETAIL,ACTION_DATE) values ('13252098',470,299.97,to_date('09-JUL-18','DD-MON-RR'));
Insert into RETAIL_DESC (ITEM,LOC,UNIT_RETAIL,ACTION_DATE) values ('13252098',470,0.01,to_date('19-JUL-18','DD-MON-RR'));
Insert into RETAIL_DESC (ITEM,LOC,UNIT_RETAIL,ACTION_DATE) values ('13252098',470,379.97,to_date('24-JUL-18','DD-MON-RR'));
Insert into RETAIL_DESC (ITEM,LOC,UNIT_RETAIL,ACTION_DATE) values ('13252098',470,300,to_date('24-JUL-18','DD-MON-RR'));

enter image description here
Note : I am using oracle 11g database .
1.Table Retail_desc contains unit_retail(price) for a item for a particular location. Action_date is the date at which unit_retail for that item gets updated to new price for that particular location .
an item/location combination can have multiple action_date based on days there price gets updated to new prices .

*Table transaction contains date (tran_date) on which item was sold from a particular location to a customer (post_date is same as tran_date- can ignore it).

i want to know the unit_retail (price) of the item which was sold to customer in a particular location .
additional comments:
1. for each item/location combination i want to fetch the unit retail which item/loc combination has during time of transaction (tran_date)
2. action_date is date at which unit_retail for item/location changes with new retail.
3. if unit retail changes multiple times on a single action_date , then fetch the retail which has lower price.

A: You need a subquery with join and row_number:
select item, loc, unit_retail, tran_date
from (
  select
      r.item, r.loc, r.unit_retail, t.tran_date
    , row_number() over (partition by r.item, r.loc, t.tran_date order by r.action_date desc, r.unit_retail) as rn
  from transaction t
  inner join retail_desc r on
    t.item = r.item
    and t.location = r.loc
  where t.tran_date >= r.action_date
) t
where rn = 1
order by item desc, loc desc, tran_date

Output for your sample data:
ITEM        LOC     UNIT_RETAIL  TRAN_DATE
13252099    473     379,97       09.07.2018 00:00:00
13252099    473     299,97       25.07.2018 00:00:00
13252098    470     299,97       09.07.2018 00:00:00
13252098    470     300          28.07.2018 00:00:00

A: I think first of a correlated subquery for this:
select t.*,
       (select min(rd.unit_retail) keep (dense_rank first order by rd.acction_date desc)
        from retail_desc rd
        where rd.loc = t.location and rd.item = t.item and
              rd.action_date <= t.post_date
       ) as unit_retail
from transaction t;

However, it might be better to use lead() and join:
select t.*, rd.unit_retail
from transaction t left join
     (select rd.*,
             lead(rd.action_date) over (partition by item, loc order by action_date) as next_action_date
      from retail_desc rd
     ) rd
     on t.location = rd.loc and t.item = rd.item and
        t.post_date >= rd.action_date and
        (t.post_date < rd.next_action_date or rd.next_action_date is null);

dense_rank() has no obvious connection to this problem.


text:
Q: Temporarily disable all other windows vb.net I'm making a color picker and I want it so on button press it will disable everything but the program (like what snipping tool does, but not add grey to the screen).
So when I click somewhere, it can capture the color from mouse pointer, and re-enable all other programs. The reason why I want it to disable all other programs is so when you click to pick the color then it won't interfere with anything and change the color.
Any help is very much appreciated.

A: 'Here you must have PictureBox1 in Your Form, and the form must be as parent container

Private Sub ButtonToPick_Click(sender As Object, e As EventArgs) Handles ButtonToPick.Click
    PictureBox1.Visible = False
    Me.Refresh()
    Dim g As Graphics
    Dim bmp As Bitmap
    bmp = New Bitmap(Me.Width, Me.Height)
    g = Graphics.FromImage(bmp)
    Dim myFRect As Rectangle
    myFRect = Me.RectangleToScreen(Me.DisplayRectangle)
    g.CopyFromScreen(myFRect.Left, myFRect.Top, 0, 0, bmp.Size)

    PictureBox1.Top = 0
    PictureBox1.Left = 0
    PictureBox1.Width = Me.Width
    PictureBox1.Height = Me.Height
    PictureBox1.Image = bmp
    PictureBox1.Visible = True
    PictureBox1.BringToFront()
    'Me.Refresh()
End Sub

Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
    'Here you process before picture box be hidden again
    PictureBox1.Visible = False
End Sub

A: In this sample, there are two form FrmDesktopDisplay and FrmCaller
Public Class FrmDesktopDisplay
    Public myResultStts As Boolean = False
    Public myResultValue As Integer = -1

    Private Sub FrmDesktopDisplay_Click(sender As Object, e As EventArgs) Handles Me.Click
        'Here your code, not just in click event, you must modify according to your need
        'And for example the result as follow:
        myResultStts = True
        myResultValue = 30
        Me.Hide()
    End Sub

    Private Sub FrmDesktopDisplay_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
        If e.KeyCode = Keys.Escape Then
            'Here Just Hide, don't be closed or disposed, because you need the result
            Me.Hide()
        End If
    End Sub

    Private Sub FrmDesktopDisplay_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'First you must hide this form, to take desktop image
        Me.Hide()

        'This to make borderless
        Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None

        Me.Refresh()
        Dim g As Graphics
        Dim bmp As Bitmap

        'This to take size of screen
        Dim myWidth As Integer = My.Computer.Screen.Bounds.Size.Width
        Dim myHeight As Integer = My.Computer.Screen.Bounds.Size.Height

        'This to make this form's Size is same as screen size
        Me.Width = myWidth
        Me.Height = myHeight

        'Create Blank Bitmap with size as same as screen size
        bmp = New Bitmap(myWidth, myHeight)

        'Create graphic with composition of bitmap
        g = Graphics.FromImage(bmp)

        'Take Image from screen, and move to graphic g
        g.CopyFromScreen(0, 0, 0, 0, bmp.Size)

        'Relocate this form to (0,0)
        Me.Top = 0
        Me.Left = 0

        'Set this form's backgroundimage with bitmap of bmp, that have been taken by graphic g
        Me.BackgroundImage = bmp
        Me.Show()

        Me.Refresh()
    End Sub
End Class

The Caller Form
Public Class FrmCaller
    Private Sub ButtonToPick_Click(sender As Object, e As EventArgs) Handles ButtonToPick.Click
        'Hide the caller form if don't need this form when you run your sniff or clip
        Me.Hide()
        FrmDesktopDisplay.ShowDialog()
        'To show again this form
        Me.Show()

        'Take the result from FrmDesktopDisplay, you can do it, because the form still active
        Dim myResultStts As Boolean = FrmDesktopDisplay.myResultStts
        Dim myResultValue As Integer = FrmDesktopDisplay.myResultValue

        'Here you close the FrmDesktopDisplay
        FrmDesktopDisplay.Close()
        FrmDesktopDisplay.Dispose()
        PictureBox1.Visible = False
    End Sub
End Class


text:
Q: How to configure elasticsearch cluster data node I want to configure a elasticsearch DB cluster where all nodes are data node, but I want each node to put data only on self node. I dont want to configure replica shards.
The purpose of this exercise is not to have a HA, but to see a cluster view of data in all nodes and when a node goes down it is ok for me if that node's data is not available in the cluster view.


text:
Q: Uncaught ReferenceError: require is not defined in Electron Js when using require() in html page I'm new to Electron Js and I am trying to make a custom titlebar as a project. I made the titlebar in a html page called nav.html and imported it in index.html (the main page)
nav.html :
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />

    <title>Document</title>

        <button
          style="font-size: 25px; cursor: default"
          class="minimize"
          id="minimize"
        >
          -
        </button>
        <button>
          <svg
            width="25px"
            height="25px"
            viewBox="0 0 512 512"
            xmlns="http://www.w3.org/2000/svg"
            style="cursor: default"
            class="restore"
            id="restore"
          >
            <path
              d="M352,153H40.247a24.028,24.028,0,0,0-24,24V458a24.028,24.028,0,0,0,24,24H352a24.028,24.028,0,0,0,24-24V177A24.028,24.028,0,0,0,352,153Zm-8,32v45.22H48.247V185ZM48.247,450V262.22H344V450Z"
              class="ci-primary"
            />
            <path
              d="M472,32H152a24.028,24.028,0,0,0-24,24v65h32V64H464V339.143H408v32h64a24.028,24.028,0,0,0,24-24V56A24.028,24.028,0,0,0,472,32Z"
              class="ci-primary"
            />
          </svg>

          <svg
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            class="maximize"
            id="maximize"
          >
            <path
              d="M896 85.333333H128a42.666667 42.666667 0 0 0-42.666667 42.666667v768a42.666667 42.666667 0 0 0 42.666667 42.666667h768a42.666667 42.666667 0 0 0 42.666667-42.666667V128a42.666667 42.666667 0 0 0-42.666667-42.666667z m-42.666667 768H170.666667V426.666667h682.666666z m0-512H170.666667V170.666667h682.666666z"
            />
          </svg>
        </button>
        <button
          style="font-size: 25px; cursor: default"
          class="close"
          id="close"
        >
          ×
        </button>

I have added inline styles as well as style tag and script tag in the same html document
Problem comes when I am not able to use require('electron') in a script tag. I am trying to make the top window buttons and using the ipcRenderer to process them to main.js.
Main.js :
const { app, BrowserWindow , ipcMain} = require('electron')
const path = require('path')
const ipc = ipcMain

function createWindow() {
  const win = new BrowserWindow({
    width: 1200,
    height: 700,
    center: true,
    minHeight: 700,
    minWidth: 1200,
    frame: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation : true,
      devTools: true,
      preload: path.join(__dirname, 'preload.js'),
    }
  })

  win.loadFile('index.html')

  //close window function
  ipc.on('closeApp', () => {
    console.log('app is closed')
    win.close()
  })
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

I have just added the index.html and preload.js for no confussion :
index.html :
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />

    <title>Home</title>

    <link rel="stylesheet" href="style.css" />

    Go to nav page

Preload.js :
window.addEventListener('DOMContentLoaded', () => {
    const replaceText = (selector, text) => {
      const element = document.getElementById(selector)
      if (element) element.innerText = text
    }

    for (const type of ['chrome', 'node', 'electron']) {
      replaceText(`${type}-version`, process.versions[type])
    }
  })

I tried using require JS but I had no idea how to do it. If anyone has an answer to it or can guide me through the error it would be highly appreciatable!
Thank you in advance!

A: You probably read some deprecated articles or forum posts, because calling electron from an HTML file is now an "old way" to use the ipcRenderer.
For security reasons, electron should not be directly accessible from your HTML page. You should only require ipcRenderer from your preload script, where you can put it in a method. Then, you can access your method by sharing it with the contextBridge.
I know this might be confusing at the beginning. You can find a well documented example here about What/How to use the ContextBridge
https://github.com/reZach/secure-electron-template/blob/master/docs/newtoelectron.md

A: @Dony is right, in today's Electron world, using require in the HTML page is a big no no. (disclaimer, I wrote the blog post that he's linking to).
I'm curious reading your question, are you looking to create a navigation or a menu? If it's a menu, then Electron has support to do this natively through the Menu class.
You ask a really great question, because setting this up in a secure way requires some communication between the renderer and main processes. My template uses this pattern within the menu to update the app's language, alongside this package.
I unfortunately don't have enough time to thoroughly go into detail at this moment, but will suggest you first take a peak at whether it may be a menu you are looking to add your functionality to. If it is, I hope some of my repository's files can direct you in the place where you can see how to set up the link between the js and the html file within an Electron application.
I'm also currently in the process of writing an "Ultimate Electron guide" that would cover these topics in a thorough blog post. I estimate it's many weeks out as I intend to go in great detail to explain Electron concepts such as this one. It'll be up on https://www.debugandrelease.com/ when I post it (subscribe if you'd like an email when it goes out).


text:
Q: ImportError: Cannot load specified object - psycopg2 OpenBSD, PostgreSQL9.2, python2.7
Trying to import psycopg2 module from python command line:
Python 2.7.3 (default, Aug  3 2012, 05:33:56)
[GCC 4.2.1 20070719 ] on openbsd5
Type "help", "copyright", "credits" or "license" for more information.
>>> import psycopg2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/psycopg2/__init__.py", line 67, in <module>
    from psycopg2._psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
ImportError: Cannot load specified object

psycopg2 is compiled and installed. I saw _psycopg.so in /site-packages/psycopg2 folder. Maybe he can not see this library ?

A: The psycopg2 python module includes an extension written in C. That extension cannot be loaded, because another C library that it is depending on is missing.
Check that you still have the PostgreSQL client libraries installed, and that psycopg2 can find it.
Note that if you run Django in a WSGI server, you need to have set the LD_LIBRARY_PATH environment variable before the WSGI server starts. Alternatively, recompile the psycopg2 extension with LD_RUN_PATH=/usr/local/pgsql/lib to 'hardcode' the path to the PostgreSQL client library at linking time, removing the need to set LD_LIBRARY_PATH.
A last resort would be to add the /usr/local/pgsql/lib path to /etc/ld.so.conf, see the ld.so(8) manpage.


text:
Q: Enable Apply Edits With Global Ids on ArcGIS Feature Services I have published a Feature Service on our ArcGIS Server 10.4.1 and in support section of the Feature Service URL I am seeing that the

ApplyEdits With Global Ids: false

can you please let me know why this is false? and how can I update it to True?

A: In my understanding, if you check the box to enable sync capabilities on the feature service during publishing, it should set it to true provided that you have the GlobalID field on your table. It also requires the database to technically be a geodatabase.


text:
Q: Can c#/c++ be used for IBM COS API Currently looking at IBM cloud storage as an option. Wondering if there is any easy way to talk to it via c#.  Would the Amazon s3 .net SDK work for it?  Or maybe the amazon s3 c++ sdk?
It's a shame that IBM only officially supports python, java and node sdk
Is there any gotchas if I were to try to leverage the amazon s3 sdk directly

A: According to the IBM documentation, COS

supports a subset of the S3 API for easy migration of applications to IBM Cloud.

so, depending on what functions exactly you need you might be able to use the Amazon S3 SDK. If the functions you need turn out to not be supported can probably use HTTPClient to wrap COS native API endpoints.


text:
Q: url to access data from foursquare API does not work I want to access data throughthe foursquare API using the foursquare ID of a given establishement. I have the following data:
client_ip = "AAA"
client_secret = "BBB"
id_place = "4c4192d5d7fad13a8cb807da"

Why the next URL does not access the data for this particular establishment?
https://api.foursquare.com/v2/venues/explore?client_id=AAA&client_secret=BBB/4c4192d5d7fad13a8cb807da
What I get is the following
  {
  "meta": {
    "code": 400,
    "errorType": "invalid_auth",
    "errorDetail": "Missing access credentials. See https://developer.foursquare.com/docs/oauth.html for details.",
    "requestId": "5900bcf84c1f6734f1ee6b02"
  },
  "response": {}
}

A: You should read through the Foursquare documentation on venue details. Your request is not formatted correctly.
The following request should get you the details for that venue:
https://api.foursquare.com/v2/venues/4c4192d5d7fad13a8cb807da?client_id=AAA&client_secret=BBB&v=20170101